xref: /linux/drivers/firmware/stratix10-svc.c (revision 8bec01c80e798eca1ae7863cf29bc6befd759db7)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2017-2018, Intel Corporation
4  * Copyright (C) 2025, Altera Corporation
5  */
6 
7 #include <linux/atomic.h>
8 #include <linux/completion.h>
9 #include <linux/delay.h>
10 #include <linux/genalloc.h>
11 #include <linux/hashtable.h>
12 #include <linux/idr.h>
13 #include <linux/io.h>
14 #include <linux/kfifo.h>
15 #include <linux/kthread.h>
16 #include <linux/module.h>
17 #include <linux/mutex.h>
18 #include <linux/of.h>
19 #include <linux/of_platform.h>
20 #include <linux/platform_device.h>
21 #include <linux/slab.h>
22 #include <linux/spinlock.h>
23 #include <linux/firmware/intel/stratix10-smc.h>
24 #include <linux/firmware/intel/stratix10-svc-client.h>
25 #include <linux/types.h>
26 
27 /**
28  * SVC_NUM_DATA_IN_FIFO - number of struct stratix10_svc_data in the FIFO
29  *
30  * SVC_NUM_CHANNEL - number of channel supported by service layer driver
31  *
32  * FPGA_CONFIG_DATA_CLAIM_TIMEOUT_MS - claim back the submitted buffer(s)
33  * from the secure world for FPGA manager to reuse, or to free the buffer(s)
34  * when all bit-stream data had be send.
35  *
36  * FPGA_CONFIG_STATUS_TIMEOUT_SEC - poll the FPGA configuration status,
37  * service layer will return error to FPGA manager when timeout occurs,
38  * timeout is set to 30 seconds (30 * 1000) at Intel Stratix10 SoC.
39  */
40 #define SVC_NUM_DATA_IN_FIFO			8
41 #define SVC_NUM_CHANNEL				4
42 #define FPGA_CONFIG_DATA_CLAIM_TIMEOUT_MS	2000
43 #define FPGA_CONFIG_STATUS_TIMEOUT_SEC		30
44 #define BYTE_TO_WORD_SIZE              4
45 
46 /* stratix10 service layer clients */
47 #define STRATIX10_RSU				"stratix10-rsu"
48 
49 /* Maximum number of SDM client IDs. */
50 #define MAX_SDM_CLIENT_IDS			16
51 /* Client ID for SIP Service Version 1. */
52 #define SIP_SVC_V1_CLIENT_ID			0x1
53 /* Maximum number of SDM job IDs. */
54 #define MAX_SDM_JOB_IDS				16
55 /* Number of bits used for asynchronous transaction hashing. */
56 #define ASYNC_TRX_HASH_BITS			3
57 /*
58  * Total number of transaction IDs, which is a combination of
59  * client ID and job ID.
60  */
61 #define TOTAL_TRANSACTION_IDS \
62 	(MAX_SDM_CLIENT_IDS * MAX_SDM_JOB_IDS)
63 
64 /* Minimum major version of the ATF for Asynchronous transactions. */
65 #define ASYNC_ATF_MINIMUM_MAJOR_VERSION		0x3
66 /* Minimum minor version of the ATF for Asynchronous transactions.*/
67 #define ASYNC_ATF_MINIMUM_MINOR_VERSION		0x0
68 
69 /* Job ID field in the transaction ID */
70 #define STRATIX10_JOB_FIELD			GENMASK(3, 0)
71 /* Client ID field in the transaction ID */
72 #define STRATIX10_CLIENT_FIELD			GENMASK(7, 4)
73 /* Transaction ID mask for Stratix10 service layer */
74 #define STRATIX10_TRANS_ID_FIELD		GENMASK(7, 0)
75 
76 /* Macro to extract the job ID from a transaction ID. */
77 #define STRATIX10_GET_JOBID(transaction_id) \
78 	(FIELD_GET(STRATIX10_JOB_FIELD, transaction_id))
79 /* Macro to set the job ID in a transaction ID. */
80 #define STRATIX10_SET_JOBID(jobid) \
81 	(FIELD_PREP(STRATIX10_JOB_FIELD, jobid))
82 /* Macro to set the client ID in a transaction ID. */
83 #define STRATIX10_SET_CLIENTID(clientid) \
84 	(FIELD_PREP(STRATIX10_CLIENT_FIELD, clientid))
85 /* Macro to set a transaction ID using a client ID and a job ID. */
86 #define STRATIX10_SET_TRANSACTIONID(clientid, jobid) \
87 	(STRATIX10_SET_CLIENTID(clientid) | STRATIX10_SET_JOBID(jobid))
88 /* Macro to set a transaction ID for SIP SMC Async transactions */
89 #define STRATIX10_SIP_SMC_SET_TRANSACTIONID_X1(transaction_id) \
90 	(FIELD_PREP(STRATIX10_TRANS_ID_FIELD, transaction_id))
91 
92 /* 10-bit mask for extracting the SDM status code */
93 #define STRATIX10_SDM_STATUS_MASK GENMASK(9, 0)
94 /* Macro to get the SDM mailbox error status */
95 #define STRATIX10_GET_SDM_STATUS_CODE(status) \
96 	(FIELD_GET(STRATIX10_SDM_STATUS_MASK, status))
97 
98 typedef void (svc_invoke_fn)(unsigned long, unsigned long, unsigned long,
99 			     unsigned long, unsigned long, unsigned long,
100 			     unsigned long, unsigned long,
101 			     struct arm_smccc_res *);
102 struct stratix10_svc_chan;
103 
104 /**
105  * struct stratix10_svc - svc private data
106  * @stratix10_svc_rsu: pointer to stratix10 RSU device
107  */
108 struct stratix10_svc {
109 	struct platform_device *stratix10_svc_rsu;
110 };
111 
112 /**
113  * struct stratix10_svc_sh_memory - service shared memory structure
114  * @sync_complete: state for a completion
115  * @addr: physical address of shared memory block
116  * @size: size of shared memory block
117  * @invoke_fn: service clients to handle secure monitor or hypervisor calls
118  *
119  * This struct is used to save physical address and size of shared memory
120  * block. The shared memory blocked is allocated by secure monitor software
121  * at secure world.
122  *
123  * Service layer driver uses the physical address and size to create a memory
124  * pool, then allocates data buffer from that memory pool for service client.
125  */
126 struct stratix10_svc_sh_memory {
127 	struct completion sync_complete;
128 	unsigned long addr;
129 	unsigned long size;
130 	svc_invoke_fn *invoke_fn;
131 };
132 
133 /**
134  * struct stratix10_svc_data_mem - service memory structure
135  * @vaddr: virtual address
136  * @paddr: physical address
137  * @size: size of memory
138  * @node: link list head node
139  *
140  * This struct is used in a list that keeps track of buffers which have
141  * been allocated or freed from the memory pool. Service layer driver also
142  * uses this struct to transfer physical address to virtual address.
143  */
144 struct stratix10_svc_data_mem {
145 	void *vaddr;
146 	phys_addr_t paddr;
147 	size_t size;
148 	struct list_head node;
149 };
150 
151 /**
152  * struct stratix10_svc_data - service data structure
153  * @chan: service channel
154  * @paddr: physical address of to be processed payload
155  * @size: to be processed playload size
156  * @paddr_output: physical address of processed payload
157  * @size_output: processed payload size
158  * @command: service command requested by client
159  * @flag: configuration type (full or partial)
160  * @arg: args to be passed via registers and not physically mapped buffers
161  *
162  * This struct is used in service FIFO for inter-process communication.
163  */
164 struct stratix10_svc_data {
165 	struct stratix10_svc_chan *chan;
166 	phys_addr_t paddr;
167 	size_t size;
168 	phys_addr_t paddr_output;
169 	size_t size_output;
170 	u32 command;
171 	u32 flag;
172 	u64 arg[3];
173 };
174 
175 /**
176  * struct stratix10_svc_async_handler - Asynchronous handler for Stratix10
177  *                                      service layer
178  * @transaction_id: Unique identifier for the transaction
179  * @achan: Pointer to the asynchronous channel structure
180  * @cb_arg: Argument to be passed to the callback function
181  * @cb: Callback function to be called upon completion
182  * @msg: Pointer to the client message structure
183  * @next: Node in the hash list
184  * @res: Response structure to store result from the secure firmware
185  *
186  * This structure is used to handle asynchronous transactions in the
187  * Stratix10 service layer. It maintains the necessary information
188  * for processing and completing asynchronous requests.
189  */
190 
191 struct stratix10_svc_async_handler {
192 	u8 transaction_id;
193 	struct stratix10_async_chan *achan;
194 	void *cb_arg;
195 	async_callback_t cb;
196 	struct stratix10_svc_client_msg *msg;
197 	struct hlist_node next;
198 	struct arm_smccc_1_2_regs res;
199 };
200 
201 /**
202  * struct stratix10_async_chan - Structure representing an asynchronous channel
203  * @async_client_id: Unique client identifier for the asynchronous operation
204  * @job_id_pool: Pointer to the job ID pool associated with this channel
205  */
206 
207 struct stratix10_async_chan {
208 	unsigned long async_client_id;
209 	struct ida job_id_pool;
210 };
211 
212 /**
213  * struct stratix10_async_ctrl - Control structure for Stratix10
214  *                               asynchronous operations
215  * @supported: Flag indicating whether the system supports async operations
216  * @initialized: Flag indicating whether the control structure has
217  *               been initialized
218  * @invoke_fn: Function pointer for invoking Stratix10 service calls
219  *             to EL3 secure firmware
220  * @async_id_pool: Pointer to the ID pool used for asynchronous
221  *                 operations
222  * @common_achan_refcount: Atomic reference count for the common
223  *                         asynchronous channel usage
224  * @common_async_chan: Pointer to the common asynchronous channel
225  *                     structure
226  * @trx_list_lock: Spinlock for protecting the transaction list
227  *                     operations
228  * @trx_list: Hash table for managing asynchronous transactions
229  */
230 
231 struct stratix10_async_ctrl {
232 	bool supported;
233 	bool initialized;
234 	void (*invoke_fn)(struct stratix10_async_ctrl *actrl,
235 			  const struct arm_smccc_1_2_regs *args,
236 			  struct arm_smccc_1_2_regs *res);
237 	struct ida async_id_pool;
238 	atomic_t common_achan_refcount;
239 	struct stratix10_async_chan *common_async_chan;
240 	/* spinlock to protect trx_list hash table */
241 	spinlock_t trx_list_lock;
242 	DECLARE_HASHTABLE(trx_list, ASYNC_TRX_HASH_BITS);
243 };
244 
245 /**
246  * struct stratix10_svc_chan - service communication channel
247  * @ctrl: pointer to service controller which is the provider of this channel
248  * @scl: pointer to service client which owns the channel
249  * @name: service client name associated with the channel
250  * @task: pointer to the thread task which handles SMC or HVC call
251  * @svc_fifo: a queue for storing service message data (separate fifo for every channel)
252  * @svc_fifo_lock: protect access to service message data queue (locking pending fifo)
253  * @lock: protect access to the channel
254  * @async_chan: reference to asynchronous channel object for this channel
255  *
256  * This struct is used by service client to communicate with service layer.
257  * Each service client has its own channel created by service controller.
258  */
259 struct stratix10_svc_chan {
260 	struct stratix10_svc_controller *ctrl;
261 	struct stratix10_svc_client *scl;
262 	char *name;
263 	struct task_struct *task;
264 	struct kfifo svc_fifo;
265 	spinlock_t svc_fifo_lock;
266 	spinlock_t lock;
267 	struct stratix10_async_chan *async_chan;
268 };
269 
270 /**
271  * struct stratix10_svc_controller - service controller
272  * @dev: device
273  * @num_chans: number of channels in 'chans' array
274  * @num_active_client: number of active service client
275  * @node: list management
276  * @genpool: memory pool pointing to the memory region
277  * @complete_status: state for completion
278  * @invoke_fn: function to issue secure monitor call or hypervisor call
279  * @svc: manages the list of client svc drivers
280  * @sdm_lock: only allows a single command single response to SDM
281  * @actrl: async control structure
282  * @chans: array of service channels
283  *
284  * This struct is used to create communication channels for service clients, to
285  * handle secure monitor or hypervisor call.
286  */
287 struct stratix10_svc_controller {
288 	struct device *dev;
289 	int num_chans;
290 	int num_active_client;
291 	struct list_head node;
292 	struct gen_pool *genpool;
293 	struct completion complete_status;
294 	svc_invoke_fn *invoke_fn;
295 	struct stratix10_svc *svc;
296 	struct mutex sdm_lock;
297 	struct stratix10_async_ctrl actrl;
298 	struct stratix10_svc_chan chans[] __counted_by(num_chans);
299 };
300 
301 static LIST_HEAD(svc_ctrl);
302 static LIST_HEAD(svc_data_mem);
303 
304 /*
305  * svc_mem_lock protects access to the svc_data_mem list for
306  * concurrent multi-client operations
307  */
308 static DEFINE_MUTEX(svc_mem_lock);
309 
310 /**
311  * svc_pa_to_va() - translate physical address to virtual address
312  * @addr: to be translated physical address
313  *
314  * Return: valid virtual address or NULL if the provided physical
315  * address doesn't exist.
316  */
317 static void *svc_pa_to_va(unsigned long addr)
318 {
319 	struct stratix10_svc_data_mem *pmem;
320 
321 	pr_debug("claim back P-addr=0x%016x\n", (unsigned int)addr);
322 	guard(mutex)(&svc_mem_lock);
323 	list_for_each_entry(pmem, &svc_data_mem, node)
324 		if (pmem->paddr == addr)
325 			return pmem->vaddr;
326 
327 	/* physical address is not found */
328 	return NULL;
329 }
330 
331 /**
332  * svc_thread_cmd_data_claim() - claim back buffer from the secure world
333  * @ctrl: pointer to service layer controller
334  * @p_data: pointer to service data structure
335  * @cb_data: pointer to callback data structure to service client
336  *
337  * Claim back the submitted buffers from the secure world and pass buffer
338  * back to service client (FPGA manager, etc) for reuse.
339  */
340 static void svc_thread_cmd_data_claim(struct stratix10_svc_controller *ctrl,
341 				      struct stratix10_svc_data *p_data,
342 				      struct stratix10_svc_cb_data *cb_data)
343 {
344 	struct arm_smccc_res res;
345 	unsigned long timeout;
346 
347 	reinit_completion(&ctrl->complete_status);
348 	timeout = msecs_to_jiffies(FPGA_CONFIG_DATA_CLAIM_TIMEOUT_MS);
349 
350 	pr_debug("%s: claim back the submitted buffer\n", __func__);
351 	do {
352 		ctrl->invoke_fn(INTEL_SIP_SMC_FPGA_CONFIG_COMPLETED_WRITE,
353 				0, 0, 0, 0, 0, 0, 0, &res);
354 
355 		if (res.a0 == INTEL_SIP_SMC_STATUS_OK) {
356 			if (!res.a1) {
357 				complete(&ctrl->complete_status);
358 				break;
359 			}
360 			cb_data->status = BIT(SVC_STATUS_BUFFER_DONE);
361 			cb_data->kaddr1 = svc_pa_to_va(res.a1);
362 			cb_data->kaddr2 = (res.a2) ?
363 					  svc_pa_to_va(res.a2) : NULL;
364 			cb_data->kaddr3 = (res.a3) ?
365 					  svc_pa_to_va(res.a3) : NULL;
366 			p_data->chan->scl->receive_cb(p_data->chan->scl,
367 						      cb_data);
368 		} else {
369 			pr_debug("%s: secure world busy, polling again\n",
370 				 __func__);
371 		}
372 	} while (res.a0 == INTEL_SIP_SMC_STATUS_OK ||
373 		 res.a0 == INTEL_SIP_SMC_STATUS_BUSY ||
374 		 wait_for_completion_timeout(&ctrl->complete_status, timeout));
375 }
376 
377 /**
378  * svc_thread_cmd_config_status() - check configuration status
379  * @ctrl: pointer to service layer controller
380  * @p_data: pointer to service data structure
381  * @cb_data: pointer to callback data structure to service client
382  *
383  * Check whether the secure firmware at secure world has finished the FPGA
384  * configuration, and then inform FPGA manager the configuration status.
385  */
386 static void svc_thread_cmd_config_status(struct stratix10_svc_controller *ctrl,
387 					 struct stratix10_svc_data *p_data,
388 					 struct stratix10_svc_cb_data *cb_data)
389 {
390 	struct arm_smccc_res res;
391 	int count_in_sec;
392 	unsigned long a0, a1, a2;
393 
394 	cb_data->kaddr1 = NULL;
395 	cb_data->kaddr2 = NULL;
396 	cb_data->kaddr3 = NULL;
397 	cb_data->status = BIT(SVC_STATUS_ERROR);
398 
399 	pr_debug("%s: polling config status\n", __func__);
400 
401 	a0 = INTEL_SIP_SMC_FPGA_CONFIG_ISDONE;
402 	a1 = (unsigned long)p_data->paddr;
403 	a2 = (unsigned long)p_data->size;
404 
405 	if (p_data->command == COMMAND_POLL_SERVICE_STATUS)
406 		a0 = INTEL_SIP_SMC_SERVICE_COMPLETED;
407 
408 	count_in_sec = FPGA_CONFIG_STATUS_TIMEOUT_SEC;
409 	while (count_in_sec) {
410 		ctrl->invoke_fn(a0, a1, a2, 0, 0, 0, 0, 0, &res);
411 		if ((res.a0 == INTEL_SIP_SMC_STATUS_OK) ||
412 		    (res.a0 == INTEL_SIP_SMC_STATUS_ERROR) ||
413 		    (res.a0 == INTEL_SIP_SMC_STATUS_REJECTED))
414 			break;
415 
416 		/*
417 		 * request is still in progress, wait one second then
418 		 * poll again
419 		 */
420 		msleep(1000);
421 		count_in_sec--;
422 	}
423 
424 	if (!count_in_sec) {
425 		pr_err("%s: poll status timeout\n", __func__);
426 		cb_data->status = BIT(SVC_STATUS_BUSY);
427 	} else if (res.a0 == INTEL_SIP_SMC_STATUS_OK) {
428 		cb_data->status = BIT(SVC_STATUS_COMPLETED);
429 		cb_data->kaddr2 = (res.a2) ?
430 				  svc_pa_to_va(res.a2) : NULL;
431 		cb_data->kaddr3 = (res.a3) ? &res.a3 : NULL;
432 	} else {
433 		pr_err("%s: poll status error\n", __func__);
434 		cb_data->kaddr1 = &res.a1;
435 		cb_data->kaddr2 = (res.a2) ?
436 				  svc_pa_to_va(res.a2) : NULL;
437 		cb_data->kaddr3 = (res.a3) ? &res.a3 : NULL;
438 		cb_data->status = BIT(SVC_STATUS_ERROR);
439 	}
440 
441 	p_data->chan->scl->receive_cb(p_data->chan->scl, cb_data);
442 }
443 
444 /**
445  * svc_thread_recv_status_ok() - handle the successful status
446  * @p_data: pointer to service data structure
447  * @cb_data: pointer to callback data structure to service client
448  * @res: result from SMC or HVC call
449  *
450  * Send back the correspond status to the service clients.
451  */
452 static void svc_thread_recv_status_ok(struct stratix10_svc_data *p_data,
453 				      struct stratix10_svc_cb_data *cb_data,
454 				      struct arm_smccc_res res)
455 {
456 	cb_data->kaddr1 = NULL;
457 	cb_data->kaddr2 = NULL;
458 	cb_data->kaddr3 = NULL;
459 
460 	switch (p_data->command) {
461 	case COMMAND_RECONFIG:
462 	case COMMAND_RSU_UPDATE:
463 	case COMMAND_RSU_NOTIFY:
464 	case COMMAND_FCS_REQUEST_SERVICE:
465 	case COMMAND_FCS_SEND_CERTIFICATE:
466 	case COMMAND_FCS_DATA_ENCRYPTION:
467 	case COMMAND_FCS_DATA_DECRYPTION:
468 	case COMMAND_FCS_GET_PROVISION_DATA:
469 		cb_data->status = BIT(SVC_STATUS_OK);
470 		break;
471 	case COMMAND_RECONFIG_DATA_SUBMIT:
472 		cb_data->status = BIT(SVC_STATUS_BUFFER_SUBMITTED);
473 		break;
474 	case COMMAND_RECONFIG_STATUS:
475 		cb_data->status = BIT(SVC_STATUS_COMPLETED);
476 		break;
477 	case COMMAND_RSU_RETRY:
478 	case COMMAND_RSU_MAX_RETRY:
479 	case COMMAND_RSU_DCMF_STATUS:
480 	case COMMAND_FIRMWARE_VERSION:
481 	case COMMAND_HWMON_READTEMP:
482 	case COMMAND_HWMON_READVOLT:
483 		cb_data->status = BIT(SVC_STATUS_OK);
484 		cb_data->kaddr1 = &res.a1;
485 		break;
486 	case COMMAND_SMC_SVC_VERSION:
487 		cb_data->status = BIT(SVC_STATUS_OK);
488 		cb_data->kaddr1 = &res.a1;
489 		cb_data->kaddr2 = &res.a2;
490 		break;
491 	case COMMAND_SMC_ATF_BUILD_VER:
492 		cb_data->status = BIT(SVC_STATUS_OK);
493 		cb_data->kaddr1 = &res.a1;
494 		cb_data->kaddr2 = &res.a2;
495 		cb_data->kaddr3 = &res.a3;
496 		break;
497 	case COMMAND_RSU_DCMF_VERSION:
498 		cb_data->status = BIT(SVC_STATUS_OK);
499 		cb_data->kaddr1 = &res.a1;
500 		cb_data->kaddr2 = &res.a2;
501 		break;
502 	case COMMAND_FCS_RANDOM_NUMBER_GEN:
503 	case COMMAND_POLL_SERVICE_STATUS:
504 		cb_data->status = BIT(SVC_STATUS_OK);
505 		cb_data->kaddr1 = &res.a1;
506 		cb_data->kaddr2 = svc_pa_to_va(res.a2);
507 		cb_data->kaddr3 = &res.a3;
508 		break;
509 	case COMMAND_MBOX_SEND_CMD:
510 		cb_data->status = BIT(SVC_STATUS_OK);
511 		cb_data->kaddr1 = &res.a1;
512 		/* SDM return size in u8. Convert size to u32 word */
513 		res.a2 = res.a2 * BYTE_TO_WORD_SIZE;
514 		cb_data->kaddr2 = &res.a2;
515 		break;
516 	default:
517 		pr_warn("it shouldn't happen\n");
518 		break;
519 	}
520 
521 	pr_debug("%s: call receive_cb\n", __func__);
522 	p_data->chan->scl->receive_cb(p_data->chan->scl, cb_data);
523 }
524 
525 /**
526  * svc_normal_to_secure_thread() - the function to run in the kthread
527  * @data: data pointer for kthread function
528  *
529  * Service layer driver creates stratix10_svc_smc_hvc_call kthread on CPU
530  * node 0, its function stratix10_svc_secure_call_thread is used to handle
531  * SMC or HVC calls between kernel driver and secure monitor software.
532  *
533  * Return: 0 for success or -ENOMEM on error.
534  */
535 static int svc_normal_to_secure_thread(void *data)
536 {
537 	struct stratix10_svc_chan *chan = (struct stratix10_svc_chan *)data;
538 	struct stratix10_svc_controller *ctrl = chan->ctrl;
539 	struct stratix10_svc_data *pdata = NULL;
540 	struct stratix10_svc_cb_data *cbdata = NULL;
541 	struct arm_smccc_res res;
542 	unsigned long a0, a1, a2, a3, a4, a5, a6, a7;
543 	int ret_fifo = 0;
544 
545 	pdata = kmalloc_obj(*pdata);
546 	if (!pdata)
547 		return -ENOMEM;
548 
549 	cbdata = kmalloc_obj(*cbdata);
550 	if (!cbdata) {
551 		kfree(pdata);
552 		return -ENOMEM;
553 	}
554 
555 	/* default set, to remove build warning */
556 	a0 = INTEL_SIP_SMC_FPGA_CONFIG_LOOPBACK;
557 	a1 = 0;
558 	a2 = 0;
559 	a3 = 0;
560 	a4 = 0;
561 	a5 = 0;
562 	a6 = 0;
563 	a7 = 0;
564 
565 	pr_debug("%s: %s: Thread is running!\n", __func__, chan->name);
566 
567 	while (!kthread_should_stop()) {
568 		ret_fifo = kfifo_out_spinlocked(&chan->svc_fifo,
569 						pdata, sizeof(*pdata),
570 						&chan->svc_fifo_lock);
571 
572 		if (!ret_fifo)
573 			continue;
574 
575 		pr_debug("get from FIFO pa=0x%016x, command=%u, size=%u\n",
576 			 (unsigned int)pdata->paddr, pdata->command,
577 			 (unsigned int)pdata->size);
578 
579 		/* SDM can only process one command at a time */
580 		pr_debug("%s: %s: Thread is waiting for mutex!\n",
581 			 __func__, chan->name);
582 		if (mutex_lock_interruptible(&ctrl->sdm_lock)) {
583 			/* item already dequeued; notify client to unblock it */
584 			cbdata->status = BIT(SVC_STATUS_ERROR);
585 			cbdata->kaddr1 = NULL;
586 			cbdata->kaddr2 = NULL;
587 			cbdata->kaddr3 = NULL;
588 			if (pdata->chan->scl)
589 				pdata->chan->scl->receive_cb(pdata->chan->scl,
590 							     cbdata);
591 			break;
592 		}
593 
594 		switch (pdata->command) {
595 		case COMMAND_RECONFIG_DATA_CLAIM:
596 			svc_thread_cmd_data_claim(ctrl, pdata, cbdata);
597 			mutex_unlock(&ctrl->sdm_lock);
598 			continue;
599 		case COMMAND_RECONFIG:
600 			a0 = INTEL_SIP_SMC_FPGA_CONFIG_START;
601 			pr_debug("conf_type=%u\n", (unsigned int)pdata->flag);
602 			a1 = pdata->flag;
603 			a2 = 0;
604 			break;
605 		case COMMAND_RECONFIG_DATA_SUBMIT:
606 			a0 = INTEL_SIP_SMC_FPGA_CONFIG_WRITE;
607 			a1 = (unsigned long)pdata->paddr;
608 			a2 = (unsigned long)pdata->size;
609 			break;
610 		case COMMAND_RECONFIG_STATUS:
611 			a0 = INTEL_SIP_SMC_FPGA_CONFIG_ISDONE;
612 			a1 = 0;
613 			a2 = 0;
614 			break;
615 		case COMMAND_RSU_STATUS:
616 			a0 = INTEL_SIP_SMC_RSU_STATUS;
617 			a1 = 0;
618 			a2 = 0;
619 			break;
620 		case COMMAND_RSU_UPDATE:
621 			a0 = INTEL_SIP_SMC_RSU_UPDATE;
622 			a1 = pdata->arg[0];
623 			a2 = 0;
624 			break;
625 		case COMMAND_RSU_NOTIFY:
626 			a0 = INTEL_SIP_SMC_RSU_NOTIFY;
627 			a1 = pdata->arg[0];
628 			a2 = 0;
629 			break;
630 		case COMMAND_RSU_RETRY:
631 			a0 = INTEL_SIP_SMC_RSU_RETRY_COUNTER;
632 			a1 = 0;
633 			a2 = 0;
634 			break;
635 		case COMMAND_RSU_MAX_RETRY:
636 			a0 = INTEL_SIP_SMC_RSU_MAX_RETRY;
637 			a1 = 0;
638 			a2 = 0;
639 			break;
640 		case COMMAND_RSU_DCMF_VERSION:
641 			a0 = INTEL_SIP_SMC_RSU_DCMF_VERSION;
642 			a1 = 0;
643 			a2 = 0;
644 			break;
645 		case COMMAND_FIRMWARE_VERSION:
646 			a0 = INTEL_SIP_SMC_FIRMWARE_VERSION;
647 			a1 = 0;
648 			a2 = 0;
649 			break;
650 
651 		/* for FCS */
652 		case COMMAND_FCS_DATA_ENCRYPTION:
653 			a0 = INTEL_SIP_SMC_FCS_CRYPTION;
654 			a1 = 1;
655 			a2 = (unsigned long)pdata->paddr;
656 			a3 = (unsigned long)pdata->size;
657 			a4 = (unsigned long)pdata->paddr_output;
658 			a5 = (unsigned long)pdata->size_output;
659 			break;
660 		case COMMAND_FCS_DATA_DECRYPTION:
661 			a0 = INTEL_SIP_SMC_FCS_CRYPTION;
662 			a1 = 0;
663 			a2 = (unsigned long)pdata->paddr;
664 			a3 = (unsigned long)pdata->size;
665 			a4 = (unsigned long)pdata->paddr_output;
666 			a5 = (unsigned long)pdata->size_output;
667 			break;
668 		case COMMAND_FCS_RANDOM_NUMBER_GEN:
669 			a0 = INTEL_SIP_SMC_FCS_RANDOM_NUMBER;
670 			a1 = (unsigned long)pdata->paddr;
671 			a2 = 0;
672 			break;
673 		case COMMAND_FCS_REQUEST_SERVICE:
674 			a0 = INTEL_SIP_SMC_FCS_SERVICE_REQUEST;
675 			a1 = (unsigned long)pdata->paddr;
676 			a2 = (unsigned long)pdata->size;
677 			break;
678 		case COMMAND_FCS_SEND_CERTIFICATE:
679 			a0 = INTEL_SIP_SMC_FCS_SEND_CERTIFICATE;
680 			a1 = (unsigned long)pdata->paddr;
681 			a2 = (unsigned long)pdata->size;
682 			break;
683 		case COMMAND_FCS_GET_PROVISION_DATA:
684 			a0 = INTEL_SIP_SMC_FCS_GET_PROVISION_DATA;
685 			a1 = 0;
686 			a2 = 0;
687 			break;
688 		/* for HWMON */
689 		case COMMAND_HWMON_READTEMP:
690 			a0 = INTEL_SIP_SMC_HWMON_READTEMP;
691 			a1 = pdata->arg[0];
692 			a2 = 0;
693 			break;
694 		case COMMAND_HWMON_READVOLT:
695 			a0 = INTEL_SIP_SMC_HWMON_READVOLT;
696 			a1 = pdata->arg[0];
697 			a2 = 0;
698 			break;
699 		/* for polling */
700 		case COMMAND_POLL_SERVICE_STATUS:
701 			a0 = INTEL_SIP_SMC_SERVICE_COMPLETED;
702 			a1 = (unsigned long)pdata->paddr;
703 			a2 = (unsigned long)pdata->size;
704 			break;
705 		case COMMAND_RSU_DCMF_STATUS:
706 			a0 = INTEL_SIP_SMC_RSU_DCMF_STATUS;
707 			a1 = 0;
708 			a2 = 0;
709 			break;
710 		case COMMAND_SMC_SVC_VERSION:
711 			a0 = INTEL_SIP_SMC_SVC_VERSION;
712 			a1 = 0;
713 			a2 = 0;
714 			break;
715 		case COMMAND_SMC_ATF_BUILD_VER:
716 			a0 = INTEL_SIP_SMC_ATF_BUILD_VER;
717 			a1 = 0;
718 			a2 = 0;
719 			a3 = 0;
720 			break;
721 		case COMMAND_MBOX_SEND_CMD:
722 			a0 = INTEL_SIP_SMC_MBOX_SEND_CMD;
723 			a1 = pdata->arg[0];
724 			a2 = (unsigned long)pdata->paddr;
725 			a3 = (unsigned long)pdata->size / BYTE_TO_WORD_SIZE;
726 			a4 = pdata->arg[1];
727 			a5 = (unsigned long)pdata->paddr_output;
728 			a6 = (unsigned long)pdata->size_output / BYTE_TO_WORD_SIZE;
729 			break;
730 		default:
731 			pr_warn("it shouldn't happen\n");
732 			mutex_unlock(&ctrl->sdm_lock);
733 			continue;
734 		}
735 		pr_debug("%s: %s: before SMC call -- a0=0x%016x a1=0x%016x",
736 			 __func__, chan->name,
737 			 (unsigned int)a0,
738 			 (unsigned int)a1);
739 		pr_debug(" a2=0x%016x\n", (unsigned int)a2);
740 		pr_debug(" a3=0x%016x\n", (unsigned int)a3);
741 		pr_debug(" a4=0x%016x\n", (unsigned int)a4);
742 		pr_debug(" a5=0x%016x\n", (unsigned int)a5);
743 		ctrl->invoke_fn(a0, a1, a2, a3, a4, a5, a6, a7, &res);
744 
745 		pr_debug("%s: %s: after SMC call -- res.a0=0x%016x",
746 			 __func__, chan->name, (unsigned int)res.a0);
747 		pr_debug(" res.a1=0x%016x, res.a2=0x%016x",
748 			 (unsigned int)res.a1, (unsigned int)res.a2);
749 		pr_debug(" res.a3=0x%016x\n", (unsigned int)res.a3);
750 
751 		if (pdata->command == COMMAND_RSU_STATUS) {
752 			if (res.a0 == INTEL_SIP_SMC_RSU_ERROR)
753 				cbdata->status = BIT(SVC_STATUS_ERROR);
754 			else
755 				cbdata->status = BIT(SVC_STATUS_OK);
756 
757 			cbdata->kaddr1 = &res;
758 			cbdata->kaddr2 = NULL;
759 			cbdata->kaddr3 = NULL;
760 			pdata->chan->scl->receive_cb(pdata->chan->scl, cbdata);
761 			mutex_unlock(&ctrl->sdm_lock);
762 			continue;
763 		}
764 
765 		switch (res.a0) {
766 		case INTEL_SIP_SMC_STATUS_OK:
767 			svc_thread_recv_status_ok(pdata, cbdata, res);
768 			break;
769 		case INTEL_SIP_SMC_STATUS_BUSY:
770 			switch (pdata->command) {
771 			case COMMAND_RECONFIG_DATA_SUBMIT:
772 				svc_thread_cmd_data_claim(ctrl,
773 							  pdata, cbdata);
774 				break;
775 			case COMMAND_RECONFIG_STATUS:
776 			case COMMAND_POLL_SERVICE_STATUS:
777 				svc_thread_cmd_config_status(ctrl,
778 							     pdata, cbdata);
779 				break;
780 			default:
781 				pr_warn("it shouldn't happen\n");
782 				break;
783 			}
784 			break;
785 		case INTEL_SIP_SMC_STATUS_REJECTED:
786 			pr_debug("%s: STATUS_REJECTED\n", __func__);
787 			/* for FCS */
788 			switch (pdata->command) {
789 			case COMMAND_FCS_REQUEST_SERVICE:
790 			case COMMAND_FCS_SEND_CERTIFICATE:
791 			case COMMAND_FCS_GET_PROVISION_DATA:
792 			case COMMAND_FCS_DATA_ENCRYPTION:
793 			case COMMAND_FCS_DATA_DECRYPTION:
794 			case COMMAND_FCS_RANDOM_NUMBER_GEN:
795 			case COMMAND_MBOX_SEND_CMD:
796 				cbdata->status = BIT(SVC_STATUS_INVALID_PARAM);
797 				cbdata->kaddr1 = NULL;
798 				cbdata->kaddr2 = NULL;
799 				cbdata->kaddr3 = NULL;
800 				pdata->chan->scl->receive_cb(pdata->chan->scl,
801 							     cbdata);
802 				break;
803 			}
804 			break;
805 		case INTEL_SIP_SMC_STATUS_ERROR:
806 		case INTEL_SIP_SMC_RSU_ERROR:
807 			pr_err("%s: STATUS_ERROR\n", __func__);
808 			cbdata->status = BIT(SVC_STATUS_ERROR);
809 			cbdata->kaddr1 = &res.a1;
810 			cbdata->kaddr2 = (res.a2) ?
811 				svc_pa_to_va(res.a2) : NULL;
812 			cbdata->kaddr3 = (res.a3) ? &res.a3 : NULL;
813 			pdata->chan->scl->receive_cb(pdata->chan->scl, cbdata);
814 			break;
815 		default:
816 			pr_warn("Secure firmware doesn't support...\n");
817 
818 			/*
819 			 * be compatible with older version firmware which
820 			 * doesn't support newer RSU commands
821 			 */
822 			if ((pdata->command != COMMAND_RSU_UPDATE) &&
823 				(pdata->command != COMMAND_RSU_STATUS)) {
824 				cbdata->status =
825 					BIT(SVC_STATUS_NO_SUPPORT);
826 				cbdata->kaddr1 = NULL;
827 				cbdata->kaddr2 = NULL;
828 				cbdata->kaddr3 = NULL;
829 				pdata->chan->scl->receive_cb(
830 					pdata->chan->scl, cbdata);
831 			}
832 			break;
833 
834 		}
835 
836 		mutex_unlock(&ctrl->sdm_lock);
837 	}
838 
839 	kfree(cbdata);
840 	kfree(pdata);
841 
842 	return 0;
843 }
844 
845 /**
846  * svc_normal_to_secure_shm_thread() - the function to run in the kthread
847  * @data: data pointer for kthread function
848  *
849  * Service layer driver creates stratix10_svc_smc_hvc_shm kthread on CPU
850  * node 0, its function stratix10_svc_secure_shm_thread is used to query the
851  * physical address of memory block reserved by secure monitor software at
852  * secure world.
853  *
854  * svc_normal_to_secure_shm_thread() terminates directly since it is a
855  * standlone thread for which no one will call kthread_stop() or return when
856  * 'kthread_should_stop()' is true.
857  */
858 static int svc_normal_to_secure_shm_thread(void *data)
859 {
860 	struct stratix10_svc_sh_memory
861 			*sh_mem = (struct stratix10_svc_sh_memory *)data;
862 	struct arm_smccc_res res;
863 
864 	/* SMC or HVC call to get shared memory info from secure world */
865 	sh_mem->invoke_fn(INTEL_SIP_SMC_FPGA_CONFIG_GET_MEM,
866 			  0, 0, 0, 0, 0, 0, 0, &res);
867 	if (res.a0 == INTEL_SIP_SMC_STATUS_OK) {
868 		sh_mem->addr = res.a1;
869 		sh_mem->size = res.a2;
870 	} else {
871 		pr_err("%s: after SMC call -- res.a0=0x%016x",  __func__,
872 		       (unsigned int)res.a0);
873 		sh_mem->addr = 0;
874 		sh_mem->size = 0;
875 	}
876 
877 	complete(&sh_mem->sync_complete);
878 	return 0;
879 }
880 
881 /**
882  * svc_get_sh_memory() - get memory block reserved by secure monitor SW
883  * @pdev: pointer to service layer device
884  * @sh_memory: pointer to service shared memory structure
885  *
886  * Return: zero for successfully getting the physical address of memory block
887  * reserved by secure monitor software, or negative value on error.
888  */
889 static int svc_get_sh_memory(struct platform_device *pdev,
890 				    struct stratix10_svc_sh_memory *sh_memory)
891 {
892 	struct device *dev = &pdev->dev;
893 	struct task_struct *sh_memory_task;
894 	unsigned int cpu = 0;
895 
896 	init_completion(&sh_memory->sync_complete);
897 
898 	/* smc or hvc call happens on cpu 0 bound kthread */
899 	sh_memory_task = kthread_create_on_node(svc_normal_to_secure_shm_thread,
900 					       (void *)sh_memory,
901 						cpu_to_node(cpu),
902 						"svc_smc_hvc_shm_thread");
903 	if (IS_ERR(sh_memory_task)) {
904 		dev_err(dev, "fail to create stratix10_svc_smc_shm_thread\n");
905 		return -EINVAL;
906 	}
907 
908 	wake_up_process(sh_memory_task);
909 
910 	if (!wait_for_completion_timeout(&sh_memory->sync_complete, 10 * HZ)) {
911 		dev_err(dev,
912 			"timeout to get sh-memory paras from secure world\n");
913 		return -ETIMEDOUT;
914 	}
915 
916 	if (!sh_memory->addr || !sh_memory->size) {
917 		dev_err(dev,
918 			"failed to get shared memory info from secure world\n");
919 		return -ENOMEM;
920 	}
921 
922 	dev_dbg(dev, "SM software provides paddr: 0x%016x, size: 0x%08x\n",
923 		(unsigned int)sh_memory->addr,
924 		(unsigned int)sh_memory->size);
925 
926 	return 0;
927 }
928 
929 /**
930  * svc_create_memory_pool() - create a memory pool from reserved memory block
931  * @pdev: pointer to service layer device
932  * @sh_memory: pointer to service shared memory structure
933  *
934  * Return: pool allocated from reserved memory block or ERR_PTR() on error.
935  */
936 static struct gen_pool *
937 svc_create_memory_pool(struct platform_device *pdev,
938 		       struct stratix10_svc_sh_memory *sh_memory)
939 {
940 	struct device *dev = &pdev->dev;
941 	struct gen_pool *genpool;
942 	unsigned long vaddr;
943 	phys_addr_t paddr;
944 	size_t size;
945 	phys_addr_t begin;
946 	phys_addr_t end;
947 	void *va;
948 	size_t page_mask = PAGE_SIZE - 1;
949 	int min_alloc_order = 3;
950 	int ret;
951 
952 	begin = roundup(sh_memory->addr, PAGE_SIZE);
953 	end = rounddown(sh_memory->addr + sh_memory->size, PAGE_SIZE);
954 	paddr = begin;
955 	size = end - begin;
956 	va = devm_memremap(dev, paddr, size, MEMREMAP_WC);
957 	if (IS_ERR(va)) {
958 		dev_err(dev, "fail to remap shared memory\n");
959 		return ERR_PTR(-EINVAL);
960 	}
961 	vaddr = (unsigned long)va;
962 	dev_dbg(dev,
963 		"reserved memory vaddr: %p, paddr: 0x%16x size: 0x%8x\n",
964 		va, (unsigned int)paddr, (unsigned int)size);
965 	if ((vaddr & page_mask) || (paddr & page_mask) ||
966 	    (size & page_mask)) {
967 		dev_err(dev, "page is not aligned\n");
968 		return ERR_PTR(-EINVAL);
969 	}
970 	genpool = gen_pool_create(min_alloc_order, -1);
971 	if (!genpool) {
972 		dev_err(dev, "fail to create genpool\n");
973 		return ERR_PTR(-ENOMEM);
974 	}
975 	gen_pool_set_algo(genpool, gen_pool_best_fit, NULL);
976 	ret = gen_pool_add_virt(genpool, vaddr, paddr, size, -1);
977 	if (ret) {
978 		dev_err(dev, "fail to add memory chunk to the pool\n");
979 		gen_pool_destroy(genpool);
980 		return ERR_PTR(ret);
981 	}
982 
983 	return genpool;
984 }
985 
986 /**
987  * svc_smccc_smc() - secure monitor call between normal and secure world
988  * @a0: argument passed in registers 0
989  * @a1: argument passed in registers 1
990  * @a2: argument passed in registers 2
991  * @a3: argument passed in registers 3
992  * @a4: argument passed in registers 4
993  * @a5: argument passed in registers 5
994  * @a6: argument passed in registers 6
995  * @a7: argument passed in registers 7
996  * @res: result values from register 0 to 3
997  */
998 static void svc_smccc_smc(unsigned long a0, unsigned long a1,
999 			  unsigned long a2, unsigned long a3,
1000 			  unsigned long a4, unsigned long a5,
1001 			  unsigned long a6, unsigned long a7,
1002 			  struct arm_smccc_res *res)
1003 {
1004 	arm_smccc_smc(a0, a1, a2, a3, a4, a5, a6, a7, res);
1005 }
1006 
1007 /**
1008  * svc_smccc_hvc() - hypervisor call between normal and secure world
1009  * @a0: argument passed in registers 0
1010  * @a1: argument passed in registers 1
1011  * @a2: argument passed in registers 2
1012  * @a3: argument passed in registers 3
1013  * @a4: argument passed in registers 4
1014  * @a5: argument passed in registers 5
1015  * @a6: argument passed in registers 6
1016  * @a7: argument passed in registers 7
1017  * @res: result values from register 0 to 3
1018  */
1019 static void svc_smccc_hvc(unsigned long a0, unsigned long a1,
1020 			  unsigned long a2, unsigned long a3,
1021 			  unsigned long a4, unsigned long a5,
1022 			  unsigned long a6, unsigned long a7,
1023 			  struct arm_smccc_res *res)
1024 {
1025 	arm_smccc_hvc(a0, a1, a2, a3, a4, a5, a6, a7, res);
1026 }
1027 
1028 /**
1029  * get_invoke_func() - invoke SMC or HVC call
1030  * @dev: pointer to device
1031  *
1032  * Return: function pointer to svc_smccc_smc or svc_smccc_hvc.
1033  */
1034 static svc_invoke_fn *get_invoke_func(struct device *dev)
1035 {
1036 	const char *method;
1037 
1038 	if (of_property_read_string(dev->of_node, "method", &method)) {
1039 		dev_warn(dev, "missing \"method\" property\n");
1040 		return ERR_PTR(-ENXIO);
1041 	}
1042 
1043 	if (!strcmp(method, "smc"))
1044 		return svc_smccc_smc;
1045 	if (!strcmp(method, "hvc"))
1046 		return svc_smccc_hvc;
1047 
1048 	dev_warn(dev, "invalid \"method\" property: %s\n", method);
1049 
1050 	return ERR_PTR(-EINVAL);
1051 }
1052 
1053 /**
1054  * stratix10_svc_request_channel_byname() - request a service channel
1055  * @client: pointer to service client
1056  * @name: service client name
1057  *
1058  * This function is used by service client to request a service channel.
1059  *
1060  * Return: a pointer to channel assigned to the client on success,
1061  * or ERR_PTR() on error.
1062  */
1063 struct stratix10_svc_chan *stratix10_svc_request_channel_byname(
1064 	struct stratix10_svc_client *client, const char *name)
1065 {
1066 	struct device *dev = client->dev;
1067 	struct stratix10_svc_controller *controller;
1068 	struct stratix10_svc_chan *chan = NULL;
1069 	unsigned long flag;
1070 	int i;
1071 
1072 	/* if probe was called after client's, or error on probe */
1073 	if (list_empty(&svc_ctrl))
1074 		return ERR_PTR(-EPROBE_DEFER);
1075 
1076 	controller = list_first_entry(&svc_ctrl,
1077 				      struct stratix10_svc_controller, node);
1078 	for (i = 0; i < SVC_NUM_CHANNEL; i++) {
1079 		if (!strcmp(controller->chans[i].name, name)) {
1080 			chan = &controller->chans[i];
1081 			break;
1082 		}
1083 	}
1084 
1085 	/* if there was no channel match */
1086 	if (i == SVC_NUM_CHANNEL) {
1087 		dev_err(dev, "%s: channel not allocated\n", __func__);
1088 		return ERR_PTR(-EINVAL);
1089 	}
1090 
1091 	if (chan->scl || !try_module_get(controller->dev->driver->owner)) {
1092 		dev_dbg(dev, "%s: svc not free\n", __func__);
1093 		return ERR_PTR(-EBUSY);
1094 	}
1095 
1096 	spin_lock_irqsave(&chan->lock, flag);
1097 	chan->scl = client;
1098 	chan->ctrl->num_active_client++;
1099 	spin_unlock_irqrestore(&chan->lock, flag);
1100 
1101 	return chan;
1102 }
1103 EXPORT_SYMBOL_GPL(stratix10_svc_request_channel_byname);
1104 
1105 /**
1106  * stratix10_svc_add_async_client - Add an asynchronous client to the
1107  * Stratix10 service channel.
1108  * @chan: Pointer to the Stratix10 service channel structure.
1109  * @use_unique_clientid: Boolean flag indicating whether to use a
1110  * unique client ID.
1111  *
1112  * This function adds an asynchronous client to the specified
1113  * Stratix10 service channel. If the `use_unique_clientid` flag is
1114  * set to true, a unique client ID is allocated for the asynchronous
1115  * channel. Otherwise, a common asynchronous channel is used.
1116  *
1117  * Return: 0 on success, or a negative error code on failure:
1118  *         -EINVAL if the channel is NULL or the async controller is
1119  *         not initialized.
1120  *         -EOPNOTSUPP if async operations are not supported.
1121  *         -EALREADY if the async channel is already allocated.
1122  *         -ENOMEM if memory allocation fails.
1123  *         Other negative values if ID allocation fails.
1124  */
1125 int stratix10_svc_add_async_client(struct stratix10_svc_chan *chan,
1126 				   bool use_unique_clientid)
1127 {
1128 	struct stratix10_svc_controller *ctrl;
1129 	struct stratix10_async_ctrl *actrl;
1130 	struct stratix10_async_chan *achan;
1131 	int ret = 0;
1132 
1133 	if (!chan)
1134 		return -EINVAL;
1135 
1136 	ctrl = chan->ctrl;
1137 	actrl = &ctrl->actrl;
1138 
1139 	if (!actrl->supported)
1140 		return -EOPNOTSUPP;
1141 
1142 	if (!actrl->initialized) {
1143 		dev_err(ctrl->dev, "Async controller not initialized\n");
1144 		return -EINVAL;
1145 	}
1146 
1147 	if (chan->async_chan) {
1148 		dev_err(ctrl->dev, "async channel already allocated\n");
1149 		return -EALREADY;
1150 	}
1151 
1152 	if (use_unique_clientid &&
1153 	    atomic_read(&actrl->common_achan_refcount) > 0) {
1154 		chan->async_chan = actrl->common_async_chan;
1155 		atomic_inc(&actrl->common_achan_refcount);
1156 		return 0;
1157 	}
1158 
1159 	achan = kzalloc_obj(*achan);
1160 	if (!achan)
1161 		return -ENOMEM;
1162 
1163 	ida_init(&achan->job_id_pool);
1164 
1165 	ret = ida_alloc_max(&actrl->async_id_pool, MAX_SDM_CLIENT_IDS,
1166 			    GFP_KERNEL);
1167 	if (ret < 0) {
1168 		dev_err(ctrl->dev,
1169 			"Failed to allocate async client id\n");
1170 		ida_destroy(&achan->job_id_pool);
1171 		kfree(achan);
1172 		return ret;
1173 	}
1174 
1175 	achan->async_client_id = ret;
1176 	chan->async_chan = achan;
1177 
1178 	if (use_unique_clientid &&
1179 	    atomic_read(&actrl->common_achan_refcount) == 0) {
1180 		actrl->common_async_chan = achan;
1181 		atomic_inc(&actrl->common_achan_refcount);
1182 	}
1183 
1184 	return 0;
1185 }
1186 EXPORT_SYMBOL_GPL(stratix10_svc_add_async_client);
1187 
1188 /**
1189  * stratix10_svc_remove_async_client - Remove an asynchronous client
1190  *                                     from the Stratix10 service
1191  *                                     channel.
1192  * @chan: Pointer to the Stratix10 service channel structure.
1193  *
1194  * This function removes an asynchronous client associated with the
1195  * given service channel. It checks if the channel and the
1196  * asynchronous channel are valid, and then proceeds to decrement
1197  * the reference count for the common asynchronous channel if
1198  * applicable. If the reference count reaches zero, it destroys the
1199  * job ID pool and deallocates the asynchronous client ID. For
1200  * non-common asynchronous channels, it directly destroys the job ID
1201  * pool, deallocates the asynchronous client ID, and frees the
1202  * memory allocated for the asynchronous channel.
1203  *
1204  * Return: 0 on success, -EINVAL if the channel or asynchronous
1205  *         channel is invalid.
1206  */
1207 int stratix10_svc_remove_async_client(struct stratix10_svc_chan *chan)
1208 {
1209 	struct stratix10_svc_controller *ctrl;
1210 	struct stratix10_async_ctrl *actrl;
1211 	struct stratix10_async_chan *achan;
1212 
1213 	if (!chan)
1214 		return -EINVAL;
1215 
1216 	ctrl = chan->ctrl;
1217 	actrl = &ctrl->actrl;
1218 	achan = chan->async_chan;
1219 
1220 	if (!achan) {
1221 		dev_err(ctrl->dev, "async channel not allocated\n");
1222 		return -EINVAL;
1223 	}
1224 
1225 	if (achan == actrl->common_async_chan) {
1226 		atomic_dec(&actrl->common_achan_refcount);
1227 		if (atomic_read(&actrl->common_achan_refcount) == 0) {
1228 			ida_destroy(&achan->job_id_pool);
1229 			ida_free(&actrl->async_id_pool,
1230 				 achan->async_client_id);
1231 			kfree(achan);
1232 			actrl->common_async_chan = NULL;
1233 		}
1234 	} else {
1235 		ida_destroy(&achan->job_id_pool);
1236 		ida_free(&actrl->async_id_pool, achan->async_client_id);
1237 		kfree(achan);
1238 	}
1239 	chan->async_chan = NULL;
1240 
1241 	return 0;
1242 }
1243 EXPORT_SYMBOL_GPL(stratix10_svc_remove_async_client);
1244 
1245 /**
1246  * stratix10_svc_async_send - Send an asynchronous message to the
1247  *                            Stratix10 service
1248  * @chan: Pointer to the service channel structure
1249  * @msg: Pointer to the message to be sent
1250  * @handler: Pointer to the handler for the asynchronous message
1251  *           used by caller for later reference.
1252  * @cb: Callback function to be called upon completion
1253  * @cb_arg: Argument to be passed to the callback function
1254  *
1255  * This function sends an asynchronous message to the SDM mailbox in
1256  * EL3 secure firmware. It performs various checks and setups,
1257  * including allocating a job ID, setting up the transaction ID and
1258  * packaging it to El3 firmware. The function handles different
1259  * commands by setting up the appropriate arguments for the SMC call.
1260  * If the SMC call is successful, the handler is set up and the
1261  * function returns 0. If the SMC call fails, appropriate error
1262  * handling is performed along with cleanup of resources.
1263  *
1264  * Return: 0 on success, -EINVAL for invalid argument, -ENOMEM if
1265  * memory is not available, -EAGAIN if EL3 firmware is busy, -EBADF
1266  * if the message is rejected by EL3 firmware and -EIO on other
1267  * errors from EL3 firmware.
1268  */
1269 int stratix10_svc_async_send(struct stratix10_svc_chan *chan, void *msg,
1270 			     void **handler, async_callback_t cb, void *cb_arg)
1271 {
1272 	struct arm_smccc_1_2_regs args = { 0 }, res = { 0 };
1273 	struct stratix10_svc_async_handler *handle = NULL;
1274 	struct stratix10_svc_client_msg *p_msg =
1275 		(struct stratix10_svc_client_msg *)msg;
1276 	struct stratix10_svc_controller *ctrl;
1277 	struct stratix10_async_ctrl *actrl;
1278 	struct stratix10_async_chan *achan;
1279 	int ret = 0;
1280 
1281 	if (!chan || !msg || !handler)
1282 		return -EINVAL;
1283 
1284 	achan = chan->async_chan;
1285 	ctrl = chan->ctrl;
1286 	actrl = &ctrl->actrl;
1287 
1288 	if (!actrl->initialized) {
1289 		dev_err(ctrl->dev, "Async controller not initialized\n");
1290 		return -EINVAL;
1291 	}
1292 
1293 	if (!achan) {
1294 		dev_err(ctrl->dev, "Async channel not allocated\n");
1295 		return -EINVAL;
1296 	}
1297 
1298 	handle = kzalloc(sizeof(*handle), GFP_KERNEL);
1299 	if (!handle)
1300 		return -ENOMEM;
1301 
1302 	ret = ida_alloc_max(&achan->job_id_pool, MAX_SDM_JOB_IDS,
1303 			    GFP_KERNEL);
1304 	if (ret < 0) {
1305 		dev_err(ctrl->dev, "Failed to allocate job id\n");
1306 		kfree(handle);
1307 		return -ENOMEM;
1308 	}
1309 
1310 	handle->transaction_id =
1311 		STRATIX10_SET_TRANSACTIONID(achan->async_client_id, ret);
1312 	handle->cb = cb;
1313 	handle->msg = p_msg;
1314 	handle->cb_arg = cb_arg;
1315 	handle->achan = achan;
1316 
1317 	/*set the transaction jobid in args.a1*/
1318 	args.a1 =
1319 		STRATIX10_SIP_SMC_SET_TRANSACTIONID_X1(handle->transaction_id);
1320 
1321 	switch (p_msg->command) {
1322 	case COMMAND_RSU_GET_SPT_TABLE:
1323 		args.a0 = INTEL_SIP_SMC_ASYNC_RSU_GET_SPT;
1324 		break;
1325 	case COMMAND_RSU_STATUS:
1326 		args.a0 = INTEL_SIP_SMC_ASYNC_RSU_GET_ERROR_STATUS;
1327 		break;
1328 	case COMMAND_RSU_NOTIFY:
1329 		args.a0 = INTEL_SIP_SMC_ASYNC_RSU_NOTIFY;
1330 		args.a2 = p_msg->arg[0];
1331 		break;
1332 	default:
1333 		dev_err(ctrl->dev, "Invalid command ,%d\n", p_msg->command);
1334 		ret = -EINVAL;
1335 		goto deallocate_id;
1336 	}
1337 
1338 	/**
1339 	 * There is a chance that during the execution of async_send()
1340 	 * in one core, an interrupt might be received in another core;
1341 	 * to mitigate this we are adding the handle to the DB and then
1342 	 * send the smc call. If the smc call is rejected or busy then
1343 	 * we will deallocate the handle for the client to retry again.
1344 	 */
1345 	scoped_guard(spinlock_bh, &actrl->trx_list_lock) {
1346 		hash_add(actrl->trx_list, &handle->next,
1347 			 handle->transaction_id);
1348 	}
1349 
1350 	actrl->invoke_fn(actrl, &args, &res);
1351 
1352 	switch (res.a0) {
1353 	case INTEL_SIP_SMC_STATUS_OK:
1354 		dev_dbg(ctrl->dev,
1355 			"Async message sent with transaction_id 0x%02x\n",
1356 			handle->transaction_id);
1357 		*handler = handle;
1358 		return 0;
1359 	case INTEL_SIP_SMC_STATUS_BUSY:
1360 		dev_warn(ctrl->dev, "Mailbox is busy, try after some time\n");
1361 		ret = -EAGAIN;
1362 		break;
1363 	case INTEL_SIP_SMC_STATUS_REJECTED:
1364 		dev_err(ctrl->dev, "Async message rejected\n");
1365 		ret = -EBADF;
1366 		break;
1367 	default:
1368 		dev_err(ctrl->dev,
1369 			"Failed to send async message ,got status as %ld\n",
1370 			res.a0);
1371 		ret = -EIO;
1372 	}
1373 
1374 	scoped_guard(spinlock_bh, &actrl->trx_list_lock) {
1375 		hash_del(&handle->next);
1376 	}
1377 
1378 deallocate_id:
1379 	ida_free(&achan->job_id_pool,
1380 		 STRATIX10_GET_JOBID(handle->transaction_id));
1381 	kfree(handle);
1382 	return ret;
1383 }
1384 EXPORT_SYMBOL_GPL(stratix10_svc_async_send);
1385 
1386 /**
1387  * stratix10_svc_async_prepare_response - Prepare the response data for
1388  * an asynchronous transaction.
1389  * @chan: Pointer to the service channel structure.
1390  * @handle: Pointer to the asynchronous handler structure.
1391  * @data: Pointer to the callback data structure.
1392  *
1393  * This function prepares the response data for an asynchronous transaction. It
1394  * extracts the response data from the SMC response structure and stores it in
1395  * the callback data structure. The function also logs the completion of the
1396  * asynchronous transaction.
1397  *
1398  * Return: 0 on success, -ENOENT if the command is invalid
1399  */
1400 static int stratix10_svc_async_prepare_response(struct stratix10_svc_chan *chan,
1401 						struct stratix10_svc_async_handler *handle,
1402 						struct stratix10_svc_cb_data *data)
1403 {
1404 	struct stratix10_svc_client_msg *p_msg =
1405 		(struct stratix10_svc_client_msg *)handle->msg;
1406 	struct stratix10_svc_controller *ctrl = chan->ctrl;
1407 
1408 	data->status = STRATIX10_GET_SDM_STATUS_CODE(handle->res.a1);
1409 
1410 	switch (p_msg->command) {
1411 	case COMMAND_RSU_NOTIFY:
1412 		break;
1413 	case COMMAND_RSU_GET_SPT_TABLE:
1414 		data->kaddr1 = (void *)&handle->res.a2;
1415 		data->kaddr2 = (void *)&handle->res.a3;
1416 		break;
1417 	case COMMAND_RSU_STATUS:
1418 		/* COMMAND_RSU_STATUS has more elements than the cb_data
1419 		 * can acomodate, so passing the response structure to the
1420 		 * response function to be handled before done command is
1421 		 * executed by the client.
1422 		 */
1423 		data->kaddr1 = (void *)&handle->res;
1424 		break;
1425 
1426 	default:
1427 		dev_alert(ctrl->dev, "Invalid command\n ,%d", p_msg->command);
1428 		return -ENOENT;
1429 	}
1430 	dev_dbg(ctrl->dev, "Async message completed transaction_id 0x%02x\n",
1431 		handle->transaction_id);
1432 	return 0;
1433 }
1434 
1435 /**
1436  * stratix10_svc_async_poll - Polls the status of an asynchronous
1437  * transaction.
1438  * @chan: Pointer to the service channel structure.
1439  * @tx_handle: Handle to the transaction being polled.
1440  * @data: Pointer to the callback data structure.
1441  *
1442  * This function polls the status of an asynchronous transaction
1443  * identified by the given transaction handle. It ensures that the
1444  * necessary structures are initialized and valid before proceeding
1445  * with the poll operation. The function sets up the necessary
1446  * arguments for the SMC call, invokes the call, and prepares the
1447  * response data if the call is successful. If the call fails, the
1448  * function returns the error mapped to the SVC status error.
1449  *
1450  * Return: 0 on success, -EINVAL if any input parameter is invalid,
1451  *         -EAGAIN if the transaction is still in progress,
1452  *         -EPERM if the command is invalid, or other negative
1453  *         error codes on failure.
1454  */
1455 int stratix10_svc_async_poll(struct stratix10_svc_chan *chan,
1456 			     void *tx_handle,
1457 			     struct stratix10_svc_cb_data *data)
1458 {
1459 	struct stratix10_svc_async_handler *handle;
1460 	struct arm_smccc_1_2_regs args = { 0 };
1461 	struct stratix10_svc_controller *ctrl;
1462 	struct stratix10_async_ctrl *actrl;
1463 	struct stratix10_async_chan *achan;
1464 	int ret;
1465 
1466 	if (!chan || !tx_handle || !data)
1467 		return -EINVAL;
1468 
1469 	ctrl = chan->ctrl;
1470 	actrl = &ctrl->actrl;
1471 	achan = chan->async_chan;
1472 
1473 	if (!achan) {
1474 		dev_err(ctrl->dev, "Async channel not allocated\n");
1475 		return -EINVAL;
1476 	}
1477 
1478 	handle = (struct stratix10_svc_async_handler *)tx_handle;
1479 	scoped_guard(spinlock_bh, &actrl->trx_list_lock) {
1480 		if (!hash_hashed(&handle->next)) {
1481 			dev_err(ctrl->dev, "Invalid transaction handler");
1482 			return -EINVAL;
1483 		}
1484 	}
1485 
1486 	args.a0 = INTEL_SIP_SMC_ASYNC_POLL;
1487 	args.a1 =
1488 		STRATIX10_SIP_SMC_SET_TRANSACTIONID_X1(handle->transaction_id);
1489 
1490 	actrl->invoke_fn(actrl, &args, &handle->res);
1491 
1492 	/*clear data for response*/
1493 	memset(data, 0, sizeof(*data));
1494 
1495 	if (handle->res.a0 == INTEL_SIP_SMC_STATUS_OK) {
1496 		ret = stratix10_svc_async_prepare_response(chan, handle, data);
1497 		if (ret) {
1498 			dev_err(ctrl->dev, "Error in preparation of response,%d\n", ret);
1499 			WARN_ON_ONCE(1);
1500 		}
1501 		return 0;
1502 	} else if (handle->res.a0 == INTEL_SIP_SMC_STATUS_BUSY ||
1503 		   handle->res.a0 == INTEL_SIP_SMC_STATUS_NO_RESPONSE) {
1504 		dev_dbg(ctrl->dev, "async message is not ready yet\n");
1505 		return -EAGAIN;
1506 	}
1507 
1508 	dev_err(ctrl->dev,
1509 		"Failed to poll async message ,got status as %ld\n",
1510 		handle->res.a0);
1511 	return -EINVAL;
1512 }
1513 EXPORT_SYMBOL_GPL(stratix10_svc_async_poll);
1514 
1515 /**
1516  * stratix10_svc_async_done - Completes an asynchronous transaction.
1517  * @chan: Pointer to the service channel structure.
1518  * @tx_handle: Handle to the transaction being completed.
1519  *
1520  * This function completes an asynchronous transaction identified by
1521  * the given transaction handle. It ensures that the necessary
1522  * structures are initialized and valid before proceeding with the
1523  * completion operation. The function deallocates the transaction ID,
1524  * frees the memory allocated for the handler, and removes the handler
1525  * from the transaction list.
1526  *
1527  * Return: 0 on success, -EINVAL if any input parameter is invalid,
1528  * or other negative error codes on failure.
1529  */
1530 int stratix10_svc_async_done(struct stratix10_svc_chan *chan, void *tx_handle)
1531 {
1532 	struct stratix10_svc_async_handler *handle;
1533 	struct stratix10_svc_controller *ctrl;
1534 	struct stratix10_async_chan *achan;
1535 	struct stratix10_async_ctrl *actrl;
1536 
1537 	if (!chan || !tx_handle)
1538 		return -EINVAL;
1539 
1540 	ctrl = chan->ctrl;
1541 	achan = chan->async_chan;
1542 	actrl = &ctrl->actrl;
1543 
1544 	if (!achan) {
1545 		dev_err(ctrl->dev, "async channel not allocated\n");
1546 		return -EINVAL;
1547 	}
1548 
1549 	handle = (struct stratix10_svc_async_handler *)tx_handle;
1550 	scoped_guard(spinlock_bh, &actrl->trx_list_lock) {
1551 		if (!hash_hashed(&handle->next)) {
1552 			dev_err(ctrl->dev, "Invalid transaction handle");
1553 			return -EINVAL;
1554 		}
1555 		hash_del(&handle->next);
1556 	}
1557 	ida_free(&achan->job_id_pool,
1558 		 STRATIX10_GET_JOBID(handle->transaction_id));
1559 	kfree(handle);
1560 	return 0;
1561 }
1562 EXPORT_SYMBOL_GPL(stratix10_svc_async_done);
1563 
1564 static inline void stratix10_smc_1_2(struct stratix10_async_ctrl *actrl,
1565 				     const struct arm_smccc_1_2_regs *args,
1566 				     struct arm_smccc_1_2_regs *res)
1567 {
1568 	arm_smccc_1_2_smc(args, res);
1569 }
1570 
1571 /**
1572  * stratix10_svc_async_init - Initialize the Stratix10 service
1573  *                            controller for asynchronous operations.
1574  * @controller: Pointer to the Stratix10 service controller structure.
1575  *
1576  * This function initializes the asynchronous service controller by
1577  * setting up the necessary data structures and initializing the
1578  * transaction list.
1579  *
1580  * Return: 0 on success, -EINVAL if the controller is NULL or already
1581  *         initialized, -ENOMEM if memory allocation fails,
1582  *         -EADDRINUSE if the client ID is already reserved, or other
1583  *         negative error codes on failure.
1584  *         -EOPNOTSUPP if system doesn't support async operations.
1585  */
1586 static int stratix10_svc_async_init(struct stratix10_svc_controller *controller)
1587 {
1588 	struct stratix10_async_ctrl *actrl;
1589 	struct arm_smccc_res res;
1590 	struct device *dev;
1591 	int ret;
1592 
1593 	if (!controller)
1594 		return -EINVAL;
1595 
1596 	actrl = &controller->actrl;
1597 
1598 	if (actrl->initialized)
1599 		return -EINVAL;
1600 
1601 	dev = controller->dev;
1602 
1603 	controller->invoke_fn(INTEL_SIP_SMC_SVC_VERSION, 0, 0, 0, 0, 0, 0, 0, &res);
1604 	if (res.a0 != INTEL_SIP_SMC_STATUS_OK ||
1605 	    !(res.a1 > ASYNC_ATF_MINIMUM_MAJOR_VERSION ||
1606 	      (res.a1 == ASYNC_ATF_MINIMUM_MAJOR_VERSION &&
1607 	       res.a2 >= ASYNC_ATF_MINIMUM_MINOR_VERSION))) {
1608 		dev_info(dev,
1609 			 "Intel Service Layer Driver: ATF version is not compatible for async operation\n");
1610 		actrl->supported = false;
1611 		return -EOPNOTSUPP;
1612 	}
1613 	actrl->supported = true;
1614 
1615 	actrl->invoke_fn = stratix10_smc_1_2;
1616 
1617 	ida_init(&actrl->async_id_pool);
1618 
1619 	/**
1620 	 * SIP_SVC_V1_CLIENT_ID is used by V1/stratix10_svc_send() clients
1621 	 * for communicating with SDM synchronously. We need to restrict
1622 	 * this in V3/stratix10_svc_async_send() usage to distinguish
1623 	 * between V1 and V3 messages in El3 firmware.
1624 	 */
1625 	ret = ida_alloc_range(&actrl->async_id_pool, SIP_SVC_V1_CLIENT_ID,
1626 			      SIP_SVC_V1_CLIENT_ID, GFP_KERNEL);
1627 	if (ret < 0) {
1628 		dev_err(dev,
1629 			"Intel Service Layer Driver: Error on reserving SIP_SVC_V1_CLIENT_ID\n");
1630 		ida_destroy(&actrl->async_id_pool);
1631 		actrl->invoke_fn = NULL;
1632 		return -EADDRINUSE;
1633 	}
1634 
1635 	spin_lock_init(&actrl->trx_list_lock);
1636 	hash_init(actrl->trx_list);
1637 	atomic_set(&actrl->common_achan_refcount, 0);
1638 
1639 	actrl->initialized = true;
1640 	return 0;
1641 }
1642 
1643 /**
1644  * stratix10_svc_async_exit - Clean up and exit the asynchronous
1645  *                            service controller
1646  * @ctrl: Pointer to the stratix10_svc_controller structure
1647  *
1648  * This function performs the necessary cleanup for the asynchronous
1649  * service controller. It checks if the controller is valid and if it
1650  * has been initialized. It then locks the transaction list and safely
1651  * removes and deallocates each handler in the list. The function also
1652  * removes any asynchronous clients associated with the controller's
1653  * channels and destroys the asynchronous ID pool. Finally, it resets
1654  * the asynchronous ID pool and invoke function pointers to NULL.
1655  *
1656  * Return: 0 on success, -EINVAL if the controller is invalid or not
1657  *         initialized.
1658  */
1659 static int stratix10_svc_async_exit(struct stratix10_svc_controller *ctrl)
1660 {
1661 	struct stratix10_svc_async_handler *handler;
1662 	struct stratix10_async_ctrl *actrl;
1663 	struct hlist_node *tmp;
1664 	int i;
1665 
1666 	if (!ctrl)
1667 		return -EINVAL;
1668 
1669 	actrl = &ctrl->actrl;
1670 
1671 	if (!actrl->initialized)
1672 		return -EINVAL;
1673 
1674 	actrl->initialized = false;
1675 
1676 	scoped_guard(spinlock_bh, &actrl->trx_list_lock) {
1677 		hash_for_each_safe(actrl->trx_list, i, tmp, handler, next) {
1678 			ida_free(&handler->achan->job_id_pool,
1679 				 STRATIX10_GET_JOBID(handler->transaction_id));
1680 			hash_del(&handler->next);
1681 			kfree(handler);
1682 		}
1683 	}
1684 
1685 	for (i = 0; i < SVC_NUM_CHANNEL; i++) {
1686 		if (ctrl->chans[i].async_chan) {
1687 			stratix10_svc_remove_async_client(&ctrl->chans[i]);
1688 			ctrl->chans[i].async_chan = NULL;
1689 		}
1690 	}
1691 
1692 	ida_destroy(&actrl->async_id_pool);
1693 	actrl->invoke_fn = NULL;
1694 
1695 	return 0;
1696 }
1697 
1698 /**
1699  * stratix10_svc_free_channel() - free service channel
1700  * @chan: service channel to be freed
1701  *
1702  * This function is used by service client to free a service channel.
1703  */
1704 void stratix10_svc_free_channel(struct stratix10_svc_chan *chan)
1705 {
1706 	unsigned long flag;
1707 
1708 	spin_lock_irqsave(&chan->lock, flag);
1709 	chan->scl = NULL;
1710 	chan->ctrl->num_active_client--;
1711 	module_put(chan->ctrl->dev->driver->owner);
1712 	spin_unlock_irqrestore(&chan->lock, flag);
1713 }
1714 EXPORT_SYMBOL_GPL(stratix10_svc_free_channel);
1715 
1716 /**
1717  * stratix10_svc_send() - send a message data to the remote
1718  * @chan: service channel assigned to the client
1719  * @msg: message data to be sent, in the format of
1720  * "struct stratix10_svc_client_msg"
1721  *
1722  * This function is used by service client to add a message to the service
1723  * layer driver's queue for being sent to the secure world.
1724  *
1725  * Return: 0 for success, -ENOMEM or -ENOBUFS on error.
1726  */
1727 int stratix10_svc_send(struct stratix10_svc_chan *chan, void *msg)
1728 {
1729 	struct stratix10_svc_client_msg
1730 		*p_msg = (struct stratix10_svc_client_msg *)msg;
1731 	struct stratix10_svc_data_mem *p_mem;
1732 	struct stratix10_svc_data *p_data;
1733 	int ret = 0;
1734 	unsigned int cpu = 0;
1735 
1736 	p_data = kzalloc_obj(*p_data);
1737 	if (!p_data)
1738 		return -ENOMEM;
1739 
1740 	/* first caller creates the per-channel kthread */
1741 	if (!chan->task) {
1742 		struct task_struct *task;
1743 
1744 		task = kthread_run_on_cpu(svc_normal_to_secure_thread,
1745 					  (void *)chan,
1746 					  cpu, "svc_smc_hvc_thread");
1747 		if (IS_ERR(task)) {
1748 			dev_err(chan->ctrl->dev,
1749 				"failed to create svc_smc_hvc_thread\n");
1750 			kfree(p_data);
1751 			return -EINVAL;
1752 		}
1753 
1754 		spin_lock(&chan->lock);
1755 		if (chan->task) {
1756 			/* another caller won the race; discard our thread */
1757 			spin_unlock(&chan->lock);
1758 			kthread_stop(task);
1759 		} else {
1760 			chan->task = task;
1761 			spin_unlock(&chan->lock);
1762 		}
1763 	}
1764 
1765 	pr_debug("%s: %s: sent P-va=%p, P-com=%x, P-size=%u\n", __func__,
1766 		 chan->name, p_msg->payload, p_msg->command,
1767 		 (unsigned int)p_msg->payload_length);
1768 
1769 	if (list_empty(&svc_data_mem)) {
1770 		if (p_msg->command == COMMAND_RECONFIG) {
1771 			struct stratix10_svc_command_config_type *ct =
1772 				(struct stratix10_svc_command_config_type *)
1773 				p_msg->payload;
1774 			p_data->flag = ct->flags;
1775 		}
1776 	} else {
1777 		guard(mutex)(&svc_mem_lock);
1778 		list_for_each_entry(p_mem, &svc_data_mem, node)
1779 			if (p_mem->vaddr == p_msg->payload) {
1780 				p_data->paddr = p_mem->paddr;
1781 				p_data->size = p_msg->payload_length;
1782 				break;
1783 			}
1784 		if (p_msg->payload_output) {
1785 			list_for_each_entry(p_mem, &svc_data_mem, node)
1786 				if (p_mem->vaddr == p_msg->payload_output) {
1787 					p_data->paddr_output =
1788 						p_mem->paddr;
1789 					p_data->size_output =
1790 						p_msg->payload_length_output;
1791 					break;
1792 				}
1793 		}
1794 	}
1795 
1796 	p_data->command = p_msg->command;
1797 	p_data->arg[0] = p_msg->arg[0];
1798 	p_data->arg[1] = p_msg->arg[1];
1799 	p_data->arg[2] = p_msg->arg[2];
1800 	p_data->size = p_msg->payload_length;
1801 	p_data->chan = chan;
1802 	pr_debug("%s: %s: put to FIFO pa=0x%016x, cmd=%x, size=%u\n",
1803 		 __func__,
1804 		 chan->name,
1805 		 (unsigned int)p_data->paddr,
1806 		 p_data->command,
1807 		 (unsigned int)p_data->size);
1808 
1809 	ret = kfifo_in_spinlocked(&chan->svc_fifo, p_data,
1810 				  sizeof(*p_data),
1811 				  &chan->svc_fifo_lock);
1812 
1813 	kfree(p_data);
1814 
1815 	if (!ret)
1816 		return -ENOBUFS;
1817 
1818 	return 0;
1819 }
1820 EXPORT_SYMBOL_GPL(stratix10_svc_send);
1821 
1822 /**
1823  * stratix10_svc_done() - complete service request transactions
1824  * @chan: service channel assigned to the client
1825  *
1826  * This function should be called when client has finished its request
1827  * or there is an error in the request process. It allows the service layer
1828  * to stop the running thread to have maximize savings in kernel resources.
1829  */
1830 void stratix10_svc_done(struct stratix10_svc_chan *chan)
1831 {
1832 	/* stop thread when thread is running */
1833 	if (chan->task) {
1834 		pr_debug("%s: %s: svc_smc_hvc_shm_thread is stopping\n",
1835 			 __func__, chan->name);
1836 		kthread_stop(chan->task);
1837 		chan->task = NULL;
1838 	}
1839 }
1840 EXPORT_SYMBOL_GPL(stratix10_svc_done);
1841 
1842 /**
1843  * stratix10_svc_allocate_memory() - allocate memory
1844  * @chan: service channel assigned to the client
1845  * @size: memory size requested by a specific service client
1846  *
1847  * Service layer allocates the requested number of bytes buffer from the
1848  * memory pool, service client uses this function to get allocated buffers.
1849  *
1850  * Return: address of allocated memory on success, or ERR_PTR() on error.
1851  */
1852 void *stratix10_svc_allocate_memory(struct stratix10_svc_chan *chan,
1853 				    size_t size)
1854 {
1855 	struct stratix10_svc_data_mem *pmem;
1856 	unsigned long va;
1857 	phys_addr_t pa;
1858 	struct gen_pool *genpool = chan->ctrl->genpool;
1859 	size_t s = roundup(size, 1 << genpool->min_alloc_order);
1860 
1861 	pmem = kzalloc_obj(*pmem);
1862 	if (!pmem)
1863 		return ERR_PTR(-ENOMEM);
1864 
1865 	guard(mutex)(&svc_mem_lock);
1866 	va = gen_pool_alloc(genpool, s);
1867 	if (!va) {
1868 		kfree(pmem);
1869 		return ERR_PTR(-ENOMEM);
1870 	}
1871 
1872 	memset((void *)va, 0, s);
1873 	pa = gen_pool_virt_to_phys(genpool, va);
1874 
1875 	pmem->vaddr = (void *)va;
1876 	pmem->paddr = pa;
1877 	pmem->size = s;
1878 	list_add_tail(&pmem->node, &svc_data_mem);
1879 	pr_debug("%s: %s: va=%p, pa=0x%016x\n", __func__,
1880 		 chan->name, pmem->vaddr, (unsigned int)pmem->paddr);
1881 
1882 	return (void *)va;
1883 }
1884 EXPORT_SYMBOL_GPL(stratix10_svc_allocate_memory);
1885 
1886 /**
1887  * stratix10_svc_free_memory() - free allocated memory
1888  * @chan: service channel assigned to the client
1889  * @kaddr: memory to be freed
1890  *
1891  * This function is used by service client to free allocated buffers.
1892  */
1893 void stratix10_svc_free_memory(struct stratix10_svc_chan *chan, void *kaddr)
1894 {
1895 	struct stratix10_svc_data_mem *pmem;
1896 
1897 	guard(mutex)(&svc_mem_lock);
1898 
1899 	list_for_each_entry(pmem, &svc_data_mem, node)
1900 		if (pmem->vaddr == kaddr) {
1901 			gen_pool_free(chan->ctrl->genpool,
1902 				       (unsigned long)kaddr, pmem->size);
1903 			pmem->vaddr = NULL;
1904 			list_del(&pmem->node);
1905 			kfree(pmem);
1906 			return;
1907 		}
1908 }
1909 EXPORT_SYMBOL_GPL(stratix10_svc_free_memory);
1910 
1911 static const struct of_device_id stratix10_svc_drv_match[] = {
1912 	{.compatible = "intel,stratix10-svc"},
1913 	{.compatible = "intel,agilex-svc"},
1914 	{},
1915 };
1916 
1917 static const char * const chan_names[SVC_NUM_CHANNEL] = {
1918 	SVC_CLIENT_FPGA,
1919 	SVC_CLIENT_RSU,
1920 	SVC_CLIENT_FCS,
1921 	SVC_CLIENT_HWMON
1922 };
1923 
1924 static int stratix10_svc_drv_probe(struct platform_device *pdev)
1925 {
1926 	struct device *dev = &pdev->dev;
1927 	struct stratix10_svc_controller *controller;
1928 	struct gen_pool *genpool;
1929 	struct stratix10_svc_sh_memory *sh_memory;
1930 	struct stratix10_svc *svc = NULL;
1931 
1932 	svc_invoke_fn *invoke_fn;
1933 	size_t fifo_size;
1934 	int ret, i = 0;
1935 
1936 	/* get SMC or HVC function */
1937 	invoke_fn = get_invoke_func(dev);
1938 	if (IS_ERR(invoke_fn))
1939 		return -EINVAL;
1940 
1941 	sh_memory = devm_kzalloc(dev, sizeof(*sh_memory), GFP_KERNEL);
1942 	if (!sh_memory)
1943 		return -ENOMEM;
1944 
1945 	sh_memory->invoke_fn = invoke_fn;
1946 	ret = svc_get_sh_memory(pdev, sh_memory);
1947 	if (ret)
1948 		return ret;
1949 
1950 	genpool = svc_create_memory_pool(pdev, sh_memory);
1951 	if (IS_ERR(genpool))
1952 		return PTR_ERR(genpool);
1953 
1954 	/* allocate service controller and supporting channel */
1955 	controller = devm_kzalloc(dev, struct_size(controller, chans, SVC_NUM_CHANNEL),
1956 				GFP_KERNEL);
1957 	if (!controller) {
1958 		ret = -ENOMEM;
1959 		goto err_destroy_pool;
1960 	}
1961 
1962 	controller->num_chans = SVC_NUM_CHANNEL;
1963 	controller->dev = dev;
1964 	controller->num_active_client = 0;
1965 	controller->genpool = genpool;
1966 	controller->invoke_fn = invoke_fn;
1967 	INIT_LIST_HEAD(&controller->node);
1968 	init_completion(&controller->complete_status);
1969 
1970 	ret = stratix10_svc_async_init(controller);
1971 	if (ret == -EOPNOTSUPP) {
1972 		dev_info(dev, "Intel Service Layer Driver Initialized (sync-only mode)\n");
1973 	} else if (ret) {
1974 		dev_dbg(dev, "Intel Service Layer Driver: Error on stratix10_svc_async_init %d\n",
1975 			ret);
1976 		goto err_destroy_pool;
1977 	} else {
1978 		dev_info(dev, "Intel Service Layer Driver Initialized\n");
1979 	}
1980 
1981 	fifo_size = sizeof(struct stratix10_svc_data) * SVC_NUM_DATA_IN_FIFO;
1982 	mutex_init(&controller->sdm_lock);
1983 
1984 	for (i = 0; i < SVC_NUM_CHANNEL; i++) {
1985 		controller->chans[i].scl = NULL;
1986 		controller->chans[i].ctrl = controller;
1987 		controller->chans[i].name = (char *)chan_names[i];
1988 		spin_lock_init(&controller->chans[i].lock);
1989 		ret = kfifo_alloc(&controller->chans[i].svc_fifo, fifo_size, GFP_KERNEL);
1990 		if (ret) {
1991 			dev_err(dev, "failed to allocate FIFO %d\n", i);
1992 			goto err_free_fifos;
1993 		}
1994 		spin_lock_init(&controller->chans[i].svc_fifo_lock);
1995 	}
1996 
1997 	list_add_tail(&controller->node, &svc_ctrl);
1998 	platform_set_drvdata(pdev, controller);
1999 
2000 	/* add svc client device(s) */
2001 	svc = devm_kzalloc(dev, sizeof(*svc), GFP_KERNEL);
2002 	if (!svc) {
2003 		ret = -ENOMEM;
2004 		goto err_free_fifos;
2005 	}
2006 	controller->svc = svc;
2007 
2008 	svc->stratix10_svc_rsu = platform_device_alloc(STRATIX10_RSU, 0);
2009 	if (!svc->stratix10_svc_rsu) {
2010 		dev_err(dev, "failed to allocate %s device\n", STRATIX10_RSU);
2011 		ret = -ENOMEM;
2012 		goto err_free_fifos;
2013 	}
2014 
2015 	ret = platform_device_add(svc->stratix10_svc_rsu);
2016 	if (ret)
2017 		goto err_put_device;
2018 
2019 	ret = of_platform_default_populate(dev_of_node(dev), NULL, dev);
2020 	if (ret)
2021 		goto err_unregister_rsu_dev;
2022 
2023 	pr_info("Intel Service Layer Driver Initialized\n");
2024 
2025 	return 0;
2026 
2027 err_unregister_rsu_dev:
2028 	platform_device_unregister(svc->stratix10_svc_rsu);
2029 	goto err_free_fifos;
2030 err_put_device:
2031 	platform_device_put(svc->stratix10_svc_rsu);
2032 err_free_fifos:
2033 	/* only remove from list if list_add_tail() was reached */
2034 	if (!list_empty(&controller->node))
2035 		list_del(&controller->node);
2036 	/* free only the FIFOs that were successfully allocated */
2037 	while (i--)
2038 		kfifo_free(&controller->chans[i].svc_fifo);
2039 	stratix10_svc_async_exit(controller);
2040 err_destroy_pool:
2041 	gen_pool_destroy(genpool);
2042 
2043 	return ret;
2044 }
2045 
2046 static void stratix10_svc_drv_remove(struct platform_device *pdev)
2047 {
2048 	int i;
2049 	struct stratix10_svc_controller *ctrl = platform_get_drvdata(pdev);
2050 	struct stratix10_svc *svc = ctrl->svc;
2051 
2052 	platform_device_unregister(svc->stratix10_svc_rsu);
2053 
2054 	stratix10_svc_async_exit(ctrl);
2055 
2056 	of_platform_depopulate(ctrl->dev);
2057 
2058 	for (i = 0; i < SVC_NUM_CHANNEL; i++) {
2059 		if (ctrl->chans[i].task) {
2060 			kthread_stop(ctrl->chans[i].task);
2061 			ctrl->chans[i].task = NULL;
2062 		}
2063 		kfifo_free(&ctrl->chans[i].svc_fifo);
2064 	}
2065 
2066 	if (ctrl->genpool)
2067 		gen_pool_destroy(ctrl->genpool);
2068 	list_del(&ctrl->node);
2069 }
2070 
2071 static struct platform_driver stratix10_svc_driver = {
2072 	.probe = stratix10_svc_drv_probe,
2073 	.remove = stratix10_svc_drv_remove,
2074 	.driver = {
2075 		.name = "stratix10-svc",
2076 		.of_match_table = stratix10_svc_drv_match,
2077 	},
2078 };
2079 
2080 static int __init stratix10_svc_init(void)
2081 {
2082 	struct device_node *fw_np;
2083 	struct device_node *np;
2084 	int ret;
2085 
2086 	fw_np = of_find_node_by_name(NULL, "firmware");
2087 	if (!fw_np)
2088 		return -ENODEV;
2089 
2090 	np = of_find_matching_node(fw_np, stratix10_svc_drv_match);
2091 	if (!np)
2092 		return -ENODEV;
2093 
2094 	of_node_put(np);
2095 	ret = of_platform_populate(fw_np, stratix10_svc_drv_match, NULL, NULL);
2096 	if (ret)
2097 		return ret;
2098 
2099 	return platform_driver_register(&stratix10_svc_driver);
2100 }
2101 
2102 static void __exit stratix10_svc_exit(void)
2103 {
2104 	return platform_driver_unregister(&stratix10_svc_driver);
2105 }
2106 
2107 subsys_initcall(stratix10_svc_init);
2108 module_exit(stratix10_svc_exit);
2109 
2110 MODULE_LICENSE("GPL v2");
2111 MODULE_DESCRIPTION("Intel Stratix10 Service Layer Driver");
2112 MODULE_AUTHOR("Richard Gong <richard.gong@intel.com>");
2113 MODULE_ALIAS("platform:stratix10-svc");
2114