summaryrefslogtreecommitdiffstats
path: root/src/gallium/winsys/amdgpu/drm/amdgpu_cs.c
blob: 8c1e9fbb11f1a355a5bc05601664ce6503864b14 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
/*
 * Copyright © 2008 Jérôme Glisse
 * Copyright © 2010 Marek Olšák <maraeo@gmail.com>
 * Copyright © 2015 Advanced Micro Devices, Inc.
 * All Rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sub license, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS, AUTHORS
 * AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
 * USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * The above copyright notice and this permission notice (including the
 * next paragraph) shall be included in all copies or substantial portions
 * of the Software.
 */
/*
 * Authors:
 *      Marek Olšák <maraeo@gmail.com>
 */

#include "amdgpu_cs.h"
#include "os/os_time.h"
#include <stdio.h>
#include <amdgpu_drm.h>

#include "../../../drivers/radeonsi/sid.h"

/* FENCES */

static struct pipe_fence_handle *
amdgpu_fence_create(struct amdgpu_ctx *ctx, unsigned ip_type,
                    unsigned ip_instance, unsigned ring)
{
   struct amdgpu_fence *fence = CALLOC_STRUCT(amdgpu_fence);

   fence->reference.count = 1;
   fence->ctx = ctx;
   fence->fence.context = ctx->ctx;
   fence->fence.ip_type = ip_type;
   fence->fence.ip_instance = ip_instance;
   fence->fence.ring = ring;
   fence->submission_in_progress = true;
   p_atomic_inc(&ctx->refcount);
   return (struct pipe_fence_handle *)fence;
}

static void amdgpu_fence_submitted(struct pipe_fence_handle *fence,
				struct amdgpu_cs_request* request,
				uint64_t *user_fence_cpu_address)
{
   struct amdgpu_fence *rfence = (struct amdgpu_fence*)fence;

   rfence->fence.fence = request->seq_no;
   rfence->user_fence_cpu_address = user_fence_cpu_address;
   rfence->submission_in_progress = false;
}

static void amdgpu_fence_signalled(struct pipe_fence_handle *fence)
{
   struct amdgpu_fence *rfence = (struct amdgpu_fence*)fence;

   rfence->signalled = true;
   rfence->submission_in_progress = false;
}

bool amdgpu_fence_wait(struct pipe_fence_handle *fence, uint64_t timeout,
                       bool absolute)
{
   struct amdgpu_fence *rfence = (struct amdgpu_fence*)fence;
   uint32_t expired;
   int64_t abs_timeout;
   uint64_t *user_fence_cpu;
   int r;

   if (rfence->signalled)
      return true;

   if (absolute)
      abs_timeout = timeout;
   else
      abs_timeout = os_time_get_absolute_timeout(timeout);

   /* The fence might not have a number assigned if its IB is being
    * submitted in the other thread right now. Wait until the submission
    * is done. */
   if (!os_wait_until_zero_abs_timeout(&rfence->submission_in_progress,
                                       abs_timeout))
      return false;

   user_fence_cpu = rfence->user_fence_cpu_address;
   if (user_fence_cpu) {
      if (*user_fence_cpu >= rfence->fence.fence) {
         rfence->signalled = true;
         return true;
      }

      /* No timeout, just query: no need for the ioctl. */
      if (!absolute && !timeout)
         return false;
   }

   /* Now use the libdrm query. */
   r = amdgpu_cs_query_fence_status(&rfence->fence,
				    abs_timeout,
				    AMDGPU_QUERY_FENCE_TIMEOUT_IS_ABSOLUTE,
				    &expired);
   if (r) {
      fprintf(stderr, "amdgpu: amdgpu_cs_query_fence_status failed.\n");
      return FALSE;
   }

   if (expired) {
      /* This variable can only transition from false to true, so it doesn't
       * matter if threads race for it. */
      rfence->signalled = true;
      return true;
   }
   return false;
}

static bool amdgpu_fence_wait_rel_timeout(struct radeon_winsys *rws,
                                          struct pipe_fence_handle *fence,
                                          uint64_t timeout)
{
   return amdgpu_fence_wait(fence, timeout, false);
}

/* CONTEXTS */

static struct radeon_winsys_ctx *amdgpu_ctx_create(struct radeon_winsys *ws)
{
   struct amdgpu_ctx *ctx = CALLOC_STRUCT(amdgpu_ctx);
   int r;
   struct amdgpu_bo_alloc_request alloc_buffer = {};
   amdgpu_bo_handle buf_handle;

   if (!ctx)
      return NULL;

   ctx->ws = amdgpu_winsys(ws);
   ctx->refcount = 1;

   r = amdgpu_cs_ctx_create(ctx->ws->dev, &ctx->ctx);
   if (r) {
      fprintf(stderr, "amdgpu: amdgpu_cs_ctx_create failed. (%i)\n", r);
      goto error_create;
   }

   alloc_buffer.alloc_size = ctx->ws->info.gart_page_size;
   alloc_buffer.phys_alignment = ctx->ws->info.gart_page_size;
   alloc_buffer.preferred_heap = AMDGPU_GEM_DOMAIN_GTT;

   r = amdgpu_bo_alloc(ctx->ws->dev, &alloc_buffer, &buf_handle);
   if (r) {
      fprintf(stderr, "amdgpu: amdgpu_bo_alloc failed. (%i)\n", r);
      goto error_user_fence_alloc;
   }

