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