xref: /linux/drivers/accel/habanalabs/common/command_submission.c (revision 0af298e62e5cff4ebf9bec47b8711177a7e2f115)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 /*
4  * Copyright 2016-2021 HabanaLabs, Ltd.
5  * All Rights Reserved.
6  */
7 
8 #include <uapi/drm/habanalabs_accel.h>
9 #include "habanalabs.h"
10 
11 #include <linux/uaccess.h>
12 #include <linux/slab.h>
13 
14 #define HL_CS_FLAGS_TYPE_MASK	(HL_CS_FLAGS_SIGNAL | HL_CS_FLAGS_WAIT | \
15 			HL_CS_FLAGS_COLLECTIVE_WAIT | HL_CS_FLAGS_RESERVE_SIGNALS_ONLY | \
16 			HL_CS_FLAGS_UNRESERVE_SIGNALS_ONLY | HL_CS_FLAGS_ENGINE_CORE_COMMAND | \
17 			HL_CS_FLAGS_ENGINES_COMMAND | HL_CS_FLAGS_FLUSH_PCI_HBW_WRITES)
18 
19 
20 #define MAX_TS_ITER_NUM 100
21 
22 /**
23  * enum hl_cs_wait_status - cs wait status
24  * @CS_WAIT_STATUS_BUSY: cs was not completed yet
25  * @CS_WAIT_STATUS_COMPLETED: cs completed
26  * @CS_WAIT_STATUS_GONE: cs completed but fence is already gone
27  */
28 enum hl_cs_wait_status {
29 	CS_WAIT_STATUS_BUSY,
30 	CS_WAIT_STATUS_COMPLETED,
31 	CS_WAIT_STATUS_GONE
32 };
33 
34 /*
35  * Data used while handling wait/timestamp nodes.
36  * The purpose of this struct is to store the needed data for both operations
37  * in one variable instead of passing large number of arguments to functions.
38  */
39 struct wait_interrupt_data {
40 	struct hl_user_interrupt *interrupt;
41 	struct hl_mmap_mem_buf *buf;
42 	struct hl_mem_mgr *mmg;
43 	struct hl_cb *cq_cb;
44 	u64 ts_handle;
45 	u64 ts_offset;
46 	u64 cq_handle;
47 	u64 cq_offset;
48 	u64 target_value;
49 	u64 intr_timeout_us;
50 };
51 
52 static void job_wq_completion(struct work_struct *work);
53 static int _hl_cs_wait_ioctl(struct hl_device *hdev, struct hl_ctx *ctx, u64 timeout_us, u64 seq,
54 				enum hl_cs_wait_status *status, s64 *timestamp);
55 static void cs_do_release(struct kref *ref);
56 
57 static void hl_push_cs_outcome(struct hl_device *hdev,
58 			       struct hl_cs_outcome_store *outcome_store,
59 			       u64 seq, ktime_t ts, int error)
60 {
61 	struct hl_cs_outcome *node;
62 	unsigned long flags;
63 
64 	/*
65 	 * CS outcome store supports the following operations:
66 	 * push outcome - store a recent CS outcome in the store
67 	 * pop outcome - retrieve a SPECIFIC (by seq) CS outcome from the store
68 	 * It uses 2 lists: used list and free list.
69 	 * It has a pre-allocated amount of nodes, each node stores
70 	 * a single CS outcome.
71 	 * Initially, all the nodes are in the free list.
72 	 * On push outcome, a node (any) is taken from the free list, its
73 	 * information is filled in, and the node is moved to the used list.
74 	 * It is possible, that there are no nodes left in the free list.
75 	 * In this case, we will lose some information about old outcomes. We
76 	 * will pop the OLDEST node from the used list, and make it free.
77 	 * On pop, the node is searched for in the used list (using a search
78 	 * index).
79 	 * If found, the node is then removed from the used list, and moved
80 	 * back to the free list. The outcome data that the node contained is
81 	 * returned back to the user.
82 	 */
83 
84 	spin_lock_irqsave(&outcome_store->db_lock, flags);
85 
86 	if (list_empty(&outcome_store->free_list)) {
87 		node = list_last_entry(&outcome_store->used_list,
88 				       struct hl_cs_outcome, list_link);
89 		hash_del(&node->map_link);
90 		dev_dbg(hdev->dev, "CS %llu outcome was lost\n", node->seq);
91 	} else {
92 		node = list_last_entry(&outcome_store->free_list,
93 				       struct hl_cs_outcome, list_link);
94 	}
95 
96 	list_del_init(&node->list_link);
97 
98 	node->seq = seq;
99 	node->ts = ts;
100 	node->error = error;
101 
102 	list_add(&node->list_link, &outcome_store->used_list);
103 	hash_add(outcome_store->outcome_map, &node->map_link, node->seq);
104 
105 	spin_unlock_irqrestore(&outcome_store->db_lock, flags);
106 }
107 
108 static bool hl_pop_cs_outcome(struct hl_cs_outcome_store *outcome_store,
109 			       u64 seq, ktime_t *ts, int *error)
110 {
111 	struct hl_cs_outcome *node;
112 	unsigned long flags;
113 
114 	spin_lock_irqsave(&outcome_store->db_lock, flags);
115 
116 	hash_for_each_possible(outcome_store->outcome_map, node, map_link, seq)
117 		if (node->seq == seq) {
118 			*ts = node->ts;
119 			*error = node->error;
120 
121 			hash_del(&node->map_link);
122 			list_del_init(&node->list_link);
123 			list_add(&node->list_link, &outcome_store->free_list);
124 
125 			spin_unlock_irqrestore(&outcome_store->db_lock, flags);
126 
127 			return true;
128 		}
129 
130 	spin_unlock_irqrestore(&outcome_store->db_lock, flags);
131 
132 	return false;
133 }
134 
135 static void hl_sob_reset(struct kref *ref)
136 {
137 	struct hl_hw_sob *hw_sob = container_of(ref, struct hl_hw_sob,
138 							kref);
139 	struct hl_device *hdev = hw_sob->hdev;
140 
141 	dev_dbg(hdev->dev, "reset sob id %u\n", hw_sob->sob_id);
142 
143 	hdev->asic_funcs->reset_sob(hdev, hw_sob);
144 
145 	hw_sob->need_reset = false;
146 }
147 
148 void hl_sob_reset_error(struct kref *ref)
149 {
150 	struct hl_hw_sob *hw_sob = container_of(ref, struct hl_hw_sob,
151 							kref);
152 	struct hl_device *hdev = hw_sob->hdev;
153 
154 	dev_crit(hdev->dev,
155 		"SOB release shouldn't be called here, q_idx: %d, sob_id: %d\n",
156 		hw_sob->q_idx, hw_sob->sob_id);
157 }
158 
159 void hw_sob_put(struct hl_hw_sob *hw_sob)
160 {
161 	if (hw_sob)
162 		kref_put(&hw_sob->kref, hl_sob_reset);
163 }
164 
165 static void hw_sob_put_err(struct hl_hw_sob *hw_sob)
166 {
167 	if (hw_sob)
168 		kref_put(&hw_sob->kref, hl_sob_reset_error);
169 }
170 
171 void hw_sob_get(struct hl_hw_sob *hw_sob)
172 {
173 	if (hw_sob)
174 		kref_get(&hw_sob->kref);
175 }
176 
177 /**
178  * hl_gen_sob_mask() - Generates a sob mask to be used in a monitor arm packet
179  * @sob_base: sob base id
180  * @sob_mask: sob user mask, each bit represents a sob offset from sob base
181  * @mask: generated mask
182  *
183  * Return: 0 if given parameters are valid
184  */
185 int hl_gen_sob_mask(u16 sob_base, u8 sob_mask, u8 *mask)
186 {
187 	int i;
188 
189 	if (sob_mask == 0)
190 		return -EINVAL;
191 
192 	if (sob_mask == 0x1) {
193 		*mask = ~(1 << (sob_base & 0x7));
194 	} else {
195 		/* find msb in order to verify sob range is valid */
196 		for (i = BITS_PER_BYTE - 1 ; i >= 0 ; i--)
197 			if (BIT(i) & sob_mask)
198 				break;
199 
200 		if (i > (HL_MAX_SOBS_PER_MONITOR - (sob_base & 0x7) - 1))
201 			return -EINVAL;
202 
203 		*mask = ~sob_mask;
204 	}
205 
206 	return 0;
207 }
208 
209 static void hl_fence_release(struct kref *kref)
210 {
211 	struct hl_fence *fence =
212 		container_of(kref, struct hl_fence, refcount);
213 	struct hl_cs_compl *hl_cs_cmpl =
214 		container_of(fence, struct hl_cs_compl, base_fence);
215 
216 	kfree(hl_cs_cmpl);
217 }
218 
219 void hl_fence_put(struct hl_fence *fence)
220 {
221 	if (IS_ERR_OR_NULL(fence))
222 		return;
223 	kref_put(&fence->refcount, hl_fence_release);
224 }
225 
226 void hl_fences_put(struct hl_fence **fence, int len)
227 {
228 	int i;
229 
230 	for (i = 0; i < len; i++, fence++)
231 		hl_fence_put(*fence);
232 }
233 
234 void hl_fence_get(struct hl_fence *fence)
235 {
236 	if (fence)
237 		kref_get(&fence->refcount);
238 }
239 
240 static void hl_fence_init(struct hl_fence *fence, u64 sequence)
241 {
242 	kref_init(&fence->refcount);
243 	fence->cs_sequence = sequence;
244 	fence->error = 0;
245 	fence->timestamp = ktime_set(0, 0);
246 	fence->mcs_handling_done = false;
247 	init_completion(&fence->completion);
248 }
249 
250 void cs_get(struct hl_cs *cs)
251 {
252 	kref_get(&cs->refcount);
253 }
254 
255 static int cs_get_unless_zero(struct hl_cs *cs)
256 {
257 	return kref_get_unless_zero(&cs->refcount);
258 }
259 
260 static void cs_put(struct hl_cs *cs)
261 {
262 	kref_put(&cs->refcount, cs_do_release);
263 }
264 
265 static void cs_job_do_release(struct kref *ref)
266 {
267 	struct hl_cs_job *job = container_of(ref, struct hl_cs_job, refcount);
268 
269 	kfree(job);
270 }
271 
272 static void hl_cs_job_put(struct hl_cs_job *job)
273 {
274 	kref_put(&job->refcount, cs_job_do_release);
275 }
276 
277 bool cs_needs_completion(struct hl_cs *cs)
278 {
279 	/* In case this is a staged CS, only the last CS in sequence should
280 	 * get a completion, any non staged CS will always get a completion
281 	 */
282 	if (cs->staged_cs && !cs->staged_last)
283 		return false;
284 
285 	return true;
286 }
287 
288 bool cs_needs_timeout(struct hl_cs *cs)
289 {
290 	/* In case this is a staged CS, only the first CS in sequence should
291 	 * get a timeout, any non staged CS will always get a timeout
292 	 */
293 	if (cs->staged_cs && !cs->staged_first)
294 		return false;
295 
296 	return true;
297 }
298 
299 static bool is_cb_patched(struct hl_device *hdev, struct hl_cs_job *job)
300 {
301 	/* Patched CB is created for external queues jobs */
302 	return (job->queue_type == QUEUE_TYPE_EXT);
303 }
304 
305 /*
306  * cs_parser - parse the user command submission
307  *
308  * @hpriv	: pointer to the private data of the fd
309  * @job        : pointer to the job that holds the command submission info
310  *
311  * The function parses the command submission of the user. It calls the
312  * ASIC specific parser, which returns a list of memory blocks to send
313  * to the device as different command buffers
314  *
315  */
316 static int cs_parser(struct hl_fpriv *hpriv, struct hl_cs_job *job)
317 {
318 	struct hl_device *hdev = hpriv->hdev;
319 	struct hl_cs_parser parser;
320 	int rc;
321 
322 	parser.ctx_id = job->cs->ctx->asid;
323 	parser.cs_sequence = job->cs->sequence;
324 	parser.job_id = job->id;
325 
326 	parser.hw_queue_id = job->hw_queue_id;
327 	parser.job_userptr_list = &job->userptr_list;
328 	parser.patched_cb = NULL;
329 	parser.user_cb = job->user_cb;
330 	parser.user_cb_size = job->user_cb_size;
331 	parser.queue_type = job->queue_type;
332 	parser.is_kernel_allocated_cb = job->is_kernel_allocated_cb;
333 	job->patched_cb = NULL;
334 	parser.completion = cs_needs_completion(job->cs);
335 
336 	rc = hdev->asic_funcs->cs_parser(hdev, &parser);
337 
338 	if (is_cb_patched(hdev, job)) {
339 		if (!rc) {
340 			job->patched_cb = parser.patched_cb;
341 			job->job_cb_size = parser.patched_cb_size;
342 			job->contains_dma_pkt = parser.contains_dma_pkt;
343 			atomic_inc(&job->patched_cb->cs_cnt);
344 		}
345 
346 		/*
347 		 * Whether the parsing worked or not, we don't need the
348 		 * original CB anymore because it was already parsed and
349 		 * won't be accessed again for this CS
350 		 */
351 		atomic_dec(&job->user_cb->cs_cnt);
352 		hl_cb_put(job->user_cb);
353 		job->user_cb = NULL;
354 	} else if (!rc) {
355 		job->job_cb_size = job->user_cb_size;
356 	}
357 
358 	return rc;
359 }
360 
361 static void hl_complete_job(struct hl_device *hdev, struct hl_cs_job *job)
362 {
363 	struct hl_cs *cs = job->cs;
364 
365 	if (is_cb_patched(hdev, job)) {
366 		hl_userptr_delete_list(hdev, &job->userptr_list);
367 
368 		/*
369 		 * We might arrive here from rollback and patched CB wasn't
370 		 * created, so we need to check it's not NULL
371 		 */
372 		if (job->patched_cb) {
373 			atomic_dec(&job->patched_cb->cs_cnt);
374 			hl_cb_put(job->patched_cb);
375 		}
376 	}
377 
378 	/* For H/W queue jobs, if a user CB was allocated by driver,
379 	 * the user CB isn't released in cs_parser() and thus should be
380 	 * released here. This is also true for INT queues jobs which were
381 	 * allocated by driver.
382 	 */
383 	if (job->is_kernel_allocated_cb &&
384 			(job->queue_type == QUEUE_TYPE_HW || job->queue_type == QUEUE_TYPE_INT)) {
385 		atomic_dec(&job->user_cb->cs_cnt);
386 		hl_cb_put(job->user_cb);
387 	}
388 
389 	/*
390 	 * This is the only place where there can be multiple threads
391 	 * modifying the list at the same time
392 	 */
393 	spin_lock(&cs->job_lock);
394 	list_del(&job->cs_node);
395 	spin_unlock(&cs->job_lock);
396 
397 	hl_debugfs_remove_job(hdev, job);
398 
399 	/* We decrement reference only for a CS that gets completion
400 	 * because the reference was incremented only for this kind of CS
401 	 * right before it was scheduled.
402 	 *
403 	 * In staged submission, only the last CS marked as 'staged_last'
404 	 * gets completion, hence its release function will be called from here.
405 	 * As for all the rest CS's in the staged submission which do not get
406 	 * completion, their CS reference will be decremented by the
407 	 * 'staged_last' CS during the CS release flow.
408 	 * All relevant PQ CI counters will be incremented during the CS release
409 	 * flow by calling 'hl_hw_queue_update_ci'.
410 	 */
411 	if (cs_needs_completion(cs) &&
412 			(job->queue_type == QUEUE_TYPE_EXT || job->queue_type == QUEUE_TYPE_HW)) {
413 
414 		/* In CS based completions, the timestamp is already available,
415 		 * so no need to extract it from job
416 		 */
417 		if (hdev->asic_prop.completion_mode == HL_COMPLETION_MODE_JOB)
418 			cs->completion_timestamp = job->timestamp;
419 
420 		cs_put(cs);
421 	}
422 
423 	hl_cs_job_put(job);
424 }
425 
426 /*
427  * hl_staged_cs_find_first - locate the first CS in this staged submission
428  *
429  * @hdev: pointer to device structure
430  * @cs_seq: staged submission sequence number
431  *
432  * @note: This function must be called under 'hdev->cs_mirror_lock'
433  *
434  * Find and return a CS pointer with the given sequence
435  */
436 struct hl_cs *hl_staged_cs_find_first(struct hl_device *hdev, u64 cs_seq)
437 {
438 	struct hl_cs *cs;
439 
440 	list_for_each_entry_reverse(cs, &hdev->cs_mirror_list, mirror_node)
441 		if (cs->staged_cs && cs->staged_first &&
442 				cs->sequence == cs_seq)
443 			return cs;
444 
445 	return NULL;
446 }
447 
448 /*
449  * is_staged_cs_last_exists - returns true if the last CS in sequence exists
450  *
451  * @hdev: pointer to device structure
452  * @cs: staged submission member
453  *
454  */
455 bool is_staged_cs_last_exists(struct hl_device *hdev, struct hl_cs *cs)
456 {
457 	struct hl_cs *last_entry;
458 
459 	last_entry = list_last_entry(&cs->staged_cs_node, struct hl_cs,
460 								staged_cs_node);
461 
462 	if (last_entry->staged_last)
463 		return true;
464 
465 	return false;
466 }
467 
468 /*
469  * staged_cs_get - get CS reference if this CS is a part of a staged CS
470  *
471  * @hdev: pointer to device structure
472  * @cs: current CS
473  * @cs_seq: staged submission sequence number
474  *
475  * Increment CS reference for every CS in this staged submission except for
476  * the CS which get completion.
477  */
478 static void staged_cs_get(struct hl_device *hdev, struct hl_cs *cs)
479 {
480 	/* Only the last CS in this staged submission will get a completion.
481 	 * We must increment the reference for all other CS's in this
482 	 * staged submission.
483 	 * Once we get a completion we will release the whole staged submission.
484 	 */
485 	if (!cs->staged_last)
486 		cs_get(cs);
487 }
488 
489 /*
490  * staged_cs_put - put a CS in case it is part of staged submission
491  *
492  * @hdev: pointer to device structure
493  * @cs: CS to put
494  *
495  * This function decrements a CS reference (for a non completion CS)
496  */
497 static void staged_cs_put(struct hl_device *hdev, struct hl_cs *cs)
498 {
499 	/* We release all CS's in a staged submission except the last
500 	 * CS which we have never incremented its reference.
501 	 */
502 	if (!cs_needs_completion(cs))
503 		cs_put(cs);
504 }
505 
506 static void cs_handle_tdr(struct hl_device *hdev, struct hl_cs *cs)
507 {
508 	struct hl_cs *next = NULL, *iter, *first_cs;
509 
510 	if (!cs_needs_timeout(cs))
511 		return;
512 
513 	spin_lock(&hdev->cs_mirror_lock);
514 
515 	/* We need to handle tdr only once for the complete staged submission.
516 	 * Hence, we choose the CS that reaches this function first which is
517 	 * the CS marked as 'staged_last'.
518 	 * In case single staged cs was submitted which has both first and last
519 	 * indications, then "cs_find_first" below will return NULL, since we
520 	 * removed the cs node from the list before getting here,
521 	 * in such cases just continue with the cs to cancel it's TDR work.
522 	 */
523 	if (cs->staged_cs && cs->staged_last) {
524 		first_cs = hl_staged_cs_find_first(hdev, cs->staged_sequence);
525 		if (first_cs)
526 			cs = first_cs;
527 	}
528 
529 	spin_unlock(&hdev->cs_mirror_lock);
530 
531 	/* Don't cancel TDR in case this CS was timedout because we might be
532 	 * running from the TDR context
533 	 */
534 	if (cs->timedout || hdev->timeout_jiffies == MAX_SCHEDULE_TIMEOUT)
535 		return;
536 
537 	if (cs->tdr_active)
538 		cancel_delayed_work_sync(&cs->work_tdr);
539 
540 	spin_lock(&hdev->cs_mirror_lock);
541 
542 	/* queue TDR for next CS */
543 	list_for_each_entry(iter, &hdev->cs_mirror_list, mirror_node)
544 		if (cs_needs_timeout(iter)) {
545 			next = iter;
546 			break;
547 		}
548 
549 	if (next && !next->tdr_active) {
550 		next->tdr_active = true;
551 		schedule_delayed_work(&next->work_tdr, next->timeout_jiffies);
552 	}
553 
554 	spin_unlock(&hdev->cs_mirror_lock);
555 }
556 
557 /*
558  * force_complete_multi_cs - complete all contexts that wait on multi-CS
559  *
560  * @hdev: pointer to habanalabs device structure
561  */
562 static void force_complete_multi_cs(struct hl_device *hdev)
563 {
564 	int i;
565 
566 	for (i = 0; i < MULTI_CS_MAX_USER_CTX; i++) {
567 		struct multi_cs_completion *mcs_compl;
568 
569 		mcs_compl = &hdev->multi_cs_completion[i];
570 
571 		spin_lock(&mcs_compl->lock);
572 
573 		if (!mcs_compl->used) {
574 			spin_unlock(&mcs_compl->lock);
575 			continue;
576 		}
577 
578 		/* when calling force complete no context should be waiting on
579 		 * multi-cS.
580 		 * We are calling the function as a protection for such case
581 		 * to free any pending context and print error message
582 		 */
583 		dev_err(hdev->dev,
584 				"multi-CS completion context %d still waiting when calling force completion\n",
585 				i);
586 		complete_all(&mcs_compl->completion);
587 		spin_unlock(&mcs_compl->lock);
588 	}
589 }
590 
591 /*
592  * complete_multi_cs - complete all waiting entities on multi-CS
593  *
594  * @hdev: pointer to habanalabs device structure
595  * @cs: CS structure
596  * The function signals a waiting entity that has an overlapping stream masters
597  * with the completed CS.
598  * For example:
599  * - a completed CS worked on stream master QID 4, multi CS completion
600  *   is actively waiting on stream master QIDs 3, 5. don't send signal as no
601  *   common stream master QID
602  * - a completed CS worked on stream master QID 4, multi CS completion
603  *   is actively waiting on stream master QIDs 3, 4. send signal as stream
604  *   master QID 4 is common
605  */
606 static void complete_multi_cs(struct hl_device *hdev, struct hl_cs *cs)
607 {
608 	struct hl_fence *fence = cs->fence;
609 	int i;
610 
611 	/* in case of multi CS check for completion only for the first CS */
612 	if (cs->staged_cs && !cs->staged_first)
613 		return;
614 
615 	for (i = 0; i < MULTI_CS_MAX_USER_CTX; i++) {
616 		struct multi_cs_completion *mcs_compl;
617 
618 		mcs_compl = &hdev->multi_cs_completion[i];
619 		if (!mcs_compl->used)
620 			continue;
621 
622 		spin_lock(&mcs_compl->lock);
623 
624 		/*
625 		 * complete if:
626 		 * 1. still waiting for completion
627 		 * 2. the completed CS has at least one overlapping stream
628 		 *    master with the stream masters in the completion
629 		 */
630 		if (mcs_compl->used &&
631 				(fence->stream_master_qid_map &
632 					mcs_compl->stream_master_qid_map)) {
633 			/* extract the timestamp only of first completed CS */
634 			if (!mcs_compl->timestamp)
635 				mcs_compl->timestamp = ktime_to_ns(fence->timestamp);
636 
637 			complete_all(&mcs_compl->completion);
638 
639 			/*
640 			 * Setting mcs_handling_done inside the lock ensures
641 			 * at least one fence have mcs_handling_done set to
642 			 * true before wait for mcs finish. This ensures at
643 			 * least one CS will be set as completed when polling
644 			 * mcs fences.
645 			 */
646 			fence->mcs_handling_done = true;
647 		}
648 
649 		spin_unlock(&mcs_compl->lock);
650 	}
651 	/* In case CS completed without mcs completion initialized */
652 	fence->mcs_handling_done = true;
653 }
654 
655 static inline void cs_release_sob_reset_handler(struct hl_device *hdev,
656 					struct hl_cs *cs,
657 					struct hl_cs_compl *hl_cs_cmpl)
658 {
659 	/* Skip this handler if the cs wasn't submitted, to avoid putting
660 	 * the hw_sob twice, since this case already handled at this point,
661 	 * also skip if the hw_sob pointer wasn't set.
662 	 */
663 	if (!hl_cs_cmpl->hw_sob || !cs->submitted)
664 		return;
665 
666 	spin_lock(&hl_cs_cmpl->lock);
667 
668 	/*
669 	 * we get refcount upon reservation of signals or signal/wait cs for the
670 	 * hw_sob object, and need to put it when the first staged cs
671 	 * (which contains the encaps signals) or cs signal/wait is completed.
672 	 */
673 	if ((hl_cs_cmpl->type == CS_TYPE_SIGNAL) ||
674 			(hl_cs_cmpl->type == CS_TYPE_WAIT) ||
675 			(hl_cs_cmpl->type == CS_TYPE_COLLECTIVE_WAIT) ||
676 			(!!hl_cs_cmpl->encaps_signals)) {
677 		dev_dbg(hdev->dev,
678 				"CS 0x%llx type %d finished, sob_id: %d, sob_val: %u\n",
679 				hl_cs_cmpl->cs_seq,
680 				hl_cs_cmpl->type,
681 				hl_cs_cmpl->hw_sob->sob_id,
682 				hl_cs_cmpl->sob_val);
683 
684 		hw_sob_put(hl_cs_cmpl->hw_sob);
685 
686 		if (hl_cs_cmpl->type == CS_TYPE_COLLECTIVE_WAIT)
687 			hdev->asic_funcs->reset_sob_group(hdev,
688 					hl_cs_cmpl->sob_group);
689 	}
690 
691 	spin_unlock(&hl_cs_cmpl->lock);
692 }
693 
694 static void cs_do_release(struct kref *ref)
695 {
696 	struct hl_cs *cs = container_of(ref, struct hl_cs, refcount);
697 	struct hl_device *hdev = cs->ctx->hdev;
698 	struct hl_cs_job *job, *tmp;
699 	struct hl_cs_compl *hl_cs_cmpl =
700 			container_of(cs->fence, struct hl_cs_compl, base_fence);
701 
702 	cs->completed = true;
703 
704 	/*
705 	 * Although if we reached here it means that all external jobs have
706 	 * finished, because each one of them took refcnt to CS, we still
707 	 * need to go over the internal jobs and complete them. Otherwise, we
708 	 * will have leaked memory and what's worse, the CS object (and
709 	 * potentially the CTX object) could be released, while the JOB
710 	 * still holds a pointer to them (but no reference).
711 	 */
712 	list_for_each_entry_safe(job, tmp, &cs->job_list, cs_node)
713 		hl_complete_job(hdev, job);
714 
715 	if (!cs->submitted) {
716 		/*
717 		 * In case the wait for signal CS was submitted, the fence put
718 		 * occurs in init_signal_wait_cs() or collective_wait_init_cs()
719 		 * right before hanging on the PQ.
720 		 */
721 		if (cs->type == CS_TYPE_WAIT ||
722 				cs->type == CS_TYPE_COLLECTIVE_WAIT)
723 			hl_fence_put(cs->signal_fence);
724 
725 		goto out;
726 	}
727 
728 	/* Need to update CI for all queue jobs that does not get completion */
729 	hl_hw_queue_update_ci(cs);
730 
731 	/* remove CS from CS mirror list */
732 	spin_lock(&hdev->cs_mirror_lock);
733 	list_del_init(&cs->mirror_node);
734 	spin_unlock(&hdev->cs_mirror_lock);
735 
736 	cs_handle_tdr(hdev, cs);
737 
738 	if (cs->staged_cs) {
739 		/* the completion CS decrements reference for the entire
740 		 * staged submission
741 		 */
742 		if (cs->staged_last) {
743 			struct hl_cs *staged_cs, *tmp_cs;
744 
745 			list_for_each_entry_safe(staged_cs, tmp_cs,
746 					&cs->staged_cs_node, staged_cs_node)
747 				staged_cs_put(hdev, staged_cs);
748 		}
749 
750 		/* A staged CS will be a member in the list only after it
751 		 * was submitted. We used 'cs_mirror_lock' when inserting
752 		 * it to list so we will use it again when removing it
753 		 */
754 		if (cs->submitted) {
755 			spin_lock(&hdev->cs_mirror_lock);
756 			list_del(&cs->staged_cs_node);
757 			spin_unlock(&hdev->cs_mirror_lock);
758 		}
759 
760 		/* decrement refcount to handle when first staged cs
761 		 * with encaps signals is completed.
762 		 */
763 		if (hl_cs_cmpl->encaps_signals)
764 			kref_put(&hl_cs_cmpl->encaps_sig_hdl->refcount,
765 					hl_encaps_release_handle_and_put_ctx);
766 	}
767 
768 	if ((cs->type == CS_TYPE_WAIT || cs->type == CS_TYPE_COLLECTIVE_WAIT) && cs->encaps_signals)
769 		kref_put(&cs->encaps_sig_hdl->refcount, hl_encaps_release_handle_and_put_ctx);
770 
771 out:
772 	/* Must be called before hl_ctx_put because inside we use ctx to get
773 	 * the device
774 	 */
775 	hl_debugfs_remove_cs(cs);
776 
777 	hdev->shadow_cs_queue[cs->sequence & (hdev->asic_prop.max_pending_cs - 1)] = NULL;
778 
779 	/* We need to mark an error for not submitted because in that case
780 	 * the hl fence release flow is different. Mainly, we don't need
781 	 * to handle hw_sob for signal/wait
782 	 */
783 	if (cs->timedout)
784 		cs->fence->error = -ETIMEDOUT;
785 	else if (cs->aborted)
786 		cs->fence->error = -EIO;
787 	else if (!cs->submitted)
788 		cs->fence->error = -EBUSY;
789 
790 	if (unlikely(cs->skip_reset_on_timeout)) {
791 		dev_err(hdev->dev,
792 			"Command submission %llu completed after %llu (s)\n",
793 			cs->sequence,
794 			div_u64(jiffies - cs->submission_time_jiffies, HZ));
795 	}
796 
797 	if (cs->timestamp) {
798 		cs->fence->timestamp = cs->completion_timestamp;
799 		hl_push_cs_outcome(hdev, &cs->ctx->outcome_store, cs->sequence,
800 				   cs->fence->timestamp, cs->fence->error);
801 	}
802 
803 	hl_ctx_put(cs->ctx);
804 
805 	complete_all(&cs->fence->completion);
806 	complete_multi_cs(hdev, cs);
807 
808 	cs_release_sob_reset_handler(hdev, cs, hl_cs_cmpl);
809 
810 	hl_fence_put(cs->fence);
811 
812 	kfree(cs->jobs_in_queue_cnt);
813 	kfree(cs);
814 }
815 
816 static void cs_timedout(struct work_struct *work)
817 {
818 	struct hl_cs *cs = container_of(work, struct hl_cs, work_tdr.work);
819 	bool skip_reset_on_timeout, device_reset = false;
820 	struct hl_device *hdev;
821 	u64 event_mask = 0x0;
822 	uint timeout_sec;
823 	int rc;
824 
825 	skip_reset_on_timeout = cs->skip_reset_on_timeout;
826 
827 	rc = cs_get_unless_zero(cs);
828 	if (!rc)
829 		return;
830 
831 	if ((!cs->submitted) || (cs->completed)) {
832 		cs_put(cs);
833 		return;
834 	}
835 
836 	hdev = cs->ctx->hdev;
837 
838 	if (likely(!skip_reset_on_timeout)) {
839 		if (hdev->reset_on_lockup)
840 			device_reset = true;
841 		else
842 			hdev->reset_info.needs_reset = true;
843 
844 		/* Mark the CS is timed out so we won't try to cancel its TDR */
845 		cs->timedout = true;
846 	}
847 
848 	/* Save only the first CS timeout parameters */
849 	rc = atomic_cmpxchg(&hdev->captured_err_info.cs_timeout.write_enable, 1, 0);
850 	if (rc) {
851 		hdev->captured_err_info.cs_timeout.timestamp = ktime_get();
852 		hdev->captured_err_info.cs_timeout.seq = cs->sequence;
853 		event_mask |= HL_NOTIFIER_EVENT_CS_TIMEOUT;
854 	}
855 
856 	timeout_sec = jiffies_to_msecs(hdev->timeout_jiffies) / 1000;
857 
858 	switch (cs->type) {
859 	case CS_TYPE_SIGNAL:
860 		dev_err(hdev->dev,
861 			"Signal command submission %llu has not finished in %u seconds!\n",
862 			cs->sequence, timeout_sec);
863 		break;
864 
865 	case CS_TYPE_WAIT:
866 		dev_err(hdev->dev,
867 			"Wait command submission %llu has not finished in %u seconds!\n",
868 			cs->sequence, timeout_sec);
869 		break;
870 
871 	case CS_TYPE_COLLECTIVE_WAIT:
872 		dev_err(hdev->dev,
873 			"Collective Wait command submission %llu has not finished in %u seconds!\n",
874 			cs->sequence, timeout_sec);
875 		break;
876 
877 	default:
878 		dev_err(hdev->dev,
879 			"Command submission %llu has not finished in %u seconds!\n",
880 			cs->sequence, timeout_sec);
881 		break;
882 	}
883 
884 	rc = hl_state_dump(hdev);
885 	if (rc)
886 		dev_err(hdev->dev, "Error during system state dump %d\n", rc);
887 
888 	cs_put(cs);
889 
890 	if (device_reset) {
891 		event_mask |= HL_NOTIFIER_EVENT_DEVICE_RESET;
892 		hl_device_cond_reset(hdev, HL_DRV_RESET_TDR, event_mask);
893 	} else if (event_mask) {
894 		hl_notifier_event_send_all(hdev, event_mask);
895 	}
896 }
897 
898 static int allocate_cs(struct hl_device *hdev, struct hl_ctx *ctx,
899 			enum hl_cs_type cs_type, u64 user_sequence,
900 			struct hl_cs **cs_new, u32 flags, u32 timeout)
901 {
902 	struct hl_cs_counters_atomic *cntr;
903 	struct hl_fence *other = NULL;
904 	struct hl_cs_compl *cs_cmpl;
905 	struct hl_cs *cs;
906 	int rc;
907 
908 	cntr = &hdev->aggregated_cs_counters;
909 
910 	cs = kzalloc_obj(*cs, GFP_ATOMIC);
911 	if (!cs)
912 		cs = kzalloc_obj(*cs);
913 
914 	if (!cs) {
915 		atomic64_inc(&ctx->cs_counters.out_of_mem_drop_cnt);
916 		atomic64_inc(&cntr->out_of_mem_drop_cnt);
917 		return -ENOMEM;
918 	}
919 
920 	/* increment refcnt for context */
921 	hl_ctx_get(ctx);
922 
923 	cs->ctx = ctx;
924 	cs->submitted = false;
925 	cs->completed = false;
926 	cs->type = cs_type;
927 	cs->timestamp = !!(flags & HL_CS_FLAGS_TIMESTAMP);
928 	cs->encaps_signals = !!(flags & HL_CS_FLAGS_ENCAP_SIGNALS);
929 	cs->timeout_jiffies = timeout;
930 	cs->skip_reset_on_timeout =
931 		hdev->reset_info.skip_reset_on_timeout ||
932 		!!(flags & HL_CS_FLAGS_SKIP_RESET_ON_TIMEOUT);
933 	cs->submission_time_jiffies = jiffies;
934 	INIT_LIST_HEAD(&cs->job_list);
935 	INIT_DELAYED_WORK(&cs->work_tdr, cs_timedout);
936 	kref_init(&cs->refcount);
937 	spin_lock_init(&cs->job_lock);
938 
939 	cs_cmpl = kzalloc_obj(*cs_cmpl, GFP_ATOMIC);
940 	if (!cs_cmpl)
941 		cs_cmpl = kzalloc_obj(*cs_cmpl);
942 
943 	if (!cs_cmpl) {
944 		atomic64_inc(&ctx->cs_counters.out_of_mem_drop_cnt);
945 		atomic64_inc(&cntr->out_of_mem_drop_cnt);
946 		rc = -ENOMEM;
947 		goto free_cs;
948 	}
949 
950 	cs->jobs_in_queue_cnt = kzalloc_objs(*cs->jobs_in_queue_cnt,
951 					     hdev->asic_prop.max_queues,
952 					     GFP_ATOMIC);
953 	if (!cs->jobs_in_queue_cnt)
954 		cs->jobs_in_queue_cnt = kzalloc_objs(*cs->jobs_in_queue_cnt,
955 						     hdev->asic_prop.max_queues);
956 
957 	if (!cs->jobs_in_queue_cnt) {
958 		atomic64_inc(&ctx->cs_counters.out_of_mem_drop_cnt);
959 		atomic64_inc(&cntr->out_of_mem_drop_cnt);
960 		rc = -ENOMEM;
961 		goto free_cs_cmpl;
962 	}
963 
964 	cs_cmpl->hdev = hdev;
965 	cs_cmpl->type = cs->type;
966 	spin_lock_init(&cs_cmpl->lock);
967 	cs->fence = &cs_cmpl->base_fence;
968 
969 	spin_lock(&ctx->cs_lock);
970 
971 	cs_cmpl->cs_seq = ctx->cs_sequence;
972 	other = ctx->cs_pending[cs_cmpl->cs_seq &
973 				(hdev->asic_prop.max_pending_cs - 1)];
974 
975 	if (other && !completion_done(&other->completion)) {
976 		/* If the following statement is true, it means we have reached
977 		 * a point in which only part of the staged submission was
978 		 * submitted and we don't have enough room in the 'cs_pending'
979 		 * array for the rest of the submission.
980 		 * This causes a deadlock because this CS will never be
981 		 * completed as it depends on future CS's for completion.
982 		 */
983 		if (other->cs_sequence == user_sequence)
984 			dev_crit_ratelimited(hdev->dev,
985 				"Staged CS %llu deadlock due to lack of resources",
986 				user_sequence);
987 
988 		dev_dbg_ratelimited(hdev->dev,
989 			"Rejecting CS because of too many in-flights CS\n");
990 		atomic64_inc(&ctx->cs_counters.max_cs_in_flight_drop_cnt);
991 		atomic64_inc(&cntr->max_cs_in_flight_drop_cnt);
992 		rc = -EAGAIN;
993 		goto free_fence;
994 	}
995 
996 	/* init hl_fence */
997 	hl_fence_init(&cs_cmpl->base_fence, cs_cmpl->cs_seq);
998 
999 	cs->sequence = cs_cmpl->cs_seq;
1000 
1001 	ctx->cs_pending[cs_cmpl->cs_seq &
1002 			(hdev->asic_prop.max_pending_cs - 1)] =
1003 							&cs_cmpl->base_fence;
1004 	ctx->cs_sequence++;
1005 
1006 	hl_fence_get(&cs_cmpl->base_fence);
1007 
1008 	hl_fence_put(other);
1009 
1010 	spin_unlock(&ctx->cs_lock);
1011 
1012 	*cs_new = cs;
1013 
1014 	return 0;
1015 
1016 free_fence:
1017 	spin_unlock(&ctx->cs_lock);
1018 	kfree(cs->jobs_in_queue_cnt);
1019 free_cs_cmpl:
1020 	kfree(cs_cmpl);
1021 free_cs:
1022 	kfree(cs);
1023 	hl_ctx_put(ctx);
1024 	return rc;
1025 }
1026 
1027 static void cs_rollback(struct hl_device *hdev, struct hl_cs *cs)
1028 {
1029 	struct hl_cs_job *job, *tmp;
1030 
1031 	staged_cs_put(hdev, cs);
1032 
1033 	list_for_each_entry_safe(job, tmp, &cs->job_list, cs_node)
1034 		hl_complete_job(hdev, job);
1035 }
1036 
1037 /*
1038  * release_reserved_encaps_signals() - release reserved encapsulated signals.
1039  * @hdev: pointer to habanalabs device structure
1040  *
1041  * Release reserved encapsulated signals which weren't un-reserved, or for which a CS with
1042  * encapsulated signals wasn't submitted and thus weren't released as part of CS roll-back.
1043  * For these signals need also to put the refcount of the H/W SOB which was taken at the
1044  * reservation.
1045  */
1046 static void release_reserved_encaps_signals(struct hl_device *hdev)
1047 {
1048 	struct hl_ctx *ctx = hl_get_compute_ctx(hdev);
1049 	struct hl_cs_encaps_sig_handle *handle;
1050 	struct hl_encaps_signals_mgr *mgr;
1051 	u32 id;
1052 
1053 	if (!ctx)
1054 		return;
1055 
1056 	mgr = &ctx->sig_mgr;
1057 
1058 	idr_for_each_entry(&mgr->handles, handle, id)
1059 		if (handle->cs_seq == ULLONG_MAX)
1060 			kref_put(&handle->refcount, hl_encaps_release_handle_and_put_sob_ctx);
1061 
1062 	hl_ctx_put(ctx);
1063 }
1064 
1065 void hl_cs_rollback_all(struct hl_device *hdev, bool skip_wq_flush)
1066 {
1067 	int i;
1068 	struct hl_cs *cs, *tmp;
1069 
1070 	if (!skip_wq_flush) {
1071 		flush_workqueue(hdev->ts_free_obj_wq);
1072 
1073 		/* flush all completions before iterating over the CS mirror list in
1074 		 * order to avoid a race with the release functions
1075 		 */
1076 		for (i = 0 ; i < hdev->asic_prop.completion_queues_count ; i++)
1077 			flush_workqueue(hdev->cq_wq[i]);
1078 
1079 		flush_workqueue(hdev->cs_cmplt_wq);
1080 	}
1081 
1082 	/* Make sure we don't have leftovers in the CS mirror list */
1083 	list_for_each_entry_safe(cs, tmp, &hdev->cs_mirror_list, mirror_node) {
1084 		cs_get(cs);
1085 		cs->aborted = true;
1086 		dev_warn_ratelimited(hdev->dev, "Killing CS %d.%llu\n",
1087 					cs->ctx->asid, cs->sequence);
1088 		cs_rollback(hdev, cs);
1089 		cs_put(cs);
1090 	}
1091 
1092 	force_complete_multi_cs(hdev);
1093 
1094 	release_reserved_encaps_signals(hdev);
1095 }
1096 
1097 static void
1098 wake_pending_user_interrupt_threads(struct hl_user_interrupt *interrupt)
1099 {
1100 	struct hl_user_pending_interrupt *pend, *temp;
1101 	unsigned long flags;
1102 
1103 	spin_lock_irqsave(&interrupt->wait_list_lock, flags);
1104 	list_for_each_entry_safe(pend, temp, &interrupt->wait_list_head, list_node) {
1105 		pend->fence.error = -EIO;
1106 		complete_all(&pend->fence.completion);
1107 	}
1108 	spin_unlock_irqrestore(&interrupt->wait_list_lock, flags);
1109 
1110 	spin_lock_irqsave(&interrupt->ts_list_lock, flags);
1111 	list_for_each_entry_safe(pend, temp, &interrupt->ts_list_head, list_node) {
1112 		list_del(&pend->list_node);
1113 		hl_mmap_mem_buf_put(pend->ts_reg_info.buf);
1114 		hl_cb_put(pend->ts_reg_info.cq_cb);
1115 	}
1116 	spin_unlock_irqrestore(&interrupt->ts_list_lock, flags);
1117 }
1118 
1119 void hl_release_pending_user_interrupts(struct hl_device *hdev)
1120 {
1121 	struct asic_fixed_properties *prop = &hdev->asic_prop;
1122 	struct hl_user_interrupt *interrupt;
1123 	int i;
1124 
1125 	if (!prop->user_interrupt_count)
1126 		return;
1127 
1128 	/* We iterate through the user interrupt requests and waking up all
1129 	 * user threads waiting for interrupt completion. We iterate the
1130 	 * list under a lock, this is why all user threads, once awake,
1131 	 * will wait on the same lock and will release the waiting object upon
1132 	 * unlock.
1133 	 */
1134 
1135 	for (i = 0 ; i < prop->user_interrupt_count ; i++) {
1136 		interrupt = &hdev->user_interrupt[i];
1137 		wake_pending_user_interrupt_threads(interrupt);
1138 	}
1139 
1140 	interrupt = &hdev->common_user_cq_interrupt;
1141 	wake_pending_user_interrupt_threads(interrupt);
1142 
1143 	interrupt = &hdev->common_decoder_interrupt;
1144 	wake_pending_user_interrupt_threads(interrupt);
1145 }
1146 
1147 static void force_complete_cs(struct hl_device *hdev)
1148 {
1149 	struct hl_cs *cs;
1150 
1151 	spin_lock(&hdev->cs_mirror_lock);
1152 
1153 	list_for_each_entry(cs, &hdev->cs_mirror_list, mirror_node) {
1154 		cs->fence->error = -EIO;
1155 		complete_all(&cs->fence->completion);
1156 	}
1157 
1158 	spin_unlock(&hdev->cs_mirror_lock);
1159 }
1160 
1161 void hl_abort_waiting_for_cs_completions(struct hl_device *hdev)
1162 {
1163 	force_complete_cs(hdev);
1164 	force_complete_multi_cs(hdev);
1165 }
1166 
1167 static void job_wq_completion(struct work_struct *work)
1168 {
1169 	struct hl_cs_job *job = container_of(work, struct hl_cs_job,
1170 						finish_work);
1171 	struct hl_cs *cs = job->cs;
1172 	struct hl_device *hdev = cs->ctx->hdev;
1173 
1174 	/* job is no longer needed */
1175 	hl_complete_job(hdev, job);
1176 }
1177 
1178 static void cs_completion(struct work_struct *work)
1179 {
1180 	struct hl_cs *cs = container_of(work, struct hl_cs, finish_work);
1181 	struct hl_device *hdev = cs->ctx->hdev;
1182 	struct hl_cs_job *job, *tmp;
1183 
1184 	list_for_each_entry_safe(job, tmp, &cs->job_list, cs_node)
1185 		hl_complete_job(hdev, job);
1186 }
1187 
1188 u32 hl_get_active_cs_num(struct hl_device *hdev)
1189 {
1190 	u32 active_cs_num = 0;
1191 	struct hl_cs *cs;
1192 
1193 	spin_lock(&hdev->cs_mirror_lock);
1194 
1195 	list_for_each_entry(cs, &hdev->cs_mirror_list, mirror_node)
1196 		if (!cs->completed)
1197 			active_cs_num++;
1198 
1199 	spin_unlock(&hdev->cs_mirror_lock);
1200 
1201 	return active_cs_num;
1202 }
1203 
1204 static int validate_queue_index(struct hl_device *hdev,
1205 				struct hl_cs_chunk *chunk,
1206 				enum hl_queue_type *queue_type,
1207 				bool *is_kernel_allocated_cb)
1208 {
1209 	struct asic_fixed_properties *asic = &hdev->asic_prop;
1210 	struct hw_queue_properties *hw_queue_prop;
1211 
1212 	/* This must be checked here to prevent out-of-bounds access to
1213 	 * hw_queues_props array
1214 	 */
1215 	if (chunk->queue_index >= asic->max_queues) {
1216 		dev_err(hdev->dev, "Queue index %d is invalid\n",
1217 			chunk->queue_index);
1218 		return -EINVAL;
1219 	}
1220 
1221 	hw_queue_prop = &asic->hw_queues_props[chunk->queue_index];
1222 
1223 	if (hw_queue_prop->type == QUEUE_TYPE_NA) {
1224 		dev_err(hdev->dev, "Queue index %d is not applicable\n",
1225 			chunk->queue_index);
1226 		return -EINVAL;
1227 	}
1228 
1229 	if (hw_queue_prop->binned) {
1230 		dev_err(hdev->dev, "Queue index %d is binned out\n",
1231 			chunk->queue_index);
1232 		return -EINVAL;
1233 	}
1234 
1235 	if (hw_queue_prop->driver_only) {
1236 		dev_err(hdev->dev,
1237 			"Queue index %d is restricted for the kernel driver\n",
1238 			chunk->queue_index);
1239 		return -EINVAL;
1240 	}
1241 
1242 	/* When hw queue type isn't QUEUE_TYPE_HW,
1243 	 * USER_ALLOC_CB flag shall be referred as "don't care".
1244 	 */
1245 	if (hw_queue_prop->type == QUEUE_TYPE_HW) {
1246 		if (chunk->cs_chunk_flags & HL_CS_CHUNK_FLAGS_USER_ALLOC_CB) {
1247 			if (!(hw_queue_prop->cb_alloc_flags & CB_ALLOC_USER)) {
1248 				dev_err(hdev->dev,
1249 					"Queue index %d doesn't support user CB\n",
1250 					chunk->queue_index);
1251 				return -EINVAL;
1252 			}
1253 
1254 			*is_kernel_allocated_cb = false;
1255 		} else {
1256 			if (!(hw_queue_prop->cb_alloc_flags &
1257 					CB_ALLOC_KERNEL)) {
1258 				dev_err(hdev->dev,
1259 					"Queue index %d doesn't support kernel CB\n",
1260 					chunk->queue_index);
1261 				return -EINVAL;
1262 			}
1263 
1264 			*is_kernel_allocated_cb = true;
1265 		}
1266 	} else {
1267 		*is_kernel_allocated_cb = !!(hw_queue_prop->cb_alloc_flags
1268 						& CB_ALLOC_KERNEL);
1269 	}
1270 
1271 	*queue_type = hw_queue_prop->type;
1272 	return 0;
1273 }
1274 
1275 static struct hl_cb *get_cb_from_cs_chunk(struct hl_device *hdev,
1276 					struct hl_mem_mgr *mmg,
1277 					struct hl_cs_chunk *chunk)
1278 {
1279 	struct hl_cb *cb;
1280 
1281 	cb = hl_cb_get(mmg, chunk->cb_handle);
1282 	if (!cb) {
1283 		dev_err(hdev->dev, "CB handle 0x%llx invalid\n", chunk->cb_handle);
1284 		return NULL;
1285 	}
1286 
1287 	if ((chunk->cb_size < 8) || (chunk->cb_size > cb->size)) {
1288 		dev_err(hdev->dev, "CB size %u invalid\n", chunk->cb_size);
1289 		goto release_cb;
1290 	}
1291 
1292 	atomic_inc(&cb->cs_cnt);
1293 
1294 	return cb;
1295 
1296 release_cb:
1297 	hl_cb_put(cb);
1298 	return NULL;
1299 }
1300 
1301 struct hl_cs_job *hl_cs_allocate_job(struct hl_device *hdev,
1302 		enum hl_queue_type queue_type, bool is_kernel_allocated_cb)
1303 {
1304 	struct hl_cs_job *job;
1305 
1306 	job = kzalloc_obj(*job, GFP_ATOMIC);
1307 	if (!job)
1308 		job = kzalloc_obj(*job);
1309 
1310 	if (!job)
1311 		return NULL;
1312 
1313 	kref_init(&job->refcount);
1314 	job->queue_type = queue_type;
1315 	job->is_kernel_allocated_cb = is_kernel_allocated_cb;
1316 
1317 	if (is_cb_patched(hdev, job))
1318 		INIT_LIST_HEAD(&job->userptr_list);
1319 
1320 	if (job->queue_type == QUEUE_TYPE_EXT)
1321 		INIT_WORK(&job->finish_work, job_wq_completion);
1322 
1323 	return job;
1324 }
1325 
1326 static enum hl_cs_type hl_cs_get_cs_type(u32 cs_type_flags)
1327 {
1328 	if (cs_type_flags & HL_CS_FLAGS_SIGNAL)
1329 		return CS_TYPE_SIGNAL;
1330 	else if (cs_type_flags & HL_CS_FLAGS_WAIT)
1331 		return CS_TYPE_WAIT;
1332 	else if (cs_type_flags & HL_CS_FLAGS_COLLECTIVE_WAIT)
1333 		return CS_TYPE_COLLECTIVE_WAIT;
1334 	else if (cs_type_flags & HL_CS_FLAGS_RESERVE_SIGNALS_ONLY)
1335 		return CS_RESERVE_SIGNALS;
1336 	else if (cs_type_flags & HL_CS_FLAGS_UNRESERVE_SIGNALS_ONLY)
1337 		return CS_UNRESERVE_SIGNALS;
1338 	else if (cs_type_flags & HL_CS_FLAGS_ENGINE_CORE_COMMAND)
1339 		return CS_TYPE_ENGINE_CORE;
1340 	else if (cs_type_flags & HL_CS_FLAGS_ENGINES_COMMAND)
1341 		return CS_TYPE_ENGINES;
1342 	else if (cs_type_flags & HL_CS_FLAGS_FLUSH_PCI_HBW_WRITES)
1343 		return CS_TYPE_FLUSH_PCI_HBW_WRITES;
1344 	else
1345 		return CS_TYPE_DEFAULT;
1346 }
1347 
1348 static int hl_cs_sanity_checks(struct hl_fpriv *hpriv, union hl_cs_args *args)
1349 {
1350 	struct hl_device *hdev = hpriv->hdev;
1351 	struct hl_ctx *ctx = hpriv->ctx;
1352 	u32 cs_type_flags, num_chunks;
1353 	enum hl_device_status status;
1354 	enum hl_cs_type cs_type;
1355 	bool is_sync_stream;
1356 	int i;
1357 
1358 	for (i = 0 ; i < sizeof(args->in.pad) ; i++)
1359 		if (args->in.pad[i]) {
1360 			dev_dbg(hdev->dev, "Padding bytes must be 0\n");
1361 			return -EINVAL;
1362 		}
1363 
1364 	if (!hl_device_operational(hdev, &status))
1365 		return -EBUSY;
1366 
1367 	if ((args->in.cs_flags & HL_CS_FLAGS_STAGED_SUBMISSION) &&
1368 			!hdev->supports_staged_submission) {
1369 		dev_err(hdev->dev, "staged submission not supported");
1370 		return -EPERM;
1371 	}
1372 
1373 	cs_type_flags = args->in.cs_flags & HL_CS_FLAGS_TYPE_MASK;
1374 
1375 	if (unlikely(cs_type_flags && !is_power_of_2(cs_type_flags))) {
1376 		dev_err(hdev->dev,
1377 			"CS type flags are mutually exclusive, context %d\n",
1378 			ctx->asid);
1379 		return -EINVAL;
1380 	}
1381 
1382 	cs_type = hl_cs_get_cs_type(cs_type_flags);
1383 	num_chunks = args->in.num_chunks_execute;
1384 
1385 	is_sync_stream = (cs_type == CS_TYPE_SIGNAL || cs_type == CS_TYPE_WAIT ||
1386 			cs_type == CS_TYPE_COLLECTIVE_WAIT);
1387 
1388 	if (unlikely(is_sync_stream && !hdev->supports_sync_stream)) {
1389 		dev_err(hdev->dev, "Sync stream CS is not supported\n");
1390 		return -EINVAL;
1391 	}
1392 
1393 	if (cs_type == CS_TYPE_DEFAULT) {
1394 		if (!num_chunks) {
1395 			dev_err(hdev->dev, "Got execute CS with 0 chunks, context %d\n", ctx->asid);
1396 			return -EINVAL;
1397 		}
1398 	} else if (is_sync_stream && num_chunks != 1) {
1399 		dev_err(hdev->dev,
1400 			"Sync stream CS mandates one chunk only, context %d\n",
1401 			ctx->asid);
1402 		return -EINVAL;
1403 	}
1404 
1405 	return 0;
1406 }
1407 
1408 static int hl_cs_copy_chunk_array(struct hl_device *hdev,
1409 					struct hl_cs_chunk **cs_chunk_array,
1410 					void __user *chunks, u32 num_chunks,
1411 					struct hl_ctx *ctx)
1412 {
1413 	u32 size_to_copy;
1414 
1415 	if (num_chunks > HL_MAX_JOBS_PER_CS) {
1416 		atomic64_inc(&ctx->cs_counters.validation_drop_cnt);
1417 		atomic64_inc(&hdev->aggregated_cs_counters.validation_drop_cnt);
1418 		dev_err(hdev->dev,
1419 			"Number of chunks can NOT be larger than %d\n",
1420 			HL_MAX_JOBS_PER_CS);
1421 		return -EINVAL;
1422 	}
1423 
1424 	*cs_chunk_array = kmalloc_objs(**cs_chunk_array, num_chunks, GFP_ATOMIC);
1425 	if (!*cs_chunk_array)
1426 		*cs_chunk_array = kmalloc_objs(**cs_chunk_array, num_chunks);
1427 	if (!*cs_chunk_array) {
1428 		atomic64_inc(&ctx->cs_counters.out_of_mem_drop_cnt);
1429 		atomic64_inc(&hdev->aggregated_cs_counters.out_of_mem_drop_cnt);
1430 		return -ENOMEM;
1431 	}
1432 
1433 	size_to_copy = num_chunks * sizeof(struct hl_cs_chunk);
1434 	if (copy_from_user(*cs_chunk_array, chunks, size_to_copy)) {
1435 		atomic64_inc(&ctx->cs_counters.validation_drop_cnt);
1436 		atomic64_inc(&hdev->aggregated_cs_counters.validation_drop_cnt);
1437 		dev_err(hdev->dev, "Failed to copy cs chunk array from user\n");
1438 		kfree(*cs_chunk_array);
1439 		return -EFAULT;
1440 	}
1441 
1442 	return 0;
1443 }
1444 
1445 static int cs_staged_submission(struct hl_device *hdev, struct hl_cs *cs,
1446 				u64 sequence, u32 flags,
1447 				u32 encaps_signal_handle)
1448 {
1449 	if (!(flags & HL_CS_FLAGS_STAGED_SUBMISSION))
1450 		return 0;
1451 
1452 	cs->staged_last = !!(flags & HL_CS_FLAGS_STAGED_SUBMISSION_LAST);
1453 	cs->staged_first = !!(flags & HL_CS_FLAGS_STAGED_SUBMISSION_FIRST);
1454 
1455 	if (cs->staged_first) {
1456 		/* Staged CS sequence is the first CS sequence */
1457 		INIT_LIST_HEAD(&cs->staged_cs_node);
1458 		cs->staged_sequence = cs->sequence;
1459 
1460 		if (cs->encaps_signals)
1461 			cs->encaps_sig_hdl_id = encaps_signal_handle;
1462 	} else {
1463 		/* User sequence will be validated in 'hl_hw_queue_schedule_cs'
1464 		 * under the cs_mirror_lock
1465 		 */
1466 		cs->staged_sequence = sequence;
1467 	}
1468 
1469 	/* Increment CS reference if needed */
1470 	staged_cs_get(hdev, cs);
1471 
1472 	cs->staged_cs = true;
1473 
1474 	return 0;
1475 }
1476 
1477 static u32 get_stream_master_qid_mask(struct hl_device *hdev, u32 qid)
1478 {
1479 	int i;
1480 
1481 	for (i = 0; i < hdev->stream_master_qid_arr_size; i++)
1482 		if (qid == hdev->stream_master_qid_arr[i])
1483 			return BIT(i);
1484 
1485 	return 0;
1486 }
1487 
1488 static int cs_ioctl_default(struct hl_fpriv *hpriv, void __user *chunks,
1489 				u32 num_chunks, u64 *cs_seq, u32 flags,
1490 				u32 encaps_signals_handle, u32 timeout,
1491 				u16 *signal_initial_sob_count)
1492 {
1493 	bool staged_mid, int_queues_only = true, using_hw_queues = false;
1494 	struct hl_device *hdev = hpriv->hdev;
1495 	struct hl_cs_chunk *cs_chunk_array;
1496 	struct hl_cs_counters_atomic *cntr;
1497 	struct hl_ctx *ctx = hpriv->ctx;
1498 	struct hl_cs_job *job;
1499 	struct hl_cs *cs;
1500 	struct hl_cb *cb;
1501 	u64 user_sequence;
1502 	u8 stream_master_qid_map = 0;
1503 	int rc, i;
1504 
1505 	cntr = &hdev->aggregated_cs_counters;
1506 	user_sequence = *cs_seq;
1507 	*cs_seq = ULLONG_MAX;
1508 
1509 	rc = hl_cs_copy_chunk_array(hdev, &cs_chunk_array, chunks, num_chunks,
1510 			hpriv->ctx);
1511 	if (rc)
1512 		goto out;
1513 
1514 	if ((flags & HL_CS_FLAGS_STAGED_SUBMISSION) &&
1515 			!(flags & HL_CS_FLAGS_STAGED_SUBMISSION_FIRST))
1516 		staged_mid = true;
1517 	else
1518 		staged_mid = false;
1519 
1520 	rc = allocate_cs(hdev, hpriv->ctx, CS_TYPE_DEFAULT,
1521 			staged_mid ? user_sequence : ULLONG_MAX, &cs, flags,
1522 			timeout);
1523 	if (rc)
1524 		goto free_cs_chunk_array;
1525 
1526 	*cs_seq = cs->sequence;
1527 
1528 	hl_debugfs_add_cs(cs);
1529 
1530 	rc = cs_staged_submission(hdev, cs, user_sequence, flags,
1531 						encaps_signals_handle);
1532 	if (rc)
1533 		goto free_cs_object;
1534 
1535 	/* If this is a staged submission we must return the staged sequence
1536 	 * rather than the internal CS sequence
1537 	 */
1538 	if (cs->staged_cs)
1539 		*cs_seq = cs->staged_sequence;
1540 
1541 	/* Validate ALL the CS chunks before submitting the CS */
1542 	for (i = 0 ; i < num_chunks ; i++) {
1543 		struct hl_cs_chunk *chunk = &cs_chunk_array[i];
1544 		enum hl_queue_type queue_type;
1545 		bool is_kernel_allocated_cb;
1546 
1547 		rc = validate_queue_index(hdev, chunk, &queue_type,
1548 						&is_kernel_allocated_cb);
1549 		if (rc) {
1550 			atomic64_inc(&ctx->cs_counters.validation_drop_cnt);
1551 			atomic64_inc(&cntr->validation_drop_cnt);
1552 			goto free_cs_object;
1553 		}
1554 
1555 		if (is_kernel_allocated_cb) {
1556 			cb = get_cb_from_cs_chunk(hdev, &hpriv->mem_mgr, chunk);
1557 			if (!cb) {
1558 				atomic64_inc(
1559 					&ctx->cs_counters.validation_drop_cnt);
1560 				atomic64_inc(&cntr->validation_drop_cnt);
1561 				rc = -EINVAL;
1562 				goto free_cs_object;
1563 			}
1564 		} else {
1565 			cb = (struct hl_cb *) (uintptr_t) chunk->cb_handle;
1566 		}
1567 
1568 		if (queue_type == QUEUE_TYPE_EXT ||
1569 						queue_type == QUEUE_TYPE_HW) {
1570 			int_queues_only = false;
1571 
1572 			/*
1573 			 * store which stream are being used for external/HW
1574 			 * queues of this CS
1575 			 */
1576 			if (hdev->supports_wait_for_multi_cs)
1577 				stream_master_qid_map |=
1578 					get_stream_master_qid_mask(hdev,
1579 							chunk->queue_index);
1580 		}
1581 
1582 		if (queue_type == QUEUE_TYPE_HW)
1583 			using_hw_queues = true;
1584 
1585 		job = hl_cs_allocate_job(hdev, queue_type,
1586 						is_kernel_allocated_cb);
1587 		if (!job) {
1588 			atomic64_inc(&ctx->cs_counters.out_of_mem_drop_cnt);
1589 			atomic64_inc(&cntr->out_of_mem_drop_cnt);
1590 			dev_err(hdev->dev, "Failed to allocate a new job\n");
1591 			rc = -ENOMEM;
1592 			if (is_kernel_allocated_cb)
1593 				goto release_cb;
1594 
1595 			goto free_cs_object;
1596 		}
1597 
1598 		job->id = i + 1;
1599 		job->cs = cs;
1600 		job->user_cb = cb;
1601 		job->user_cb_size = chunk->cb_size;
1602 		job->hw_queue_id = chunk->queue_index;
1603 
1604 		cs->jobs_in_queue_cnt[job->hw_queue_id]++;
1605 		cs->jobs_cnt++;
1606 
1607 		list_add_tail(&job->cs_node, &cs->job_list);
1608 
1609 		/*
1610 		 * Increment CS reference. When CS reference is 0, CS is
1611 		 * done and can be signaled to user and free all its resources
1612 		 * Only increment for JOB on external or H/W queues, because
1613 		 * only for those JOBs we get completion
1614 		 */
1615 		if (cs_needs_completion(cs) &&
1616 			(job->queue_type == QUEUE_TYPE_EXT ||
1617 				job->queue_type == QUEUE_TYPE_HW))
1618 			cs_get(cs);
1619 
1620 		hl_debugfs_add_job(hdev, job);
1621 
1622 		rc = cs_parser(hpriv, job);
1623 		if (rc) {
1624 			atomic64_inc(&ctx->cs_counters.parsing_drop_cnt);
1625 			atomic64_inc(&cntr->parsing_drop_cnt);
1626 			dev_err(hdev->dev,
1627 				"Failed to parse JOB %d.%llu.%d, err %d, rejecting the CS\n",
1628 				cs->ctx->asid, cs->sequence, job->id, rc);
1629 			goto free_cs_object;
1630 		}
1631 	}
1632 
1633 	/* We allow a CS with any queue type combination as long as it does
1634 	 * not get a completion
1635 	 */
1636 	if (int_queues_only && cs_needs_completion(cs)) {
1637 		atomic64_inc(&ctx->cs_counters.validation_drop_cnt);
1638 		atomic64_inc(&cntr->validation_drop_cnt);
1639 		dev_err(hdev->dev,
1640 			"Reject CS %d.%llu since it contains only internal queues jobs and needs completion\n",
1641 			cs->ctx->asid, cs->sequence);
1642 		rc = -EINVAL;
1643 		goto free_cs_object;
1644 	}
1645 
1646 	if (using_hw_queues)
1647 		INIT_WORK(&cs->finish_work, cs_completion);
1648 
1649 	/*
1650 	 * store the (external/HW queues) streams used by the CS in the
1651 	 * fence object for multi-CS completion
1652 	 */
1653 	if (hdev->supports_wait_for_multi_cs)
1654 		cs->fence->stream_master_qid_map = stream_master_qid_map;
1655 
1656 	rc = hl_hw_queue_schedule_cs(cs);
1657 	if (rc) {
1658 		if (rc != -EAGAIN)
1659 			dev_err(hdev->dev,
1660 				"Failed to submit CS %d.%llu to H/W queues, error %d\n",
1661 				cs->ctx->asid, cs->sequence, rc);
1662 		goto free_cs_object;
1663 	}
1664 
1665 	*signal_initial_sob_count = cs->initial_sob_count;
1666 
1667 	rc = HL_CS_STATUS_SUCCESS;
1668 	goto put_cs;
1669 
1670 release_cb:
1671 	atomic_dec(&cb->cs_cnt);
1672 	hl_cb_put(cb);
1673 free_cs_object:
1674 	cs_rollback(hdev, cs);
1675 	*cs_seq = ULLONG_MAX;
1676 	/* The path below is both for good and erroneous exits */
1677 put_cs:
1678 	/* We finished with the CS in this function, so put the ref */
1679 	cs_put(cs);
1680 free_cs_chunk_array:
1681 	kfree(cs_chunk_array);
1682 out:
1683 	return rc;
1684 }
1685 
1686 static int hl_cs_ctx_switch(struct hl_fpriv *hpriv, union hl_cs_args *args,
1687 				u64 *cs_seq)
1688 {
1689 	struct hl_device *hdev = hpriv->hdev;
1690 	struct hl_ctx *ctx = hpriv->ctx;
1691 	bool need_soft_reset = false;
1692 	int rc = 0, do_ctx_switch = 0;
1693 	void __user *chunks;
1694 	u32 num_chunks, tmp;
1695 	u16 sob_count;
1696 	int ret;
1697 
1698 	if (hdev->supports_ctx_switch)
1699 		do_ctx_switch = atomic_cmpxchg(&ctx->thread_ctx_switch_token, 1, 0);
1700 
1701 	if (do_ctx_switch || (args->in.cs_flags & HL_CS_FLAGS_FORCE_RESTORE)) {
1702 		mutex_lock(&hpriv->restore_phase_mutex);
1703 
1704 		if (do_ctx_switch) {
1705 			rc = hdev->asic_funcs->context_switch(hdev, ctx->asid);
1706 			if (rc) {
1707 				dev_err_ratelimited(hdev->dev,
1708 					"Failed to switch to context %d, rejecting CS! %d\n",
1709 					ctx->asid, rc);
1710 				/*
1711 				 * If we timedout, or if the device is not IDLE
1712 				 * while we want to do context-switch (-EBUSY),
1713 				 * we need to soft-reset because QMAN is
1714 				 * probably stuck. However, we can't call to
1715 				 * reset here directly because of deadlock, so
1716 				 * need to do it at the very end of this
1717 				 * function
1718 				 */
1719 				if ((rc == -ETIMEDOUT) || (rc == -EBUSY))
1720 					need_soft_reset = true;
1721 				mutex_unlock(&hpriv->restore_phase_mutex);
1722 				goto out;
1723 			}
1724 		}
1725 
1726 		hdev->asic_funcs->restore_phase_topology(hdev);
1727 
1728 		chunks = (void __user *) (uintptr_t) args->in.chunks_restore;
1729 		num_chunks = args->in.num_chunks_restore;
1730 
1731 		if (!num_chunks) {
1732 			dev_dbg(hdev->dev,
1733 				"Need to run restore phase but restore CS is empty\n");
1734 			rc = 0;
1735 		} else {
1736 			rc = cs_ioctl_default(hpriv, chunks, num_chunks,
1737 					cs_seq, 0, 0, hdev->timeout_jiffies, &sob_count);
1738 		}
1739 
1740 		mutex_unlock(&hpriv->restore_phase_mutex);
1741 
1742 		if (rc) {
1743 			dev_err(hdev->dev,
1744 				"Failed to submit restore CS for context %d (%d)\n",
1745 				ctx->asid, rc);
1746 			goto out;
1747 		}
1748 
1749 		/* Need to wait for restore completion before execution phase */
1750 		if (num_chunks) {
1751 			enum hl_cs_wait_status status;
1752 
1753 			ret = _hl_cs_wait_ioctl(hdev, ctx,
1754 					jiffies_to_usecs(hdev->timeout_jiffies),
1755 					*cs_seq, &status, NULL);
1756 			if (ret) {
1757 				dev_err(hdev->dev,
1758 					"Restore CS for context %d failed to complete %d\n",
1759 					ctx->asid, ret);
1760 				rc = -ENOEXEC;
1761 				goto out;
1762 			}
1763 		}
1764 
1765 		if (hdev->supports_ctx_switch)
1766 			ctx->thread_ctx_switch_wait_token = 1;
1767 
1768 	} else if (hdev->supports_ctx_switch && !ctx->thread_ctx_switch_wait_token) {
1769 		rc = hl_poll_timeout_memory(hdev,
1770 			&ctx->thread_ctx_switch_wait_token, tmp, (tmp == 1),
1771 			100, jiffies_to_usecs(hdev->timeout_jiffies), false);
1772 
1773 		if (rc == -ETIMEDOUT) {
1774 			dev_err(hdev->dev,
1775 				"context switch phase timeout (%d)\n", tmp);
1776 			goto out;
1777 		}
1778 	}
1779 
1780 out:
1781 	if ((rc == -ETIMEDOUT || rc == -EBUSY) && (need_soft_reset))
1782 		hl_device_reset(hdev, 0);
1783 
1784 	return rc;
1785 }
1786 
1787 /*
1788  * hl_cs_signal_sob_wraparound_handler: handle SOB value wrapaound case.
1789  * if the SOB value reaches the max value move to the other SOB reserved
1790  * to the queue.
1791  * @hdev: pointer to device structure
1792  * @q_idx: stream queue index
1793  * @hw_sob: the H/W SOB used in this signal CS.
1794  * @count: signals count
1795  * @encaps_sig: tells whether it's reservation for encaps signals or not.
1796  *
1797  * Note that this function must be called while hw_queues_lock is taken.
1798  */
1799 int hl_cs_signal_sob_wraparound_handler(struct hl_device *hdev, u32 q_idx,
1800 			struct hl_hw_sob **hw_sob, u32 count, bool encaps_sig)
1801 
1802 {
1803 	struct hl_sync_stream_properties *prop;
1804 	struct hl_hw_sob *sob = *hw_sob, *other_sob;
1805 	u8 other_sob_offset;
1806 
1807 	prop = &hdev->kernel_queues[q_idx].sync_stream_prop;
1808 
1809 	hw_sob_get(sob);
1810 
1811 	/* check for wraparound */
1812 	if (prop->next_sob_val + count >= HL_MAX_SOB_VAL) {
1813 		/*
1814 		 * Decrement as we reached the max value.
1815 		 * The release function won't be called here as we've
1816 		 * just incremented the refcount right before calling this
1817 		 * function.
1818 		 */
1819 		hw_sob_put_err(sob);
1820 
1821 		/*
1822 		 * check the other sob value, if it still in use then fail
1823 		 * otherwise make the switch
1824 		 */
1825 		other_sob_offset = (prop->curr_sob_offset + 1) % HL_RSVD_SOBS;
1826 		other_sob = &prop->hw_sob[other_sob_offset];
1827 
1828 		if (kref_read(&other_sob->kref) != 1) {
1829 			dev_err(hdev->dev, "error: Cannot switch SOBs q_idx: %d\n",
1830 								q_idx);
1831 			return -EINVAL;
1832 		}
1833 
1834 		/*
1835 		 * next_sob_val always points to the next available signal
1836 		 * in the sob, so in encaps signals it will be the next one
1837 		 * after reserving the required amount.
1838 		 */
1839 		if (encaps_sig)
1840 			prop->next_sob_val = count + 1;
1841 		else
1842 			prop->next_sob_val = count;
1843 
1844 		/* only two SOBs are currently in use */
1845 		prop->curr_sob_offset = other_sob_offset;
1846 		*hw_sob = other_sob;
1847 
1848 		/*
1849 		 * check if other_sob needs reset, then do it before using it
1850 		 * for the reservation or the next signal cs.
1851 		 * we do it here, and for both encaps and regular signal cs
1852 		 * cases in order to avoid possible races of two kref_put
1853 		 * of the sob which can occur at the same time if we move the
1854 		 * sob reset(kref_put) to cs_do_release function.
1855 		 * in addition, if we have combination of cs signal and
1856 		 * encaps, and at the point we need to reset the sob there was
1857 		 * no more reservations and only signal cs keep coming,
1858 		 * in such case we need signal_cs to put the refcount and
1859 		 * reset the sob.
1860 		 */
1861 		if (other_sob->need_reset)
1862 			hw_sob_put(other_sob);
1863 
1864 		if (encaps_sig) {
1865 			/* set reset indication for the sob */
1866 			sob->need_reset = true;
1867 			hw_sob_get(other_sob);
1868 		}
1869 
1870 		dev_dbg(hdev->dev, "switched to SOB %d, q_idx: %d\n",
1871 				prop->curr_sob_offset, q_idx);
1872 	} else {
1873 		prop->next_sob_val += count;
1874 	}
1875 
1876 	return 0;
1877 }
1878 
1879 static int cs_ioctl_extract_signal_seq(struct hl_device *hdev,
1880 		struct hl_cs_chunk *chunk, u64 *signal_seq, struct hl_ctx *ctx,
1881 		bool encaps_signals)
1882 {
1883 	u64 *signal_seq_arr = NULL;
1884 	u32 size_to_copy, signal_seq_arr_len;
1885 	int rc = 0;
1886 
1887 	if (encaps_signals) {
1888 		*signal_seq = chunk->encaps_signal_seq;
1889 		return 0;
1890 	}
1891 
1892 	signal_seq_arr_len = chunk->num_signal_seq_arr;
1893 
1894 	/* currently only one signal seq is supported */
1895 	if (signal_seq_arr_len != 1) {
1896 		atomic64_inc(&ctx->cs_counters.validation_drop_cnt);
1897 		atomic64_inc(&hdev->aggregated_cs_counters.validation_drop_cnt);
1898 		dev_err(hdev->dev,
1899 			"Wait for signal CS supports only one signal CS seq\n");
1900 		return -EINVAL;
1901 	}
1902 
1903 	signal_seq_arr = kmalloc_objs(*signal_seq_arr, signal_seq_arr_len,
1904 				      GFP_ATOMIC);
1905 	if (!signal_seq_arr)
1906 		signal_seq_arr = kmalloc_objs(*signal_seq_arr,
1907 					      signal_seq_arr_len);
1908 	if (!signal_seq_arr) {
1909 		atomic64_inc(&ctx->cs_counters.out_of_mem_drop_cnt);
1910 		atomic64_inc(&hdev->aggregated_cs_counters.out_of_mem_drop_cnt);
1911 		return -ENOMEM;
1912 	}
1913 
1914 	size_to_copy = signal_seq_arr_len * sizeof(*signal_seq_arr);
1915 	if (copy_from_user(signal_seq_arr,
1916 				u64_to_user_ptr(chunk->signal_seq_arr),
1917 				size_to_copy)) {
1918 		atomic64_inc(&ctx->cs_counters.validation_drop_cnt);
1919 		atomic64_inc(&hdev->aggregated_cs_counters.validation_drop_cnt);
1920 		dev_err(hdev->dev,
1921 			"Failed to copy signal seq array from user\n");
1922 		rc = -EFAULT;
1923 		goto out;
1924 	}
1925 
1926 	/* currently it is guaranteed to have only one signal seq */
1927 	*signal_seq = signal_seq_arr[0];
1928 
1929 out:
1930 	kfree(signal_seq_arr);
1931 
1932 	return rc;
1933 }
1934 
1935 static int cs_ioctl_signal_wait_create_jobs(struct hl_device *hdev,
1936 		struct hl_ctx *ctx, struct hl_cs *cs,
1937 		enum hl_queue_type q_type, u32 q_idx, u32 encaps_signal_offset)
1938 {
1939 	struct hl_cs_counters_atomic *cntr;
1940 	struct hl_cs_job *job;
1941 	struct hl_cb *cb;
1942 	u32 cb_size;
1943 
1944 	cntr = &hdev->aggregated_cs_counters;
1945 
1946 	job = hl_cs_allocate_job(hdev, q_type, true);
1947 	if (!job) {
1948 		atomic64_inc(&ctx->cs_counters.out_of_mem_drop_cnt);
1949 		atomic64_inc(&cntr->out_of_mem_drop_cnt);
1950 		dev_err(hdev->dev, "Failed to allocate a new job\n");
1951 		return -ENOMEM;
1952 	}
1953 
1954 	if (cs->type == CS_TYPE_WAIT)
1955 		cb_size = hdev->asic_funcs->get_wait_cb_size(hdev);
1956 	else
1957 		cb_size = hdev->asic_funcs->get_signal_cb_size(hdev);
1958 
1959 	cb = hl_cb_kernel_create(hdev, cb_size, q_type == QUEUE_TYPE_HW);
1960 	if (!cb) {
1961 		atomic64_inc(&ctx->cs_counters.out_of_mem_drop_cnt);
1962 		atomic64_inc(&cntr->out_of_mem_drop_cnt);
1963 		kfree(job);
1964 		return -EFAULT;
1965 	}
1966 
1967 	job->id = 0;
1968 	job->cs = cs;
1969 	job->user_cb = cb;
1970 	atomic_inc(&job->user_cb->cs_cnt);
1971 	job->user_cb_size = cb_size;
1972 	job->hw_queue_id = q_idx;
1973 
1974 	if ((cs->type == CS_TYPE_WAIT || cs->type == CS_TYPE_COLLECTIVE_WAIT)
1975 			&& cs->encaps_signals)
1976 		job->encaps_sig_wait_offset = encaps_signal_offset;
1977 	/*
1978 	 * No need in parsing, user CB is the patched CB.
1979 	 * We call hl_cb_destroy() out of two reasons - we don't need the CB in
1980 	 * the CB idr anymore and to decrement its refcount as it was
1981 	 * incremented inside hl_cb_kernel_create().
1982 	 */
1983 	job->patched_cb = job->user_cb;
1984 	job->job_cb_size = job->user_cb_size;
1985 	hl_cb_destroy(&hdev->kernel_mem_mgr, cb->buf->handle);
1986 
1987 	/* increment refcount as for external queues we get completion */
1988 	cs_get(cs);
1989 
1990 	cs->jobs_in_queue_cnt[job->hw_queue_id]++;
1991 	cs->jobs_cnt++;
1992 
1993 	list_add_tail(&job->cs_node, &cs->job_list);
1994 
1995 	hl_debugfs_add_job(hdev, job);
1996 
1997 	return 0;
1998 }
1999 
2000 static int cs_ioctl_reserve_signals(struct hl_fpriv *hpriv,
2001 				u32 q_idx, u32 count,
2002 				u32 *handle_id, u32 *sob_addr,
2003 				u32 *signals_count)
2004 {
2005 	struct hw_queue_properties *hw_queue_prop;
2006 	struct hl_sync_stream_properties *prop;
2007 	struct hl_device *hdev = hpriv->hdev;
2008 	struct hl_cs_encaps_sig_handle *handle;
2009 	struct hl_encaps_signals_mgr *mgr;
2010 	struct hl_hw_sob *hw_sob;
2011 	int hdl_id;
2012 	int rc = 0;
2013 
2014 	if (count >= HL_MAX_SOB_VAL) {
2015 		dev_err(hdev->dev, "signals count(%u) exceeds the max SOB value\n",
2016 						count);
2017 		rc = -EINVAL;
2018 		goto out;
2019 	}
2020 
2021 	if (q_idx >= hdev->asic_prop.max_queues) {
2022 		dev_err(hdev->dev, "Queue index %d is invalid\n",
2023 			q_idx);
2024 		rc = -EINVAL;
2025 		goto out;
2026 	}
2027 
2028 	hw_queue_prop = &hdev->asic_prop.hw_queues_props[q_idx];
2029 
2030 	if (!hw_queue_prop->supports_sync_stream) {
2031 		dev_err(hdev->dev,
2032 			"Queue index %d does not support sync stream operations\n",
2033 									q_idx);
2034 		rc = -EINVAL;
2035 		goto out;
2036 	}
2037 
2038 	prop = &hdev->kernel_queues[q_idx].sync_stream_prop;
2039 
2040 	handle = kzalloc_obj(*handle);
2041 	if (!handle) {
2042 		rc = -ENOMEM;
2043 		goto out;
2044 	}
2045 
2046 	handle->count = count;
2047 
2048 	hl_ctx_get(hpriv->ctx);
2049 	handle->ctx = hpriv->ctx;
2050 	mgr = &hpriv->ctx->sig_mgr;
2051 
2052 	spin_lock(&mgr->lock);
2053 	hdl_id = idr_alloc(&mgr->handles, handle, 1, 0, GFP_ATOMIC);
2054 	spin_unlock(&mgr->lock);
2055 
2056 	if (hdl_id < 0) {
2057 		dev_err(hdev->dev, "Failed to allocate IDR for a new signal reservation\n");
2058 		rc = -EINVAL;
2059 		goto put_ctx;
2060 	}
2061 
2062 	handle->id = hdl_id;
2063 	handle->q_idx = q_idx;
2064 	handle->hdev = hdev;
2065 	kref_init(&handle->refcount);
2066 
2067 	hdev->asic_funcs->hw_queues_lock(hdev);
2068 
2069 	hw_sob = &prop->hw_sob[prop->curr_sob_offset];
2070 
2071 	/*
2072 	 * Increment the SOB value by count by user request
2073 	 * to reserve those signals
2074 	 * check if the signals amount to reserve is not exceeding the max sob
2075 	 * value, if yes then switch sob.
2076 	 */
2077 	rc = hl_cs_signal_sob_wraparound_handler(hdev, q_idx, &hw_sob, count,
2078 								true);
2079 	if (rc) {
2080 		dev_err(hdev->dev, "Failed to switch SOB\n");
2081 		hdev->asic_funcs->hw_queues_unlock(hdev);
2082 		rc = -EINVAL;
2083 		goto remove_idr;
2084 	}
2085 	/* set the hw_sob to the handle after calling the sob wraparound handler
2086 	 * since sob could have changed.
2087 	 */
2088 	handle->hw_sob = hw_sob;
2089 
2090 	/* store the current sob value for unreserve validity check, and
2091 	 * signal offset support
2092 	 */
2093 	handle->pre_sob_val = prop->next_sob_val - handle->count;
2094 
2095 	handle->cs_seq = ULLONG_MAX;
2096 
2097 	*signals_count = prop->next_sob_val;
2098 	hdev->asic_funcs->hw_queues_unlock(hdev);
2099 
2100 	*sob_addr = handle->hw_sob->sob_addr;
2101 	*handle_id = hdl_id;
2102 
2103 	dev_dbg(hdev->dev,
2104 		"Signals reserved, sob_id: %d, sob addr: 0x%x, last sob_val: %u, q_idx: %d, hdl_id: %d\n",
2105 			hw_sob->sob_id, handle->hw_sob->sob_addr,
2106 			prop->next_sob_val - 1, q_idx, hdl_id);
2107 	goto out;
2108 
2109 remove_idr:
2110 	spin_lock(&mgr->lock);
2111 	idr_remove(&mgr->handles, hdl_id);
2112 	spin_unlock(&mgr->lock);
2113 
2114 put_ctx:
2115 	hl_ctx_put(handle->ctx);
2116 	kfree(handle);
2117 
2118 out:
2119 	return rc;
2120 }
2121 
2122 static int cs_ioctl_unreserve_signals(struct hl_fpriv *hpriv, u32 handle_id)
2123 {
2124 	struct hl_cs_encaps_sig_handle *encaps_sig_hdl;
2125 	struct hl_sync_stream_properties *prop;
2126 	struct hl_device *hdev = hpriv->hdev;
2127 	struct hl_encaps_signals_mgr *mgr;
2128 	struct hl_hw_sob *hw_sob;
2129 	u32 q_idx, sob_addr;
2130 	int rc = 0;
2131 
2132 	mgr = &hpriv->ctx->sig_mgr;
2133 
2134 	spin_lock(&mgr->lock);
2135 	encaps_sig_hdl = idr_find(&mgr->handles, handle_id);
2136 	if (encaps_sig_hdl) {
2137 		dev_dbg(hdev->dev, "unreserve signals, handle: %u, SOB:0x%x, count: %u\n",
2138 				handle_id, encaps_sig_hdl->hw_sob->sob_addr,
2139 					encaps_sig_hdl->count);
2140 
2141 		hdev->asic_funcs->hw_queues_lock(hdev);
2142 
2143 		q_idx = encaps_sig_hdl->q_idx;
2144 		prop = &hdev->kernel_queues[q_idx].sync_stream_prop;
2145 		hw_sob = &prop->hw_sob[prop->curr_sob_offset];
2146 		sob_addr = hdev->asic_funcs->get_sob_addr(hdev, hw_sob->sob_id);
2147 
2148 		/* Check if sob_val got out of sync due to other
2149 		 * signal submission requests which were handled
2150 		 * between the reserve-unreserve calls or SOB switch
2151 		 * upon reaching SOB max value.
2152 		 */
2153 		if (encaps_sig_hdl->pre_sob_val + encaps_sig_hdl->count
2154 				!= prop->next_sob_val ||
2155 				sob_addr != encaps_sig_hdl->hw_sob->sob_addr) {
2156 			dev_err(hdev->dev, "Cannot unreserve signals, SOB val ran out of sync, expected: %u, actual val: %u\n",
2157 				encaps_sig_hdl->pre_sob_val,
2158 				(prop->next_sob_val - encaps_sig_hdl->count));
2159 
2160 			hdev->asic_funcs->hw_queues_unlock(hdev);
2161 			rc = -EINVAL;
2162 			goto out_unlock;
2163 		}
2164 
2165 		/*
2166 		 * Decrement the SOB value by count by user request
2167 		 * to unreserve those signals
2168 		 */
2169 		prop->next_sob_val -= encaps_sig_hdl->count;
2170 
2171 		hdev->asic_funcs->hw_queues_unlock(hdev);
2172 
2173 		hw_sob_put(hw_sob);
2174 
2175 		/* Release the id and free allocated memory of the handle */
2176 		idr_remove(&mgr->handles, handle_id);
2177 
2178 		/* unlock before calling ctx_put, where we might sleep */
2179 		spin_unlock(&mgr->lock);
2180 		hl_ctx_put(encaps_sig_hdl->ctx);
2181 		kfree(encaps_sig_hdl);
2182 		goto out;
2183 	} else {
2184 		rc = -EINVAL;
2185 		dev_err(hdev->dev, "failed to unreserve signals, cannot find handler\n");
2186 	}
2187 
2188 out_unlock:
2189 	spin_unlock(&mgr->lock);
2190 
2191 out:
2192 	return rc;
2193 }
2194 
2195 static int cs_ioctl_signal_wait(struct hl_fpriv *hpriv, enum hl_cs_type cs_type,
2196 				void __user *chunks, u32 num_chunks,
2197 				u64 *cs_seq, u32 flags, u32 timeout,
2198 				u32 *signal_sob_addr_offset, u16 *signal_initial_sob_count)
2199 {
2200 	struct hl_cs_encaps_sig_handle *encaps_sig_hdl = NULL;
2201 	bool handle_found = false, is_wait_cs = false,
2202 			wait_cs_submitted = false,
2203 			cs_encaps_signals = false;
2204 	struct hl_cs_chunk *cs_chunk_array, *chunk;
2205 	bool staged_cs_with_encaps_signals = false;
2206 	struct hw_queue_properties *hw_queue_prop;
2207 	struct hl_device *hdev = hpriv->hdev;
2208 	struct hl_cs_compl *sig_waitcs_cmpl;
2209 	u32 q_idx, collective_engine_id = 0;
2210 	struct hl_cs_counters_atomic *cntr;
2211 	struct hl_fence *sig_fence = NULL;
2212 	struct hl_ctx *ctx = hpriv->ctx;
2213 	enum hl_queue_type q_type;
2214 	struct hl_cs *cs;
2215 	u64 signal_seq;
2216 	int rc;
2217 
2218 	cntr = &hdev->aggregated_cs_counters;
2219 	*cs_seq = ULLONG_MAX;
2220 
2221 	rc = hl_cs_copy_chunk_array(hdev, &cs_chunk_array, chunks, num_chunks,
2222 			ctx);
2223 	if (rc)
2224 		goto out;
2225 
2226 	/* currently it is guaranteed to have only one chunk */
2227 	chunk = &cs_chunk_array[0];
2228 
2229 	if (chunk->queue_index >= hdev->asic_prop.max_queues) {
2230 		atomic64_inc(&ctx->cs_counters.validation_drop_cnt);
2231 		atomic64_inc(&cntr->validation_drop_cnt);
2232 		dev_err(hdev->dev, "Queue index %d is invalid\n",
2233 			chunk->queue_index);
2234 		rc = -EINVAL;
2235 		goto free_cs_chunk_array;
2236 	}
2237 
2238 	q_idx = chunk->queue_index;
2239 	hw_queue_prop = &hdev->asic_prop.hw_queues_props[q_idx];
2240 	q_type = hw_queue_prop->type;
2241 
2242 	if (!hw_queue_prop->supports_sync_stream) {
2243 		atomic64_inc(&ctx->cs_counters.validation_drop_cnt);
2244 		atomic64_inc(&cntr->validation_drop_cnt);
2245 		dev_err(hdev->dev,
2246 			"Queue index %d does not support sync stream operations\n",
2247 			q_idx);
2248 		rc = -EINVAL;
2249 		goto free_cs_chunk_array;
2250 	}
2251 
2252 	if (cs_type == CS_TYPE_COLLECTIVE_WAIT) {
2253 		if (!(hw_queue_prop->collective_mode == HL_COLLECTIVE_MASTER)) {
2254 			atomic64_inc(&ctx->cs_counters.validation_drop_cnt);
2255 			atomic64_inc(&cntr->validation_drop_cnt);
2256 			dev_err(hdev->dev,
2257 				"Queue index %d is invalid\n", q_idx);
2258 			rc = -EINVAL;
2259 			goto free_cs_chunk_array;
2260 		}
2261 
2262 		if (!hdev->nic_ports_mask) {
2263 			atomic64_inc(&ctx->cs_counters.validation_drop_cnt);
2264 			atomic64_inc(&cntr->validation_drop_cnt);
2265 			dev_err(hdev->dev,
2266 				"Collective operations not supported when NIC ports are disabled");
2267 			rc = -EINVAL;
2268 			goto free_cs_chunk_array;
2269 		}
2270 
2271 		collective_engine_id = chunk->collective_engine_id;
2272 	}
2273 
2274 	is_wait_cs = !!(cs_type == CS_TYPE_WAIT ||
2275 			cs_type == CS_TYPE_COLLECTIVE_WAIT);
2276 
2277 	cs_encaps_signals = !!(flags & HL_CS_FLAGS_ENCAP_SIGNALS);
2278 
2279 	if (is_wait_cs) {
2280 		rc = cs_ioctl_extract_signal_seq(hdev, chunk, &signal_seq,
2281 				ctx, cs_encaps_signals);
2282 		if (rc)
2283 			goto free_cs_chunk_array;
2284 
2285 		if (cs_encaps_signals) {
2286 			/* check if cs sequence has encapsulated
2287 			 * signals handle
2288 			 */
2289 			struct idr *idp;
2290 			u32 id;
2291 
2292 			spin_lock(&ctx->sig_mgr.lock);
2293 			idp = &ctx->sig_mgr.handles;
2294 			idr_for_each_entry(idp, encaps_sig_hdl, id) {
2295 				if (encaps_sig_hdl->cs_seq == signal_seq) {
2296 					/* get refcount to protect removing this handle from idr,
2297 					 * needed when multiple wait cs are used with offset
2298 					 * to wait on reserved encaps signals.
2299 					 * Since kref_put of this handle is executed outside the
2300 					 * current lock, it is possible that the handle refcount
2301 					 * is 0 but it yet to be removed from the list. In this
2302 					 * case need to consider the handle as not valid.
2303 					 */
2304 					if (kref_get_unless_zero(&encaps_sig_hdl->refcount))
2305 						handle_found = true;
2306 					break;
2307 				}
2308 			}
2309 			spin_unlock(&ctx->sig_mgr.lock);
2310 
2311 			if (!handle_found) {
2312 				/* treat as signal CS already finished */
2313 				dev_dbg(hdev->dev, "Cannot find encapsulated signals handle for seq 0x%llx\n",
2314 						signal_seq);
2315 				rc = 0;
2316 				goto free_cs_chunk_array;
2317 			}
2318 
2319 			/* validate also the signal offset value */
2320 			if (chunk->encaps_signal_offset >
2321 					encaps_sig_hdl->count) {
2322 				dev_err(hdev->dev, "offset(%u) value exceed max reserved signals count(%u)!\n",
2323 						chunk->encaps_signal_offset,
2324 						encaps_sig_hdl->count);
2325 				rc = -EINVAL;
2326 				goto free_cs_chunk_array;
2327 			}
2328 		}
2329 
2330 		sig_fence = hl_ctx_get_fence(ctx, signal_seq);
2331 		if (IS_ERR(sig_fence)) {
2332 			atomic64_inc(&ctx->cs_counters.validation_drop_cnt);
2333 			atomic64_inc(&cntr->validation_drop_cnt);
2334 			dev_err(hdev->dev,
2335 				"Failed to get signal CS with seq 0x%llx\n",
2336 				signal_seq);
2337 			rc = PTR_ERR(sig_fence);
2338 			goto free_cs_chunk_array;
2339 		}
2340 
2341 		if (!sig_fence) {
2342 			/* signal CS already finished */
2343 			rc = 0;
2344 			goto free_cs_chunk_array;
2345 		}
2346 
2347 		sig_waitcs_cmpl =
2348 			container_of(sig_fence, struct hl_cs_compl, base_fence);
2349 
2350 		staged_cs_with_encaps_signals = !!
2351 				(sig_waitcs_cmpl->type == CS_TYPE_DEFAULT &&
2352 				(flags & HL_CS_FLAGS_ENCAP_SIGNALS));
2353 
2354 		if (sig_waitcs_cmpl->type != CS_TYPE_SIGNAL &&
2355 				!staged_cs_with_encaps_signals) {
2356 			atomic64_inc(&ctx->cs_counters.validation_drop_cnt);
2357 			atomic64_inc(&cntr->validation_drop_cnt);
2358 			dev_err(hdev->dev,
2359 				"CS seq 0x%llx is not of a signal/encaps-signal CS\n",
2360 				signal_seq);
2361 			hl_fence_put(sig_fence);
2362 			rc = -EINVAL;
2363 			goto free_cs_chunk_array;
2364 		}
2365 
2366 		if (completion_done(&sig_fence->completion)) {
2367 			/* signal CS already finished */
2368 			hl_fence_put(sig_fence);
2369 			rc = 0;
2370 			goto free_cs_chunk_array;
2371 		}
2372 	}
2373 
2374 	rc = allocate_cs(hdev, ctx, cs_type, ULLONG_MAX, &cs, flags, timeout);
2375 	if (rc) {
2376 		if (is_wait_cs)
2377 			hl_fence_put(sig_fence);
2378 
2379 		goto free_cs_chunk_array;
2380 	}
2381 
2382 	/*
2383 	 * Save the signal CS fence for later initialization right before
2384 	 * hanging the wait CS on the queue.
2385 	 * for encaps signals case, we save the cs sequence and handle pointer
2386 	 * for later initialization.
2387 	 */
2388 	if (is_wait_cs) {
2389 		cs->signal_fence = sig_fence;
2390 		/* store the handle pointer, so we don't have to
2391 		 * look for it again, later on the flow
2392 		 * when we need to set SOB info in hw_queue.
2393 		 */
2394 		if (cs->encaps_signals)
2395 			cs->encaps_sig_hdl = encaps_sig_hdl;
2396 	}
2397 
2398 	hl_debugfs_add_cs(cs);
2399 
2400 	*cs_seq = cs->sequence;
2401 
2402 	if (cs_type == CS_TYPE_WAIT || cs_type == CS_TYPE_SIGNAL)
2403 		rc = cs_ioctl_signal_wait_create_jobs(hdev, ctx, cs, q_type,
2404 				q_idx, chunk->encaps_signal_offset);
2405 	else if (cs_type == CS_TYPE_COLLECTIVE_WAIT)
2406 		rc = hdev->asic_funcs->collective_wait_create_jobs(hdev, ctx,
2407 				cs, q_idx, collective_engine_id,
2408 				chunk->encaps_signal_offset);
2409 	else {
2410 		atomic64_inc(&ctx->cs_counters.validation_drop_cnt);
2411 		atomic64_inc(&cntr->validation_drop_cnt);
2412 		rc = -EINVAL;
2413 	}
2414 
2415 	if (rc)
2416 		goto free_cs_object;
2417 
2418 	if (q_type == QUEUE_TYPE_HW)
2419 		INIT_WORK(&cs->finish_work, cs_completion);
2420 
2421 	rc = hl_hw_queue_schedule_cs(cs);
2422 	if (rc) {
2423 		/* In case wait cs failed here, it means the signal cs
2424 		 * already completed. we want to free all it's related objects
2425 		 * but we don't want to fail the ioctl.
2426 		 */
2427 		if (is_wait_cs)
2428 			rc = 0;
2429 		else if (rc != -EAGAIN)
2430 			dev_err(hdev->dev,
2431 				"Failed to submit CS %d.%llu to H/W queues, error %d\n",
2432 				ctx->asid, cs->sequence, rc);
2433 		goto free_cs_object;
2434 	}
2435 
2436 	*signal_sob_addr_offset = cs->sob_addr_offset;
2437 	*signal_initial_sob_count = cs->initial_sob_count;
2438 
2439 	rc = HL_CS_STATUS_SUCCESS;
2440 	if (is_wait_cs)
2441 		wait_cs_submitted = true;
2442 	goto put_cs;
2443 
2444 free_cs_object:
2445 	cs_rollback(hdev, cs);
2446 	*cs_seq = ULLONG_MAX;
2447 	/* The path below is both for good and erroneous exits */
2448 put_cs:
2449 	/* We finished with the CS in this function, so put the ref */
2450 	cs_put(cs);
2451 free_cs_chunk_array:
2452 	if (!wait_cs_submitted && cs_encaps_signals && handle_found && is_wait_cs)
2453 		kref_put(&encaps_sig_hdl->refcount, hl_encaps_release_handle_and_put_ctx);
2454 	kfree(cs_chunk_array);
2455 out:
2456 	return rc;
2457 }
2458 
2459 static int cs_ioctl_engine_cores(struct hl_fpriv *hpriv, u64 engine_cores,
2460 						u32 num_engine_cores, u32 core_command)
2461 {
2462 	struct hl_device *hdev = hpriv->hdev;
2463 	void __user *engine_cores_arr;
2464 	u32 *cores;
2465 	int rc;
2466 
2467 	if (!hdev->asic_prop.supports_engine_modes)
2468 		return -EPERM;
2469 
2470 	if (!num_engine_cores || num_engine_cores > hdev->asic_prop.num_engine_cores) {
2471 		dev_err(hdev->dev, "Number of engine cores %d is invalid\n", num_engine_cores);
2472 		return -EINVAL;
2473 	}
2474 
2475 	if (core_command != HL_ENGINE_CORE_RUN && core_command != HL_ENGINE_CORE_HALT) {
2476 		dev_err(hdev->dev, "Engine core command is invalid\n");
2477 		return -EINVAL;
2478 	}
2479 
2480 	engine_cores_arr = (void __user *) (uintptr_t) engine_cores;
2481 	cores = kmalloc_objs(u32, num_engine_cores);
2482 	if (!cores)
2483 		return -ENOMEM;
2484 
2485 	if (copy_from_user(cores, engine_cores_arr, num_engine_cores * sizeof(u32))) {
2486 		dev_err(hdev->dev, "Failed to copy core-ids array from user\n");
2487 		kfree(cores);
2488 		return -EFAULT;
2489 	}
2490 
2491 	rc = hdev->asic_funcs->set_engine_cores(hdev, cores, num_engine_cores, core_command);
2492 	kfree(cores);
2493 
2494 	return rc;
2495 }
2496 
2497 static int cs_ioctl_engines(struct hl_fpriv *hpriv, u64 engines_arr_user_addr,
2498 						u32 num_engines, enum hl_engine_command command)
2499 {
2500 	struct hl_device *hdev = hpriv->hdev;
2501 	u32 *engines, max_num_of_engines;
2502 	void __user *engines_arr;
2503 	int rc;
2504 
2505 	if (!hdev->asic_prop.supports_engine_modes)
2506 		return -EPERM;
2507 
2508 	if (command >= HL_ENGINE_COMMAND_MAX) {
2509 		dev_err(hdev->dev, "Engine command is invalid\n");
2510 		return -EINVAL;
2511 	}
2512 
2513 	max_num_of_engines = hdev->asic_prop.max_num_of_engines;
2514 	if (command == HL_ENGINE_CORE_RUN || command == HL_ENGINE_CORE_HALT)
2515 		max_num_of_engines = hdev->asic_prop.num_engine_cores;
2516 
2517 	if (!num_engines || num_engines > max_num_of_engines) {
2518 		dev_err(hdev->dev, "Number of engines %d is invalid\n", num_engines);
2519 		return -EINVAL;
2520 	}
2521 
2522 	engines_arr = (void __user *) (uintptr_t) engines_arr_user_addr;
2523 	engines = kmalloc_objs(u32, num_engines);
2524 	if (!engines)
2525 		return -ENOMEM;
2526 
2527 	if (copy_from_user(engines, engines_arr, num_engines * sizeof(u32))) {
2528 		dev_err(hdev->dev, "Failed to copy engine-ids array from user\n");
2529 		kfree(engines);
2530 		return -EFAULT;
2531 	}
2532 
2533 	rc = hdev->asic_funcs->set_engines(hdev, engines, num_engines, command);
2534 	kfree(engines);
2535 
2536 	return rc;
2537 }
2538 
2539 static int cs_ioctl_flush_pci_hbw_writes(struct hl_fpriv *hpriv)
2540 {
2541 	struct hl_device *hdev = hpriv->hdev;
2542 	struct asic_fixed_properties *prop = &hdev->asic_prop;
2543 
2544 	if (!prop->hbw_flush_reg) {
2545 		dev_dbg(hdev->dev, "HBW flush is not supported\n");
2546 		return -EOPNOTSUPP;
2547 	}
2548 
2549 	RREG32(prop->hbw_flush_reg);
2550 
2551 	return 0;
2552 }
2553 
2554 int hl_cs_ioctl(struct drm_device *ddev, void *data, struct drm_file *file_priv)
2555 {
2556 	struct hl_fpriv *hpriv = file_priv->driver_priv;
2557 	union hl_cs_args *args = data;
2558 	enum hl_cs_type cs_type = 0;
2559 	u64 cs_seq = ULONG_MAX;
2560 	void __user *chunks;
2561 	u32 num_chunks, flags, timeout,
2562 		signals_count = 0, sob_addr = 0, handle_id = 0;
2563 	u16 sob_initial_count = 0;
2564 	int rc;
2565 
2566 	rc = hl_cs_sanity_checks(hpriv, args);
2567 	if (rc)
2568 		goto out;
2569 
2570 	rc = hl_cs_ctx_switch(hpriv, args, &cs_seq);
2571 	if (rc)
2572 		goto out;
2573 
2574 	cs_type = hl_cs_get_cs_type(args->in.cs_flags &
2575 					~HL_CS_FLAGS_FORCE_RESTORE);
2576 	chunks = (void __user *) (uintptr_t) args->in.chunks_execute;
2577 	num_chunks = args->in.num_chunks_execute;
2578 	flags = args->in.cs_flags;
2579 
2580 	/* In case this is a staged CS, user should supply the CS sequence */
2581 	if ((flags & HL_CS_FLAGS_STAGED_SUBMISSION) &&
2582 			!(flags & HL_CS_FLAGS_STAGED_SUBMISSION_FIRST))
2583 		cs_seq = args->in.seq;
2584 
2585 	timeout = flags & HL_CS_FLAGS_CUSTOM_TIMEOUT
2586 			? secs_to_jiffies(args->in.timeout)
2587 			: hpriv->hdev->timeout_jiffies;
2588 
2589 	switch (cs_type) {
2590 	case CS_TYPE_SIGNAL:
2591 	case CS_TYPE_WAIT:
2592 	case CS_TYPE_COLLECTIVE_WAIT:
2593 		rc = cs_ioctl_signal_wait(hpriv, cs_type, chunks, num_chunks,
2594 					&cs_seq, args->in.cs_flags, timeout,
2595 					&sob_addr, &sob_initial_count);
2596 		break;
2597 	case CS_RESERVE_SIGNALS:
2598 		rc = cs_ioctl_reserve_signals(hpriv,
2599 					args->in.encaps_signals_q_idx,
2600 					args->in.encaps_signals_count,
2601 					&handle_id, &sob_addr, &signals_count);
2602 		break;
2603 	case CS_UNRESERVE_SIGNALS:
2604 		rc = cs_ioctl_unreserve_signals(hpriv,
2605 					args->in.encaps_sig_handle_id);
2606 		break;
2607 	case CS_TYPE_ENGINE_CORE:
2608 		rc = cs_ioctl_engine_cores(hpriv, args->in.engine_cores,
2609 				args->in.num_engine_cores, args->in.core_command);
2610 		break;
2611 	case CS_TYPE_ENGINES:
2612 		rc = cs_ioctl_engines(hpriv, args->in.engines,
2613 				args->in.num_engines, args->in.engine_command);
2614 		break;
2615 	case CS_TYPE_FLUSH_PCI_HBW_WRITES:
2616 		rc = cs_ioctl_flush_pci_hbw_writes(hpriv);
2617 		break;
2618 	default:
2619 		rc = cs_ioctl_default(hpriv, chunks, num_chunks, &cs_seq,
2620 						args->in.cs_flags,
2621 						args->in.encaps_sig_handle_id,
2622 						timeout, &sob_initial_count);
2623 		break;
2624 	}
2625 out:
2626 	if (rc != -EAGAIN) {
2627 		memset(args, 0, sizeof(*args));
2628 
2629 		switch (cs_type) {
2630 		case CS_RESERVE_SIGNALS:
2631 			args->out.handle_id = handle_id;
2632 			args->out.sob_base_addr_offset = sob_addr;
2633 			args->out.count = signals_count;
2634 			break;
2635 		case CS_TYPE_SIGNAL:
2636 			args->out.sob_base_addr_offset = sob_addr;
2637 			args->out.sob_count_before_submission = sob_initial_count;
2638 			args->out.seq = cs_seq;
2639 			break;
2640 		case CS_TYPE_DEFAULT:
2641 			args->out.sob_count_before_submission = sob_initial_count;
2642 			args->out.seq = cs_seq;
2643 			break;
2644 		default:
2645 			args->out.seq = cs_seq;
2646 			break;
2647 		}
2648 
2649 		args->out.status = rc;
2650 	}
2651 
2652 	return rc;
2653 }
2654 
2655 static int hl_wait_for_fence(struct hl_ctx *ctx, u64 seq, struct hl_fence *fence,
2656 				enum hl_cs_wait_status *status, u64 timeout_us, s64 *timestamp)
2657 {
2658 	struct hl_device *hdev = ctx->hdev;
2659 	ktime_t timestamp_kt;
2660 	long completion_rc;
2661 	int rc = 0, error;
2662 
2663 	if (IS_ERR(fence)) {
2664 		rc = PTR_ERR(fence);
2665 		if (rc == -EINVAL)
2666 			dev_notice_ratelimited(hdev->dev,
2667 				"Can't wait on CS %llu because current CS is at seq %llu\n",
2668 				seq, ctx->cs_sequence);
2669 		return rc;
2670 	}
2671 
2672 	if (!fence) {
2673 		if (!hl_pop_cs_outcome(&ctx->outcome_store, seq, &timestamp_kt, &error)) {
2674 			dev_dbg(hdev->dev,
2675 				"Can't wait on seq %llu because current CS is at seq %llu (Fence is gone)\n",
2676 				seq, ctx->cs_sequence);
2677 			*status = CS_WAIT_STATUS_GONE;
2678 			return 0;
2679 		}
2680 
2681 		completion_rc = 1;
2682 		goto report_results;
2683 	}
2684 
2685 	if (!timeout_us) {
2686 		completion_rc = completion_done(&fence->completion);
2687 	} else {
2688 		unsigned long timeout;
2689 
2690 		timeout = (timeout_us == MAX_SCHEDULE_TIMEOUT) ?
2691 				timeout_us : usecs_to_jiffies(timeout_us);
2692 		completion_rc =
2693 			wait_for_completion_interruptible_timeout(
2694 				&fence->completion, timeout);
2695 	}
2696 
2697 	error = fence->error;
2698 	timestamp_kt = fence->timestamp;
2699 
2700 report_results:
2701 	if (completion_rc > 0) {
2702 		*status = CS_WAIT_STATUS_COMPLETED;
2703 		if (timestamp)
2704 			*timestamp = ktime_to_ns(timestamp_kt);
2705 	} else {
2706 		*status = CS_WAIT_STATUS_BUSY;
2707 	}
2708 
2709 	if (completion_rc == -ERESTARTSYS)
2710 		rc = completion_rc;
2711 	else if (error == -ETIMEDOUT || error == -EIO)
2712 		rc = error;
2713 
2714 	return rc;
2715 }
2716 
2717 /*
2718  * hl_cs_poll_fences - iterate CS fences to check for CS completion
2719  *
2720  * @mcs_data: multi-CS internal data
2721  * @mcs_compl: multi-CS completion structure
2722  *
2723  * @return 0 on success, otherwise non 0 error code
2724  *
2725  * The function iterates on all CS sequence in the list and set bit in
2726  * completion_bitmap for each completed CS.
2727  * While iterating, the function sets the stream map of each fence in the fence
2728  * array in the completion QID stream map to be used by CSs to perform
2729  * completion to the multi-CS context.
2730  * This function shall be called after taking context ref
2731  */
2732 static int hl_cs_poll_fences(struct multi_cs_data *mcs_data, struct multi_cs_completion *mcs_compl)
2733 {
2734 	struct hl_fence **fence_ptr = mcs_data->fence_arr;
2735 	struct hl_device *hdev = mcs_data->ctx->hdev;
2736 	int i, rc, arr_len = mcs_data->arr_len;
2737 	u64 *seq_arr = mcs_data->seq_arr;
2738 	ktime_t max_ktime, first_cs_time;
2739 	enum hl_cs_wait_status status;
2740 
2741 	memset(fence_ptr, 0, arr_len * sizeof(struct hl_fence *));
2742 
2743 	/* get all fences under the same lock */
2744 	rc = hl_ctx_get_fences(mcs_data->ctx, seq_arr, fence_ptr, arr_len);
2745 	if (rc)
2746 		return rc;
2747 
2748 	/*
2749 	 * re-initialize the completion here to handle 2 possible cases:
2750 	 * 1. CS will complete the multi-CS prior clearing the completion. in which
2751 	 *    case the fence iteration is guaranteed to catch the CS completion.
2752 	 * 2. the completion will occur after re-init of the completion.
2753 	 *    in which case we will wake up immediately in wait_for_completion.
2754 	 */
2755 	reinit_completion(&mcs_compl->completion);
2756 
2757 	/*
2758 	 * set to maximum time to verify timestamp is valid: if at the end
2759 	 * this value is maintained- no timestamp was updated
2760 	 */
2761 	max_ktime = ktime_set(KTIME_SEC_MAX, 0);
2762 	first_cs_time = max_ktime;
2763 
2764 	for (i = 0; i < arr_len; i++, fence_ptr++) {
2765 		struct hl_fence *fence = *fence_ptr;
2766 
2767 		/*
2768 		 * In order to prevent case where we wait until timeout even though a CS associated
2769 		 * with the multi-CS actually completed we do things in the below order:
2770 		 * 1. for each fence set it's QID map in the multi-CS completion QID map. This way
2771 		 *    any CS can, potentially, complete the multi CS for the specific QID (note
2772 		 *    that once completion is initialized, calling complete* and then wait on the
2773 		 *    completion will cause it to return at once)
2774 		 * 2. only after allowing multi-CS completion for the specific QID we check whether
2775 		 *    the specific CS already completed (and thus the wait for completion part will
2776 		 *    be skipped). if the CS not completed it is guaranteed that completing CS will
2777 		 *    wake up the completion.
2778 		 */
2779 		if (fence)
2780 			mcs_compl->stream_master_qid_map |= fence->stream_master_qid_map;
2781 
2782 		/*
2783 		 * function won't sleep as it is called with timeout 0 (i.e.
2784 		 * poll the fence)
2785 		 */
2786 		rc = hl_wait_for_fence(mcs_data->ctx, seq_arr[i], fence, &status, 0, NULL);
2787 		if (rc) {
2788 			dev_err(hdev->dev,
2789 				"wait_for_fence error :%d for CS seq %llu\n",
2790 								rc, seq_arr[i]);
2791 			break;
2792 		}
2793 
2794 		switch (status) {
2795 		case CS_WAIT_STATUS_BUSY:
2796 			/* CS did not finished, QID to wait on already stored */
2797 			break;
2798 		case CS_WAIT_STATUS_COMPLETED:
2799 			/*
2800 			 * Using mcs_handling_done to avoid possibility of mcs_data
2801 			 * returns to user indicating CS completed before it finished
2802 			 * all of its mcs handling, to avoid race the next time the
2803 			 * user waits for mcs.
2804 			 * note: when reaching this case fence is definitely not NULL
2805 			 *       but NULL check was added to overcome static analysis
2806 			 */
2807 			if (fence && !fence->mcs_handling_done) {
2808 				/*
2809 				 * in case multi CS is completed but MCS handling not done
2810 				 * we "complete" the multi CS to prevent it from waiting
2811 				 * until time-out and the "multi-CS handling done" will have
2812 				 * another chance at the next iteration
2813 				 */
2814 				complete_all(&mcs_compl->completion);
2815 				break;
2816 			}
2817 
2818 			mcs_data->completion_bitmap |= BIT(i);
2819 			/*
2820 			 * For all completed CSs we take the earliest timestamp.
2821 			 * For this we have to validate that the timestamp is
2822 			 * earliest of all timestamps so far.
2823 			 */
2824 			if (fence && mcs_data->update_ts &&
2825 					(ktime_compare(fence->timestamp, first_cs_time) < 0))
2826 				first_cs_time = fence->timestamp;
2827 			break;
2828 		case CS_WAIT_STATUS_GONE:
2829 			mcs_data->update_ts = false;
2830 			mcs_data->gone_cs = true;
2831 			/*
2832 			 * It is possible to get an old sequence numbers from user
2833 			 * which related to already completed CSs and their fences
2834 			 * already gone. In this case, CS set as completed but
2835 			 * no need to consider its QID for mcs completion.
2836 			 */
2837 			mcs_data->completion_bitmap |= BIT(i);
2838 			break;
2839 		default:
2840 			dev_err(hdev->dev, "Invalid fence status\n");
2841 			rc = -EINVAL;
2842 			break;
2843 		}
2844 
2845 	}
2846 
2847 	hl_fences_put(mcs_data->fence_arr, arr_len);
2848 
2849 	if (mcs_data->update_ts &&
2850 			(ktime_compare(first_cs_time, max_ktime) != 0))
2851 		mcs_data->timestamp = ktime_to_ns(first_cs_time);
2852 
2853 	return rc;
2854 }
2855 
2856 static int _hl_cs_wait_ioctl(struct hl_device *hdev, struct hl_ctx *ctx, u64 timeout_us, u64 seq,
2857 				enum hl_cs_wait_status *status, s64 *timestamp)
2858 {
2859 	struct hl_fence *fence;
2860 	int rc = 0;
2861 
2862 	if (timestamp)
2863 		*timestamp = 0;
2864 
2865 	hl_ctx_get(ctx);
2866 
2867 	fence = hl_ctx_get_fence(ctx, seq);
2868 
2869 	rc = hl_wait_for_fence(ctx, seq, fence, status, timeout_us, timestamp);
2870 	hl_fence_put(fence);
2871 	hl_ctx_put(ctx);
2872 
2873 	return rc;
2874 }
2875 
2876 static inline unsigned long hl_usecs64_to_jiffies(const u64 usecs)
2877 {
2878 	if (usecs <= U32_MAX)
2879 		return usecs_to_jiffies(usecs);
2880 
2881 	/*
2882 	 * If the value in nanoseconds is larger than 64 bit, use the largest
2883 	 * 64 bit value.
2884 	 */
2885 	if (usecs >= ((u64)(U64_MAX / NSEC_PER_USEC)))
2886 		return nsecs_to_jiffies(U64_MAX);
2887 
2888 	return nsecs_to_jiffies(usecs * NSEC_PER_USEC);
2889 }
2890 
2891 /*
2892  * hl_wait_multi_cs_completion_init - init completion structure
2893  *
2894  * @hdev: pointer to habanalabs device structure
2895  * @stream_master_bitmap: stream master QIDs map, set bit indicates stream
2896  *                        master QID to wait on
2897  *
2898  * @return valid completion struct pointer on success, otherwise error pointer
2899  *
2900  * up to MULTI_CS_MAX_USER_CTX calls can be done concurrently to the driver.
2901  * the function gets the first available completion (by marking it "used")
2902  * and initialize its values.
2903  */
2904 static struct multi_cs_completion *hl_wait_multi_cs_completion_init(struct hl_device *hdev)
2905 {
2906 	struct multi_cs_completion *mcs_compl;
2907 	int i;
2908 
2909 	/* find free multi_cs completion structure */
2910 	for (i = 0; i < MULTI_CS_MAX_USER_CTX; i++) {
2911 		mcs_compl = &hdev->multi_cs_completion[i];
2912 		spin_lock(&mcs_compl->lock);
2913 		if (!mcs_compl->used) {
2914 			mcs_compl->used = 1;
2915 			mcs_compl->timestamp = 0;
2916 			/*
2917 			 * init QID map to 0 to avoid completion by CSs. the actual QID map
2918 			 * to multi-CS CSs will be set incrementally at a later stage
2919 			 */
2920 			mcs_compl->stream_master_qid_map = 0;
2921 			spin_unlock(&mcs_compl->lock);
2922 			break;
2923 		}
2924 		spin_unlock(&mcs_compl->lock);
2925 	}
2926 
2927 	if (i == MULTI_CS_MAX_USER_CTX) {
2928 		dev_err(hdev->dev, "no available multi-CS completion structure\n");
2929 		return ERR_PTR(-ENOMEM);
2930 	}
2931 	return mcs_compl;
2932 }
2933 
2934 /*
2935  * hl_wait_multi_cs_completion_fini - return completion structure and set as
2936  *                                    unused
2937  *
2938  * @mcs_compl: pointer to the completion structure
2939  */
2940 static void hl_wait_multi_cs_completion_fini(
2941 					struct multi_cs_completion *mcs_compl)
2942 {
2943 	/*
2944 	 * free completion structure, do it under lock to be in-sync with the
2945 	 * thread that signals completion
2946 	 */
2947 	spin_lock(&mcs_compl->lock);
2948 	mcs_compl->used = 0;
2949 	spin_unlock(&mcs_compl->lock);
2950 }
2951 
2952 /*
2953  * hl_wait_multi_cs_completion - wait for first CS to complete
2954  *
2955  * @mcs_data: multi-CS internal data
2956  *
2957  * @return 0 on success, otherwise non 0 error code
2958  */
2959 static int hl_wait_multi_cs_completion(struct multi_cs_data *mcs_data,
2960 						struct multi_cs_completion *mcs_compl)
2961 {
2962 	long completion_rc;
2963 
2964 	completion_rc = wait_for_completion_interruptible_timeout(&mcs_compl->completion,
2965 									mcs_data->timeout_jiffies);
2966 
2967 	/* update timestamp */
2968 	if (completion_rc > 0)
2969 		mcs_data->timestamp = mcs_compl->timestamp;
2970 
2971 	if (completion_rc == -ERESTARTSYS)
2972 		return completion_rc;
2973 
2974 	mcs_data->wait_status = completion_rc;
2975 
2976 	return 0;
2977 }
2978 
2979 /*
2980  * hl_multi_cs_completion_init - init array of multi-CS completion structures
2981  *
2982  * @hdev: pointer to habanalabs device structure
2983  */
2984 void hl_multi_cs_completion_init(struct hl_device *hdev)
2985 {
2986 	struct multi_cs_completion *mcs_cmpl;
2987 	int i;
2988 
2989 	for (i = 0; i < MULTI_CS_MAX_USER_CTX; i++) {
2990 		mcs_cmpl = &hdev->multi_cs_completion[i];
2991 		mcs_cmpl->used = 0;
2992 		spin_lock_init(&mcs_cmpl->lock);
2993 		init_completion(&mcs_cmpl->completion);
2994 	}
2995 }
2996 
2997 /*
2998  * hl_multi_cs_wait_ioctl - implementation of the multi-CS wait ioctl
2999  *
3000  * @hpriv: pointer to the private data of the fd
3001  * @data: pointer to multi-CS wait ioctl in/out args
3002  *
3003  */
3004 static int hl_multi_cs_wait_ioctl(struct hl_fpriv *hpriv, void *data)
3005 {
3006 	struct multi_cs_completion *mcs_compl;
3007 	struct hl_device *hdev = hpriv->hdev;
3008 	struct multi_cs_data mcs_data = {};
3009 	union hl_wait_cs_args *args = data;
3010 	struct hl_ctx *ctx = hpriv->ctx;
3011 	struct hl_fence **fence_arr;
3012 	void __user *seq_arr;
3013 	u32 size_to_copy;
3014 	u64 *cs_seq_arr;
3015 	u8 seq_arr_len;
3016 	int rc, i;
3017 
3018 	for (i = 0 ; i < sizeof(args->in.pad) ; i++)
3019 		if (args->in.pad[i]) {
3020 			dev_dbg(hdev->dev, "Padding bytes must be 0\n");
3021 			return -EINVAL;
3022 		}
3023 
3024 	if (!hdev->supports_wait_for_multi_cs) {
3025 		dev_err(hdev->dev, "Wait for multi CS is not supported\n");
3026 		return -EPERM;
3027 	}
3028 
3029 	seq_arr_len = args->in.seq_arr_len;
3030 
3031 	if (seq_arr_len > HL_WAIT_MULTI_CS_LIST_MAX_LEN) {
3032 		dev_err(hdev->dev, "Can wait only up to %d CSs, input sequence is of length %u\n",
3033 				HL_WAIT_MULTI_CS_LIST_MAX_LEN, seq_arr_len);
3034 		return -EINVAL;
3035 	}
3036 
3037 	/* allocate memory for sequence array */
3038 	cs_seq_arr =
3039 		kmalloc_objs(*cs_seq_arr, seq_arr_len);
3040 	if (!cs_seq_arr)
3041 		return -ENOMEM;
3042 
3043 	/* copy CS sequence array from user */
3044 	seq_arr = (void __user *) (uintptr_t) args->in.seq;
3045 	size_to_copy = seq_arr_len * sizeof(*cs_seq_arr);
3046 	if (copy_from_user(cs_seq_arr, seq_arr, size_to_copy)) {
3047 		dev_err(hdev->dev, "Failed to copy multi-cs sequence array from user\n");
3048 		rc = -EFAULT;
3049 		goto free_seq_arr;
3050 	}
3051 
3052 	/* allocate array for the fences */
3053 	fence_arr = kmalloc_objs(struct hl_fence *, seq_arr_len);
3054 	if (!fence_arr) {
3055 		rc = -ENOMEM;
3056 		goto free_seq_arr;
3057 	}
3058 
3059 	/* initialize the multi-CS internal data */
3060 	mcs_data.ctx = ctx;
3061 	mcs_data.seq_arr = cs_seq_arr;
3062 	mcs_data.fence_arr = fence_arr;
3063 	mcs_data.arr_len = seq_arr_len;
3064 
3065 	hl_ctx_get(ctx);
3066 
3067 	/* wait (with timeout) for the first CS to be completed */
3068 	mcs_data.timeout_jiffies = hl_usecs64_to_jiffies(args->in.timeout_us);
3069 	mcs_compl = hl_wait_multi_cs_completion_init(hdev);
3070 	if (IS_ERR(mcs_compl)) {
3071 		rc = PTR_ERR(mcs_compl);
3072 		goto put_ctx;
3073 	}
3074 
3075 	/* poll all CS fences, extract timestamp */
3076 	mcs_data.update_ts = true;
3077 	rc = hl_cs_poll_fences(&mcs_data, mcs_compl);
3078 	/*
3079 	 * skip wait for CS completion when one of the below is true:
3080 	 * - an error on the poll function
3081 	 * - one or more CS in the list completed
3082 	 * - the user called ioctl with timeout 0
3083 	 */
3084 	if (rc || mcs_data.completion_bitmap || !args->in.timeout_us)
3085 		goto completion_fini;
3086 
3087 	while (true) {
3088 		rc = hl_wait_multi_cs_completion(&mcs_data, mcs_compl);
3089 		if (rc || (mcs_data.wait_status == 0))
3090 			break;
3091 
3092 		/*
3093 		 * poll fences once again to update the CS map.
3094 		 * no timestamp should be updated this time.
3095 		 */
3096 		mcs_data.update_ts = false;
3097 		rc = hl_cs_poll_fences(&mcs_data, mcs_compl);
3098 
3099 		if (rc || mcs_data.completion_bitmap)
3100 			break;
3101 
3102 		/*
3103 		 * if hl_wait_multi_cs_completion returned before timeout (i.e.
3104 		 * it got a completion) it either got completed by CS in the multi CS list
3105 		 * (in which case the indication will be non empty completion_bitmap) or it
3106 		 * got completed by CS submitted to one of the shared stream master but
3107 		 * not in the multi CS list (in which case we should wait again but modify
3108 		 * the timeout and set timestamp as zero to let a CS related to the current
3109 		 * multi-CS set a new, relevant, timestamp)
3110 		 */
3111 		mcs_data.timeout_jiffies = mcs_data.wait_status;
3112 		mcs_compl->timestamp = 0;
3113 	}
3114 
3115 completion_fini:
3116 	hl_wait_multi_cs_completion_fini(mcs_compl);
3117 
3118 put_ctx:
3119 	hl_ctx_put(ctx);
3120 	kfree(fence_arr);
3121 
3122 free_seq_arr:
3123 	kfree(cs_seq_arr);
3124 
3125 	if (rc == -ERESTARTSYS) {
3126 		dev_err_ratelimited(hdev->dev,
3127 				"user process got signal while waiting for Multi-CS\n");
3128 		rc = -EINTR;
3129 	}
3130 
3131 	if (rc)
3132 		return rc;
3133 
3134 	/* update output args */
3135 	memset(args, 0, sizeof(*args));
3136 
3137 	if (mcs_data.completion_bitmap) {
3138 		args->out.status = HL_WAIT_CS_STATUS_COMPLETED;
3139 		args->out.cs_completion_map = mcs_data.completion_bitmap;
3140 
3141 		/* if timestamp not 0- it's valid */
3142 		if (mcs_data.timestamp) {
3143 			args->out.timestamp_nsec = mcs_data.timestamp;
3144 			args->out.flags |= HL_WAIT_CS_STATUS_FLAG_TIMESTAMP_VLD;
3145 		}
3146 
3147 		/* update if some CS was gone */
3148 		if (!mcs_data.timestamp)
3149 			args->out.flags |= HL_WAIT_CS_STATUS_FLAG_GONE;
3150 	} else {
3151 		args->out.status = HL_WAIT_CS_STATUS_BUSY;
3152 	}
3153 
3154 	return 0;
3155 }
3156 
3157 static int hl_cs_wait_ioctl(struct hl_fpriv *hpriv, void *data)
3158 {
3159 	struct hl_device *hdev = hpriv->hdev;
3160 	union hl_wait_cs_args *args = data;
3161 	enum hl_cs_wait_status status;
3162 	u64 seq = args->in.seq;
3163 	s64 timestamp;
3164 	int rc;
3165 
3166 	rc = _hl_cs_wait_ioctl(hdev, hpriv->ctx, args->in.timeout_us, seq, &status, &timestamp);
3167 
3168 	if (rc == -ERESTARTSYS) {
3169 		dev_err_ratelimited(hdev->dev,
3170 			"user process got signal while waiting for CS handle %llu\n",
3171 			seq);
3172 		return -EINTR;
3173 	}
3174 
3175 	memset(args, 0, sizeof(*args));
3176 
3177 	if (rc) {
3178 		if (rc == -ETIMEDOUT) {
3179 			dev_err_ratelimited(hdev->dev,
3180 				"CS %llu has timed-out while user process is waiting for it\n",
3181 				seq);
3182 			args->out.status = HL_WAIT_CS_STATUS_TIMEDOUT;
3183 		} else if (rc == -EIO) {
3184 			dev_err_ratelimited(hdev->dev,
3185 				"CS %llu has been aborted while user process is waiting for it\n",
3186 				seq);
3187 			args->out.status = HL_WAIT_CS_STATUS_ABORTED;
3188 		}
3189 		return rc;
3190 	}
3191 
3192 	if (timestamp) {
3193 		args->out.flags |= HL_WAIT_CS_STATUS_FLAG_TIMESTAMP_VLD;
3194 		args->out.timestamp_nsec = timestamp;
3195 	}
3196 
3197 	switch (status) {
3198 	case CS_WAIT_STATUS_GONE:
3199 		args->out.flags |= HL_WAIT_CS_STATUS_FLAG_GONE;
3200 		fallthrough;
3201 	case CS_WAIT_STATUS_COMPLETED:
3202 		args->out.status = HL_WAIT_CS_STATUS_COMPLETED;
3203 		break;
3204 	case CS_WAIT_STATUS_BUSY:
3205 	default:
3206 		args->out.status = HL_WAIT_CS_STATUS_BUSY;
3207 		break;
3208 	}
3209 
3210 	return 0;
3211 }
3212 
3213 static inline void set_record_cq_info(struct hl_user_pending_interrupt *record,
3214 					struct hl_cb *cq_cb, u32 cq_offset, u32 target_value)
3215 {
3216 	record->ts_reg_info.cq_cb = cq_cb;
3217 	record->cq_kernel_addr = (u64 *) cq_cb->kernel_address + cq_offset;
3218 	record->cq_target_value = target_value;
3219 }
3220 
3221 static int validate_and_get_ts_record(struct device *dev,
3222 					struct hl_ts_buff *ts_buff, u64 ts_offset,
3223 					struct hl_user_pending_interrupt **req_event_record)
3224 {
3225 	struct hl_user_pending_interrupt *ts_cb_last;
3226 
3227 	*req_event_record = (struct hl_user_pending_interrupt *)ts_buff->kernel_buff_address +
3228 						ts_offset;
3229 	ts_cb_last = (struct hl_user_pending_interrupt *)ts_buff->kernel_buff_address +
3230 			(ts_buff->kernel_buff_size / sizeof(struct hl_user_pending_interrupt));
3231 
3232 	/* Validate ts_offset not exceeding last max */
3233 	if (*req_event_record >= ts_cb_last) {
3234 		dev_err(dev, "Ts offset(%llu) exceeds max CB offset(0x%llx)\n",
3235 				ts_offset, (u64)(uintptr_t)ts_cb_last);
3236 		return -EINVAL;
3237 	}
3238 
3239 	return 0;
3240 }
3241 
3242 static void unregister_timestamp_node(struct hl_device *hdev,
3243 			struct hl_user_pending_interrupt *record, bool need_lock)
3244 {
3245 	struct hl_user_interrupt *interrupt = record->ts_reg_info.interrupt;
3246 	bool ts_rec_found = false;
3247 	unsigned long flags;
3248 
3249 	if (need_lock)
3250 		spin_lock_irqsave(&interrupt->ts_list_lock, flags);
3251 
3252 	if (record->ts_reg_info.in_use) {
3253 		record->ts_reg_info.in_use = false;
3254 		list_del(&record->list_node);
3255 		ts_rec_found = true;
3256 	}
3257 
3258 	if (need_lock)
3259 		spin_unlock_irqrestore(&interrupt->ts_list_lock, flags);
3260 
3261 	/* Put refcounts that were taken when we registered the event */
3262 	if (ts_rec_found) {
3263 		hl_mmap_mem_buf_put(record->ts_reg_info.buf);
3264 		hl_cb_put(record->ts_reg_info.cq_cb);
3265 	}
3266 }
3267 
3268 static int ts_get_and_handle_kernel_record(struct hl_device *hdev, struct hl_ctx *ctx,
3269 					struct wait_interrupt_data *data, unsigned long *flags,
3270 					struct hl_user_pending_interrupt **pend)
3271 {
3272 	struct hl_user_pending_interrupt *req_offset_record;
3273 	struct hl_ts_buff *ts_buff = data->buf->private;
3274 	bool need_lock = false;
3275 	int rc;
3276 
3277 	rc = validate_and_get_ts_record(data->buf->mmg->dev, ts_buff, data->ts_offset,
3278 									&req_offset_record);
3279 	if (rc)
3280 		return rc;
3281 
3282 	/* In case the node already registered, need to unregister first then re-use */
3283 	if (req_offset_record->ts_reg_info.in_use) {
3284 		/*
3285 		 * Since interrupt here can be different than the one the node currently registered
3286 		 * on, and we don't want to lock two lists while we're doing unregister, so
3287 		 * unlock the new interrupt wait list here and acquire the lock again after you done
3288 		 */
3289 		if (data->interrupt->interrupt_id !=
3290 				req_offset_record->ts_reg_info.interrupt->interrupt_id) {
3291 
3292 			need_lock = true;
3293 			spin_unlock_irqrestore(&data->interrupt->ts_list_lock, *flags);
3294 		}
3295 
3296 		unregister_timestamp_node(hdev, req_offset_record, need_lock);
3297 
3298 		if (need_lock)
3299 			spin_lock_irqsave(&data->interrupt->ts_list_lock, *flags);
3300 	}
3301 
3302 	/* Fill up the new registration node info and add it to the list */
3303 	req_offset_record->ts_reg_info.in_use = true;
3304 	req_offset_record->ts_reg_info.buf = data->buf;
3305 	req_offset_record->ts_reg_info.timestamp_kernel_addr =
3306 			(u64 *) ts_buff->user_buff_address + data->ts_offset;
3307 	req_offset_record->ts_reg_info.interrupt = data->interrupt;
3308 	set_record_cq_info(req_offset_record, data->cq_cb, data->cq_offset,
3309 						data->target_value);
3310 
3311 	*pend = req_offset_record;
3312 
3313 	return rc;
3314 }
3315 
3316 static int _hl_interrupt_ts_reg_ioctl(struct hl_device *hdev, struct hl_ctx *ctx,
3317 				struct wait_interrupt_data *data,
3318 				u32 *status, u64 *timestamp)
3319 {
3320 	struct hl_user_pending_interrupt *pend;
3321 	unsigned long flags;
3322 	int rc = 0;
3323 
3324 	hl_ctx_get(ctx);
3325 
3326 	data->cq_cb = hl_cb_get(data->mmg, data->cq_handle);
3327 	if (!data->cq_cb) {
3328 		rc = -EINVAL;
3329 		goto put_ctx;
3330 	}
3331 
3332 	/* Validate the cq offset */
3333 	if (((u64 *) data->cq_cb->kernel_address + data->cq_offset) >=
3334 			((u64 *) data->cq_cb->kernel_address + (data->cq_cb->size / sizeof(u64)))) {
3335 		rc = -EINVAL;
3336 		goto put_cq_cb;
3337 	}
3338 
3339 	data->buf = hl_mmap_mem_buf_get(data->mmg, data->ts_handle);
3340 	if (!data->buf) {
3341 		rc = -EINVAL;
3342 		goto put_cq_cb;
3343 	}
3344 
3345 	spin_lock_irqsave(&data->interrupt->ts_list_lock, flags);
3346 
3347 	/* get ts buffer record */
3348 	rc = ts_get_and_handle_kernel_record(hdev, ctx, data, &flags, &pend);
3349 	if (rc) {
3350 		spin_unlock_irqrestore(&data->interrupt->ts_list_lock, flags);
3351 		goto put_ts_buff;
3352 	}
3353 
3354 	/* We check for completion value as interrupt could have been received
3355 	 * before we add the timestamp node to the ts list.
3356 	 */
3357 	if (*pend->cq_kernel_addr >= data->target_value) {
3358 		spin_unlock_irqrestore(&data->interrupt->ts_list_lock, flags);
3359 
3360 		pend->ts_reg_info.in_use = 0;
3361 		*status = HL_WAIT_CS_STATUS_COMPLETED;
3362 		*pend->ts_reg_info.timestamp_kernel_addr = ktime_get_ns();
3363 
3364 		goto put_ts_buff;
3365 	}
3366 
3367 	list_add_tail(&pend->list_node, &data->interrupt->ts_list_head);
3368 	spin_unlock_irqrestore(&data->interrupt->ts_list_lock, flags);
3369 
3370 	rc = *status = HL_WAIT_CS_STATUS_COMPLETED;
3371 
3372 	hl_ctx_put(ctx);
3373 
3374 	return rc;
3375 
3376 put_ts_buff:
3377 	hl_mmap_mem_buf_put(data->buf);
3378 put_cq_cb:
3379 	hl_cb_put(data->cq_cb);
3380 put_ctx:
3381 	hl_ctx_put(ctx);
3382 
3383 	return rc;
3384 }
3385 
3386 static int _hl_interrupt_wait_ioctl(struct hl_device *hdev, struct hl_ctx *ctx,
3387 				struct wait_interrupt_data *data,
3388 				u32 *status, u64 *timestamp)
3389 {
3390 	struct hl_user_pending_interrupt *pend;
3391 	unsigned long timeout, flags;
3392 	long completion_rc;
3393 	int rc = 0;
3394 
3395 	timeout = hl_usecs64_to_jiffies(data->intr_timeout_us);
3396 
3397 	hl_ctx_get(ctx);
3398 
3399 	data->cq_cb = hl_cb_get(data->mmg, data->cq_handle);
3400 	if (!data->cq_cb) {
3401 		rc = -EINVAL;
3402 		goto put_ctx;
3403 	}
3404 
3405 	/* Validate the cq offset */
3406 	if (((u64 *) data->cq_cb->kernel_address + data->cq_offset) >=
3407 			((u64 *) data->cq_cb->kernel_address + (data->cq_cb->size / sizeof(u64)))) {
3408 		rc = -EINVAL;
3409 		goto put_cq_cb;
3410 	}
3411 
3412 	pend = kzalloc_obj(*pend);
3413 	if (!pend) {
3414 		rc = -ENOMEM;
3415 		goto put_cq_cb;
3416 	}
3417 
3418 	hl_fence_init(&pend->fence, ULONG_MAX);
3419 	pend->cq_kernel_addr = (u64 *) data->cq_cb->kernel_address + data->cq_offset;
3420 	pend->cq_target_value = data->target_value;
3421 	spin_lock_irqsave(&data->interrupt->wait_list_lock, flags);
3422 
3423 
3424 	/* We check for completion value as interrupt could have been received
3425 	 * before we add the wait node to the wait list.
3426 	 */
3427 	if (*pend->cq_kernel_addr >= data->target_value || (!data->intr_timeout_us)) {
3428 		spin_unlock_irqrestore(&data->interrupt->wait_list_lock, flags);
3429 
3430 		if (*pend->cq_kernel_addr >= data->target_value)
3431 			*status = HL_WAIT_CS_STATUS_COMPLETED;
3432 		else
3433 			*status = HL_WAIT_CS_STATUS_BUSY;
3434 
3435 		pend->fence.timestamp = ktime_get();
3436 		goto set_timestamp;
3437 	}
3438 
3439 	/* Add pending user interrupt to relevant list for the interrupt
3440 	 * handler to monitor.
3441 	 * Note that we cannot have sorted list by target value,
3442 	 * in order to shorten the list pass loop, since
3443 	 * same list could have nodes for different cq counter handle.
3444 	 */
3445 	list_add_tail(&pend->list_node, &data->interrupt->wait_list_head);
3446 	spin_unlock_irqrestore(&data->interrupt->wait_list_lock, flags);
3447 
3448 	/* Wait for interrupt handler to signal completion */
3449 	completion_rc = wait_for_completion_interruptible_timeout(&pend->fence.completion,
3450 								timeout);
3451 	if (completion_rc > 0) {
3452 		if (pend->fence.error == -EIO) {
3453 			dev_err_ratelimited(hdev->dev,
3454 					"interrupt based wait ioctl aborted(error:%d) due to a reset cycle initiated\n",
3455 					pend->fence.error);
3456 			rc = -EIO;
3457 			*status = HL_WAIT_CS_STATUS_ABORTED;
3458 		} else {
3459 			*status = HL_WAIT_CS_STATUS_COMPLETED;
3460 		}
3461 	} else {
3462 		if (completion_rc == -ERESTARTSYS) {
3463 			dev_err_ratelimited(hdev->dev,
3464 					"user process got signal while waiting for interrupt ID %d\n",
3465 					data->interrupt->interrupt_id);
3466 			rc = -EINTR;
3467 			*status = HL_WAIT_CS_STATUS_ABORTED;
3468 		} else {
3469 			/* The wait has timed-out. We don't know anything beyond that
3470 			 * because the workload was not submitted through the driver.
3471 			 * Therefore, from driver's perspective, the workload is still
3472 			 * executing.
3473 			 */
3474 			rc = 0;
3475 			*status = HL_WAIT_CS_STATUS_BUSY;
3476 		}
3477 	}
3478 
3479 	/*
3480 	 * We keep removing the node from list here, and not at the irq handler
3481 	 * for completion timeout case. and if it's a registration
3482 	 * for ts record, the node will be deleted in the irq handler after
3483 	 * we reach the target value.
3484 	 */
3485 	spin_lock_irqsave(&data->interrupt->wait_list_lock, flags);
3486 	list_del(&pend->list_node);
3487 	spin_unlock_irqrestore(&data->interrupt->wait_list_lock, flags);
3488 
3489 set_timestamp:
3490 	*timestamp = ktime_to_ns(pend->fence.timestamp);
3491 	kfree(pend);
3492 	hl_cb_put(data->cq_cb);
3493 	hl_ctx_put(ctx);
3494 
3495 	return rc;
3496 
3497 put_cq_cb:
3498 	hl_cb_put(data->cq_cb);
3499 put_ctx:
3500 	hl_ctx_put(ctx);
3501 
3502 	return rc;
3503 }
3504 
3505 static int _hl_interrupt_wait_ioctl_user_addr(struct hl_device *hdev, struct hl_ctx *ctx,
3506 				u64 timeout_us, u64 user_address,
3507 				u64 target_value, struct hl_user_interrupt *interrupt,
3508 				u32 *status,
3509 				u64 *timestamp)
3510 {
3511 	struct hl_user_pending_interrupt *pend;
3512 	unsigned long timeout, flags;
3513 	u64 completion_value;
3514 	long completion_rc;
3515 	int rc = 0;
3516 
3517 	timeout = hl_usecs64_to_jiffies(timeout_us);
3518 
3519 	hl_ctx_get(ctx);
3520 
3521 	pend = kzalloc_obj(*pend);
3522 	if (!pend) {
3523 		hl_ctx_put(ctx);
3524 		return -ENOMEM;
3525 	}
3526 
3527 	hl_fence_init(&pend->fence, ULONG_MAX);
3528 
3529 	/* Add pending user interrupt to relevant list for the interrupt
3530 	 * handler to monitor
3531 	 */
3532 	spin_lock_irqsave(&interrupt->wait_list_lock, flags);
3533 	list_add_tail(&pend->list_node, &interrupt->wait_list_head);
3534 	spin_unlock_irqrestore(&interrupt->wait_list_lock, flags);
3535 
3536 	/* We check for completion value as interrupt could have been received
3537 	 * before we added the node to the wait list
3538 	 */
3539 	if (copy_from_user(&completion_value, u64_to_user_ptr(user_address), 8)) {
3540 		dev_err(hdev->dev, "Failed to copy completion value from user\n");
3541 		rc = -EFAULT;
3542 		goto remove_pending_user_interrupt;
3543 	}
3544 
3545 	if (completion_value >= target_value) {
3546 		*status = HL_WAIT_CS_STATUS_COMPLETED;
3547 		/* There was no interrupt, we assume the completion is now. */
3548 		pend->fence.timestamp = ktime_get();
3549 	} else {
3550 		*status = HL_WAIT_CS_STATUS_BUSY;
3551 	}
3552 
3553 	if (!timeout_us || (*status == HL_WAIT_CS_STATUS_COMPLETED))
3554 		goto remove_pending_user_interrupt;
3555 
3556 wait_again:
3557 	/* Wait for interrupt handler to signal completion */
3558 	completion_rc = wait_for_completion_interruptible_timeout(&pend->fence.completion,
3559 										timeout);
3560 
3561 	/* If timeout did not expire we need to perform the comparison.
3562 	 * If comparison fails, keep waiting until timeout expires
3563 	 */
3564 	if (completion_rc > 0) {
3565 		spin_lock_irqsave(&interrupt->wait_list_lock, flags);
3566 		/* reinit_completion must be called before we check for user
3567 		 * completion value, otherwise, if interrupt is received after
3568 		 * the comparison and before the next wait_for_completion,
3569 		 * we will reach timeout and fail
3570 		 */
3571 		reinit_completion(&pend->fence.completion);
3572 		spin_unlock_irqrestore(&interrupt->wait_list_lock, flags);
3573 
3574 		if (copy_from_user(&completion_value, u64_to_user_ptr(user_address), 8)) {
3575 			dev_err(hdev->dev, "Failed to copy completion value from user\n");
3576 			rc = -EFAULT;
3577 
3578 			goto remove_pending_user_interrupt;
3579 		}
3580 
3581 		if (completion_value >= target_value) {
3582 			*status = HL_WAIT_CS_STATUS_COMPLETED;
3583 		} else if (pend->fence.error) {
3584 			dev_err_ratelimited(hdev->dev,
3585 				"interrupt based wait ioctl aborted(error:%d) due to a reset cycle initiated\n",
3586 				pend->fence.error);
3587 			/* set the command completion status as ABORTED */
3588 			*status = HL_WAIT_CS_STATUS_ABORTED;
3589 		} else {
3590 			timeout = completion_rc;
3591 			goto wait_again;
3592 		}
3593 	} else if (completion_rc == -ERESTARTSYS) {
3594 		dev_err_ratelimited(hdev->dev,
3595 			"user process got signal while waiting for interrupt ID %d\n",
3596 			interrupt->interrupt_id);
3597 		rc = -EINTR;
3598 	} else {
3599 		/* The wait has timed-out. We don't know anything beyond that
3600 		 * because the workload wasn't submitted through the driver.
3601 		 * Therefore, from driver's perspective, the workload is still
3602 		 * executing.
3603 		 */
3604 		rc = 0;
3605 		*status = HL_WAIT_CS_STATUS_BUSY;
3606 	}
3607 
3608 remove_pending_user_interrupt:
3609 	spin_lock_irqsave(&interrupt->wait_list_lock, flags);
3610 	list_del(&pend->list_node);
3611 	spin_unlock_irqrestore(&interrupt->wait_list_lock, flags);
3612 
3613 	*timestamp = ktime_to_ns(pend->fence.timestamp);
3614 
3615 	kfree(pend);
3616 	hl_ctx_put(ctx);
3617 
3618 	return rc;
3619 }
3620 
3621 static int hl_interrupt_wait_ioctl(struct hl_fpriv *hpriv, void *data)
3622 {
3623 	u16 interrupt_id, first_interrupt, last_interrupt;
3624 	struct hl_device *hdev = hpriv->hdev;
3625 	struct asic_fixed_properties *prop;
3626 	struct hl_user_interrupt *interrupt;
3627 	union hl_wait_cs_args *args = data;
3628 	u32 status = HL_WAIT_CS_STATUS_BUSY;
3629 	u64 timestamp = 0;
3630 	int rc, int_idx;
3631 
3632 	prop = &hdev->asic_prop;
3633 
3634 	if (!(prop->user_interrupt_count + prop->user_dec_intr_count)) {
3635 		dev_err(hdev->dev, "no user interrupts allowed");
3636 		return -EPERM;
3637 	}
3638 
3639 	interrupt_id = FIELD_GET(HL_WAIT_CS_FLAGS_INTERRUPT_MASK, args->in.flags);
3640 
3641 	first_interrupt = prop->first_available_user_interrupt;
3642 	last_interrupt = prop->first_available_user_interrupt + prop->user_interrupt_count - 1;
3643 
3644 	if (interrupt_id < prop->user_dec_intr_count) {
3645 
3646 		/* Check if the requested core is enabled */
3647 		if (!(prop->decoder_enabled_mask & BIT(interrupt_id))) {
3648 			dev_err(hdev->dev, "interrupt on a disabled core(%u) not allowed",
3649 				interrupt_id);
3650 			return -EINVAL;
3651 		}
3652 
3653 		interrupt = &hdev->user_interrupt[interrupt_id];
3654 
3655 	} else if (interrupt_id >= first_interrupt && interrupt_id <= last_interrupt) {
3656 
3657 		int_idx = interrupt_id - first_interrupt + prop->user_dec_intr_count;
3658 		interrupt = &hdev->user_interrupt[int_idx];
3659 
3660 	} else if (interrupt_id == HL_COMMON_USER_CQ_INTERRUPT_ID) {
3661 		interrupt = &hdev->common_user_cq_interrupt;
3662 	} else if (interrupt_id == HL_COMMON_DEC_INTERRUPT_ID) {
3663 		interrupt = &hdev->common_decoder_interrupt;
3664 	} else {
3665 		dev_err(hdev->dev, "invalid user interrupt %u", interrupt_id);
3666 		return -EINVAL;
3667 	}
3668 
3669 	if (args->in.flags & HL_WAIT_CS_FLAGS_INTERRUPT_KERNEL_CQ) {
3670 		struct wait_interrupt_data wait_intr_data = {0};
3671 
3672 		wait_intr_data.interrupt = interrupt;
3673 		wait_intr_data.mmg = &hpriv->mem_mgr;
3674 		wait_intr_data.cq_handle = args->in.cq_counters_handle;
3675 		wait_intr_data.cq_offset = args->in.cq_counters_offset;
3676 		wait_intr_data.ts_handle = args->in.timestamp_handle;
3677 		wait_intr_data.ts_offset = args->in.timestamp_offset;
3678 		wait_intr_data.target_value = args->in.target;
3679 		wait_intr_data.intr_timeout_us = args->in.interrupt_timeout_us;
3680 
3681 		if (args->in.flags & HL_WAIT_CS_FLAGS_REGISTER_INTERRUPT) {
3682 			/*
3683 			 * Allow only one registration at a time. this is needed in order to prevent
3684 			 * issues while handling the flow of re-use of the same offset.
3685 			 * Since the registration flow is protected only by the interrupt lock,
3686 			 * re-use flow might request to move ts node to another interrupt list,
3687 			 * and in such case we're not protected.
3688 			 */
3689 			mutex_lock(&hpriv->ctx->ts_reg_lock);
3690 
3691 			rc = _hl_interrupt_ts_reg_ioctl(hdev, hpriv->ctx, &wait_intr_data,
3692 						&status, &timestamp);
3693 
3694 			mutex_unlock(&hpriv->ctx->ts_reg_lock);
3695 		} else
3696 			rc = _hl_interrupt_wait_ioctl(hdev, hpriv->ctx, &wait_intr_data,
3697 						&status, &timestamp);
3698 	} else {
3699 		rc = _hl_interrupt_wait_ioctl_user_addr(hdev, hpriv->ctx,
3700 				args->in.interrupt_timeout_us, args->in.addr,
3701 				args->in.target, interrupt, &status,
3702 				&timestamp);
3703 	}
3704 
3705 	if (rc)
3706 		return rc;
3707 
3708 	memset(args, 0, sizeof(*args));
3709 	args->out.status = status;
3710 
3711 	if (timestamp) {
3712 		args->out.timestamp_nsec = timestamp;
3713 		args->out.flags |= HL_WAIT_CS_STATUS_FLAG_TIMESTAMP_VLD;
3714 	}
3715 
3716 	return 0;
3717 }
3718 
3719 int hl_wait_ioctl(struct drm_device *ddev, void *data, struct drm_file *file_priv)
3720 {
3721 	struct hl_fpriv *hpriv = file_priv->driver_priv;
3722 	struct hl_device *hdev = hpriv->hdev;
3723 	union hl_wait_cs_args *args = data;
3724 	u32 flags = args->in.flags;
3725 	int rc;
3726 
3727 	/* If the device is not operational, or if an error has happened and user should release the
3728 	 * device, there is no point in waiting for any command submission or user interrupt.
3729 	 */
3730 	if (!hl_device_operational(hpriv->hdev, NULL) || hdev->reset_info.watchdog_active)
3731 		return -EBUSY;
3732 
3733 	if (flags & HL_WAIT_CS_FLAGS_INTERRUPT)
3734 		rc = hl_interrupt_wait_ioctl(hpriv, data);
3735 	else if (flags & HL_WAIT_CS_FLAGS_MULTI_CS)
3736 		rc = hl_multi_cs_wait_ioctl(hpriv, data);
3737 	else
3738 		rc = hl_cs_wait_ioctl(hpriv, data);
3739 
3740 	return rc;
3741 }
3742