   r = amdgpu_bo_cpu_map(buf_handle, (void**)&ctx->user_fence_cpu_address_base);
   if (r) {
      fprintf(stderr, "amdgpu: amdgpu_bo_cpu_map failed. (%i)\n", r);
      goto error_user_fence_map;
   }

   memset(ctx->user_fence_cpu_address_base, 0, alloc_buffer.alloc_size);
   ctx->user_fence_bo = buf_handle;

   return (struct radeon_winsys_ctx*)ctx;

error_user_fence_map:
   amdgpu_bo_free(buf_handle);
error_user_fence_alloc:
   amdgpu_cs_ctx_free(ctx->ctx);
error_create:
   FREE(ctx);
   return NULL;
}

static void amdgpu_ctx_destroy(struct radeon_winsys_ctx *rwctx)
{
   amdgpu_ctx_unref((struct amdgpu_ctx*)rwctx);
}

static enum pipe_reset_status
amdgpu_ctx_query_reset_status(struct radeon_winsys_ctx *rwctx)
{
   struct amdgpu_ctx *ctx = (struct amdgpu_ctx*)rwctx;
   uint32_t result, hangs;
   int r;

   r = amdgpu_cs_query_reset_state(ctx->ctx, &result, &hangs);
   if (r) {
      fprintf(stderr, "amdgpu: amdgpu_cs_query_reset_state failed. (%i)\n", r);
      return PIPE_NO_RESET;
   }

   switch (result) {
   case AMDGPU_CTX_GUILTY_RESET:
      return PIPE_GUILTY_CONTEXT_RESET;
   case AMDGPU_CTX_INNOCENT_RESET:
      return PIPE_INNOCENT_CONTEXT_RESET;
   case AMDGPU_CTX_UNKNOWN_RESET:
      return PIPE_UNKNOWN_CONTEXT_RESET;
   case AMDGPU_CTX_NO_RESET:
   default:
      return PIPE_NO_RESET;
   }
}

/* COMMAND SUBMISSION */

static bool amdgpu_cs_has_user_fence(struct amdgpu_cs_context *cs)
{
   return cs->request.ip_type != AMDGPU_HW_IP_UVD &&
          cs->request.ip_type != AMDGPU_HW_IP_VCE;
}

static bool amdgpu_cs_has_chaining(enum ring_type ring_type)
{
   return ring_type == RING_GFX;
}

static unsigned amdgpu_cs_epilog_dws(enum ring_type ring_type)
{
   if (ring_type == RING_GFX)
      return 4; /* for chaining */

   return 0;
}

int amdgpu_lookup_buffer(struct amdgpu_cs_context *cs, struct amdgpu_winsys_bo *bo)
{
   unsigned hash = bo->unique_id & (ARRAY_SIZE(cs->buffer_indices_hashlist)-1);
   int i = cs->buffer_indices_hashlist[hash];

   /* not found or found */
   if (i == -1 || cs->buffers[i].bo == bo)
      return i;

   /* Hash collision, look for the BO in the list of buffers linearly. */
   for (i = cs->num_buffers - 1; i >= 0; i--) {
      if (cs->buffers[i].bo == bo) {
         /* Put this buffer in the hash list.
          * This will prevent additional hash collisions if there are
          * several consecutive lookup_buffer calls for the same buffer.
          *
          * Example: Assuming buffers A,B,C collide in the hash list,
          * the following sequence of buffers:
          *         AAAAAAAAAAABBBBBBBBBBBBBBCCCCCCCC
          * will collide here: ^ and here:   ^,
          * meaning that we should get very few collisions in the end. */
         cs->buffer_indices_hashlist[hash] = i;
         return i;
      }
   }
   return -1;
}

static unsigned amdgpu_add_buffer(struct amdgpu_cs *acs,
                                 struct amdgpu_winsys_bo *bo,
                                 enum radeon_bo_usage usage,
                                 enum radeon_bo_domain domains,
                                 unsigned priority,
                                 enum radeon_bo_domain *added_domains)
{
   struct amdgpu_cs_context *cs = acs->csc;
   struct amdgpu_cs_buffer *buffer;
   unsigned hash = bo->unique_id & (ARRAY_SIZE(cs->buffer_indices_hashlist)-1);
   int i = -1;

   assert(priority < 64);
   *added_domains = 0;

   i = amdgpu_lookup_buffer(cs, bo);

   if (i >= 0) {
      buffer = &cs->buffers[i];
      buffer->priority_usage |= 1llu << priority;
      buffer->usage |= usage;
      *added_domains = domains & ~buffer->domains;
      buffer->domains |= domains;
      cs->flags[i] = MAX2(cs->flags[i], priority / 4);
      return i;
   }

   /* New buffer, check if the backing array is large enough. */
   if (cs->num_buffers >= cs->max_num_buffers) {
      uint32_t size;
      cs->max_num_buffers += 10;

      size = cs->max_num_buffers * sizeof(struct amdgpu_cs_buffer);
      cs->buffers = realloc(cs->buffers, size);

      size = cs->max_num_buffers * sizeof(amdgpu_bo_handle);
      cs->handles = realloc(cs->handles, size);

      cs->flags = realloc(cs->flags, cs->max_num_buffers);
   }

