OSDN Git Service

[intel-gem] Only update obj->write_domain if we're actually changing it.
[android-x86/external-libdrm.git] / linux-core / i915_gem.c
1 /*
2  * Copyright © 2008 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  *
23  * Authors:
24  *    Eric Anholt <eric@anholt.net>
25  *
26  */
27
28 #include "drmP.h"
29 #include "drm.h"
30 #include "i915_drm.h"
31 #include "i915_drv.h"
32
33 #define WATCH_COHERENCY 0
34 #define WATCH_BUF       0
35 #define WATCH_EXEC      0
36 #define WATCH_LRU       0
37 #define WATCH_RELOC     0
38
39 static void
40 i915_gem_object_set_domain(struct drm_gem_object *obj,
41                             uint32_t read_domains,
42                             uint32_t write_domain);
43
44 int
45 i915_gem_init_ioctl(struct drm_device *dev, void *data,
46                     struct drm_file *file_priv)
47 {
48         drm_i915_private_t *dev_priv = dev->dev_private;
49         struct drm_i915_gem_init *args = data;
50
51         mutex_lock(&dev->struct_mutex);
52
53         if (args->gtt_start >= args->gtt_end ||
54             (args->gtt_start & (PAGE_SIZE - 1)) != 0 ||
55             (args->gtt_end & (PAGE_SIZE - 1)) != 0) {
56                 mutex_unlock(&dev->struct_mutex);
57                 return -EINVAL;
58         }
59
60         drm_memrange_init(&dev_priv->mm.gtt_space, args->gtt_start,
61             args->gtt_end - args->gtt_start);
62
63         mutex_unlock(&dev->struct_mutex);
64
65         return 0;
66 }
67
68 static void
69 i915_gem_object_free_page_list(struct drm_gem_object *obj)
70 {
71         struct drm_i915_gem_object *obj_priv = obj->driver_private;
72         int page_count = obj->size / PAGE_SIZE;
73         int i;
74
75         if (obj_priv->page_list == NULL)
76                 return;
77
78
79         for (i = 0; i < page_count; i++)
80                 if (obj_priv->page_list[i] != NULL)
81                         page_cache_release(obj_priv->page_list[i]);
82
83         drm_free(obj_priv->page_list,
84                  page_count * sizeof(struct page *),
85                  DRM_MEM_DRIVER);
86         obj_priv->page_list = NULL;
87 }
88
89 static void
90 i915_gem_object_move_to_active(struct drm_gem_object *obj)
91 {
92         struct drm_device *dev = obj->dev;
93         drm_i915_private_t *dev_priv = dev->dev_private;
94         struct drm_i915_gem_object *obj_priv = obj->driver_private;
95
96         /* Add a reference if we're newly entering the active list. */
97         if (!obj_priv->active) {
98                 drm_gem_object_reference(obj);
99                 obj_priv->active = 1;
100         }
101         /* Move from whatever list we were on to the tail of execution. */
102         list_move_tail(&obj_priv->list,
103                        &dev_priv->mm.active_list);
104 }
105
106 static void
107 i915_gem_object_move_to_inactive(struct drm_gem_object *obj)
108 {
109         struct drm_device *dev = obj->dev;
110         drm_i915_private_t *dev_priv = dev->dev_private;
111         struct drm_i915_gem_object *obj_priv = obj->driver_private;
112
113         if (obj_priv->pin_count != 0)
114                 list_del_init(&obj_priv->list);
115         else
116                 list_move_tail(&obj_priv->list, &dev_priv->mm.inactive_list);
117
118         if (obj_priv->active) {
119                 obj_priv->active = 0;
120                 drm_gem_object_unreference(obj);
121         }
122 }
123
124 /**
125  * Creates a new sequence number, emitting a write of it to the status page
126  * plus an interrupt, which will trigger i915_user_interrupt_handler.
127  *
128  * Must be called with struct_lock held.
129  *
130  * Returned sequence numbers are nonzero on success.
131  */
132 static uint32_t
133 i915_add_request(struct drm_device *dev, uint32_t flush_domains)
134 {
135         drm_i915_private_t *dev_priv = dev->dev_private;
136         struct drm_i915_gem_request *request;
137         uint32_t seqno;
138         RING_LOCALS;
139
140         request = drm_calloc(1, sizeof(*request), DRM_MEM_DRIVER);
141         if (request == NULL)
142                 return 0;
143
144         /* Grab the seqno we're going to make this request be, and bump the
145          * next (skipping 0 so it can be the reserved no-seqno value).
146          */
147         seqno = dev_priv->mm.next_gem_seqno;
148         dev_priv->mm.next_gem_seqno++;
149         if (dev_priv->mm.next_gem_seqno == 0)
150                 dev_priv->mm.next_gem_seqno++;
151
152         BEGIN_LP_RING(4);
153         OUT_RING(CMD_STORE_DWORD_IDX);
154         OUT_RING(I915_GEM_HWS_INDEX << STORE_DWORD_INDEX_SHIFT);
155         OUT_RING(seqno);
156
157         OUT_RING(GFX_OP_USER_INTERRUPT);
158         ADVANCE_LP_RING();
159
160         DRM_DEBUG("%d\n", seqno);
161
162         request->seqno = seqno;
163         request->emitted_jiffies = jiffies;
164         request->flush_domains = flush_domains;
165         list_add_tail(&request->list, &dev_priv->mm.request_list);
166
167         return seqno;
168 }
169
170 /**
171  * Command execution barrier
172  *
173  * Ensures that all commands in the ring are finished
174  * before signalling the CPU
175  */
176
177 uint32_t
178 i915_retire_commands(struct drm_device *dev)
179 {
180         drm_i915_private_t *dev_priv = dev->dev_private;
181         uint32_t cmd = CMD_MI_FLUSH | MI_NO_WRITE_FLUSH;
182         uint32_t flush_domains = 0;
183         RING_LOCALS;
184
185         /* The sampler always gets flushed on i965 (sigh) */
186         if (IS_I965G(dev))
187                 flush_domains |= DRM_GEM_DOMAIN_I915_SAMPLER;
188         BEGIN_LP_RING(2);
189         OUT_RING(cmd);
190         OUT_RING(0); /* noop */
191         ADVANCE_LP_RING();
192         return flush_domains;
193 }
194
195 /**
196  * Moves buffers associated only with the given active seqno from the active
197  * to inactive list, potentially freeing them.
198  */
199 static void
200 i915_gem_retire_request(struct drm_device *dev,
201                         struct drm_i915_gem_request *request)
202 {
203         drm_i915_private_t *dev_priv = dev->dev_private;
204
205         if (request->flush_domains != 0) {
206                 struct drm_i915_gem_object *obj_priv, *next;
207
208                 /* First clear any buffers that were only waiting for a flush
209                  * matching the one just retired.
210                  */
211
212                 list_for_each_entry_safe(obj_priv, next,
213                                          &dev_priv->mm.flushing_list, list) {
214                         struct drm_gem_object *obj = obj_priv->obj;
215
216                         if (obj->write_domain & request->flush_domains) {
217                                 obj->write_domain = 0;
218                                 i915_gem_object_move_to_inactive(obj);
219                         }
220                 }
221
222         }
223
224         /* Move any buffers on the active list that are no longer referenced
225          * by the ringbuffer to the flushing/inactive lists as appropriate.
226          */
227         while (!list_empty(&dev_priv->mm.active_list)) {
228                 struct drm_gem_object *obj;
229                 struct drm_i915_gem_object *obj_priv;
230
231                 obj_priv = list_first_entry(&dev_priv->mm.active_list,
232                                             struct drm_i915_gem_object,
233                                             list);
234                 obj = obj_priv->obj;
235
236                 /* If the seqno being retired doesn't match the oldest in the
237                  * list, then the oldest in the list must still be newer than
238                  * this seqno.
239                  */
240                 if (obj_priv->last_rendering_seqno != request->seqno)
241                         return;
242 #if WATCH_LRU
243                 DRM_INFO("%s: retire %d moves to inactive list %p\n",
244                          __func__, request->seqno, obj);
245 #endif
246
247                 if (obj->write_domain != 0) {
248                         list_move_tail(&obj_priv->list,
249                                        &dev_priv->mm.flushing_list);
250                 } else {
251                         i915_gem_object_move_to_inactive(obj);
252                 }
253         }
254 }
255
256 /**
257  * Returns true if seq1 is later than seq2.
258  */
259 static int
260 i915_seqno_passed(uint32_t seq1, uint32_t seq2)
261 {
262         return (int32_t)(seq1 - seq2) >= 0;
263 }
264
265 static uint32_t
266 i915_get_gem_seqno(struct drm_device *dev)
267 {
268         drm_i915_private_t *dev_priv = dev->dev_private;
269
270         return READ_HWSP(dev_priv, I915_GEM_HWS_INDEX);
271 }
272
273 /**
274  * This function clears the request list as sequence numbers are passed.
275  */
276 void
277 i915_gem_retire_requests(struct drm_device *dev)
278 {
279         drm_i915_private_t *dev_priv = dev->dev_private;
280         uint32_t seqno;
281
282         seqno = i915_get_gem_seqno(dev);
283
284         while (!list_empty(&dev_priv->mm.request_list)) {
285                 struct drm_i915_gem_request *request;
286                 uint32_t retiring_seqno;
287
288                 request = list_first_entry(&dev_priv->mm.request_list,
289                                            struct drm_i915_gem_request,
290                                            list);
291                 retiring_seqno = request->seqno;
292
293                 if (i915_seqno_passed(seqno, retiring_seqno)) {
294                         i915_gem_retire_request(dev, request);
295
296                         list_del(&request->list);
297                         drm_free(request, sizeof(*request), DRM_MEM_DRIVER);
298                 } else
299                     break;
300         }
301 }
302
303 /**
304  * Waits for a sequence number to be signaled, and cleans up the
305  * request and object lists appropriately for that event.
306  */
307 int
308 i915_wait_request(struct drm_device *dev, uint32_t seqno)
309 {
310         drm_i915_private_t *dev_priv = dev->dev_private;
311         int ret = 0;
312
313         BUG_ON(seqno == 0);
314
315         if (!i915_seqno_passed(i915_get_gem_seqno(dev), seqno)) {
316                 i915_user_irq_on(dev_priv);
317                 ret = wait_event_interruptible(dev_priv->irq_queue,
318                                                i915_seqno_passed(i915_get_gem_seqno(dev),
319                                                                  seqno));
320                 i915_user_irq_off(dev_priv);
321         }
322
323         /* Directly dispatch request retiring.  While we have the work queue
324          * to handle this, the waiter on a request often wants an associated
325          * buffer to have made it to the inactive list, and we would need
326          * a separate wait queue to handle that.
327          */
328         if (ret == 0)
329                 i915_gem_retire_requests(dev);
330
331         return ret;
332 }
333
334 static void
335 i915_gem_flush(struct drm_device *dev,
336                uint32_t invalidate_domains,
337                uint32_t flush_domains)
338 {
339         drm_i915_private_t *dev_priv = dev->dev_private;
340         uint32_t cmd;
341         RING_LOCALS;
342
343 #if WATCH_EXEC
344         DRM_INFO("%s: invalidate %08x flush %08x\n", __func__,
345                   invalidate_domains, flush_domains);
346 #endif
347
348         if (flush_domains & DRM_GEM_DOMAIN_CPU)
349                 drm_agp_chipset_flush(dev);
350
351         if ((invalidate_domains|flush_domains) & ~DRM_GEM_DOMAIN_CPU) {
352                 /*
353                  * read/write caches:
354                  *
355                  * DRM_GEM_DOMAIN_I915_RENDER is always invalidated, but is
356                  * only flushed if MI_NO_WRITE_FLUSH is unset.  On 965, it is
357                  * also flushed at 2d versus 3d pipeline switches.
358                  *
359                  * read-only caches:
360                  *
361                  * DRM_GEM_DOMAIN_I915_SAMPLER is flushed on pre-965 if
362                  * MI_READ_FLUSH is set, and is always flushed on 965.
363                  *
364                  * DRM_GEM_DOMAIN_I915_COMMAND may not exist?
365                  *
366                  * DRM_GEM_DOMAIN_I915_INSTRUCTION, which exists on 965, is
367                  * invalidated when MI_EXE_FLUSH is set.
368                  *
369                  * DRM_GEM_DOMAIN_I915_VERTEX, which exists on 965, is
370                  * invalidated with every MI_FLUSH.
371                  *
372                  * TLBs:
373                  *
374                  * On 965, TLBs associated with DRM_GEM_DOMAIN_I915_COMMAND
375                  * and DRM_GEM_DOMAIN_CPU in are invalidated at PTE write and
376                  * DRM_GEM_DOMAIN_I915_RENDER and DRM_GEM_DOMAIN_I915_SAMPLER
377                  * are flushed at any MI_FLUSH.
378                  */
379
380                 cmd = CMD_MI_FLUSH | MI_NO_WRITE_FLUSH;
381                 if ((invalidate_domains|flush_domains) &
382                     DRM_GEM_DOMAIN_I915_RENDER)
383                         cmd &= ~MI_NO_WRITE_FLUSH;
384                 if (!IS_I965G(dev)) {
385                         /*
386                          * On the 965, the sampler cache always gets flushed
387                          * and this bit is reserved.
388                          */
389                         if (invalidate_domains & DRM_GEM_DOMAIN_I915_SAMPLER)
390                                 cmd |= MI_READ_FLUSH;
391                 }
392                 if (invalidate_domains & DRM_GEM_DOMAIN_I915_INSTRUCTION)
393                         cmd |= MI_EXE_FLUSH;
394
395 #if WATCH_EXEC
396                 DRM_INFO("%s: queue flush %08x to ring\n", __func__, cmd);
397 #endif
398                 BEGIN_LP_RING(2);
399                 OUT_RING(cmd);
400                 OUT_RING(0); /* noop */
401                 ADVANCE_LP_RING();
402         }
403 }
404
405 /**
406  * Ensures that all rendering to the object has completed and the object is
407  * safe to unbind from the GTT or access from the CPU.
408  */
409 static int
410 i915_gem_object_wait_rendering(struct drm_gem_object *obj)
411 {
412         struct drm_device *dev = obj->dev;
413         struct drm_i915_gem_object *obj_priv = obj->driver_private;
414         int ret;
415
416         /* If there are writes queued to the buffer, flush and
417          * create a new seqno to wait for.
418          */
419         if (obj->write_domain & ~(DRM_GEM_DOMAIN_CPU)) {
420                 uint32_t write_domain = obj->write_domain;
421 #if WATCH_BUF
422                 DRM_INFO("%s: flushing object %p from write domain %08x\n",
423                           __func__, obj, write_domain);
424 #endif
425                 i915_gem_flush(dev, 0, write_domain);
426                 obj->write_domain = 0;
427
428                 i915_gem_object_move_to_active(obj);
429                 obj_priv->last_rendering_seqno = i915_add_request(dev,
430                                                                   write_domain);
431                 BUG_ON(obj_priv->last_rendering_seqno == 0);
432 #if WATCH_LRU
433                 DRM_INFO("%s: flush moves to exec list %p\n", __func__, obj);
434 #endif
435         }
436         /* If there is rendering queued on the buffer being evicted, wait for
437          * it.
438          */
439         if (obj_priv->active) {
440 #if WATCH_BUF
441                 DRM_INFO("%s: object %p wait for seqno %08x\n",
442                           __func__, obj, obj_priv->last_rendering_seqno);
443 #endif
444                 ret = i915_wait_request(dev, obj_priv->last_rendering_seqno);
445                 if (ret != 0)
446                         return ret;
447         }
448
449         return 0;
450 }
451
452 /**
453  * Unbinds an object from the GTT aperture.
454  */
455 static void
456 i915_gem_object_unbind(struct drm_gem_object *obj)
457 {
458         struct drm_i915_gem_object *obj_priv = obj->driver_private;
459
460 #if WATCH_BUF
461         DRM_INFO("%s:%d %p\n", __func__, __LINE__, obj);
462         DRM_INFO("gtt_space %p\n", obj_priv->gtt_space);
463 #endif
464         if (obj_priv->gtt_space == NULL)
465                 return;
466
467         /* Move the object to the CPU domain to ensure that
468          * any possible CPU writes while it's not in the GTT
469          * are flushed when we go to remap it. This will
470          * also ensure that all pending GPU writes are finished
471          * before we unbind.
472          */
473         i915_gem_object_set_domain (obj, DRM_GEM_DOMAIN_CPU,
474                                     DRM_GEM_DOMAIN_CPU);
475
476         if (obj_priv->agp_mem != NULL) {
477                 drm_unbind_agp(obj_priv->agp_mem);
478                 drm_free_agp(obj_priv->agp_mem, obj->size / PAGE_SIZE);
479                 obj_priv->agp_mem = NULL;
480         }
481
482         i915_gem_object_free_page_list(obj);
483
484         drm_memrange_put_block(obj_priv->gtt_space);
485         obj_priv->gtt_space = NULL;
486
487         /* Remove ourselves from the LRU list if present. */
488         if (!list_empty(&obj_priv->list)) {
489                 list_del_init(&obj_priv->list);
490                 if (obj_priv->active) {
491                         DRM_ERROR("Failed to wait on buffer when unbinding, "
492                                   "continued anyway.\n");
493                         obj_priv->active = 0;
494                         drm_gem_object_unreference(obj);
495                 }
496         }
497 }
498
499 #if WATCH_BUF | WATCH_EXEC
500 static void
501 i915_gem_dump_page(struct page *page, uint32_t start, uint32_t end,
502                    uint32_t bias, uint32_t mark)
503 {
504         uint32_t *mem = kmap_atomic(page, KM_USER0);
505         int i;
506         for (i = start; i < end; i += 4)
507                 DRM_INFO("%08x: %08x%s\n",
508                           (int) (bias + i), mem[i / 4],
509                           (bias + i == mark) ? " ********" : "");
510         kunmap_atomic(mem, KM_USER0);
511         /* give syslog time to catch up */
512         msleep(1);
513 }
514
515 static void
516 i915_gem_dump_object(struct drm_gem_object *obj, int len,
517                      const char *where, uint32_t mark)
518 {
519         struct drm_i915_gem_object *obj_priv = obj->driver_private;
520         int page;
521
522         DRM_INFO("%s: object at offset %08x\n", where, obj_priv->gtt_offset);
523         for (page = 0; page < (len + PAGE_SIZE-1) / PAGE_SIZE; page++) {
524                 int page_len, chunk, chunk_len;
525
526                 page_len = len - page * PAGE_SIZE;
527                 if (page_len > PAGE_SIZE)
528                         page_len = PAGE_SIZE;
529
530                 for (chunk = 0; chunk < page_len; chunk += 128) {
531                         chunk_len = page_len - chunk;
532                         if (chunk_len > 128)
533                                 chunk_len = 128;
534                         i915_gem_dump_page(obj_priv->page_list[page],
535                                            chunk, chunk + chunk_len,
536                                            obj_priv->gtt_offset +
537                                            page * PAGE_SIZE,
538                                            mark);
539                 }
540         }
541 }
542 #endif
543
544 #if WATCH_LRU
545 static void
546 i915_dump_lru(struct drm_device *dev, const char *where)
547 {
548         drm_i915_private_t              *dev_priv = dev->dev_private;
549         struct drm_i915_gem_object      *obj_priv;
550
551         DRM_INFO("active list %s {\n", where);
552         list_for_each_entry(obj_priv, &dev_priv->mm.active_list,
553                             list)
554         {
555                 DRM_INFO("    %p: %08x\n", obj_priv,
556                          obj_priv->last_rendering_seqno);
557         }
558         DRM_INFO("}\n");
559         DRM_INFO("flushing list %s {\n", where);
560         list_for_each_entry(obj_priv, &dev_priv->mm.flushing_list,
561                             list)
562         {
563                 DRM_INFO("    %p: %08x\n", obj_priv,
564                          obj_priv->last_rendering_seqno);
565         }
566         DRM_INFO("}\n");
567         DRM_INFO("inactive %s {\n", where);
568         list_for_each_entry(obj_priv, &dev_priv->mm.inactive_list, list) {
569                 DRM_INFO("    %p: %08x\n", obj_priv,
570                          obj_priv->last_rendering_seqno);
571         }
572         DRM_INFO("}\n");
573 }
574 #endif
575
576 static int
577 i915_gem_evict_something(struct drm_device *dev)
578 {
579         drm_i915_private_t *dev_priv = dev->dev_private;
580         struct drm_gem_object *obj;
581         struct drm_i915_gem_object *obj_priv;
582
583         for (;;) {
584                 /* If there's an inactive buffer available now, grab it
585                  * and be done.
586                  */
587                 if (!list_empty(&dev_priv->mm.inactive_list)) {
588                         obj_priv = list_first_entry(&dev_priv->mm.inactive_list,
589                                                     struct drm_i915_gem_object,
590                                                     list);
591                         obj = obj_priv->obj;
592                         BUG_ON(obj_priv->pin_count != 0);
593                         break;
594                 }
595
596                 /* If we didn't get anything, but the ring is still processing
597                  * things, wait for one of those things to finish and hopefully
598                  * leave us a buffer to evict.
599                  */
600                 if (!list_empty(&dev_priv->mm.request_list)) {
601                         struct drm_i915_gem_request *request;
602                         int ret;
603
604                         request = list_first_entry(&dev_priv->mm.request_list,
605                                                    struct drm_i915_gem_request,
606                                                    list);
607
608                         ret = i915_wait_request(dev, request->seqno);
609                         if (ret != 0)
610                                 return ret;
611
612                         continue;
613                 }
614
615                 /* If we didn't have anything on the request list but there
616                  * are buffers awaiting a flush, emit one and try again.
617                  * When we wait on it, those buffers waiting for that flush
618                  * will get moved to inactive.
619                  */
620                 if (!list_empty(&dev_priv->mm.flushing_list)) {
621                         obj_priv = list_first_entry(&dev_priv->mm.flushing_list,
622                                                     struct drm_i915_gem_object,
623                                                     list);
624                         obj = obj_priv->obj;
625
626                         i915_gem_flush(dev,
627                                        obj->write_domain,
628                                        obj->write_domain);
629                         i915_add_request(dev, obj->write_domain);
630
631                         obj = NULL;
632                         continue;
633                 }
634
635                 /* If we didn't do any of the above, there's nothing to be done
636                  * and we just can't fit it in.
637                  */
638                 return -ENOMEM;
639         }
640
641 #if WATCH_LRU
642         DRM_INFO("%s: evicting %p\n", __func__, obj);
643 #endif
644
645         BUG_ON(obj_priv->active);
646
647         /* Wait on the rendering and unbind the buffer. */
648         i915_gem_object_unbind(obj);
649
650         return 0;
651 }
652
653 static int
654 i915_gem_object_get_page_list(struct drm_gem_object *obj)
655 {
656         struct drm_i915_gem_object *obj_priv = obj->driver_private;
657         int page_count, i;
658         if (obj_priv->page_list)
659                 return 0;
660
661         /* Get the list of pages out of our struct file.  They'll be pinned
662          * at this point until we release them.
663          */
664         page_count = obj->size / PAGE_SIZE;
665         BUG_ON(obj_priv->page_list != NULL);
666         obj_priv->page_list = drm_calloc(page_count, sizeof(struct page *),
667                                          DRM_MEM_DRIVER);
668         if (obj_priv->page_list == NULL)
669                 return -ENOMEM;
670
671         for (i = 0; i < page_count; i++) {
672                 obj_priv->page_list[i] =
673                     find_or_create_page(obj->filp->f_mapping, i, GFP_HIGHUSER);
674
675                 if (obj_priv->page_list[i] == NULL) {
676                         i915_gem_object_free_page_list(obj);
677                         return -ENOMEM;
678                 }
679                 unlock_page(obj_priv->page_list[i]);
680         }
681         return 0;
682 }
683
684 /**
685  * Finds free space in the GTT aperture and binds the object there.
686  */
687 static int
688 i915_gem_object_bind_to_gtt(struct drm_gem_object *obj, unsigned alignment)
689 {
690         struct drm_device *dev = obj->dev;
691         drm_i915_private_t *dev_priv = dev->dev_private;
692         struct drm_i915_gem_object *obj_priv = obj->driver_private;
693         struct drm_memrange_node *free_space;
694         int page_count, ret;
695
696         if (alignment == 0)
697                 alignment = PAGE_SIZE;
698         if (alignment & (PAGE_SIZE - 1)) {
699                 DRM_ERROR("Invalid object alignment requested %u\n", alignment);
700                 return -EINVAL;
701         }
702
703  search_free:
704         free_space = drm_memrange_search_free(&dev_priv->mm.gtt_space,
705                                               obj->size,
706                                               alignment, 0);
707         if (free_space != NULL) {
708                 obj_priv->gtt_space =
709                         drm_memrange_get_block(free_space, obj->size,
710                                                alignment);
711                 if (obj_priv->gtt_space != NULL) {
712                         obj_priv->gtt_space->private = obj;
713                         obj_priv->gtt_offset = obj_priv->gtt_space->start;
714                 }
715         }
716         if (obj_priv->gtt_space == NULL) {
717                 /* If the gtt is empty and we're still having trouble
718                  * fitting our object in, we're out of memory.
719                  */
720 #if WATCH_LRU
721                 DRM_INFO("%s: GTT full, evicting something\n", __func__);
722 #endif
723                 if (list_empty(&dev_priv->mm.inactive_list) &&
724                     list_empty(&dev_priv->mm.active_list)) {
725                         DRM_ERROR("GTT full, but LRU list empty\n");
726                         return -ENOMEM;
727                 }
728
729                 ret = i915_gem_evict_something(dev);
730                 if (ret != 0)
731                         return ret;
732                 goto search_free;
733         }
734
735 #if WATCH_BUF
736         DRM_INFO("Binding object of size %d at 0x%08x\n",
737                  obj->size, obj_priv->gtt_offset);
738 #endif
739         ret = i915_gem_object_get_page_list(obj);
740         if (ret) {
741                 drm_memrange_put_block(obj_priv->gtt_space);
742                 obj_priv->gtt_space = NULL;
743                 return ret;
744         }
745
746         page_count = obj->size / PAGE_SIZE;
747         /* Create an AGP memory structure pointing at our pages, and bind it
748          * into the GTT.
749          */
750         obj_priv->agp_mem = drm_agp_bind_pages(dev,
751                                                obj_priv->page_list,
752                                                page_count,
753                                                obj_priv->gtt_offset);
754         if (obj_priv->agp_mem == NULL) {
755                 i915_gem_object_free_page_list(obj);
756                 drm_memrange_put_block(obj_priv->gtt_space);
757                 obj_priv->gtt_space = NULL;
758                 return -ENOMEM;
759         }
760
761         /* Assert that the object is not currently in any GPU domain. As it
762          * wasn't in the GTT, there shouldn't be any way it could have been in
763          * a GPU cache
764          */
765         BUG_ON(obj->read_domains & ~DRM_GEM_DOMAIN_CPU);
766         BUG_ON(obj->write_domain & ~DRM_GEM_DOMAIN_CPU);
767
768         return 0;
769 }
770
771 static void
772 i915_gem_clflush_object(struct drm_gem_object *obj)
773 {
774         struct drm_i915_gem_object      *obj_priv = obj->driver_private;
775
776         /* If we don't have a page list set up, then we're not pinned
777          * to GPU, and we can ignore the cache flush because it'll happen
778          * again at bind time.
779          */
780         if (obj_priv->page_list == NULL)
781                 return;
782
783         drm_ttm_cache_flush(obj_priv->page_list, obj->size / PAGE_SIZE);
784 }
785
786 /*
787  * Set the next domain for the specified object. This
788  * may not actually perform the necessary flushing/invaliding though,
789  * as that may want to be batched with other set_domain operations
790  *
791  * This is (we hope) the only really tricky part of gem. The goal
792  * is fairly simple -- track which caches hold bits of the object
793  * and make sure they remain coherent. A few concrete examples may
794  * help to explain how it works. For shorthand, we use the notation
795  * (read_domains, write_domain), e.g. (CPU, CPU) to indicate the
796  * a pair of read and write domain masks.
797  *
798  * Case 1: the batch buffer
799  *
800  *      1. Allocated
801  *      2. Written by CPU
802  *      3. Mapped to GTT
803  *      4. Read by GPU
804  *      5. Unmapped from GTT
805  *      6. Freed
806  *
807  *      Let's take these a step at a time
808  *
809  *      1. Allocated
810  *              Pages allocated from the kernel may still have
811  *              cache contents, so we set them to (CPU, CPU) always.
812  *      2. Written by CPU (using pwrite)
813  *              The pwrite function calls set_domain (CPU, CPU) and
814  *              this function does nothing (as nothing changes)
815  *      3. Mapped by GTT
816  *              This function asserts that the object is not
817  *              currently in any GPU-based read or write domains
818  *      4. Read by GPU
819  *              i915_gem_execbuffer calls set_domain (COMMAND, 0).
820  *              As write_domain is zero, this function adds in the
821  *              current read domains (CPU+COMMAND, 0).
822  *              flush_domains is set to CPU.
823  *              invalidate_domains is set to COMMAND
824  *              clflush is run to get data out of the CPU caches
825  *              then i915_dev_set_domain calls i915_gem_flush to
826  *              emit an MI_FLUSH and drm_agp_chipset_flush
827  *      5. Unmapped from GTT
828  *              i915_gem_object_unbind calls set_domain (CPU, CPU)
829  *              flush_domains and invalidate_domains end up both zero
830  *              so no flushing/invalidating happens
831  *      6. Freed
832  *              yay, done
833  *
834  * Case 2: The shared render buffer
835  *
836  *      1. Allocated
837  *      2. Mapped to GTT
838  *      3. Read/written by GPU
839  *      4. set_domain to (CPU,CPU)
840  *      5. Read/written by CPU
841  *      6. Read/written by GPU
842  *
843  *      1. Allocated
844  *              Same as last example, (CPU, CPU)
845  *      2. Mapped to GTT
846  *              Nothing changes (assertions find that it is not in the GPU)
847  *      3. Read/written by GPU
848  *              execbuffer calls set_domain (RENDER, RENDER)
849  *              flush_domains gets CPU
850  *              invalidate_domains gets GPU
851  *              clflush (obj)
852  *              MI_FLUSH and drm_agp_chipset_flush
853  *      4. set_domain (CPU, CPU)
854  *              flush_domains gets GPU
855  *              invalidate_domains gets CPU
856  *              wait_rendering (obj) to make sure all drawing is complete.
857  *              This will include an MI_FLUSH to get the data from GPU
858  *              to memory
859  *              clflush (obj) to invalidate the CPU cache
860  *              Another MI_FLUSH in i915_gem_flush (eliminate this somehow?)
861  *      5. Read/written by CPU
862  *              cache lines are loaded and dirtied
863  *      6. Read written by GPU
864  *              Same as last GPU access
865  *
866  * Case 3: The constant buffer
867  *
868  *      1. Allocated
869  *      2. Written by CPU
870  *      3. Read by GPU
871  *      4. Updated (written) by CPU again
872  *      5. Read by GPU
873  *
874  *      1. Allocated
875  *              (CPU, CPU)
876  *      2. Written by CPU
877  *              (CPU, CPU)
878  *      3. Read by GPU
879  *              (CPU+RENDER, 0)
880  *              flush_domains = CPU
881  *              invalidate_domains = RENDER
882  *              clflush (obj)
883  *              MI_FLUSH
884  *              drm_agp_chipset_flush
885  *      4. Updated (written) by CPU again
886  *              (CPU, CPU)
887  *              flush_domains = 0 (no previous write domain)
888  *              invalidate_domains = 0 (no new read domains)
889  *      5. Read by GPU
890  *              (CPU+RENDER, 0)
891  *              flush_domains = CPU
892  *              invalidate_domains = RENDER
893  *              clflush (obj)
894  *              MI_FLUSH
895  *              drm_agp_chipset_flush
896  */
897 static void
898 i915_gem_object_set_domain(struct drm_gem_object *obj,
899                             uint32_t read_domains,
900                             uint32_t write_domain)
901 {
902         struct drm_device               *dev = obj->dev;
903         uint32_t                        invalidate_domains = 0;
904         uint32_t                        flush_domains = 0;
905
906 #if WATCH_BUF
907         DRM_INFO("%s: object %p read %08x write %08x\n",
908                  __func__, obj, read_domains, write_domain);
909 #endif
910         /*
911          * If the object isn't moving to a new write domain,
912          * let the object stay in multiple read domains
913          */
914         if (write_domain == 0)
915                 read_domains |= obj->read_domains;
916
917         /*
918          * Flush the current write domain if
919          * the new read domains don't match. Invalidate
920          * any read domains which differ from the old
921          * write domain
922          */
923         if (obj->write_domain && obj->write_domain != read_domains) {
924                 flush_domains |= obj->write_domain;
925                 invalidate_domains |= read_domains & ~obj->write_domain;
926         }
927         /*
928          * Invalidate any read caches which may have
929          * stale data. That is, any new read domains.
930          */
931         invalidate_domains |= read_domains & ~obj->read_domains;
932         if ((flush_domains | invalidate_domains) & DRM_GEM_DOMAIN_CPU) {
933 #if WATCH_BUF
934                 DRM_INFO("%s: CPU domain flush %08x invalidate %08x\n",
935                          __func__, flush_domains, invalidate_domains);
936 #endif
937                 /*
938                  * If we're invaliding the CPU cache and flushing a GPU cache,
939                  * then pause for rendering so that the GPU caches will be
940                  * flushed before the cpu cache is invalidated
941                  */
942                 if ((invalidate_domains & DRM_GEM_DOMAIN_CPU) &&
943                     (flush_domains & ~DRM_GEM_DOMAIN_CPU))
944                         i915_gem_object_wait_rendering(obj);
945                 i915_gem_clflush_object(obj);
946         }
947
948         if ((write_domain | flush_domains) != 0)
949                 obj->write_domain = write_domain;
950         obj->read_domains = read_domains;
951         dev->invalidate_domains |= invalidate_domains;
952         dev->flush_domains |= flush_domains;
953 }
954
955 /**
956  * Once all of the objects have been set in the proper domain,
957  * perform the necessary flush and invalidate operations.
958  *
959  * Returns the write domains flushed, for use in flush tracking.
960  */
961 static uint32_t
962 i915_gem_dev_set_domain(struct drm_device *dev)
963 {
964         uint32_t flush_domains = dev->flush_domains;
965
966         /*
967          * Now that all the buffers are synced to the proper domains,
968          * flush and invalidate the collected domains
969          */
970         if (dev->invalidate_domains | dev->flush_domains) {
971 #if WATCH_EXEC
972                 DRM_INFO("%s: invalidate_domains %08x flush_domains %08x\n",
973                           __func__,
974                          dev->invalidate_domains,
975                          dev->flush_domains);
976 #endif
977                 i915_gem_flush(dev,
978                                dev->invalidate_domains,
979                                dev->flush_domains);
980                 dev->invalidate_domains = 0;
981                 dev->flush_domains = 0;
982         }
983
984         return flush_domains;
985 }
986
987 #if WATCH_COHERENCY
988 static void
989 i915_gem_object_check_coherency(struct drm_gem_object *obj, int handle)
990 {
991         struct drm_device *dev = obj->dev;
992         struct drm_i915_gem_object *obj_priv = obj->driver_private;
993         int page;
994         uint32_t *gtt_mapping;
995         uint32_t *backing_map = NULL;
996         int bad_count = 0;
997
998         DRM_INFO("%s: checking coherency of object %p@0x%08x (%d, %dkb):\n",
999                  __FUNCTION__, obj, obj_priv->gtt_offset, handle,
1000                  obj->size / 1024);
1001
1002         gtt_mapping = ioremap(dev->agp->base + obj_priv->gtt_offset,
1003                               obj->size);
1004         if (gtt_mapping == NULL) {
1005                 DRM_ERROR("failed to map GTT space\n");
1006                 return;
1007         }
1008
1009         for (page = 0; page < obj->size / PAGE_SIZE; page++) {
1010                 int i;
1011
1012                 backing_map = kmap_atomic(obj_priv->page_list[page], KM_USER0);
1013
1014                 if (backing_map == NULL) {
1015                         DRM_ERROR("failed to map backing page\n");
1016                         goto out;
1017                 }
1018
1019                 for (i = 0; i < PAGE_SIZE / 4; i++) {
1020                         uint32_t cpuval = backing_map[i];
1021                         uint32_t gttval = readl(gtt_mapping +
1022                                                 page * 1024 + i);
1023
1024                         if (cpuval != gttval) {
1025                                 DRM_INFO("incoherent CPU vs GPU at 0x%08x: "
1026                                          "0x%08x vs 0x%08x\n",
1027                                          (int)(obj_priv->gtt_offset +
1028                                                page * PAGE_SIZE + i * 4),
1029                                          cpuval, gttval);
1030                                 if (bad_count++ >= 8) {
1031                                         DRM_INFO("...\n");
1032                                         goto out;
1033                                 }
1034                         }
1035                 }
1036                 kunmap_atomic(backing_map, KM_USER0);
1037                 backing_map = NULL;
1038         }
1039
1040  out:
1041         if (backing_map != NULL)
1042                 kunmap_atomic(backing_map, KM_USER0);
1043         iounmap(gtt_mapping);
1044
1045         /* give syslog time to catch up */
1046         msleep(1);
1047
1048         /* Directly flush the object, since we just loaded values with the CPU
1049          * from thebacking pages and we don't want to disturb the cache
1050          * management that we're trying to observe.
1051          */
1052
1053         i915_gem_clflush_object(obj);
1054 }
1055 #endif
1056
1057 static int
1058 i915_gem_reloc_and_validate_object(struct drm_gem_object *obj,
1059                                    struct drm_file *file_priv,
1060                                    struct drm_i915_gem_exec_object *entry)
1061 {
1062         struct drm_device *dev = obj->dev;
1063         struct drm_i915_gem_relocation_entry reloc;
1064         struct drm_i915_gem_relocation_entry __user *relocs;
1065         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1066         int i;
1067         uint32_t last_reloc_offset = -1;
1068         void *reloc_page = NULL;
1069
1070         /* Choose the GTT offset for our buffer and put it there. */
1071         if (obj_priv->gtt_space == NULL) {
1072                 i915_gem_object_bind_to_gtt(obj, (unsigned) entry->alignment);
1073                 if (obj_priv->gtt_space == NULL)
1074                         return -ENOMEM;
1075         }
1076
1077         entry->offset = obj_priv->gtt_offset;
1078
1079         relocs = (struct drm_i915_gem_relocation_entry __user *)
1080                  (uintptr_t) entry->relocs_ptr;
1081         /* Apply the relocations, using the GTT aperture to avoid cache
1082          * flushing requirements.
1083          */
1084         for (i = 0; i < entry->relocation_count; i++) {
1085                 struct drm_gem_object *target_obj;
1086                 struct drm_i915_gem_object *target_obj_priv;
1087                 uint32_t reloc_val, reloc_offset, *reloc_entry;
1088                 int ret;
1089
1090                 ret = copy_from_user(&reloc, relocs + i, sizeof(reloc));
1091                 if (ret != 0)
1092                         return ret;
1093
1094                 target_obj = drm_gem_object_lookup(obj->dev, file_priv,
1095                                                    reloc.target_handle);
1096                 if (target_obj == NULL)
1097                         return -EINVAL;
1098                 target_obj_priv = target_obj->driver_private;
1099
1100                 /* The target buffer should have appeared before us in the
1101                  * validate list, so it should have a GTT space bound by now.
1102                  */
1103                 if (target_obj_priv->gtt_space == NULL) {
1104                         DRM_ERROR("No GTT space found for object %d\n",
1105                                   reloc.target_handle);
1106                         drm_gem_object_unreference(target_obj);
1107                         return -EINVAL;
1108                 }
1109
1110                 if (reloc.offset > obj->size - 4) {
1111                         DRM_ERROR("Relocation beyond object bounds: "
1112                                   "obj %p target %d offset %d size %d.\n",
1113                                   obj, reloc.target_handle,
1114                                   (int) reloc.offset, (int) obj->size);
1115                         drm_gem_object_unreference(target_obj);
1116                         return -EINVAL;
1117                 }
1118                 if (reloc.offset & 3) {
1119                         DRM_ERROR("Relocation not 4-byte aligned: "
1120                                   "obj %p target %d offset %d.\n",
1121                                   obj, reloc.target_handle,
1122                                   (int) reloc.offset);
1123                         drm_gem_object_unreference(target_obj);
1124                         return -EINVAL;
1125                 }
1126
1127                 if (reloc.write_domain && target_obj->pending_write_domain &&
1128                     reloc.write_domain != target_obj->pending_write_domain) {
1129                         DRM_ERROR("Write domain conflict: "
1130                                   "obj %p target %d offset %d "
1131                                   "new %08x old %08x\n",
1132                                   obj, reloc.target_handle,
1133                                   (int) reloc.offset,
1134                                   reloc.write_domain,
1135                                   target_obj->pending_write_domain);
1136                         drm_gem_object_unreference(target_obj);
1137                         return -EINVAL;
1138                 }
1139
1140 #if WATCH_RELOC
1141                 DRM_INFO("%s: obj %p offset %08x target %d "
1142                          "read %08x write %08x gtt %08x "
1143                          "presumed %08x delta %08x\n",
1144                          __func__,
1145                          obj,
1146                          (int) reloc.offset,
1147                          (int) reloc.target_handle,
1148                          (int) reloc.read_domains,
1149                          (int) reloc.write_domain,
1150                          (int) target_obj_priv->gtt_offset,
1151                          (int) reloc.presumed_offset,
1152                          reloc.delta);
1153 #endif
1154
1155                 target_obj->pending_read_domains |= reloc.read_domains;
1156                 target_obj->pending_write_domain |= reloc.write_domain;
1157
1158                 /* If the relocation already has the right value in it, no
1159                  * more work needs to be done.
1160                  */
1161                 if (target_obj_priv->gtt_offset == reloc.presumed_offset) {
1162                         drm_gem_object_unreference(target_obj);
1163                         continue;
1164                 }
1165
1166                 /* Now that we're going to actually write some data in,
1167                  * make sure that any rendering using this buffer's contents
1168                  * is completed.
1169                  */
1170                 i915_gem_object_wait_rendering(obj);
1171
1172                 /* As we're writing through the gtt, flush
1173                  * any CPU writes before we write the relocations
1174                  */
1175                 if (obj->write_domain & DRM_GEM_DOMAIN_CPU) {
1176                         i915_gem_clflush_object(obj);
1177                         drm_agp_chipset_flush(dev);
1178                         obj->write_domain = 0;
1179                 }
1180
1181                 /* Map the page containing the relocation we're going to
1182                  * perform.
1183                  */
1184                 reloc_offset = obj_priv->gtt_offset + reloc.offset;
1185                 if (reloc_page == NULL ||
1186                     (last_reloc_offset & ~(PAGE_SIZE - 1)) !=
1187                     (reloc_offset & ~(PAGE_SIZE - 1))) {
1188                         if (reloc_page != NULL)
1189                                 iounmap(reloc_page);
1190
1191                         reloc_page = ioremap(dev->agp->base +
1192                                              (reloc_offset & ~(PAGE_SIZE - 1)),
1193                                              PAGE_SIZE);
1194                         last_reloc_offset = reloc_offset;
1195                         if (reloc_page == NULL) {
1196                                 drm_gem_object_unreference(target_obj);
1197                                 return -ENOMEM;
1198                         }
1199                 }
1200
1201                 reloc_entry = (uint32_t *)((char *)reloc_page +
1202                                            (reloc_offset & (PAGE_SIZE - 1)));
1203                 reloc_val = target_obj_priv->gtt_offset + reloc.delta;
1204
1205 #if WATCH_BUF
1206                 DRM_INFO("Applied relocation: %p@0x%08x %08x -> %08x\n",
1207                           obj, (unsigned int) reloc.offset,
1208                           readl(reloc_entry), reloc_val);
1209 #endif
1210                 writel(reloc_val, reloc_entry);
1211
1212                 /* Write the updated presumed offset for this entry back out
1213                  * to the user.
1214                  */
1215                 reloc.presumed_offset = target_obj_priv->gtt_offset;
1216                 ret = copy_to_user(relocs + i, &reloc, sizeof(reloc));
1217                 if (ret != 0) {
1218                         drm_gem_object_unreference(target_obj);
1219                         return ret;
1220                 }
1221
1222                 drm_gem_object_unreference(target_obj);
1223         }
1224
1225         if (reloc_page != NULL)
1226                 iounmap(reloc_page);
1227
1228 #if WATCH_BUF
1229         if (0)
1230                 i915_gem_dump_object(obj, 128, __func__, ~0);
1231 #endif
1232         return 0;
1233 }
1234
1235 static int
1236 i915_dispatch_gem_execbuffer(struct drm_device *dev,
1237                               struct drm_i915_gem_execbuffer *exec,
1238                               uint64_t exec_offset)
1239 {
1240         drm_i915_private_t *dev_priv = dev->dev_private;
1241         struct drm_clip_rect __user *boxes = (struct drm_clip_rect __user *)
1242                                              (uintptr_t) exec->cliprects_ptr;
1243         int nbox = exec->num_cliprects;
1244         int i = 0, count;
1245         uint32_t        exec_start, exec_len;
1246         RING_LOCALS;
1247
1248         exec_start = (uint32_t) exec_offset + exec->batch_start_offset;
1249         exec_len = (uint32_t) exec->batch_len;
1250
1251         if ((exec_start | exec_len) & 0x7) {
1252                 DRM_ERROR("alignment\n");
1253                 return -EINVAL;
1254         }
1255
1256         if (!exec_start)
1257                 return -EINVAL;
1258
1259         count = nbox ? nbox : 1;
1260
1261         for (i = 0; i < count; i++) {
1262                 if (i < nbox) {
1263                         int ret = i915_emit_box(dev, boxes, i,
1264                                                 exec->DR1, exec->DR4);
1265                         if (ret)
1266                                 return ret;
1267                 }
1268
1269                 if (dev_priv->use_mi_batchbuffer_start) {
1270                         BEGIN_LP_RING(2);
1271                         if (IS_I965G(dev)) {
1272                                 OUT_RING(MI_BATCH_BUFFER_START |
1273                                          (2 << 6) |
1274                                          MI_BATCH_NON_SECURE_I965);
1275                                 OUT_RING(exec_start);
1276                         } else {
1277                                 OUT_RING(MI_BATCH_BUFFER_START |
1278                                          (2 << 6));
1279                                 OUT_RING(exec_start | MI_BATCH_NON_SECURE);
1280                         }
1281                         ADVANCE_LP_RING();
1282
1283                 } else {
1284                         BEGIN_LP_RING(4);
1285                         OUT_RING(MI_BATCH_BUFFER);
1286                         OUT_RING(exec_start | MI_BATCH_NON_SECURE);
1287                         OUT_RING(exec_start + exec_len - 4);
1288                         OUT_RING(0);
1289                         ADVANCE_LP_RING();
1290                 }
1291         }
1292
1293         /* XXX breadcrumb */
1294         return 0;
1295 }
1296
1297 /* Throttle our rendering by waiting until the ring has completed our requests
1298  * emitted over 20 msec ago.
1299  *
1300  * This should get us reasonable parallelism between CPU and GPU but also
1301  * relatively low latency when blocking on a particular request to finish.
1302  */
1303 static int
1304 i915_gem_ring_throttle(struct drm_device *dev)
1305 {
1306         drm_i915_private_t *dev_priv = dev->dev_private;
1307         int ret = 0;
1308
1309         mutex_lock(&dev->struct_mutex);
1310         while (!list_empty(&dev_priv->mm.request_list)) {
1311                 struct drm_i915_gem_request *request;
1312
1313                 request = list_first_entry(&dev_priv->mm.request_list,
1314                                            struct drm_i915_gem_request,
1315                                            list);
1316
1317                 /* Break out if we're close enough. */
1318                 if ((long) (jiffies - request->emitted_jiffies) <= (20 * HZ) / 1000) {
1319                         mutex_unlock(&dev->struct_mutex);
1320                         return 0;
1321                 }
1322
1323                 /* Wait on the last request if not. */
1324                 ret = i915_wait_request(dev, request->seqno);
1325                 if (ret != 0) {
1326                         mutex_unlock(&dev->struct_mutex);
1327                         return ret;
1328                 }
1329         }
1330         mutex_unlock(&dev->struct_mutex);
1331         return ret;
1332 }
1333
1334 int
1335 i915_gem_execbuffer(struct drm_device *dev, void *data,
1336                     struct drm_file *file_priv)
1337 {
1338         struct drm_i915_gem_execbuffer *args = data;
1339         struct drm_i915_gem_exec_object *validate_list = NULL;
1340         struct drm_gem_object **object_list = NULL;
1341         struct drm_gem_object *batch_obj;
1342         int ret, i;
1343         uint64_t exec_offset;
1344         uint32_t seqno, flush_domains;
1345
1346         LOCK_TEST_WITH_RETURN(dev, file_priv);
1347
1348 #if WATCH_EXEC
1349         DRM_INFO("buffers_ptr %d buffer_count %d len %08x\n",
1350                   (int) args->buffers_ptr, args->buffer_count, args->batch_len);
1351 #endif
1352         i915_kernel_lost_context(dev);
1353
1354         ret = i915_gem_ring_throttle(dev);
1355         if (ret)
1356                 return ret;
1357
1358         /* Copy in the validate list from userland */
1359         validate_list = drm_calloc(sizeof(*validate_list), args->buffer_count,
1360                                    DRM_MEM_DRIVER);
1361         object_list = drm_calloc(sizeof(*object_list), args->buffer_count,
1362                                  DRM_MEM_DRIVER);
1363         if (validate_list == NULL || object_list == NULL) {
1364                 DRM_ERROR("Failed to allocate validate or object list "
1365                           "for %d buffers\n",
1366                           args->buffer_count);
1367                 ret = -ENOMEM;
1368                 goto err;
1369         }
1370         ret = copy_from_user(validate_list,
1371                              (struct drm_i915_relocation_entry __user *)
1372                              (uintptr_t) args->buffers_ptr,
1373                              sizeof(*validate_list) * args->buffer_count);
1374         if (ret != 0) {
1375                 DRM_ERROR("copy %d validate entries failed %d\n",
1376                           args->buffer_count, ret);
1377                 goto err;
1378         }
1379
1380         mutex_lock(&dev->struct_mutex);
1381         /* Look up object handles and perform the relocations */
1382         for (i = 0; i < args->buffer_count; i++) {
1383                 object_list[i] = drm_gem_object_lookup(dev, file_priv,
1384                                                        validate_list[i].handle);
1385                 if (object_list[i] == NULL) {
1386                         DRM_ERROR("Invalid object handle %d at index %d\n",
1387                                    validate_list[i].handle, i);
1388                         ret = -EINVAL;
1389                         goto err;
1390                 }
1391
1392                 ret = i915_gem_reloc_and_validate_object(object_list[i],
1393                                                          file_priv,
1394                                                          &validate_list[i]);
1395                 if (ret) {
1396                         DRM_ERROR("reloc and validate failed %d\n", ret);
1397                         goto err;
1398                 }
1399         }
1400
1401         /* Set the pending read domains for the batch buffer to COMMAND */
1402         batch_obj = object_list[args->buffer_count-1];
1403         batch_obj->pending_read_domains = DRM_GEM_DOMAIN_I915_COMMAND;
1404         batch_obj->pending_write_domain = 0;
1405
1406         for (i = 0; i < args->buffer_count; i++) {
1407                 struct drm_gem_object *obj = object_list[i];
1408                 struct drm_i915_gem_object *obj_priv = obj->driver_private;
1409
1410                 if (obj_priv->gtt_space == NULL) {
1411                         /* We evicted the buffer in the process of validating
1412                          * our set of buffers in.  We could try to recover by
1413                          * kicking them everything out and trying again from
1414                          * the start.
1415                          */
1416                         ret = -ENOMEM;
1417                         goto err;
1418                 }
1419
1420                 /* make sure all previous memory operations have passed */
1421                 i915_gem_object_set_domain(obj,
1422                                             obj->pending_read_domains,
1423                                             obj->pending_write_domain);
1424                 obj->pending_read_domains = 0;
1425                 obj->pending_write_domain = 0;
1426         }
1427
1428         /* Flush/invalidate caches and chipset buffer */
1429         flush_domains = i915_gem_dev_set_domain(dev);
1430
1431 #if WATCH_COHERENCY
1432         for (i = 0; i < args->buffer_count; i++) {
1433                 i915_gem_object_check_coherency(object_list[i],
1434                                                 validate_list[i].handle);
1435         }
1436 #endif
1437
1438         exec_offset = validate_list[args->buffer_count - 1].offset;
1439
1440 #if WATCH_EXEC
1441         i915_gem_dump_object(object_list[args->buffer_count - 1],
1442                               args->batch_len,
1443                               __func__,
1444                               ~0);
1445 #endif
1446
1447         /* Exec the batchbuffer */
1448         ret = i915_dispatch_gem_execbuffer(dev, args, exec_offset);
1449         if (ret) {
1450                 DRM_ERROR("dispatch failed %d\n", ret);
1451                 goto err;
1452         }
1453
1454         /*
1455          * Ensure that the commands in the batch buffer are
1456          * finished before the interrupt fires
1457          */
1458         flush_domains |= i915_retire_commands(dev);
1459
1460         /*
1461          * Get a seqno representing the execution of the current buffer,
1462          * which we can wait on.  We would like to mitigate these interrupts,
1463          * likely by only creating seqnos occasionally (so that we have
1464          * *some* interrupts representing completion of buffers that we can
1465          * wait on when trying to clear up gtt space).
1466          */
1467         seqno = i915_add_request(dev, flush_domains);
1468         BUG_ON(seqno == 0);
1469         for (i = 0; i < args->buffer_count; i++) {
1470                 struct drm_gem_object *obj = object_list[i];
1471                 struct drm_i915_gem_object *obj_priv = obj->driver_private;
1472
1473                 i915_gem_object_move_to_active(obj);
1474                 obj_priv->last_rendering_seqno = seqno;
1475 #if WATCH_LRU
1476                 DRM_INFO("%s: move to exec list %p\n", __func__, obj);
1477 #endif
1478         }
1479 #if WATCH_LRU
1480         i915_dump_lru(dev, __func__);
1481 #endif
1482
1483         /* Copy the new buffer offsets back to the user's validate list. */
1484         ret = copy_to_user((struct drm_i915_relocation_entry __user *)
1485                            (uintptr_t) args->buffers_ptr,
1486                            validate_list,
1487                            sizeof(*validate_list) * args->buffer_count);
1488         if (ret)
1489                 DRM_ERROR("failed to copy %d validate entries "
1490                           "back to user (%d)\n",
1491                            args->buffer_count, ret);
1492 err:
1493         if (object_list != NULL) {
1494                 for (i = 0; i < args->buffer_count; i++)
1495                         drm_gem_object_unreference(object_list[i]);
1496         }
1497         mutex_unlock(&dev->struct_mutex);
1498
1499         drm_free(object_list, sizeof(*object_list) * args->buffer_count,
1500                  DRM_MEM_DRIVER);
1501         drm_free(validate_list, sizeof(*validate_list) * args->buffer_count,
1502                  DRM_MEM_DRIVER);
1503
1504         return ret;
1505 }
1506
1507 int
1508 i915_gem_pin_ioctl(struct drm_device *dev, void *data,
1509                    struct drm_file *file_priv)
1510 {
1511         struct drm_i915_gem_pin *args = data;
1512         struct drm_gem_object *obj;
1513         struct drm_i915_gem_object *obj_priv;
1514         int ret;
1515
1516         mutex_lock(&dev->struct_mutex);
1517
1518         i915_kernel_lost_context(dev);
1519         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
1520         if (obj == NULL) {
1521                 DRM_ERROR("Bad handle in i915_gem_pin_ioctl(): %d\n",
1522                           args->handle);
1523                 mutex_unlock(&dev->struct_mutex);
1524                 return -EINVAL;
1525         }
1526
1527         obj_priv = obj->driver_private;
1528         if (obj_priv->gtt_space == NULL) {
1529                 ret = i915_gem_object_bind_to_gtt(obj,
1530                                                   (unsigned) args->alignment);
1531                 if (ret != 0) {
1532                         DRM_ERROR("Failure to bind in "
1533                                   "i915_gem_pin_ioctl(): %d\n",
1534                                   ret);
1535                         drm_gem_object_unreference(obj);
1536                         mutex_unlock(&dev->struct_mutex);
1537                         return ret;
1538                 }
1539         }
1540
1541         obj_priv->pin_count++;
1542         args->offset = obj_priv->gtt_offset;
1543         drm_gem_object_unreference(obj);
1544         mutex_unlock(&dev->struct_mutex);
1545
1546         return 0;
1547 }
1548
1549 int
1550 i915_gem_unpin_ioctl(struct drm_device *dev, void *data,
1551                      struct drm_file *file_priv)
1552 {
1553         struct drm_i915_gem_pin *args = data;
1554         struct drm_gem_object *obj;
1555         struct drm_i915_gem_object *obj_priv;
1556
1557         mutex_lock(&dev->struct_mutex);
1558
1559         i915_kernel_lost_context(dev);
1560         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
1561         if (obj == NULL) {
1562                 DRM_ERROR("Bad handle in i915_gem_unpin_ioctl(): %d\n",
1563                           args->handle);
1564                 mutex_unlock(&dev->struct_mutex);
1565                 return -EINVAL;
1566         }
1567
1568         obj_priv = obj->driver_private;
1569         obj_priv->pin_count--;
1570         drm_gem_object_unreference(obj);
1571         mutex_unlock(&dev->struct_mutex);
1572         return 0;
1573 }
1574
1575 int
1576 i915_gem_busy_ioctl(struct drm_device *dev, void *data,
1577                     struct drm_file *file_priv)
1578 {
1579         struct drm_i915_gem_busy *args = data;
1580         struct drm_gem_object *obj;
1581         struct drm_i915_gem_object *obj_priv;
1582
1583         mutex_lock(&dev->struct_mutex);
1584         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
1585         if (obj == NULL) {
1586                 DRM_ERROR("Bad handle in i915_gem_busy_ioctl(): %d\n",
1587                           args->handle);
1588                 mutex_unlock(&dev->struct_mutex);
1589                 return -EINVAL;
1590         }
1591
1592         obj_priv = obj->driver_private;
1593         args->busy = obj_priv->active;
1594         
1595         drm_gem_object_unreference(obj);
1596         mutex_unlock(&dev->struct_mutex);
1597         return 0;
1598 }
1599
1600 int i915_gem_init_object(struct drm_gem_object *obj)
1601 {
1602         struct drm_i915_gem_object *obj_priv;
1603
1604         obj_priv = drm_calloc(1, sizeof(*obj_priv), DRM_MEM_DRIVER);
1605         if (obj_priv == NULL)
1606                 return -ENOMEM;
1607
1608         obj->driver_private = obj_priv;
1609         obj_priv->obj = obj;
1610         INIT_LIST_HEAD(&obj_priv->list);
1611         return 0;
1612 }
1613
1614 void i915_gem_free_object(struct drm_gem_object *obj)
1615 {
1616         i915_kernel_lost_context(obj->dev);
1617         i915_gem_object_unbind(obj);
1618
1619         drm_free(obj->driver_private, 1, DRM_MEM_DRIVER);
1620 }
1621
1622 int
1623 i915_gem_set_domain(struct drm_gem_object *obj,
1624                     struct drm_file *file_priv,
1625                     uint32_t read_domains,
1626                     uint32_t write_domain)
1627 {
1628         struct drm_device *dev = obj->dev;
1629
1630         BUG_ON(!mutex_is_locked(&dev->struct_mutex));
1631
1632         drm_client_lock_take(dev, file_priv);
1633         i915_kernel_lost_context(dev);
1634         i915_gem_object_set_domain(obj, read_domains, write_domain);
1635         i915_gem_dev_set_domain(obj->dev);
1636         drm_client_lock_release(dev);
1637
1638         return 0;
1639 }
1640
1641 int
1642 i915_gem_flush_pwrite(struct drm_gem_object *obj,
1643                       uint64_t offset, uint64_t size)
1644 {
1645 #if 0
1646         struct drm_device *dev = obj->dev;
1647         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1648
1649         /*
1650          * For writes much less than the size of the object and
1651          * which are already pinned in memory, do the flush right now
1652          */
1653
1654         if ((size < obj->size >> 1) && obj_priv->page_list != NULL) {
1655                 unsigned long first_page = offset / PAGE_SIZE;
1656                 unsigned long beyond_page = roundup(offset + size, PAGE_SIZE) / PAGE_SIZE;
1657
1658                 drm_ttm_cache_flush(obj_priv->page_list + first_page,
1659                                     beyond_page - first_page);
1660                 drm_agp_chipset_flush(dev);
1661                 obj->write_domain = 0;
1662         }
1663 #endif
1664         return 0;
1665 }
1666
1667 void
1668 i915_gem_lastclose(struct drm_device *dev)
1669 {
1670         drm_i915_private_t *dev_priv = dev->dev_private;
1671
1672         mutex_lock(&dev->struct_mutex);
1673
1674         /* Assume that the chip has been idled at this point. Just pull them
1675          * off the execution list and unref them.  Since this is the last
1676          * close, this is also the last ref and they'll go away.
1677          */
1678
1679         while (!list_empty(&dev_priv->mm.active_list)) {
1680                 struct drm_i915_gem_object *obj_priv;
1681
1682                 obj_priv = list_first_entry(&dev_priv->mm.active_list,
1683                                             struct drm_i915_gem_object,
1684                                             list);
1685
1686                 list_del_init(&obj_priv->list);
1687                 obj_priv->active = 0;
1688                 obj_priv->obj->write_domain = 0;
1689                 drm_gem_object_unreference(obj_priv->obj);
1690         }
1691
1692         mutex_unlock(&dev->struct_mutex);
1693 }