GNU Linux-libre 4.4.284-gnu1
[releases.git] / drivers / gpu / drm / amd / amdgpu / amdgpu_cs.c
1 /*
2  * Copyright 2008 Jerome Glisse.
3  * All Rights Reserved.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice (including the next
13  * paragraph) shall be included in all copies or substantial portions of the
14  * Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
19  * PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22  * DEALINGS IN THE SOFTWARE.
23  *
24  * Authors:
25  *    Jerome Glisse <glisse@freedesktop.org>
26  */
27 #include <linux/list_sort.h>
28 #include <drm/drmP.h>
29 #include <drm/amdgpu_drm.h>
30 #include "amdgpu.h"
31 #include "amdgpu_trace.h"
32
33 #define AMDGPU_CS_MAX_PRIORITY          32u
34 #define AMDGPU_CS_NUM_BUCKETS           (AMDGPU_CS_MAX_PRIORITY + 1)
35
36 /* This is based on the bucket sort with O(n) time complexity.
37  * An item with priority "i" is added to bucket[i]. The lists are then
38  * concatenated in descending order.
39  */
40 struct amdgpu_cs_buckets {
41         struct list_head bucket[AMDGPU_CS_NUM_BUCKETS];
42 };
43
44 static void amdgpu_cs_buckets_init(struct amdgpu_cs_buckets *b)
45 {
46         unsigned i;
47
48         for (i = 0; i < AMDGPU_CS_NUM_BUCKETS; i++)
49                 INIT_LIST_HEAD(&b->bucket[i]);
50 }
51
52 static void amdgpu_cs_buckets_add(struct amdgpu_cs_buckets *b,
53                                   struct list_head *item, unsigned priority)
54 {
55         /* Since buffers which appear sooner in the relocation list are
56          * likely to be used more often than buffers which appear later
57          * in the list, the sort mustn't change the ordering of buffers
58          * with the same priority, i.e. it must be stable.
59          */
60         list_add_tail(item, &b->bucket[min(priority, AMDGPU_CS_MAX_PRIORITY)]);
61 }
62
63 static void amdgpu_cs_buckets_get_list(struct amdgpu_cs_buckets *b,
64                                        struct list_head *out_list)
65 {
66         unsigned i;
67
68         /* Connect the sorted buckets in the output list. */
69         for (i = 0; i < AMDGPU_CS_NUM_BUCKETS; i++) {
70                 list_splice(&b->bucket[i], out_list);
71         }
72 }
73
74 int amdgpu_cs_get_ring(struct amdgpu_device *adev, u32 ip_type,
75                        u32 ip_instance, u32 ring,
76                        struct amdgpu_ring **out_ring)
77 {
78         /* Right now all IPs have only one instance - multiple rings. */
79         if (ip_instance != 0) {
80                 DRM_ERROR("invalid ip instance: %d\n", ip_instance);
81                 return -EINVAL;
82         }
83
84         switch (ip_type) {
85         default:
86                 DRM_ERROR("unknown ip type: %d\n", ip_type);
87                 return -EINVAL;
88         case AMDGPU_HW_IP_GFX:
89                 if (ring < adev->gfx.num_gfx_rings) {
90                         *out_ring = &adev->gfx.gfx_ring[ring];
91                 } else {
92                         DRM_ERROR("only %d gfx rings are supported now\n",
93                                   adev->gfx.num_gfx_rings);
94                         return -EINVAL;
95                 }
96                 break;
97         case AMDGPU_HW_IP_COMPUTE:
98                 if (ring < adev->gfx.num_compute_rings) {
99                         *out_ring = &adev->gfx.compute_ring[ring];
100                 } else {
101                         DRM_ERROR("only %d compute rings are supported now\n",
102                                   adev->gfx.num_compute_rings);
103                         return -EINVAL;
104                 }
105                 break;
106         case AMDGPU_HW_IP_DMA:
107                 if (ring < adev->sdma.num_instances) {
108                         *out_ring = &adev->sdma.instance[ring].ring;
109                 } else {
110                         DRM_ERROR("only %d SDMA rings are supported\n",
111                                   adev->sdma.num_instances);
112                         return -EINVAL;
113                 }
114                 break;
115         case AMDGPU_HW_IP_UVD:
116                 *out_ring = &adev->uvd.ring;
117                 break;
118         case AMDGPU_HW_IP_VCE:
119                 if (ring < 2){
120                         *out_ring = &adev->vce.ring[ring];
121                 } else {
122                         DRM_ERROR("only two VCE rings are supported\n");
123                         return -EINVAL;
124                 }
125                 break;
126         }
127
128         if (!(*out_ring && (*out_ring)->adev)) {
129                 DRM_ERROR("Ring %d is not initialized on IP %d\n",
130                           ring, ip_type);
131                 return -EINVAL;
132         }
133
134         return 0;
135 }
136
137 static int amdgpu_cs_user_fence_chunk(struct amdgpu_cs_parser *p,
138                                       struct drm_amdgpu_cs_chunk_fence *fence_data)
139 {
140         struct drm_gem_object *gobj;
141         uint32_t handle;
142
143         handle = fence_data->handle;
144         gobj = drm_gem_object_lookup(p->adev->ddev, p->filp,
145                                      fence_data->handle);
146         if (gobj == NULL)
147                 return -EINVAL;
148
149         p->uf.bo = amdgpu_bo_ref(gem_to_amdgpu_bo(gobj));
150         p->uf.offset = fence_data->offset;
151
152         if (amdgpu_ttm_tt_has_userptr(p->uf.bo->tbo.ttm)) {
153                 drm_gem_object_unreference_unlocked(gobj);
154                 return -EINVAL;
155         }
156
157         p->uf_entry.robj = amdgpu_bo_ref(p->uf.bo);
158         p->uf_entry.prefered_domains = AMDGPU_GEM_DOMAIN_GTT;
159         p->uf_entry.allowed_domains = AMDGPU_GEM_DOMAIN_GTT;
160         p->uf_entry.priority = 0;
161         p->uf_entry.tv.bo = &p->uf_entry.robj->tbo;
162         p->uf_entry.tv.shared = true;
163
164         drm_gem_object_unreference_unlocked(gobj);
165         return 0;
166 }
167
168 int amdgpu_cs_parser_init(struct amdgpu_cs_parser *p, void *data)
169 {
170         union drm_amdgpu_cs *cs = data;
171         uint64_t *chunk_array_user;
172         uint64_t *chunk_array;
173         struct amdgpu_fpriv *fpriv = p->filp->driver_priv;
174         unsigned size;
175         int i;
176         int ret;
177
178         if (cs->in.num_chunks == 0)
179                 return 0;
180
181         chunk_array = kmalloc_array(cs->in.num_chunks, sizeof(uint64_t), GFP_KERNEL);
182         if (!chunk_array)
183                 return -ENOMEM;
184
185         p->ctx = amdgpu_ctx_get(fpriv, cs->in.ctx_id);
186         if (!p->ctx) {
187                 ret = -EINVAL;
188                 goto free_chunk;
189         }
190
191         p->bo_list = amdgpu_bo_list_get(fpriv, cs->in.bo_list_handle);
192
193         /* get chunks */
194         INIT_LIST_HEAD(&p->validated);
195         chunk_array_user = (uint64_t __user *)(unsigned long)(cs->in.chunks);
196         if (copy_from_user(chunk_array, chunk_array_user,
197                            sizeof(uint64_t)*cs->in.num_chunks)) {
198                 ret = -EFAULT;
199                 goto put_bo_list;
200         }
201
202         p->nchunks = cs->in.num_chunks;
203         p->chunks = kmalloc_array(p->nchunks, sizeof(struct amdgpu_cs_chunk),
204                             GFP_KERNEL);
205         if (!p->chunks) {
206                 ret = -ENOMEM;
207                 goto put_bo_list;
208         }
209
210         for (i = 0; i < p->nchunks; i++) {
211                 struct drm_amdgpu_cs_chunk __user **chunk_ptr = NULL;
212                 struct drm_amdgpu_cs_chunk user_chunk;
213                 uint32_t __user *cdata;
214
215                 chunk_ptr = (void __user *)(unsigned long)chunk_array[i];
216                 if (copy_from_user(&user_chunk, chunk_ptr,
217                                        sizeof(struct drm_amdgpu_cs_chunk))) {
218                         ret = -EFAULT;
219                         i--;
220                         goto free_partial_kdata;
221                 }
222                 p->chunks[i].chunk_id = user_chunk.chunk_id;
223                 p->chunks[i].length_dw = user_chunk.length_dw;
224
225                 size = p->chunks[i].length_dw;
226                 cdata = (void __user *)(unsigned long)user_chunk.chunk_data;
227                 p->chunks[i].user_ptr = cdata;
228
229                 p->chunks[i].kdata = drm_malloc_ab(size, sizeof(uint32_t));
230                 if (p->chunks[i].kdata == NULL) {
231                         ret = -ENOMEM;
232                         i--;
233                         goto free_partial_kdata;
234                 }
235                 size *= sizeof(uint32_t);
236                 if (copy_from_user(p->chunks[i].kdata, cdata, size)) {
237                         ret = -EFAULT;
238                         goto free_partial_kdata;
239                 }
240
241                 switch (p->chunks[i].chunk_id) {
242                 case AMDGPU_CHUNK_ID_IB:
243                         p->num_ibs++;
244                         break;
245
246                 case AMDGPU_CHUNK_ID_FENCE:
247                         size = sizeof(struct drm_amdgpu_cs_chunk_fence);
248                         if (p->chunks[i].length_dw * sizeof(uint32_t) < size) {
249                                 ret = -EINVAL;
250                                 goto free_partial_kdata;
251                         }
252
253                         ret = amdgpu_cs_user_fence_chunk(p, (void *)p->chunks[i].kdata);
254                         if (ret)
255                                 goto free_partial_kdata;
256
257                         break;
258
259                 case AMDGPU_CHUNK_ID_DEPENDENCIES:
260                         break;
261
262                 default:
263                         ret = -EINVAL;
264                         goto free_partial_kdata;
265                 }
266         }
267
268
269         p->ibs = kcalloc(p->num_ibs, sizeof(struct amdgpu_ib), GFP_KERNEL);
270         if (!p->ibs) {
271                 ret = -ENOMEM;
272                 goto free_all_kdata;
273         }
274
275         kfree(chunk_array);
276         return 0;
277
278 free_all_kdata:
279         i = p->nchunks - 1;
280 free_partial_kdata:
281         for (; i >= 0; i--)
282                 drm_free_large(p->chunks[i].kdata);
283         kfree(p->chunks);
284 put_bo_list:
285         if (p->bo_list)
286                 amdgpu_bo_list_put(p->bo_list);
287         amdgpu_ctx_put(p->ctx);
288 free_chunk:
289         kfree(chunk_array);
290
291         return ret;
292 }
293
294 /* Returns how many bytes TTM can move per IB.
295  */
296 static u64 amdgpu_cs_get_threshold_for_moves(struct amdgpu_device *adev)
297 {
298         u64 real_vram_size = adev->mc.real_vram_size;
299         u64 vram_usage = atomic64_read(&adev->vram_usage);
300
301         /* This function is based on the current VRAM usage.
302          *
303          * - If all of VRAM is free, allow relocating the number of bytes that
304          *   is equal to 1/4 of the size of VRAM for this IB.
305
306          * - If more than one half of VRAM is occupied, only allow relocating
307          *   1 MB of data for this IB.
308          *
309          * - From 0 to one half of used VRAM, the threshold decreases
310          *   linearly.
311          *         __________________
312          * 1/4 of -|\               |
313          * VRAM    | \              |
314          *         |  \             |
315          *         |   \            |
316          *         |    \           |
317          *         |     \          |
318          *         |      \         |
319          *         |       \________|1 MB
320          *         |----------------|
321          *    VRAM 0 %             100 %
322          *         used            used
323          *
324          * Note: It's a threshold, not a limit. The threshold must be crossed
325          * for buffer relocations to stop, so any buffer of an arbitrary size
326          * can be moved as long as the threshold isn't crossed before
327          * the relocation takes place. We don't want to disable buffer
328          * relocations completely.
329          *
330          * The idea is that buffers should be placed in VRAM at creation time
331          * and TTM should only do a minimum number of relocations during
332          * command submission. In practice, you need to submit at least
333          * a dozen IBs to move all buffers to VRAM if they are in GTT.
334          *
335          * Also, things can get pretty crazy under memory pressure and actual
336          * VRAM usage can change a lot, so playing safe even at 50% does
337          * consistently increase performance.
338          */
339
340         u64 half_vram = real_vram_size >> 1;
341         u64 half_free_vram = vram_usage >= half_vram ? 0 : half_vram - vram_usage;
342         u64 bytes_moved_threshold = half_free_vram >> 1;
343         return max(bytes_moved_threshold, 1024*1024ull);
344 }
345
346 int amdgpu_cs_list_validate(struct amdgpu_device *adev,
347                             struct amdgpu_vm *vm,
348                             struct list_head *validated)
349 {
350         struct amdgpu_bo_list_entry *lobj;
351         struct amdgpu_bo *bo;
352         u64 bytes_moved = 0, initial_bytes_moved;
353         u64 bytes_moved_threshold = amdgpu_cs_get_threshold_for_moves(adev);
354         int r;
355
356         list_for_each_entry(lobj, validated, tv.head) {
357                 bo = lobj->robj;
358                 if (!bo->pin_count) {
359                         u32 domain = lobj->prefered_domains;
360                         u32 current_domain =
361                                 amdgpu_mem_type_to_domain(bo->tbo.mem.mem_type);
362
363                         /* Check if this buffer will be moved and don't move it
364                          * if we have moved too many buffers for this IB already.
365                          *
366                          * Note that this allows moving at least one buffer of
367                          * any size, because it doesn't take the current "bo"
368                          * into account. We don't want to disallow buffer moves
369                          * completely.
370                          */
371                         if ((lobj->allowed_domains & current_domain) != 0 &&
372                             (domain & current_domain) == 0 && /* will be moved */
373                             bytes_moved > bytes_moved_threshold) {
374                                 /* don't move it */
375                                 domain = current_domain;
376                         }
377
378                 retry:
379                         amdgpu_ttm_placement_from_domain(bo, domain);
380                         initial_bytes_moved = atomic64_read(&adev->num_bytes_moved);
381                         r = ttm_bo_validate(&bo->tbo, &bo->placement, true, false);
382                         bytes_moved += atomic64_read(&adev->num_bytes_moved) -
383                                        initial_bytes_moved;
384
385                         if (unlikely(r)) {
386                                 if (r != -ERESTARTSYS && domain != lobj->allowed_domains) {
387                                         domain = lobj->allowed_domains;
388                                         goto retry;
389                                 }
390                                 return r;
391                         }
392                 }
393                 lobj->bo_va = amdgpu_vm_bo_find(vm, bo);
394         }
395         return 0;
396 }
397
398 static int amdgpu_cs_parser_relocs(struct amdgpu_cs_parser *p)
399 {
400         struct amdgpu_fpriv *fpriv = p->filp->driver_priv;
401         struct amdgpu_cs_buckets buckets;
402         struct list_head duplicates;
403         bool need_mmap_lock = false;
404         int i, r;
405
406         if (p->bo_list) {
407                 need_mmap_lock = p->bo_list->has_userptr;
408                 amdgpu_cs_buckets_init(&buckets);
409                 for (i = 0; i < p->bo_list->num_entries; i++)
410                         amdgpu_cs_buckets_add(&buckets, &p->bo_list->array[i].tv.head,
411                                                                   p->bo_list->array[i].priority);
412
413                 amdgpu_cs_buckets_get_list(&buckets, &p->validated);
414         }
415
416         p->vm_bos = amdgpu_vm_get_bos(p->adev, &fpriv->vm,
417                                       &p->validated);
418
419         if (p->uf.bo)
420                 list_add(&p->uf_entry.tv.head, &p->validated);
421
422         if (need_mmap_lock)
423                 down_read(&current->mm->mmap_sem);
424
425         INIT_LIST_HEAD(&duplicates);
426         r = ttm_eu_reserve_buffers(&p->ticket, &p->validated, true, &duplicates);
427         if (unlikely(r != 0))
428                 goto error_reserve;
429
430         r = amdgpu_cs_list_validate(p->adev, &fpriv->vm, &p->validated);
431         if (r)
432                 goto error_validate;
433
434         r = amdgpu_cs_list_validate(p->adev, &fpriv->vm, &duplicates);
435
436 error_validate:
437         if (r)
438                 ttm_eu_backoff_reservation(&p->ticket, &p->validated);
439
440 error_reserve:
441         if (need_mmap_lock)
442                 up_read(&current->mm->mmap_sem);
443
444         return r;
445 }
446
447 static int amdgpu_cs_sync_rings(struct amdgpu_cs_parser *p)
448 {
449         struct amdgpu_bo_list_entry *e;
450         int r;
451
452         list_for_each_entry(e, &p->validated, tv.head) {
453                 struct reservation_object *resv = e->robj->tbo.resv;
454                 r = amdgpu_sync_resv(p->adev, &p->ibs[0].sync, resv, p->filp);
455
456                 if (r)
457                         return r;
458         }
459         return 0;
460 }
461
462 static int cmp_size_smaller_first(void *priv, struct list_head *a,
463                                   struct list_head *b)
464 {
465         struct amdgpu_bo_list_entry *la = list_entry(a, struct amdgpu_bo_list_entry, tv.head);
466         struct amdgpu_bo_list_entry *lb = list_entry(b, struct amdgpu_bo_list_entry, tv.head);
467
468         /* Sort A before B if A is smaller. */
469         return (int)la->robj->tbo.num_pages - (int)lb->robj->tbo.num_pages;
470 }
471
472 /**
473  * cs_parser_fini() - clean parser states
474  * @parser:     parser structure holding parsing context.
475  * @error:      error number
476  *
477  * If error is set than unvalidate buffer, otherwise just free memory
478  * used by parsing context.
479  **/
480 static void amdgpu_cs_parser_fini(struct amdgpu_cs_parser *parser, int error, bool backoff)
481 {
482         unsigned i;
483
484         if (!error) {
485                 /* Sort the buffer list from the smallest to largest buffer,
486                  * which affects the order of buffers in the LRU list.
487                  * This assures that the smallest buffers are added first
488                  * to the LRU list, so they are likely to be later evicted
489                  * first, instead of large buffers whose eviction is more
490                  * expensive.
491                  *
492                  * This slightly lowers the number of bytes moved by TTM
493                  * per frame under memory pressure.
494                  */
495                 list_sort(NULL, &parser->validated, cmp_size_smaller_first);
496
497                 ttm_eu_fence_buffer_objects(&parser->ticket,
498                                             &parser->validated,
499                                             parser->fence);
500         } else if (backoff) {
501                 ttm_eu_backoff_reservation(&parser->ticket,
502                                            &parser->validated);
503         }
504         fence_put(parser->fence);
505
506         if (parser->ctx)
507                 amdgpu_ctx_put(parser->ctx);
508         if (parser->bo_list)
509                 amdgpu_bo_list_put(parser->bo_list);
510
511         drm_free_large(parser->vm_bos);
512         for (i = 0; i < parser->nchunks; i++)
513                 drm_free_large(parser->chunks[i].kdata);
514         kfree(parser->chunks);
515         if (parser->ibs)
516                 for (i = 0; i < parser->num_ibs; i++)
517                         amdgpu_ib_free(parser->adev, &parser->ibs[i]);
518         kfree(parser->ibs);
519         amdgpu_bo_unref(&parser->uf.bo);
520         amdgpu_bo_unref(&parser->uf_entry.robj);
521 }
522
523 static int amdgpu_bo_vm_update_pte(struct amdgpu_cs_parser *p,
524                                    struct amdgpu_vm *vm)
525 {
526         struct amdgpu_device *adev = p->adev;
527         struct amdgpu_bo_va *bo_va;
528         struct amdgpu_bo *bo;
529         int i, r;
530
531         r = amdgpu_vm_update_page_directory(adev, vm);
532         if (r)
533                 return r;
534
535         r = amdgpu_sync_fence(adev, &p->ibs[0].sync, vm->page_directory_fence);
536         if (r)
537                 return r;
538
539         r = amdgpu_vm_clear_freed(adev, vm);
540         if (r)
541                 return r;
542
543         if (p->bo_list) {
544                 for (i = 0; i < p->bo_list->num_entries; i++) {
545                         struct fence *f;
546
547                         /* ignore duplicates */
548                         bo = p->bo_list->array[i].robj;
549                         if (!bo)
550                                 continue;
551
552                         bo_va = p->bo_list->array[i].bo_va;
553                         if (bo_va == NULL)
554                                 continue;
555
556                         r = amdgpu_vm_bo_update(adev, bo_va, &bo->tbo.mem);
557                         if (r)
558                                 return r;
559
560                         f = bo_va->last_pt_update;
561                         r = amdgpu_sync_fence(adev, &p->ibs[0].sync, f);
562                         if (r)
563                                 return r;
564                 }
565
566         }
567
568         r = amdgpu_vm_clear_invalids(adev, vm, &p->ibs[0].sync);
569
570         if (amdgpu_vm_debug && p->bo_list) {
571                 /* Invalidate all BOs to test for userspace bugs */
572                 for (i = 0; i < p->bo_list->num_entries; i++) {
573                         /* ignore duplicates */
574                         bo = p->bo_list->array[i].robj;
575                         if (!bo)
576                                 continue;
577
578                         amdgpu_vm_bo_invalidate(adev, bo);
579                 }
580         }
581
582         return r;
583 }
584
585 static int amdgpu_cs_ib_vm_chunk(struct amdgpu_device *adev,
586                                  struct amdgpu_cs_parser *parser)
587 {
588         struct amdgpu_fpriv *fpriv = parser->filp->driver_priv;
589         struct amdgpu_vm *vm = &fpriv->vm;
590         struct amdgpu_ring *ring;
591         int i, r;
592
593         if (parser->num_ibs == 0)
594                 return 0;
595
596         /* Only for UVD/VCE VM emulation */
597         for (i = 0; i < parser->num_ibs; i++) {
598                 ring = parser->ibs[i].ring;
599                 if (ring->funcs->parse_cs) {
600                         r = amdgpu_ring_parse_cs(ring, parser, i);
601                         if (r)
602                                 return r;
603                 }
604         }
605
606         r = amdgpu_bo_vm_update_pte(parser, vm);
607         if (!r)
608                 amdgpu_cs_sync_rings(parser);
609
610         return r;
611 }
612
613 static int amdgpu_cs_handle_lockup(struct amdgpu_device *adev, int r)
614 {
615         if (r == -EDEADLK) {
616                 r = amdgpu_gpu_reset(adev);
617                 if (!r)
618                         r = -EAGAIN;
619         }
620         return r;
621 }
622
623 static int amdgpu_cs_ib_fill(struct amdgpu_device *adev,
624                              struct amdgpu_cs_parser *parser)
625 {
626         struct amdgpu_fpriv *fpriv = parser->filp->driver_priv;
627         struct amdgpu_vm *vm = &fpriv->vm;
628         int i, j;
629         int r;
630
631         for (i = 0, j = 0; i < parser->nchunks && j < parser->num_ibs; i++) {
632                 struct amdgpu_cs_chunk *chunk;
633                 struct amdgpu_ib *ib;
634                 struct drm_amdgpu_cs_chunk_ib *chunk_ib;
635                 struct amdgpu_ring *ring;
636
637                 chunk = &parser->chunks[i];
638                 ib = &parser->ibs[j];
639                 chunk_ib = (struct drm_amdgpu_cs_chunk_ib *)chunk->kdata;
640
641                 if (chunk->chunk_id != AMDGPU_CHUNK_ID_IB)
642                         continue;
643
644                 r = amdgpu_cs_get_ring(adev, chunk_ib->ip_type,
645                                        chunk_ib->ip_instance, chunk_ib->ring,
646                                        &ring);
647                 if (r)
648                         return r;
649
650                 if (ring->funcs->parse_cs) {
651                         struct amdgpu_bo_va_mapping *m;
652                         struct amdgpu_bo *aobj = NULL;
653                         uint64_t offset;
654                         uint8_t *kptr;
655
656                         m = amdgpu_cs_find_mapping(parser, chunk_ib->va_start,
657                                                    &aobj);
658                         if (!aobj) {
659                                 DRM_ERROR("IB va_start is invalid\n");
660                                 return -EINVAL;
661                         }
662
663                         if ((chunk_ib->va_start + chunk_ib->ib_bytes) >
664                             (m->it.last + 1) * AMDGPU_GPU_PAGE_SIZE) {
665                                 DRM_ERROR("IB va_start+ib_bytes is invalid\n");
666                                 return -EINVAL;
667                         }
668
669                         /* the IB should be reserved at this point */
670                         r = amdgpu_bo_kmap(aobj, (void **)&kptr);
671                         if (r) {
672                                 return r;
673                         }
674
675                         offset = ((uint64_t)m->it.start) * AMDGPU_GPU_PAGE_SIZE;
676                         kptr += chunk_ib->va_start - offset;
677
678                         r =  amdgpu_ib_get(ring, NULL, chunk_ib->ib_bytes, ib);
679                         if (r) {
680                                 DRM_ERROR("Failed to get ib !\n");
681                                 return r;
682                         }
683
684                         memcpy(ib->ptr, kptr, chunk_ib->ib_bytes);
685                         amdgpu_bo_kunmap(aobj);
686                 } else {
687                         r =  amdgpu_ib_get(ring, vm, 0, ib);
688                         if (r) {
689                                 DRM_ERROR("Failed to get ib !\n");
690                                 return r;
691                         }
692
693                         ib->gpu_addr = chunk_ib->va_start;
694                 }
695
696                 ib->length_dw = chunk_ib->ib_bytes / 4;
697                 ib->flags = chunk_ib->flags;
698                 ib->ctx = parser->ctx;
699                 j++;
700         }
701
702         if (!parser->num_ibs)
703                 return 0;
704
705         /* add GDS resources to first IB */
706         if (parser->bo_list) {
707                 struct amdgpu_bo *gds = parser->bo_list->gds_obj;
708                 struct amdgpu_bo *gws = parser->bo_list->gws_obj;
709                 struct amdgpu_bo *oa = parser->bo_list->oa_obj;
710                 struct amdgpu_ib *ib = &parser->ibs[0];
711
712                 if (gds) {
713                         ib->gds_base = amdgpu_bo_gpu_offset(gds);
714                         ib->gds_size = amdgpu_bo_size(gds);
715                 }
716                 if (gws) {
717                         ib->gws_base = amdgpu_bo_gpu_offset(gws);
718                         ib->gws_size = amdgpu_bo_size(gws);
719                 }
720                 if (oa) {
721                         ib->oa_base = amdgpu_bo_gpu_offset(oa);
722                         ib->oa_size = amdgpu_bo_size(oa);
723                 }
724         }
725         /* wrap the last IB with user fence */
726         if (parser->uf.bo) {
727                 struct amdgpu_ib *ib = &parser->ibs[parser->num_ibs - 1];
728
729                 /* UVD & VCE fw doesn't support user fences */
730                 if (ib->ring->type == AMDGPU_RING_TYPE_UVD ||
731                     ib->ring->type == AMDGPU_RING_TYPE_VCE)
732                         return -EINVAL;
733
734                 ib->user = &parser->uf;
735         }
736
737         return 0;
738 }
739
740 static int amdgpu_cs_dependencies(struct amdgpu_device *adev,
741                                   struct amdgpu_cs_parser *p)
742 {
743         struct amdgpu_fpriv *fpriv = p->filp->driver_priv;
744         struct amdgpu_ib *ib;
745         int i, j, r;
746
747         if (!p->num_ibs)
748                 return 0;
749
750         /* Add dependencies to first IB */
751         ib = &p->ibs[0];
752         for (i = 0; i < p->nchunks; ++i) {
753                 struct drm_amdgpu_cs_chunk_dep *deps;
754                 struct amdgpu_cs_chunk *chunk;
755                 unsigned num_deps;
756
757                 chunk = &p->chunks[i];
758
759                 if (chunk->chunk_id != AMDGPU_CHUNK_ID_DEPENDENCIES)
760                         continue;
761
762                 deps = (struct drm_amdgpu_cs_chunk_dep *)chunk->kdata;
763                 num_deps = chunk->length_dw * 4 /
764                         sizeof(struct drm_amdgpu_cs_chunk_dep);
765
766                 for (j = 0; j < num_deps; ++j) {
767                         struct amdgpu_ring *ring;
768                         struct amdgpu_ctx *ctx;
769                         struct fence *fence;
770
771                         r = amdgpu_cs_get_ring(adev, deps[j].ip_type,
772                                                deps[j].ip_instance,
773                                                deps[j].ring, &ring);
774                         if (r)
775                                 return r;
776
777                         ctx = amdgpu_ctx_get(fpriv, deps[j].ctx_id);
778                         if (ctx == NULL)
779                                 return -EINVAL;
780
781                         fence = amdgpu_ctx_get_fence(ctx, ring,
782                                                      deps[j].handle);
783                         if (IS_ERR(fence)) {
784                                 r = PTR_ERR(fence);
785                                 amdgpu_ctx_put(ctx);
786                                 return r;
787
788                         } else if (fence) {
789                                 r = amdgpu_sync_fence(adev, &ib->sync, fence);
790                                 fence_put(fence);
791                                 amdgpu_ctx_put(ctx);
792                                 if (r)
793                                         return r;
794                         }
795                 }
796         }
797
798         return 0;
799 }
800
801 static int amdgpu_cs_free_job(struct amdgpu_job *job)
802 {
803         int i;
804         if (job->ibs)
805                 for (i = 0; i < job->num_ibs; i++)
806                         amdgpu_ib_free(job->adev, &job->ibs[i]);
807         kfree(job->ibs);
808         if (job->uf.bo)
809                 amdgpu_bo_unref(&job->uf.bo);
810         return 0;
811 }
812
813 int amdgpu_cs_ioctl(struct drm_device *dev, void *data, struct drm_file *filp)
814 {
815         struct amdgpu_device *adev = dev->dev_private;
816         union drm_amdgpu_cs *cs = data;
817         struct amdgpu_cs_parser parser = {};
818         bool reserved_buffers = false;
819         int i, r;
820
821         if (!adev->accel_working)
822                 return -EBUSY;
823
824         parser.adev = adev;
825         parser.filp = filp;
826
827         r = amdgpu_cs_parser_init(&parser, data);
828         if (r) {
829                 DRM_ERROR("Failed to initialize parser !\n");
830                 amdgpu_cs_parser_fini(&parser, r, false);
831                 r = amdgpu_cs_handle_lockup(adev, r);
832                 return r;
833         }
834         r = amdgpu_cs_parser_relocs(&parser);
835         if (r == -ENOMEM)
836                 DRM_ERROR("Not enough memory for command submission!\n");
837         else if (r && r != -ERESTARTSYS)
838                 DRM_ERROR("Failed to process the buffer list %d!\n", r);
839         else if (!r) {
840                 reserved_buffers = true;
841                 r = amdgpu_cs_ib_fill(adev, &parser);
842         }
843
844         if (!r) {
845                 r = amdgpu_cs_dependencies(adev, &parser);
846                 if (r)
847                         DRM_ERROR("Failed in the dependencies handling %d!\n", r);
848         }
849
850         if (r)
851                 goto out;
852
853         for (i = 0; i < parser.num_ibs; i++)
854                 trace_amdgpu_cs(&parser, i);
855
856         r = amdgpu_cs_ib_vm_chunk(adev, &parser);
857         if (r)
858                 goto out;
859
860         if (amdgpu_enable_scheduler && parser.num_ibs) {
861                 struct amdgpu_ring * ring = parser.ibs->ring;
862                 struct amd_sched_fence *fence;
863                 struct amdgpu_job *job;
864
865                 job = kzalloc(sizeof(struct amdgpu_job), GFP_KERNEL);
866                 if (!job) {
867                         r = -ENOMEM;
868                         goto out;
869                 }
870
871                 job->base.sched = &ring->sched;
872                 job->base.s_entity = &parser.ctx->rings[ring->idx].entity;
873                 job->adev = parser.adev;
874                 job->owner = parser.filp;
875                 job->free_job = amdgpu_cs_free_job;
876
877                 job->ibs = parser.ibs;
878                 job->num_ibs = parser.num_ibs;
879                 parser.ibs = NULL;
880                 parser.num_ibs = 0;
881
882                 if (job->ibs[job->num_ibs - 1].user) {
883                         job->uf = parser.uf;
884                         job->ibs[job->num_ibs - 1].user = &job->uf;
885                         parser.uf.bo = NULL;
886                 }
887
888                 fence = amd_sched_fence_create(job->base.s_entity,
889                                                parser.filp);
890                 if (!fence) {
891                         r = -ENOMEM;
892                         amdgpu_cs_free_job(job);
893                         kfree(job);
894                         goto out;
895                 }
896                 job->base.s_fence = fence;
897                 parser.fence = fence_get(&fence->base);
898
899                 cs->out.handle = amdgpu_ctx_add_fence(parser.ctx, ring,
900                                                       &fence->base);
901                 job->ibs[job->num_ibs - 1].sequence = cs->out.handle;
902
903                 trace_amdgpu_cs_ioctl(job);
904                 amd_sched_entity_push_job(&job->base);
905
906         } else {
907                 struct amdgpu_fence *fence;
908
909                 r = amdgpu_ib_schedule(adev, parser.num_ibs, parser.ibs,
910                                        parser.filp);
911                 fence = parser.ibs[parser.num_ibs - 1].fence;
912                 parser.fence = fence_get(&fence->base);
913                 cs->out.handle = parser.ibs[parser.num_ibs - 1].sequence;
914         }
915
916 out:
917         amdgpu_cs_parser_fini(&parser, r, reserved_buffers);
918         r = amdgpu_cs_handle_lockup(adev, r);
919         return r;
920 }
921
922 /**
923  * amdgpu_cs_wait_ioctl - wait for a command submission to finish
924  *
925  * @dev: drm device
926  * @data: data from userspace
927  * @filp: file private
928  *
929  * Wait for the command submission identified by handle to finish.
930  */
931 int amdgpu_cs_wait_ioctl(struct drm_device *dev, void *data,
932                          struct drm_file *filp)
933 {
934         union drm_amdgpu_wait_cs *wait = data;
935         struct amdgpu_device *adev = dev->dev_private;
936         unsigned long timeout = amdgpu_gem_timeout(wait->in.timeout);
937         struct amdgpu_ring *ring = NULL;
938         struct amdgpu_ctx *ctx;
939         struct fence *fence;
940         long r;
941
942         r = amdgpu_cs_get_ring(adev, wait->in.ip_type, wait->in.ip_instance,
943                                wait->in.ring, &ring);
944         if (r)
945                 return r;
946
947         ctx = amdgpu_ctx_get(filp->driver_priv, wait->in.ctx_id);
948         if (ctx == NULL)
949                 return -EINVAL;
950
951         fence = amdgpu_ctx_get_fence(ctx, ring, wait->in.handle);
952         if (IS_ERR(fence))
953                 r = PTR_ERR(fence);
954         else if (fence) {
955                 r = fence_wait_timeout(fence, true, timeout);
956                 fence_put(fence);
957         } else
958                 r = 1;
959
960         amdgpu_ctx_put(ctx);
961         if (r < 0)
962                 return r;
963
964         memset(wait, 0, sizeof(*wait));
965         wait->out.status = (r == 0);
966
967         return 0;
968 }
969
970 /**
971  * amdgpu_cs_find_bo_va - find bo_va for VM address
972  *
973  * @parser: command submission parser context
974  * @addr: VM address
975  * @bo: resulting BO of the mapping found
976  *
977  * Search the buffer objects in the command submission context for a certain
978  * virtual memory address. Returns allocation structure when found, NULL
979  * otherwise.
980  */
981 struct amdgpu_bo_va_mapping *
982 amdgpu_cs_find_mapping(struct amdgpu_cs_parser *parser,
983                        uint64_t addr, struct amdgpu_bo **bo)
984 {
985         struct amdgpu_bo_list_entry *reloc;
986         struct amdgpu_bo_va_mapping *mapping;
987
988         addr /= AMDGPU_GPU_PAGE_SIZE;
989
990         list_for_each_entry(reloc, &parser->validated, tv.head) {
991                 if (!reloc->bo_va)
992                         continue;
993
994                 list_for_each_entry(mapping, &reloc->bo_va->valids, list) {
995                         if (mapping->it.start > addr ||
996                             addr > mapping->it.last)
997                                 continue;
998
999                         *bo = reloc->bo_va->bo;
1000                         return mapping;
1001                 }
1002
1003                 list_for_each_entry(mapping, &reloc->bo_va->invalids, list) {
1004                         if (mapping->it.start > addr ||
1005                             addr > mapping->it.last)
1006                                 continue;
1007
1008                         *bo = reloc->bo_va->bo;
1009                         return mapping;
1010                 }
1011         }
1012
1013         return NULL;
1014 }