   /* Initialize the new buffer. */
   cs->buffers[cs->num_buffers].bo = NULL;
   amdgpu_winsys_bo_reference(&cs->buffers[cs->num_buffers].bo, bo);
   cs->handles[cs->num_buffers] = bo->bo;
   cs->flags[cs->num_buffers] = priority / 4;
   p_atomic_inc(&bo->num_cs_references);
   buffer = &cs->buffers[cs->num_buffers];
   buffer->bo = bo;
   buffer->priority_usage = 1llu << priority;
   buffer->usage = usage;
   buffer->domains = domains;

   cs->buffer_indices_hashlist[hash] = cs->num_buffers;

   *added_domains = domains;
   return cs->num_buffers++;
}

static unsigned amdgpu_cs_add_buffer(struct radeon_winsys_cs *rcs,
                                    struct pb_buffer *buf,
                                    enum radeon_bo_usage usage,
                                    enum radeon_bo_domain domains,
                                    enum radeon_bo_priority priority)
{
   /* Don't use the "domains" parameter. Amdgpu doesn't support changing
    * the buffer placement during command submission.
    */
   struct amdgpu_cs *cs = amdgpu_cs(rcs);
   struct amdgpu_winsys_bo *bo = (struct amdgpu_winsys_bo*)buf;
   enum radeon_bo_domain added_domains;
   unsigned index = amdgpu_add_buffer(cs, bo, usage, bo->initial_domain,
                                     priority, &added_domains);

   if (added_domains & RADEON_DOMAIN_VRAM)
      cs->csc->used_vram += bo->base.size;
   else if (added_domains & RADEON_DOMAIN_GTT)
      cs->csc->used_gart += bo->base.size;

   return index;
}

static bool amdgpu_ib_new_buffer(struct amdgpu_winsys *ws, struct amdgpu_ib *ib)
{
   struct pb_buffer *pb;
   uint8_t *mapped;
   unsigned buffer_size;

   /* Always create a buffer that is at least as large as the maximum seen IB
    * size, aligned to a power of two (and multiplied by 4 to reduce internal
    * fragmentation if chaining is not available). Limit to 512k dwords, which
    * is the largest power of two that fits into the size field of the
    * INDIRECT_BUFFER packet.
    */
   if (amdgpu_cs_has_chaining(amdgpu_cs_from_ib(ib)->ring_type))
      buffer_size = 4 *util_next_power_of_two(ib->max_ib_size);
   else
      buffer_size = 4 *util_next_power_of_two(4 * ib->max_ib_size);

   buffer_size = MIN2(buffer_size, 4 * 512 * 1024);

   switch (ib->ib_type) {
   case IB_CONST_PREAMBLE:
      buffer_size = MAX2(buffer_size, 4 * 1024);
      break;
   case IB_CONST:
      buffer_size = MAX2(buffer_size, 16 * 1024 * 4);
      break;
   case IB_MAIN:
      buffer_size = MAX2(buffer_size, 8 * 1024 * 4);
      break;
   default:
      unreachable("unhandled IB type");
   }

   pb = ws->base.buffer_create(&ws->base, buffer_size,
                               ws->info.gart_page_size,
                               RADEON_DOMAIN_GTT,
                               RADEON_FLAG_CPU_ACCESS);
   if (!pb)
      return false;

   mapped = ws->base.buffer_map(pb, NULL, PIPE_TRANSFER_WRITE);
   if (!mapped) {
      pb_reference(&pb, NULL);
      return false;
   }

   pb_reference(&ib->big_ib_buffer, pb);
   pb_reference(&pb, NULL);

   ib->ib_mapped = mapped;
   ib->used_ib_space = 0;

   return true;
}

static unsigned amdgpu_ib_max_submit_dwords(enum ib_type ib_type)
{
   switch (ib_type) {
   case IB_MAIN:
      /* Smaller submits means the GPU gets busy sooner and there is less
       * waiting for buffers and fences. Proof:
       *   http://www.phoronix.com/scan.php?page=article&item=mesa-111-si&num=1
       */
      return 20 * 1024;
   case IB_CONST_PREAMBLE:
   case IB_CONST:
      /* There isn't really any reason to limit CE IB size beyond the natural
       * limit implied by the main IB, except perhaps GTT size. Just return
       * an extremely large value that we never get anywhere close to.
       */
      return 16 * 1024 * 1024;
   default:
      unreachable("bad ib_type");
   }
}

static bool amdgpu_get_new_ib(struct radeon_winsys *ws, struct amdgpu_cs *cs,
                              enum ib_type ib_type)
{
   struct amdgpu_winsys *aws = (struct amdgpu_winsys*)ws;
   /* Small IBs are better than big IBs, because the GPU goes idle quicker
    * and there is less waiting for buffers and fences. Proof:
    *   http://www.phoronix.com/scan.php?page=article&item=mesa-111-si&num=1
    */
   struct amdgpu_ib *ib = NULL;
   struct amdgpu_cs_ib_info *info = &cs->csc->ib[ib_type];
   unsigned ib_size = 0;

   switch (ib_type) {
   case IB_CONST_PREAMBLE:
      ib = &cs->const_preamble_ib;
      ib_size = 256 * 4;
      break;
   case IB_CONST:
      ib = &cs->const_ib;
      ib_size = 8 * 1024 * 4;
      break;
   case IB_MAIN:
      ib = &cs->main;
      ib_size = 4 * 1024 * 4;
      break;
   default:
      unreachable("unhandled IB type");
   }

