xref: /rk3399_ARM-atf/services/std_svc/spm/el3_spmc/spmc_shared_mem.c (revision 77acde4c35480081c51ff17dd5e3a68f0f349429)
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 desc_size;
805 		size_t header_emad_size;
806 		uint32_t offset;
807 		struct ffa_comp_mrd *comp;
808 		struct ffa_emad_v1_0 *emad;
809 
810 		emad = spmc_shmem_obj_get_emad(&obj->desc, emad_num,
811 					       ffa_version, &emad_size);
812 
813 		/*
814 		 * Validate the calculated emad address resides within the
815 		 * descriptor.
816 		 */
817 		if ((uintptr_t) emad >=
818 		    (uintptr_t)((uint8_t *) &obj->desc + obj->desc_size)) {
819 			WARN("Invalid emad access.\n");
820 			return -EINVAL;
821 		}
822 
823 		offset = emad->comp_mrd_offset;
824 
825 		if (ffa_version == MAKE_FFA_VERSION(1, 0)) {
826 			desc_size =  sizeof(struct ffa_mtd_v1_0);
827 		} else {
828 			desc_size =  sizeof(struct ffa_mtd);
829 		}
830 
831 		header_emad_size = desc_size +
832 			(obj->desc.emad_count * emad_size);
833 
834 		if (offset < header_emad_size) {
835 			WARN("%s: invalid object, offset %u < header + emad %zu\n",
836 			     __func__, offset, header_emad_size);
837 			return -EINVAL;
838 		}
839 
840 		size = obj->desc_size;
841 
842 		if (offset > size) {
843 			WARN("%s: invalid object, offset %u > total size %zu\n",
844 			     __func__, offset, obj->desc_size);
845 			return -EINVAL;
846 		}
847 		size -= offset;
848 
849 		if (size < sizeof(struct ffa_comp_mrd)) {
850 			WARN("%s: invalid object, offset %u, total size %zu, no header space.\n",
851 			     __func__, offset, obj->desc_size);
852 			return -EINVAL;
853 		}
854 		size -= sizeof(struct ffa_comp_mrd);
855 
856 		count = size / sizeof(struct ffa_cons_mrd);
857 
858 		comp = spmc_shmem_obj_get_comp_mrd(obj, ffa_version);
859 
860 		if (comp == NULL) {
861 			WARN("%s: invalid comp_mrd offset\n", __func__);
862 			return -EINVAL;
863 		}
864 
865 		if (comp->address_range_count != count) {
866 			WARN("%s: invalid object, desc count %u != %zu\n",
867 			     __func__, comp->address_range_count, count);
868 			return -EINVAL;
869 		}
870 
871 		expected_size = offset + sizeof(*comp) +
872 				spmc_shmem_obj_ffa_constituent_size(obj,
873 								    ffa_version);
874 
875 		if (expected_size != obj->desc_size) {
876 			WARN("%s: invalid object, computed size %zu != size %zu\n",
877 			       __func__, expected_size, obj->desc_size);
878 			return -EINVAL;
879 		}
880 
881 		if (obj->desc_filled < obj->desc_size) {
882 			/*
883 			 * The whole descriptor has not yet been received.
884 			 * Skip final checks.
885 			 */
886 			return 0;
887 		}
888 
889 		/*
890 		 * The offset provided to the composite memory region descriptor
891 		 * should be consistent across endpoint descriptors. Store the
892 		 * first entry and compare against subsequent entries.
893 		 */
894 		if (comp_mrd_offset == 0) {
895 			comp_mrd_offset = offset;
896 		} else {
897 			if (comp_mrd_offset != offset) {
898 				ERROR("%s: mismatching offsets provided, %u != %u\n",
899 				       __func__, offset, comp_mrd_offset);
900 				return -EINVAL;
901 			}
902 		}
903 
904 		total_page_count = 0;
905 
906 		for (size_t i = 0; i < count; i++) {
907 			total_page_count +=
908 				comp->address_range_array[i].page_count;
909 		}
910 		if (comp->total_page_count != total_page_count) {
911 			WARN("%s: invalid object, desc total_page_count %u != %zu\n",
912 			     __func__, comp->total_page_count,
913 			total_page_count);
914 			return -EINVAL;
915 		}
916 	}
917 	return 0;
918 }
919 
920 /**
921  * spmc_shmem_check_state_obj - Check if the descriptor describes memory
922  *				regions that are currently involved with an
923  *				existing memory transactions. This implies that
924  *				the memory is not in a valid state for lending.
925  * @obj:    Object containing ffa_memory_region_descriptor.
926  *
927  * Return: 0 if object is valid, -EINVAL if invalid memory state.
928  */
929 static int spmc_shmem_check_state_obj(struct spmc_shmem_obj *obj,
930 				      uint32_t ffa_version)
931 {
932 	size_t obj_offset = 0;
933 	struct spmc_shmem_obj *inflight_obj;
934 
935 	struct ffa_comp_mrd *other_mrd;
936 	struct ffa_comp_mrd *requested_mrd = spmc_shmem_obj_get_comp_mrd(obj,
937 								  ffa_version);
938 
939 	if (requested_mrd == NULL) {
940 		return -EINVAL;
941 	}
942 
943 	inflight_obj = spmc_shmem_obj_get_next(&spmc_shmem_obj_state,
944 					       &obj_offset);
945 
946 	while (inflight_obj != NULL) {
947 		/*
948 		 * Don't compare the transaction to itself or to partially
949 		 * transmitted descriptors.
950 		 */
951 		if ((obj->desc.handle != inflight_obj->desc.handle) &&
952 		    (obj->desc_size == obj->desc_filled)) {
953 			other_mrd = spmc_shmem_obj_get_comp_mrd(inflight_obj,
954 							  FFA_VERSION_COMPILED);
955 			if (other_mrd == NULL) {
956 				return -EINVAL;
957 			}
958 			if (overlapping_memory_regions(requested_mrd,
959 						       other_mrd)) {
960 				return -EINVAL;
961 			}
962 		}
963 
964 		inflight_obj = spmc_shmem_obj_get_next(&spmc_shmem_obj_state,
965 						       &obj_offset);
966 	}
967 	return 0;
968 }
969 
970 static long spmc_ffa_fill_desc(struct mailbox *mbox,
971 			       struct spmc_shmem_obj *obj,
972 			       uint32_t fragment_length,
973 			       ffa_mtd_flag32_t mtd_flag,
974 			       uint32_t ffa_version,
975 			       void *smc_handle)
976 {
977 	int ret;
978 	size_t emad_size;
979 	uint32_t handle_low;
980 	uint32_t handle_high;
981 	struct ffa_emad_v1_0 *emad;
982 	struct ffa_emad_v1_0 *other_emad;
983 
984 	if (mbox->rxtx_page_count == 0U) {
985 		WARN("%s: buffer pair not registered.\n", __func__);
986 		ret = FFA_ERROR_INVALID_PARAMETER;
987 		goto err_arg;
988 	}
989 
990 	if (fragment_length > mbox->rxtx_page_count * PAGE_SIZE_4KB) {
991 		WARN("%s: bad fragment size %u > %u buffer size\n", __func__,
992 		     fragment_length, mbox->rxtx_page_count * PAGE_SIZE_4KB);
993 		ret = FFA_ERROR_INVALID_PARAMETER;
994 		goto err_arg;
995 	}
996 
997 	if (fragment_length > obj->desc_size - obj->desc_filled) {
998 		WARN("%s: bad fragment size %u > %zu remaining\n", __func__,
999 		     fragment_length, obj->desc_size - obj->desc_filled);
1000 		ret = FFA_ERROR_INVALID_PARAMETER;
1001 		goto err_arg;
1002 	}
1003 
1004 	memcpy((uint8_t *)&obj->desc + obj->desc_filled,
1005 	       (uint8_t *) mbox->tx_buffer, fragment_length);
1006 
1007 	/* Ensure that the sender ID resides in the normal world. */
1008 	if (ffa_is_secure_world_id(obj->desc.sender_id)) {
1009 		WARN("%s: Invalid sender ID 0x%x.\n",
1010 		     __func__, obj->desc.sender_id);
1011 		ret = FFA_ERROR_DENIED;
1012 		goto err_arg;
1013 	}
1014 
1015 	/* Ensure the NS bit is set to 0. */
1016 	if ((obj->desc.memory_region_attributes & FFA_MEM_ATTR_NS_BIT) != 0U) {
1017 		WARN("%s: NS mem attributes flags MBZ.\n", __func__);
1018 		ret = FFA_ERROR_INVALID_PARAMETER;
1019 		goto err_arg;
1020 	}
1021 
1022 	/*
1023 	 * We don't currently support any optional flags so ensure none are
1024 	 * requested.
1025 	 */
1026 	if (obj->desc.flags != 0U && mtd_flag != 0U &&
1027 	    (obj->desc.flags != mtd_flag)) {
1028 		WARN("%s: invalid memory transaction flags %u != %u\n",
1029 		     __func__, obj->desc.flags, mtd_flag);
1030 		ret = FFA_ERROR_INVALID_PARAMETER;
1031 		goto err_arg;
1032 	}
1033 
1034 	if (obj->desc_filled == 0U) {
1035 		/* First fragment, descriptor header has been copied */
1036 		ret = spmc_validate_mtd_start(&obj->desc, ffa_version,
1037 					      fragment_length, obj->desc_size);
1038 		if (ret != 0) {
1039 			goto err_bad_desc;
1040 		}
1041 
1042 		obj->desc.handle = spmc_shmem_obj_state.next_handle++;
1043 		obj->desc.flags |= mtd_flag;
1044 	}
1045 
1046 	obj->desc_filled += fragment_length;
1047 	ret = spmc_shmem_check_obj(obj, ffa_version);
1048 	if (ret != 0) {
1049 		ret = FFA_ERROR_INVALID_PARAMETER;
1050 		goto err_bad_desc;
1051 	}
1052 
1053 	handle_low = (uint32_t)obj->desc.handle;
1054 	handle_high = obj->desc.handle >> 32;
1055 
1056 	if (obj->desc_filled != obj->desc_size) {
1057 		SMC_RET8(smc_handle, FFA_MEM_FRAG_RX, handle_low,
1058 			 handle_high, obj->desc_filled,
1059 			 (uint32_t)obj->desc.sender_id << 16, 0, 0, 0);
1060 	}
1061 
1062 	/* The full descriptor has been received, perform any final checks. */
1063 
1064 	/*
1065 	 * If a partition ID resides in the secure world validate that the
1066 	 * partition ID is for a known partition. Ignore any partition ID
1067 	 * belonging to the normal world as it is assumed the Hypervisor will
1068 	 * have validated these.
1069 	 */
1070 	for (size_t i = 0; i < obj->desc.emad_count; i++) {
1071 		emad = spmc_shmem_obj_get_emad(&obj->desc, i, ffa_version,
1072 					       &emad_size);
1073 
1074 		ffa_endpoint_id16_t ep_id = emad->mapd.endpoint_id;
1075 
1076 		if (ffa_is_secure_world_id(ep_id)) {
1077 			if (spmc_get_sp_ctx(ep_id) == NULL) {
1078 				WARN("%s: Invalid receiver id 0x%x\n",
1079 				     __func__, ep_id);
1080 				ret = FFA_ERROR_INVALID_PARAMETER;
1081 				goto err_bad_desc;
1082 			}
1083 		}
1084 	}
1085 
1086 	/* Ensure partition IDs are not duplicated. */
1087 	for (size_t i = 0; i < obj->desc.emad_count; i++) {
1088 		emad = spmc_shmem_obj_get_emad(&obj->desc, i, ffa_version,
1089 					       &emad_size);
1090 
1091 		for (size_t j = i + 1; j < obj->desc.emad_count; j++) {
1092 			other_emad = spmc_shmem_obj_get_emad(&obj->desc, j,
1093 							     ffa_version,
1094 							     &emad_size);
1095 
1096 			if (emad->mapd.endpoint_id ==
1097 				other_emad->mapd.endpoint_id) {
1098 				WARN("%s: Duplicated endpoint id 0x%x\n",
1099 				     __func__, emad->mapd.endpoint_id);
1100 				ret = FFA_ERROR_INVALID_PARAMETER;
1101 				goto err_bad_desc;
1102 			}
1103 		}
1104 	}
1105 
1106 	ret = spmc_shmem_check_state_obj(obj, ffa_version);
1107 	if (ret) {
1108 		ERROR("%s: invalid memory region descriptor.\n", __func__);
1109 		ret = FFA_ERROR_INVALID_PARAMETER;
1110 		goto err_bad_desc;
1111 	}
1112 
1113 	/*
1114 	 * Everything checks out, if the sender was using FF-A v1.0, convert
1115 	 * the descriptor format to use the v1.1 structures.
1116 	 */
1117 	if (ffa_version == MAKE_FFA_VERSION(1, 0)) {
1118 		struct spmc_shmem_obj *v1_1_obj;
1119 		uint64_t mem_handle;
1120 
1121 		/* Calculate the size that the v1.1 descriptor will required. */
1122 		size_t v1_1_desc_size =
1123 		    spmc_shm_get_v1_1_descriptor_size((void *) &obj->desc,
1124 						      obj->desc_size);
1125 
1126 		if (v1_1_desc_size == 0U) {
1127 			ERROR("%s: cannot determine size of descriptor.\n",
1128 			      __func__);
1129 			goto err_arg;
1130 		}
1131 
1132 		/* Get a new obj to store the v1.1 descriptor. */
1133 		v1_1_obj =
1134 		    spmc_shmem_obj_alloc(&spmc_shmem_obj_state, v1_1_desc_size);
1135 
1136 		if (!v1_1_obj) {
1137 			ret = FFA_ERROR_NO_MEMORY;
1138 			goto err_arg;
1139 		}
1140 
1141 		/* Perform the conversion from v1.0 to v1.1. */
1142 		v1_1_obj->desc_size = v1_1_desc_size;
1143 		v1_1_obj->desc_filled = v1_1_desc_size;
1144 		if (!spmc_shm_convert_shmem_obj_from_v1_0(v1_1_obj, obj)) {
1145 			ERROR("%s: Could not convert mtd!\n", __func__);
1146 			spmc_shmem_obj_free(&spmc_shmem_obj_state, v1_1_obj);
1147 			goto err_arg;
1148 		}
1149 
1150 		/*
1151 		 * We're finished with the v1.0 descriptor so free it
1152 		 * and continue our checks with the new v1.1 descriptor.
1153 		 */
1154 		mem_handle = obj->desc.handle;
1155 		spmc_shmem_obj_free(&spmc_shmem_obj_state, obj);
1156 		obj = spmc_shmem_obj_lookup(&spmc_shmem_obj_state, mem_handle);
1157 		if (obj == NULL) {
1158 			ERROR("%s: Failed to find converted descriptor.\n",
1159 			     __func__);
1160 			ret = FFA_ERROR_INVALID_PARAMETER;
1161 			return spmc_ffa_error_return(smc_handle, ret);
1162 		}
1163 	}
1164 
1165 	/* Allow for platform specific operations to be performed. */
1166 	ret = plat_spmc_shmem_begin(&obj->desc);
1167 	if (ret != 0) {
1168 		goto err_arg;
1169 	}
1170 
1171 	SMC_RET8(smc_handle, FFA_SUCCESS_SMC32, 0, handle_low, handle_high, 0,
1172 		 0, 0, 0);
1173 
1174 err_bad_desc:
1175 err_arg:
1176 	spmc_shmem_obj_free(&spmc_shmem_obj_state, obj);
1177 	return spmc_ffa_error_return(smc_handle, ret);
1178 }
1179 
1180 /**
1181  * spmc_ffa_mem_send - FFA_MEM_SHARE/LEND implementation.
1182  * @client:             Client state.
1183  * @total_length:       Total length of shared memory descriptor.
1184  * @fragment_length:    Length of fragment of shared memory descriptor passed in
1185  *                      this call.
1186  * @address:            Not supported, must be 0.
1187  * @page_count:         Not supported, must be 0.
1188  * @smc_handle:         Handle passed to smc call. Used to return
1189  *                      FFA_MEM_FRAG_RX or SMC_FC_FFA_SUCCESS.
1190  *
1191  * Implements a subset of the FF-A FFA_MEM_SHARE and FFA_MEM_LEND calls needed
1192  * to share or lend memory from non-secure os to secure os (with no stream
1193  * endpoints).
1194  *
1195  * Return: 0 on success, error code on failure.
1196  */
1197 long spmc_ffa_mem_send(uint32_t smc_fid,
1198 			bool secure_origin,
1199 			uint64_t total_length,
1200 			uint32_t fragment_length,
1201 			uint64_t address,
1202 			uint32_t page_count,
1203 			void *cookie,
1204 			void *handle,
1205 			uint64_t flags)
1206 
1207 {
1208 	long ret;
1209 	struct spmc_shmem_obj *obj;
1210 	struct mailbox *mbox = spmc_get_mbox_desc(secure_origin);
1211 	ffa_mtd_flag32_t mtd_flag;
1212 	uint32_t ffa_version = get_partition_ffa_version(secure_origin);
1213 	size_t min_desc_size;
1214 
1215 	if (address != 0U || page_count != 0U) {
1216 		WARN("%s: custom memory region for message not supported.\n",
1217 		     __func__);
1218 		return spmc_ffa_error_return(handle,
1219 					     FFA_ERROR_INVALID_PARAMETER);
1220 	}
1221 
1222 	if (secure_origin) {
1223 		WARN("%s: unsupported share direction.\n", __func__);
1224 		return spmc_ffa_error_return(handle,
1225 					     FFA_ERROR_INVALID_PARAMETER);
1226 	}
1227 
1228 	if (ffa_version == MAKE_FFA_VERSION(1, 0)) {
1229 		min_desc_size = sizeof(struct ffa_mtd_v1_0);
1230 	} else if (ffa_version == MAKE_FFA_VERSION(1, 1)) {
1231 		min_desc_size = sizeof(struct ffa_mtd);
1232 	} else {
1233 		WARN("%s: bad FF-A version.\n", __func__);
1234 		return spmc_ffa_error_return(handle,
1235 					     FFA_ERROR_INVALID_PARAMETER);
1236 	}
1237 
1238 	/* Check if the descriptor is too small for the FF-A version. */
1239 	if (fragment_length < min_desc_size) {
1240 		WARN("%s: bad first fragment size %u < %zu\n",
1241 		     __func__, fragment_length, sizeof(struct ffa_mtd_v1_0));
1242 		return spmc_ffa_error_return(handle,
1243 					     FFA_ERROR_INVALID_PARAMETER);
1244 	}
1245 
1246 	if ((smc_fid & FUNCID_NUM_MASK) == FFA_FNUM_MEM_SHARE) {
1247 		mtd_flag = FFA_MTD_FLAG_TYPE_SHARE_MEMORY;
1248 	} else if ((smc_fid & FUNCID_NUM_MASK) == FFA_FNUM_MEM_LEND) {
1249 		mtd_flag = FFA_MTD_FLAG_TYPE_LEND_MEMORY;
1250 	} else {
1251 		WARN("%s: invalid memory management operation.\n", __func__);
1252 		return spmc_ffa_error_return(handle,
1253 					     FFA_ERROR_INVALID_PARAMETER);
1254 	}
1255 
1256 	spin_lock(&spmc_shmem_obj_state.lock);
1257 	obj = spmc_shmem_obj_alloc(&spmc_shmem_obj_state, total_length);
1258 	if (obj == NULL) {
1259 		ret = FFA_ERROR_NO_MEMORY;
1260 		goto err_unlock;
1261 	}
1262 
1263 	spin_lock(&mbox->lock);
1264 	ret = spmc_ffa_fill_desc(mbox, obj, fragment_length, mtd_flag,
1265 				 ffa_version, handle);
1266 	spin_unlock(&mbox->lock);
1267 
1268 	spin_unlock(&spmc_shmem_obj_state.lock);
1269 	return ret;
1270 
1271 err_unlock:
1272 	spin_unlock(&spmc_shmem_obj_state.lock);
1273 	return spmc_ffa_error_return(handle, ret);
1274 }
1275 
1276 /**
1277  * spmc_ffa_mem_frag_tx - FFA_MEM_FRAG_TX implementation.
1278  * @client:             Client state.
1279  * @handle_low:         Handle_low value returned from FFA_MEM_FRAG_RX.
1280  * @handle_high:        Handle_high value returned from FFA_MEM_FRAG_RX.
1281  * @fragment_length:    Length of fragments transmitted.
1282  * @sender_id:          Vmid of sender in bits [31:16]
1283  * @smc_handle:         Handle passed to smc call. Used to return
1284  *                      FFA_MEM_FRAG_RX or SMC_FC_FFA_SUCCESS.
1285  *
1286  * Return: @smc_handle on success, error code on failure.
1287  */
1288 long spmc_ffa_mem_frag_tx(uint32_t smc_fid,
1289 			  bool secure_origin,
1290 			  uint64_t handle_low,
1291 			  uint64_t handle_high,
1292 			  uint32_t fragment_length,
1293 			  uint32_t sender_id,
1294 			  void *cookie,
1295 			  void *handle,
1296 			  uint64_t flags)
1297 {
1298 	long ret;
1299 	uint32_t desc_sender_id;
1300 	uint32_t ffa_version = get_partition_ffa_version(secure_origin);
1301 	struct mailbox *mbox = spmc_get_mbox_desc(secure_origin);
1302 
1303 	struct spmc_shmem_obj *obj;
1304 	uint64_t mem_handle = handle_low | (((uint64_t)handle_high) << 32);
1305 
1306 	spin_lock(&spmc_shmem_obj_state.lock);
1307 
1308 	obj = spmc_shmem_obj_lookup(&spmc_shmem_obj_state, mem_handle);
1309 	if (obj == NULL) {
1310 		WARN("%s: invalid handle, 0x%lx, not a valid handle.\n",
1311 		     __func__, mem_handle);
1312 		ret = FFA_ERROR_INVALID_PARAMETER;
1313 		goto err_unlock;
1314 	}
1315 
1316 	desc_sender_id = (uint32_t)obj->desc.sender_id << 16;
1317 	if (sender_id != desc_sender_id) {
1318 		WARN("%s: invalid sender_id 0x%x != 0x%x\n", __func__,
1319 		     sender_id, desc_sender_id);
1320 		ret = FFA_ERROR_INVALID_PARAMETER;
1321 		goto err_unlock;
1322 	}
1323 
1324 	if (obj->desc_filled == obj->desc_size) {
1325 		WARN("%s: object desc already filled, %zu\n", __func__,
1326 		     obj->desc_filled);
1327 		ret = FFA_ERROR_INVALID_PARAMETER;
1328 		goto err_unlock;
1329 	}
1330 
1331 	spin_lock(&mbox->lock);
1332 	ret = spmc_ffa_fill_desc(mbox, obj, fragment_length, 0, ffa_version,
1333 				 handle);
1334 	spin_unlock(&mbox->lock);
1335 
1336 	spin_unlock(&spmc_shmem_obj_state.lock);
1337 	return ret;
1338 
1339 err_unlock:
1340 	spin_unlock(&spmc_shmem_obj_state.lock);
1341 	return spmc_ffa_error_return(handle, ret);
1342 }
1343 
1344 /**
1345  * spmc_ffa_mem_retrieve_set_ns_bit - Set the NS bit in the response descriptor
1346  *				      if the caller implements a version greater
1347  *				      than FF-A 1.0 or if they have requested
1348  *				      the functionality.
1349  *				      TODO: We are assuming that the caller is
1350  *				      an SP. To support retrieval from the
1351  *				      normal world this function will need to be
1352  *				      expanded accordingly.
1353  * @resp:       Descriptor populated in callers RX buffer.
1354  * @sp_ctx:     Context of the calling SP.
1355  */
1356 void spmc_ffa_mem_retrieve_set_ns_bit(struct ffa_mtd *resp,
1357 			 struct secure_partition_desc *sp_ctx)
1358 {
1359 	if (sp_ctx->ffa_version > MAKE_FFA_VERSION(1, 0) ||
1360 	    sp_ctx->ns_bit_requested) {
1361 		/*
1362 		 * Currently memory senders must reside in the normal
1363 		 * world, and we do not have the functionlaity to change
1364 		 * the state of memory dynamically. Therefore we can always set
1365 		 * the NS bit to 1.
1366 		 */
1367 		resp->memory_region_attributes |= FFA_MEM_ATTR_NS_BIT;
1368 	}
1369 }
1370 
1371 /**
1372  * spmc_ffa_mem_retrieve_req - FFA_MEM_RETRIEVE_REQ implementation.
1373  * @smc_fid:            FID of SMC
1374  * @total_length:       Total length of retrieve request descriptor if this is
1375  *                      the first call. Otherwise (unsupported) must be 0.
1376  * @fragment_length:    Length of fragment of retrieve request descriptor passed
1377  *                      in this call. Only @fragment_length == @length is
1378  *                      supported by this implementation.
1379  * @address:            Not supported, must be 0.
1380  * @page_count:         Not supported, must be 0.
1381  * @smc_handle:         Handle passed to smc call. Used to return
1382  *                      FFA_MEM_RETRIEVE_RESP.
1383  *
1384  * Implements a subset of the FF-A FFA_MEM_RETRIEVE_REQ call.
1385  * Used by secure os to retrieve memory already shared by non-secure os.
1386  * If the data does not fit in a single FFA_MEM_RETRIEVE_RESP message,
1387  * the client must call FFA_MEM_FRAG_RX until the full response has been
1388  * received.
1389  *
1390  * Return: @handle on success, error code on failure.
1391  */
1392 long
1393 spmc_ffa_mem_retrieve_req(uint32_t smc_fid,
1394 			  bool secure_origin,
1395 			  uint32_t total_length,
1396 			  uint32_t fragment_length,
1397 			  uint64_t address,
1398 			  uint32_t page_count,
1399 			  void *cookie,
1400 			  void *handle,
1401 			  uint64_t flags)
1402 {
1403 	int ret;
1404 	size_t buf_size;
1405 	size_t copy_size = 0;
1406 	size_t min_desc_size;
1407 	size_t out_desc_size = 0;
1408 
1409 	/*
1410 	 * Currently we are only accessing fields that are the same in both the
1411 	 * v1.0 and v1.1 mtd struct therefore we can use a v1.1 struct directly
1412 	 * here. We only need validate against the appropriate struct size.
1413 	 */
1414 	struct ffa_mtd *resp;
1415 	const struct ffa_mtd *req;
1416 	struct spmc_shmem_obj *obj = NULL;
1417 	struct mailbox *mbox = spmc_get_mbox_desc(secure_origin);
1418 	uint32_t ffa_version = get_partition_ffa_version(secure_origin);
1419 	struct secure_partition_desc *sp_ctx = spmc_get_current_sp_ctx();
1420 
1421 	if (!secure_origin) {
1422 		WARN("%s: unsupported retrieve req direction.\n", __func__);
1423 		return spmc_ffa_error_return(handle,
1424 					     FFA_ERROR_INVALID_PARAMETER);
1425 	}
1426 
1427 	if (address != 0U || page_count != 0U) {
1428 		WARN("%s: custom memory region not supported.\n", __func__);
1429 		return spmc_ffa_error_return(handle,
1430 					     FFA_ERROR_INVALID_PARAMETER);
1431 	}
1432 
1433 	spin_lock(&mbox->lock);
1434 
1435 	req = mbox->tx_buffer;
1436 	resp = mbox->rx_buffer;
1437 	buf_size = mbox->rxtx_page_count * FFA_PAGE_SIZE;
1438 
1439 	if (mbox->rxtx_page_count == 0U) {
1440 		WARN("%s: buffer pair not registered.\n", __func__);
1441 		ret = FFA_ERROR_INVALID_PARAMETER;
1442 		goto err_unlock_mailbox;
1443 	}
1444 
1445 	if (mbox->state != MAILBOX_STATE_EMPTY) {
1446 		WARN("%s: RX Buffer is full! %d\n", __func__, mbox->state);
1447 		ret = FFA_ERROR_DENIED;
1448 		goto err_unlock_mailbox;
1449 	}
1450 
1451 	if (fragment_length != total_length) {
1452 		WARN("%s: fragmented retrieve request not supported.\n",
1453 		     __func__);
1454 		ret = FFA_ERROR_INVALID_PARAMETER;
1455 		goto err_unlock_mailbox;
1456 	}
1457 
1458 	if (req->emad_count == 0U) {
1459 		WARN("%s: unsupported attribute desc count %u.\n",
1460 		     __func__, obj->desc.emad_count);
1461 		ret = FFA_ERROR_INVALID_PARAMETER;
1462 		goto err_unlock_mailbox;
1463 	}
1464 
1465 	/* Determine the appropriate minimum descriptor size. */
1466 	if (ffa_version == MAKE_FFA_VERSION(1, 0)) {
1467 		min_desc_size = sizeof(struct ffa_mtd_v1_0);
1468 	} else {
1469 		min_desc_size = sizeof(struct ffa_mtd);
1470 	}
1471 	if (total_length < min_desc_size) {
1472 		WARN("%s: invalid length %u < %zu\n", __func__, total_length,
1473 		     min_desc_size);
1474 		ret = FFA_ERROR_INVALID_PARAMETER;
1475 		goto err_unlock_mailbox;
1476 	}
1477 
1478 	spin_lock(&spmc_shmem_obj_state.lock);
1479 
1480 	obj = spmc_shmem_obj_lookup(&spmc_shmem_obj_state, req->handle);
1481 	if (obj == NULL) {
1482 		ret = FFA_ERROR_INVALID_PARAMETER;
1483 		goto err_unlock_all;
1484 	}
1485 
1486 	if (obj->desc_filled != obj->desc_size) {
1487 		WARN("%s: incomplete object desc filled %zu < size %zu\n",
1488 		     __func__, obj->desc_filled, obj->desc_size);
1489 		ret = FFA_ERROR_INVALID_PARAMETER;
1490 		goto err_unlock_all;
1491 	}
1492 
1493 	if (req->emad_count != 0U && req->sender_id != obj->desc.sender_id) {
1494 		WARN("%s: wrong sender id 0x%x != 0x%x\n",
1495 		     __func__, req->sender_id, obj->desc.sender_id);
1496 		ret = FFA_ERROR_INVALID_PARAMETER;
1497 		goto err_unlock_all;
1498 	}
1499 
1500 	if (req->emad_count != 0U && req->tag != obj->desc.tag) {
1501 		WARN("%s: wrong tag 0x%lx != 0x%lx\n",
1502 		     __func__, req->tag, obj->desc.tag);
1503 		ret = FFA_ERROR_INVALID_PARAMETER;
1504 		goto err_unlock_all;
1505 	}
1506 
1507 	if (req->emad_count != 0U && req->emad_count != obj->desc.emad_count) {
1508 		WARN("%s: mistmatch of endpoint counts %u != %u\n",
1509 		     __func__, req->emad_count, obj->desc.emad_count);
1510 		ret = FFA_ERROR_INVALID_PARAMETER;
1511 		goto err_unlock_all;
1512 	}
1513 
1514 	/* Ensure the NS bit is set to 0 in the request. */
1515 	if ((req->memory_region_attributes & FFA_MEM_ATTR_NS_BIT) != 0U) {
1516 		WARN("%s: NS mem attributes flags MBZ.\n", __func__);
1517 		ret = FFA_ERROR_INVALID_PARAMETER;
1518 		goto err_unlock_all;
1519 	}
1520 
1521 	if (req->flags != 0U) {
1522 		if ((req->flags & FFA_MTD_FLAG_TYPE_MASK) !=
1523 		    (obj->desc.flags & FFA_MTD_FLAG_TYPE_MASK)) {
1524 			/*
1525 			 * If the retrieve request specifies the memory
1526 			 * transaction ensure it matches what we expect.
1527 			 */
1528 			WARN("%s: wrong mem transaction flags %x != %x\n",
1529 			__func__, req->flags, obj->desc.flags);
1530 			ret = FFA_ERROR_INVALID_PARAMETER;
1531 			goto err_unlock_all;
1532 		}
1533 
1534 		if (req->flags != FFA_MTD_FLAG_TYPE_SHARE_MEMORY &&
1535 		    req->flags != FFA_MTD_FLAG_TYPE_LEND_MEMORY) {
1536 			/*
1537 			 * Current implementation does not support donate and
1538 			 * it supports no other flags.
1539 			 */
1540 			WARN("%s: invalid flags 0x%x\n", __func__, req->flags);
1541 			ret = FFA_ERROR_INVALID_PARAMETER;
1542 			goto err_unlock_all;
1543 		}
1544 	}
1545 
1546 	/* Validate the caller is a valid participant. */
1547 	if (!spmc_shmem_obj_validate_id(obj, sp_ctx->sp_id)) {
1548 		WARN("%s: Invalid endpoint ID (0x%x).\n",
1549 			__func__, sp_ctx->sp_id);
1550 		ret = FFA_ERROR_INVALID_PARAMETER;
1551 		goto err_unlock_all;
1552 	}
1553 
1554 	/* Validate that the provided emad offset and structure is valid.*/
1555 	for (size_t i = 0; i < req->emad_count; i++) {
1556 		size_t emad_size;
1557 		struct ffa_emad_v1_0 *emad;
1558 
1559 		emad = spmc_shmem_obj_get_emad(req, i, ffa_version,
1560 					       &emad_size);
1561 
1562 		if ((uintptr_t) emad >= (uintptr_t)
1563 					((uint8_t *) req + total_length)) {
1564 			WARN("Invalid emad access.\n");
1565 			ret = FFA_ERROR_INVALID_PARAMETER;
1566 			goto err_unlock_all;
1567 		}
1568 	}
1569 
1570 	/*
1571 	 * Validate all the endpoints match in the case of multiple
1572 	 * borrowers. We don't mandate that the order of the borrowers
1573 	 * must match in the descriptors therefore check to see if the
1574 	 * endpoints match in any order.
1575 	 */
1576 	for (size_t i = 0; i < req->emad_count; i++) {
1577 		bool found = false;
1578 		size_t emad_size;
1579 		struct ffa_emad_v1_0 *emad;
1580 		struct ffa_emad_v1_0 *other_emad;
1581 
1582 		emad = spmc_shmem_obj_get_emad(req, i, ffa_version,
1583 					       &emad_size);
1584 
1585 		for (size_t j = 0; j < obj->desc.emad_count; j++) {
1586 			other_emad = spmc_shmem_obj_get_emad(
1587 					&obj->desc, j, MAKE_FFA_VERSION(1, 1),
1588 					&emad_size);
1589 
1590 			if (req->emad_count &&
1591 			    emad->mapd.endpoint_id ==
1592 			    other_emad->mapd.endpoint_id) {
1593 				found = true;
1594 				break;
1595 			}
1596 		}
1597 
1598 		if (!found) {
1599 			WARN("%s: invalid receiver id (0x%x).\n",
1600 			     __func__, emad->mapd.endpoint_id);
1601 			ret = FFA_ERROR_INVALID_PARAMETER;
1602 			goto err_unlock_all;
1603 		}
1604 	}
1605 
1606 	mbox->state = MAILBOX_STATE_FULL;
1607 
1608 	if (req->emad_count != 0U) {
1609 		obj->in_use++;
1610 	}
1611 
1612 	/*
1613 	 * If the caller is v1.0 convert the descriptor, otherwise copy
1614 	 * directly.
1615 	 */
1616 	if (ffa_version == MAKE_FFA_VERSION(1, 0)) {
1617 		ret = spmc_populate_ffa_v1_0_descriptor(resp, obj, buf_size, 0,
1618 							&copy_size,
1619 							&out_desc_size);
1620 		if (ret != 0U) {
1621 			ERROR("%s: Failed to process descriptor.\n", __func__);
1622 			goto err_unlock_all;
1623 		}
1624 	} else {
1625 		copy_size = MIN(obj->desc_size, buf_size);
1626 		out_desc_size = obj->desc_size;
1627 
1628 		memcpy(resp, &obj->desc, copy_size);
1629 	}
1630 
1631 	/* Set the NS bit in the response if applicable. */
1632 	spmc_ffa_mem_retrieve_set_ns_bit(resp, sp_ctx);
1633 
1634 	spin_unlock(&spmc_shmem_obj_state.lock);
1635 	spin_unlock(&mbox->lock);
1636 
1637 	SMC_RET8(handle, FFA_MEM_RETRIEVE_RESP, out_desc_size,
1638 		 copy_size, 0, 0, 0, 0, 0);
1639 
1640 err_unlock_all:
1641 	spin_unlock(&spmc_shmem_obj_state.lock);
1642 err_unlock_mailbox:
1643 	spin_unlock(&mbox->lock);
1644 	return spmc_ffa_error_return(handle, ret);
1645 }
1646 
1647 /**
1648  * spmc_ffa_mem_frag_rx - FFA_MEM_FRAG_RX implementation.
1649  * @client:             Client state.
1650  * @handle_low:         Handle passed to &FFA_MEM_RETRIEVE_REQ. Bit[31:0].
1651  * @handle_high:        Handle passed to &FFA_MEM_RETRIEVE_REQ. Bit[63:32].
1652  * @fragment_offset:    Byte offset in descriptor to resume at.
1653  * @sender_id:          Bit[31:16]: Endpoint id of sender if client is a
1654  *                      hypervisor. 0 otherwise.
1655  * @smc_handle:         Handle passed to smc call. Used to return
1656  *                      FFA_MEM_FRAG_TX.
1657  *
1658  * Return: @smc_handle on success, error code on failure.
1659  */
1660 long spmc_ffa_mem_frag_rx(uint32_t smc_fid,
1661 			  bool secure_origin,
1662 			  uint32_t handle_low,
1663 			  uint32_t handle_high,
1664 			  uint32_t fragment_offset,
1665 			  uint32_t sender_id,
1666 			  void *cookie,
1667 			  void *handle,
1668 			  uint64_t flags)
1669 {
1670 	int ret;
1671 	void *src;
1672 	size_t buf_size;
1673 	size_t copy_size;
1674 	size_t full_copy_size;
1675 	uint32_t desc_sender_id;
1676 	struct mailbox *mbox = spmc_get_mbox_desc(secure_origin);
1677 	uint64_t mem_handle = handle_low | (((uint64_t)handle_high) << 32);
1678 	struct spmc_shmem_obj *obj;
1679 	uint32_t ffa_version = get_partition_ffa_version(secure_origin);
1680 
1681 	if (!secure_origin) {
1682 		WARN("%s: can only be called from swld.\n",
1683 		     __func__);
1684 		return spmc_ffa_error_return(handle,
1685 					     FFA_ERROR_INVALID_PARAMETER);
1686 	}
1687 
1688 	spin_lock(&spmc_shmem_obj_state.lock);
1689 
1690 	obj = spmc_shmem_obj_lookup(&spmc_shmem_obj_state, mem_handle);
1691 	if (obj == NULL) {
1692 		WARN("%s: invalid handle, 0x%lx, not a valid handle.\n",
1693 		     __func__, mem_handle);
1694 		ret = FFA_ERROR_INVALID_PARAMETER;
1695 		goto err_unlock_shmem;
1696 	}
1697 
1698 	desc_sender_id = (uint32_t)obj->desc.sender_id << 16;
1699 	if (sender_id != 0U && sender_id != desc_sender_id) {
1700 		WARN("%s: invalid sender_id 0x%x != 0x%x\n", __func__,
1701 		     sender_id, desc_sender_id);
1702 		ret = FFA_ERROR_INVALID_PARAMETER;
1703 		goto err_unlock_shmem;
1704 	}
1705 
1706 	if (fragment_offset >= obj->desc_size) {
1707 		WARN("%s: invalid fragment_offset 0x%x >= 0x%zx\n",
1708 		     __func__, fragment_offset, obj->desc_size);
1709 		ret = FFA_ERROR_INVALID_PARAMETER;
1710 		goto err_unlock_shmem;
1711 	}
1712 
1713 	spin_lock(&mbox->lock);
1714 
1715 	if (mbox->rxtx_page_count == 0U) {
1716 		WARN("%s: buffer pair not registered.\n", __func__);
1717 		ret = FFA_ERROR_INVALID_PARAMETER;
1718 		goto err_unlock_all;
1719 	}
1720 
1721 	if (mbox->state != MAILBOX_STATE_EMPTY) {
1722 		WARN("%s: RX Buffer is full!\n", __func__);
1723 		ret = FFA_ERROR_DENIED;
1724 		goto err_unlock_all;
1725 	}
1726 
1727 	buf_size = mbox->rxtx_page_count * FFA_PAGE_SIZE;
1728 
1729 	mbox->state = MAILBOX_STATE_FULL;
1730 
1731 	/*
1732 	 * If the caller is v1.0 convert the descriptor, otherwise copy
1733 	 * directly.
1734 	 */
1735 	if (ffa_version == MAKE_FFA_VERSION(1, 0)) {
1736 		size_t out_desc_size;
1737 
1738 		ret = spmc_populate_ffa_v1_0_descriptor(mbox->rx_buffer, obj,
1739 							buf_size,
1740 							fragment_offset,
1741 							&copy_size,
1742 							&out_desc_size);
1743 		if (ret != 0U) {
1744 			ERROR("%s: Failed to process descriptor.\n", __func__);
1745 			goto err_unlock_all;
1746 		}
1747 	} else {
1748 		full_copy_size = obj->desc_size - fragment_offset;
1749 		copy_size = MIN(full_copy_size, buf_size);
1750 
1751 		src = &obj->desc;
1752 
1753 		memcpy(mbox->rx_buffer, src + fragment_offset, copy_size);
1754 	}
1755 
1756 	spin_unlock(&mbox->lock);
1757 	spin_unlock(&spmc_shmem_obj_state.lock);
1758 
1759 	SMC_RET8(handle, FFA_MEM_FRAG_TX, handle_low, handle_high,
1760 		 copy_size, sender_id, 0, 0, 0);
1761 
1762 err_unlock_all:
1763 	spin_unlock(&mbox->lock);
1764 err_unlock_shmem:
1765 	spin_unlock(&spmc_shmem_obj_state.lock);
1766 	return spmc_ffa_error_return(handle, ret);
1767 }
1768 
1769 /**
1770  * spmc_ffa_mem_relinquish - FFA_MEM_RELINQUISH implementation.
1771  * @client:             Client state.
1772  *
1773  * Implements a subset of the FF-A FFA_MEM_RELINQUISH call.
1774  * Used by secure os release previously shared memory to non-secure os.
1775  *
1776  * The handle to release must be in the client's (secure os's) transmit buffer.
1777  *
1778  * Return: 0 on success, error code on failure.
1779  */
1780 int spmc_ffa_mem_relinquish(uint32_t smc_fid,
1781 			    bool secure_origin,
1782 			    uint32_t handle_low,
1783 			    uint32_t handle_high,
1784 			    uint32_t fragment_offset,
1785 			    uint32_t sender_id,
1786 			    void *cookie,
1787 			    void *handle,
1788 			    uint64_t flags)
1789 {
1790 	int ret;
1791 	struct mailbox *mbox = spmc_get_mbox_desc(secure_origin);
1792 	struct spmc_shmem_obj *obj;
1793 	const struct ffa_mem_relinquish_descriptor *req;
1794 	struct secure_partition_desc *sp_ctx = spmc_get_current_sp_ctx();
1795 
1796 	if (!secure_origin) {
1797 		WARN("%s: unsupported relinquish direction.\n", __func__);
1798 		return spmc_ffa_error_return(handle,
1799 					     FFA_ERROR_INVALID_PARAMETER);
1800 	}
1801 
1802 	spin_lock(&mbox->lock);
1803 
1804 	if (mbox->rxtx_page_count == 0U) {
1805 		WARN("%s: buffer pair not registered.\n", __func__);
1806 		ret = FFA_ERROR_INVALID_PARAMETER;
1807 		goto err_unlock_mailbox;
1808 	}
1809 
1810 	req = mbox->tx_buffer;
1811 
1812 	if (req->flags != 0U) {
1813 		WARN("%s: unsupported flags 0x%x\n", __func__, req->flags);
1814 		ret = FFA_ERROR_INVALID_PARAMETER;
1815 		goto err_unlock_mailbox;
1816 	}
1817 
1818 	if (req->endpoint_count == 0) {
1819 		WARN("%s: endpoint count cannot be 0.\n", __func__);
1820 		ret = FFA_ERROR_INVALID_PARAMETER;
1821 		goto err_unlock_mailbox;
1822 	}
1823 
1824 	spin_lock(&spmc_shmem_obj_state.lock);
1825 
1826 	obj = spmc_shmem_obj_lookup(&spmc_shmem_obj_state, req->handle);
1827 	if (obj == NULL) {
1828 		ret = FFA_ERROR_INVALID_PARAMETER;
1829 		goto err_unlock_all;
1830 	}
1831 
1832 	/*
1833 	 * Validate the endpoint ID was populated correctly. We don't currently
1834 	 * support proxy endpoints so the endpoint count should always be 1.
1835 	 */
1836 	if (req->endpoint_count != 1U) {
1837 		WARN("%s: unsupported endpoint count %u != 1\n", __func__,
1838 		     req->endpoint_count);
1839 		ret = FFA_ERROR_INVALID_PARAMETER;
1840 		goto err_unlock_all;
1841 	}
1842 
1843 	/* Validate provided endpoint ID matches the partition ID. */
1844 	if (req->endpoint_array[0] != sp_ctx->sp_id) {
1845 		WARN("%s: invalid endpoint ID %u != %u\n", __func__,
1846 		     req->endpoint_array[0], sp_ctx->sp_id);
1847 		ret = FFA_ERROR_INVALID_PARAMETER;
1848 		goto err_unlock_all;
1849 	}
1850 
1851 	/* Validate the caller is a valid participant. */
1852 	if (!spmc_shmem_obj_validate_id(obj, sp_ctx->sp_id)) {
1853 		WARN("%s: Invalid endpoint ID (0x%x).\n",
1854 			__func__, req->endpoint_array[0]);
1855 		ret = FFA_ERROR_INVALID_PARAMETER;
1856 		goto err_unlock_all;
1857 	}
1858 
1859 	if (obj->in_use == 0U) {
1860 		ret = FFA_ERROR_INVALID_PARAMETER;
1861 		goto err_unlock_all;
1862 	}
1863 	obj->in_use--;
1864 
1865 	spin_unlock(&spmc_shmem_obj_state.lock);
1866 	spin_unlock(&mbox->lock);
1867 
1868 	SMC_RET1(handle, FFA_SUCCESS_SMC32);
1869 
1870 err_unlock_all:
1871 	spin_unlock(&spmc_shmem_obj_state.lock);
1872 err_unlock_mailbox:
1873 	spin_unlock(&mbox->lock);
1874 	return spmc_ffa_error_return(handle, ret);
1875 }
1876 
1877 /**
1878  * spmc_ffa_mem_reclaim - FFA_MEM_RECLAIM implementation.
1879  * @client:         Client state.
1880  * @handle_low:     Unique handle of shared memory object to reclaim. Bit[31:0].
1881  * @handle_high:    Unique handle of shared memory object to reclaim.
1882  *                  Bit[63:32].
1883  * @flags:          Unsupported, ignored.
1884  *
1885  * Implements a subset of the FF-A FFA_MEM_RECLAIM call.
1886  * Used by non-secure os reclaim memory previously shared with secure os.
1887  *
1888  * Return: 0 on success, error code on failure.
1889  */
1890 int spmc_ffa_mem_reclaim(uint32_t smc_fid,
1891 			 bool secure_origin,
1892 			 uint32_t handle_low,
1893 			 uint32_t handle_high,
1894 			 uint32_t mem_flags,
1895 			 uint64_t x4,
1896 			 void *cookie,
1897 			 void *handle,
1898 			 uint64_t flags)
1899 {
1900 	int ret;
1901 	struct spmc_shmem_obj *obj;
1902 	uint64_t mem_handle = handle_low | (((uint64_t)handle_high) << 32);
1903 
1904 	if (secure_origin) {
1905 		WARN("%s: unsupported reclaim direction.\n", __func__);
1906 		return spmc_ffa_error_return(handle,
1907 					     FFA_ERROR_INVALID_PARAMETER);
1908 	}
1909 
1910 	if (mem_flags != 0U) {
1911 		WARN("%s: unsupported flags 0x%x\n", __func__, mem_flags);
1912 		return spmc_ffa_error_return(handle,
1913 					     FFA_ERROR_INVALID_PARAMETER);
1914 	}
1915 
1916 	spin_lock(&spmc_shmem_obj_state.lock);
1917 
1918 	obj = spmc_shmem_obj_lookup(&spmc_shmem_obj_state, mem_handle);
1919 	if (obj == NULL) {
1920 		ret = FFA_ERROR_INVALID_PARAMETER;
1921 		goto err_unlock;
1922 	}
1923 	if (obj->in_use != 0U) {
1924 		ret = FFA_ERROR_DENIED;
1925 		goto err_unlock;
1926 	}
1927 
1928 	if (obj->desc_filled != obj->desc_size) {
1929 		WARN("%s: incomplete object desc filled %zu < size %zu\n",
1930 		     __func__, obj->desc_filled, obj->desc_size);
1931 		ret = FFA_ERROR_INVALID_PARAMETER;
1932 		goto err_unlock;
1933 	}
1934 
1935 	/* Allow for platform specific operations to be performed. */
1936 	ret = plat_spmc_shmem_reclaim(&obj->desc);
1937 	if (ret != 0) {
1938 		goto err_unlock;
1939 	}
1940 
1941 	spmc_shmem_obj_free(&spmc_shmem_obj_state, obj);
1942 	spin_unlock(&spmc_shmem_obj_state.lock);
1943 
1944 	SMC_RET1(handle, FFA_SUCCESS_SMC32);
1945 
1946 err_unlock:
1947 	spin_unlock(&spmc_shmem_obj_state.lock);
1948 	return spmc_ffa_error_return(handle, ret);
1949 }
1950