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