   if (!amdgpu_cs_has_chaining(cs->ring_type)) {
      ib_size = MAX2(ib_size,
                     4 * MIN2(util_next_power_of_two(ib->max_ib_size),
                              amdgpu_ib_max_submit_dwords(ib_type)));
   }

   ib->max_ib_size = ib->max_ib_size - ib->max_ib_size / 32;

   ib->base.prev_dw = 0;
   ib->base.num_prev = 0;
   ib->base.current.cdw = 0;
   ib->base.current.buf = NULL;

   /* Allocate a new buffer for IBs if the current buffer is all used. */
   if (!ib->big_ib_buffer ||
       ib->used_ib_space + ib_size > ib->big_ib_buffer->size) {
      if (!amdgpu_ib_new_buffer(aws, ib))
         return false;
   }

   info->ib_mc_address = amdgpu_winsys_bo(ib->big_ib_buffer)->va +
                         ib->used_ib_space;
   info->size = 0;
   ib->ptr_ib_size = &info->size;

   amdgpu_cs_add_buffer(&cs->main.base, ib->big_ib_buffer,
                        RADEON_USAGE_READ, 0, RADEON_PRIO_IB1);

   ib->base.current.buf = (uint32_t*)(ib->ib_mapped + ib->used_ib_space);

   ib_size = ib->big_ib_buffer->size - ib->used_ib_space;
   ib->base.current.max_dw = ib_size / 4 - amdgpu_cs_epilog_dws(cs->ring_type);
   return true;
}

static void amdgpu_ib_finalize(struct amdgpu_ib *ib)
{
   *ib->ptr_ib_size |= ib->base.current.cdw;
   ib->used_ib_space += ib->base.current.cdw * 4;
   ib->max_ib_size = MAX2(ib->max_ib_size, ib->base.prev_dw + ib->base.current.cdw);
}

static boolean amdgpu_init_cs_context(struct amdgpu_cs_context *cs,
                                      enum ring_type ring_type)
{
   int i;

   switch (ring_type) {
   case RING_DMA:
      cs->request.ip_type = AMDGPU_HW_IP_DMA;
      break;

   case RING_UVD:
      cs->request.ip_type = AMDGPU_HW_IP_UVD;
      break;

   case RING_VCE:
      cs->request.ip_type = AMDGPU_HW_IP_VCE;
      break;

   case RING_COMPUTE:
      cs->request.ip_type = AMDGPU_HW_IP_COMPUTE;
      break;

   default:
   case RING_GFX:
      cs->request.ip_type = AMDGPU_HW_IP_GFX;
      break;
   }

   cs->max_num_buffers = 512;
   cs->buffers = (struct amdgpu_cs_buffer*)
                  CALLOC(1, cs->max_num_buffers * sizeof(struct amdgpu_cs_buffer));
   if (!cs->buffers) {
      return FALSE;
   }

   cs->handles = CALLOC(1, cs->max_num_buffers * sizeof(amdgpu_bo_handle));
   if (!cs->handles) {
      FREE(cs->buffers);
      return FALSE;
   }

   cs->flags = CALLOC(1, cs->max_num_buffers);
   if (!cs->flags) {
      FREE(cs->handles);
      FREE(cs->buffers);
      return FALSE;
   }

   for (i = 0; i < ARRAY_SIZE(cs->buffer_indices_hashlist); i++) {
      cs->buffer_indices_hashlist[i] = -1;
   }

   cs->request.number_of_ibs = 1;
   cs->request.ibs = &cs->ib[IB_MAIN];

   cs->ib[IB_CONST].flags = AMDGPU_IB_FLAG_CE;
   cs->ib[IB_CONST_PREAMBLE].flags = AMDGPU_IB_FLAG_CE |
                                     AMDGPU_IB_FLAG_PREAMBLE;

   return TRUE;
}

static void amdgpu_cs_context_cleanup(struct amdgpu_cs_context *cs)
{
   unsigned i;

   for (i = 0; i < cs->num_buffers; i++) {
      p_atomic_dec(&cs->buffers[i].bo->num_cs_references);
      amdgpu_winsys_bo_reference(&cs->buffers[i].bo, NULL);
      cs->handles[i] = NULL;
      cs->flags[i] = 0;
   }

   cs->num_buffers = 0;
   cs->used_gart = 0;
   cs->used_vram = 0;
   amdgpu_fence_reference(&cs->fence, NULL);

   for (i = 0; i < ARRAY_SIZE(cs->buffer_indices_hashlist); i++) {
      cs->buffer_indices_hashlist[i] = -1;
   }
}

static void amdgpu_destroy_cs_context(struct amdgpu_cs_context *cs)
{
   amdgpu_cs_context_cleanup(cs);
   FREE(cs->flags);
   FREE(cs->buffers);
   FREE(cs->handles);
   FREE(cs->request.dependencies);
}


