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