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