static struct radeon_winsys_cs *
amdgpu_cs_create(struct radeon_winsys_ctx *rwctx,
                 enum ring_type ring_type,
                 void (*flush)(void *ctx, unsigned flags,
                               struct pipe_fence_handle **fence),
                 void *flush_ctx)
{
   struct amdgpu_ctx *ctx = (struct amdgpu_ctx*)rwctx;
   struct amdgpu_cs *cs;

   cs = CALLOC_STRUCT(amdgpu_cs);
   if (!cs) {
      return NULL;
   }

   util_queue_fence_init(&cs->flush_completed);

   cs->ctx = ctx;
   cs->flush_cs = flush;
   cs->flush_data = flush_ctx;
   cs->ring_type = ring_type;

   cs->main.ib_type = IB_MAIN;
   cs->const_ib.ib_type = IB_CONST;
   cs->const_preamble_ib.ib_type = IB_CONST_PREAMBLE;

   if (!amdgpu_init_cs_context(&cs->csc1, ring_type)) {
      FREE(cs);
      return NULL;
   }

   if (!amdgpu_init_cs_context(&cs->csc2, ring_type)) {
      amdgpu_destroy_cs_context(&cs->csc1);
      FREE(cs);
      return NULL;
   }

   /* Set the first submission context as current. */
   cs->csc = &cs->csc1;
   cs->cst = &cs->csc2;

   if (!amdgpu_get_new_ib(&ctx->ws->base, cs, IB_MAIN)) {
      amdgpu_destroy_cs_context(&cs->csc2);
      amdgpu_destroy_cs_context(&cs->csc1);
      FREE(cs);
      return NULL;
   }

   p_atomic_inc(&ctx->ws->num_cs);
   return &cs->main.base;
}

static struct radeon_winsys_cs *
amdgpu_cs_add_const_ib(struct radeon_winsys_cs *rcs)
{
   struct amdgpu_cs *cs = (struct amdgpu_cs*)rcs;
   struct amdgpu_winsys *ws = cs->ctx->ws;

   /* only one const IB can be added */
   if (cs->ring_type != RING_GFX || cs->const_ib.ib_mapped)
      return NULL;

   if (!amdgpu_get_new_ib(&ws->base, cs, IB_CONST))
      return NULL;

   cs->csc->request.number_of_ibs = 2;
   cs->csc->request.ibs = &cs->csc->ib[IB_CONST];

   cs->cst->request.number_of_ibs = 2;
   cs->cst->request.ibs = &cs->cst->ib[IB_CONST];

   return &cs->const_ib.base;
}

static struct radeon_winsys_cs *
amdgpu_cs_add_const_preamble_ib(struct radeon_winsys_cs *rcs)
{
   struct amdgpu_cs *cs = (struct amdgpu_cs*)rcs;
   struct amdgpu_winsys *ws = cs->ctx->ws;

   /* only one const preamble IB can be added and only when the const IB has
    * also been mapped */
   if (cs->ring_type != RING_GFX || !cs->const_ib.ib_mapped ||
       cs->const_preamble_ib.ib_mapped)
      return NULL;

   if (!amdgpu_get_new_ib(&ws->base, cs, IB_CONST_PREAMBLE))
      return NULL;

   cs->csc->request.number_of_ibs = 3;
   cs->csc->request.ibs = &cs->csc->ib[IB_CONST_PREAMBLE];

   cs->cst->request.number_of_ibs = 3;
   cs->cst->request.ibs = &cs->cst->ib[IB_CONST_PREAMBLE];

   return &cs->const_preamble_ib.base;
}

#define OUT_CS(cs, value) (cs)->current.buf[(cs)->current.cdw++] = (value)

static int amdgpu_cs_lookup_buffer(struct radeon_winsys_cs *rcs,
                               struct pb_buffer *buf)
{
   struct amdgpu_cs *cs = amdgpu_cs(rcs);

   return amdgpu_lookup_buffer(cs->csc, (struct amdgpu_winsys_bo*)buf);
}

static boolean amdgpu_cs_validate(struct radeon_winsys_cs *rcs)
{
   return TRUE;
}

