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