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