static bool amdgpu_cs_check_space(struct radeon_winsys_cs *rcs, unsigned dw)
{
   struct amdgpu_ib *ib = amdgpu_ib(rcs);
   struct amdgpu_cs *cs = amdgpu_cs_from_ib(ib);
   unsigned requested_size = rcs->prev_dw + rcs->current.cdw + dw;
   uint64_t va;
   uint32_t *new_ptr_ib_size;

   assert(rcs->current.cdw <= rcs->current.max_dw);

   if (requested_size > amdgpu_ib_max_submit_dwords(ib->ib_type))
      return false;

   ib->max_ib_size = MAX2(ib->max_ib_size, requested_size);

   if (rcs->current.max_dw - rcs->current.cdw >= dw)
      return true;

   if (!amdgpu_cs_has_chaining(cs->ring_type))
      return false;

   /* Allocate a new chunk */
   if (rcs->num_prev >= rcs->max_prev) {
      unsigned new_max_prev = MAX2(1, 2 * rcs->max_prev);
      struct radeon_winsys_cs_chunk *new_prev;

      new_prev = REALLOC(rcs->prev,
                         sizeof(*new_prev) * rcs->max_prev,
                         sizeof(*new_prev) * new_max_prev);
      if (!new_prev)
         return false;

      rcs->prev = new_prev;
      rcs->max_prev = new_max_prev;
   }

   if (!amdgpu_ib_new_buffer(cs->ctx->ws, ib))
      return false;

   assert(ib->used_ib_space == 0);
   va = amdgpu_winsys_bo(ib->big_ib_buffer)->va;

   /* This space was originally reserved. */
   rcs->current.max_dw += 4;
   assert(ib->used_ib_space + 4 * rcs->current.max_dw <= ib->big_ib_buffer->size);

   /* Pad with NOPs and add INDIRECT_BUFFER packet */
   while ((rcs->current.cdw & 7) != 4)
      OUT_CS(rcs, 0xffff1000); /* type3 nop packet */

   OUT_CS(rcs, PKT3(ib->ib_type == IB_MAIN ? PKT3_INDIRECT_BUFFER_CIK
                                           : PKT3_INDIRECT_BUFFER_CONST, 2, 0));
   OUT_CS(rcs, va);
   OUT_CS(rcs, va >> 32);
   new_ptr_ib_size = &rcs->current.buf[rcs->current.cdw];
   OUT_CS(rcs, S_3F2_CHAIN(1) | S_3F2_VALID(1));

   assert((rcs->current.cdw & 7) == 0);
   assert(rcs->current.cdw <= rcs->current.max_dw);

   *ib->ptr_ib_size |= rcs->current.cdw;
   ib->ptr_ib_size = new_ptr_ib_size;

   /* Hook up the new chunk */
   rcs->prev[rcs->num_prev].buf = rcs->current.buf;
   rcs->prev[rcs->num_prev].cdw = rcs->current.cdw;
   rcs->prev[rcs->num_prev].max_dw = rcs->current.cdw; /* no modifications */
   rcs->num_prev++;

   ib->base.prev_dw += ib->base.current.cdw;
   ib->base.current.cdw = 0;

   ib->base.current.buf = (uint32_t*)(ib->ib_mapped + ib->used_ib_space);
   ib->base.current.max_dw = ib->big_ib_buffer->size / 4 - amdgpu_cs_epilog_dws(cs->ring_type);

   amdgpu_cs_add_buffer(&cs->main.base, ib->big_ib_buffer,
                        RADEON_USAGE_READ, 0, RADEON_PRIO_IB1);

   return true;
}

static boolean amdgpu_cs_memory_below_limit(struct radeon_winsys_cs *rcs, uint64_t vram, uint64_t gtt)
{
   struct amdgpu_cs *cs = amdgpu_cs(rcs);
   struct amdgpu_winsys *ws = cs->ctx->ws;

   vram += cs->csc->used_vram;
   gtt += cs->csc->used_gart;

   /* Anything that goes above the VRAM size should go to GTT. */
   if (vram > ws->info.vram_size)
       gtt += vram - ws->info.vram_size;

   /* Now we just need to check if we have enough GTT. */
   return gtt < ws->info.gart_size * 0.7;
}

static uint64_t amdgpu_cs_query_memory_usage(struct radeon_winsys_cs *rcs)
{
   struct amdgpu_cs_context *cs = amdgpu_cs(rcs)->csc;

   return cs->used_vram + cs->used_gart;
}

static unsigned amdgpu_cs_get_buffer_list(struct radeon_winsys_cs *rcs,
                                          struct radeon_bo_list_item *list)
{
    struct amdgpu_cs_context *cs = amdgpu_cs(rcs)->csc;
    int i;

    if (list) {
        for (i = 0; i < cs->num_buffers; i++) {
            pb_reference(&list[i].buf, &cs->buffers[i].bo->base);
            list[i].vm_address = cs->buffers[i].bo->va;
            list[i].priority_usage = cs->buffers[i].priority_usage;
        }
    }
    return cs->num_buffers;
}

DEBUG_GET_ONCE_BOOL_OPTION(all_bos, "RADEON_ALL_BOS", FALSE)

/* Since the kernel driver doesn't synchronize execution between different
 * rings automatically, we have to add fence dependencies manually.
 */
static void amdgpu_add_fence_dependencies(struct amdgpu_cs *acs)
{
   struct amdgpu_cs_context *cs = acs->csc;
   int i, j;

   cs->request.number_of_dependencies = 0;

   for (i = 0; i < cs->num_buffers; i++) {
      for (j = 0; j < RING_LAST; j++) {
         struct amdgpu_cs_fence *dep;
         unsigned idx;

         struct amdgpu_fence *bo_fence = (void *)cs->buffers[i].bo->fence[j];
         if (!bo_fence)
            continue;

         if (bo_fence->ctx == acs->ctx &&
             bo_fence->fence.ip_type == cs->request.ip_type &&
             bo_fence->fence.ip_instance == cs->request.ip_instance &&
             bo_fence->fence.ring == cs->request.ring)
            continue;

         if (amdgpu_fence_wait((void *)bo_fence, 0, false))
            continue;

         if (bo_fence->submission_in_progress)
            os_wait_until_zero(&bo_fence->submission_in_progress,
                               PIPE_TIMEOUT_INFINITE);

         idx = cs->request.number_of_dependencies++;
         if (idx >= cs->max_dependencies) {
            unsigned size;

            cs->max_dependencies = idx + 8;
            size = cs->max_dependencies * sizeof(struct amdgpu_cs_fence);
            cs->request.dependencies = realloc(cs->request.dependencies, size);
         }

         dep = &cs->request.dependencies[idx];
         memcpy(dep, &bo_fence->fence, sizeof(*dep));
      }
   }
}

