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