radeon_drm_bo.c revision 6d59b7f6dc3131e773e9c9729388c08a2f987364
1/*
2 * Copyright © 2011 Marek Olšák <maraeo@gmail.com>
3 * All Rights Reserved.
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining
6 * a copy of this software and associated documentation files (the
7 * "Software"), to deal in the Software without restriction, including
8 * without limitation the rights to use, copy, modify, merge, publish,
9 * distribute, sub license, and/or sell copies of the Software, and to
10 * permit persons to whom the Software is furnished to do so, subject to
11 * the following conditions:
12 *
13 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
14 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
15 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
16 * NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS, AUTHORS
17 * AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 * USE OR OTHER DEALINGS IN THE SOFTWARE.
21 *
22 * The above copyright notice and this permission notice (including the
23 * next paragraph) shall be included in all copies or substantial portions
24 * of the Software.
25 */
26
27#define _FILE_OFFSET_BITS 64
28#include "radeon_drm_cs.h"
29
30#include "util/u_hash_table.h"
31#include "util/u_memory.h"
32#include "util/u_simple_list.h"
33#include "util/u_double_list.h"
34#include "os/os_thread.h"
35#include "os/os_mman.h"
36
37#include "state_tracker/drm_driver.h"
38
39#include <sys/ioctl.h>
40#include <xf86drm.h>
41#include <errno.h>
42
43/*
44 * this are copy from radeon_drm, once an updated libdrm is released
45 * we should bump configure.ac requirement for it and remove the following
46 * field
47 */
48#define RADEON_BO_FLAGS_MACRO_TILE  1
49#define RADEON_BO_FLAGS_MICRO_TILE  2
50#define RADEON_BO_FLAGS_MICRO_TILE_SQUARE 0x20
51
52#ifndef DRM_RADEON_GEM_WAIT
53#define DRM_RADEON_GEM_WAIT     0x2b
54
55#define RADEON_GEM_NO_WAIT      0x1
56#define RADEON_GEM_USAGE_READ   0x2
57#define RADEON_GEM_USAGE_WRITE  0x4
58
59struct drm_radeon_gem_wait {
60    uint32_t    handle;
61    uint32_t    flags;  /* one of RADEON_GEM_* */
62};
63
64#endif
65
66#ifndef RADEON_VA_MAP
67
68#define RADEON_VA_MAP               1
69#define RADEON_VA_UNMAP             2
70
71#define RADEON_VA_RESULT_OK         0
72#define RADEON_VA_RESULT_ERROR      1
73#define RADEON_VA_RESULT_VA_EXIST   2
74
75#define RADEON_VM_PAGE_VALID        (1 << 0)
76#define RADEON_VM_PAGE_READABLE     (1 << 1)
77#define RADEON_VM_PAGE_WRITEABLE    (1 << 2)
78#define RADEON_VM_PAGE_SYSTEM       (1 << 3)
79#define RADEON_VM_PAGE_SNOOPED      (1 << 4)
80
81struct drm_radeon_gem_va {
82    uint32_t    handle;
83    uint32_t    operation;
84    uint32_t    vm_id;
85    uint32_t    flags;
86    uint64_t    offset;
87};
88
89#define DRM_RADEON_GEM_VA   0x2b
90#endif
91
92
93
94extern const struct pb_vtbl radeon_bo_vtbl;
95
96
97static INLINE struct radeon_bo *radeon_bo(struct pb_buffer *bo)
98{
99    assert(bo->vtbl == &radeon_bo_vtbl);
100    return (struct radeon_bo *)bo;
101}
102
103struct radeon_bo_va_hole {
104    struct list_head list;
105    uint64_t         offset;
106    uint64_t         size;
107};
108
109struct radeon_bomgr {
110    /* Base class. */
111    struct pb_manager base;
112
113    /* Winsys. */
114    struct radeon_drm_winsys *rws;
115
116    /* List of buffer handles and its mutex. */
117    struct util_hash_table *bo_handles;
118    pipe_mutex bo_handles_mutex;
119    pipe_mutex bo_va_mutex;
120
121    /* is virtual address supported */
122    bool va;
123    uint64_t va_offset;
124    struct list_head va_holes;
125};
126
127static INLINE struct radeon_bomgr *radeon_bomgr(struct pb_manager *mgr)
128{
129    return (struct radeon_bomgr *)mgr;
130}
131
132static struct radeon_bo *get_radeon_bo(struct pb_buffer *_buf)
133{
134    struct radeon_bo *bo = NULL;
135
136    if (_buf->vtbl == &radeon_bo_vtbl) {
137        bo = radeon_bo(_buf);
138    } else {
139        struct pb_buffer *base_buf;
140        pb_size offset;
141        pb_get_base_buffer(_buf, &base_buf, &offset);
142
143        if (base_buf->vtbl == &radeon_bo_vtbl)
144            bo = radeon_bo(base_buf);
145    }
146
147    return bo;
148}
149
150static void radeon_bo_wait(struct pb_buffer *_buf, enum radeon_bo_usage usage)
151{
152    struct radeon_bo *bo = get_radeon_bo(_buf);
153
154    while (p_atomic_read(&bo->num_active_ioctls)) {
155        sched_yield();
156    }
157
158    /* XXX use this when it's ready */
159    /*if (bo->rws->info.drm_minor >= 12) {
160        struct drm_radeon_gem_wait args = {};
161        args.handle = bo->handle;
162        args.flags = usage;
163        while (drmCommandWriteRead(bo->rws->fd, DRM_RADEON_GEM_WAIT,
164                                   &args, sizeof(args)) == -EBUSY);
165    } else*/ {
166        struct drm_radeon_gem_wait_idle args;
167        memset(&args, 0, sizeof(args));
168        args.handle = bo->handle;
169        while (drmCommandWriteRead(bo->rws->fd, DRM_RADEON_GEM_WAIT_IDLE,
170                                   &args, sizeof(args)) == -EBUSY);
171    }
172}
173
174static boolean radeon_bo_is_busy(struct pb_buffer *_buf,
175                                 enum radeon_bo_usage usage)
176{
177    struct radeon_bo *bo = get_radeon_bo(_buf);
178
179    if (p_atomic_read(&bo->num_active_ioctls)) {
180        return TRUE;
181    }
182
183    /* XXX use this when it's ready */
184    /*if (bo->rws->info.drm_minor >= 12) {
185        struct drm_radeon_gem_wait args = {};
186        args.handle = bo->handle;
187        args.flags = usage | RADEON_GEM_NO_WAIT;
188        return drmCommandWriteRead(bo->rws->fd, DRM_RADEON_GEM_WAIT,
189                                   &args, sizeof(args)) != 0;
190    } else*/ {
191        struct drm_radeon_gem_busy args;
192        memset(&args, 0, sizeof(args));
193        args.handle = bo->handle;
194        return drmCommandWriteRead(bo->rws->fd, DRM_RADEON_GEM_BUSY,
195                                   &args, sizeof(args)) != 0;
196    }
197}
198
199static uint64_t radeon_bomgr_find_va(struct radeon_bomgr *mgr, uint64_t size, uint64_t alignment)
200{
201    struct radeon_bo_va_hole *hole, *n;
202    uint64_t offset = 0, waste = 0;
203
204    pipe_mutex_lock(mgr->bo_va_mutex);
205    /* first look for a hole */
206    LIST_FOR_EACH_ENTRY_SAFE(hole, n, &mgr->va_holes, list) {
207        offset = hole->offset;
208        waste = 0;
209        if (alignment) {
210            waste = offset % alignment;
211            waste = waste ? alignment - waste : 0;
212        }
213        offset += waste;
214        if (offset >= (hole->offset + hole->size)) {
215            continue;
216        }
217        if (!waste && hole->size == size) {
218            offset = hole->offset;
219            list_del(&hole->list);
220            FREE(hole);
221            pipe_mutex_unlock(mgr->bo_va_mutex);
222            return offset;
223        }
224        if ((hole->size - waste) > size) {
225            if (waste) {
226                n = CALLOC_STRUCT(radeon_bo_va_hole);
227                n->size = waste;
228                n->offset = hole->offset;
229                list_add(&n->list, &hole->list);
230            }
231            hole->size -= (size + waste);
232            hole->offset += size + waste;
233            pipe_mutex_unlock(mgr->bo_va_mutex);
234            return offset;
235        }
236        if ((hole->size - waste) == size) {
237            hole->size = waste;
238            pipe_mutex_unlock(mgr->bo_va_mutex);
239            return offset;
240        }
241    }
242
243    offset = mgr->va_offset;
244    waste = 0;
245    if (alignment) {
246        waste = offset % alignment;
247        waste = waste ? alignment - waste : 0;
248    }
249    offset += waste;
250    mgr->va_offset += size + waste;
251    pipe_mutex_unlock(mgr->bo_va_mutex);
252    return offset;
253}
254
255static void radeon_bomgr_force_va(struct radeon_bomgr *mgr, uint64_t va, uint64_t size)
256{
257    pipe_mutex_lock(mgr->bo_va_mutex);
258    if (va >= mgr->va_offset) {
259        if (va > mgr->va_offset) {
260            struct radeon_bo_va_hole *hole;
261            hole = CALLOC_STRUCT(radeon_bo_va_hole);
262            if (hole) {
263                hole->size = va - mgr->va_offset;
264                hole->offset = mgr->va_offset;
265                list_add(&hole->list, &mgr->va_holes);
266            }
267        }
268        mgr->va_offset = va + size;
269    } else {
270        struct radeon_bo_va_hole *hole, *n;
271        uint64_t stmp, etmp;
272
273        /* free all holes that fall into the range
274         * NOTE that we might lose virtual address space
275         */
276        LIST_FOR_EACH_ENTRY_SAFE(hole, n, &mgr->va_holes, list) {
277            stmp = hole->offset;
278            etmp = stmp + hole->size;
279            if (va >= stmp && va < etmp) {
280                list_del(&hole->list);
281                FREE(hole);
282            }
283        }
284    }
285    pipe_mutex_unlock(mgr->bo_va_mutex);
286}
287
288static void radeon_bomgr_free_va(struct radeon_bomgr *mgr, uint64_t va, uint64_t size)
289{
290    struct radeon_bo_va_hole *hole;
291
292    pipe_mutex_lock(mgr->bo_va_mutex);
293    if ((va + size) == mgr->va_offset) {
294        mgr->va_offset = va;
295        /* Delete uppermost hole if it reaches the new top */
296        if (!LIST_IS_EMPTY(&mgr->va_holes)) {
297            hole = container_of(mgr->va_holes.next, hole, list);
298            if ((hole->offset + hole->size) == va) {
299                mgr->va_offset = hole->offset;
300                list_del(&hole->list);
301                FREE(hole);
302            }
303        }
304    } else {
305        struct radeon_bo_va_hole *next;
306
307        hole = container_of(&mgr->va_holes, hole, list);
308        LIST_FOR_EACH_ENTRY(next, &mgr->va_holes, list) {
309	    if (next->offset < va)
310	        break;
311            hole = next;
312        }
313
314        if (&hole->list != &mgr->va_holes) {
315            /* Grow upper hole if it's adjacent */
316            if (hole->offset == (va + size)) {
317                hole->offset = va;
318                hole->size += size;
319                /* Merge lower hole if it's adjacent */
320                if (next != hole && &next->list != &mgr->va_holes &&
321                    (next->offset + next->size) == va) {
322                    next->size += hole->size;
323                    list_del(&hole->list);
324                    FREE(hole);
325                }
326                goto out;
327            }
328        }
329
330        /* Grow lower hole if it's adjacent */
331        if (next != hole && &next->list != &mgr->va_holes &&
332            (next->offset + next->size) == va) {
333            next->size += size;
334            goto out;
335        }
336
337        /* FIXME on allocation failure we just lose virtual address space
338         * maybe print a warning
339         */
340        next = CALLOC_STRUCT(radeon_bo_va_hole);
341        if (next) {
342            next->size = size;
343            next->offset = va;
344            list_add(&next->list, &hole->list);
345        }
346    }
347out:
348    pipe_mutex_unlock(mgr->bo_va_mutex);
349}
350
351static void radeon_bo_destroy(struct pb_buffer *_buf)
352{
353    struct radeon_bo *bo = radeon_bo(_buf);
354    struct radeon_bomgr *mgr = bo->mgr;
355    struct drm_gem_close args;
356
357    memset(&args, 0, sizeof(args));
358
359    if (bo->name) {
360        pipe_mutex_lock(bo->mgr->bo_handles_mutex);
361        util_hash_table_remove(bo->mgr->bo_handles,
362                               (void*)(uintptr_t)bo->name);
363        pipe_mutex_unlock(bo->mgr->bo_handles_mutex);
364    }
365
366    if (bo->ptr)
367        os_munmap(bo->ptr, bo->base.size);
368
369    /* Close object. */
370    args.handle = bo->handle;
371    drmIoctl(bo->rws->fd, DRM_IOCTL_GEM_CLOSE, &args);
372
373    if (mgr->va) {
374        radeon_bomgr_free_va(mgr, bo->va, bo->va_size);
375    }
376
377    pipe_mutex_destroy(bo->map_mutex);
378    FREE(bo);
379}
380
381static void *radeon_bo_map(struct radeon_winsys_cs_handle *buf,
382                           struct radeon_winsys_cs *rcs,
383                           enum pipe_transfer_usage usage)
384{
385    struct radeon_bo *bo = (struct radeon_bo*)buf;
386    struct radeon_drm_cs *cs = (struct radeon_drm_cs*)rcs;
387    struct drm_radeon_gem_mmap args = {0};
388    void *ptr;
389
390    /* If it's not unsynchronized bo_map, flush CS if needed and then wait. */
391    if (!(usage & PIPE_TRANSFER_UNSYNCHRONIZED)) {
392        /* DONTBLOCK doesn't make sense with UNSYNCHRONIZED. */
393        if (usage & PIPE_TRANSFER_DONTBLOCK) {
394            if (!(usage & PIPE_TRANSFER_WRITE)) {
395                /* Mapping for read.
396                 *
397                 * Since we are mapping for read, we don't need to wait
398                 * if the GPU is using the buffer for read too
399                 * (neither one is changing it).
400                 *
401                 * Only check whether the buffer is being used for write. */
402                if (radeon_bo_is_referenced_by_cs_for_write(cs, bo)) {
403                    cs->flush_cs(cs->flush_data, RADEON_FLUSH_ASYNC);
404                    return NULL;
405                }
406
407                if (radeon_bo_is_busy((struct pb_buffer*)bo,
408                                      RADEON_USAGE_WRITE)) {
409                    return NULL;
410                }
411            } else {
412                if (radeon_bo_is_referenced_by_cs(cs, bo)) {
413                    cs->flush_cs(cs->flush_data, RADEON_FLUSH_ASYNC);
414                    return NULL;
415                }
416
417                if (radeon_bo_is_busy((struct pb_buffer*)bo,
418                                      RADEON_USAGE_READWRITE)) {
419                    return NULL;
420                }
421            }
422        } else {
423            if (!(usage & PIPE_TRANSFER_WRITE)) {
424                /* Mapping for read.
425                 *
426                 * Since we are mapping for read, we don't need to wait
427                 * if the GPU is using the buffer for read too
428                 * (neither one is changing it).
429                 *
430                 * Only check whether the buffer is being used for write. */
431                if (radeon_bo_is_referenced_by_cs_for_write(cs, bo)) {
432                    cs->flush_cs(cs->flush_data, 0);
433                }
434                radeon_bo_wait((struct pb_buffer*)bo,
435                               RADEON_USAGE_WRITE);
436            } else {
437                /* Mapping for write. */
438                if (radeon_bo_is_referenced_by_cs(cs, bo)) {
439                    cs->flush_cs(cs->flush_data, 0);
440                } else {
441                    /* Try to avoid busy-waiting in radeon_bo_wait. */
442                    if (p_atomic_read(&bo->num_active_ioctls))
443                        radeon_drm_cs_sync_flush(cs);
444                }
445
446                radeon_bo_wait((struct pb_buffer*)bo, RADEON_USAGE_READWRITE);
447            }
448        }
449    }
450
451    /* Return the pointer if it's already mapped. */
452    if (bo->ptr)
453        return bo->ptr;
454
455    /* Map the buffer. */
456    pipe_mutex_lock(bo->map_mutex);
457    /* Return the pointer if it's already mapped (in case of a race). */
458    if (bo->ptr) {
459        pipe_mutex_unlock(bo->map_mutex);
460        return bo->ptr;
461    }
462    args.handle = bo->handle;
463    args.offset = 0;
464    args.size = (uint64_t)bo->base.size;
465    if (drmCommandWriteRead(bo->rws->fd,
466                            DRM_RADEON_GEM_MMAP,
467                            &args,
468                            sizeof(args))) {
469        pipe_mutex_unlock(bo->map_mutex);
470        fprintf(stderr, "radeon: gem_mmap failed: %p 0x%08X\n",
471                bo, bo->handle);
472        return NULL;
473    }
474
475    ptr = os_mmap(0, args.size, PROT_READ|PROT_WRITE, MAP_SHARED,
476               bo->rws->fd, args.addr_ptr);
477    if (ptr == MAP_FAILED) {
478        pipe_mutex_unlock(bo->map_mutex);
479        fprintf(stderr, "radeon: mmap failed, errno: %i\n", errno);
480        return NULL;
481    }
482    bo->ptr = ptr;
483    pipe_mutex_unlock(bo->map_mutex);
484
485    return bo->ptr;
486}
487
488static void radeon_bo_unmap(struct radeon_winsys_cs_handle *_buf)
489{
490    /* NOP */
491}
492
493static void radeon_bo_get_base_buffer(struct pb_buffer *buf,
494                                      struct pb_buffer **base_buf,
495                                      unsigned *offset)
496{
497    *base_buf = buf;
498    *offset = 0;
499}
500
501static enum pipe_error radeon_bo_validate(struct pb_buffer *_buf,
502                                          struct pb_validate *vl,
503                                          unsigned flags)
504{
505    /* Always pinned */
506    return PIPE_OK;
507}
508
509static void radeon_bo_fence(struct pb_buffer *buf,
510                            struct pipe_fence_handle *fence)
511{
512}
513
514const struct pb_vtbl radeon_bo_vtbl = {
515    radeon_bo_destroy,
516    NULL, /* never called */
517    NULL, /* never called */
518    radeon_bo_validate,
519    radeon_bo_fence,
520    radeon_bo_get_base_buffer,
521};
522
523static struct pb_buffer *radeon_bomgr_create_bo(struct pb_manager *_mgr,
524                                                pb_size size,
525                                                const struct pb_desc *desc)
526{
527    struct radeon_bomgr *mgr = radeon_bomgr(_mgr);
528    struct radeon_drm_winsys *rws = mgr->rws;
529    struct radeon_bo *bo;
530    struct drm_radeon_gem_create args;
531    struct radeon_bo_desc *rdesc = (struct radeon_bo_desc*)desc;
532    int r;
533
534    memset(&args, 0, sizeof(args));
535
536    assert(rdesc->initial_domains);
537    assert((rdesc->initial_domains &
538            ~(RADEON_GEM_DOMAIN_GTT | RADEON_GEM_DOMAIN_VRAM)) == 0);
539
540    args.size = size;
541    args.alignment = desc->alignment;
542    args.initial_domain = rdesc->initial_domains;
543
544    if (drmCommandWriteRead(rws->fd, DRM_RADEON_GEM_CREATE,
545                            &args, sizeof(args))) {
546        fprintf(stderr, "radeon: Failed to allocate a buffer:\n");
547        fprintf(stderr, "radeon:    size      : %d bytes\n", size);
548        fprintf(stderr, "radeon:    alignment : %d bytes\n", desc->alignment);
549        fprintf(stderr, "radeon:    domains   : %d\n", args.initial_domain);
550        return NULL;
551    }
552
553    bo = CALLOC_STRUCT(radeon_bo);
554    if (!bo)
555        return NULL;
556
557    pipe_reference_init(&bo->base.reference, 1);
558    bo->base.alignment = desc->alignment;
559    bo->base.usage = desc->usage;
560    bo->base.size = size;
561    bo->base.vtbl = &radeon_bo_vtbl;
562    bo->mgr = mgr;
563    bo->rws = mgr->rws;
564    bo->handle = args.handle;
565    bo->va = 0;
566    pipe_mutex_init(bo->map_mutex);
567
568    if (mgr->va) {
569        struct drm_radeon_gem_va va;
570
571        bo->va_size = align(size,  4096);
572        bo->va = radeon_bomgr_find_va(mgr, bo->va_size, desc->alignment);
573
574        va.handle = bo->handle;
575        va.vm_id = 0;
576        va.operation = RADEON_VA_MAP;
577        va.flags = RADEON_VM_PAGE_READABLE |
578                   RADEON_VM_PAGE_WRITEABLE |
579                   RADEON_VM_PAGE_SNOOPED;
580        va.offset = bo->va;
581        r = drmCommandWriteRead(rws->fd, DRM_RADEON_GEM_VA, &va, sizeof(va));
582        if (r && va.operation == RADEON_VA_RESULT_ERROR) {
583            fprintf(stderr, "radeon: Failed to allocate a buffer:\n");
584            fprintf(stderr, "radeon:    size      : %d bytes\n", size);
585            fprintf(stderr, "radeon:    alignment : %d bytes\n", desc->alignment);
586            fprintf(stderr, "radeon:    domains   : %d\n", args.initial_domain);
587            radeon_bo_destroy(&bo->base);
588            return NULL;
589        }
590        if (va.operation == RADEON_VA_RESULT_VA_EXIST) {
591            radeon_bomgr_free_va(mgr, bo->va, bo->va_size);
592            bo->va = va.offset;
593            radeon_bomgr_force_va(mgr, bo->va, bo->va_size);
594        }
595    }
596
597    return &bo->base;
598}
599
600static void radeon_bomgr_flush(struct pb_manager *mgr)
601{
602    /* NOP */
603}
604
605/* This is for the cache bufmgr. */
606static boolean radeon_bomgr_is_buffer_busy(struct pb_manager *_mgr,
607                                           struct pb_buffer *_buf)
608{
609   struct radeon_bo *bo = radeon_bo(_buf);
610
611   if (radeon_bo_is_referenced_by_any_cs(bo)) {
612       return TRUE;
613   }
614
615   if (radeon_bo_is_busy((struct pb_buffer*)bo, RADEON_USAGE_READWRITE)) {
616       return TRUE;
617   }
618
619   return FALSE;
620}
621
622static void radeon_bomgr_destroy(struct pb_manager *_mgr)
623{
624    struct radeon_bomgr *mgr = radeon_bomgr(_mgr);
625    util_hash_table_destroy(mgr->bo_handles);
626    pipe_mutex_destroy(mgr->bo_handles_mutex);
627    pipe_mutex_destroy(mgr->bo_va_mutex);
628    FREE(mgr);
629}
630
631#define PTR_TO_UINT(x) ((unsigned)((intptr_t)(x)))
632
633static unsigned handle_hash(void *key)
634{
635    return PTR_TO_UINT(key);
636}
637
638static int handle_compare(void *key1, void *key2)
639{
640    return PTR_TO_UINT(key1) != PTR_TO_UINT(key2);
641}
642
643struct pb_manager *radeon_bomgr_create(struct radeon_drm_winsys *rws)
644{
645    struct radeon_bomgr *mgr;
646
647    mgr = CALLOC_STRUCT(radeon_bomgr);
648    if (!mgr)
649        return NULL;
650
651    mgr->base.destroy = radeon_bomgr_destroy;
652    mgr->base.create_buffer = radeon_bomgr_create_bo;
653    mgr->base.flush = radeon_bomgr_flush;
654    mgr->base.is_buffer_busy = radeon_bomgr_is_buffer_busy;
655
656    mgr->rws = rws;
657    mgr->bo_handles = util_hash_table_create(handle_hash, handle_compare);
658    pipe_mutex_init(mgr->bo_handles_mutex);
659    pipe_mutex_init(mgr->bo_va_mutex);
660
661    mgr->va = rws->info.r600_virtual_address;
662    mgr->va_offset = rws->info.r600_va_start;
663    list_inithead(&mgr->va_holes);
664
665    return &mgr->base;
666}
667
668static unsigned eg_tile_split(unsigned tile_split)
669{
670    switch (tile_split) {
671    case 0:     tile_split = 64;    break;
672    case 1:     tile_split = 128;   break;
673    case 2:     tile_split = 256;   break;
674    case 3:     tile_split = 512;   break;
675    default:
676    case 4:     tile_split = 1024;  break;
677    case 5:     tile_split = 2048;  break;
678    case 6:     tile_split = 4096;  break;
679    }
680    return tile_split;
681}
682
683static unsigned eg_tile_split_rev(unsigned eg_tile_split)
684{
685    switch (eg_tile_split) {
686    case 64:    return 0;
687    case 128:   return 1;
688    case 256:   return 2;
689    case 512:   return 3;
690    default:
691    case 1024:  return 4;
692    case 2048:  return 5;
693    case 4096:  return 6;
694    }
695}
696
697static void radeon_bo_get_tiling(struct pb_buffer *_buf,
698                                 enum radeon_bo_layout *microtiled,
699                                 enum radeon_bo_layout *macrotiled,
700                                 unsigned *bankw, unsigned *bankh,
701                                 unsigned *tile_split,
702                                 unsigned *stencil_tile_split,
703                                 unsigned *mtilea)
704{
705    struct radeon_bo *bo = get_radeon_bo(_buf);
706    struct drm_radeon_gem_set_tiling args;
707
708    memset(&args, 0, sizeof(args));
709
710    args.handle = bo->handle;
711
712    drmCommandWriteRead(bo->rws->fd,
713                        DRM_RADEON_GEM_GET_TILING,
714                        &args,
715                        sizeof(args));
716
717    *microtiled = RADEON_LAYOUT_LINEAR;
718    *macrotiled = RADEON_LAYOUT_LINEAR;
719    if (args.tiling_flags & RADEON_BO_FLAGS_MICRO_TILE)
720        *microtiled = RADEON_LAYOUT_TILED;
721
722    if (args.tiling_flags & RADEON_BO_FLAGS_MACRO_TILE)
723        *macrotiled = RADEON_LAYOUT_TILED;
724    if (bankw && tile_split && stencil_tile_split && mtilea && tile_split) {
725        *bankw = (args.tiling_flags >> RADEON_TILING_EG_BANKW_SHIFT) & RADEON_TILING_EG_BANKW_MASK;
726        *bankh = (args.tiling_flags >> RADEON_TILING_EG_BANKH_SHIFT) & RADEON_TILING_EG_BANKH_MASK;
727        *tile_split = (args.tiling_flags >> RADEON_TILING_EG_TILE_SPLIT_SHIFT) & RADEON_TILING_EG_TILE_SPLIT_MASK;
728        *stencil_tile_split = (args.tiling_flags >> RADEON_TILING_EG_STENCIL_TILE_SPLIT_SHIFT) & RADEON_TILING_EG_STENCIL_TILE_SPLIT_MASK;
729        *mtilea = (args.tiling_flags >> RADEON_TILING_EG_MACRO_TILE_ASPECT_SHIFT) & RADEON_TILING_EG_MACRO_TILE_ASPECT_MASK;
730        *tile_split = eg_tile_split(*tile_split);
731    }
732}
733
734static void radeon_bo_set_tiling(struct pb_buffer *_buf,
735                                 struct radeon_winsys_cs *rcs,
736                                 enum radeon_bo_layout microtiled,
737                                 enum radeon_bo_layout macrotiled,
738                                 unsigned bankw, unsigned bankh,
739                                 unsigned tile_split,
740                                 unsigned stencil_tile_split,
741                                 unsigned mtilea,
742                                 uint32_t pitch)
743{
744    struct radeon_bo *bo = get_radeon_bo(_buf);
745    struct radeon_drm_cs *cs = radeon_drm_cs(rcs);
746    struct drm_radeon_gem_set_tiling args;
747
748    memset(&args, 0, sizeof(args));
749
750    /* Tiling determines how DRM treats the buffer data.
751     * We must flush CS when changing it if the buffer is referenced. */
752    if (cs && radeon_bo_is_referenced_by_cs(cs, bo)) {
753        cs->flush_cs(cs->flush_data, 0);
754    }
755
756    while (p_atomic_read(&bo->num_active_ioctls)) {
757        sched_yield();
758    }
759
760    if (microtiled == RADEON_LAYOUT_TILED)
761        args.tiling_flags |= RADEON_BO_FLAGS_MICRO_TILE;
762    else if (microtiled == RADEON_LAYOUT_SQUARETILED)
763        args.tiling_flags |= RADEON_BO_FLAGS_MICRO_TILE_SQUARE;
764
765    if (macrotiled == RADEON_LAYOUT_TILED)
766        args.tiling_flags |= RADEON_BO_FLAGS_MACRO_TILE;
767
768    args.tiling_flags |= (bankw & RADEON_TILING_EG_BANKW_MASK) <<
769        RADEON_TILING_EG_BANKW_SHIFT;
770    args.tiling_flags |= (bankh & RADEON_TILING_EG_BANKH_MASK) <<
771        RADEON_TILING_EG_BANKH_SHIFT;
772    if (tile_split) {
773	args.tiling_flags |= (eg_tile_split_rev(tile_split) &
774			      RADEON_TILING_EG_TILE_SPLIT_MASK) <<
775	    RADEON_TILING_EG_TILE_SPLIT_SHIFT;
776    }
777    args.tiling_flags |= (stencil_tile_split &
778			  RADEON_TILING_EG_STENCIL_TILE_SPLIT_MASK) <<
779        RADEON_TILING_EG_STENCIL_TILE_SPLIT_SHIFT;
780    args.tiling_flags |= (mtilea & RADEON_TILING_EG_MACRO_TILE_ASPECT_MASK) <<
781        RADEON_TILING_EG_MACRO_TILE_ASPECT_SHIFT;
782
783    args.handle = bo->handle;
784    args.pitch = pitch;
785
786    drmCommandWriteRead(bo->rws->fd,
787                        DRM_RADEON_GEM_SET_TILING,
788                        &args,
789                        sizeof(args));
790}
791
792static struct radeon_winsys_cs_handle *radeon_drm_get_cs_handle(
793        struct pb_buffer *_buf)
794{
795    /* return radeon_bo. */
796    return (struct radeon_winsys_cs_handle*)get_radeon_bo(_buf);
797}
798
799static struct pb_buffer *
800radeon_winsys_bo_create(struct radeon_winsys *rws,
801                        unsigned size,
802                        unsigned alignment,
803                        unsigned bind,
804                        enum radeon_bo_domain domain)
805{
806    struct radeon_drm_winsys *ws = radeon_drm_winsys(rws);
807    struct radeon_bo_desc desc;
808    struct pb_manager *provider;
809    struct pb_buffer *buffer;
810
811    memset(&desc, 0, sizeof(desc));
812    desc.base.alignment = alignment;
813
814    /* Additional criteria for the cache manager. */
815    desc.base.usage = domain;
816    desc.initial_domains = domain;
817
818    /* Assign a buffer manager. */
819    if (bind & (PIPE_BIND_VERTEX_BUFFER | PIPE_BIND_INDEX_BUFFER |
820                PIPE_BIND_CONSTANT_BUFFER | PIPE_BIND_CUSTOM))
821        provider = ws->cman;
822    else
823        provider = ws->kman;
824
825    buffer = provider->create_buffer(provider, size, &desc.base);
826    if (!buffer)
827        return NULL;
828
829    return (struct pb_buffer*)buffer;
830}
831
832static struct pb_buffer *radeon_winsys_bo_from_handle(struct radeon_winsys *rws,
833                                                      struct winsys_handle *whandle,
834                                                      unsigned *stride)
835{
836    struct radeon_drm_winsys *ws = radeon_drm_winsys(rws);
837    struct radeon_bo *bo;
838    struct radeon_bomgr *mgr = radeon_bomgr(ws->kman);
839    struct drm_gem_open open_arg = {};
840    int r;
841
842    memset(&open_arg, 0, sizeof(open_arg));
843
844    /* We must maintain a list of pairs <handle, bo>, so that we always return
845     * the same BO for one particular handle. If we didn't do that and created
846     * more than one BO for the same handle and then relocated them in a CS,
847     * we would hit a deadlock in the kernel.
848     *
849     * The list of pairs is guarded by a mutex, of course. */
850    pipe_mutex_lock(mgr->bo_handles_mutex);
851
852    /* First check if there already is an existing bo for the handle. */
853    bo = util_hash_table_get(mgr->bo_handles, (void*)(uintptr_t)whandle->handle);
854    if (bo) {
855        /* Increase the refcount. */
856        struct pb_buffer *b = NULL;
857        pb_reference(&b, &bo->base);
858        goto done;
859    }
860
861    /* There isn't, create a new one. */
862    bo = CALLOC_STRUCT(radeon_bo);
863    if (!bo) {
864        goto fail;
865    }
866
867    /* Open the BO. */
868    open_arg.name = whandle->handle;
869    if (drmIoctl(ws->fd, DRM_IOCTL_GEM_OPEN, &open_arg)) {
870        FREE(bo);
871        goto fail;
872    }
873    bo->handle = open_arg.handle;
874    bo->name = whandle->handle;
875
876    /* Initialize it. */
877    pipe_reference_init(&bo->base.reference, 1);
878    bo->base.alignment = 0;
879    bo->base.usage = PB_USAGE_GPU_WRITE | PB_USAGE_GPU_READ;
880    bo->base.size = open_arg.size;
881    bo->base.vtbl = &radeon_bo_vtbl;
882    bo->mgr = mgr;
883    bo->rws = mgr->rws;
884    bo->va = 0;
885    pipe_mutex_init(bo->map_mutex);
886
887    util_hash_table_set(mgr->bo_handles, (void*)(uintptr_t)whandle->handle, bo);
888
889done:
890    pipe_mutex_unlock(mgr->bo_handles_mutex);
891
892    if (stride)
893        *stride = whandle->stride;
894
895    if (mgr->va) {
896        struct drm_radeon_gem_va va;
897
898        bo->va_size = ((bo->base.size + 4095) & ~4095);
899        bo->va = radeon_bomgr_find_va(mgr, bo->va_size, 1 << 20);
900
901        va.handle = bo->handle;
902        va.operation = RADEON_VA_MAP;
903        va.vm_id = 0;
904        va.offset = bo->va;
905        va.flags = RADEON_VM_PAGE_READABLE |
906                   RADEON_VM_PAGE_WRITEABLE |
907                   RADEON_VM_PAGE_SNOOPED;
908        va.offset = bo->va;
909        r = drmCommandWriteRead(ws->fd, DRM_RADEON_GEM_VA, &va, sizeof(va));
910        if (r && va.operation == RADEON_VA_RESULT_ERROR) {
911            fprintf(stderr, "radeon: Failed to assign virtual address space\n");
912            radeon_bo_destroy(&bo->base);
913            return NULL;
914        }
915        if (va.operation == RADEON_VA_RESULT_VA_EXIST) {
916            radeon_bomgr_free_va(mgr, bo->va, bo->va_size);
917            bo->va = va.offset;
918            radeon_bomgr_force_va(mgr, bo->va, bo->va_size);
919        }
920    }
921
922    return (struct pb_buffer*)bo;
923
924fail:
925    pipe_mutex_unlock(mgr->bo_handles_mutex);
926    return NULL;
927}
928
929static boolean radeon_winsys_bo_get_handle(struct pb_buffer *buffer,
930                                           unsigned stride,
931                                           struct winsys_handle *whandle)
932{
933    struct drm_gem_flink flink;
934    struct radeon_bo *bo = get_radeon_bo(buffer);
935
936    memset(&flink, 0, sizeof(flink));
937
938    if (whandle->type == DRM_API_HANDLE_TYPE_SHARED) {
939        if (!bo->flinked) {
940            flink.handle = bo->handle;
941
942            if (ioctl(bo->rws->fd, DRM_IOCTL_GEM_FLINK, &flink)) {
943                return FALSE;
944            }
945
946            bo->flinked = TRUE;
947            bo->flink = flink.name;
948        }
949        whandle->handle = bo->flink;
950    } else if (whandle->type == DRM_API_HANDLE_TYPE_KMS) {
951        whandle->handle = bo->handle;
952    }
953
954    whandle->stride = stride;
955    return TRUE;
956}
957
958static uint64_t radeon_winsys_bo_va(struct radeon_winsys_cs_handle *buf)
959{
960    return ((struct radeon_bo*)buf)->va;
961}
962
963void radeon_bomgr_init_functions(struct radeon_drm_winsys *ws)
964{
965    ws->base.buffer_get_cs_handle = radeon_drm_get_cs_handle;
966    ws->base.buffer_set_tiling = radeon_bo_set_tiling;
967    ws->base.buffer_get_tiling = radeon_bo_get_tiling;
968    ws->base.buffer_map = radeon_bo_map;
969    ws->base.buffer_unmap = radeon_bo_unmap;
970    ws->base.buffer_wait = radeon_bo_wait;
971    ws->base.buffer_is_busy = radeon_bo_is_busy;
972    ws->base.buffer_create = radeon_winsys_bo_create;
973    ws->base.buffer_from_handle = radeon_winsys_bo_from_handle;
974    ws->base.buffer_get_handle = radeon_winsys_bo_get_handle;
975    ws->base.buffer_get_virtual_address = radeon_winsys_bo_va;
976}
977