void amdgpu_cs_submit_ib(void *job, int thread_index)
{
   struct amdgpu_cs *acs = (struct amdgpu_cs*)job;
   struct amdgpu_winsys *ws = acs->ctx->ws;
   struct amdgpu_cs_context *cs = acs->cst;
   int i, r;

   cs->request.fence_info.handle = NULL;
   if (amdgpu_cs_has_user_fence(cs)) {
	cs->request.fence_info.handle = acs->ctx->user_fence_bo;
	cs->request.fence_info.offset = acs->ring_type;
   }

   /* Create the buffer list.
    * Use a buffer list containing all allocated buffers if requested.
    */
   if (debug_get_option_all_bos()) {
      struct amdgpu_winsys_bo *bo;
      amdgpu_bo_handle *handles;
      unsigned num = 0;

      pipe_mutex_lock(ws->global_bo_list_lock);

      handles = malloc(sizeof(handles[0]) * ws->num_buffers);
      if (!handles) {
         pipe_mutex_unlock(ws->global_bo_list_lock);
         amdgpu_cs_context_cleanup(cs);
         return;
      }

      LIST_FOR_EACH_ENTRY(bo, &ws->global_bo_list, global_list_item) {
         assert(num < ws->num_buffers);
         handles[num++] = bo->bo;
      }

      r = amdgpu_bo_list_create(ws->dev, ws->num_buffers,
                                handles, NULL,
                                &cs->request.resources);
      free(handles);
      pipe_mutex_unlock(ws->global_bo_list_lock);
   } else {
      r = amdgpu_bo_list_create(ws->dev, cs->num_buffers,
                                cs->handles, cs->flags,
                                &cs->request.resources);
   }

   if (r) {
      fprintf(stderr, "amdgpu: buffer list creation failed (%d)\n", r);
      cs->request.resources = NULL;
      amdgpu_fence_signalled(cs->fence);
      goto cleanup;
   }

   r = amdgpu_cs_submit(acs->ctx->ctx, 0, &cs->request, 1);
   if (r) {
      if (r == -ENOMEM)
         fprintf(stderr, "amdgpu: Not enough memory for command submission.\n");
      else
         fprintf(stderr, "amdgpu: The CS has been rejected, "
                 "see dmesg for more information.\n");

      amdgpu_fence_signalled(cs->fence);
   } else {
      /* Success. */
      uint64_t *user_fence = NULL;
      if (amdgpu_cs_has_user_fence(cs))
         user_fence = acs->ctx->user_fence_cpu_address_base +
                      cs->request.fence_info.offset;
      amdgpu_fence_submitted(cs->fence, &cs->request, user_fence);
   }

   /* Cleanup. */
   if (cs->request.resources)
      amdgpu_bo_list_destroy(cs->request.resources);

cleanup:
   for (i = 0; i < cs->num_buffers; i++)
      p_atomic_dec(&cs->buffers[i].bo->num_active_ioctls);

   amdgpu_cs_context_cleanup(cs);
}

/* Make sure the previous submission is completed. */
void amdgpu_cs_sync_flush(struct radeon_winsys_cs *rcs)
{
   struct amdgpu_cs *cs = amdgpu_cs(rcs);
   struct amdgpu_winsys *ws = cs->ctx->ws;

   /* Wait for any pending ioctl of this CS to complete. */
   if (util_queue_is_initialized(&ws->cs_queue))
      util_queue_job_wait(&cs->flush_completed);
}

DEBUG_GET_ONCE_BOOL_OPTION(noop, "RADEON_NOOP", FALSE)

static void amdgpu_cs_flush(struct radeon_winsys_cs *rcs,
                            unsigned flags,
                            struct pipe_fence_handle **fence)
{
   struct amdgpu_cs *cs = amdgpu_cs(rcs);
   struct amdgpu_winsys *ws = cs->ctx->ws;

   rcs->current.max_dw += amdgpu_cs_epilog_dws(cs->ring_type);

   switch (cs->ring_type) {
   case RING_DMA:
      /* pad DMA ring to 8 DWs */
      while (rcs->current.cdw & 7)
         OUT_CS(rcs, 0x00000000); /* NOP packet */
      break;
   case RING_GFX:
      /* pad GFX ring to 8 DWs to meet CP fetch alignment requirements */
      while (rcs->current.cdw & 7)
         OUT_CS(rcs, 0xffff1000); /* type3 nop packet */

      /* Also pad the const IB. */
      if (cs->const_ib.ib_mapped)
         while (!cs->const_ib.base.current.cdw || (cs->const_ib.base.current.cdw & 7))
            OUT_CS(&cs->const_ib.base, 0xffff1000); /* type3 nop packet */

      if (cs->const_preamble_ib.ib_mapped)
         while (!cs->const_preamble_ib.base.current.cdw || (cs->const_preamble_ib.base.current.cdw & 7))
            OUT_CS(&cs->const_preamble_ib.base, 0xffff1000);
      break;
   case RING_UVD:
      while (rcs->current.cdw & 15)
         OUT_CS(rcs, 0x80000000); /* type2 nop packet */
      break;
   default:
      break;
   }

   if (rcs->current.cdw > rcs->current.max_dw) {
      fprintf(stderr, "amdgpu: command stream overflowed\n");
   }

