xref: /linux/drivers/firmware/arm_ffa/driver.c (revision f183b1dda4fc0348c4016f6289588d5853ab7936)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Arm Firmware Framework for ARMv8-A(FFA) interface driver
4  *
5  * The Arm FFA specification[1] describes a software architecture to
6  * leverages the virtualization extension to isolate software images
7  * provided by an ecosystem of vendors from each other and describes
8  * interfaces that standardize communication between the various software
9  * images including communication between images in the Secure world and
10  * Normal world. Any Hypervisor could use the FFA interfaces to enable
11  * communication between VMs it manages.
12  *
13  * The Hypervisor a.k.a Partition managers in FFA terminology can assign
14  * system resources(Memory regions, Devices, CPU cycles) to the partitions
15  * and manage isolation amongst them.
16  *
17  * [1] https://developer.arm.com/docs/den0077/latest
18  *
19  * Copyright (C) 2021 ARM Ltd.
20  */
21 
22 #define DRIVER_NAME "ARM FF-A"
23 #define pr_fmt(fmt) DRIVER_NAME ": " fmt
24 
25 #include <linux/acpi.h>
26 #include <linux/arm_ffa.h>
27 #include <linux/bitfield.h>
28 #include <linux/cpuhotplug.h>
29 #include <linux/delay.h>
30 #include <linux/device.h>
31 #include <linux/hashtable.h>
32 #include <linux/interrupt.h>
33 #include <linux/io.h>
34 #include <linux/kernel.h>
35 #include <linux/module.h>
36 #include <linux/mm.h>
37 #include <linux/mutex.h>
38 #include <linux/of_irq.h>
39 #include <linux/scatterlist.h>
40 #include <linux/slab.h>
41 #include <linux/smp.h>
42 #include <linux/uuid.h>
43 #include <linux/xarray.h>
44 
45 #include "common.h"
46 
47 #define FFA_DRIVER_VERSION	FFA_VERSION_1_2
48 #define FFA_MIN_VERSION		FFA_VERSION_1_0
49 
50 #define SENDER_ID_MASK		GENMASK(31, 16)
51 #define RECEIVER_ID_MASK	GENMASK(15, 0)
52 #define SENDER_ID(x)		((u16)(FIELD_GET(SENDER_ID_MASK, (x))))
53 #define RECEIVER_ID(x)		((u16)(FIELD_GET(RECEIVER_ID_MASK, (x))))
54 #define PACK_TARGET_INFO(s, r)		\
55 	(FIELD_PREP(SENDER_ID_MASK, (s)) | FIELD_PREP(RECEIVER_ID_MASK, (r)))
56 
57 #define RXTX_MAP_MIN_BUFSZ_MASK	GENMASK(1, 0)
58 #define RXTX_MAP_MIN_BUFSZ(x)	((x) & RXTX_MAP_MIN_BUFSZ_MASK)
59 
60 #define FFA_MAX_NOTIFICATIONS		64
61 
62 static ffa_fn *invoke_ffa_fn;
63 
64 static const int ffa_linux_errmap[] = {
65 	/* better than switch case as long as return value is continuous */
66 	0,		/* FFA_RET_SUCCESS */
67 	-EOPNOTSUPP,	/* FFA_RET_NOT_SUPPORTED */
68 	-EINVAL,	/* FFA_RET_INVALID_PARAMETERS */
69 	-ENOMEM,	/* FFA_RET_NO_MEMORY */
70 	-EBUSY,		/* FFA_RET_BUSY */
71 	-EINTR,		/* FFA_RET_INTERRUPTED */
72 	-EACCES,	/* FFA_RET_DENIED */
73 	-EAGAIN,	/* FFA_RET_RETRY */
74 	-ECANCELED,	/* FFA_RET_ABORTED */
75 	-ENODATA,	/* FFA_RET_NO_DATA */
76 	-EAGAIN,	/* FFA_RET_NOT_READY */
77 };
78 
79 static inline int ffa_to_linux_errno(int errno)
80 {
81 	int err_idx = -errno;
82 
83 	if (err_idx >= 0 && err_idx < ARRAY_SIZE(ffa_linux_errmap))
84 		return ffa_linux_errmap[err_idx];
85 	return -EINVAL;
86 }
87 
88 struct ffa_pcpu_irq {
89 	struct ffa_drv_info *info;
90 };
91 
92 struct ffa_drv_info {
93 	u32 version;
94 	u16 vm_id;
95 	struct mutex rx_lock; /* lock to protect Rx buffer */
96 	struct mutex tx_lock; /* lock to protect Tx buffer */
97 	void *rx_buffer;
98 	void *tx_buffer;
99 	size_t rxtx_bufsz;
100 	bool mem_ops_native;
101 	bool msg_direct_req2_supp;
102 	bool bitmap_created;
103 	bool notif_enabled;
104 	unsigned int sched_recv_irq;
105 	unsigned int notif_pend_irq;
106 	unsigned int cpuhp_state;
107 	struct ffa_pcpu_irq __percpu *irq_pcpu;
108 	struct workqueue_struct *notif_pcpu_wq;
109 	struct work_struct notif_pcpu_work;
110 	struct work_struct sched_recv_irq_work;
111 	struct xarray partition_info;
112 	DECLARE_HASHTABLE(notifier_hash, ilog2(FFA_MAX_NOTIFICATIONS));
113 	rwlock_t notify_lock; /* lock to protect notifier hashtable  */
114 };
115 
116 static struct ffa_drv_info *drv_info;
117 
118 /*
119  * The driver must be able to support all the versions from the earliest
120  * supported FFA_MIN_VERSION to the latest supported FFA_DRIVER_VERSION.
121  * The specification states that if firmware supports a FFA implementation
122  * that is incompatible with and at a greater version number than specified
123  * by the caller(FFA_DRIVER_VERSION passed as parameter to FFA_VERSION),
124  * it must return the NOT_SUPPORTED error code.
125  */
126 static u32 ffa_compatible_version_find(u32 version)
127 {
128 	u16 major = FFA_MAJOR_VERSION(version), minor = FFA_MINOR_VERSION(version);
129 	u16 drv_major = FFA_MAJOR_VERSION(FFA_DRIVER_VERSION);
130 	u16 drv_minor = FFA_MINOR_VERSION(FFA_DRIVER_VERSION);
131 
132 	if ((major < drv_major) || (major == drv_major && minor <= drv_minor))
133 		return version;
134 
135 	pr_info("Firmware version higher than driver version, downgrading\n");
136 	return FFA_DRIVER_VERSION;
137 }
138 
139 static int ffa_version_check(u32 *version)
140 {
141 	ffa_value_t ver;
142 
143 	invoke_ffa_fn((ffa_value_t){
144 		      .a0 = FFA_VERSION, .a1 = FFA_DRIVER_VERSION,
145 		      }, &ver);
146 
147 	if ((s32)ver.a0 == FFA_RET_NOT_SUPPORTED) {
148 		pr_info("FFA_VERSION returned not supported\n");
149 		return -EOPNOTSUPP;
150 	}
151 
152 	if (FFA_MAJOR_VERSION(ver.a0) > FFA_MAJOR_VERSION(FFA_DRIVER_VERSION)) {
153 		pr_err("Incompatible v%d.%d! Latest supported v%d.%d\n",
154 		       FFA_MAJOR_VERSION(ver.a0), FFA_MINOR_VERSION(ver.a0),
155 		       FFA_MAJOR_VERSION(FFA_DRIVER_VERSION),
156 		       FFA_MINOR_VERSION(FFA_DRIVER_VERSION));
157 		return -EINVAL;
158 	}
159 
160 	if (ver.a0 < FFA_MIN_VERSION) {
161 		pr_err("Incompatible v%d.%d! Earliest supported v%d.%d\n",
162 		       FFA_MAJOR_VERSION(ver.a0), FFA_MINOR_VERSION(ver.a0),
163 		       FFA_MAJOR_VERSION(FFA_MIN_VERSION),
164 		       FFA_MINOR_VERSION(FFA_MIN_VERSION));
165 		return -EINVAL;
166 	}
167 
168 	pr_info("Driver version %d.%d\n", FFA_MAJOR_VERSION(FFA_DRIVER_VERSION),
169 		FFA_MINOR_VERSION(FFA_DRIVER_VERSION));
170 	pr_info("Firmware version %d.%d found\n", FFA_MAJOR_VERSION(ver.a0),
171 		FFA_MINOR_VERSION(ver.a0));
172 	*version = ffa_compatible_version_find(ver.a0);
173 
174 	return 0;
175 }
176 
177 static int ffa_rx_release(void)
178 {
179 	ffa_value_t ret;
180 
181 	invoke_ffa_fn((ffa_value_t){
182 		      .a0 = FFA_RX_RELEASE,
183 		      }, &ret);
184 
185 	if (ret.a0 == FFA_ERROR)
186 		return ffa_to_linux_errno((int)ret.a2);
187 
188 	/* check for ret.a0 == FFA_RX_RELEASE ? */
189 
190 	return 0;
191 }
192 
193 static int ffa_rxtx_map(phys_addr_t tx_buf, phys_addr_t rx_buf, u32 pg_cnt)
194 {
195 	ffa_value_t ret;
196 
197 	invoke_ffa_fn((ffa_value_t){
198 		      .a0 = FFA_FN_NATIVE(RXTX_MAP),
199 		      .a1 = tx_buf, .a2 = rx_buf, .a3 = pg_cnt,
200 		      }, &ret);
201 
202 	if (ret.a0 == FFA_ERROR)
203 		return ffa_to_linux_errno((int)ret.a2);
204 
205 	return 0;
206 }
207 
208 static int ffa_rxtx_unmap(u16 vm_id)
209 {
210 	ffa_value_t ret;
211 
212 	invoke_ffa_fn((ffa_value_t){
213 		      .a0 = FFA_RXTX_UNMAP, .a1 = PACK_TARGET_INFO(vm_id, 0),
214 		      }, &ret);
215 
216 	if (ret.a0 == FFA_ERROR)
217 		return ffa_to_linux_errno((int)ret.a2);
218 
219 	return 0;
220 }
221 
222 static int ffa_features(u32 func_feat_id, u32 input_props,
223 			u32 *if_props_1, u32 *if_props_2)
224 {
225 	ffa_value_t id;
226 
227 	if (!ARM_SMCCC_IS_FAST_CALL(func_feat_id) && input_props) {
228 		pr_err("%s: Invalid Parameters: %x, %x", __func__,
229 		       func_feat_id, input_props);
230 		return ffa_to_linux_errno(FFA_RET_INVALID_PARAMETERS);
231 	}
232 
233 	invoke_ffa_fn((ffa_value_t){
234 		.a0 = FFA_FEATURES, .a1 = func_feat_id, .a2 = input_props,
235 		}, &id);
236 
237 	if (id.a0 == FFA_ERROR)
238 		return ffa_to_linux_errno((int)id.a2);
239 
240 	if (if_props_1)
241 		*if_props_1 = id.a2;
242 	if (if_props_2)
243 		*if_props_2 = id.a3;
244 
245 	return 0;
246 }
247 
248 #define PARTITION_INFO_GET_RETURN_COUNT_ONLY	BIT(0)
249 #define FFA_SUPPORTS_GET_COUNT_ONLY(version)	((version) > FFA_VERSION_1_0)
250 #define FFA_PART_INFO_HAS_SIZE_IN_RESP(version)	((version) > FFA_VERSION_1_0)
251 #define FFA_PART_INFO_HAS_UUID_IN_RESP(version)	((version) > FFA_VERSION_1_0)
252 #define FFA_PART_INFO_HAS_EXEC_STATE_IN_RESP(version)	\
253 	((version) > FFA_VERSION_1_0)
254 
255 /* buffer must be sizeof(struct ffa_partition_info) * num_partitions */
256 static int
257 __ffa_partition_info_get(u32 uuid0, u32 uuid1, u32 uuid2, u32 uuid3,
258 			 struct ffa_partition_info *buffer, int num_partitions)
259 {
260 	int idx, count, flags = 0, sz, buf_sz;
261 	ffa_value_t partition_info;
262 
263 	if (FFA_SUPPORTS_GET_COUNT_ONLY(drv_info->version) &&
264 	    (!buffer || !num_partitions)) /* Just get the count for now */
265 		flags = PARTITION_INFO_GET_RETURN_COUNT_ONLY;
266 
267 	mutex_lock(&drv_info->rx_lock);
268 	invoke_ffa_fn((ffa_value_t){
269 		      .a0 = FFA_PARTITION_INFO_GET,
270 		      .a1 = uuid0, .a2 = uuid1, .a3 = uuid2, .a4 = uuid3,
271 		      .a5 = flags,
272 		      }, &partition_info);
273 
274 	if (partition_info.a0 == FFA_ERROR) {
275 		mutex_unlock(&drv_info->rx_lock);
276 		return ffa_to_linux_errno((int)partition_info.a2);
277 	}
278 
279 	count = partition_info.a2;
280 
281 	if (FFA_PART_INFO_HAS_SIZE_IN_RESP(drv_info->version)) {
282 		buf_sz = sz = partition_info.a3;
283 		if (sz > sizeof(*buffer))
284 			buf_sz = sizeof(*buffer);
285 	} else {
286 		buf_sz = sz = 8;
287 	}
288 
289 	if (buffer && count <= num_partitions)
290 		for (idx = 0; idx < count; idx++) {
291 			struct ffa_partition_info_le {
292 				__le16 id;
293 				__le16 exec_ctxt;
294 				__le32 properties;
295 				uuid_t uuid;
296 			} *rx_buf = drv_info->rx_buffer + idx * sz;
297 			struct ffa_partition_info *buf = buffer + idx;
298 
299 			buf->id = le16_to_cpu(rx_buf->id);
300 			buf->exec_ctxt = le16_to_cpu(rx_buf->exec_ctxt);
301 			buf->properties = le32_to_cpu(rx_buf->properties);
302 			if (buf_sz > 8)
303 				import_uuid(&buf->uuid, (u8 *)&rx_buf->uuid);
304 		}
305 
306 	if (!(flags & PARTITION_INFO_GET_RETURN_COUNT_ONLY))
307 		ffa_rx_release();
308 
309 	mutex_unlock(&drv_info->rx_lock);
310 
311 	return count;
312 }
313 
314 #define LAST_INDEX_MASK		GENMASK(15, 0)
315 #define CURRENT_INDEX_MASK	GENMASK(31, 16)
316 #define UUID_INFO_TAG_MASK	GENMASK(47, 32)
317 #define PARTITION_INFO_SZ_MASK	GENMASK(63, 48)
318 #define PARTITION_COUNT(x)	((u16)(FIELD_GET(LAST_INDEX_MASK, (x))) + 1)
319 #define CURRENT_INDEX(x)	((u16)(FIELD_GET(CURRENT_INDEX_MASK, (x))))
320 #define UUID_INFO_TAG(x)	((u16)(FIELD_GET(UUID_INFO_TAG_MASK, (x))))
321 #define PARTITION_INFO_SZ(x)	((u16)(FIELD_GET(PARTITION_INFO_SZ_MASK, (x))))
322 #define PART_INFO_ID_MASK	GENMASK(15, 0)
323 #define PART_INFO_EXEC_CXT_MASK	GENMASK(31, 16)
324 #define PART_INFO_PROPS_MASK	GENMASK(63, 32)
325 #define PART_INFO_ID(x)		((u16)(FIELD_GET(PART_INFO_ID_MASK, (x))))
326 #define PART_INFO_EXEC_CXT(x)	((u16)(FIELD_GET(PART_INFO_EXEC_CXT_MASK, (x))))
327 #define PART_INFO_PROPERTIES(x)	((u32)(FIELD_GET(PART_INFO_PROPS_MASK, (x))))
328 static int
329 __ffa_partition_info_get_regs(u32 uuid0, u32 uuid1, u32 uuid2, u32 uuid3,
330 			      struct ffa_partition_info *buffer, int num_parts)
331 {
332 	u16 buf_sz, start_idx, cur_idx, count = 0, prev_idx = 0, tag = 0;
333 	struct ffa_partition_info *buf = buffer;
334 	ffa_value_t partition_info;
335 
336 	do {
337 		__le64 *regs;
338 		int idx;
339 
340 		start_idx = prev_idx ? prev_idx + 1 : 0;
341 
342 		invoke_ffa_fn((ffa_value_t){
343 			      .a0 = FFA_PARTITION_INFO_GET_REGS,
344 			      .a1 = (u64)uuid1 << 32 | uuid0,
345 			      .a2 = (u64)uuid3 << 32 | uuid2,
346 			      .a3 = start_idx | tag << 16,
347 			      }, &partition_info);
348 
349 		if (partition_info.a0 == FFA_ERROR)
350 			return ffa_to_linux_errno((int)partition_info.a2);
351 
352 		if (!count)
353 			count = PARTITION_COUNT(partition_info.a2);
354 		if (!buffer || !num_parts) /* count only */
355 			return count;
356 
357 		cur_idx = CURRENT_INDEX(partition_info.a2);
358 		tag = UUID_INFO_TAG(partition_info.a2);
359 		buf_sz = PARTITION_INFO_SZ(partition_info.a2);
360 		if (buf_sz > sizeof(*buffer))
361 			buf_sz = sizeof(*buffer);
362 
363 		regs = (void *)&partition_info.a3;
364 		for (idx = 0; idx < cur_idx - start_idx + 1; idx++, buf++) {
365 			union {
366 				uuid_t uuid;
367 				u64 regs[2];
368 			} uuid_regs = {
369 				.regs = {
370 					le64_to_cpu(*(regs + 1)),
371 					le64_to_cpu(*(regs + 2)),
372 					}
373 			};
374 			u64 val = *(u64 *)regs;
375 
376 			buf->id = PART_INFO_ID(val);
377 			buf->exec_ctxt = PART_INFO_EXEC_CXT(val);
378 			buf->properties = PART_INFO_PROPERTIES(val);
379 			uuid_copy(&buf->uuid, &uuid_regs.uuid);
380 			regs += 3;
381 		}
382 		prev_idx = cur_idx;
383 
384 	} while (cur_idx < (count - 1));
385 
386 	return count;
387 }
388 
389 /* buffer is allocated and caller must free the same if returned count > 0 */
390 static int
391 ffa_partition_probe(const uuid_t *uuid, struct ffa_partition_info **buffer)
392 {
393 	int count;
394 	u32 uuid0_4[4];
395 	bool reg_mode = false;
396 	struct ffa_partition_info *pbuf;
397 
398 	if (!ffa_features(FFA_PARTITION_INFO_GET_REGS, 0, NULL, NULL))
399 		reg_mode = true;
400 
401 	export_uuid((u8 *)uuid0_4, uuid);
402 	if (reg_mode)
403 		count = __ffa_partition_info_get_regs(uuid0_4[0], uuid0_4[1],
404 						      uuid0_4[2], uuid0_4[3],
405 						      NULL, 0);
406 	else
407 		count = __ffa_partition_info_get(uuid0_4[0], uuid0_4[1],
408 						 uuid0_4[2], uuid0_4[3],
409 						 NULL, 0);
410 	if (count <= 0)
411 		return count;
412 
413 	pbuf = kcalloc(count, sizeof(*pbuf), GFP_KERNEL);
414 	if (!pbuf)
415 		return -ENOMEM;
416 
417 	if (reg_mode)
418 		count = __ffa_partition_info_get_regs(uuid0_4[0], uuid0_4[1],
419 						      uuid0_4[2], uuid0_4[3],
420 						      pbuf, count);
421 	else
422 		count = __ffa_partition_info_get(uuid0_4[0], uuid0_4[1],
423 						 uuid0_4[2], uuid0_4[3],
424 						 pbuf, count);
425 	if (count <= 0)
426 		kfree(pbuf);
427 	else
428 		*buffer = pbuf;
429 
430 	return count;
431 }
432 
433 #define VM_ID_MASK	GENMASK(15, 0)
434 static int ffa_id_get(u16 *vm_id)
435 {
436 	ffa_value_t id;
437 
438 	invoke_ffa_fn((ffa_value_t){
439 		      .a0 = FFA_ID_GET,
440 		      }, &id);
441 
442 	if (id.a0 == FFA_ERROR)
443 		return ffa_to_linux_errno((int)id.a2);
444 
445 	*vm_id = FIELD_GET(VM_ID_MASK, (id.a2));
446 
447 	return 0;
448 }
449 
450 static inline void ffa_msg_send_wait_for_completion(ffa_value_t *ret)
451 {
452 	while (ret->a0 == FFA_INTERRUPT || ret->a0 == FFA_YIELD) {
453 		if (ret->a0 == FFA_YIELD)
454 			fsleep(1000);
455 
456 		invoke_ffa_fn((ffa_value_t){
457 			      .a0 = FFA_RUN, .a1 = ret->a1,
458 			      }, ret);
459 	}
460 }
461 
462 static int ffa_msg_send_direct_req(u16 src_id, u16 dst_id, bool mode_32bit,
463 				   struct ffa_send_direct_data *data)
464 {
465 	u32 req_id, resp_id, src_dst_ids = PACK_TARGET_INFO(src_id, dst_id);
466 	ffa_value_t ret;
467 
468 	if (mode_32bit) {
469 		req_id = FFA_MSG_SEND_DIRECT_REQ;
470 		resp_id = FFA_MSG_SEND_DIRECT_RESP;
471 	} else {
472 		req_id = FFA_FN_NATIVE(MSG_SEND_DIRECT_REQ);
473 		resp_id = FFA_FN_NATIVE(MSG_SEND_DIRECT_RESP);
474 	}
475 
476 	invoke_ffa_fn((ffa_value_t){
477 		      .a0 = req_id, .a1 = src_dst_ids, .a2 = 0,
478 		      .a3 = data->data0, .a4 = data->data1, .a5 = data->data2,
479 		      .a6 = data->data3, .a7 = data->data4,
480 		      }, &ret);
481 
482 	ffa_msg_send_wait_for_completion(&ret);
483 
484 	if (ret.a0 == FFA_ERROR)
485 		return ffa_to_linux_errno((int)ret.a2);
486 
487 	if (ret.a0 == resp_id) {
488 		data->data0 = ret.a3;
489 		data->data1 = ret.a4;
490 		data->data2 = ret.a5;
491 		data->data3 = ret.a6;
492 		data->data4 = ret.a7;
493 		return 0;
494 	}
495 
496 	return -EINVAL;
497 }
498 
499 static int ffa_msg_send2(struct ffa_device *dev, u16 src_id, void *buf, size_t sz)
500 {
501 	u32 src_dst_ids = PACK_TARGET_INFO(src_id, dev->vm_id);
502 	struct ffa_indirect_msg_hdr *msg;
503 	ffa_value_t ret;
504 	int retval = 0;
505 
506 	if (sz > (drv_info->rxtx_bufsz - sizeof(*msg)))
507 		return -ERANGE;
508 
509 	mutex_lock(&drv_info->tx_lock);
510 
511 	msg = drv_info->tx_buffer;
512 	msg->flags = 0;
513 	msg->res0 = 0;
514 	msg->offset = sizeof(*msg);
515 	msg->send_recv_id = src_dst_ids;
516 	msg->size = sz;
517 	uuid_copy(&msg->uuid, &dev->uuid);
518 	memcpy((u8 *)msg + msg->offset, buf, sz);
519 
520 	/* flags = 0, sender VMID = 0 works for both physical/virtual NS */
521 	invoke_ffa_fn((ffa_value_t){
522 		      .a0 = FFA_MSG_SEND2, .a1 = 0, .a2 = 0
523 		      }, &ret);
524 
525 	if (ret.a0 == FFA_ERROR)
526 		retval = ffa_to_linux_errno((int)ret.a2);
527 
528 	mutex_unlock(&drv_info->tx_lock);
529 	return retval;
530 }
531 
532 static int ffa_msg_send_direct_req2(u16 src_id, u16 dst_id, const uuid_t *uuid,
533 				    struct ffa_send_direct_data2 *data)
534 {
535 	u32 src_dst_ids = PACK_TARGET_INFO(src_id, dst_id);
536 	union {
537 		uuid_t uuid;
538 		__le64 regs[2];
539 	} uuid_regs = { .uuid = *uuid };
540 	ffa_value_t ret, args = {
541 		.a0 = FFA_MSG_SEND_DIRECT_REQ2,
542 		.a1 = src_dst_ids,
543 		.a2 = le64_to_cpu(uuid_regs.regs[0]),
544 		.a3 = le64_to_cpu(uuid_regs.regs[1]),
545 	};
546 	memcpy((void *)&args + offsetof(ffa_value_t, a4), data, sizeof(*data));
547 
548 	invoke_ffa_fn(args, &ret);
549 
550 	ffa_msg_send_wait_for_completion(&ret);
551 
552 	if (ret.a0 == FFA_ERROR)
553 		return ffa_to_linux_errno((int)ret.a2);
554 
555 	if (ret.a0 == FFA_MSG_SEND_DIRECT_RESP2) {
556 		memcpy(data, (void *)&ret + offsetof(ffa_value_t, a4), sizeof(*data));
557 		return 0;
558 	}
559 
560 	return -EINVAL;
561 }
562 
563 static int ffa_mem_first_frag(u32 func_id, phys_addr_t buf, u32 buf_sz,
564 			      u32 frag_len, u32 len, u64 *handle)
565 {
566 	ffa_value_t ret;
567 
568 	invoke_ffa_fn((ffa_value_t){
569 		      .a0 = func_id, .a1 = len, .a2 = frag_len,
570 		      .a3 = buf, .a4 = buf_sz,
571 		      }, &ret);
572 
573 	while (ret.a0 == FFA_MEM_OP_PAUSE)
574 		invoke_ffa_fn((ffa_value_t){
575 			      .a0 = FFA_MEM_OP_RESUME,
576 			      .a1 = ret.a1, .a2 = ret.a2,
577 			      }, &ret);
578 
579 	if (ret.a0 == FFA_ERROR)
580 		return ffa_to_linux_errno((int)ret.a2);
581 
582 	if (ret.a0 == FFA_SUCCESS) {
583 		if (handle)
584 			*handle = PACK_HANDLE(ret.a2, ret.a3);
585 	} else if (ret.a0 == FFA_MEM_FRAG_RX) {
586 		if (handle)
587 			*handle = PACK_HANDLE(ret.a1, ret.a2);
588 	} else {
589 		return -EOPNOTSUPP;
590 	}
591 
592 	return frag_len;
593 }
594 
595 static int ffa_mem_next_frag(u64 handle, u32 frag_len)
596 {
597 	ffa_value_t ret;
598 
599 	invoke_ffa_fn((ffa_value_t){
600 		      .a0 = FFA_MEM_FRAG_TX,
601 		      .a1 = HANDLE_LOW(handle), .a2 = HANDLE_HIGH(handle),
602 		      .a3 = frag_len,
603 		      }, &ret);
604 
605 	while (ret.a0 == FFA_MEM_OP_PAUSE)
606 		invoke_ffa_fn((ffa_value_t){
607 			      .a0 = FFA_MEM_OP_RESUME,
608 			      .a1 = ret.a1, .a2 = ret.a2,
609 			      }, &ret);
610 
611 	if (ret.a0 == FFA_ERROR)
612 		return ffa_to_linux_errno((int)ret.a2);
613 
614 	if (ret.a0 == FFA_MEM_FRAG_RX)
615 		return ret.a3;
616 	else if (ret.a0 == FFA_SUCCESS)
617 		return 0;
618 
619 	return -EOPNOTSUPP;
620 }
621 
622 static int
623 ffa_transmit_fragment(u32 func_id, phys_addr_t buf, u32 buf_sz, u32 frag_len,
624 		      u32 len, u64 *handle, bool first)
625 {
626 	if (!first)
627 		return ffa_mem_next_frag(*handle, frag_len);
628 
629 	return ffa_mem_first_frag(func_id, buf, buf_sz, frag_len, len, handle);
630 }
631 
632 static u32 ffa_get_num_pages_sg(struct scatterlist *sg)
633 {
634 	u32 num_pages = 0;
635 
636 	do {
637 		num_pages += sg->length / FFA_PAGE_SIZE;
638 	} while ((sg = sg_next(sg)));
639 
640 	return num_pages;
641 }
642 
643 static u16 ffa_memory_attributes_get(u32 func_id)
644 {
645 	/*
646 	 * For the memory lend or donate operation, if the receiver is a PE or
647 	 * a proxy endpoint, the owner/sender must not specify the attributes
648 	 */
649 	if (func_id == FFA_FN_NATIVE(MEM_LEND) ||
650 	    func_id == FFA_MEM_LEND)
651 		return 0;
652 
653 	return FFA_MEM_NORMAL | FFA_MEM_WRITE_BACK | FFA_MEM_INNER_SHAREABLE;
654 }
655 
656 static void ffa_emad_impdef_value_init(u32 version, void *dst, void *src)
657 {
658 	struct ffa_mem_region_attributes *ep_mem_access;
659 
660 	if (FFA_EMAD_HAS_IMPDEF_FIELD(version))
661 		memcpy(dst, src, sizeof(ep_mem_access->impdef_val));
662 }
663 
664 static void
665 ffa_mem_region_additional_setup(u32 version, struct ffa_mem_region *mem_region)
666 {
667 	if (!FFA_MEM_REGION_HAS_EP_MEM_OFFSET(version)) {
668 		mem_region->ep_mem_size = 0;
669 	} else {
670 		mem_region->ep_mem_size = ffa_emad_size_get(version);
671 		mem_region->ep_mem_offset = sizeof(*mem_region);
672 		memset(mem_region->reserved, 0, 12);
673 	}
674 }
675 
676 static int
677 ffa_setup_and_transmit(u32 func_id, void *buffer, u32 max_fragsize,
678 		       struct ffa_mem_ops_args *args)
679 {
680 	int rc = 0;
681 	bool first = true;
682 	u32 composite_offset;
683 	phys_addr_t addr = 0;
684 	struct ffa_mem_region *mem_region = buffer;
685 	struct ffa_composite_mem_region *composite;
686 	struct ffa_mem_region_addr_range *constituents;
687 	struct ffa_mem_region_attributes *ep_mem_access;
688 	u32 idx, frag_len, length, buf_sz = 0, num_entries = sg_nents(args->sg);
689 
690 	mem_region->tag = args->tag;
691 	mem_region->flags = args->flags;
692 	mem_region->sender_id = drv_info->vm_id;
693 	mem_region->attributes = ffa_memory_attributes_get(func_id);
694 	composite_offset = ffa_mem_desc_offset(buffer, args->nattrs,
695 					       drv_info->version);
696 
697 	for (idx = 0; idx < args->nattrs; idx++) {
698 		ep_mem_access = buffer +
699 			ffa_mem_desc_offset(buffer, idx, drv_info->version);
700 		ep_mem_access->receiver = args->attrs[idx].receiver;
701 		ep_mem_access->attrs = args->attrs[idx].attrs;
702 		ep_mem_access->composite_off = composite_offset;
703 		ep_mem_access->flag = 0;
704 		ep_mem_access->reserved = 0;
705 		ffa_emad_impdef_value_init(drv_info->version,
706 					   ep_mem_access->impdef_val,
707 					   args->attrs[idx].impdef_val);
708 	}
709 	mem_region->handle = 0;
710 	mem_region->ep_count = args->nattrs;
711 	ffa_mem_region_additional_setup(drv_info->version, mem_region);
712 
713 	composite = buffer + composite_offset;
714 	composite->total_pg_cnt = ffa_get_num_pages_sg(args->sg);
715 	composite->addr_range_cnt = num_entries;
716 	composite->reserved = 0;
717 
718 	length = composite_offset + CONSTITUENTS_OFFSET(num_entries);
719 	frag_len = composite_offset + CONSTITUENTS_OFFSET(0);
720 	if (frag_len > max_fragsize)
721 		return -ENXIO;
722 
723 	if (!args->use_txbuf) {
724 		addr = virt_to_phys(buffer);
725 		buf_sz = max_fragsize / FFA_PAGE_SIZE;
726 	}
727 
728 	constituents = buffer + frag_len;
729 	idx = 0;
730 	do {
731 		if (frag_len == max_fragsize) {
732 			rc = ffa_transmit_fragment(func_id, addr, buf_sz,
733 						   frag_len, length,
734 						   &args->g_handle, first);
735 			if (rc < 0)
736 				return -ENXIO;
737 
738 			first = false;
739 			idx = 0;
740 			frag_len = 0;
741 			constituents = buffer;
742 		}
743 
744 		if ((void *)constituents - buffer > max_fragsize) {
745 			pr_err("Memory Region Fragment > Tx Buffer size\n");
746 			return -EFAULT;
747 		}
748 
749 		constituents->address = sg_phys(args->sg);
750 		constituents->pg_cnt = args->sg->length / FFA_PAGE_SIZE;
751 		constituents->reserved = 0;
752 		constituents++;
753 		frag_len += sizeof(struct ffa_mem_region_addr_range);
754 	} while ((args->sg = sg_next(args->sg)));
755 
756 	return ffa_transmit_fragment(func_id, addr, buf_sz, frag_len,
757 				     length, &args->g_handle, first);
758 }
759 
760 static int ffa_memory_ops(u32 func_id, struct ffa_mem_ops_args *args)
761 {
762 	int ret;
763 	void *buffer;
764 	size_t rxtx_bufsz = drv_info->rxtx_bufsz;
765 
766 	if (!args->use_txbuf) {
767 		buffer = alloc_pages_exact(rxtx_bufsz, GFP_KERNEL);
768 		if (!buffer)
769 			return -ENOMEM;
770 	} else {
771 		buffer = drv_info->tx_buffer;
772 		mutex_lock(&drv_info->tx_lock);
773 	}
774 
775 	ret = ffa_setup_and_transmit(func_id, buffer, rxtx_bufsz, args);
776 
777 	if (args->use_txbuf)
778 		mutex_unlock(&drv_info->tx_lock);
779 	else
780 		free_pages_exact(buffer, rxtx_bufsz);
781 
782 	return ret < 0 ? ret : 0;
783 }
784 
785 static int ffa_memory_reclaim(u64 g_handle, u32 flags)
786 {
787 	ffa_value_t ret;
788 
789 	invoke_ffa_fn((ffa_value_t){
790 		      .a0 = FFA_MEM_RECLAIM,
791 		      .a1 = HANDLE_LOW(g_handle), .a2 = HANDLE_HIGH(g_handle),
792 		      .a3 = flags,
793 		      }, &ret);
794 
795 	if (ret.a0 == FFA_ERROR)
796 		return ffa_to_linux_errno((int)ret.a2);
797 
798 	return 0;
799 }
800 
801 static int ffa_notification_bitmap_create(void)
802 {
803 	ffa_value_t ret;
804 	u16 vcpu_count = nr_cpu_ids;
805 
806 	invoke_ffa_fn((ffa_value_t){
807 		      .a0 = FFA_NOTIFICATION_BITMAP_CREATE,
808 		      .a1 = drv_info->vm_id, .a2 = vcpu_count,
809 		      }, &ret);
810 
811 	if (ret.a0 == FFA_ERROR)
812 		return ffa_to_linux_errno((int)ret.a2);
813 
814 	return 0;
815 }
816 
817 static int ffa_notification_bitmap_destroy(void)
818 {
819 	ffa_value_t ret;
820 
821 	invoke_ffa_fn((ffa_value_t){
822 		      .a0 = FFA_NOTIFICATION_BITMAP_DESTROY,
823 		      .a1 = drv_info->vm_id,
824 		      }, &ret);
825 
826 	if (ret.a0 == FFA_ERROR)
827 		return ffa_to_linux_errno((int)ret.a2);
828 
829 	return 0;
830 }
831 
832 enum notify_type {
833 	SECURE_PARTITION,
834 	NON_SECURE_VM,
835 	SPM_FRAMEWORK,
836 	NS_HYP_FRAMEWORK,
837 };
838 
839 #define NOTIFICATION_LOW_MASK		GENMASK(31, 0)
840 #define NOTIFICATION_HIGH_MASK		GENMASK(63, 32)
841 #define NOTIFICATION_BITMAP_HIGH(x)	\
842 		((u32)(FIELD_GET(NOTIFICATION_HIGH_MASK, (x))))
843 #define NOTIFICATION_BITMAP_LOW(x)	\
844 		((u32)(FIELD_GET(NOTIFICATION_LOW_MASK, (x))))
845 #define PACK_NOTIFICATION_BITMAP(low, high)	\
846 	(FIELD_PREP(NOTIFICATION_LOW_MASK, (low)) | \
847 	 FIELD_PREP(NOTIFICATION_HIGH_MASK, (high)))
848 
849 #define RECEIVER_VCPU_MASK		GENMASK(31, 16)
850 #define PACK_NOTIFICATION_GET_RECEIVER_INFO(vcpu_r, r) \
851 	(FIELD_PREP(RECEIVER_VCPU_MASK, (vcpu_r)) | \
852 	 FIELD_PREP(RECEIVER_ID_MASK, (r)))
853 
854 #define NOTIFICATION_INFO_GET_MORE_PEND_MASK	BIT(0)
855 #define NOTIFICATION_INFO_GET_ID_COUNT		GENMASK(11, 7)
856 #define ID_LIST_MASK_64				GENMASK(51, 12)
857 #define ID_LIST_MASK_32				GENMASK(31, 12)
858 #define MAX_IDS_64				20
859 #define MAX_IDS_32				10
860 
861 #define PER_VCPU_NOTIFICATION_FLAG		BIT(0)
862 #define SECURE_PARTITION_BITMAP_ENABLE		BIT(SECURE_PARTITION)
863 #define NON_SECURE_VM_BITMAP_ENABLE		BIT(NON_SECURE_VM)
864 #define SPM_FRAMEWORK_BITMAP_ENABLE		BIT(SPM_FRAMEWORK)
865 #define NS_HYP_FRAMEWORK_BITMAP_ENABLE		BIT(NS_HYP_FRAMEWORK)
866 #define FFA_BITMAP_SECURE_ENABLE_MASK		\
867 	(SECURE_PARTITION_BITMAP_ENABLE | SPM_FRAMEWORK_BITMAP_ENABLE)
868 #define FFA_BITMAP_NS_ENABLE_MASK		\
869 	(NON_SECURE_VM_BITMAP_ENABLE | NS_HYP_FRAMEWORK_BITMAP_ENABLE)
870 #define FFA_BITMAP_ALL_ENABLE_MASK		\
871 	(FFA_BITMAP_SECURE_ENABLE_MASK | FFA_BITMAP_NS_ENABLE_MASK)
872 
873 #define FFA_SECURE_PARTITION_ID_FLAG		BIT(15)
874 
875 #define SPM_FRAMEWORK_BITMAP(x)			NOTIFICATION_BITMAP_LOW(x)
876 #define NS_HYP_FRAMEWORK_BITMAP(x)		NOTIFICATION_BITMAP_HIGH(x)
877 #define FRAMEWORK_NOTIFY_RX_BUFFER_FULL		BIT(0)
878 
879 static int ffa_notification_bind_common(u16 dst_id, u64 bitmap,
880 					u32 flags, bool is_bind)
881 {
882 	ffa_value_t ret;
883 	u32 func, src_dst_ids = PACK_TARGET_INFO(dst_id, drv_info->vm_id);
884 
885 	func = is_bind ? FFA_NOTIFICATION_BIND : FFA_NOTIFICATION_UNBIND;
886 
887 	invoke_ffa_fn((ffa_value_t){
888 		  .a0 = func, .a1 = src_dst_ids, .a2 = flags,
889 		  .a3 = NOTIFICATION_BITMAP_LOW(bitmap),
890 		  .a4 = NOTIFICATION_BITMAP_HIGH(bitmap),
891 		  }, &ret);
892 
893 	if (ret.a0 == FFA_ERROR)
894 		return ffa_to_linux_errno((int)ret.a2);
895 	else if (ret.a0 != FFA_SUCCESS)
896 		return -EINVAL;
897 
898 	return 0;
899 }
900 
901 static
902 int ffa_notification_set(u16 src_id, u16 dst_id, u32 flags, u64 bitmap)
903 {
904 	ffa_value_t ret;
905 	u32 src_dst_ids = PACK_TARGET_INFO(dst_id, src_id);
906 
907 	invoke_ffa_fn((ffa_value_t) {
908 		  .a0 = FFA_NOTIFICATION_SET, .a1 = src_dst_ids, .a2 = flags,
909 		  .a3 = NOTIFICATION_BITMAP_LOW(bitmap),
910 		  .a4 = NOTIFICATION_BITMAP_HIGH(bitmap),
911 		  }, &ret);
912 
913 	if (ret.a0 == FFA_ERROR)
914 		return ffa_to_linux_errno((int)ret.a2);
915 	else if (ret.a0 != FFA_SUCCESS)
916 		return -EINVAL;
917 
918 	return 0;
919 }
920 
921 struct ffa_notify_bitmaps {
922 	u64 sp_map;
923 	u64 vm_map;
924 	u64 arch_map;
925 };
926 
927 static int ffa_notification_get(u32 flags, struct ffa_notify_bitmaps *notify)
928 {
929 	ffa_value_t ret;
930 	u16 src_id = drv_info->vm_id;
931 	u16 cpu_id = smp_processor_id();
932 	u32 rec_vcpu_ids = PACK_NOTIFICATION_GET_RECEIVER_INFO(cpu_id, src_id);
933 
934 	invoke_ffa_fn((ffa_value_t){
935 		  .a0 = FFA_NOTIFICATION_GET, .a1 = rec_vcpu_ids, .a2 = flags,
936 		  }, &ret);
937 
938 	if (ret.a0 == FFA_ERROR)
939 		return ffa_to_linux_errno((int)ret.a2);
940 	else if (ret.a0 != FFA_SUCCESS)
941 		return -EINVAL; /* Something else went wrong. */
942 
943 	if (flags & SECURE_PARTITION_BITMAP_ENABLE)
944 		notify->sp_map = PACK_NOTIFICATION_BITMAP(ret.a2, ret.a3);
945 	if (flags & NON_SECURE_VM_BITMAP_ENABLE)
946 		notify->vm_map = PACK_NOTIFICATION_BITMAP(ret.a4, ret.a5);
947 	if (flags & SPM_FRAMEWORK_BITMAP_ENABLE)
948 		notify->arch_map = SPM_FRAMEWORK_BITMAP(ret.a6);
949 	if (flags & NS_HYP_FRAMEWORK_BITMAP_ENABLE)
950 		notify->arch_map = PACK_NOTIFICATION_BITMAP(notify->arch_map,
951 							    ret.a7);
952 
953 	return 0;
954 }
955 
956 struct ffa_dev_part_info {
957 	ffa_sched_recv_cb callback;
958 	void *cb_data;
959 	rwlock_t rw_lock;
960 	struct ffa_device *dev;
961 	struct list_head node;
962 };
963 
964 static void __do_sched_recv_cb(u16 part_id, u16 vcpu, bool is_per_vcpu)
965 {
966 	struct ffa_dev_part_info *partition = NULL, *tmp;
967 	ffa_sched_recv_cb callback;
968 	struct list_head *phead;
969 	void *cb_data;
970 
971 	phead = xa_load(&drv_info->partition_info, part_id);
972 	if (!phead) {
973 		pr_err("%s: Invalid partition ID 0x%x\n", __func__, part_id);
974 		return;
975 	}
976 
977 	list_for_each_entry_safe(partition, tmp, phead, node) {
978 		read_lock(&partition->rw_lock);
979 		callback = partition->callback;
980 		cb_data = partition->cb_data;
981 		read_unlock(&partition->rw_lock);
982 
983 		if (callback)
984 			callback(vcpu, is_per_vcpu, cb_data);
985 	}
986 }
987 
988 static void ffa_notification_info_get(void)
989 {
990 	int idx, list, max_ids, lists_cnt, ids_processed, ids_count[MAX_IDS_64];
991 	bool is_64b_resp;
992 	ffa_value_t ret;
993 	u64 id_list;
994 
995 	do {
996 		invoke_ffa_fn((ffa_value_t){
997 			  .a0 = FFA_FN_NATIVE(NOTIFICATION_INFO_GET),
998 			  }, &ret);
999 
1000 		if (ret.a0 != FFA_FN_NATIVE(SUCCESS) && ret.a0 != FFA_SUCCESS) {
1001 			if ((s32)ret.a2 != FFA_RET_NO_DATA)
1002 				pr_err("Notification Info fetch failed: 0x%lx (0x%lx)",
1003 				       ret.a0, ret.a2);
1004 			return;
1005 		}
1006 
1007 		is_64b_resp = (ret.a0 == FFA_FN64_SUCCESS);
1008 
1009 		ids_processed = 0;
1010 		lists_cnt = FIELD_GET(NOTIFICATION_INFO_GET_ID_COUNT, ret.a2);
1011 		if (is_64b_resp) {
1012 			max_ids = MAX_IDS_64;
1013 			id_list = FIELD_GET(ID_LIST_MASK_64, ret.a2);
1014 		} else {
1015 			max_ids = MAX_IDS_32;
1016 			id_list = FIELD_GET(ID_LIST_MASK_32, ret.a2);
1017 		}
1018 
1019 		for (idx = 0; idx < lists_cnt; idx++, id_list >>= 2)
1020 			ids_count[idx] = (id_list & 0x3) + 1;
1021 
1022 		/* Process IDs */
1023 		for (list = 0; list < lists_cnt; list++) {
1024 			u16 vcpu_id, part_id, *packed_id_list = (u16 *)&ret.a3;
1025 
1026 			if (ids_processed >= max_ids - 1)
1027 				break;
1028 
1029 			part_id = packed_id_list[ids_processed++];
1030 
1031 			if (ids_count[list] == 1) { /* Global Notification */
1032 				__do_sched_recv_cb(part_id, 0, false);
1033 				continue;
1034 			}
1035 
1036 			/* Per vCPU Notification */
1037 			for (idx = 1; idx < ids_count[list]; idx++) {
1038 				if (ids_processed >= max_ids - 1)
1039 					break;
1040 
1041 				vcpu_id = packed_id_list[ids_processed++];
1042 
1043 				__do_sched_recv_cb(part_id, vcpu_id, true);
1044 			}
1045 		}
1046 	} while (ret.a2 & NOTIFICATION_INFO_GET_MORE_PEND_MASK);
1047 }
1048 
1049 static int ffa_run(struct ffa_device *dev, u16 vcpu)
1050 {
1051 	ffa_value_t ret;
1052 	u32 target = dev->vm_id << 16 | vcpu;
1053 
1054 	invoke_ffa_fn((ffa_value_t){ .a0 = FFA_RUN, .a1 = target, }, &ret);
1055 
1056 	while (ret.a0 == FFA_INTERRUPT)
1057 		invoke_ffa_fn((ffa_value_t){ .a0 = FFA_RUN, .a1 = ret.a1, },
1058 			      &ret);
1059 
1060 	if (ret.a0 == FFA_ERROR)
1061 		return ffa_to_linux_errno((int)ret.a2);
1062 
1063 	return 0;
1064 }
1065 
1066 static void ffa_drvinfo_flags_init(void)
1067 {
1068 	if (!ffa_features(FFA_FN_NATIVE(MEM_LEND), 0, NULL, NULL) ||
1069 	    !ffa_features(FFA_FN_NATIVE(MEM_SHARE), 0, NULL, NULL))
1070 		drv_info->mem_ops_native = true;
1071 
1072 	if (!ffa_features(FFA_MSG_SEND_DIRECT_REQ2, 0, NULL, NULL) ||
1073 	    !ffa_features(FFA_MSG_SEND_DIRECT_RESP2, 0, NULL, NULL))
1074 		drv_info->msg_direct_req2_supp = true;
1075 }
1076 
1077 static u32 ffa_api_version_get(void)
1078 {
1079 	return drv_info->version;
1080 }
1081 
1082 static int ffa_partition_info_get(const char *uuid_str,
1083 				  struct ffa_partition_info *buffer)
1084 {
1085 	int count;
1086 	uuid_t uuid;
1087 	struct ffa_partition_info *pbuf;
1088 
1089 	if (uuid_parse(uuid_str, &uuid)) {
1090 		pr_err("invalid uuid (%s)\n", uuid_str);
1091 		return -ENODEV;
1092 	}
1093 
1094 	count = ffa_partition_probe(&uuid, &pbuf);
1095 	if (count <= 0)
1096 		return -ENOENT;
1097 
1098 	memcpy(buffer, pbuf, sizeof(*pbuf) * count);
1099 	kfree(pbuf);
1100 	return 0;
1101 }
1102 
1103 static void ffa_mode_32bit_set(struct ffa_device *dev)
1104 {
1105 	dev->mode_32bit = true;
1106 }
1107 
1108 static int ffa_sync_send_receive(struct ffa_device *dev,
1109 				 struct ffa_send_direct_data *data)
1110 {
1111 	return ffa_msg_send_direct_req(drv_info->vm_id, dev->vm_id,
1112 				       dev->mode_32bit, data);
1113 }
1114 
1115 static int ffa_indirect_msg_send(struct ffa_device *dev, void *buf, size_t sz)
1116 {
1117 	return ffa_msg_send2(dev, drv_info->vm_id, buf, sz);
1118 }
1119 
1120 static int ffa_sync_send_receive2(struct ffa_device *dev,
1121 				  struct ffa_send_direct_data2 *data)
1122 {
1123 	if (!drv_info->msg_direct_req2_supp)
1124 		return -EOPNOTSUPP;
1125 
1126 	return ffa_msg_send_direct_req2(drv_info->vm_id, dev->vm_id,
1127 					&dev->uuid, data);
1128 }
1129 
1130 static int ffa_memory_share(struct ffa_mem_ops_args *args)
1131 {
1132 	if (drv_info->mem_ops_native)
1133 		return ffa_memory_ops(FFA_FN_NATIVE(MEM_SHARE), args);
1134 
1135 	return ffa_memory_ops(FFA_MEM_SHARE, args);
1136 }
1137 
1138 static int ffa_memory_lend(struct ffa_mem_ops_args *args)
1139 {
1140 	/* Note that upon a successful MEM_LEND request the caller
1141 	 * must ensure that the memory region specified is not accessed
1142 	 * until a successful MEM_RECALIM call has been made.
1143 	 * On systems with a hypervisor present this will been enforced,
1144 	 * however on systems without a hypervisor the responsibility
1145 	 * falls to the calling kernel driver to prevent access.
1146 	 */
1147 	if (drv_info->mem_ops_native)
1148 		return ffa_memory_ops(FFA_FN_NATIVE(MEM_LEND), args);
1149 
1150 	return ffa_memory_ops(FFA_MEM_LEND, args);
1151 }
1152 
1153 #define ffa_notifications_disabled()	(!drv_info->notif_enabled)
1154 
1155 struct notifier_cb_info {
1156 	struct hlist_node hnode;
1157 	struct ffa_device *dev;
1158 	ffa_fwk_notifier_cb fwk_cb;
1159 	ffa_notifier_cb cb;
1160 	void *cb_data;
1161 };
1162 
1163 static int
1164 ffa_sched_recv_cb_update(struct ffa_device *dev, ffa_sched_recv_cb callback,
1165 			 void *cb_data, bool is_registration)
1166 {
1167 	struct ffa_dev_part_info *partition = NULL, *tmp;
1168 	struct list_head *phead;
1169 	bool cb_valid;
1170 
1171 	if (ffa_notifications_disabled())
1172 		return -EOPNOTSUPP;
1173 
1174 	phead = xa_load(&drv_info->partition_info, dev->vm_id);
1175 	if (!phead) {
1176 		pr_err("%s: Invalid partition ID 0x%x\n", __func__, dev->vm_id);
1177 		return -EINVAL;
1178 	}
1179 
1180 	list_for_each_entry_safe(partition, tmp, phead, node)
1181 		if (partition->dev == dev)
1182 			break;
1183 
1184 	if (!partition) {
1185 		pr_err("%s: No such partition ID 0x%x\n", __func__, dev->vm_id);
1186 		return -EINVAL;
1187 	}
1188 
1189 	write_lock(&partition->rw_lock);
1190 
1191 	cb_valid = !!partition->callback;
1192 	if (!(is_registration ^ cb_valid)) {
1193 		write_unlock(&partition->rw_lock);
1194 		return -EINVAL;
1195 	}
1196 
1197 	partition->callback = callback;
1198 	partition->cb_data = cb_data;
1199 
1200 	write_unlock(&partition->rw_lock);
1201 	return 0;
1202 }
1203 
1204 static int ffa_sched_recv_cb_register(struct ffa_device *dev,
1205 				      ffa_sched_recv_cb cb, void *cb_data)
1206 {
1207 	return ffa_sched_recv_cb_update(dev, cb, cb_data, true);
1208 }
1209 
1210 static int ffa_sched_recv_cb_unregister(struct ffa_device *dev)
1211 {
1212 	return ffa_sched_recv_cb_update(dev, NULL, NULL, false);
1213 }
1214 
1215 static int ffa_notification_bind(u16 dst_id, u64 bitmap, u32 flags)
1216 {
1217 	return ffa_notification_bind_common(dst_id, bitmap, flags, true);
1218 }
1219 
1220 static int ffa_notification_unbind(u16 dst_id, u64 bitmap)
1221 {
1222 	return ffa_notification_bind_common(dst_id, bitmap, 0, false);
1223 }
1224 
1225 static enum notify_type ffa_notify_type_get(u16 vm_id)
1226 {
1227 	if (vm_id & FFA_SECURE_PARTITION_ID_FLAG)
1228 		return SECURE_PARTITION;
1229 	else
1230 		return NON_SECURE_VM;
1231 }
1232 
1233 /* notifier_hnode_get* should be called with notify_lock held */
1234 static struct notifier_cb_info *
1235 notifier_hnode_get_by_vmid(u16 notify_id, int vmid)
1236 {
1237 	struct notifier_cb_info *node;
1238 
1239 	hash_for_each_possible(drv_info->notifier_hash, node, hnode, notify_id)
1240 		if (node->fwk_cb && vmid == node->dev->vm_id)
1241 			return node;
1242 
1243 	return NULL;
1244 }
1245 
1246 static struct notifier_cb_info *
1247 notifier_hnode_get_by_vmid_uuid(u16 notify_id, int vmid, const uuid_t *uuid)
1248 {
1249 	struct notifier_cb_info *node;
1250 
1251 	if (uuid_is_null(uuid))
1252 		return notifier_hnode_get_by_vmid(notify_id, vmid);
1253 
1254 	hash_for_each_possible(drv_info->notifier_hash, node, hnode, notify_id)
1255 		if (node->fwk_cb && vmid == node->dev->vm_id &&
1256 		    uuid_equal(&node->dev->uuid, uuid))
1257 			return node;
1258 
1259 	return NULL;
1260 }
1261 
1262 static struct notifier_cb_info *
1263 notifier_hnode_get_by_type(u16 notify_id, enum notify_type type)
1264 {
1265 	struct notifier_cb_info *node;
1266 
1267 	hash_for_each_possible(drv_info->notifier_hash, node, hnode, notify_id)
1268 		if (node->cb && type == ffa_notify_type_get(node->dev->vm_id))
1269 			return node;
1270 
1271 	return NULL;
1272 }
1273 
1274 static int update_notifier_cb(struct ffa_device *dev, int notify_id,
1275 			      struct notifier_cb_info *cb, bool is_framework)
1276 {
1277 	struct notifier_cb_info *cb_info = NULL;
1278 	enum notify_type type = ffa_notify_type_get(dev->vm_id);
1279 	bool cb_found, is_registration = !!cb;
1280 
1281 	if (is_framework)
1282 		cb_info = notifier_hnode_get_by_vmid_uuid(notify_id, dev->vm_id,
1283 							  &dev->uuid);
1284 	else
1285 		cb_info = notifier_hnode_get_by_type(notify_id, type);
1286 
1287 	cb_found = !!cb_info;
1288 
1289 	if (!(is_registration ^ cb_found))
1290 		return -EINVAL;
1291 
1292 	if (is_registration) {
1293 		hash_add(drv_info->notifier_hash, &cb->hnode, notify_id);
1294 	} else {
1295 		hash_del(&cb_info->hnode);
1296 		kfree(cb_info);
1297 	}
1298 
1299 	return 0;
1300 }
1301 
1302 static int __ffa_notify_relinquish(struct ffa_device *dev, int notify_id,
1303 				   bool is_framework)
1304 {
1305 	int rc;
1306 
1307 	if (ffa_notifications_disabled())
1308 		return -EOPNOTSUPP;
1309 
1310 	if (notify_id >= FFA_MAX_NOTIFICATIONS)
1311 		return -EINVAL;
1312 
1313 	write_lock(&drv_info->notify_lock);
1314 
1315 	rc = update_notifier_cb(dev, notify_id, NULL, is_framework);
1316 	if (rc) {
1317 		pr_err("Could not unregister notification callback\n");
1318 		write_unlock(&drv_info->notify_lock);
1319 		return rc;
1320 	}
1321 
1322 	if (!is_framework)
1323 		rc = ffa_notification_unbind(dev->vm_id, BIT(notify_id));
1324 
1325 	write_unlock(&drv_info->notify_lock);
1326 
1327 	return rc;
1328 }
1329 
1330 static int ffa_notify_relinquish(struct ffa_device *dev, int notify_id)
1331 {
1332 	return __ffa_notify_relinquish(dev, notify_id, false);
1333 }
1334 
1335 static int ffa_fwk_notify_relinquish(struct ffa_device *dev, int notify_id)
1336 {
1337 	return __ffa_notify_relinquish(dev, notify_id, true);
1338 }
1339 
1340 static int __ffa_notify_request(struct ffa_device *dev, bool is_per_vcpu,
1341 				void *cb, void *cb_data,
1342 				int notify_id, bool is_framework)
1343 {
1344 	int rc;
1345 	u32 flags = 0;
1346 	struct notifier_cb_info *cb_info = NULL;
1347 
1348 	if (ffa_notifications_disabled())
1349 		return -EOPNOTSUPP;
1350 
1351 	if (notify_id >= FFA_MAX_NOTIFICATIONS)
1352 		return -EINVAL;
1353 
1354 	cb_info = kzalloc(sizeof(*cb_info), GFP_KERNEL);
1355 	if (!cb_info)
1356 		return -ENOMEM;
1357 
1358 	cb_info->dev = dev;
1359 	cb_info->cb_data = cb_data;
1360 	if (is_framework)
1361 		cb_info->fwk_cb = cb;
1362 	else
1363 		cb_info->cb = cb;
1364 
1365 	write_lock(&drv_info->notify_lock);
1366 
1367 	if (!is_framework) {
1368 		if (is_per_vcpu)
1369 			flags = PER_VCPU_NOTIFICATION_FLAG;
1370 
1371 		rc = ffa_notification_bind(dev->vm_id, BIT(notify_id), flags);
1372 		if (rc)
1373 			goto out_unlock_free;
1374 	}
1375 
1376 	rc = update_notifier_cb(dev, notify_id, cb_info, is_framework);
1377 	if (rc) {
1378 		pr_err("Failed to register callback for %d - %d\n",
1379 		       notify_id, rc);
1380 		if (!is_framework)
1381 			ffa_notification_unbind(dev->vm_id, BIT(notify_id));
1382 	}
1383 
1384 out_unlock_free:
1385 	write_unlock(&drv_info->notify_lock);
1386 	if (rc)
1387 		kfree(cb_info);
1388 
1389 	return rc;
1390 }
1391 
1392 static int ffa_notify_request(struct ffa_device *dev, bool is_per_vcpu,
1393 			      ffa_notifier_cb cb, void *cb_data, int notify_id)
1394 {
1395 	return __ffa_notify_request(dev, is_per_vcpu, cb, cb_data, notify_id,
1396 				    false);
1397 }
1398 
1399 static int
1400 ffa_fwk_notify_request(struct ffa_device *dev, ffa_fwk_notifier_cb cb,
1401 		       void *cb_data, int notify_id)
1402 {
1403 	return __ffa_notify_request(dev, false, cb, cb_data, notify_id, true);
1404 }
1405 
1406 static int ffa_notify_send(struct ffa_device *dev, int notify_id,
1407 			   bool is_per_vcpu, u16 vcpu)
1408 {
1409 	u32 flags = 0;
1410 
1411 	if (ffa_notifications_disabled())
1412 		return -EOPNOTSUPP;
1413 
1414 	if (is_per_vcpu)
1415 		flags |= (PER_VCPU_NOTIFICATION_FLAG | vcpu << 16);
1416 
1417 	return ffa_notification_set(dev->vm_id, drv_info->vm_id, flags,
1418 				    BIT(notify_id));
1419 }
1420 
1421 static void handle_notif_callbacks(u64 bitmap, enum notify_type type)
1422 {
1423 	int notify_id;
1424 	struct notifier_cb_info *cb_info = NULL;
1425 
1426 	for (notify_id = 0; notify_id <= FFA_MAX_NOTIFICATIONS && bitmap;
1427 	     notify_id++, bitmap >>= 1) {
1428 		if (!(bitmap & 1))
1429 			continue;
1430 
1431 		read_lock(&drv_info->notify_lock);
1432 		cb_info = notifier_hnode_get_by_type(notify_id, type);
1433 		read_unlock(&drv_info->notify_lock);
1434 
1435 		if (cb_info && cb_info->cb)
1436 			cb_info->cb(notify_id, cb_info->cb_data);
1437 	}
1438 }
1439 
1440 static void handle_fwk_notif_callbacks(u32 bitmap)
1441 {
1442 	void *buf;
1443 	uuid_t uuid;
1444 	int notify_id = 0, target;
1445 	struct ffa_indirect_msg_hdr *msg;
1446 	struct notifier_cb_info *cb_info = NULL;
1447 
1448 	/* Only one framework notification defined and supported for now */
1449 	if (!(bitmap & FRAMEWORK_NOTIFY_RX_BUFFER_FULL))
1450 		return;
1451 
1452 	mutex_lock(&drv_info->rx_lock);
1453 
1454 	msg = drv_info->rx_buffer;
1455 	buf = kmemdup((void *)msg + msg->offset, msg->size, GFP_KERNEL);
1456 	if (!buf) {
1457 		mutex_unlock(&drv_info->rx_lock);
1458 		return;
1459 	}
1460 
1461 	target = SENDER_ID(msg->send_recv_id);
1462 	if (msg->offset >= sizeof(*msg))
1463 		uuid_copy(&uuid, &msg->uuid);
1464 	else
1465 		uuid_copy(&uuid, &uuid_null);
1466 
1467 	mutex_unlock(&drv_info->rx_lock);
1468 
1469 	ffa_rx_release();
1470 
1471 	read_lock(&drv_info->notify_lock);
1472 	cb_info = notifier_hnode_get_by_vmid_uuid(notify_id, target, &uuid);
1473 	read_unlock(&drv_info->notify_lock);
1474 
1475 	if (cb_info && cb_info->fwk_cb)
1476 		cb_info->fwk_cb(notify_id, cb_info->cb_data, buf);
1477 	kfree(buf);
1478 }
1479 
1480 static void notif_get_and_handle(void *cb_data)
1481 {
1482 	int rc;
1483 	u32 flags;
1484 	struct ffa_drv_info *info = cb_data;
1485 	struct ffa_notify_bitmaps bitmaps = { 0 };
1486 
1487 	if (info->vm_id == 0) /* Non secure physical instance */
1488 		flags = FFA_BITMAP_SECURE_ENABLE_MASK;
1489 	else
1490 		flags = FFA_BITMAP_ALL_ENABLE_MASK;
1491 
1492 	rc = ffa_notification_get(flags, &bitmaps);
1493 	if (rc) {
1494 		pr_err("Failed to retrieve notifications with %d!\n", rc);
1495 		return;
1496 	}
1497 
1498 	handle_fwk_notif_callbacks(SPM_FRAMEWORK_BITMAP(bitmaps.arch_map));
1499 	handle_fwk_notif_callbacks(NS_HYP_FRAMEWORK_BITMAP(bitmaps.arch_map));
1500 	handle_notif_callbacks(bitmaps.vm_map, NON_SECURE_VM);
1501 	handle_notif_callbacks(bitmaps.sp_map, SECURE_PARTITION);
1502 }
1503 
1504 static void
1505 ffa_self_notif_handle(u16 vcpu, bool is_per_vcpu, void *cb_data)
1506 {
1507 	struct ffa_drv_info *info = cb_data;
1508 
1509 	if (!is_per_vcpu)
1510 		notif_get_and_handle(info);
1511 	else
1512 		smp_call_function_single(vcpu, notif_get_and_handle, info, 0);
1513 }
1514 
1515 static void notif_pcpu_irq_work_fn(struct work_struct *work)
1516 {
1517 	struct ffa_drv_info *info = container_of(work, struct ffa_drv_info,
1518 						 notif_pcpu_work);
1519 
1520 	ffa_self_notif_handle(smp_processor_id(), true, info);
1521 }
1522 
1523 static const struct ffa_info_ops ffa_drv_info_ops = {
1524 	.api_version_get = ffa_api_version_get,
1525 	.partition_info_get = ffa_partition_info_get,
1526 };
1527 
1528 static const struct ffa_msg_ops ffa_drv_msg_ops = {
1529 	.mode_32bit_set = ffa_mode_32bit_set,
1530 	.sync_send_receive = ffa_sync_send_receive,
1531 	.indirect_send = ffa_indirect_msg_send,
1532 	.sync_send_receive2 = ffa_sync_send_receive2,
1533 };
1534 
1535 static const struct ffa_mem_ops ffa_drv_mem_ops = {
1536 	.memory_reclaim = ffa_memory_reclaim,
1537 	.memory_share = ffa_memory_share,
1538 	.memory_lend = ffa_memory_lend,
1539 };
1540 
1541 static const struct ffa_cpu_ops ffa_drv_cpu_ops = {
1542 	.run = ffa_run,
1543 };
1544 
1545 static const struct ffa_notifier_ops ffa_drv_notifier_ops = {
1546 	.sched_recv_cb_register = ffa_sched_recv_cb_register,
1547 	.sched_recv_cb_unregister = ffa_sched_recv_cb_unregister,
1548 	.notify_request = ffa_notify_request,
1549 	.notify_relinquish = ffa_notify_relinquish,
1550 	.fwk_notify_request = ffa_fwk_notify_request,
1551 	.fwk_notify_relinquish = ffa_fwk_notify_relinquish,
1552 	.notify_send = ffa_notify_send,
1553 };
1554 
1555 static const struct ffa_ops ffa_drv_ops = {
1556 	.info_ops = &ffa_drv_info_ops,
1557 	.msg_ops = &ffa_drv_msg_ops,
1558 	.mem_ops = &ffa_drv_mem_ops,
1559 	.cpu_ops = &ffa_drv_cpu_ops,
1560 	.notifier_ops = &ffa_drv_notifier_ops,
1561 };
1562 
1563 void ffa_device_match_uuid(struct ffa_device *ffa_dev, const uuid_t *uuid)
1564 {
1565 	int count, idx;
1566 	struct ffa_partition_info *pbuf, *tpbuf;
1567 
1568 	count = ffa_partition_probe(uuid, &pbuf);
1569 	if (count <= 0)
1570 		return;
1571 
1572 	for (idx = 0, tpbuf = pbuf; idx < count; idx++, tpbuf++)
1573 		if (tpbuf->id == ffa_dev->vm_id)
1574 			uuid_copy(&ffa_dev->uuid, uuid);
1575 	kfree(pbuf);
1576 }
1577 
1578 static int
1579 ffa_bus_notifier(struct notifier_block *nb, unsigned long action, void *data)
1580 {
1581 	struct device *dev = data;
1582 	struct ffa_device *fdev = to_ffa_dev(dev);
1583 
1584 	if (action == BUS_NOTIFY_BIND_DRIVER) {
1585 		struct ffa_driver *ffa_drv = to_ffa_driver(dev->driver);
1586 		const struct ffa_device_id *id_table = ffa_drv->id_table;
1587 
1588 		/*
1589 		 * FF-A v1.1 provides UUID for each partition as part of the
1590 		 * discovery API, the discovered UUID must be populated in the
1591 		 * device's UUID and there is no need to workaround by copying
1592 		 * the same from the driver table.
1593 		 */
1594 		if (uuid_is_null(&fdev->uuid))
1595 			ffa_device_match_uuid(fdev, &id_table->uuid);
1596 
1597 		return NOTIFY_OK;
1598 	}
1599 
1600 	return NOTIFY_DONE;
1601 }
1602 
1603 static struct notifier_block ffa_bus_nb = {
1604 	.notifier_call = ffa_bus_notifier,
1605 };
1606 
1607 static int ffa_xa_add_partition_info(struct ffa_device *dev)
1608 {
1609 	struct ffa_dev_part_info *info;
1610 	struct list_head *head, *phead;
1611 	int ret = -ENOMEM;
1612 
1613 	phead = xa_load(&drv_info->partition_info, dev->vm_id);
1614 	if (phead) {
1615 		head = phead;
1616 		list_for_each_entry(info, head, node) {
1617 			if (info->dev == dev) {
1618 				pr_err("%s: duplicate dev %p part ID 0x%x\n",
1619 				       __func__, dev, dev->vm_id);
1620 				return -EEXIST;
1621 			}
1622 		}
1623 	}
1624 
1625 	info = kzalloc(sizeof(*info), GFP_KERNEL);
1626 	if (!info)
1627 		return ret;
1628 
1629 	rwlock_init(&info->rw_lock);
1630 	info->dev = dev;
1631 
1632 	if (!phead) {
1633 		phead = kzalloc(sizeof(*phead), GFP_KERNEL);
1634 		if (!phead)
1635 			goto free_out;
1636 
1637 		INIT_LIST_HEAD(phead);
1638 
1639 		ret = xa_insert(&drv_info->partition_info, dev->vm_id, phead,
1640 				GFP_KERNEL);
1641 		if (ret) {
1642 			pr_err("%s: failed to save part ID 0x%x Ret:%d\n",
1643 			       __func__, dev->vm_id, ret);
1644 			goto free_out;
1645 		}
1646 	}
1647 	list_add(&info->node, phead);
1648 	return 0;
1649 
1650 free_out:
1651 	kfree(phead);
1652 	kfree(info);
1653 	return ret;
1654 }
1655 
1656 static int ffa_setup_host_partition(int vm_id)
1657 {
1658 	struct ffa_partition_info buf = { 0 };
1659 	struct ffa_device *ffa_dev;
1660 	int ret;
1661 
1662 	buf.id = vm_id;
1663 	ffa_dev = ffa_device_register(&buf, &ffa_drv_ops);
1664 	if (!ffa_dev) {
1665 		pr_err("%s: failed to register host partition ID 0x%x\n",
1666 		       __func__, vm_id);
1667 		return -EINVAL;
1668 	}
1669 
1670 	ret = ffa_xa_add_partition_info(ffa_dev);
1671 	if (ret)
1672 		return ret;
1673 
1674 	if (ffa_notifications_disabled())
1675 		return 0;
1676 
1677 	ret = ffa_sched_recv_cb_update(ffa_dev, ffa_self_notif_handle,
1678 				       drv_info, true);
1679 	if (ret)
1680 		pr_info("Failed to register driver sched callback %d\n", ret);
1681 
1682 	return ret;
1683 }
1684 
1685 static void ffa_partitions_cleanup(void)
1686 {
1687 	struct list_head *phead;
1688 	unsigned long idx;
1689 
1690 	/* Clean up/free all registered devices */
1691 	ffa_devices_unregister();
1692 
1693 	xa_for_each(&drv_info->partition_info, idx, phead) {
1694 		struct ffa_dev_part_info *info, *tmp;
1695 
1696 		xa_erase(&drv_info->partition_info, idx);
1697 		list_for_each_entry_safe(info, tmp, phead, node) {
1698 			list_del(&info->node);
1699 			kfree(info);
1700 		}
1701 		kfree(phead);
1702 	}
1703 
1704 	xa_destroy(&drv_info->partition_info);
1705 }
1706 
1707 static int ffa_setup_partitions(void)
1708 {
1709 	int count, idx, ret;
1710 	struct ffa_device *ffa_dev;
1711 	struct ffa_partition_info *pbuf, *tpbuf;
1712 
1713 	if (!FFA_PART_INFO_HAS_UUID_IN_RESP(drv_info->version)) {
1714 		ret = bus_register_notifier(&ffa_bus_type, &ffa_bus_nb);
1715 		if (ret)
1716 			pr_err("Failed to register FF-A bus notifiers\n");
1717 	}
1718 
1719 	count = ffa_partition_probe(&uuid_null, &pbuf);
1720 	if (count <= 0) {
1721 		pr_info("%s: No partitions found, error %d\n", __func__, count);
1722 		return -EINVAL;
1723 	}
1724 
1725 	xa_init(&drv_info->partition_info);
1726 	for (idx = 0, tpbuf = pbuf; idx < count; idx++, tpbuf++) {
1727 		/* Note that if the UUID will be uuid_null, that will require
1728 		 * ffa_bus_notifier() to find the UUID of this partition id
1729 		 * with help of ffa_device_match_uuid(). FF-A v1.1 and above
1730 		 * provides UUID here for each partition as part of the
1731 		 * discovery API and the same is passed.
1732 		 */
1733 		ffa_dev = ffa_device_register(tpbuf, &ffa_drv_ops);
1734 		if (!ffa_dev) {
1735 			pr_err("%s: failed to register partition ID 0x%x\n",
1736 			       __func__, tpbuf->id);
1737 			continue;
1738 		}
1739 
1740 		if (FFA_PART_INFO_HAS_EXEC_STATE_IN_RESP(drv_info->version) &&
1741 		    !(tpbuf->properties & FFA_PARTITION_AARCH64_EXEC))
1742 			ffa_mode_32bit_set(ffa_dev);
1743 
1744 		if (ffa_xa_add_partition_info(ffa_dev)) {
1745 			ffa_device_unregister(ffa_dev);
1746 			continue;
1747 		}
1748 	}
1749 
1750 	kfree(pbuf);
1751 
1752 	/*
1753 	 * Check if the host is already added as part of partition info
1754 	 * No multiple UUID possible for the host, so just checking if
1755 	 * there is an entry will suffice
1756 	 */
1757 	if (xa_load(&drv_info->partition_info, drv_info->vm_id))
1758 		return 0;
1759 
1760 	/* Allocate for the host */
1761 	ret = ffa_setup_host_partition(drv_info->vm_id);
1762 	if (ret)
1763 		ffa_partitions_cleanup();
1764 
1765 	return ret;
1766 }
1767 
1768 /* FFA FEATURE IDs */
1769 #define FFA_FEAT_NOTIFICATION_PENDING_INT	(1)
1770 #define FFA_FEAT_SCHEDULE_RECEIVER_INT		(2)
1771 #define FFA_FEAT_MANAGED_EXIT_INT		(3)
1772 
1773 static irqreturn_t ffa_sched_recv_irq_handler(int irq, void *irq_data)
1774 {
1775 	struct ffa_pcpu_irq *pcpu = irq_data;
1776 	struct ffa_drv_info *info = pcpu->info;
1777 
1778 	queue_work(info->notif_pcpu_wq, &info->sched_recv_irq_work);
1779 
1780 	return IRQ_HANDLED;
1781 }
1782 
1783 static irqreturn_t notif_pend_irq_handler(int irq, void *irq_data)
1784 {
1785 	struct ffa_pcpu_irq *pcpu = irq_data;
1786 	struct ffa_drv_info *info = pcpu->info;
1787 
1788 	queue_work_on(smp_processor_id(), info->notif_pcpu_wq,
1789 		      &info->notif_pcpu_work);
1790 
1791 	return IRQ_HANDLED;
1792 }
1793 
1794 static void ffa_sched_recv_irq_work_fn(struct work_struct *work)
1795 {
1796 	ffa_notification_info_get();
1797 }
1798 
1799 static int ffa_irq_map(u32 id)
1800 {
1801 	char *err_str;
1802 	int ret, irq, intid;
1803 
1804 	if (id == FFA_FEAT_NOTIFICATION_PENDING_INT)
1805 		err_str = "Notification Pending Interrupt";
1806 	else if (id == FFA_FEAT_SCHEDULE_RECEIVER_INT)
1807 		err_str = "Schedule Receiver Interrupt";
1808 	else
1809 		err_str = "Unknown ID";
1810 
1811 	/* The returned intid is assumed to be SGI donated to NS world */
1812 	ret = ffa_features(id, 0, &intid, NULL);
1813 	if (ret < 0) {
1814 		if (ret != -EOPNOTSUPP)
1815 			pr_err("Failed to retrieve FF-A %s %u\n", err_str, id);
1816 		return ret;
1817 	}
1818 
1819 	if (acpi_disabled) {
1820 		struct of_phandle_args oirq = {};
1821 		struct device_node *gic;
1822 
1823 		/* Only GICv3 supported currently with the device tree */
1824 		gic = of_find_compatible_node(NULL, NULL, "arm,gic-v3");
1825 		if (!gic)
1826 			return -ENXIO;
1827 
1828 		oirq.np = gic;
1829 		oirq.args_count = 1;
1830 		oirq.args[0] = intid;
1831 		irq = irq_create_of_mapping(&oirq);
1832 		of_node_put(gic);
1833 #ifdef CONFIG_ACPI
1834 	} else {
1835 		irq = acpi_register_gsi(NULL, intid, ACPI_EDGE_SENSITIVE,
1836 					ACPI_ACTIVE_HIGH);
1837 #endif
1838 	}
1839 
1840 	if (irq <= 0) {
1841 		pr_err("Failed to create IRQ mapping!\n");
1842 		return -ENODATA;
1843 	}
1844 
1845 	return irq;
1846 }
1847 
1848 static void ffa_irq_unmap(unsigned int irq)
1849 {
1850 	if (!irq)
1851 		return;
1852 	irq_dispose_mapping(irq);
1853 }
1854 
1855 static int ffa_cpuhp_pcpu_irq_enable(unsigned int cpu)
1856 {
1857 	if (drv_info->sched_recv_irq)
1858 		enable_percpu_irq(drv_info->sched_recv_irq, IRQ_TYPE_NONE);
1859 	if (drv_info->notif_pend_irq)
1860 		enable_percpu_irq(drv_info->notif_pend_irq, IRQ_TYPE_NONE);
1861 	return 0;
1862 }
1863 
1864 static int ffa_cpuhp_pcpu_irq_disable(unsigned int cpu)
1865 {
1866 	if (drv_info->sched_recv_irq)
1867 		disable_percpu_irq(drv_info->sched_recv_irq);
1868 	if (drv_info->notif_pend_irq)
1869 		disable_percpu_irq(drv_info->notif_pend_irq);
1870 	return 0;
1871 }
1872 
1873 static void ffa_uninit_pcpu_irq(void)
1874 {
1875 	if (drv_info->cpuhp_state) {
1876 		cpuhp_remove_state(drv_info->cpuhp_state);
1877 		drv_info->cpuhp_state = 0;
1878 	}
1879 
1880 	if (drv_info->notif_pcpu_wq) {
1881 		destroy_workqueue(drv_info->notif_pcpu_wq);
1882 		drv_info->notif_pcpu_wq = NULL;
1883 	}
1884 
1885 	if (drv_info->sched_recv_irq)
1886 		free_percpu_irq(drv_info->sched_recv_irq, drv_info->irq_pcpu);
1887 
1888 	if (drv_info->notif_pend_irq)
1889 		free_percpu_irq(drv_info->notif_pend_irq, drv_info->irq_pcpu);
1890 
1891 	if (drv_info->irq_pcpu) {
1892 		free_percpu(drv_info->irq_pcpu);
1893 		drv_info->irq_pcpu = NULL;
1894 	}
1895 }
1896 
1897 static int ffa_init_pcpu_irq(void)
1898 {
1899 	struct ffa_pcpu_irq __percpu *irq_pcpu;
1900 	int ret, cpu;
1901 
1902 	irq_pcpu = alloc_percpu(struct ffa_pcpu_irq);
1903 	if (!irq_pcpu)
1904 		return -ENOMEM;
1905 
1906 	for_each_present_cpu(cpu)
1907 		per_cpu_ptr(irq_pcpu, cpu)->info = drv_info;
1908 
1909 	drv_info->irq_pcpu = irq_pcpu;
1910 
1911 	if (drv_info->sched_recv_irq) {
1912 		ret = request_percpu_irq(drv_info->sched_recv_irq,
1913 					 ffa_sched_recv_irq_handler,
1914 					 "ARM-FFA-SRI", irq_pcpu);
1915 		if (ret) {
1916 			pr_err("Error registering percpu SRI nIRQ %d : %d\n",
1917 			       drv_info->sched_recv_irq, ret);
1918 			drv_info->sched_recv_irq = 0;
1919 			return ret;
1920 		}
1921 	}
1922 
1923 	if (drv_info->notif_pend_irq) {
1924 		ret = request_percpu_irq(drv_info->notif_pend_irq,
1925 					 notif_pend_irq_handler,
1926 					 "ARM-FFA-NPI", irq_pcpu);
1927 		if (ret) {
1928 			pr_err("Error registering percpu NPI nIRQ %d : %d\n",
1929 			       drv_info->notif_pend_irq, ret);
1930 			drv_info->notif_pend_irq = 0;
1931 			return ret;
1932 		}
1933 	}
1934 
1935 	INIT_WORK(&drv_info->sched_recv_irq_work, ffa_sched_recv_irq_work_fn);
1936 	INIT_WORK(&drv_info->notif_pcpu_work, notif_pcpu_irq_work_fn);
1937 	drv_info->notif_pcpu_wq = create_workqueue("ffa_pcpu_irq_notification");
1938 	if (!drv_info->notif_pcpu_wq)
1939 		return -EINVAL;
1940 
1941 	ret = cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "ffa/pcpu-irq:starting",
1942 				ffa_cpuhp_pcpu_irq_enable,
1943 				ffa_cpuhp_pcpu_irq_disable);
1944 
1945 	if (ret < 0)
1946 		return ret;
1947 
1948 	drv_info->cpuhp_state = ret;
1949 	return 0;
1950 }
1951 
1952 static void ffa_notifications_cleanup(void)
1953 {
1954 	ffa_uninit_pcpu_irq();
1955 	ffa_irq_unmap(drv_info->sched_recv_irq);
1956 	drv_info->sched_recv_irq = 0;
1957 	ffa_irq_unmap(drv_info->notif_pend_irq);
1958 	drv_info->notif_pend_irq = 0;
1959 
1960 	if (drv_info->bitmap_created) {
1961 		ffa_notification_bitmap_destroy();
1962 		drv_info->bitmap_created = false;
1963 	}
1964 	drv_info->notif_enabled = false;
1965 }
1966 
1967 static void ffa_notifications_setup(void)
1968 {
1969 	int ret;
1970 
1971 	ret = ffa_features(FFA_NOTIFICATION_BITMAP_CREATE, 0, NULL, NULL);
1972 	if (!ret) {
1973 		ret = ffa_notification_bitmap_create();
1974 		if (ret) {
1975 			pr_err("Notification bitmap create error %d\n", ret);
1976 			return;
1977 		}
1978 
1979 		drv_info->bitmap_created = true;
1980 	}
1981 
1982 	ret = ffa_irq_map(FFA_FEAT_SCHEDULE_RECEIVER_INT);
1983 	if (ret > 0)
1984 		drv_info->sched_recv_irq = ret;
1985 
1986 	ret = ffa_irq_map(FFA_FEAT_NOTIFICATION_PENDING_INT);
1987 	if (ret > 0)
1988 		drv_info->notif_pend_irq = ret;
1989 
1990 	if (!drv_info->sched_recv_irq && !drv_info->notif_pend_irq)
1991 		goto cleanup;
1992 
1993 	ret = ffa_init_pcpu_irq();
1994 	if (ret)
1995 		goto cleanup;
1996 
1997 	hash_init(drv_info->notifier_hash);
1998 	rwlock_init(&drv_info->notify_lock);
1999 
2000 	drv_info->notif_enabled = true;
2001 	return;
2002 cleanup:
2003 	pr_info("Notification setup failed %d, not enabled\n", ret);
2004 	ffa_notifications_cleanup();
2005 }
2006 
2007 static int __init ffa_init(void)
2008 {
2009 	int ret;
2010 	u32 buf_sz;
2011 	size_t rxtx_bufsz = SZ_4K;
2012 
2013 	ret = ffa_transport_init(&invoke_ffa_fn);
2014 	if (ret)
2015 		return ret;
2016 
2017 	drv_info = kzalloc(sizeof(*drv_info), GFP_KERNEL);
2018 	if (!drv_info)
2019 		return -ENOMEM;
2020 
2021 	ret = ffa_version_check(&drv_info->version);
2022 	if (ret)
2023 		goto free_drv_info;
2024 
2025 	if (ffa_id_get(&drv_info->vm_id)) {
2026 		pr_err("failed to obtain VM id for self\n");
2027 		ret = -ENODEV;
2028 		goto free_drv_info;
2029 	}
2030 
2031 	ret = ffa_features(FFA_FN_NATIVE(RXTX_MAP), 0, &buf_sz, NULL);
2032 	if (!ret) {
2033 		if (RXTX_MAP_MIN_BUFSZ(buf_sz) == 1)
2034 			rxtx_bufsz = SZ_64K;
2035 		else if (RXTX_MAP_MIN_BUFSZ(buf_sz) == 2)
2036 			rxtx_bufsz = SZ_16K;
2037 		else
2038 			rxtx_bufsz = SZ_4K;
2039 	}
2040 
2041 	drv_info->rxtx_bufsz = rxtx_bufsz;
2042 	drv_info->rx_buffer = alloc_pages_exact(rxtx_bufsz, GFP_KERNEL);
2043 	if (!drv_info->rx_buffer) {
2044 		ret = -ENOMEM;
2045 		goto free_pages;
2046 	}
2047 
2048 	drv_info->tx_buffer = alloc_pages_exact(rxtx_bufsz, GFP_KERNEL);
2049 	if (!drv_info->tx_buffer) {
2050 		ret = -ENOMEM;
2051 		goto free_pages;
2052 	}
2053 
2054 	ret = ffa_rxtx_map(virt_to_phys(drv_info->tx_buffer),
2055 			   virt_to_phys(drv_info->rx_buffer),
2056 			   rxtx_bufsz / FFA_PAGE_SIZE);
2057 	if (ret) {
2058 		pr_err("failed to register FFA RxTx buffers\n");
2059 		goto free_pages;
2060 	}
2061 
2062 	mutex_init(&drv_info->rx_lock);
2063 	mutex_init(&drv_info->tx_lock);
2064 
2065 	ffa_drvinfo_flags_init();
2066 
2067 	ffa_notifications_setup();
2068 
2069 	ret = ffa_setup_partitions();
2070 	if (!ret)
2071 		return ret;
2072 
2073 	pr_err("failed to setup partitions\n");
2074 	ffa_notifications_cleanup();
2075 	ffa_rxtx_unmap(drv_info->vm_id);
2076 free_pages:
2077 	if (drv_info->tx_buffer)
2078 		free_pages_exact(drv_info->tx_buffer, rxtx_bufsz);
2079 	free_pages_exact(drv_info->rx_buffer, rxtx_bufsz);
2080 free_drv_info:
2081 	kfree(drv_info);
2082 	return ret;
2083 }
2084 rootfs_initcall(ffa_init);
2085 
2086 static void __exit ffa_exit(void)
2087 {
2088 	ffa_notifications_cleanup();
2089 	ffa_partitions_cleanup();
2090 	ffa_rxtx_unmap(drv_info->vm_id);
2091 	free_pages_exact(drv_info->tx_buffer, drv_info->rxtx_bufsz);
2092 	free_pages_exact(drv_info->rx_buffer, drv_info->rxtx_bufsz);
2093 	kfree(drv_info);
2094 }
2095 module_exit(ffa_exit);
2096 
2097 MODULE_ALIAS("arm-ffa");
2098 MODULE_AUTHOR("Sudeep Holla <sudeep.holla@arm.com>");
2099 MODULE_DESCRIPTION("Arm FF-A interface driver");
2100 MODULE_LICENSE("GPL v2");
2101