]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/gpu/drm/amd/amdgpu/amdgpu_cs.c
144b251bd7c8e945dbcf9830e6d59e7866640388
[karo-tx-linux.git] / drivers / gpu / drm / amd / amdgpu / amdgpu_cs.c
1 /*
2  * Copyright 2008 Jerome Glisse.
3  * All Rights Reserved.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice (including the next
13  * paragraph) shall be included in all copies or substantial portions of the
14  * Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
19  * PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22  * DEALINGS IN THE SOFTWARE.
23  *
24  * Authors:
25  *    Jerome Glisse <glisse@freedesktop.org>
26  */
27 #include <linux/pagemap.h>
28 #include <drm/drmP.h>
29 #include <drm/amdgpu_drm.h>
30 #include <drm/drm_syncobj.h>
31 #include "amdgpu.h"
32 #include "amdgpu_trace.h"
33
34 static int amdgpu_cs_user_fence_chunk(struct amdgpu_cs_parser *p,
35                                       struct drm_amdgpu_cs_chunk_fence *data,
36                                       uint32_t *offset)
37 {
38         struct drm_gem_object *gobj;
39         unsigned long size;
40
41         gobj = drm_gem_object_lookup(p->filp, data->handle);
42         if (gobj == NULL)
43                 return -EINVAL;
44
45         p->uf_entry.robj = amdgpu_bo_ref(gem_to_amdgpu_bo(gobj));
46         p->uf_entry.priority = 0;
47         p->uf_entry.tv.bo = &p->uf_entry.robj->tbo;
48         p->uf_entry.tv.shared = true;
49         p->uf_entry.user_pages = NULL;
50
51         size = amdgpu_bo_size(p->uf_entry.robj);
52         if (size != PAGE_SIZE || (data->offset + 8) > size)
53                 return -EINVAL;
54
55         *offset = data->offset;
56
57         drm_gem_object_unreference_unlocked(gobj);
58
59         if (amdgpu_ttm_tt_get_usermm(p->uf_entry.robj->tbo.ttm)) {
60                 amdgpu_bo_unref(&p->uf_entry.robj);
61                 return -EINVAL;
62         }
63
64         return 0;
65 }
66
67 int amdgpu_cs_parser_init(struct amdgpu_cs_parser *p, void *data)
68 {
69         struct amdgpu_fpriv *fpriv = p->filp->driver_priv;
70         struct amdgpu_vm *vm = &fpriv->vm;
71         union drm_amdgpu_cs *cs = data;
72         uint64_t *chunk_array_user;
73         uint64_t *chunk_array;
74         unsigned size, num_ibs = 0;
75         uint32_t uf_offset = 0;
76         int i;
77         int ret;
78
79         if (cs->in.num_chunks == 0)
80                 return 0;
81
82         chunk_array = kmalloc_array(cs->in.num_chunks, sizeof(uint64_t), GFP_KERNEL);
83         if (!chunk_array)
84                 return -ENOMEM;
85
86         p->ctx = amdgpu_ctx_get(fpriv, cs->in.ctx_id);
87         if (!p->ctx) {
88                 ret = -EINVAL;
89                 goto free_chunk;
90         }
91
92         /* get chunks */
93         chunk_array_user = (uint64_t __user *)(uintptr_t)(cs->in.chunks);
94         if (copy_from_user(chunk_array, chunk_array_user,
95                            sizeof(uint64_t)*cs->in.num_chunks)) {
96                 ret = -EFAULT;
97                 goto put_ctx;
98         }
99
100         p->nchunks = cs->in.num_chunks;
101         p->chunks = kmalloc_array(p->nchunks, sizeof(struct amdgpu_cs_chunk),
102                             GFP_KERNEL);
103         if (!p->chunks) {
104                 ret = -ENOMEM;
105                 goto put_ctx;
106         }
107
108         for (i = 0; i < p->nchunks; i++) {
109                 struct drm_amdgpu_cs_chunk __user **chunk_ptr = NULL;
110                 struct drm_amdgpu_cs_chunk user_chunk;
111                 uint32_t __user *cdata;
112
113                 chunk_ptr = (void __user *)(uintptr_t)chunk_array[i];
114                 if (copy_from_user(&user_chunk, chunk_ptr,
115                                        sizeof(struct drm_amdgpu_cs_chunk))) {
116                         ret = -EFAULT;
117                         i--;
118                         goto free_partial_kdata;
119                 }
120                 p->chunks[i].chunk_id = user_chunk.chunk_id;
121                 p->chunks[i].length_dw = user_chunk.length_dw;
122
123                 size = p->chunks[i].length_dw;
124                 cdata = (void __user *)(uintptr_t)user_chunk.chunk_data;
125
126                 p->chunks[i].kdata = kvmalloc_array(size, sizeof(uint32_t), GFP_KERNEL);
127                 if (p->chunks[i].kdata == NULL) {
128                         ret = -ENOMEM;
129                         i--;
130                         goto free_partial_kdata;
131                 }
132                 size *= sizeof(uint32_t);
133                 if (copy_from_user(p->chunks[i].kdata, cdata, size)) {
134                         ret = -EFAULT;
135                         goto free_partial_kdata;
136                 }
137
138                 switch (p->chunks[i].chunk_id) {
139                 case AMDGPU_CHUNK_ID_IB:
140                         ++num_ibs;
141                         break;
142
143                 case AMDGPU_CHUNK_ID_FENCE:
144                         size = sizeof(struct drm_amdgpu_cs_chunk_fence);
145                         if (p->chunks[i].length_dw * sizeof(uint32_t) < size) {
146                                 ret = -EINVAL;
147                                 goto free_partial_kdata;
148                         }
149
150                         ret = amdgpu_cs_user_fence_chunk(p, p->chunks[i].kdata,
151                                                          &uf_offset);
152                         if (ret)
153                                 goto free_partial_kdata;
154
155                         break;
156
157                 case AMDGPU_CHUNK_ID_DEPENDENCIES:
158                 case AMDGPU_CHUNK_ID_SYNCOBJ_IN:
159                 case AMDGPU_CHUNK_ID_SYNCOBJ_OUT:
160                         break;
161
162                 default:
163                         ret = -EINVAL;
164                         goto free_partial_kdata;
165                 }
166         }
167
168         ret = amdgpu_job_alloc(p->adev, num_ibs, &p->job, vm);
169         if (ret)
170                 goto free_all_kdata;
171
172         if (p->uf_entry.robj)
173                 p->job->uf_addr = uf_offset;
174         kfree(chunk_array);
175         return 0;
176
177 free_all_kdata:
178         i = p->nchunks - 1;
179 free_partial_kdata:
180         for (; i >= 0; i--)
181                 kvfree(p->chunks[i].kdata);
182         kfree(p->chunks);
183         p->chunks = NULL;
184         p->nchunks = 0;
185 put_ctx:
186         amdgpu_ctx_put(p->ctx);
187 free_chunk:
188         kfree(chunk_array);
189
190         return ret;
191 }
192
193 /* Convert microseconds to bytes. */
194 static u64 us_to_bytes(struct amdgpu_device *adev, s64 us)
195 {
196         if (us <= 0 || !adev->mm_stats.log2_max_MBps)
197                 return 0;
198
199         /* Since accum_us is incremented by a million per second, just
200          * multiply it by the number of MB/s to get the number of bytes.
201          */
202         return us << adev->mm_stats.log2_max_MBps;
203 }
204
205 static s64 bytes_to_us(struct amdgpu_device *adev, u64 bytes)
206 {
207         if (!adev->mm_stats.log2_max_MBps)
208                 return 0;
209
210         return bytes >> adev->mm_stats.log2_max_MBps;
211 }
212
213 /* Returns how many bytes TTM can move right now. If no bytes can be moved,
214  * it returns 0. If it returns non-zero, it's OK to move at least one buffer,
215  * which means it can go over the threshold once. If that happens, the driver
216  * will be in debt and no other buffer migrations can be done until that debt
217  * is repaid.
218  *
219  * This approach allows moving a buffer of any size (it's important to allow
220  * that).
221  *
222  * The currency is simply time in microseconds and it increases as the clock
223  * ticks. The accumulated microseconds (us) are converted to bytes and
224  * returned.
225  */
226 static u64 amdgpu_cs_get_threshold_for_moves(struct amdgpu_device *adev)
227 {
228         s64 time_us, increment_us;
229         u64 max_bytes;
230         u64 free_vram, total_vram, used_vram;
231
232         /* Allow a maximum of 200 accumulated ms. This is basically per-IB
233          * throttling.
234          *
235          * It means that in order to get full max MBps, at least 5 IBs per
236          * second must be submitted and not more than 200ms apart from each
237          * other.
238          */
239         const s64 us_upper_bound = 200000;
240
241         if (!adev->mm_stats.log2_max_MBps)
242                 return 0;
243
244         total_vram = adev->mc.real_vram_size - adev->vram_pin_size;
245         used_vram = atomic64_read(&adev->vram_usage);
246         free_vram = used_vram >= total_vram ? 0 : total_vram - used_vram;
247
248         spin_lock(&adev->mm_stats.lock);
249
250         /* Increase the amount of accumulated us. */
251         time_us = ktime_to_us(ktime_get());
252         increment_us = time_us - adev->mm_stats.last_update_us;
253         adev->mm_stats.last_update_us = time_us;
254         adev->mm_stats.accum_us = min(adev->mm_stats.accum_us + increment_us,
255                                       us_upper_bound);
256
257         /* This prevents the short period of low performance when the VRAM
258          * usage is low and the driver is in debt or doesn't have enough
259          * accumulated us to fill VRAM quickly.
260          *
261          * The situation can occur in these cases:
262          * - a lot of VRAM is freed by userspace
263          * - the presence of a big buffer causes a lot of evictions
264          *   (solution: split buffers into smaller ones)
265          *
266          * If 128 MB or 1/8th of VRAM is free, start filling it now by setting
267          * accum_us to a positive number.
268          */
269         if (free_vram >= 128 * 1024 * 1024 || free_vram >= total_vram / 8) {
270                 s64 min_us;
271
272                 /* Be more aggresive on dGPUs. Try to fill a portion of free
273                  * VRAM now.
274                  */
275                 if (!(adev->flags & AMD_IS_APU))
276                         min_us = bytes_to_us(adev, free_vram / 4);
277                 else
278                         min_us = 0; /* Reset accum_us on APUs. */
279
280                 adev->mm_stats.accum_us = max(min_us, adev->mm_stats.accum_us);
281         }
282
283         /* This returns 0 if the driver is in debt to disallow (optional)
284          * buffer moves.
285          */
286         max_bytes = us_to_bytes(adev, adev->mm_stats.accum_us);
287
288         spin_unlock(&adev->mm_stats.lock);
289         return max_bytes;
290 }
291
292 /* Report how many bytes have really been moved for the last command
293  * submission. This can result in a debt that can stop buffer migrations
294  * temporarily.
295  */
296 void amdgpu_cs_report_moved_bytes(struct amdgpu_device *adev, u64 num_bytes)
297 {
298         spin_lock(&adev->mm_stats.lock);
299         adev->mm_stats.accum_us -= bytes_to_us(adev, num_bytes);
300         spin_unlock(&adev->mm_stats.lock);
301 }
302
303 static int amdgpu_cs_bo_validate(struct amdgpu_cs_parser *p,
304                                  struct amdgpu_bo *bo)
305 {
306         struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
307         u64 initial_bytes_moved;
308         uint32_t domain;
309         int r;
310
311         if (bo->pin_count)
312                 return 0;
313
314         /* Don't move this buffer if we have depleted our allowance
315          * to move it. Don't move anything if the threshold is zero.
316          */
317         if (p->bytes_moved < p->bytes_moved_threshold)
318                 domain = bo->prefered_domains;
319         else
320                 domain = bo->allowed_domains;
321
322 retry:
323         amdgpu_ttm_placement_from_domain(bo, domain);
324         initial_bytes_moved = atomic64_read(&adev->num_bytes_moved);
325         r = ttm_bo_validate(&bo->tbo, &bo->placement, true, false);
326         p->bytes_moved += atomic64_read(&adev->num_bytes_moved) -
327                 initial_bytes_moved;
328
329         if (unlikely(r == -ENOMEM) && domain != bo->allowed_domains) {
330                 domain = bo->allowed_domains;
331                 goto retry;
332         }
333
334         return r;
335 }
336
337 /* Last resort, try to evict something from the current working set */
338 static bool amdgpu_cs_try_evict(struct amdgpu_cs_parser *p,
339                                 struct amdgpu_bo *validated)
340 {
341         uint32_t domain = validated->allowed_domains;
342         int r;
343
344         if (!p->evictable)
345                 return false;
346
347         for (;&p->evictable->tv.head != &p->validated;
348              p->evictable = list_prev_entry(p->evictable, tv.head)) {
349
350                 struct amdgpu_bo_list_entry *candidate = p->evictable;
351                 struct amdgpu_bo *bo = candidate->robj;
352                 struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
353                 u64 initial_bytes_moved;
354                 uint32_t other;
355
356                 /* If we reached our current BO we can forget it */
357                 if (candidate->robj == validated)
358                         break;
359
360                 other = amdgpu_mem_type_to_domain(bo->tbo.mem.mem_type);
361
362                 /* Check if this BO is in one of the domains we need space for */
363                 if (!(other & domain))
364                         continue;
365
366                 /* Check if we can move this BO somewhere else */
367                 other = bo->allowed_domains & ~domain;
368                 if (!other)
369                         continue;
370
371                 /* Good we can try to move this BO somewhere else */
372                 amdgpu_ttm_placement_from_domain(bo, other);
373                 initial_bytes_moved = atomic64_read(&adev->num_bytes_moved);
374                 r = ttm_bo_validate(&bo->tbo, &bo->placement, true, false);
375                 p->bytes_moved += atomic64_read(&adev->num_bytes_moved) -
376                         initial_bytes_moved;
377
378                 if (unlikely(r))
379                         break;
380
381                 p->evictable = list_prev_entry(p->evictable, tv.head);
382                 list_move(&candidate->tv.head, &p->validated);
383
384                 return true;
385         }
386
387         return false;
388 }
389
390 static int amdgpu_cs_validate(void *param, struct amdgpu_bo *bo)
391 {
392         struct amdgpu_cs_parser *p = param;
393         int r;
394
395         do {
396                 r = amdgpu_cs_bo_validate(p, bo);
397         } while (r == -ENOMEM && amdgpu_cs_try_evict(p, bo));
398         if (r)
399                 return r;
400
401         if (bo->shadow)
402                 r = amdgpu_cs_bo_validate(p, bo->shadow);
403
404         return r;
405 }
406
407 static int amdgpu_cs_list_validate(struct amdgpu_cs_parser *p,
408                             struct list_head *validated)
409 {
410         struct amdgpu_bo_list_entry *lobj;
411         int r;
412
413         list_for_each_entry(lobj, validated, tv.head) {
414                 struct amdgpu_bo *bo = lobj->robj;
415                 bool binding_userptr = false;
416                 struct mm_struct *usermm;
417
418                 usermm = amdgpu_ttm_tt_get_usermm(bo->tbo.ttm);
419                 if (usermm && usermm != current->mm)
420                         return -EPERM;
421
422                 /* Check if we have user pages and nobody bound the BO already */
423                 if (lobj->user_pages && bo->tbo.ttm->state != tt_bound) {
424                         size_t size = sizeof(struct page *);
425
426                         size *= bo->tbo.ttm->num_pages;
427                         memcpy(bo->tbo.ttm->pages, lobj->user_pages, size);
428                         binding_userptr = true;
429                 }
430
431                 if (p->evictable == lobj)
432                         p->evictable = NULL;
433
434                 r = amdgpu_cs_validate(p, bo);
435                 if (r)
436                         return r;
437
438                 if (binding_userptr) {
439                         kvfree(lobj->user_pages);
440                         lobj->user_pages = NULL;
441                 }
442         }
443         return 0;
444 }
445
446 static int amdgpu_cs_parser_bos(struct amdgpu_cs_parser *p,
447                                 union drm_amdgpu_cs *cs)
448 {
449         struct amdgpu_fpriv *fpriv = p->filp->driver_priv;
450         struct amdgpu_bo_list_entry *e;
451         struct list_head duplicates;
452         bool need_mmap_lock = false;
453         unsigned i, tries = 10;
454         int r;
455
456         INIT_LIST_HEAD(&p->validated);
457
458         p->bo_list = amdgpu_bo_list_get(fpriv, cs->in.bo_list_handle);
459         if (p->bo_list) {
460                 need_mmap_lock = p->bo_list->first_userptr !=
461                         p->bo_list->num_entries;
462                 amdgpu_bo_list_get_list(p->bo_list, &p->validated);
463         }
464
465         INIT_LIST_HEAD(&duplicates);
466         amdgpu_vm_get_pd_bo(&fpriv->vm, &p->validated, &p->vm_pd);
467
468         if (p->uf_entry.robj)
469                 list_add(&p->uf_entry.tv.head, &p->validated);
470
471         if (need_mmap_lock)
472                 down_read(&current->mm->mmap_sem);
473
474         while (1) {
475                 struct list_head need_pages;
476                 unsigned i;
477
478                 r = ttm_eu_reserve_buffers(&p->ticket, &p->validated, true,
479                                            &duplicates);
480                 if (unlikely(r != 0)) {
481                         if (r != -ERESTARTSYS)
482                                 DRM_ERROR("ttm_eu_reserve_buffers failed.\n");
483                         goto error_free_pages;
484                 }
485
486                 /* Without a BO list we don't have userptr BOs */
487                 if (!p->bo_list)
488                         break;
489
490                 INIT_LIST_HEAD(&need_pages);
491                 for (i = p->bo_list->first_userptr;
492                      i < p->bo_list->num_entries; ++i) {
493
494                         e = &p->bo_list->array[i];
495
496                         if (amdgpu_ttm_tt_userptr_invalidated(e->robj->tbo.ttm,
497                                  &e->user_invalidated) && e->user_pages) {
498
499                                 /* We acquired a page array, but somebody
500                                  * invalidated it. Free it and try again
501                                  */
502                                 release_pages(e->user_pages,
503                                               e->robj->tbo.ttm->num_pages,
504                                               false);
505                                 kvfree(e->user_pages);
506                                 e->user_pages = NULL;
507                         }
508
509                         if (e->robj->tbo.ttm->state != tt_bound &&
510                             !e->user_pages) {
511                                 list_del(&e->tv.head);
512                                 list_add(&e->tv.head, &need_pages);
513
514                                 amdgpu_bo_unreserve(e->robj);
515                         }
516                 }
517
518                 if (list_empty(&need_pages))
519                         break;
520
521                 /* Unreserve everything again. */
522                 ttm_eu_backoff_reservation(&p->ticket, &p->validated);
523
524                 /* We tried too many times, just abort */
525                 if (!--tries) {
526                         r = -EDEADLK;
527                         DRM_ERROR("deadlock in %s\n", __func__);
528                         goto error_free_pages;
529                 }
530
531                 /* Fill the page arrays for all userptrs. */
532                 list_for_each_entry(e, &need_pages, tv.head) {
533                         struct ttm_tt *ttm = e->robj->tbo.ttm;
534
535                         e->user_pages = kvmalloc_array(ttm->num_pages,
536                                                          sizeof(struct page*),
537                                                          GFP_KERNEL | __GFP_ZERO);
538                         if (!e->user_pages) {
539                                 r = -ENOMEM;
540                                 DRM_ERROR("calloc failure in %s\n", __func__);
541                                 goto error_free_pages;
542                         }
543
544                         r = amdgpu_ttm_tt_get_user_pages(ttm, e->user_pages);
545                         if (r) {
546                                 DRM_ERROR("amdgpu_ttm_tt_get_user_pages failed.\n");
547                                 kvfree(e->user_pages);
548                                 e->user_pages = NULL;
549                                 goto error_free_pages;
550                         }
551                 }
552
553                 /* And try again. */
554                 list_splice(&need_pages, &p->validated);
555         }
556
557         p->bytes_moved_threshold = amdgpu_cs_get_threshold_for_moves(p->adev);
558         p->bytes_moved = 0;
559         p->evictable = list_last_entry(&p->validated,
560                                        struct amdgpu_bo_list_entry,
561                                        tv.head);
562
563         r = amdgpu_vm_validate_pt_bos(p->adev, &fpriv->vm,
564                                       amdgpu_cs_validate, p);
565         if (r) {
566                 DRM_ERROR("amdgpu_vm_validate_pt_bos() failed.\n");
567                 goto error_validate;
568         }
569
570         r = amdgpu_cs_list_validate(p, &duplicates);
571         if (r) {
572                 DRM_ERROR("amdgpu_cs_list_validate(duplicates) failed.\n");
573                 goto error_validate;
574         }
575
576         r = amdgpu_cs_list_validate(p, &p->validated);
577         if (r) {
578                 DRM_ERROR("amdgpu_cs_list_validate(validated) failed.\n");
579                 goto error_validate;
580         }
581
582         amdgpu_cs_report_moved_bytes(p->adev, p->bytes_moved);
583
584         fpriv->vm.last_eviction_counter =
585                 atomic64_read(&p->adev->num_evictions);
586
587         if (p->bo_list) {
588                 struct amdgpu_bo *gds = p->bo_list->gds_obj;
589                 struct amdgpu_bo *gws = p->bo_list->gws_obj;
590                 struct amdgpu_bo *oa = p->bo_list->oa_obj;
591                 struct amdgpu_vm *vm = &fpriv->vm;
592                 unsigned i;
593
594                 for (i = 0; i < p->bo_list->num_entries; i++) {
595                         struct amdgpu_bo *bo = p->bo_list->array[i].robj;
596
597                         p->bo_list->array[i].bo_va = amdgpu_vm_bo_find(vm, bo);
598                 }
599
600                 if (gds) {
601                         p->job->gds_base = amdgpu_bo_gpu_offset(gds);
602                         p->job->gds_size = amdgpu_bo_size(gds);
603                 }
604                 if (gws) {
605                         p->job->gws_base = amdgpu_bo_gpu_offset(gws);
606                         p->job->gws_size = amdgpu_bo_size(gws);
607                 }
608                 if (oa) {
609                         p->job->oa_base = amdgpu_bo_gpu_offset(oa);
610                         p->job->oa_size = amdgpu_bo_size(oa);
611                 }
612         }
613
614         if (!r && p->uf_entry.robj) {
615                 struct amdgpu_bo *uf = p->uf_entry.robj;
616
617                 r = amdgpu_ttm_bind(&uf->tbo, &uf->tbo.mem);
618                 p->job->uf_addr += amdgpu_bo_gpu_offset(uf);
619         }
620
621 error_validate:
622         if (r) {
623                 amdgpu_vm_move_pt_bos_in_lru(p->adev, &fpriv->vm);
624                 ttm_eu_backoff_reservation(&p->ticket, &p->validated);
625         }
626
627 error_free_pages:
628
629         if (need_mmap_lock)
630                 up_read(&current->mm->mmap_sem);
631
632         if (p->bo_list) {
633                 for (i = p->bo_list->first_userptr;
634                      i < p->bo_list->num_entries; ++i) {
635                         e = &p->bo_list->array[i];
636
637                         if (!e->user_pages)
638                                 continue;
639
640                         release_pages(e->user_pages,
641                                       e->robj->tbo.ttm->num_pages,
642                                       false);
643                         kvfree(e->user_pages);
644                 }
645         }
646
647         return r;
648 }
649
650 static int amdgpu_cs_sync_rings(struct amdgpu_cs_parser *p)
651 {
652         struct amdgpu_bo_list_entry *e;
653         int r;
654
655         list_for_each_entry(e, &p->validated, tv.head) {
656                 struct reservation_object *resv = e->robj->tbo.resv;
657                 r = amdgpu_sync_resv(p->adev, &p->job->sync, resv, p->filp);
658
659                 if (r)
660                         return r;
661         }
662         return 0;
663 }
664
665 /**
666  * cs_parser_fini() - clean parser states
667  * @parser:     parser structure holding parsing context.
668  * @error:      error number
669  *
670  * If error is set than unvalidate buffer, otherwise just free memory
671  * used by parsing context.
672  **/
673 static void amdgpu_cs_parser_fini(struct amdgpu_cs_parser *parser, int error, bool backoff)
674 {
675         struct amdgpu_fpriv *fpriv = parser->filp->driver_priv;
676         unsigned i;
677
678         if (!error) {
679                 amdgpu_vm_move_pt_bos_in_lru(parser->adev, &fpriv->vm);
680
681                 ttm_eu_fence_buffer_objects(&parser->ticket,
682                                             &parser->validated,
683                                             parser->fence);
684         } else if (backoff) {
685                 ttm_eu_backoff_reservation(&parser->ticket,
686                                            &parser->validated);
687         }
688
689         for (i = 0; i < parser->num_post_dep_syncobjs; i++)
690                 drm_syncobj_put(parser->post_dep_syncobjs[i]);
691         kfree(parser->post_dep_syncobjs);
692
693         dma_fence_put(parser->fence);
694
695         if (parser->ctx)
696                 amdgpu_ctx_put(parser->ctx);
697         if (parser->bo_list)
698                 amdgpu_bo_list_put(parser->bo_list);
699
700         for (i = 0; i < parser->nchunks; i++)
701                 kvfree(parser->chunks[i].kdata);
702         kfree(parser->chunks);
703         if (parser->job)
704                 amdgpu_job_free(parser->job);
705         amdgpu_bo_unref(&parser->uf_entry.robj);
706 }
707
708 static int amdgpu_bo_vm_update_pte(struct amdgpu_cs_parser *p)
709 {
710         struct amdgpu_device *adev = p->adev;
711         struct amdgpu_fpriv *fpriv = p->filp->driver_priv;
712         struct amdgpu_vm *vm = &fpriv->vm;
713         struct amdgpu_bo_va *bo_va;
714         struct amdgpu_bo *bo;
715         int i, r;
716
717         r = amdgpu_vm_update_directories(adev, vm);
718         if (r)
719                 return r;
720
721         r = amdgpu_sync_fence(adev, &p->job->sync, vm->last_dir_update);
722         if (r)
723                 return r;
724
725         r = amdgpu_vm_clear_freed(adev, vm, NULL);
726         if (r)
727                 return r;
728
729         r = amdgpu_vm_bo_update(adev, fpriv->prt_va, false);
730         if (r)
731                 return r;
732
733         r = amdgpu_sync_fence(adev, &p->job->sync,
734                               fpriv->prt_va->last_pt_update);
735         if (r)
736                 return r;
737
738         if (amdgpu_sriov_vf(adev)) {
739                 struct dma_fence *f;
740                 bo_va = vm->csa_bo_va;
741                 BUG_ON(!bo_va);
742                 r = amdgpu_vm_bo_update(adev, bo_va, false);
743                 if (r)
744                         return r;
745
746                 f = bo_va->last_pt_update;
747                 r = amdgpu_sync_fence(adev, &p->job->sync, f);
748                 if (r)
749                         return r;
750         }
751
752         if (p->bo_list) {
753                 for (i = 0; i < p->bo_list->num_entries; i++) {
754                         struct dma_fence *f;
755
756                         /* ignore duplicates */
757                         bo = p->bo_list->array[i].robj;
758                         if (!bo)
759                                 continue;
760
761                         bo_va = p->bo_list->array[i].bo_va;
762                         if (bo_va == NULL)
763                                 continue;
764
765                         r = amdgpu_vm_bo_update(adev, bo_va, false);
766                         if (r)
767                                 return r;
768
769                         f = bo_va->last_pt_update;
770                         r = amdgpu_sync_fence(adev, &p->job->sync, f);
771                         if (r)
772                                 return r;
773                 }
774
775         }
776
777         r = amdgpu_vm_clear_invalids(adev, vm, &p->job->sync);
778
779         if (amdgpu_vm_debug && p->bo_list) {
780                 /* Invalidate all BOs to test for userspace bugs */
781                 for (i = 0; i < p->bo_list->num_entries; i++) {
782                         /* ignore duplicates */
783                         bo = p->bo_list->array[i].robj;
784                         if (!bo)
785                                 continue;
786
787                         amdgpu_vm_bo_invalidate(adev, bo);
788                 }
789         }
790
791         return r;
792 }
793
794 static int amdgpu_cs_ib_vm_chunk(struct amdgpu_device *adev,
795                                  struct amdgpu_cs_parser *p)
796 {
797         struct amdgpu_fpriv *fpriv = p->filp->driver_priv;
798         struct amdgpu_vm *vm = &fpriv->vm;
799         struct amdgpu_ring *ring = p->job->ring;
800         int i, r;
801
802         /* Only for UVD/VCE VM emulation */
803         if (ring->funcs->parse_cs) {
804                 for (i = 0; i < p->job->num_ibs; i++) {
805                         r = amdgpu_ring_parse_cs(ring, p, i);
806                         if (r)
807                                 return r;
808                 }
809         }
810
811         if (p->job->vm) {
812                 p->job->vm_pd_addr = amdgpu_bo_gpu_offset(vm->root.bo);
813
814                 r = amdgpu_bo_vm_update_pte(p);
815                 if (r)
816                         return r;
817         }
818
819         return amdgpu_cs_sync_rings(p);
820 }
821
822 static int amdgpu_cs_ib_fill(struct amdgpu_device *adev,
823                              struct amdgpu_cs_parser *parser)
824 {
825         struct amdgpu_fpriv *fpriv = parser->filp->driver_priv;
826         struct amdgpu_vm *vm = &fpriv->vm;
827         int i, j;
828         int r, ce_preempt = 0, de_preempt = 0;
829
830         for (i = 0, j = 0; i < parser->nchunks && j < parser->job->num_ibs; i++) {
831                 struct amdgpu_cs_chunk *chunk;
832                 struct amdgpu_ib *ib;
833                 struct drm_amdgpu_cs_chunk_ib *chunk_ib;
834                 struct amdgpu_ring *ring;
835
836                 chunk = &parser->chunks[i];
837                 ib = &parser->job->ibs[j];
838                 chunk_ib = (struct drm_amdgpu_cs_chunk_ib *)chunk->kdata;
839
840                 if (chunk->chunk_id != AMDGPU_CHUNK_ID_IB)
841                         continue;
842
843                 if (chunk_ib->ip_type == AMDGPU_HW_IP_GFX && amdgpu_sriov_vf(adev)) {
844                         if (chunk_ib->flags & AMDGPU_IB_FLAG_PREEMPT) {
845                                 if (chunk_ib->flags & AMDGPU_IB_FLAG_CE)
846                                         ce_preempt++;
847                                 else
848                                         de_preempt++;
849                         }
850
851                         /* each GFX command submit allows 0 or 1 IB preemptible for CE & DE */
852                         if (ce_preempt > 1 || de_preempt > 1)
853                                 return -EINVAL;
854                 }
855
856                 r = amdgpu_queue_mgr_map(adev, &parser->ctx->queue_mgr, chunk_ib->ip_type,
857                                          chunk_ib->ip_instance, chunk_ib->ring, &ring);
858                 if (r)
859                         return r;
860
861                 if (chunk_ib->flags & AMDGPU_IB_FLAG_PREAMBLE) {
862                         parser->job->preamble_status |= AMDGPU_PREAMBLE_IB_PRESENT;
863                         if (!parser->ctx->preamble_presented) {
864                                 parser->job->preamble_status |= AMDGPU_PREAMBLE_IB_PRESENT_FIRST;
865                                 parser->ctx->preamble_presented = true;
866                         }
867                 }
868
869                 if (parser->job->ring && parser->job->ring != ring)
870                         return -EINVAL;
871
872                 parser->job->ring = ring;
873
874                 if (ring->funcs->parse_cs) {
875                         struct amdgpu_bo_va_mapping *m;
876                         struct amdgpu_bo *aobj = NULL;
877                         uint64_t offset;
878                         uint8_t *kptr;
879
880                         m = amdgpu_cs_find_mapping(parser, chunk_ib->va_start,
881                                                    &aobj);
882                         if (!aobj) {
883                                 DRM_ERROR("IB va_start is invalid\n");
884                                 return -EINVAL;
885                         }
886
887                         if ((chunk_ib->va_start + chunk_ib->ib_bytes) >
888                             (m->last + 1) * AMDGPU_GPU_PAGE_SIZE) {
889                                 DRM_ERROR("IB va_start+ib_bytes is invalid\n");
890                                 return -EINVAL;
891                         }
892
893                         /* the IB should be reserved at this point */
894                         r = amdgpu_bo_kmap(aobj, (void **)&kptr);
895                         if (r) {
896                                 return r;
897                         }
898
899                         offset = m->start * AMDGPU_GPU_PAGE_SIZE;
900                         kptr += chunk_ib->va_start - offset;
901
902                         r =  amdgpu_ib_get(adev, vm, chunk_ib->ib_bytes, ib);
903                         if (r) {
904                                 DRM_ERROR("Failed to get ib !\n");
905                                 return r;
906                         }
907
908                         memcpy(ib->ptr, kptr, chunk_ib->ib_bytes);
909                         amdgpu_bo_kunmap(aobj);
910                 } else {
911                         r =  amdgpu_ib_get(adev, vm, 0, ib);
912                         if (r) {
913                                 DRM_ERROR("Failed to get ib !\n");
914                                 return r;
915                         }
916
917                 }
918
919                 ib->gpu_addr = chunk_ib->va_start;
920                 ib->length_dw = chunk_ib->ib_bytes / 4;
921                 ib->flags = chunk_ib->flags;
922                 j++;
923         }
924
925         /* UVD & VCE fw doesn't support user fences */
926         if (parser->job->uf_addr && (
927             parser->job->ring->funcs->type == AMDGPU_RING_TYPE_UVD ||
928             parser->job->ring->funcs->type == AMDGPU_RING_TYPE_VCE))
929                 return -EINVAL;
930
931         return 0;
932 }
933
934 static int amdgpu_cs_process_fence_dep(struct amdgpu_cs_parser *p,
935                                        struct amdgpu_cs_chunk *chunk)
936 {
937         struct amdgpu_fpriv *fpriv = p->filp->driver_priv;
938         unsigned num_deps;
939         int i, r;
940         struct drm_amdgpu_cs_chunk_dep *deps;
941
942         deps = (struct drm_amdgpu_cs_chunk_dep *)chunk->kdata;
943         num_deps = chunk->length_dw * 4 /
944                 sizeof(struct drm_amdgpu_cs_chunk_dep);
945
946         for (i = 0; i < num_deps; ++i) {
947                 struct amdgpu_ring *ring;
948                 struct amdgpu_ctx *ctx;
949                 struct dma_fence *fence;
950
951                 ctx = amdgpu_ctx_get(fpriv, deps[i].ctx_id);
952                 if (ctx == NULL)
953                         return -EINVAL;
954
955                 r = amdgpu_queue_mgr_map(p->adev, &ctx->queue_mgr,
956                                          deps[i].ip_type,
957                                          deps[i].ip_instance,
958                                          deps[i].ring, &ring);
959                 if (r) {
960                         amdgpu_ctx_put(ctx);
961                         return r;
962                 }
963
964                 fence = amdgpu_ctx_get_fence(ctx, ring,
965                                              deps[i].handle);
966                 if (IS_ERR(fence)) {
967                         r = PTR_ERR(fence);
968                         amdgpu_ctx_put(ctx);
969                         return r;
970                 } else if (fence) {
971                         r = amdgpu_sync_fence(p->adev, &p->job->sync,
972                                               fence);
973                         dma_fence_put(fence);
974                         amdgpu_ctx_put(ctx);
975                         if (r)
976                                 return r;
977                 }
978         }
979         return 0;
980 }
981
982 static int amdgpu_syncobj_lookup_and_add_to_sync(struct amdgpu_cs_parser *p,
983                                                  uint32_t handle)
984 {
985         int r;
986         struct dma_fence *fence;
987         r = drm_syncobj_fence_get(p->filp, handle, &fence);
988         if (r)
989                 return r;
990
991         r = amdgpu_sync_fence(p->adev, &p->job->sync, fence);
992         dma_fence_put(fence);
993
994         return r;
995 }
996
997 static int amdgpu_cs_process_syncobj_in_dep(struct amdgpu_cs_parser *p,
998                                             struct amdgpu_cs_chunk *chunk)
999 {
1000         unsigned num_deps;
1001         int i, r;
1002         struct drm_amdgpu_cs_chunk_sem *deps;
1003
1004         deps = (struct drm_amdgpu_cs_chunk_sem *)chunk->kdata;
1005         num_deps = chunk->length_dw * 4 /
1006                 sizeof(struct drm_amdgpu_cs_chunk_sem);
1007
1008         for (i = 0; i < num_deps; ++i) {
1009                 r = amdgpu_syncobj_lookup_and_add_to_sync(p, deps[i].handle);
1010                 if (r)
1011                         return r;
1012         }
1013         return 0;
1014 }
1015
1016 static int amdgpu_cs_process_syncobj_out_dep(struct amdgpu_cs_parser *p,
1017                                              struct amdgpu_cs_chunk *chunk)
1018 {
1019         unsigned num_deps;
1020         int i;
1021         struct drm_amdgpu_cs_chunk_sem *deps;
1022         deps = (struct drm_amdgpu_cs_chunk_sem *)chunk->kdata;
1023         num_deps = chunk->length_dw * 4 /
1024                 sizeof(struct drm_amdgpu_cs_chunk_sem);
1025
1026         p->post_dep_syncobjs = kmalloc_array(num_deps,
1027                                              sizeof(struct drm_syncobj *),
1028                                              GFP_KERNEL);
1029         p->num_post_dep_syncobjs = 0;
1030
1031         for (i = 0; i < num_deps; ++i) {
1032                 p->post_dep_syncobjs[i] = drm_syncobj_find(p->filp, deps[i].handle);
1033                 if (!p->post_dep_syncobjs[i])
1034                         return -EINVAL;
1035                 p->num_post_dep_syncobjs++;
1036         }
1037         return 0;
1038 }
1039
1040 static int amdgpu_cs_dependencies(struct amdgpu_device *adev,
1041                                   struct amdgpu_cs_parser *p)
1042 {
1043         int i, r;
1044
1045         for (i = 0; i < p->nchunks; ++i) {
1046                 struct amdgpu_cs_chunk *chunk;
1047
1048                 chunk = &p->chunks[i];
1049
1050                 if (chunk->chunk_id == AMDGPU_CHUNK_ID_DEPENDENCIES) {
1051                         r = amdgpu_cs_process_fence_dep(p, chunk);
1052                         if (r)
1053                                 return r;
1054                 } else if (chunk->chunk_id == AMDGPU_CHUNK_ID_SYNCOBJ_IN) {
1055                         r = amdgpu_cs_process_syncobj_in_dep(p, chunk);
1056                         if (r)
1057                                 return r;
1058                 } else if (chunk->chunk_id == AMDGPU_CHUNK_ID_SYNCOBJ_OUT) {
1059                         r = amdgpu_cs_process_syncobj_out_dep(p, chunk);
1060                         if (r)
1061                                 return r;
1062                 }
1063         }
1064
1065         return 0;
1066 }
1067
1068 static void amdgpu_cs_post_dependencies(struct amdgpu_cs_parser *p)
1069 {
1070         int i;
1071
1072         for (i = 0; i < p->num_post_dep_syncobjs; ++i) {
1073                 drm_syncobj_replace_fence(p->filp, p->post_dep_syncobjs[i],
1074                                           p->fence);
1075         }
1076 }
1077
1078 static int amdgpu_cs_submit(struct amdgpu_cs_parser *p,
1079                             union drm_amdgpu_cs *cs)
1080 {
1081         struct amdgpu_ring *ring = p->job->ring;
1082         struct amd_sched_entity *entity = &p->ctx->rings[ring->idx].entity;
1083         struct amdgpu_job *job;
1084         int r;
1085
1086         job = p->job;
1087         p->job = NULL;
1088
1089         r = amd_sched_job_init(&job->base, &ring->sched, entity, p->filp);
1090         if (r) {
1091                 amdgpu_job_free(job);
1092                 return r;
1093         }
1094
1095         job->owner = p->filp;
1096         job->fence_ctx = entity->fence_context;
1097         p->fence = dma_fence_get(&job->base.s_fence->finished);
1098
1099         amdgpu_cs_post_dependencies(p);
1100
1101         cs->out.handle = amdgpu_ctx_add_fence(p->ctx, ring, p->fence);
1102         job->uf_sequence = cs->out.handle;
1103         amdgpu_job_free_resources(job);
1104         amdgpu_cs_parser_fini(p, 0, true);
1105
1106         trace_amdgpu_cs_ioctl(job);
1107         amd_sched_entity_push_job(&job->base);
1108         return 0;
1109 }
1110
1111 int amdgpu_cs_ioctl(struct drm_device *dev, void *data, struct drm_file *filp)
1112 {
1113         struct amdgpu_device *adev = dev->dev_private;
1114         struct amdgpu_fpriv *fpriv = filp->driver_priv;
1115         union drm_amdgpu_cs *cs = data;
1116         struct amdgpu_cs_parser parser = {};
1117         bool reserved_buffers = false;
1118         int i, r;
1119
1120         if (!adev->accel_working)
1121                 return -EBUSY;
1122         if (amdgpu_kms_vram_lost(adev, fpriv))
1123                 return -ENODEV;
1124
1125         parser.adev = adev;
1126         parser.filp = filp;
1127
1128         r = amdgpu_cs_parser_init(&parser, data);
1129         if (r) {
1130                 DRM_ERROR("Failed to initialize parser !\n");
1131                 goto out;
1132         }
1133
1134         r = amdgpu_cs_parser_bos(&parser, data);
1135         if (r) {
1136                 if (r == -ENOMEM)
1137                         DRM_ERROR("Not enough memory for command submission!\n");
1138                 else if (r != -ERESTARTSYS)
1139                         DRM_ERROR("Failed to process the buffer list %d!\n", r);
1140                 goto out;
1141         }
1142
1143         reserved_buffers = true;
1144         r = amdgpu_cs_ib_fill(adev, &parser);
1145         if (r)
1146                 goto out;
1147
1148         r = amdgpu_cs_dependencies(adev, &parser);
1149         if (r) {
1150                 DRM_ERROR("Failed in the dependencies handling %d!\n", r);
1151                 goto out;
1152         }
1153
1154         for (i = 0; i < parser.job->num_ibs; i++)
1155                 trace_amdgpu_cs(&parser, i);
1156
1157         r = amdgpu_cs_ib_vm_chunk(adev, &parser);
1158         if (r)
1159                 goto out;
1160
1161         r = amdgpu_cs_submit(&parser, cs);
1162         if (r)
1163                 goto out;
1164
1165         return 0;
1166 out:
1167         amdgpu_cs_parser_fini(&parser, r, reserved_buffers);
1168         return r;
1169 }
1170
1171 /**
1172  * amdgpu_cs_wait_ioctl - wait for a command submission to finish
1173  *
1174  * @dev: drm device
1175  * @data: data from userspace
1176  * @filp: file private
1177  *
1178  * Wait for the command submission identified by handle to finish.
1179  */
1180 int amdgpu_cs_wait_ioctl(struct drm_device *dev, void *data,
1181                          struct drm_file *filp)
1182 {
1183         union drm_amdgpu_wait_cs *wait = data;
1184         struct amdgpu_device *adev = dev->dev_private;
1185         struct amdgpu_fpriv *fpriv = filp->driver_priv;
1186         unsigned long timeout = amdgpu_gem_timeout(wait->in.timeout);
1187         struct amdgpu_ring *ring = NULL;
1188         struct amdgpu_ctx *ctx;
1189         struct dma_fence *fence;
1190         long r;
1191
1192         if (amdgpu_kms_vram_lost(adev, fpriv))
1193                 return -ENODEV;
1194
1195         ctx = amdgpu_ctx_get(filp->driver_priv, wait->in.ctx_id);
1196         if (ctx == NULL)
1197                 return -EINVAL;
1198
1199         r = amdgpu_queue_mgr_map(adev, &ctx->queue_mgr,
1200                                  wait->in.ip_type, wait->in.ip_instance,
1201                                  wait->in.ring, &ring);
1202         if (r) {
1203                 amdgpu_ctx_put(ctx);
1204                 return r;
1205         }
1206
1207         fence = amdgpu_ctx_get_fence(ctx, ring, wait->in.handle);
1208         if (IS_ERR(fence))
1209                 r = PTR_ERR(fence);
1210         else if (fence) {
1211                 r = dma_fence_wait_timeout(fence, true, timeout);
1212                 dma_fence_put(fence);
1213         } else
1214                 r = 1;
1215
1216         amdgpu_ctx_put(ctx);
1217         if (r < 0)
1218                 return r;
1219
1220         memset(wait, 0, sizeof(*wait));
1221         wait->out.status = (r == 0);
1222
1223         return 0;
1224 }
1225
1226 /**
1227  * amdgpu_cs_get_fence - helper to get fence from drm_amdgpu_fence
1228  *
1229  * @adev: amdgpu device
1230  * @filp: file private
1231  * @user: drm_amdgpu_fence copied from user space
1232  */
1233 static struct dma_fence *amdgpu_cs_get_fence(struct amdgpu_device *adev,
1234                                              struct drm_file *filp,
1235                                              struct drm_amdgpu_fence *user)
1236 {
1237         struct amdgpu_ring *ring;
1238         struct amdgpu_ctx *ctx;
1239         struct dma_fence *fence;
1240         int r;
1241
1242         ctx = amdgpu_ctx_get(filp->driver_priv, user->ctx_id);
1243         if (ctx == NULL)
1244                 return ERR_PTR(-EINVAL);
1245
1246         r = amdgpu_queue_mgr_map(adev, &ctx->queue_mgr, user->ip_type,
1247                                  user->ip_instance, user->ring, &ring);
1248         if (r) {
1249                 amdgpu_ctx_put(ctx);
1250                 return ERR_PTR(r);
1251         }
1252
1253         fence = amdgpu_ctx_get_fence(ctx, ring, user->seq_no);
1254         amdgpu_ctx_put(ctx);
1255
1256         return fence;
1257 }
1258
1259 /**
1260  * amdgpu_cs_wait_all_fence - wait on all fences to signal
1261  *
1262  * @adev: amdgpu device
1263  * @filp: file private
1264  * @wait: wait parameters
1265  * @fences: array of drm_amdgpu_fence
1266  */
1267 static int amdgpu_cs_wait_all_fences(struct amdgpu_device *adev,
1268                                      struct drm_file *filp,
1269                                      union drm_amdgpu_wait_fences *wait,
1270                                      struct drm_amdgpu_fence *fences)
1271 {
1272         uint32_t fence_count = wait->in.fence_count;
1273         unsigned int i;
1274         long r = 1;
1275
1276         for (i = 0; i < fence_count; i++) {
1277                 struct dma_fence *fence;
1278                 unsigned long timeout = amdgpu_gem_timeout(wait->in.timeout_ns);
1279
1280                 fence = amdgpu_cs_get_fence(adev, filp, &fences[i]);
1281                 if (IS_ERR(fence))
1282                         return PTR_ERR(fence);
1283                 else if (!fence)
1284                         continue;
1285
1286                 r = dma_fence_wait_timeout(fence, true, timeout);
1287                 dma_fence_put(fence);
1288                 if (r < 0)
1289                         return r;
1290
1291                 if (r == 0)
1292                         break;
1293         }
1294
1295         memset(wait, 0, sizeof(*wait));
1296         wait->out.status = (r > 0);
1297
1298         return 0;
1299 }
1300
1301 /**
1302  * amdgpu_cs_wait_any_fence - wait on any fence to signal
1303  *
1304  * @adev: amdgpu device
1305  * @filp: file private
1306  * @wait: wait parameters
1307  * @fences: array of drm_amdgpu_fence
1308  */
1309 static int amdgpu_cs_wait_any_fence(struct amdgpu_device *adev,
1310                                     struct drm_file *filp,
1311                                     union drm_amdgpu_wait_fences *wait,
1312                                     struct drm_amdgpu_fence *fences)
1313 {
1314         unsigned long timeout = amdgpu_gem_timeout(wait->in.timeout_ns);
1315         uint32_t fence_count = wait->in.fence_count;
1316         uint32_t first = ~0;
1317         struct dma_fence **array;
1318         unsigned int i;
1319         long r;
1320
1321         /* Prepare the fence array */
1322         array = kcalloc(fence_count, sizeof(struct dma_fence *), GFP_KERNEL);
1323
1324         if (array == NULL)
1325                 return -ENOMEM;
1326
1327         for (i = 0; i < fence_count; i++) {
1328                 struct dma_fence *fence;
1329
1330                 fence = amdgpu_cs_get_fence(adev, filp, &fences[i]);
1331                 if (IS_ERR(fence)) {
1332                         r = PTR_ERR(fence);
1333                         goto err_free_fence_array;
1334                 } else if (fence) {
1335                         array[i] = fence;
1336                 } else { /* NULL, the fence has been already signaled */
1337                         r = 1;
1338                         goto out;
1339                 }
1340         }
1341
1342         r = dma_fence_wait_any_timeout(array, fence_count, true, timeout,
1343                                        &first);
1344         if (r < 0)
1345                 goto err_free_fence_array;
1346
1347 out:
1348         memset(wait, 0, sizeof(*wait));
1349         wait->out.status = (r > 0);
1350         wait->out.first_signaled = first;
1351         /* set return value 0 to indicate success */
1352         r = 0;
1353
1354 err_free_fence_array:
1355         for (i = 0; i < fence_count; i++)
1356                 dma_fence_put(array[i]);
1357         kfree(array);
1358
1359         return r;
1360 }
1361
1362 /**
1363  * amdgpu_cs_wait_fences_ioctl - wait for multiple command submissions to finish
1364  *
1365  * @dev: drm device
1366  * @data: data from userspace
1367  * @filp: file private
1368  */
1369 int amdgpu_cs_wait_fences_ioctl(struct drm_device *dev, void *data,
1370                                 struct drm_file *filp)
1371 {
1372         struct amdgpu_device *adev = dev->dev_private;
1373         struct amdgpu_fpriv *fpriv = filp->driver_priv;
1374         union drm_amdgpu_wait_fences *wait = data;
1375         uint32_t fence_count = wait->in.fence_count;
1376         struct drm_amdgpu_fence *fences_user;
1377         struct drm_amdgpu_fence *fences;
1378         int r;
1379
1380         if (amdgpu_kms_vram_lost(adev, fpriv))
1381                 return -ENODEV;
1382         /* Get the fences from userspace */
1383         fences = kmalloc_array(fence_count, sizeof(struct drm_amdgpu_fence),
1384                         GFP_KERNEL);
1385         if (fences == NULL)
1386                 return -ENOMEM;
1387
1388         fences_user = (void __user *)(uintptr_t)(wait->in.fences);
1389         if (copy_from_user(fences, fences_user,
1390                 sizeof(struct drm_amdgpu_fence) * fence_count)) {
1391                 r = -EFAULT;
1392                 goto err_free_fences;
1393         }
1394
1395         if (wait->in.wait_all)
1396                 r = amdgpu_cs_wait_all_fences(adev, filp, wait, fences);
1397         else
1398                 r = amdgpu_cs_wait_any_fence(adev, filp, wait, fences);
1399
1400 err_free_fences:
1401         kfree(fences);
1402
1403         return r;
1404 }
1405
1406 /**
1407  * amdgpu_cs_find_bo_va - find bo_va for VM address
1408  *
1409  * @parser: command submission parser context
1410  * @addr: VM address
1411  * @bo: resulting BO of the mapping found
1412  *
1413  * Search the buffer objects in the command submission context for a certain
1414  * virtual memory address. Returns allocation structure when found, NULL
1415  * otherwise.
1416  */
1417 struct amdgpu_bo_va_mapping *
1418 amdgpu_cs_find_mapping(struct amdgpu_cs_parser *parser,
1419                        uint64_t addr, struct amdgpu_bo **bo)
1420 {
1421         struct amdgpu_bo_va_mapping *mapping;
1422         unsigned i;
1423
1424         if (!parser->bo_list)
1425                 return NULL;
1426
1427         addr /= AMDGPU_GPU_PAGE_SIZE;
1428
1429         for (i = 0; i < parser->bo_list->num_entries; i++) {
1430                 struct amdgpu_bo_list_entry *lobj;
1431
1432                 lobj = &parser->bo_list->array[i];
1433                 if (!lobj->bo_va)
1434                         continue;
1435
1436                 list_for_each_entry(mapping, &lobj->bo_va->valids, list) {
1437                         if (mapping->start > addr ||
1438                             addr > mapping->last)
1439                                 continue;
1440
1441                         *bo = lobj->bo_va->bo;
1442                         return mapping;
1443                 }
1444
1445                 list_for_each_entry(mapping, &lobj->bo_va->invalids, list) {
1446                         if (mapping->start > addr ||
1447                             addr > mapping->last)
1448                                 continue;
1449
1450                         *bo = lobj->bo_va->bo;
1451                         return mapping;
1452                 }
1453         }
1454
1455         return NULL;
1456 }
1457
1458 /**
1459  * amdgpu_cs_sysvm_access_required - make BOs accessible by the system VM
1460  *
1461  * @parser: command submission parser context
1462  *
1463  * Helper for UVD/VCE VM emulation, make sure BOs are accessible by the system VM.
1464  */
1465 int amdgpu_cs_sysvm_access_required(struct amdgpu_cs_parser *parser)
1466 {
1467         unsigned i;
1468         int r;
1469
1470         if (!parser->bo_list)
1471                 return 0;
1472
1473         for (i = 0; i < parser->bo_list->num_entries; i++) {
1474                 struct amdgpu_bo *bo = parser->bo_list->array[i].robj;
1475
1476                 r = amdgpu_ttm_bind(&bo->tbo, &bo->tbo.mem);
1477                 if (unlikely(r))
1478                         return r;
1479
1480                 if (bo->flags & AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS)
1481                         continue;
1482
1483                 bo->flags |= AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS;
1484                 amdgpu_ttm_placement_from_domain(bo, bo->allowed_domains);
1485                 r = ttm_bo_validate(&bo->tbo, &bo->placement, false, false);
1486                 if (unlikely(r))
1487                         return r;
1488         }
1489
1490         return 0;
1491 }