summaryrefslogtreecommitdiffstats
path: root/src/gallium/drivers/svga/svga_resource_buffer_upload.c
blob: ac8cedfd3b791256c75ca0fbc1894f430efb4268 (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
/**********************************************************
 * Copyright 2008-2009 VMware, 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, sublicense, 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 above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * 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
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * 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.
 *
 **********************************************************/


#include "os/os_thread.h"
#include "pipe/p_state.h"
#include "pipe/p_defines.h"
#include "util/u_inlines.h"
#include "util/u_math.h"
#include "util/u_memory.h"

#include "svga_cmd.h"
#include "svga_context.h"
#include "svga_debug.h"
#include "svga_resource_buffer.h"
#include "svga_resource_buffer_upload.h"
#include "svga_screen.h"
#include "svga_winsys.h"

/**
 * Describes a complete SVGA_3D_CMD_UPDATE_GB_IMAGE command
 *
 */
struct svga_3d_update_gb_image {
   SVGA3dCmdHeader header;
   SVGA3dCmdUpdateGBImage body;
};

struct svga_3d_invalidate_gb_image {
   SVGA3dCmdHeader header;
   SVGA3dCmdInvalidateGBImage body;
};


/**
 * Allocate a winsys_buffer (ie. DMA, aka GMR memory).
 *
 * It will flush and retry in case the first attempt to create a DMA buffer
 * fails, so it should not be called from any function involved in flushing
 * to avoid recursion.
 */
struct svga_winsys_buffer *
svga_winsys_buffer_create( struct svga_context *svga,
                           unsigned alignment,
                           unsigned usage,
                           unsigned size )
{
   struct svga_screen *svgascreen = svga_screen(svga->pipe.screen);
   struct svga_winsys_screen *sws = svgascreen->sws;
   struct svga_winsys_buffer *buf;

   /* Just try */
   buf = sws->buffer_create(sws, alignment, usage, size);
   if (!buf) {
      SVGA_DBG(DEBUG_DMA|DEBUG_PERF, "flushing context to find %d bytes GMR\n",
               size);

      /* Try flushing all pending DMAs */
      svga_context_flush(svga, NULL);
      buf = sws->buffer_create(sws, alignment, usage, size);
   }

   return buf;
}


/**
 * Destroy HW storage if separate from the host surface.
 * In the GB case, the HW storage is associated with the host surface
 * and is therefore a No-op.
 */
void
svga_buffer_destroy_hw_storage(struct svga_screen *ss, struct svga_buffer *sbuf)
{
   struct svga_winsys_screen *sws = ss->sws;

   assert(sbuf->map.count == 0);
   assert(sbuf->hwbuf);
   if (sbuf->hwbuf) {
      sws->buffer_destroy(sws, sbuf->hwbuf);
      sbuf->hwbuf = NULL;
   }
}



/**
 * Allocate DMA'ble or Updatable storage for the buffer.
 *
 * Called before mapping a buffer.
 */
enum pipe_error
svga_buffer_create_hw_storage(struct svga_screen *ss,
                              struct svga_buffer *sbuf)
{
   assert(!sbuf->user);

   if (ss->sws->have_gb_objects) {
      assert(sbuf->handle || !sbuf->dma.pending);
      return svga_buffer_create_host_surface(ss, sbuf);
   }
   if (!sbuf->hwbuf) {
      struct svga_winsys_screen *sws = ss->sws;
      unsigned alignment = 16;
      unsigned usage = 0;
      unsigned size = sbuf->b.b.width0;

      sbuf->hwbuf = sws->buffer_create(sws, alignment, usage, size);
      if (!sbuf->hwbuf)
         return PIPE_ERROR_OUT_OF_MEMORY;

      assert(!sbuf->dma.pending);
   }

   return PIPE_OK;
}



enum pipe_error
svga_buffer_create_host_surface(struct svga_screen *ss,
                                struct svga_buffer *sbuf)
{
   assert(!sbuf->user);

   if (!sbuf->handle) {
      sbuf->key.flags = 0;

      sbuf->key.format = SVGA3D_BUFFER;
      if (sbuf->bind_flags & PIPE_BIND_VERTEX_BUFFER) {
         sbuf->key.flags |= SVGA3D_SURFACE_HINT_VERTEXBUFFER;
         sbuf->key.flags |= SVGA3D_SURFACE_BIND_VERTEX_BUFFER;
      }
      if (sbuf->bind_flags & PIPE_BIND_INDEX_BUFFER) {
         sbuf->key.flags |= SVGA3D_SURFACE_HINT_INDEXBUFFER;
         sbuf->key.flags |= SVGA3D_SURFACE_BIND_INDEX_BUFFER;
      }
      if (sbuf->bind_flags & PIPE_BIND_CONSTANT_BUFFER)
         sbuf->key.flags |= SVGA3D_SURFACE_BIND_CONSTANT_BUFFER;

      if (sbuf->bind_flags & PIPE_BIND_STREAM_OUTPUT)
         sbuf->key.flags |= SVGA3D_SURFACE_BIND_STREAM_OUTPUT;

      if (sbuf->bind_flags & PIPE_BIND_SAMPLER_VIEW)
         sbuf->key.flags |= SVGA3D_SURFACE_BIND_SHADER_RESOURCE;

      if (!sbuf->bind_flags && sbuf->b.b.usage == PIPE_USAGE_STAGING) {
         /* This surface is to be used with the
          * SVGA3D_CMD_DX_TRANSFER_FROM_BUFFER command, and no other
          * bind flags are allowed to be set for this surface.
          */
         sbuf->key.flags = SVGA3D_SURFACE_TRANSFER_FROM_BUFFER;
      }

      sbuf->key.size.width = sbuf->b.b.width0;
      sbuf->key.size.height = 1;
      sbuf->key.size.depth = 1;

      sbuf->key.numFaces = 1;
      sbuf->key.numMipLevels = 1;
      sbuf->key.cachable = 1;
      sbuf->key.arraySize = 1;

      SVGA_DBG(DEBUG_DMA, "surface_create for buffer sz %d\n",
               sbuf->b.b.width0);

      sbuf->handle = svga_screen_surface_create(ss, sbuf->b.b.bind,
                                                sbuf->b.b.usage, &sbuf->key);
      if (!sbuf->handle)
         return PIPE_ERROR_OUT_OF_MEMORY;

      /* Always set the discard flag on the first time the buffer is written
       * as svga_screen_surface_create might have passed a recycled host
       * buffer.
       */
      sbuf->dma.flags.discard = TRUE;

      SVGA_DBG(DEBUG_DMA, "   --> got sid %p sz %d (buffer)\n",
               sbuf->handle, sbuf->b.b.width0);
   }

   return PIPE_OK;
}


void
svga_buffer_destroy_host_surface(struct svga_screen *ss,
                                 struct svga_buffer *sbuf)
{
   if (sbuf->handle) {
      SVGA_DBG(DEBUG_DMA, " ungrab sid %p sz %d\n",
               sbuf->handle, sbuf->b.b.width0);
      svga_screen_surface_destroy(ss, &sbuf->key, &sbuf->handle);
   }
}


/**
 * Insert a number of preliminary UPDATE_GB_IMAGE commands in the
 * command buffer, equal to the current number of mapped ranges.
 * The UPDATE_GB_IMAGE commands will be patched with the
 * actual ranges just before flush.
 */
static enum pipe_error
svga_buffer_upload_gb_command(struct svga_context *svga,
			      struct svga_buffer *sbuf)
{
   struct svga_winsys_context *swc = svga->swc;
   SVGA3dCmdUpdateGBImage *update_cmd;
   struct svga_3d_update_gb_image *whole_update_cmd = NULL;
   const uint32 numBoxes = sbuf->map.num_ranges;
   struct pipe_resource *dummy;
   unsigned i;

   assert(svga_have_gb_objects(svga));
   assert(numBoxes);
   assert(sbuf->dma.updates == NULL);

   if (sbuf->dma.flags.discard) {
      struct svga_3d_invalidate_gb_image *cicmd = NULL;
      SVGA3dCmdInvalidateGBImage *invalidate_cmd;
      const unsigned total_commands_size =
         sizeof(*invalidate_cmd) + numBoxes * sizeof(*whole_update_cmd);

      /* Allocate FIFO space for one INVALIDATE_GB_IMAGE command followed by
       * 'numBoxes' UPDATE_GB_IMAGE commands.  Allocate all at once rather
       * than with separate commands because we need to properly deal with
       * filling the command buffer.
       */
      invalidate_cmd = SVGA3D_FIFOReserve(swc,
                                          SVGA_3D_CMD_INVALIDATE_GB_IMAGE,
                                          total_commands_size, 1 + numBoxes);
      if (!invalidate_cmd)
	 return PIPE_ERROR_OUT_OF_MEMORY;

      cicmd = container_of(invalidate_cmd, cicmd, body);
      cicmd->header.size = sizeof(*invalidate_cmd);
      swc->surface_relocation(swc, &invalidate_cmd->image.sid, NULL, sbuf->handle,
                              (SVGA_RELOC_WRITE |
                               SVGA_RELOC_INTERNAL |
                               SVGA_RELOC_DMA));
      invalidate_cmd->image.face = 0;
      invalidate_cmd->image.mipmap = 0;

      /* The whole_update_command is a SVGA3dCmdHeader plus the
       * SVGA3dCmdUpdateGBImage command.
       */
      whole_update_cmd = (struct svga_3d_update_gb_image *) &invalidate_cmd[1];
      /* initialize the first UPDATE_GB_IMAGE command */
      whole_update_cmd->header.id = SVGA_3D_CMD_UPDATE_GB_IMAGE;
      update_cmd = &whole_update_cmd->body;

   } else {
      /* Allocate FIFO space for 'numBoxes' UPDATE_GB_IMAGE commands */
      const unsigned total_commands_size =
         sizeof(*update_cmd) + (numBoxes - 1) * sizeof(*whole_update_cmd);

      update_cmd = SVGA3D_FIFOReserve(swc,
                                      SVGA_3D_CMD_UPDATE_GB_IMAGE,
                                      total_commands_size, numBoxes);
      if (!update_cmd)
	 return PIPE_ERROR_OUT_OF_MEMORY;

      /* The whole_update_command is a SVGA3dCmdHeader plus the
       * SVGA3dCmdUpdateGBImage command.
       */
      whole_update_cmd = container_of(update_cmd, whole_update_cmd, body);
   }

   /* Init the first UPDATE_GB_IMAGE command */
   whole_update_cmd->header.size = sizeof(*update_cmd);
   swc->surface_relocation(swc, &update_cmd->image.sid, NULL, sbuf->handle,
			   SVGA_RELOC_WRITE | SVGA_RELOC_INTERNAL);
   update_cmd->image.face = 0;
   update_cmd->image.mipmap = 0;

   /* Save pointer to the first UPDATE_GB_IMAGE command so that we can
    * fill in the box info below.
    */
   sbuf->dma.updates = whole_update_cmd;

   /*
    * Copy the face, mipmap, etc. info to all subsequent commands.
    * Also do the surface relocation for each subsequent command.
    */
   for (i = 1; i < numBoxes; ++i) {
      whole_update_cmd++;
      memcpy(whole_update_cmd, sbuf->dma.updates, sizeof(*whole_update_cmd));

      swc->surface_relocation(swc, &whole_update_cmd->body.image.sid, NULL,
                              sbuf->handle,
                              SVGA_RELOC_WRITE | SVGA_RELOC_INTERNAL);
   }

   /* Increment reference count */
   sbuf->dma.svga = svga;
   dummy = NULL;
   pipe_resource_reference(&dummy, &sbuf->b.b);
   SVGA_FIFOCommitAll(swc);

   swc->hints |= SVGA_HINT_FLAG_CAN_PRE_FLUSH;
   sbuf->dma.flags.discard = FALSE;

   svga->hud.num_resource_updates++;

   return PIPE_OK;
}


/**
 * Issue DMA commands to transfer guest memory to the host.
 * Note that the memory segments (offset, size) will be patched in
 * later in the svga_buffer_upload_flush() function.
 */
static enum pipe_error
svga_buffer_upload_hb_command(struct svga_context *svga,
                              struct svga_buffer *sbuf)
{
   struct svga_winsys_context *swc = svga->swc;
   struct svga_winsys_buffer *guest = sbuf->hwbuf;
   struct svga_winsys_surface *host = sbuf->handle;
   const SVGA3dTransferType transfer = SVGA3D_WRITE_HOST_VRAM;
   SVGA3dCmdSurfaceDMA *cmd;
   const uint32 numBoxes = sbuf->map.num_ranges;
   SVGA3dCopyBox *boxes;
   SVGA3dCmdSurfaceDMASuffix *pSuffix;
   unsigned region_flags;
   unsigned surface_flags;
   struct pipe_resource *dummy;

   assert(!svga_have_gb_objects(svga));

   if (transfer == SVGA3D_WRITE_HOST_VRAM) {
      region_flags = SVGA_RELOC_READ;
      surface_flags = SVGA_RELOC_WRITE;
   }
   else if (transfer == SVGA3D_READ_HOST_VRAM) {
      region_flags = SVGA_RELOC_WRITE;
      surface_flags = SVGA_RELOC_READ;
   }
   else {
      assert(0);
      return PIPE_ERROR_BAD_INPUT;
   }

   assert(numBoxes);

   cmd = SVGA3D_FIFOReserve(swc,
                            SVGA_3D_CMD_SURFACE_DMA,
                            sizeof *cmd + numBoxes * sizeof *boxes + sizeof *pSuffix,
                            2);
   if (!cmd)
      return PIPE_ERROR_OUT_OF_MEMORY;

   swc->region_relocation(swc, &cmd->guest.ptr, guest, 0, region_flags);
   cmd->guest.pitch = 0;

   swc->surface_relocation(swc, &cmd->host.sid, NULL, host, surface_flags);
   cmd->host.face = 0;
   cmd->host.mipmap = 0;

   cmd->transfer = transfer;

   sbuf->dma.boxes = (SVGA3dCopyBox *)&cmd[1];
   sbuf->dma.svga = svga;

   /* Increment reference count */
   dummy = NULL;
   pipe_resource_reference(&dummy, &sbuf->b.b);

   pSuffix = (SVGA3dCmdSurfaceDMASuffix *)((uint8_t*)cmd + sizeof *cmd + numBoxes * sizeof *boxes);
   pSuffix->suffixSize = sizeof *pSuffix;
   pSuffix->maximumOffset = sbuf->b.b.width0;
   pSuffix->flags = sbuf->dma.flags;

   SVGA_FIFOCommitAll(swc);

   swc->hints |= SVGA_HINT_FLAG_CAN_PRE_FLUSH;
   sbuf->dma.flags.discard = FALSE;

   svga->hud.num_buffer_uploads++;

   return PIPE_OK;
}


/**
 * Issue commands to transfer guest memory to the host.
 */
static enum pipe_error
svga_buffer_upload_command(struct svga_context *svga, struct svga_buffer *sbuf)
{
   if (svga_have_gb_objects(svga)) {
      return svga_buffer_upload_gb_command(svga, sbuf);
   } else {
      return svga_buffer_upload_hb_command(svga, sbuf);
   }
}


/**
 * Patch up the upload DMA command reserved by svga_buffer_upload_command
 * with the final ranges.
 */
void
svga_buffer_upload_flush(struct svga_context *svga,
			 struct svga_buffer *sbuf)
{
   unsigned i;
   struct pipe_resource *dummy;

   if (!sbuf->dma.pending) {
      //debug_printf("no dma pending on buffer\n");
      return;
   }

   assert(sbuf->handle);
   assert(sbuf->map.num_ranges);
   assert(sbuf->dma.svga == svga);

   /*
    * Patch the DMA/update command with the final copy box.
    */
   if (svga_have_gb_objects(svga)) {
      struct svga_3d_update_gb_image *update = sbuf->dma.updates;
      assert(update);

      for (i = 0; i < sbuf->map.num_ranges; ++i, ++update) {
         SVGA3dBox *box = &update->body.box;

         SVGA_DBG(DEBUG_DMA, "  bytes %u - %u\n",
                  sbuf->map.ranges[i].start, sbuf->map.ranges[i].end);

         box->x = sbuf->map.ranges[i].start;
         box->y = 0;
         box->z = 0;
         box->w = sbuf->map.ranges[i].end - sbuf->map.ranges[i].start;
         box->h = 1;
         box->d = 1;

         assert(box->x <= sbuf->b.b.width0);
         assert(box->x + box->w <= sbuf->b.b.width0);

         svga->hud.num_bytes_uploaded += box->w;
         svga->hud.num_buffer_uploads++;
      }
   }
   else {
      assert(sbuf->hwbuf);
      assert(sbuf->dma.boxes);
      SVGA_DBG(DEBUG_DMA, "dma to sid %p\n", sbuf->handle);

      for (i = 0; i < sbuf->map.num_ranges; ++i) {
         SVGA3dCopyBox *box = sbuf->dma.boxes + i;

         SVGA_DBG(DEBUG_DMA, "  bytes %u - %u\n",
               sbuf->map.ranges[i].start, sbuf->map.ranges[i].end);

         box->x = sbuf->map.ranges[i].start;
         box->y = 0;
         box->z = 0;
         box->w = sbuf->map.ranges[i].end - sbuf->map.ranges[i].start;
         box->h = 1;
         box->d = 1;
         box->srcx = sbuf->map.ranges[i].start;
         box->srcy = 0;
         box->srcz = 0;

         assert(box->x <= sbuf->b.b.width0);
         assert(box->x + box->w <= sbuf->b.b.width0);

         svga->hud.num_bytes_uploaded += box->w;
         svga->hud.num_buffer_uploads++;
      }
   }

   /* Reset sbuf for next use/upload */

   sbuf->map.num_ranges = 0;

   assert(sbuf->head.prev && sbuf->head.next);
   LIST_DEL(&sbuf->head);  /* remove from svga->dirty_buffers list */
#ifdef DEBUG
   sbuf->head.next = sbuf->head.prev = NULL;
#endif
   sbuf->dma.pending = FALSE;
   sbuf->dma.flags.discard = FALSE;
   sbuf->dma.flags.unsynchronized = FALSE;

   sbuf->dma.svga = NULL;
   sbuf->dma.boxes = NULL;
   sbuf->dma.updates = NULL;

   /* Decrement reference count (and potentially destroy) */
   dummy = &sbuf->b.b;
   pipe_resource_reference(&dummy, NULL);
}


/**
 * Note a dirty range.
 *
 * This function only notes the range down. It doesn't actually emit a DMA
 * upload command. That only happens when a context tries to refer to this
 * buffer, and the DMA upload command is added to that context's command
 * buffer.
 *
 * We try to lump as many contiguous DMA transfers together as possible.
 */
void
svga_buffer_add_range(struct svga_buffer *sbuf, unsigned start, unsigned end)
{
   unsigned i;
   unsigned nearest_range;
   unsigned nearest_dist;

   assert(end > start);

   if (sbuf->map.num_ranges < SVGA_BUFFER_MAX_RANGES) {
      nearest_range = sbuf->map.num_ranges;
      nearest_dist = ~0;
   } else {
      nearest_range = SVGA_BUFFER_MAX_RANGES - 1;
      nearest_dist = 0;
   }

   /*
    * Try to grow one of the ranges.
    */
   for (i = 0; i < sbuf->map.num_ranges; ++i) {
      const int left_dist = start - sbuf->map.ranges[i].end;
      const int right_dist = sbuf->map.ranges[i].start - end;
      const int dist = MAX2(left_dist, right_dist);

      if (dist <= 0) {
         /*
          * Ranges are contiguous or overlapping -- extend this one and return.
          *
          * Note that it is not this function's task to prevent overlapping
          * ranges, as the GMR was already given so it is too late to do
          * anything.  If the ranges overlap here it must surely be because
          * PIPE_TRANSFER_UNSYNCHRONIZED was set.
          */
         sbuf->map.ranges[i].start = MIN2(sbuf->map.ranges[i].start, start);
         sbuf->map.ranges[i].end   = MAX2(sbuf->map.ranges[i].end,   end);
         return;
      }
      else {
         /*
          * Discontiguous ranges -- keep track of the nearest range.
          */
         if (dist < nearest_dist) {
            nearest_range = i;
            nearest_dist = dist;
         }
      }
   }

   /*
    * We cannot add a new range to an existing DMA command, so patch-up the
    * pending DMA upload and start clean.
    */

   svga_buffer_upload_flush(sbuf->dma.svga, sbuf);

   assert(!sbuf->dma.pending);
   assert(!sbuf->dma.svga);
   assert(!sbuf->dma.boxes);

   if (sbuf->map.num_ranges < SVGA_BUFFER_MAX_RANGES) {
      /*
       * Add a new range.
       */

      sbuf->map.ranges[sbuf->map.num_ranges].start = start;
      sbuf->map.ranges[sbuf->map.num_ranges].end = end;
      ++sbuf->map.num_ranges;
   } else {
      /*
       * Everything else failed, so just extend the nearest range.
       *
       * It is OK to do this because we always keep a local copy of the
       * host buffer data, for SW TNL, and the host never modifies the buffer.
       */

      assert(nearest_range < SVGA_BUFFER_MAX_RANGES);
      assert(nearest_range < sbuf->map.num_ranges);
      sbuf->map.ranges[nearest_range].start =
         MIN2(sbuf->map.ranges[nearest_range].start, start);
      sbuf->map.ranges[nearest_range].end =
         MAX2(sbuf->map.ranges[nearest_range].end, end);
   }
}



/**
 * Copy the contents of the malloc buffer to a hardware buffer.
 */
static enum pipe_error
svga_buffer_update_hw(struct svga_context *svga, struct svga_buffer *sbuf)
{
   assert(!sbuf->user);
   if (!svga_buffer_has_hw_storage(sbuf)) {
      struct svga_screen *ss = svga_screen(sbuf->b.b.screen);
      enum pipe_error ret;
      boolean retry;
      void *map;
      unsigned i;

      assert(sbuf->swbuf);
      if (!sbuf->swbuf)
         return PIPE_ERROR;

      ret = svga_buffer_create_hw_storage(svga_screen(sbuf->b.b.screen), sbuf);
      if (ret != PIPE_OK)
         return ret;

      pipe_mutex_lock(ss->swc_mutex);
      map = svga_buffer_hw_storage_map(svga, sbuf, PIPE_TRANSFER_WRITE, &retry);
      assert(map);
      assert(!retry);
      if (!map) {
	 pipe_mutex_unlock(ss->swc_mutex);
         svga_buffer_destroy_hw_storage(ss, sbuf);
         return PIPE_ERROR;
      }

      /* Copy data from malloc'd swbuf to the new hardware buffer */
      for (i = 0; i < sbuf->map.num_ranges; i++) {
         unsigned start = sbuf->map.ranges[i].start;
         unsigned len = sbuf->map.ranges[i].end - start;
         memcpy((uint8_t *) map + start, (uint8_t *) sbuf->swbuf + start, len);
      }

      svga_buffer_hw_storage_unmap(svga, sbuf);

      /* This user/malloc buffer is now indistinguishable from a gpu buffer */
      assert(sbuf->map.count == 0);
      if (sbuf->map.count == 0) {
         if (sbuf->user)
            sbuf->user = FALSE;
         else
            align_free(sbuf->swbuf);
         sbuf->swbuf = NULL;
      }

      pipe_mutex_unlock(ss->swc_mutex);
   }

   return PIPE_OK;
}


/**
 * Upload the buffer to the host in a piecewise fashion.
 *
 * Used when the buffer is too big to fit in the GMR aperture.
 * This function should never get called in the guest-backed case
 * since we always have a full-sized hardware storage backing the
 * host surface.
 */
static enum pipe_error
svga_buffer_upload_piecewise(struct svga_screen *ss,
                             struct svga_context *svga,
                             struct svga_buffer *sbuf)
{
   struct svga_winsys_screen *sws = ss->sws;
   const unsigned alignment = sizeof(void *);
   const unsigned usage = 0;
   unsigned i;

   assert(sbuf->map.num_ranges);
   assert(!sbuf->dma.pending);
   assert(!svga_have_gb_objects(svga));

   SVGA_DBG(DEBUG_DMA, "dma to sid %p\n", sbuf->handle);

   for (i = 0; i < sbuf->map.num_ranges; ++i) {
      const struct svga_buffer_range *range = &sbuf->map.ranges[i];
      unsigned offset = range->start;
      unsigned size = range->end - range->start;

      while (offset < range->end) {
         struct svga_winsys_buffer *hwbuf;
         uint8_t *map;
         enum pipe_error ret;

         if (offset + size > range->end)
            size = range->end - offset;

         hwbuf = sws->buffer_create(sws, alignment, usage, size);
         while (!hwbuf) {
            size /= 2;
            if (!size)
               return PIPE_ERROR_OUT_OF_MEMORY;
            hwbuf = sws->buffer_create(sws, alignment, usage, size);
         }

         SVGA_DBG(DEBUG_DMA, "  bytes %u - %u\n",
                  offset, offset + size);

         map = sws->buffer_map(sws, hwbuf,
                               PIPE_TRANSFER_WRITE |
                               PIPE_TRANSFER_DISCARD_RANGE);
         assert(map);
         if (map) {
            memcpy(map, (const char *) sbuf->swbuf + offset, size);
            sws->buffer_unmap(sws, hwbuf);
         }

         ret = SVGA3D_BufferDMA(svga->swc,
                                hwbuf, sbuf->handle,
                                SVGA3D_WRITE_HOST_VRAM,
                                size, 0, offset, sbuf->dma.flags);
         if (ret != PIPE_OK) {
            svga_context_flush(svga, NULL);
            ret =  SVGA3D_BufferDMA(svga->swc,
                                    hwbuf, sbuf->handle,
                                    SVGA3D_WRITE_HOST_VRAM,
                                    size, 0, offset, sbuf->dma.flags);
            assert(ret == PIPE_OK);
         }

         sbuf->dma.flags.discard = FALSE;

         sws->buffer_destroy(sws, hwbuf);

         offset += size;
      }
   }

   sbuf->map.num_ranges = 0;

   return PIPE_OK;
}


/**
 * Get (or create/upload) the winsys surface handle so that we can
 * refer to this buffer in fifo commands.
 * This function will create the host surface, and in the GB case also the
 * hardware storage. In the non-GB case, the hardware storage will be created
 * if there are mapped ranges and the data is currently in a malloc'ed buffer.
 */
struct svga_winsys_surface *
svga_buffer_handle(struct svga_context *svga, struct pipe_resource *buf)
{
   struct pipe_screen *screen = svga->pipe.screen;
   struct svga_screen *ss = svga_screen(screen);
   struct svga_buffer *sbuf;
   enum pipe_error ret;

   if (!buf)
      return NULL;

   sbuf = svga_buffer(buf);

   assert(!sbuf->user);

   if (!sbuf->handle) {
      /* This call will set sbuf->handle */
      if (svga_have_gb_objects(svga)) {
	 ret = svga_buffer_update_hw(svga, sbuf);
      } else {
	 ret = svga_buffer_create_host_surface(ss, sbuf);
      }
      if (ret != PIPE_OK)
	 return NULL;
   }

   assert(sbuf->handle);

   if (sbuf->map.num_ranges) {
      if (!sbuf->dma.pending) {
         /* No pending DMA/update commands yet. */

         /* Migrate the data from swbuf -> hwbuf if necessary */
         ret = svga_buffer_update_hw(svga, sbuf);
         if (ret == PIPE_OK) {
            /* Emit DMA or UpdateGBImage commands */
            ret = svga_buffer_upload_command(svga, sbuf);
            if (ret == PIPE_ERROR_OUT_OF_MEMORY) {
               svga_context_flush(svga, NULL);
               ret = svga_buffer_upload_command(svga, sbuf);
               assert(ret == PIPE_OK);
            }
            if (ret == PIPE_OK) {
               sbuf->dma.pending = TRUE;
               assert(!sbuf->head.prev && !sbuf->head.next);
               LIST_ADDTAIL(&sbuf->head, &svga->dirty_buffers);
            }
         }
         else if (ret == PIPE_ERROR_OUT_OF_MEMORY) {
            /*
             * The buffer is too big to fit in the GMR aperture, so break it in
             * smaller pieces.
             */
            ret = svga_buffer_upload_piecewise(ss, svga, sbuf);
         }

         if (ret != PIPE_OK) {
            /*
             * Something unexpected happened above. There is very little that
             * we can do other than proceeding while ignoring the dirty ranges.
             */
            assert(0);
            sbuf->map.num_ranges = 0;
         }
      }
      else {
         /*
          * There a pending dma already. Make sure it is from this context.
          */
         assert(sbuf->dma.svga == svga);
      }
   }

   assert(sbuf->map.num_ranges == 0 || sbuf->dma.pending);

   return sbuf->handle;
}



void
svga_context_flush_buffers(struct svga_context *svga)
{
   struct list_head *curr, *next;

   SVGA_STATS_TIME_PUSH(svga_sws(svga), SVGA_STATS_TIME_BUFFERSFLUSH);

   curr = svga->dirty_buffers.next;
   next = curr->next;
   while (curr != &svga->dirty_buffers) {
      struct svga_buffer *sbuf = LIST_ENTRY(struct svga_buffer, curr, head);

      assert(p_atomic_read(&sbuf->b.b.reference.count) != 0);
      assert(sbuf->dma.pending);

      svga_buffer_upload_flush(svga, sbuf);

      curr = next;
      next = curr->next;
   }

   SVGA_STATS_TIME_POP(svga_sws(svga));
}