habanalabs: check for DMA errors when clearing memory
[linux-2.6-microblaze.git] / drivers / misc / habanalabs / command_submission.c
1 // SPDX-License-Identifier: GPL-2.0
2
3 /*
4  * Copyright 2016-2019 HabanaLabs, Ltd.
5  * All Rights Reserved.
6  */
7
8 #include <uapi/misc/habanalabs.h>
9 #include "habanalabs.h"
10
11 #include <linux/uaccess.h>
12 #include <linux/slab.h>
13
14 #define HL_CS_FLAGS_SIG_WAIT    (HL_CS_FLAGS_SIGNAL | HL_CS_FLAGS_WAIT)
15
16 static void job_wq_completion(struct work_struct *work);
17 static long _hl_cs_wait_ioctl(struct hl_device *hdev,
18                 struct hl_ctx *ctx, u64 timeout_us, u64 seq);
19 static void cs_do_release(struct kref *ref);
20
21 static void hl_sob_reset(struct kref *ref)
22 {
23         struct hl_hw_sob *hw_sob = container_of(ref, struct hl_hw_sob,
24                                                         kref);
25         struct hl_device *hdev = hw_sob->hdev;
26
27         hdev->asic_funcs->reset_sob(hdev, hw_sob);
28 }
29
30 void hl_sob_reset_error(struct kref *ref)
31 {
32         struct hl_hw_sob *hw_sob = container_of(ref, struct hl_hw_sob,
33                                                         kref);
34         struct hl_device *hdev = hw_sob->hdev;
35
36         dev_crit(hdev->dev,
37                         "SOB release shouldn't be called here, q_idx: %d, sob_id: %d\n",
38                         hw_sob->q_idx, hw_sob->sob_id);
39 }
40
41 static const char *hl_fence_get_driver_name(struct dma_fence *fence)
42 {
43         return "HabanaLabs";
44 }
45
46 static const char *hl_fence_get_timeline_name(struct dma_fence *fence)
47 {
48         struct hl_cs_compl *hl_cs_compl =
49                 container_of(fence, struct hl_cs_compl, base_fence);
50
51         return dev_name(hl_cs_compl->hdev->dev);
52 }
53
54 static bool hl_fence_enable_signaling(struct dma_fence *fence)
55 {
56         return true;
57 }
58
59 static void hl_fence_release(struct dma_fence *fence)
60 {
61         struct hl_cs_compl *hl_cs_cmpl =
62                 container_of(fence, struct hl_cs_compl, base_fence);
63         struct hl_device *hdev = hl_cs_cmpl->hdev;
64
65         /* EBUSY means the CS was never submitted and hence we don't have
66          * an attached hw_sob object that we should handle here
67          */
68         if (fence->error == -EBUSY)
69                 goto free;
70
71         if ((hl_cs_cmpl->type == CS_TYPE_SIGNAL) ||
72                         (hl_cs_cmpl->type == CS_TYPE_WAIT)) {
73
74                 dev_dbg(hdev->dev,
75                         "CS 0x%llx type %d finished, sob_id: %d, sob_val: 0x%x\n",
76                         hl_cs_cmpl->cs_seq,
77                         hl_cs_cmpl->type,
78                         hl_cs_cmpl->hw_sob->sob_id,
79                         hl_cs_cmpl->sob_val);
80
81                 /*
82                  * A signal CS can get completion while the corresponding wait
83                  * for signal CS is on its way to the PQ. The wait for signal CS
84                  * will get stuck if the signal CS incremented the SOB to its
85                  * max value and there are no pending (submitted) waits on this
86                  * SOB.
87                  * We do the following to void this situation:
88                  * 1. The wait for signal CS must get a ref for the signal CS as
89                  *    soon as possible in cs_ioctl_signal_wait() and put it
90                  *    before being submitted to the PQ but after it incremented
91                  *    the SOB refcnt in init_signal_wait_cs().
92                  * 2. Signal/Wait for signal CS will decrement the SOB refcnt
93                  *    here.
94                  * These two measures guarantee that the wait for signal CS will
95                  * reset the SOB upon completion rather than the signal CS and
96                  * hence the above scenario is avoided.
97                  */
98                 kref_put(&hl_cs_cmpl->hw_sob->kref, hl_sob_reset);
99         }
100
101 free:
102         kfree_rcu(hl_cs_cmpl, base_fence.rcu);
103 }
104
105 static const struct dma_fence_ops hl_fence_ops = {
106         .get_driver_name = hl_fence_get_driver_name,
107         .get_timeline_name = hl_fence_get_timeline_name,
108         .enable_signaling = hl_fence_enable_signaling,
109         .release = hl_fence_release
110 };
111
112 static void cs_get(struct hl_cs *cs)
113 {
114         kref_get(&cs->refcount);
115 }
116
117 static int cs_get_unless_zero(struct hl_cs *cs)
118 {
119         return kref_get_unless_zero(&cs->refcount);
120 }
121
122 static void cs_put(struct hl_cs *cs)
123 {
124         kref_put(&cs->refcount, cs_do_release);
125 }
126
127 static bool is_cb_patched(struct hl_device *hdev, struct hl_cs_job *job)
128 {
129         /*
130          * Patched CB is created for external queues jobs, and for H/W queues
131          * jobs if the user CB was allocated by driver and MMU is disabled.
132          */
133         return (job->queue_type == QUEUE_TYPE_EXT ||
134                         (job->queue_type == QUEUE_TYPE_HW &&
135                                         job->is_kernel_allocated_cb &&
136                                         !hdev->mmu_enable));
137 }
138
139 /*
140  * cs_parser - parse the user command submission
141  *
142  * @hpriv       : pointer to the private data of the fd
143  * @job        : pointer to the job that holds the command submission info
144  *
145  * The function parses the command submission of the user. It calls the
146  * ASIC specific parser, which returns a list of memory blocks to send
147  * to the device as different command buffers
148  *
149  */
150 static int cs_parser(struct hl_fpriv *hpriv, struct hl_cs_job *job)
151 {
152         struct hl_device *hdev = hpriv->hdev;
153         struct hl_cs_parser parser;
154         int rc;
155
156         parser.ctx_id = job->cs->ctx->asid;
157         parser.cs_sequence = job->cs->sequence;
158         parser.job_id = job->id;
159
160         parser.hw_queue_id = job->hw_queue_id;
161         parser.job_userptr_list = &job->userptr_list;
162         parser.patched_cb = NULL;
163         parser.user_cb = job->user_cb;
164         parser.user_cb_size = job->user_cb_size;
165         parser.queue_type = job->queue_type;
166         parser.is_kernel_allocated_cb = job->is_kernel_allocated_cb;
167         job->patched_cb = NULL;
168
169         rc = hdev->asic_funcs->cs_parser(hdev, &parser);
170
171         if (is_cb_patched(hdev, job)) {
172                 if (!rc) {
173                         job->patched_cb = parser.patched_cb;
174                         job->job_cb_size = parser.patched_cb_size;
175                         job->contains_dma_pkt = parser.contains_dma_pkt;
176
177                         spin_lock(&job->patched_cb->lock);
178                         job->patched_cb->cs_cnt++;
179                         spin_unlock(&job->patched_cb->lock);
180                 }
181
182                 /*
183                  * Whether the parsing worked or not, we don't need the
184                  * original CB anymore because it was already parsed and
185                  * won't be accessed again for this CS
186                  */
187                 spin_lock(&job->user_cb->lock);
188                 job->user_cb->cs_cnt--;
189                 spin_unlock(&job->user_cb->lock);
190                 hl_cb_put(job->user_cb);
191                 job->user_cb = NULL;
192         } else if (!rc) {
193                 job->job_cb_size = job->user_cb_size;
194         }
195
196         return rc;
197 }
198
199 static void free_job(struct hl_device *hdev, struct hl_cs_job *job)
200 {
201         struct hl_cs *cs = job->cs;
202
203         if (is_cb_patched(hdev, job)) {
204                 hl_userptr_delete_list(hdev, &job->userptr_list);
205
206                 /*
207                  * We might arrive here from rollback and patched CB wasn't
208                  * created, so we need to check it's not NULL
209                  */
210                 if (job->patched_cb) {
211                         spin_lock(&job->patched_cb->lock);
212                         job->patched_cb->cs_cnt--;
213                         spin_unlock(&job->patched_cb->lock);
214
215                         hl_cb_put(job->patched_cb);
216                 }
217         }
218
219         /* For H/W queue jobs, if a user CB was allocated by driver and MMU is
220          * enabled, the user CB isn't released in cs_parser() and thus should be
221          * released here.
222          */
223         if (job->queue_type == QUEUE_TYPE_HW &&
224                         job->is_kernel_allocated_cb && hdev->mmu_enable) {
225                 spin_lock(&job->user_cb->lock);
226                 job->user_cb->cs_cnt--;
227                 spin_unlock(&job->user_cb->lock);
228
229                 hl_cb_put(job->user_cb);
230         }
231
232         /*
233          * This is the only place where there can be multiple threads
234          * modifying the list at the same time
235          */
236         spin_lock(&cs->job_lock);
237         list_del(&job->cs_node);
238         spin_unlock(&cs->job_lock);
239
240         hl_debugfs_remove_job(hdev, job);
241
242         if (job->queue_type == QUEUE_TYPE_EXT ||
243                         job->queue_type == QUEUE_TYPE_HW)
244                 cs_put(cs);
245
246         kfree(job);
247 }
248
249 static void cs_counters_aggregate(struct hl_device *hdev, struct hl_ctx *ctx)
250 {
251         hdev->aggregated_cs_counters.device_in_reset_drop_cnt +=
252                         ctx->cs_counters.device_in_reset_drop_cnt;
253         hdev->aggregated_cs_counters.out_of_mem_drop_cnt +=
254                         ctx->cs_counters.out_of_mem_drop_cnt;
255         hdev->aggregated_cs_counters.parsing_drop_cnt +=
256                         ctx->cs_counters.parsing_drop_cnt;
257         hdev->aggregated_cs_counters.queue_full_drop_cnt +=
258                         ctx->cs_counters.queue_full_drop_cnt;
259 }
260
261 static void cs_do_release(struct kref *ref)
262 {
263         struct hl_cs *cs = container_of(ref, struct hl_cs,
264                                                 refcount);
265         struct hl_device *hdev = cs->ctx->hdev;
266         struct hl_cs_job *job, *tmp;
267
268         cs->completed = true;
269
270         /*
271          * Although if we reached here it means that all external jobs have
272          * finished, because each one of them took refcnt to CS, we still
273          * need to go over the internal jobs and free them. Otherwise, we
274          * will have leaked memory and what's worse, the CS object (and
275          * potentially the CTX object) could be released, while the JOB
276          * still holds a pointer to them (but no reference).
277          */
278         list_for_each_entry_safe(job, tmp, &cs->job_list, cs_node)
279                 free_job(hdev, job);
280
281         /* We also need to update CI for internal queues */
282         if (cs->submitted) {
283                 hdev->asic_funcs->hw_queues_lock(hdev);
284
285                 hdev->cs_active_cnt--;
286                 if (!hdev->cs_active_cnt) {
287                         struct hl_device_idle_busy_ts *ts;
288
289                         ts = &hdev->idle_busy_ts_arr[hdev->idle_busy_ts_idx++];
290                         ts->busy_to_idle_ts = ktime_get();
291
292                         if (hdev->idle_busy_ts_idx == HL_IDLE_BUSY_TS_ARR_SIZE)
293                                 hdev->idle_busy_ts_idx = 0;
294                 } else if (hdev->cs_active_cnt < 0) {
295                         dev_crit(hdev->dev, "CS active cnt %d is negative\n",
296                                 hdev->cs_active_cnt);
297                 }
298
299                 hdev->asic_funcs->hw_queues_unlock(hdev);
300
301                 hl_int_hw_queue_update_ci(cs);
302
303                 spin_lock(&hdev->hw_queues_mirror_lock);
304                 /* remove CS from hw_queues mirror list */
305                 list_del_init(&cs->mirror_node);
306                 spin_unlock(&hdev->hw_queues_mirror_lock);
307
308                 /*
309                  * Don't cancel TDR in case this CS was timedout because we
310                  * might be running from the TDR context
311                  */
312                 if ((!cs->timedout) &&
313                         (hdev->timeout_jiffies != MAX_SCHEDULE_TIMEOUT)) {
314                         struct hl_cs *next;
315
316                         if (cs->tdr_active)
317                                 cancel_delayed_work_sync(&cs->work_tdr);
318
319                         spin_lock(&hdev->hw_queues_mirror_lock);
320
321                         /* queue TDR for next CS */
322                         next = list_first_entry_or_null(
323                                         &hdev->hw_queues_mirror_list,
324                                         struct hl_cs, mirror_node);
325
326                         if ((next) && (!next->tdr_active)) {
327                                 next->tdr_active = true;
328                                 schedule_delayed_work(&next->work_tdr,
329                                                         hdev->timeout_jiffies);
330                         }
331
332                         spin_unlock(&hdev->hw_queues_mirror_lock);
333                 }
334         } else if (cs->type == CS_TYPE_WAIT) {
335                 /*
336                  * In case the wait for signal CS was submitted, the put occurs
337                  * in init_signal_wait_cs() right before hanging on the PQ.
338                  */
339                 dma_fence_put(cs->signal_fence);
340         }
341
342         /*
343          * Must be called before hl_ctx_put because inside we use ctx to get
344          * the device
345          */
346         hl_debugfs_remove_cs(cs);
347
348         hl_ctx_put(cs->ctx);
349
350         /* We need to mark an error for not submitted because in that case
351          * the dma fence release flow is different. Mainly, we don't need
352          * to handle hw_sob for signal/wait
353          */
354         if (cs->timedout)
355                 dma_fence_set_error(cs->fence, -ETIMEDOUT);
356         else if (cs->aborted)
357                 dma_fence_set_error(cs->fence, -EIO);
358         else if (!cs->submitted)
359                 dma_fence_set_error(cs->fence, -EBUSY);
360
361         dma_fence_signal(cs->fence);
362         dma_fence_put(cs->fence);
363
364         cs_counters_aggregate(hdev, cs->ctx);
365
366         kfree(cs->jobs_in_queue_cnt);
367         kfree(cs);
368 }
369
370 static void cs_timedout(struct work_struct *work)
371 {
372         struct hl_device *hdev;
373         int ctx_asid, rc;
374         struct hl_cs *cs = container_of(work, struct hl_cs,
375                                                  work_tdr.work);
376         rc = cs_get_unless_zero(cs);
377         if (!rc)
378                 return;
379
380         if ((!cs->submitted) || (cs->completed)) {
381                 cs_put(cs);
382                 return;
383         }
384
385         /* Mark the CS is timed out so we won't try to cancel its TDR */
386         cs->timedout = true;
387
388         hdev = cs->ctx->hdev;
389         ctx_asid = cs->ctx->asid;
390
391         dev_err(hdev->dev,
392                 "Command submission %llu has not finished in time!\n",
393                 cs->sequence);
394
395         cs_put(cs);
396
397         if (hdev->reset_on_lockup)
398                 hl_device_reset(hdev, false, false);
399 }
400
401 static int allocate_cs(struct hl_device *hdev, struct hl_ctx *ctx,
402                         enum hl_cs_type cs_type, struct hl_cs **cs_new)
403 {
404         struct hl_cs_compl *cs_cmpl;
405         struct dma_fence *other = NULL;
406         struct hl_cs *cs;
407         int rc;
408
409         cs = kzalloc(sizeof(*cs), GFP_ATOMIC);
410         if (!cs)
411                 return -ENOMEM;
412
413         cs->ctx = ctx;
414         cs->submitted = false;
415         cs->completed = false;
416         cs->type = cs_type;
417         INIT_LIST_HEAD(&cs->job_list);
418         INIT_DELAYED_WORK(&cs->work_tdr, cs_timedout);
419         kref_init(&cs->refcount);
420         spin_lock_init(&cs->job_lock);
421
422         cs_cmpl = kmalloc(sizeof(*cs_cmpl), GFP_ATOMIC);
423         if (!cs_cmpl) {
424                 rc = -ENOMEM;
425                 goto free_cs;
426         }
427
428         cs_cmpl->hdev = hdev;
429         cs_cmpl->type = cs->type;
430         spin_lock_init(&cs_cmpl->lock);
431         cs->fence = &cs_cmpl->base_fence;
432
433         spin_lock(&ctx->cs_lock);
434
435         cs_cmpl->cs_seq = ctx->cs_sequence;
436         other = ctx->cs_pending[cs_cmpl->cs_seq &
437                                 (hdev->asic_prop.max_pending_cs - 1)];
438         if ((other) && (!dma_fence_is_signaled(other))) {
439                 dev_dbg(hdev->dev,
440                         "Rejecting CS because of too many in-flights CS\n");
441                 rc = -EAGAIN;
442                 goto free_fence;
443         }
444
445         cs->jobs_in_queue_cnt = kcalloc(hdev->asic_prop.max_queues,
446                         sizeof(*cs->jobs_in_queue_cnt), GFP_ATOMIC);
447         if (!cs->jobs_in_queue_cnt) {
448                 rc = -ENOMEM;
449                 goto free_fence;
450         }
451
452         dma_fence_init(&cs_cmpl->base_fence, &hl_fence_ops, &cs_cmpl->lock,
453                         ctx->asid, ctx->cs_sequence);
454
455         cs->sequence = cs_cmpl->cs_seq;
456
457         ctx->cs_pending[cs_cmpl->cs_seq &
458                         (hdev->asic_prop.max_pending_cs - 1)] =
459                                                         &cs_cmpl->base_fence;
460         ctx->cs_sequence++;
461
462         dma_fence_get(&cs_cmpl->base_fence);
463
464         dma_fence_put(other);
465
466         spin_unlock(&ctx->cs_lock);
467
468         *cs_new = cs;
469
470         return 0;
471
472 free_fence:
473         spin_unlock(&ctx->cs_lock);
474         kfree(cs_cmpl);
475 free_cs:
476         kfree(cs);
477         return rc;
478 }
479
480 static void cs_rollback(struct hl_device *hdev, struct hl_cs *cs)
481 {
482         struct hl_cs_job *job, *tmp;
483
484         list_for_each_entry_safe(job, tmp, &cs->job_list, cs_node)
485                 free_job(hdev, job);
486 }
487
488 void hl_cs_rollback_all(struct hl_device *hdev)
489 {
490         int i;
491         struct hl_cs *cs, *tmp;
492
493         /* flush all completions */
494         for (i = 0 ; i < hdev->asic_prop.completion_queues_count ; i++)
495                 flush_workqueue(hdev->cq_wq[i]);
496
497         /* Make sure we don't have leftovers in the H/W queues mirror list */
498         list_for_each_entry_safe(cs, tmp, &hdev->hw_queues_mirror_list,
499                                 mirror_node) {
500                 cs_get(cs);
501                 cs->aborted = true;
502                 dev_warn_ratelimited(hdev->dev, "Killing CS %d.%llu\n",
503                                         cs->ctx->asid, cs->sequence);
504                 cs_rollback(hdev, cs);
505                 cs_put(cs);
506         }
507 }
508
509 static void job_wq_completion(struct work_struct *work)
510 {
511         struct hl_cs_job *job = container_of(work, struct hl_cs_job,
512                                                 finish_work);
513         struct hl_cs *cs = job->cs;
514         struct hl_device *hdev = cs->ctx->hdev;
515
516         /* job is no longer needed */
517         free_job(hdev, job);
518 }
519
520 static int validate_queue_index(struct hl_device *hdev,
521                                 struct hl_cs_chunk *chunk,
522                                 enum hl_queue_type *queue_type,
523                                 bool *is_kernel_allocated_cb)
524 {
525         struct asic_fixed_properties *asic = &hdev->asic_prop;
526         struct hw_queue_properties *hw_queue_prop;
527
528         /* This must be checked here to prevent out-of-bounds access to
529          * hw_queues_props array
530          */
531         if (chunk->queue_index >= asic->max_queues) {
532                 dev_err(hdev->dev, "Queue index %d is invalid\n",
533                         chunk->queue_index);
534                 return -EINVAL;
535         }
536
537         hw_queue_prop = &asic->hw_queues_props[chunk->queue_index];
538
539         if (hw_queue_prop->type == QUEUE_TYPE_NA) {
540                 dev_err(hdev->dev, "Queue index %d is invalid\n",
541                         chunk->queue_index);
542                 return -EINVAL;
543         }
544
545         if (hw_queue_prop->driver_only) {
546                 dev_err(hdev->dev,
547                         "Queue index %d is restricted for the kernel driver\n",
548                         chunk->queue_index);
549                 return -EINVAL;
550         }
551
552         *queue_type = hw_queue_prop->type;
553         *is_kernel_allocated_cb = !!hw_queue_prop->requires_kernel_cb;
554
555         return 0;
556 }
557
558 static struct hl_cb *get_cb_from_cs_chunk(struct hl_device *hdev,
559                                         struct hl_cb_mgr *cb_mgr,
560                                         struct hl_cs_chunk *chunk)
561 {
562         struct hl_cb *cb;
563         u32 cb_handle;
564
565         cb_handle = (u32) (chunk->cb_handle >> PAGE_SHIFT);
566
567         cb = hl_cb_get(hdev, cb_mgr, cb_handle);
568         if (!cb) {
569                 dev_err(hdev->dev, "CB handle 0x%x invalid\n", cb_handle);
570                 return NULL;
571         }
572
573         if ((chunk->cb_size < 8) || (chunk->cb_size > cb->size)) {
574                 dev_err(hdev->dev, "CB size %u invalid\n", chunk->cb_size);
575                 goto release_cb;
576         }
577
578         spin_lock(&cb->lock);
579         cb->cs_cnt++;
580         spin_unlock(&cb->lock);
581
582         return cb;
583
584 release_cb:
585         hl_cb_put(cb);
586         return NULL;
587 }
588
589 struct hl_cs_job *hl_cs_allocate_job(struct hl_device *hdev,
590                 enum hl_queue_type queue_type, bool is_kernel_allocated_cb)
591 {
592         struct hl_cs_job *job;
593
594         job = kzalloc(sizeof(*job), GFP_ATOMIC);
595         if (!job)
596                 return NULL;
597
598         job->queue_type = queue_type;
599         job->is_kernel_allocated_cb = is_kernel_allocated_cb;
600
601         if (is_cb_patched(hdev, job))
602                 INIT_LIST_HEAD(&job->userptr_list);
603
604         if (job->queue_type == QUEUE_TYPE_EXT)
605                 INIT_WORK(&job->finish_work, job_wq_completion);
606
607         return job;
608 }
609
610 static int cs_ioctl_default(struct hl_fpriv *hpriv, void __user *chunks,
611                                 u32 num_chunks, u64 *cs_seq)
612 {
613         struct hl_device *hdev = hpriv->hdev;
614         struct hl_cs_chunk *cs_chunk_array;
615         struct hl_cs_job *job;
616         struct hl_cs *cs;
617         struct hl_cb *cb;
618         bool int_queues_only = true;
619         u32 size_to_copy;
620         int rc, i;
621
622         *cs_seq = ULLONG_MAX;
623
624         if (num_chunks > HL_MAX_JOBS_PER_CS) {
625                 dev_err(hdev->dev,
626                         "Number of chunks can NOT be larger than %d\n",
627                         HL_MAX_JOBS_PER_CS);
628                 rc = -EINVAL;
629                 goto out;
630         }
631
632         cs_chunk_array = kmalloc_array(num_chunks, sizeof(*cs_chunk_array),
633                                         GFP_ATOMIC);
634         if (!cs_chunk_array) {
635                 rc = -ENOMEM;
636                 goto out;
637         }
638
639         size_to_copy = num_chunks * sizeof(struct hl_cs_chunk);
640         if (copy_from_user(cs_chunk_array, chunks, size_to_copy)) {
641                 dev_err(hdev->dev, "Failed to copy cs chunk array from user\n");
642                 rc = -EFAULT;
643                 goto free_cs_chunk_array;
644         }
645
646         /* increment refcnt for context */
647         hl_ctx_get(hdev, hpriv->ctx);
648
649         rc = allocate_cs(hdev, hpriv->ctx, CS_TYPE_DEFAULT, &cs);
650         if (rc) {
651                 hl_ctx_put(hpriv->ctx);
652                 goto free_cs_chunk_array;
653         }
654
655         *cs_seq = cs->sequence;
656
657         hl_debugfs_add_cs(cs);
658
659         /* Validate ALL the CS chunks before submitting the CS */
660         for (i = 0 ; i < num_chunks ; i++) {
661                 struct hl_cs_chunk *chunk = &cs_chunk_array[i];
662                 enum hl_queue_type queue_type;
663                 bool is_kernel_allocated_cb;
664
665                 rc = validate_queue_index(hdev, chunk, &queue_type,
666                                                 &is_kernel_allocated_cb);
667                 if (rc) {
668                         hpriv->ctx->cs_counters.parsing_drop_cnt++;
669                         goto free_cs_object;
670                 }
671
672                 if (is_kernel_allocated_cb) {
673                         cb = get_cb_from_cs_chunk(hdev, &hpriv->cb_mgr, chunk);
674                         if (!cb) {
675                                 hpriv->ctx->cs_counters.parsing_drop_cnt++;
676                                 rc = -EINVAL;
677                                 goto free_cs_object;
678                         }
679                 } else {
680                         cb = (struct hl_cb *) (uintptr_t) chunk->cb_handle;
681                 }
682
683                 if (queue_type == QUEUE_TYPE_EXT || queue_type == QUEUE_TYPE_HW)
684                         int_queues_only = false;
685
686                 job = hl_cs_allocate_job(hdev, queue_type,
687                                                 is_kernel_allocated_cb);
688                 if (!job) {
689                         hpriv->ctx->cs_counters.out_of_mem_drop_cnt++;
690                         dev_err(hdev->dev, "Failed to allocate a new job\n");
691                         rc = -ENOMEM;
692                         if (is_kernel_allocated_cb)
693                                 goto release_cb;
694                         else
695                                 goto free_cs_object;
696                 }
697
698                 job->id = i + 1;
699                 job->cs = cs;
700                 job->user_cb = cb;
701                 job->user_cb_size = chunk->cb_size;
702                 job->hw_queue_id = chunk->queue_index;
703
704                 cs->jobs_in_queue_cnt[job->hw_queue_id]++;
705
706                 list_add_tail(&job->cs_node, &cs->job_list);
707
708                 /*
709                  * Increment CS reference. When CS reference is 0, CS is
710                  * done and can be signaled to user and free all its resources
711                  * Only increment for JOB on external or H/W queues, because
712                  * only for those JOBs we get completion
713                  */
714                 if (job->queue_type == QUEUE_TYPE_EXT ||
715                                 job->queue_type == QUEUE_TYPE_HW)
716                         cs_get(cs);
717
718                 hl_debugfs_add_job(hdev, job);
719
720                 rc = cs_parser(hpriv, job);
721                 if (rc) {
722                         hpriv->ctx->cs_counters.parsing_drop_cnt++;
723                         dev_err(hdev->dev,
724                                 "Failed to parse JOB %d.%llu.%d, err %d, rejecting the CS\n",
725                                 cs->ctx->asid, cs->sequence, job->id, rc);
726                         goto free_cs_object;
727                 }
728         }
729
730         if (int_queues_only) {
731                 hpriv->ctx->cs_counters.parsing_drop_cnt++;
732                 dev_err(hdev->dev,
733                         "Reject CS %d.%llu because only internal queues jobs are present\n",
734                         cs->ctx->asid, cs->sequence);
735                 rc = -EINVAL;
736                 goto free_cs_object;
737         }
738
739         rc = hl_hw_queue_schedule_cs(cs);
740         if (rc) {
741                 if (rc != -EAGAIN)
742                         dev_err(hdev->dev,
743                                 "Failed to submit CS %d.%llu to H/W queues, error %d\n",
744                                 cs->ctx->asid, cs->sequence, rc);
745                 goto free_cs_object;
746         }
747
748         rc = HL_CS_STATUS_SUCCESS;
749         goto put_cs;
750
751 release_cb:
752         spin_lock(&cb->lock);
753         cb->cs_cnt--;
754         spin_unlock(&cb->lock);
755         hl_cb_put(cb);
756 free_cs_object:
757         cs_rollback(hdev, cs);
758         *cs_seq = ULLONG_MAX;
759         /* The path below is both for good and erroneous exits */
760 put_cs:
761         /* We finished with the CS in this function, so put the ref */
762         cs_put(cs);
763 free_cs_chunk_array:
764         kfree(cs_chunk_array);
765 out:
766         return rc;
767 }
768
769 static int cs_ioctl_signal_wait(struct hl_fpriv *hpriv, enum hl_cs_type cs_type,
770                                 void __user *chunks, u32 num_chunks,
771                                 u64 *cs_seq)
772 {
773         struct hl_device *hdev = hpriv->hdev;
774         struct hl_ctx *ctx = hpriv->ctx;
775         struct hl_cs_chunk *cs_chunk_array, *chunk;
776         struct hw_queue_properties *hw_queue_prop;
777         struct dma_fence *sig_fence = NULL;
778         struct hl_cs_job *job;
779         struct hl_cs *cs;
780         struct hl_cb *cb;
781         enum hl_queue_type q_type;
782         u64 *signal_seq_arr = NULL, signal_seq;
783         u32 size_to_copy, q_idx, signal_seq_arr_len, cb_size;
784         int rc;
785
786         *cs_seq = ULLONG_MAX;
787
788         if (num_chunks > HL_MAX_JOBS_PER_CS) {
789                 dev_err(hdev->dev,
790                         "Number of chunks can NOT be larger than %d\n",
791                         HL_MAX_JOBS_PER_CS);
792                 rc = -EINVAL;
793                 goto out;
794         }
795
796         cs_chunk_array = kmalloc_array(num_chunks, sizeof(*cs_chunk_array),
797                                         GFP_ATOMIC);
798         if (!cs_chunk_array) {
799                 rc = -ENOMEM;
800                 goto out;
801         }
802
803         size_to_copy = num_chunks * sizeof(struct hl_cs_chunk);
804         if (copy_from_user(cs_chunk_array, chunks, size_to_copy)) {
805                 dev_err(hdev->dev, "Failed to copy cs chunk array from user\n");
806                 rc = -EFAULT;
807                 goto free_cs_chunk_array;
808         }
809
810         /* currently it is guaranteed to have only one chunk */
811         chunk = &cs_chunk_array[0];
812         q_idx = chunk->queue_index;
813         hw_queue_prop = &hdev->asic_prop.hw_queues_props[q_idx];
814         q_type = hw_queue_prop->type;
815
816         if ((q_idx >= hdev->asic_prop.max_queues) ||
817                         (!hw_queue_prop->supports_sync_stream)) {
818                 dev_err(hdev->dev, "Queue index %d is invalid\n", q_idx);
819                 rc = -EINVAL;
820                 goto free_cs_chunk_array;
821         }
822
823         if (cs_type == CS_TYPE_WAIT) {
824                 struct hl_cs_compl *sig_waitcs_cmpl;
825
826                 signal_seq_arr_len = chunk->num_signal_seq_arr;
827
828                 /* currently only one signal seq is supported */
829                 if (signal_seq_arr_len != 1) {
830                         dev_err(hdev->dev,
831                                 "Wait for signal CS supports only one signal CS seq\n");
832                         rc = -EINVAL;
833                         goto free_cs_chunk_array;
834                 }
835
836                 signal_seq_arr = kmalloc_array(signal_seq_arr_len,
837                                                 sizeof(*signal_seq_arr),
838                                                 GFP_ATOMIC);
839                 if (!signal_seq_arr) {
840                         rc = -ENOMEM;
841                         goto free_cs_chunk_array;
842                 }
843
844                 size_to_copy = chunk->num_signal_seq_arr *
845                                 sizeof(*signal_seq_arr);
846                 if (copy_from_user(signal_seq_arr,
847                                         u64_to_user_ptr(chunk->signal_seq_arr),
848                                         size_to_copy)) {
849                         dev_err(hdev->dev,
850                                 "Failed to copy signal seq array from user\n");
851                         rc = -EFAULT;
852                         goto free_signal_seq_array;
853                 }
854
855                 /* currently it is guaranteed to have only one signal seq */
856                 signal_seq = signal_seq_arr[0];
857                 sig_fence = hl_ctx_get_fence(ctx, signal_seq);
858                 if (IS_ERR(sig_fence)) {
859                         dev_err(hdev->dev,
860                                 "Failed to get signal CS with seq 0x%llx\n",
861                                 signal_seq);
862                         rc = PTR_ERR(sig_fence);
863                         goto free_signal_seq_array;
864                 }
865
866                 if (!sig_fence) {
867                         /* signal CS already finished */
868                         rc = 0;
869                         goto free_signal_seq_array;
870                 }
871
872                 sig_waitcs_cmpl =
873                         container_of(sig_fence, struct hl_cs_compl, base_fence);
874
875                 if (sig_waitcs_cmpl->type != CS_TYPE_SIGNAL) {
876                         dev_err(hdev->dev,
877                                 "CS seq 0x%llx is not of a signal CS\n",
878                                 signal_seq);
879                         dma_fence_put(sig_fence);
880                         rc = -EINVAL;
881                         goto free_signal_seq_array;
882                 }
883
884                 if (dma_fence_is_signaled(sig_fence)) {
885                         /* signal CS already finished */
886                         dma_fence_put(sig_fence);
887                         rc = 0;
888                         goto free_signal_seq_array;
889                 }
890         }
891
892         /* increment refcnt for context */
893         hl_ctx_get(hdev, ctx);
894
895         rc = allocate_cs(hdev, ctx, cs_type, &cs);
896         if (rc) {
897                 if (cs_type == CS_TYPE_WAIT)
898                         dma_fence_put(sig_fence);
899                 hl_ctx_put(ctx);
900                 goto free_signal_seq_array;
901         }
902
903         /*
904          * Save the signal CS fence for later initialization right before
905          * hanging the wait CS on the queue.
906          */
907         if (cs->type == CS_TYPE_WAIT)
908                 cs->signal_fence = sig_fence;
909
910         hl_debugfs_add_cs(cs);
911
912         *cs_seq = cs->sequence;
913
914         job = hl_cs_allocate_job(hdev, q_type, true);
915         if (!job) {
916                 ctx->cs_counters.out_of_mem_drop_cnt++;
917                 dev_err(hdev->dev, "Failed to allocate a new job\n");
918                 rc = -ENOMEM;
919                 goto put_cs;
920         }
921
922         cb = hl_cb_kernel_create(hdev, PAGE_SIZE);
923         if (!cb) {
924                 ctx->cs_counters.out_of_mem_drop_cnt++;
925                 kfree(job);
926                 rc = -EFAULT;
927                 goto put_cs;
928         }
929
930         if (cs->type == CS_TYPE_WAIT)
931                 cb_size = hdev->asic_funcs->get_wait_cb_size(hdev);
932         else
933                 cb_size = hdev->asic_funcs->get_signal_cb_size(hdev);
934
935         job->id = 0;
936         job->cs = cs;
937         job->user_cb = cb;
938         job->user_cb->cs_cnt++;
939         job->user_cb_size = cb_size;
940         job->hw_queue_id = q_idx;
941
942         /*
943          * No need in parsing, user CB is the patched CB.
944          * We call hl_cb_destroy() out of two reasons - we don't need the CB in
945          * the CB idr anymore and to decrement its refcount as it was
946          * incremented inside hl_cb_kernel_create().
947          */
948         job->patched_cb = job->user_cb;
949         job->job_cb_size = job->user_cb_size;
950         hl_cb_destroy(hdev, &hdev->kernel_cb_mgr, cb->id << PAGE_SHIFT);
951
952         cs->jobs_in_queue_cnt[job->hw_queue_id]++;
953
954         list_add_tail(&job->cs_node, &cs->job_list);
955
956         /* increment refcount as for external queues we get completion */
957         cs_get(cs);
958
959         hl_debugfs_add_job(hdev, job);
960
961         rc = hl_hw_queue_schedule_cs(cs);
962         if (rc) {
963                 if (rc != -EAGAIN)
964                         dev_err(hdev->dev,
965                                 "Failed to submit CS %d.%llu to H/W queues, error %d\n",
966                                 ctx->asid, cs->sequence, rc);
967                 goto free_cs_object;
968         }
969
970         rc = HL_CS_STATUS_SUCCESS;
971         goto put_cs;
972
973 free_cs_object:
974         cs_rollback(hdev, cs);
975         *cs_seq = ULLONG_MAX;
976         /* The path below is both for good and erroneous exits */
977 put_cs:
978         /* We finished with the CS in this function, so put the ref */
979         cs_put(cs);
980 free_signal_seq_array:
981         if (cs_type == CS_TYPE_WAIT)
982                 kfree(signal_seq_arr);
983 free_cs_chunk_array:
984         kfree(cs_chunk_array);
985 out:
986         return rc;
987 }
988
989 int hl_cs_ioctl(struct hl_fpriv *hpriv, void *data)
990 {
991         struct hl_device *hdev = hpriv->hdev;
992         union hl_cs_args *args = data;
993         struct hl_ctx *ctx = hpriv->ctx;
994         void __user *chunks_execute, *chunks_restore;
995         enum hl_cs_type cs_type;
996         u32 num_chunks_execute, num_chunks_restore, sig_wait_flags;
997         u64 cs_seq = ULONG_MAX;
998         int rc, do_ctx_switch;
999         bool need_soft_reset = false;
1000
1001         if (hl_device_disabled_or_in_reset(hdev)) {
1002                 dev_warn_ratelimited(hdev->dev,
1003                         "Device is %s. Can't submit new CS\n",
1004                         atomic_read(&hdev->in_reset) ? "in_reset" : "disabled");
1005                 rc = -EBUSY;
1006                 goto out;
1007         }
1008
1009         sig_wait_flags = args->in.cs_flags & HL_CS_FLAGS_SIG_WAIT;
1010
1011         if (unlikely(sig_wait_flags == HL_CS_FLAGS_SIG_WAIT)) {
1012                 dev_err(hdev->dev,
1013                         "Signal and wait CS flags are mutually exclusive, context %d\n",
1014                 ctx->asid);
1015                 rc = -EINVAL;
1016                 goto out;
1017         }
1018
1019         if (unlikely((sig_wait_flags & HL_CS_FLAGS_SIG_WAIT) &&
1020                         (!hdev->supports_sync_stream))) {
1021                 dev_err(hdev->dev, "Sync stream CS is not supported\n");
1022                 rc = -EINVAL;
1023                 goto out;
1024         }
1025
1026         if (args->in.cs_flags & HL_CS_FLAGS_SIGNAL)
1027                 cs_type = CS_TYPE_SIGNAL;
1028         else if (args->in.cs_flags & HL_CS_FLAGS_WAIT)
1029                 cs_type = CS_TYPE_WAIT;
1030         else
1031                 cs_type = CS_TYPE_DEFAULT;
1032
1033         chunks_execute = (void __user *) (uintptr_t) args->in.chunks_execute;
1034         num_chunks_execute = args->in.num_chunks_execute;
1035
1036         if (cs_type == CS_TYPE_DEFAULT) {
1037                 if (!num_chunks_execute) {
1038                         dev_err(hdev->dev,
1039                                 "Got execute CS with 0 chunks, context %d\n",
1040                                 ctx->asid);
1041                         rc = -EINVAL;
1042                         goto out;
1043                 }
1044         } else if (num_chunks_execute != 1) {
1045                 dev_err(hdev->dev,
1046                         "Sync stream CS mandates one chunk only, context %d\n",
1047                         ctx->asid);
1048                 rc = -EINVAL;
1049                 goto out;
1050         }
1051
1052         do_ctx_switch = atomic_cmpxchg(&ctx->thread_ctx_switch_token, 1, 0);
1053
1054         if (do_ctx_switch || (args->in.cs_flags & HL_CS_FLAGS_FORCE_RESTORE)) {
1055                 long ret;
1056
1057                 chunks_restore =
1058                         (void __user *) (uintptr_t) args->in.chunks_restore;
1059                 num_chunks_restore = args->in.num_chunks_restore;
1060
1061                 mutex_lock(&hpriv->restore_phase_mutex);
1062
1063                 if (do_ctx_switch) {
1064                         rc = hdev->asic_funcs->context_switch(hdev, ctx->asid);
1065                         if (rc) {
1066                                 dev_err_ratelimited(hdev->dev,
1067                                         "Failed to switch to context %d, rejecting CS! %d\n",
1068                                         ctx->asid, rc);
1069                                 /*
1070                                  * If we timedout, or if the device is not IDLE
1071                                  * while we want to do context-switch (-EBUSY),
1072                                  * we need to soft-reset because QMAN is
1073                                  * probably stuck. However, we can't call to
1074                                  * reset here directly because of deadlock, so
1075                                  * need to do it at the very end of this
1076                                  * function
1077                                  */
1078                                 if ((rc == -ETIMEDOUT) || (rc == -EBUSY))
1079                                         need_soft_reset = true;
1080                                 mutex_unlock(&hpriv->restore_phase_mutex);
1081                                 goto out;
1082                         }
1083                 }
1084
1085                 hdev->asic_funcs->restore_phase_topology(hdev);
1086
1087                 if (!num_chunks_restore) {
1088                         dev_dbg(hdev->dev,
1089                         "Need to run restore phase but restore CS is empty\n");
1090                         rc = 0;
1091                 } else {
1092                         rc = cs_ioctl_default(hpriv, chunks_restore,
1093                                                 num_chunks_restore, &cs_seq);
1094                 }
1095
1096                 mutex_unlock(&hpriv->restore_phase_mutex);
1097
1098                 if (rc) {
1099                         dev_err(hdev->dev,
1100                                 "Failed to submit restore CS for context %d (%d)\n",
1101                                 ctx->asid, rc);
1102                         goto out;
1103                 }
1104
1105                 /* Need to wait for restore completion before execution phase */
1106                 if (num_chunks_restore) {
1107                         ret = _hl_cs_wait_ioctl(hdev, ctx,
1108                                         jiffies_to_usecs(hdev->timeout_jiffies),
1109                                         cs_seq);
1110                         if (ret <= 0) {
1111                                 dev_err(hdev->dev,
1112                                         "Restore CS for context %d failed to complete %ld\n",
1113                                         ctx->asid, ret);
1114                                 rc = -ENOEXEC;
1115                                 goto out;
1116                         }
1117                 }
1118
1119                 ctx->thread_ctx_switch_wait_token = 1;
1120         } else if (!ctx->thread_ctx_switch_wait_token) {
1121                 u32 tmp;
1122
1123                 rc = hl_poll_timeout_memory(hdev,
1124                         &ctx->thread_ctx_switch_wait_token, tmp, (tmp == 1),
1125                         100, jiffies_to_usecs(hdev->timeout_jiffies), false);
1126
1127                 if (rc == -ETIMEDOUT) {
1128                         dev_err(hdev->dev,
1129                                 "context switch phase timeout (%d)\n", tmp);
1130                         goto out;
1131                 }
1132         }
1133
1134         if (cs_type == CS_TYPE_DEFAULT)
1135                 rc = cs_ioctl_default(hpriv, chunks_execute, num_chunks_execute,
1136                                         &cs_seq);
1137         else
1138                 rc = cs_ioctl_signal_wait(hpriv, cs_type, chunks_execute,
1139                                                 num_chunks_execute, &cs_seq);
1140
1141 out:
1142         if (rc != -EAGAIN) {
1143                 memset(args, 0, sizeof(*args));
1144                 args->out.status = rc;
1145                 args->out.seq = cs_seq;
1146         }
1147
1148         if (((rc == -ETIMEDOUT) || (rc == -EBUSY)) && (need_soft_reset))
1149                 hl_device_reset(hdev, false, false);
1150
1151         return rc;
1152 }
1153
1154 static long _hl_cs_wait_ioctl(struct hl_device *hdev,
1155                 struct hl_ctx *ctx, u64 timeout_us, u64 seq)
1156 {
1157         struct dma_fence *fence;
1158         unsigned long timeout;
1159         long rc;
1160
1161         if (timeout_us == MAX_SCHEDULE_TIMEOUT)
1162                 timeout = timeout_us;
1163         else
1164                 timeout = usecs_to_jiffies(timeout_us);
1165
1166         hl_ctx_get(hdev, ctx);
1167
1168         fence = hl_ctx_get_fence(ctx, seq);
1169         if (IS_ERR(fence)) {
1170                 rc = PTR_ERR(fence);
1171                 if (rc == -EINVAL)
1172                         dev_notice_ratelimited(hdev->dev,
1173                                 "Can't wait on CS %llu because current CS is at seq %llu\n",
1174                                 seq, ctx->cs_sequence);
1175         } else if (fence) {
1176                 rc = dma_fence_wait_timeout(fence, true, timeout);
1177                 if (fence->error == -ETIMEDOUT)
1178                         rc = -ETIMEDOUT;
1179                 else if (fence->error == -EIO)
1180                         rc = -EIO;
1181                 dma_fence_put(fence);
1182         } else {
1183                 dev_dbg(hdev->dev,
1184                         "Can't wait on seq %llu because current CS is at seq %llu (Fence is gone)\n",
1185                         seq, ctx->cs_sequence);
1186                 rc = 1;
1187         }
1188
1189         hl_ctx_put(ctx);
1190
1191         return rc;
1192 }
1193
1194 int hl_cs_wait_ioctl(struct hl_fpriv *hpriv, void *data)
1195 {
1196         struct hl_device *hdev = hpriv->hdev;
1197         union hl_wait_cs_args *args = data;
1198         u64 seq = args->in.seq;
1199         long rc;
1200
1201         rc = _hl_cs_wait_ioctl(hdev, hpriv->ctx, args->in.timeout_us, seq);
1202
1203         memset(args, 0, sizeof(*args));
1204
1205         if (rc < 0) {
1206                 if (rc == -ERESTARTSYS) {
1207                         dev_err_ratelimited(hdev->dev,
1208                                 "user process got signal while waiting for CS handle %llu\n",
1209                                 seq);
1210                         args->out.status = HL_WAIT_CS_STATUS_INTERRUPTED;
1211                         rc = -EINTR;
1212                 } else if (rc == -ETIMEDOUT) {
1213                         dev_err_ratelimited(hdev->dev,
1214                                 "CS %llu has timed-out while user process is waiting for it\n",
1215                                 seq);
1216                         args->out.status = HL_WAIT_CS_STATUS_TIMEDOUT;
1217                 } else if (rc == -EIO) {
1218                         dev_err_ratelimited(hdev->dev,
1219                                 "CS %llu has been aborted while user process is waiting for it\n",
1220                                 seq);
1221                         args->out.status = HL_WAIT_CS_STATUS_ABORTED;
1222                 }
1223                 return rc;
1224         }
1225
1226         if (rc == 0)
1227                 args->out.status = HL_WAIT_CS_STATUS_BUSY;
1228         else
1229                 args->out.status = HL_WAIT_CS_STATUS_COMPLETED;
1230
1231         return 0;
1232 }