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