   /* If the CS is not empty or overflowed.... */
   if (radeon_emitted(&cs->main.base, 0) &&
       cs->main.base.current.cdw <= cs->main.base.current.max_dw &&
       !debug_get_option_noop()) {
      struct amdgpu_cs_context *cur = cs->csc;
      unsigned i, num_buffers = cur->num_buffers;

      /* Set IB sizes. */
      amdgpu_ib_finalize(&cs->main);

      if (cs->const_ib.ib_mapped)
         amdgpu_ib_finalize(&cs->const_ib);

      if (cs->const_preamble_ib.ib_mapped)
         amdgpu_ib_finalize(&cs->const_preamble_ib);

      /* Create a fence. */
      amdgpu_fence_reference(&cur->fence, NULL);
      cur->fence = amdgpu_fence_create(cs->ctx,
                                           cur->request.ip_type,
                                           cur->request.ip_instance,
                                           cur->request.ring);
      if (fence)
         amdgpu_fence_reference(fence, cur->fence);

      /* Prepare buffers. */
      pipe_mutex_lock(ws->bo_fence_lock);
      amdgpu_add_fence_dependencies(cs);
      for (i = 0; i < num_buffers; i++) {
         p_atomic_inc(&cur->buffers[i].bo->num_active_ioctls);
         amdgpu_fence_reference(&cur->buffers[i].bo->fence[cs->ring_type],
                                cur->fence);
      }
      pipe_mutex_unlock(ws->bo_fence_lock);

      amdgpu_cs_sync_flush(rcs);

      /* Swap command streams. "cst" is going to be submitted. */
      cs->csc = cs->cst;
      cs->cst = cur;

      /* Submit. */
      if ((flags & RADEON_FLUSH_ASYNC) &&
          util_queue_is_initialized(&ws->cs_queue)) {
         util_queue_add_job(&ws->cs_queue, cs, &cs->flush_completed,
                            amdgpu_cs_submit_ib);
      } else {
         amdgpu_cs_submit_ib(cs, 0);
      }
   } else {
      amdgpu_cs_context_cleanup(cs->csc);
   }

   amdgpu_get_new_ib(&ws->base, cs, IB_MAIN);
   if (cs->const_ib.ib_mapped)
      amdgpu_get_new_ib(&ws->base, cs, IB_CONST);
   if (cs->const_preamble_ib.ib_mapped)
      amdgpu_get_new_ib(&ws->base, cs, IB_CONST_PREAMBLE);

   ws->num_cs_flushes++;
}

static void amdgpu_cs_destroy(struct radeon_winsys_cs *rcs)
{
   struct amdgpu_cs *cs = amdgpu_cs(rcs);

   amdgpu_cs_sync_flush(rcs);
   util_queue_fence_destroy(&cs->flush_completed);
   p_atomic_dec(&cs->ctx->ws->num_cs);
   pb_reference(&cs->main.big_ib_buffer, NULL);
   FREE(cs->main.base.prev);
   pb_reference(&cs->const_ib.big_ib_buffer, NULL);
   FREE(cs->const_ib.base.prev);
   pb_reference(&cs->const_preamble_ib.big_ib_buffer, NULL);
   FREE(cs->const_preamble_ib.base.prev);
   amdgpu_destroy_cs_context(&cs->csc1);
   amdgpu_destroy_cs_context(&cs->csc2);
   FREE(cs);
}

static boolean amdgpu_bo_is_referenced(struct radeon_winsys_cs *rcs,
                                       struct pb_buffer *_buf,
                                       enum radeon_bo_usage usage)
{
   struct amdgpu_cs *cs = amdgpu_cs(rcs);
   struct amdgpu_winsys_bo *bo = (struct amdgpu_winsys_bo*)_buf;

   return amdgpu_bo_is_referenced_by_cs_with_usage(cs, bo, usage);
}

void amdgpu_cs_init_functions(struct amdgpu_winsys *ws)
{
   ws->base.ctx_create = amdgpu_ctx_create;
   ws->base.ctx_destroy = amdgpu_ctx_destroy;
   ws->base.ctx_query_reset_status = amdgpu_ctx_query_reset_status;
   ws->base.cs_create = amdgpu_cs_create;
   ws->base.cs_add_const_ib = amdgpu_cs_add_const_ib;
   ws->base.cs_add_const_preamble_ib = amdgpu_cs_add_const_preamble_ib;
   ws->base.cs_destroy = amdgpu_cs_destroy;
   ws->base.cs_add_buffer = amdgpu_cs_add_buffer;
   ws->base.cs_lookup_buffer = amdgpu_cs_lookup_buffer;
   ws->base.cs_validate = amdgpu_cs_validate;
   ws->base.cs_check_space = amdgpu_cs_check_space;
   ws->base.cs_memory_below_limit = amdgpu_cs_memory_below_limit;
   ws->base.cs_query_memory_usage = amdgpu_cs_query_memory_usage;
   ws->base.cs_get_buffer_list = amdgpu_cs_get_buffer_list;
   ws->base.cs_flush = amdgpu_cs_flush;
   ws->base.cs_is_buffer_referenced = amdgpu_bo_is_referenced;
   ws->base.cs_sync_flush = amdgpu_cs_sync_flush;
   ws->base.fence_wait = amdgpu_fence_wait_rel_timeout;
   ws->base.fence_reference = amdgpu_fence_reference;
}