fix CONFIG_HIGHMEM compile error in drivers/gpu/drm/i915/i915_gem.c
[kernel.git] / drivers / gpu / drm / i915 / 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 #include <linux/swap.h>
33
34 static int
35 i915_gem_object_set_domain(struct drm_gem_object *obj,
36                             uint32_t read_domains,
37                             uint32_t write_domain);
38 static int
39 i915_gem_object_set_domain_range(struct drm_gem_object *obj,
40                                  uint64_t offset,
41                                  uint64_t size,
42                                  uint32_t read_domains,
43                                  uint32_t write_domain);
44 static int
45 i915_gem_set_domain(struct drm_gem_object *obj,
46                     struct drm_file *file_priv,
47                     uint32_t read_domains,
48                     uint32_t write_domain);
49 static int i915_gem_object_get_page_list(struct drm_gem_object *obj);
50 static void i915_gem_object_free_page_list(struct drm_gem_object *obj);
51 static int i915_gem_object_wait_rendering(struct drm_gem_object *obj);
52
53 static void
54 i915_gem_cleanup_ringbuffer(struct drm_device *dev);
55
56 int
57 i915_gem_init_ioctl(struct drm_device *dev, void *data,
58                     struct drm_file *file_priv)
59 {
60         drm_i915_private_t *dev_priv = dev->dev_private;
61         struct drm_i915_gem_init *args = data;
62
63         mutex_lock(&dev->struct_mutex);
64
65         if (args->gtt_start >= args->gtt_end ||
66             (args->gtt_start & (PAGE_SIZE - 1)) != 0 ||
67             (args->gtt_end & (PAGE_SIZE - 1)) != 0) {
68                 mutex_unlock(&dev->struct_mutex);
69                 return -EINVAL;
70         }
71
72         drm_mm_init(&dev_priv->mm.gtt_space, args->gtt_start,
73             args->gtt_end - args->gtt_start);
74
75         dev->gtt_total = (uint32_t) (args->gtt_end - args->gtt_start);
76
77         mutex_unlock(&dev->struct_mutex);
78
79         return 0;
80 }
81
82
83 /**
84  * Creates a new mm object and returns a handle to it.
85  */
86 int
87 i915_gem_create_ioctl(struct drm_device *dev, void *data,
88                       struct drm_file *file_priv)
89 {
90         struct drm_i915_gem_create *args = data;
91         struct drm_gem_object *obj;
92         int handle, ret;
93
94         args->size = roundup(args->size, PAGE_SIZE);
95
96         /* Allocate the new object */
97         obj = drm_gem_object_alloc(dev, args->size);
98         if (obj == NULL)
99                 return -ENOMEM;
100
101         ret = drm_gem_handle_create(file_priv, obj, &handle);
102         mutex_lock(&dev->struct_mutex);
103         drm_gem_object_handle_unreference(obj);
104         mutex_unlock(&dev->struct_mutex);
105
106         if (ret)
107                 return ret;
108
109         args->handle = handle;
110
111         return 0;
112 }
113
114 /**
115  * Reads data from the object referenced by handle.
116  *
117  * On error, the contents of *data are undefined.
118  */
119 int
120 i915_gem_pread_ioctl(struct drm_device *dev, void *data,
121                      struct drm_file *file_priv)
122 {
123         struct drm_i915_gem_pread *args = data;
124         struct drm_gem_object *obj;
125         struct drm_i915_gem_object *obj_priv;
126         ssize_t read;
127         loff_t offset;
128         int ret;
129
130         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
131         if (obj == NULL)
132                 return -EBADF;
133         obj_priv = obj->driver_private;
134
135         /* Bounds check source.
136          *
137          * XXX: This could use review for overflow issues...
138          */
139         if (args->offset > obj->size || args->size > obj->size ||
140             args->offset + args->size > obj->size) {
141                 drm_gem_object_unreference(obj);
142                 return -EINVAL;
143         }
144
145         mutex_lock(&dev->struct_mutex);
146
147         ret = i915_gem_object_set_domain_range(obj, args->offset, args->size,
148                                                I915_GEM_DOMAIN_CPU, 0);
149         if (ret != 0) {
150                 drm_gem_object_unreference(obj);
151                 mutex_unlock(&dev->struct_mutex);
152                 return ret;
153         }
154
155         offset = args->offset;
156
157         read = vfs_read(obj->filp, (char __user *)(uintptr_t)args->data_ptr,
158                         args->size, &offset);
159         if (read != args->size) {
160                 drm_gem_object_unreference(obj);
161                 mutex_unlock(&dev->struct_mutex);
162                 if (read < 0)
163                         return read;
164                 else
165                         return -EINVAL;
166         }
167
168         drm_gem_object_unreference(obj);
169         mutex_unlock(&dev->struct_mutex);
170
171         return 0;
172 }
173
174 /*
175  * Try to write quickly with an atomic kmap. Return true on success.
176  *
177  * If this fails (which includes a partial write), we'll redo the whole
178  * thing with the slow version.
179  *
180  * This is a workaround for the low performance of iounmap (approximate
181  * 10% cpu cost on normal 3D workloads).  kmap_atomic on HIGHMEM kernels
182  * happens to let us map card memory without taking IPIs.  When the vmap
183  * rework lands we should be able to dump this hack.
184  */
185 static inline int fast_user_write(unsigned long pfn, char __user *user_data,
186                                   int l, int o)
187 {
188 #ifdef CONFIG_HIGHMEM
189         unsigned long unwritten;
190         char *vaddr_atomic;
191
192         vaddr_atomic = kmap_atomic_pfn(pfn, KM_USER0);
193 #if WATCH_PWRITE
194         DRM_INFO("pwrite i %d o %d l %d pfn %ld vaddr %p\n",
195                  i, o, l, pfn, vaddr_atomic);
196 #endif
197         unwritten = __copy_from_user_inatomic_nocache(vaddr_atomic + o, user_data, l);
198         kunmap_atomic(vaddr_atomic, KM_USER0);
199         return !unwritten;
200 #else
201         return 0;
202 #endif
203 }
204
205 static int
206 i915_gem_gtt_pwrite(struct drm_device *dev, struct drm_gem_object *obj,
207                     struct drm_i915_gem_pwrite *args,
208                     struct drm_file *file_priv)
209 {
210         struct drm_i915_gem_object *obj_priv = obj->driver_private;
211         ssize_t remain;
212         loff_t offset;
213         char __user *user_data;
214         int ret = 0;
215
216         user_data = (char __user *) (uintptr_t) args->data_ptr;
217         remain = args->size;
218         if (!access_ok(VERIFY_READ, user_data, remain))
219                 return -EFAULT;
220
221
222         mutex_lock(&dev->struct_mutex);
223         ret = i915_gem_object_pin(obj, 0);
224         if (ret) {
225                 mutex_unlock(&dev->struct_mutex);
226                 return ret;
227         }
228         ret = i915_gem_set_domain(obj, file_priv,
229                                   I915_GEM_DOMAIN_GTT, I915_GEM_DOMAIN_GTT);
230         if (ret)
231                 goto fail;
232
233         obj_priv = obj->driver_private;
234         offset = obj_priv->gtt_offset + args->offset;
235         obj_priv->dirty = 1;
236
237         while (remain > 0) {
238                 unsigned long pfn;
239                 int i, o, l;
240
241                 /* Operation in this page
242                  *
243                  * i = page number
244                  * o = offset within page
245                  * l = bytes to copy
246                  */
247                 i = offset >> PAGE_SHIFT;
248                 o = offset & (PAGE_SIZE-1);
249                 l = remain;
250                 if ((o + l) > PAGE_SIZE)
251                         l = PAGE_SIZE - o;
252
253                 pfn = (dev->agp->base >> PAGE_SHIFT) + i;
254
255                 if (!fast_user_write(pfn, user_data, l, o)) {
256                         unsigned long unwritten;
257                         char __iomem *vaddr;
258
259                         vaddr = ioremap_wc(pfn << PAGE_SHIFT, PAGE_SIZE);
260 #if WATCH_PWRITE
261                         DRM_INFO("pwrite slow i %d o %d l %d "
262                                  "pfn %ld vaddr %p\n",
263                                  i, o, l, pfn, vaddr);
264 #endif
265                         if (vaddr == NULL) {
266                                 ret = -EFAULT;
267                                 goto fail;
268                         }
269                         unwritten = __copy_from_user(vaddr + o, user_data, l);
270 #if WATCH_PWRITE
271                         DRM_INFO("unwritten %ld\n", unwritten);
272 #endif
273                         iounmap(vaddr);
274                         if (unwritten) {
275                                 ret = -EFAULT;
276                                 goto fail;
277                         }
278                 }
279
280                 remain -= l;
281                 user_data += l;
282                 offset += l;
283         }
284 #if WATCH_PWRITE && 1
285         i915_gem_clflush_object(obj);
286         i915_gem_dump_object(obj, args->offset + args->size, __func__, ~0);
287         i915_gem_clflush_object(obj);
288 #endif
289
290 fail:
291         i915_gem_object_unpin(obj);
292         mutex_unlock(&dev->struct_mutex);
293
294         return ret;
295 }
296
297 static int
298 i915_gem_shmem_pwrite(struct drm_device *dev, struct drm_gem_object *obj,
299                       struct drm_i915_gem_pwrite *args,
300                       struct drm_file *file_priv)
301 {
302         int ret;
303         loff_t offset;
304         ssize_t written;
305
306         mutex_lock(&dev->struct_mutex);
307
308         ret = i915_gem_set_domain(obj, file_priv,
309                                   I915_GEM_DOMAIN_CPU, I915_GEM_DOMAIN_CPU);
310         if (ret) {
311                 mutex_unlock(&dev->struct_mutex);
312                 return ret;
313         }
314
315         offset = args->offset;
316
317         written = vfs_write(obj->filp,
318                             (char __user *)(uintptr_t) args->data_ptr,
319                             args->size, &offset);
320         if (written != args->size) {
321                 mutex_unlock(&dev->struct_mutex);
322                 if (written < 0)
323                         return written;
324                 else
325                         return -EINVAL;
326         }
327
328         mutex_unlock(&dev->struct_mutex);
329
330         return 0;
331 }
332
333 /**
334  * Writes data to the object referenced by handle.
335  *
336  * On error, the contents of the buffer that were to be modified are undefined.
337  */
338 int
339 i915_gem_pwrite_ioctl(struct drm_device *dev, void *data,
340                       struct drm_file *file_priv)
341 {
342         struct drm_i915_gem_pwrite *args = data;
343         struct drm_gem_object *obj;
344         struct drm_i915_gem_object *obj_priv;
345         int ret = 0;
346
347         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
348         if (obj == NULL)
349                 return -EBADF;
350         obj_priv = obj->driver_private;
351
352         /* Bounds check destination.
353          *
354          * XXX: This could use review for overflow issues...
355          */
356         if (args->offset > obj->size || args->size > obj->size ||
357             args->offset + args->size > obj->size) {
358                 drm_gem_object_unreference(obj);
359                 return -EINVAL;
360         }
361
362         /* We can only do the GTT pwrite on untiled buffers, as otherwise
363          * it would end up going through the fenced access, and we'll get
364          * different detiling behavior between reading and writing.
365          * pread/pwrite currently are reading and writing from the CPU
366          * perspective, requiring manual detiling by the client.
367          */
368         if (obj_priv->tiling_mode == I915_TILING_NONE &&
369             dev->gtt_total != 0)
370                 ret = i915_gem_gtt_pwrite(dev, obj, args, file_priv);
371         else
372                 ret = i915_gem_shmem_pwrite(dev, obj, args, file_priv);
373
374 #if WATCH_PWRITE
375         if (ret)
376                 DRM_INFO("pwrite failed %d\n", ret);
377 #endif
378
379         drm_gem_object_unreference(obj);
380
381         return ret;
382 }
383
384 /**
385  * Called when user space prepares to use an object
386  */
387 int
388 i915_gem_set_domain_ioctl(struct drm_device *dev, void *data,
389                           struct drm_file *file_priv)
390 {
391         struct drm_i915_gem_set_domain *args = data;
392         struct drm_gem_object *obj;
393         int ret;
394
395         if (!(dev->driver->driver_features & DRIVER_GEM))
396                 return -ENODEV;
397
398         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
399         if (obj == NULL)
400                 return -EBADF;
401
402         mutex_lock(&dev->struct_mutex);
403 #if WATCH_BUF
404         DRM_INFO("set_domain_ioctl %p(%d), %08x %08x\n",
405                  obj, obj->size, args->read_domains, args->write_domain);
406 #endif
407         ret = i915_gem_set_domain(obj, file_priv,
408                                   args->read_domains, args->write_domain);
409         drm_gem_object_unreference(obj);
410         mutex_unlock(&dev->struct_mutex);
411         return ret;
412 }
413
414 /**
415  * Called when user space has done writes to this buffer
416  */
417 int
418 i915_gem_sw_finish_ioctl(struct drm_device *dev, void *data,
419                       struct drm_file *file_priv)
420 {
421         struct drm_i915_gem_sw_finish *args = data;
422         struct drm_gem_object *obj;
423         struct drm_i915_gem_object *obj_priv;
424         int ret = 0;
425
426         if (!(dev->driver->driver_features & DRIVER_GEM))
427                 return -ENODEV;
428
429         mutex_lock(&dev->struct_mutex);
430         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
431         if (obj == NULL) {
432                 mutex_unlock(&dev->struct_mutex);
433                 return -EBADF;
434         }
435
436 #if WATCH_BUF
437         DRM_INFO("%s: sw_finish %d (%p %d)\n",
438                  __func__, args->handle, obj, obj->size);
439 #endif
440         obj_priv = obj->driver_private;
441
442         /* Pinned buffers may be scanout, so flush the cache */
443         if ((obj->write_domain & I915_GEM_DOMAIN_CPU) && obj_priv->pin_count) {
444                 i915_gem_clflush_object(obj);
445                 drm_agp_chipset_flush(dev);
446         }
447         drm_gem_object_unreference(obj);
448         mutex_unlock(&dev->struct_mutex);
449         return ret;
450 }
451
452 /**
453  * Maps the contents of an object, returning the address it is mapped
454  * into.
455  *
456  * While the mapping holds a reference on the contents of the object, it doesn't
457  * imply a ref on the object itself.
458  */
459 int
460 i915_gem_mmap_ioctl(struct drm_device *dev, void *data,
461                    struct drm_file *file_priv)
462 {
463         struct drm_i915_gem_mmap *args = data;
464         struct drm_gem_object *obj;
465         loff_t offset;
466         unsigned long addr;
467
468         if (!(dev->driver->driver_features & DRIVER_GEM))
469                 return -ENODEV;
470
471         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
472         if (obj == NULL)
473                 return -EBADF;
474
475         offset = args->offset;
476
477         down_write(&current->mm->mmap_sem);
478         addr = do_mmap(obj->filp, 0, args->size,
479                        PROT_READ | PROT_WRITE, MAP_SHARED,
480                        args->offset);
481         up_write(&current->mm->mmap_sem);
482         mutex_lock(&dev->struct_mutex);
483         drm_gem_object_unreference(obj);
484         mutex_unlock(&dev->struct_mutex);
485         if (IS_ERR((void *)addr))
486                 return addr;
487
488         args->addr_ptr = (uint64_t) addr;
489
490         return 0;
491 }
492
493 static void
494 i915_gem_object_free_page_list(struct drm_gem_object *obj)
495 {
496         struct drm_i915_gem_object *obj_priv = obj->driver_private;
497         int page_count = obj->size / PAGE_SIZE;
498         int i;
499
500         if (obj_priv->page_list == NULL)
501                 return;
502
503
504         for (i = 0; i < page_count; i++)
505                 if (obj_priv->page_list[i] != NULL) {
506                         if (obj_priv->dirty)
507                                 set_page_dirty(obj_priv->page_list[i]);
508                         mark_page_accessed(obj_priv->page_list[i]);
509                         page_cache_release(obj_priv->page_list[i]);
510                 }
511         obj_priv->dirty = 0;
512
513         drm_free(obj_priv->page_list,
514                  page_count * sizeof(struct page *),
515                  DRM_MEM_DRIVER);
516         obj_priv->page_list = NULL;
517 }
518
519 static void
520 i915_gem_object_move_to_active(struct drm_gem_object *obj)
521 {
522         struct drm_device *dev = obj->dev;
523         drm_i915_private_t *dev_priv = dev->dev_private;
524         struct drm_i915_gem_object *obj_priv = obj->driver_private;
525
526         /* Add a reference if we're newly entering the active list. */
527         if (!obj_priv->active) {
528                 drm_gem_object_reference(obj);
529                 obj_priv->active = 1;
530         }
531         /* Move from whatever list we were on to the tail of execution. */
532         list_move_tail(&obj_priv->list,
533                        &dev_priv->mm.active_list);
534 }
535
536
537 static void
538 i915_gem_object_move_to_inactive(struct drm_gem_object *obj)
539 {
540         struct drm_device *dev = obj->dev;
541         drm_i915_private_t *dev_priv = dev->dev_private;
542         struct drm_i915_gem_object *obj_priv = obj->driver_private;
543
544         i915_verify_inactive(dev, __FILE__, __LINE__);
545         if (obj_priv->pin_count != 0)
546                 list_del_init(&obj_priv->list);
547         else
548                 list_move_tail(&obj_priv->list, &dev_priv->mm.inactive_list);
549
550         if (obj_priv->active) {
551                 obj_priv->active = 0;
552                 drm_gem_object_unreference(obj);
553         }
554         i915_verify_inactive(dev, __FILE__, __LINE__);
555 }
556
557 /**
558  * Creates a new sequence number, emitting a write of it to the status page
559  * plus an interrupt, which will trigger i915_user_interrupt_handler.
560  *
561  * Must be called with struct_lock held.
562  *
563  * Returned sequence numbers are nonzero on success.
564  */
565 static uint32_t
566 i915_add_request(struct drm_device *dev, uint32_t flush_domains)
567 {
568         drm_i915_private_t *dev_priv = dev->dev_private;
569         struct drm_i915_gem_request *request;
570         uint32_t seqno;
571         int was_empty;
572         RING_LOCALS;
573
574         request = drm_calloc(1, sizeof(*request), DRM_MEM_DRIVER);
575         if (request == NULL)
576                 return 0;
577
578         /* Grab the seqno we're going to make this request be, and bump the
579          * next (skipping 0 so it can be the reserved no-seqno value).
580          */
581         seqno = dev_priv->mm.next_gem_seqno;
582         dev_priv->mm.next_gem_seqno++;
583         if (dev_priv->mm.next_gem_seqno == 0)
584                 dev_priv->mm.next_gem_seqno++;
585
586         BEGIN_LP_RING(4);
587         OUT_RING(MI_STORE_DWORD_INDEX);
588         OUT_RING(I915_GEM_HWS_INDEX << MI_STORE_DWORD_INDEX_SHIFT);
589         OUT_RING(seqno);
590
591         OUT_RING(MI_USER_INTERRUPT);
592         ADVANCE_LP_RING();
593
594         DRM_DEBUG("%d\n", seqno);
595
596         request->seqno = seqno;
597         request->emitted_jiffies = jiffies;
598         request->flush_domains = flush_domains;
599         was_empty = list_empty(&dev_priv->mm.request_list);
600         list_add_tail(&request->list, &dev_priv->mm.request_list);
601
602         if (was_empty && !dev_priv->mm.suspended)
603                 schedule_delayed_work(&dev_priv->mm.retire_work, HZ);
604         return seqno;
605 }
606
607 /**
608  * Command execution barrier
609  *
610  * Ensures that all commands in the ring are finished
611  * before signalling the CPU
612  */
613 static uint32_t
614 i915_retire_commands(struct drm_device *dev)
615 {
616         drm_i915_private_t *dev_priv = dev->dev_private;
617         uint32_t cmd = MI_FLUSH | MI_NO_WRITE_FLUSH;
618         uint32_t flush_domains = 0;
619         RING_LOCALS;
620
621         /* The sampler always gets flushed on i965 (sigh) */
622         if (IS_I965G(dev))
623                 flush_domains |= I915_GEM_DOMAIN_SAMPLER;
624         BEGIN_LP_RING(2);
625         OUT_RING(cmd);
626         OUT_RING(0); /* noop */
627         ADVANCE_LP_RING();
628         return flush_domains;
629 }
630
631 /**
632  * Moves buffers associated only with the given active seqno from the active
633  * to inactive list, potentially freeing them.
634  */
635 static void
636 i915_gem_retire_request(struct drm_device *dev,
637                         struct drm_i915_gem_request *request)
638 {
639         drm_i915_private_t *dev_priv = dev->dev_private;
640
641         /* Move any buffers on the active list that are no longer referenced
642          * by the ringbuffer to the flushing/inactive lists as appropriate.
643          */
644         while (!list_empty(&dev_priv->mm.active_list)) {
645                 struct drm_gem_object *obj;
646                 struct drm_i915_gem_object *obj_priv;
647
648                 obj_priv = list_first_entry(&dev_priv->mm.active_list,
649                                             struct drm_i915_gem_object,
650                                             list);
651                 obj = obj_priv->obj;
652
653                 /* If the seqno being retired doesn't match the oldest in the
654                  * list, then the oldest in the list must still be newer than
655                  * this seqno.
656                  */
657                 if (obj_priv->last_rendering_seqno != request->seqno)
658                         return;
659 #if WATCH_LRU
660                 DRM_INFO("%s: retire %d moves to inactive list %p\n",
661                          __func__, request->seqno, obj);
662 #endif
663
664                 if (obj->write_domain != 0) {
665                         list_move_tail(&obj_priv->list,
666                                        &dev_priv->mm.flushing_list);
667                 } else {
668                         i915_gem_object_move_to_inactive(obj);
669                 }
670         }
671
672         if (request->flush_domains != 0) {
673                 struct drm_i915_gem_object *obj_priv, *next;
674
675                 /* Clear the write domain and activity from any buffers
676                  * that are just waiting for a flush matching the one retired.
677                  */
678                 list_for_each_entry_safe(obj_priv, next,
679                                          &dev_priv->mm.flushing_list, list) {
680                         struct drm_gem_object *obj = obj_priv->obj;
681
682                         if (obj->write_domain & request->flush_domains) {
683                                 obj->write_domain = 0;
684                                 i915_gem_object_move_to_inactive(obj);
685                         }
686                 }
687
688         }
689 }
690
691 /**
692  * Returns true if seq1 is later than seq2.
693  */
694 static int
695 i915_seqno_passed(uint32_t seq1, uint32_t seq2)
696 {
697         return (int32_t)(seq1 - seq2) >= 0;
698 }
699
700 uint32_t
701 i915_get_gem_seqno(struct drm_device *dev)
702 {
703         drm_i915_private_t *dev_priv = dev->dev_private;
704
705         return READ_HWSP(dev_priv, I915_GEM_HWS_INDEX);
706 }
707
708 /**
709  * This function clears the request list as sequence numbers are passed.
710  */
711 void
712 i915_gem_retire_requests(struct drm_device *dev)
713 {
714         drm_i915_private_t *dev_priv = dev->dev_private;
715         uint32_t seqno;
716
717         seqno = i915_get_gem_seqno(dev);
718
719         while (!list_empty(&dev_priv->mm.request_list)) {
720                 struct drm_i915_gem_request *request;
721                 uint32_t retiring_seqno;
722
723                 request = list_first_entry(&dev_priv->mm.request_list,
724                                            struct drm_i915_gem_request,
725                                            list);
726                 retiring_seqno = request->seqno;
727
728                 if (i915_seqno_passed(seqno, retiring_seqno) ||
729                     dev_priv->mm.wedged) {
730                         i915_gem_retire_request(dev, request);
731
732                         list_del(&request->list);
733                         drm_free(request, sizeof(*request), DRM_MEM_DRIVER);
734                 } else
735                         break;
736         }
737 }
738
739 void
740 i915_gem_retire_work_handler(struct work_struct *work)
741 {
742         drm_i915_private_t *dev_priv;
743         struct drm_device *dev;
744
745         dev_priv = container_of(work, drm_i915_private_t,
746                                 mm.retire_work.work);
747         dev = dev_priv->dev;
748
749         mutex_lock(&dev->struct_mutex);
750         i915_gem_retire_requests(dev);
751         if (!dev_priv->mm.suspended &&
752             !list_empty(&dev_priv->mm.request_list))
753                 schedule_delayed_work(&dev_priv->mm.retire_work, HZ);
754         mutex_unlock(&dev->struct_mutex);
755 }
756
757 /**
758  * Waits for a sequence number to be signaled, and cleans up the
759  * request and object lists appropriately for that event.
760  */
761 static int
762 i915_wait_request(struct drm_device *dev, uint32_t seqno)
763 {
764         drm_i915_private_t *dev_priv = dev->dev_private;
765         int ret = 0;
766
767         BUG_ON(seqno == 0);
768
769         if (!i915_seqno_passed(i915_get_gem_seqno(dev), seqno)) {
770                 dev_priv->mm.waiting_gem_seqno = seqno;
771                 i915_user_irq_get(dev);
772                 ret = wait_event_interruptible(dev_priv->irq_queue,
773                                                i915_seqno_passed(i915_get_gem_seqno(dev),
774                                                                  seqno) ||
775                                                dev_priv->mm.wedged);
776                 i915_user_irq_put(dev);
777                 dev_priv->mm.waiting_gem_seqno = 0;
778         }
779         if (dev_priv->mm.wedged)
780                 ret = -EIO;
781
782         if (ret && ret != -ERESTARTSYS)
783                 DRM_ERROR("%s returns %d (awaiting %d at %d)\n",
784                           __func__, ret, seqno, i915_get_gem_seqno(dev));
785
786         /* Directly dispatch request retiring.  While we have the work queue
787          * to handle this, the waiter on a request often wants an associated
788          * buffer to have made it to the inactive list, and we would need
789          * a separate wait queue to handle that.
790          */
791         if (ret == 0)
792                 i915_gem_retire_requests(dev);
793
794         return ret;
795 }
796
797 static void
798 i915_gem_flush(struct drm_device *dev,
799                uint32_t invalidate_domains,
800                uint32_t flush_domains)
801 {
802         drm_i915_private_t *dev_priv = dev->dev_private;
803         uint32_t cmd;
804         RING_LOCALS;
805
806 #if WATCH_EXEC
807         DRM_INFO("%s: invalidate %08x flush %08x\n", __func__,
808                   invalidate_domains, flush_domains);
809 #endif
810
811         if (flush_domains & I915_GEM_DOMAIN_CPU)
812                 drm_agp_chipset_flush(dev);
813
814         if ((invalidate_domains | flush_domains) & ~(I915_GEM_DOMAIN_CPU |
815                                                      I915_GEM_DOMAIN_GTT)) {
816                 /*
817                  * read/write caches:
818                  *
819                  * I915_GEM_DOMAIN_RENDER is always invalidated, but is
820                  * only flushed if MI_NO_WRITE_FLUSH is unset.  On 965, it is
821                  * also flushed at 2d versus 3d pipeline switches.
822                  *
823                  * read-only caches:
824                  *
825                  * I915_GEM_DOMAIN_SAMPLER is flushed on pre-965 if
826                  * MI_READ_FLUSH is set, and is always flushed on 965.
827                  *
828                  * I915_GEM_DOMAIN_COMMAND may not exist?
829                  *
830                  * I915_GEM_DOMAIN_INSTRUCTION, which exists on 965, is
831                  * invalidated when MI_EXE_FLUSH is set.
832                  *
833                  * I915_GEM_DOMAIN_VERTEX, which exists on 965, is
834                  * invalidated with every MI_FLUSH.
835                  *
836                  * TLBs:
837                  *
838                  * On 965, TLBs associated with I915_GEM_DOMAIN_COMMAND
839                  * and I915_GEM_DOMAIN_CPU in are invalidated at PTE write and
840                  * I915_GEM_DOMAIN_RENDER and I915_GEM_DOMAIN_SAMPLER
841                  * are flushed at any MI_FLUSH.
842                  */
843
844                 cmd = MI_FLUSH | MI_NO_WRITE_FLUSH;
845                 if ((invalidate_domains|flush_domains) &
846                     I915_GEM_DOMAIN_RENDER)
847                         cmd &= ~MI_NO_WRITE_FLUSH;
848                 if (!IS_I965G(dev)) {
849                         /*
850                          * On the 965, the sampler cache always gets flushed
851                          * and this bit is reserved.
852                          */
853                         if (invalidate_domains & I915_GEM_DOMAIN_SAMPLER)
854                                 cmd |= MI_READ_FLUSH;
855                 }
856                 if (invalidate_domains & I915_GEM_DOMAIN_INSTRUCTION)
857                         cmd |= MI_EXE_FLUSH;
858
859 #if WATCH_EXEC
860                 DRM_INFO("%s: queue flush %08x to ring\n", __func__, cmd);
861 #endif
862                 BEGIN_LP_RING(2);
863                 OUT_RING(cmd);
864                 OUT_RING(0); /* noop */
865                 ADVANCE_LP_RING();
866         }
867 }
868
869 /**
870  * Ensures that all rendering to the object has completed and the object is
871  * safe to unbind from the GTT or access from the CPU.
872  */
873 static int
874 i915_gem_object_wait_rendering(struct drm_gem_object *obj)
875 {
876         struct drm_device *dev = obj->dev;
877         struct drm_i915_gem_object *obj_priv = obj->driver_private;
878         int ret;
879
880         /* If there are writes queued to the buffer, flush and
881          * create a new seqno to wait for.
882          */
883         if (obj->write_domain & ~(I915_GEM_DOMAIN_CPU|I915_GEM_DOMAIN_GTT)) {
884                 uint32_t write_domain = obj->write_domain;
885 #if WATCH_BUF
886                 DRM_INFO("%s: flushing object %p from write domain %08x\n",
887                           __func__, obj, write_domain);
888 #endif
889                 i915_gem_flush(dev, 0, write_domain);
890
891                 i915_gem_object_move_to_active(obj);
892                 obj_priv->last_rendering_seqno = i915_add_request(dev,
893                                                                   write_domain);
894                 BUG_ON(obj_priv->last_rendering_seqno == 0);
895 #if WATCH_LRU
896                 DRM_INFO("%s: flush moves to exec list %p\n", __func__, obj);
897 #endif
898         }
899
900         /* If there is rendering queued on the buffer being evicted, wait for
901          * it.
902          */
903         if (obj_priv->active) {
904 #if WATCH_BUF
905                 DRM_INFO("%s: object %p wait for seqno %08x\n",
906                           __func__, obj, obj_priv->last_rendering_seqno);
907 #endif
908                 ret = i915_wait_request(dev, obj_priv->last_rendering_seqno);
909                 if (ret != 0)
910                         return ret;
911         }
912
913         return 0;
914 }
915
916 /**
917  * Unbinds an object from the GTT aperture.
918  */
919 static int
920 i915_gem_object_unbind(struct drm_gem_object *obj)
921 {
922         struct drm_device *dev = obj->dev;
923         struct drm_i915_gem_object *obj_priv = obj->driver_private;
924         int ret = 0;
925
926 #if WATCH_BUF
927         DRM_INFO("%s:%d %p\n", __func__, __LINE__, obj);
928         DRM_INFO("gtt_space %p\n", obj_priv->gtt_space);
929 #endif
930         if (obj_priv->gtt_space == NULL)
931                 return 0;
932
933         if (obj_priv->pin_count != 0) {
934                 DRM_ERROR("Attempting to unbind pinned buffer\n");
935                 return -EINVAL;
936         }
937
938         /* Wait for any rendering to complete
939          */
940         ret = i915_gem_object_wait_rendering(obj);
941         if (ret) {
942                 DRM_ERROR("wait_rendering failed: %d\n", ret);
943                 return ret;
944         }
945
946         /* Move the object to the CPU domain to ensure that
947          * any possible CPU writes while it's not in the GTT
948          * are flushed when we go to remap it. This will
949          * also ensure that all pending GPU writes are finished
950          * before we unbind.
951          */
952         ret = i915_gem_object_set_domain(obj, I915_GEM_DOMAIN_CPU,
953                                          I915_GEM_DOMAIN_CPU);
954         if (ret) {
955                 DRM_ERROR("set_domain failed: %d\n", ret);
956                 return ret;
957         }
958
959         if (obj_priv->agp_mem != NULL) {
960                 drm_unbind_agp(obj_priv->agp_mem);
961                 drm_free_agp(obj_priv->agp_mem, obj->size / PAGE_SIZE);
962                 obj_priv->agp_mem = NULL;
963         }
964
965         BUG_ON(obj_priv->active);
966
967         i915_gem_object_free_page_list(obj);
968
969         if (obj_priv->gtt_space) {
970                 atomic_dec(&dev->gtt_count);
971                 atomic_sub(obj->size, &dev->gtt_memory);
972
973                 drm_mm_put_block(obj_priv->gtt_space);
974                 obj_priv->gtt_space = NULL;
975         }
976
977         /* Remove ourselves from the LRU list if present. */
978         if (!list_empty(&obj_priv->list))
979                 list_del_init(&obj_priv->list);
980
981         return 0;
982 }
983
984 static int
985 i915_gem_evict_something(struct drm_device *dev)
986 {
987         drm_i915_private_t *dev_priv = dev->dev_private;
988         struct drm_gem_object *obj;
989         struct drm_i915_gem_object *obj_priv;
990         int ret = 0;
991
992         for (;;) {
993                 /* If there's an inactive buffer available now, grab it
994                  * and be done.
995                  */
996                 if (!list_empty(&dev_priv->mm.inactive_list)) {
997                         obj_priv = list_first_entry(&dev_priv->mm.inactive_list,
998                                                     struct drm_i915_gem_object,
999                                                     list);
1000                         obj = obj_priv->obj;
1001                         BUG_ON(obj_priv->pin_count != 0);
1002 #if WATCH_LRU
1003                         DRM_INFO("%s: evicting %p\n", __func__, obj);
1004 #endif
1005                         BUG_ON(obj_priv->active);
1006
1007                         /* Wait on the rendering and unbind the buffer. */
1008                         ret = i915_gem_object_unbind(obj);
1009                         break;
1010                 }
1011
1012                 /* If we didn't get anything, but the ring is still processing
1013                  * things, wait for one of those things to finish and hopefully
1014                  * leave us a buffer to evict.
1015                  */
1016                 if (!list_empty(&dev_priv->mm.request_list)) {
1017                         struct drm_i915_gem_request *request;
1018
1019                         request = list_first_entry(&dev_priv->mm.request_list,
1020                                                    struct drm_i915_gem_request,
1021                                                    list);
1022
1023                         ret = i915_wait_request(dev, request->seqno);
1024                         if (ret)
1025                                 break;
1026
1027                         /* if waiting caused an object to become inactive,
1028                          * then loop around and wait for it. Otherwise, we
1029                          * assume that waiting freed and unbound something,
1030                          * so there should now be some space in the GTT
1031                          */
1032                         if (!list_empty(&dev_priv->mm.inactive_list))
1033                                 continue;
1034                         break;
1035                 }
1036
1037                 /* If we didn't have anything on the request list but there
1038                  * are buffers awaiting a flush, emit one and try again.
1039                  * When we wait on it, those buffers waiting for that flush
1040                  * will get moved to inactive.
1041                  */
1042                 if (!list_empty(&dev_priv->mm.flushing_list)) {
1043                         obj_priv = list_first_entry(&dev_priv->mm.flushing_list,
1044                                                     struct drm_i915_gem_object,
1045                                                     list);
1046                         obj = obj_priv->obj;
1047
1048                         i915_gem_flush(dev,
1049                                        obj->write_domain,
1050                                        obj->write_domain);
1051                         i915_add_request(dev, obj->write_domain);
1052
1053                         obj = NULL;
1054                         continue;
1055                 }
1056
1057                 DRM_ERROR("inactive empty %d request empty %d "
1058                           "flushing empty %d\n",
1059                           list_empty(&dev_priv->mm.inactive_list),
1060                           list_empty(&dev_priv->mm.request_list),
1061                           list_empty(&dev_priv->mm.flushing_list));
1062                 /* If we didn't do any of the above, there's nothing to be done
1063                  * and we just can't fit it in.
1064                  */
1065                 return -ENOMEM;
1066         }
1067         return ret;
1068 }
1069
1070 static int
1071 i915_gem_object_get_page_list(struct drm_gem_object *obj)
1072 {
1073         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1074         int page_count, i;
1075         struct address_space *mapping;
1076         struct inode *inode;
1077         struct page *page;
1078         int ret;
1079
1080         if (obj_priv->page_list)
1081                 return 0;
1082
1083         /* Get the list of pages out of our struct file.  They'll be pinned
1084          * at this point until we release them.
1085          */
1086         page_count = obj->size / PAGE_SIZE;
1087         BUG_ON(obj_priv->page_list != NULL);
1088         obj_priv->page_list = drm_calloc(page_count, sizeof(struct page *),
1089                                          DRM_MEM_DRIVER);
1090         if (obj_priv->page_list == NULL) {
1091                 DRM_ERROR("Faled to allocate page list\n");
1092                 return -ENOMEM;
1093         }
1094
1095         inode = obj->filp->f_path.dentry->d_inode;
1096         mapping = inode->i_mapping;
1097         for (i = 0; i < page_count; i++) {
1098                 page = read_mapping_page(mapping, i, NULL);
1099                 if (IS_ERR(page)) {
1100                         ret = PTR_ERR(page);
1101                         DRM_ERROR("read_mapping_page failed: %d\n", ret);
1102                         i915_gem_object_free_page_list(obj);
1103                         return ret;
1104                 }
1105                 obj_priv->page_list[i] = page;
1106         }
1107         return 0;
1108 }
1109
1110 /**
1111  * Finds free space in the GTT aperture and binds the object there.
1112  */
1113 static int
1114 i915_gem_object_bind_to_gtt(struct drm_gem_object *obj, unsigned alignment)
1115 {
1116         struct drm_device *dev = obj->dev;
1117         drm_i915_private_t *dev_priv = dev->dev_private;
1118         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1119         struct drm_mm_node *free_space;
1120         int page_count, ret;
1121
1122         if (alignment == 0)
1123                 alignment = PAGE_SIZE;
1124         if (alignment & (PAGE_SIZE - 1)) {
1125                 DRM_ERROR("Invalid object alignment requested %u\n", alignment);
1126                 return -EINVAL;
1127         }
1128
1129  search_free:
1130         free_space = drm_mm_search_free(&dev_priv->mm.gtt_space,
1131                                         obj->size, alignment, 0);
1132         if (free_space != NULL) {
1133                 obj_priv->gtt_space = drm_mm_get_block(free_space, obj->size,
1134                                                        alignment);
1135                 if (obj_priv->gtt_space != NULL) {
1136                         obj_priv->gtt_space->private = obj;
1137                         obj_priv->gtt_offset = obj_priv->gtt_space->start;
1138                 }
1139         }
1140         if (obj_priv->gtt_space == NULL) {
1141                 /* If the gtt is empty and we're still having trouble
1142                  * fitting our object in, we're out of memory.
1143                  */
1144 #if WATCH_LRU
1145                 DRM_INFO("%s: GTT full, evicting something\n", __func__);
1146 #endif
1147                 if (list_empty(&dev_priv->mm.inactive_list) &&
1148                     list_empty(&dev_priv->mm.flushing_list) &&
1149                     list_empty(&dev_priv->mm.active_list)) {
1150                         DRM_ERROR("GTT full, but LRU list empty\n");
1151                         return -ENOMEM;
1152                 }
1153
1154                 ret = i915_gem_evict_something(dev);
1155                 if (ret != 0) {
1156                         DRM_ERROR("Failed to evict a buffer %d\n", ret);
1157                         return ret;
1158                 }
1159                 goto search_free;
1160         }
1161
1162 #if WATCH_BUF
1163         DRM_INFO("Binding object of size %d at 0x%08x\n",
1164                  obj->size, obj_priv->gtt_offset);
1165 #endif
1166         ret = i915_gem_object_get_page_list(obj);
1167         if (ret) {
1168                 drm_mm_put_block(obj_priv->gtt_space);
1169                 obj_priv->gtt_space = NULL;
1170                 return ret;
1171         }
1172
1173         page_count = obj->size / PAGE_SIZE;
1174         /* Create an AGP memory structure pointing at our pages, and bind it
1175          * into the GTT.
1176          */
1177         obj_priv->agp_mem = drm_agp_bind_pages(dev,
1178                                                obj_priv->page_list,
1179                                                page_count,
1180                                                obj_priv->gtt_offset,
1181                                                obj_priv->agp_type);
1182         if (obj_priv->agp_mem == NULL) {
1183                 i915_gem_object_free_page_list(obj);
1184                 drm_mm_put_block(obj_priv->gtt_space);
1185                 obj_priv->gtt_space = NULL;
1186                 return -ENOMEM;
1187         }
1188         atomic_inc(&dev->gtt_count);
1189         atomic_add(obj->size, &dev->gtt_memory);
1190
1191         /* Assert that the object is not currently in any GPU domain. As it
1192          * wasn't in the GTT, there shouldn't be any way it could have been in
1193          * a GPU cache
1194          */
1195         BUG_ON(obj->read_domains & ~(I915_GEM_DOMAIN_CPU|I915_GEM_DOMAIN_GTT));
1196         BUG_ON(obj->write_domain & ~(I915_GEM_DOMAIN_CPU|I915_GEM_DOMAIN_GTT));
1197
1198         return 0;
1199 }
1200
1201 void
1202 i915_gem_clflush_object(struct drm_gem_object *obj)
1203 {
1204         struct drm_i915_gem_object      *obj_priv = obj->driver_private;
1205
1206         /* If we don't have a page list set up, then we're not pinned
1207          * to GPU, and we can ignore the cache flush because it'll happen
1208          * again at bind time.
1209          */
1210         if (obj_priv->page_list == NULL)
1211                 return;
1212
1213         drm_clflush_pages(obj_priv->page_list, obj->size / PAGE_SIZE);
1214 }
1215
1216 /*
1217  * Set the next domain for the specified object. This
1218  * may not actually perform the necessary flushing/invaliding though,
1219  * as that may want to be batched with other set_domain operations
1220  *
1221  * This is (we hope) the only really tricky part of gem. The goal
1222  * is fairly simple -- track which caches hold bits of the object
1223  * and make sure they remain coherent. A few concrete examples may
1224  * help to explain how it works. For shorthand, we use the notation
1225  * (read_domains, write_domain), e.g. (CPU, CPU) to indicate the
1226  * a pair of read and write domain masks.
1227  *
1228  * Case 1: the batch buffer
1229  *
1230  *      1. Allocated
1231  *      2. Written by CPU
1232  *      3. Mapped to GTT
1233  *      4. Read by GPU
1234  *      5. Unmapped from GTT
1235  *      6. Freed
1236  *
1237  *      Let's take these a step at a time
1238  *
1239  *      1. Allocated
1240  *              Pages allocated from the kernel may still have
1241  *              cache contents, so we set them to (CPU, CPU) always.
1242  *      2. Written by CPU (using pwrite)
1243  *              The pwrite function calls set_domain (CPU, CPU) and
1244  *              this function does nothing (as nothing changes)
1245  *      3. Mapped by GTT
1246  *              This function asserts that the object is not
1247  *              currently in any GPU-based read or write domains
1248  *      4. Read by GPU
1249  *              i915_gem_execbuffer calls set_domain (COMMAND, 0).
1250  *              As write_domain is zero, this function adds in the
1251  *              current read domains (CPU+COMMAND, 0).
1252  *              flush_domains is set to CPU.
1253  *              invalidate_domains is set to COMMAND
1254  *              clflush is run to get data out of the CPU caches
1255  *              then i915_dev_set_domain calls i915_gem_flush to
1256  *              emit an MI_FLUSH and drm_agp_chipset_flush
1257  *      5. Unmapped from GTT
1258  *              i915_gem_object_unbind calls set_domain (CPU, CPU)
1259  *              flush_domains and invalidate_domains end up both zero
1260  *              so no flushing/invalidating happens
1261  *      6. Freed
1262  *              yay, done
1263  *
1264  * Case 2: The shared render buffer
1265  *
1266  *      1. Allocated
1267  *      2. Mapped to GTT
1268  *      3. Read/written by GPU
1269  *      4. set_domain to (CPU,CPU)
1270  *      5. Read/written by CPU
1271  *      6. Read/written by GPU
1272  *
1273  *      1. Allocated
1274  *              Same as last example, (CPU, CPU)
1275  *      2. Mapped to GTT
1276  *              Nothing changes (assertions find that it is not in the GPU)
1277  *      3. Read/written by GPU
1278  *              execbuffer calls set_domain (RENDER, RENDER)
1279  *              flush_domains gets CPU
1280  *              invalidate_domains gets GPU
1281  *              clflush (obj)
1282  *              MI_FLUSH and drm_agp_chipset_flush
1283  *      4. set_domain (CPU, CPU)
1284  *              flush_domains gets GPU
1285  *              invalidate_domains gets CPU
1286  *              wait_rendering (obj) to make sure all drawing is complete.
1287  *              This will include an MI_FLUSH to get the data from GPU
1288  *              to memory
1289  *              clflush (obj) to invalidate the CPU cache
1290  *              Another MI_FLUSH in i915_gem_flush (eliminate this somehow?)
1291  *      5. Read/written by CPU
1292  *              cache lines are loaded and dirtied
1293  *      6. Read written by GPU
1294  *              Same as last GPU access
1295  *
1296  * Case 3: The constant buffer
1297  *
1298  *      1. Allocated
1299  *      2. Written by CPU
1300  *      3. Read by GPU
1301  *      4. Updated (written) by CPU again
1302  *      5. Read by GPU
1303  *
1304  *      1. Allocated
1305  *              (CPU, CPU)
1306  *      2. Written by CPU
1307  *              (CPU, CPU)
1308  *      3. Read by GPU
1309  *              (CPU+RENDER, 0)
1310  *              flush_domains = CPU
1311  *              invalidate_domains = RENDER
1312  *              clflush (obj)
1313  *              MI_FLUSH
1314  *              drm_agp_chipset_flush
1315  *      4. Updated (written) by CPU again
1316  *              (CPU, CPU)
1317  *              flush_domains = 0 (no previous write domain)
1318  *              invalidate_domains = 0 (no new read domains)
1319  *      5. Read by GPU
1320  *              (CPU+RENDER, 0)
1321  *              flush_domains = CPU
1322  *              invalidate_domains = RENDER
1323  *              clflush (obj)
1324  *              MI_FLUSH
1325  *              drm_agp_chipset_flush
1326  */
1327 static int
1328 i915_gem_object_set_domain(struct drm_gem_object *obj,
1329                             uint32_t read_domains,
1330                             uint32_t write_domain)
1331 {
1332         struct drm_device               *dev = obj->dev;
1333         struct drm_i915_gem_object      *obj_priv = obj->driver_private;
1334         uint32_t                        invalidate_domains = 0;
1335         uint32_t                        flush_domains = 0;
1336         int                             ret;
1337
1338 #if WATCH_BUF
1339         DRM_INFO("%s: object %p read %08x -> %08x write %08x -> %08x\n",
1340                  __func__, obj,
1341                  obj->read_domains, read_domains,
1342                  obj->write_domain, write_domain);
1343 #endif
1344         /*
1345          * If the object isn't moving to a new write domain,
1346          * let the object stay in multiple read domains
1347          */
1348         if (write_domain == 0)
1349                 read_domains |= obj->read_domains;
1350         else
1351                 obj_priv->dirty = 1;
1352
1353         /*
1354          * Flush the current write domain if
1355          * the new read domains don't match. Invalidate
1356          * any read domains which differ from the old
1357          * write domain
1358          */
1359         if (obj->write_domain && obj->write_domain != read_domains) {
1360                 flush_domains |= obj->write_domain;
1361                 invalidate_domains |= read_domains & ~obj->write_domain;
1362         }
1363         /*
1364          * Invalidate any read caches which may have
1365          * stale data. That is, any new read domains.
1366          */
1367         invalidate_domains |= read_domains & ~obj->read_domains;
1368         if ((flush_domains | invalidate_domains) & I915_GEM_DOMAIN_CPU) {
1369 #if WATCH_BUF
1370                 DRM_INFO("%s: CPU domain flush %08x invalidate %08x\n",
1371                          __func__, flush_domains, invalidate_domains);
1372 #endif
1373                 /*
1374                  * If we're invaliding the CPU cache and flushing a GPU cache,
1375                  * then pause for rendering so that the GPU caches will be
1376                  * flushed before the cpu cache is invalidated
1377                  */
1378                 if ((invalidate_domains & I915_GEM_DOMAIN_CPU) &&
1379                     (flush_domains & ~(I915_GEM_DOMAIN_CPU |
1380                                        I915_GEM_DOMAIN_GTT))) {
1381                         ret = i915_gem_object_wait_rendering(obj);
1382                         if (ret)
1383                                 return ret;
1384                 }
1385                 i915_gem_clflush_object(obj);
1386         }
1387
1388         if ((write_domain | flush_domains) != 0)
1389                 obj->write_domain = write_domain;
1390
1391         /* If we're invalidating the CPU domain, clear the per-page CPU
1392          * domain list as well.
1393          */
1394         if (obj_priv->page_cpu_valid != NULL &&
1395             (write_domain != 0 ||
1396              read_domains & I915_GEM_DOMAIN_CPU)) {
1397                 drm_free(obj_priv->page_cpu_valid, obj->size / PAGE_SIZE,
1398                          DRM_MEM_DRIVER);
1399                 obj_priv->page_cpu_valid = NULL;
1400         }
1401         obj->read_domains = read_domains;
1402
1403         dev->invalidate_domains |= invalidate_domains;
1404         dev->flush_domains |= flush_domains;
1405 #if WATCH_BUF
1406         DRM_INFO("%s: read %08x write %08x invalidate %08x flush %08x\n",
1407                  __func__,
1408                  obj->read_domains, obj->write_domain,
1409                  dev->invalidate_domains, dev->flush_domains);
1410 #endif
1411         return 0;
1412 }
1413
1414 /**
1415  * Set the read/write domain on a range of the object.
1416  *
1417  * Currently only implemented for CPU reads, otherwise drops to normal
1418  * i915_gem_object_set_domain().
1419  */
1420 static int
1421 i915_gem_object_set_domain_range(struct drm_gem_object *obj,
1422                                  uint64_t offset,
1423                                  uint64_t size,
1424                                  uint32_t read_domains,
1425                                  uint32_t write_domain)
1426 {
1427         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1428         int ret, i;
1429
1430         if (obj->read_domains & I915_GEM_DOMAIN_CPU)
1431                 return 0;
1432
1433         if (read_domains != I915_GEM_DOMAIN_CPU ||
1434             write_domain != 0)
1435                 return i915_gem_object_set_domain(obj,
1436                                                   read_domains, write_domain);
1437
1438         /* Wait on any GPU rendering to the object to be flushed. */
1439         if (obj->write_domain & ~(I915_GEM_DOMAIN_CPU | I915_GEM_DOMAIN_GTT)) {
1440                 ret = i915_gem_object_wait_rendering(obj);
1441                 if (ret)
1442                         return ret;
1443         }
1444
1445         if (obj_priv->page_cpu_valid == NULL) {
1446                 obj_priv->page_cpu_valid = drm_calloc(1, obj->size / PAGE_SIZE,
1447                                                       DRM_MEM_DRIVER);
1448         }
1449
1450         /* Flush the cache on any pages that are still invalid from the CPU's
1451          * perspective.
1452          */
1453         for (i = offset / PAGE_SIZE; i <= (offset + size - 1) / PAGE_SIZE; i++) {
1454                 if (obj_priv->page_cpu_valid[i])
1455                         continue;
1456
1457                 drm_clflush_pages(obj_priv->page_list + i, 1);
1458
1459                 obj_priv->page_cpu_valid[i] = 1;
1460         }
1461
1462         return 0;
1463 }
1464
1465 /**
1466  * Once all of the objects have been set in the proper domain,
1467  * perform the necessary flush and invalidate operations.
1468  *
1469  * Returns the write domains flushed, for use in flush tracking.
1470  */
1471 static uint32_t
1472 i915_gem_dev_set_domain(struct drm_device *dev)
1473 {
1474         uint32_t flush_domains = dev->flush_domains;
1475
1476         /*
1477          * Now that all the buffers are synced to the proper domains,
1478          * flush and invalidate the collected domains
1479          */
1480         if (dev->invalidate_domains | dev->flush_domains) {
1481 #if WATCH_EXEC
1482                 DRM_INFO("%s: invalidate_domains %08x flush_domains %08x\n",
1483                           __func__,
1484                          dev->invalidate_domains,
1485                          dev->flush_domains);
1486 #endif
1487                 i915_gem_flush(dev,
1488                                dev->invalidate_domains,
1489                                dev->flush_domains);
1490                 dev->invalidate_domains = 0;
1491                 dev->flush_domains = 0;
1492         }
1493
1494         return flush_domains;
1495 }
1496
1497 /**
1498  * Pin an object to the GTT and evaluate the relocations landing in it.
1499  */
1500 static int
1501 i915_gem_object_pin_and_relocate(struct drm_gem_object *obj,
1502                                  struct drm_file *file_priv,
1503                                  struct drm_i915_gem_exec_object *entry)
1504 {
1505         struct drm_device *dev = obj->dev;
1506         struct drm_i915_gem_relocation_entry reloc;
1507         struct drm_i915_gem_relocation_entry __user *relocs;
1508         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1509         int i, ret;
1510         uint32_t last_reloc_offset = -1;
1511         void __iomem *reloc_page = NULL;
1512
1513         /* Choose the GTT offset for our buffer and put it there. */
1514         ret = i915_gem_object_pin(obj, (uint32_t) entry->alignment);
1515         if (ret)
1516                 return ret;
1517
1518         entry->offset = obj_priv->gtt_offset;
1519
1520         relocs = (struct drm_i915_gem_relocation_entry __user *)
1521                  (uintptr_t) entry->relocs_ptr;
1522         /* Apply the relocations, using the GTT aperture to avoid cache
1523          * flushing requirements.
1524          */
1525         for (i = 0; i < entry->relocation_count; i++) {
1526                 struct drm_gem_object *target_obj;
1527                 struct drm_i915_gem_object *target_obj_priv;
1528                 uint32_t reloc_val, reloc_offset;
1529                 uint32_t __iomem *reloc_entry;
1530
1531                 ret = copy_from_user(&reloc, relocs + i, sizeof(reloc));
1532                 if (ret != 0) {
1533                         i915_gem_object_unpin(obj);
1534                         return ret;
1535                 }
1536
1537                 target_obj = drm_gem_object_lookup(obj->dev, file_priv,
1538                                                    reloc.target_handle);
1539                 if (target_obj == NULL) {
1540                         i915_gem_object_unpin(obj);
1541                         return -EBADF;
1542                 }
1543                 target_obj_priv = target_obj->driver_private;
1544
1545                 /* The target buffer should have appeared before us in the
1546                  * exec_object list, so it should have a GTT space bound by now.
1547                  */
1548                 if (target_obj_priv->gtt_space == NULL) {
1549                         DRM_ERROR("No GTT space found for object %d\n",
1550                                   reloc.target_handle);
1551                         drm_gem_object_unreference(target_obj);
1552                         i915_gem_object_unpin(obj);
1553                         return -EINVAL;
1554                 }
1555
1556                 if (reloc.offset > obj->size - 4) {
1557                         DRM_ERROR("Relocation beyond object bounds: "
1558                                   "obj %p target %d offset %d size %d.\n",
1559                                   obj, reloc.target_handle,
1560                                   (int) reloc.offset, (int) obj->size);
1561                         drm_gem_object_unreference(target_obj);
1562                         i915_gem_object_unpin(obj);
1563                         return -EINVAL;
1564                 }
1565                 if (reloc.offset & 3) {
1566                         DRM_ERROR("Relocation not 4-byte aligned: "
1567                                   "obj %p target %d offset %d.\n",
1568                                   obj, reloc.target_handle,
1569                                   (int) reloc.offset);
1570                         drm_gem_object_unreference(target_obj);
1571                         i915_gem_object_unpin(obj);
1572                         return -EINVAL;
1573                 }
1574
1575                 if (reloc.write_domain && target_obj->pending_write_domain &&
1576                     reloc.write_domain != target_obj->pending_write_domain) {
1577                         DRM_ERROR("Write domain conflict: "
1578                                   "obj %p target %d offset %d "
1579                                   "new %08x old %08x\n",
1580                                   obj, reloc.target_handle,
1581                                   (int) reloc.offset,
1582                                   reloc.write_domain,
1583                                   target_obj->pending_write_domain);
1584                         drm_gem_object_unreference(target_obj);
1585                         i915_gem_object_unpin(obj);
1586                         return -EINVAL;
1587                 }
1588
1589 #if WATCH_RELOC
1590                 DRM_INFO("%s: obj %p offset %08x target %d "
1591                          "read %08x write %08x gtt %08x "
1592                          "presumed %08x delta %08x\n",
1593                          __func__,
1594                          obj,
1595                          (int) reloc.offset,
1596                          (int) reloc.target_handle,
1597                          (int) reloc.read_domains,
1598                          (int) reloc.write_domain,
1599                          (int) target_obj_priv->gtt_offset,
1600                          (int) reloc.presumed_offset,
1601                          reloc.delta);
1602 #endif
1603
1604                 target_obj->pending_read_domains |= reloc.read_domains;
1605                 target_obj->pending_write_domain |= reloc.write_domain;
1606
1607                 /* If the relocation already has the right value in it, no
1608                  * more work needs to be done.
1609                  */
1610                 if (target_obj_priv->gtt_offset == reloc.presumed_offset) {
1611                         drm_gem_object_unreference(target_obj);
1612                         continue;
1613                 }
1614
1615                 /* Now that we're going to actually write some data in,
1616                  * make sure that any rendering using this buffer's contents
1617                  * is completed.
1618                  */
1619                 i915_gem_object_wait_rendering(obj);
1620
1621                 /* As we're writing through the gtt, flush
1622                  * any CPU writes before we write the relocations
1623                  */
1624                 if (obj->write_domain & I915_GEM_DOMAIN_CPU) {
1625                         i915_gem_clflush_object(obj);
1626                         drm_agp_chipset_flush(dev);
1627                         obj->write_domain = 0;
1628                 }
1629
1630                 /* Map the page containing the relocation we're going to
1631                  * perform.
1632                  */
1633                 reloc_offset = obj_priv->gtt_offset + reloc.offset;
1634                 if (reloc_page == NULL ||
1635                     (last_reloc_offset & ~(PAGE_SIZE - 1)) !=
1636                     (reloc_offset & ~(PAGE_SIZE - 1))) {
1637                         if (reloc_page != NULL)
1638                                 iounmap(reloc_page);
1639
1640                         reloc_page = ioremap_wc(dev->agp->base +
1641                                                 (reloc_offset &
1642                                                  ~(PAGE_SIZE - 1)),
1643                                                 PAGE_SIZE);
1644                         last_reloc_offset = reloc_offset;
1645                         if (reloc_page == NULL) {
1646                                 drm_gem_object_unreference(target_obj);
1647                                 i915_gem_object_unpin(obj);
1648                                 return -ENOMEM;
1649                         }
1650                 }
1651
1652                 reloc_entry = (uint32_t __iomem *)(reloc_page +
1653                                            (reloc_offset & (PAGE_SIZE - 1)));
1654                 reloc_val = target_obj_priv->gtt_offset + reloc.delta;
1655
1656 #if WATCH_BUF
1657                 DRM_INFO("Applied relocation: %p@0x%08x %08x -> %08x\n",
1658                           obj, (unsigned int) reloc.offset,
1659                           readl(reloc_entry), reloc_val);
1660 #endif
1661                 writel(reloc_val, reloc_entry);
1662
1663                 /* Write the updated presumed offset for this entry back out
1664                  * to the user.
1665                  */
1666                 reloc.presumed_offset = target_obj_priv->gtt_offset;
1667                 ret = copy_to_user(relocs + i, &reloc, sizeof(reloc));
1668                 if (ret != 0) {
1669                         drm_gem_object_unreference(target_obj);
1670                         i915_gem_object_unpin(obj);
1671                         return ret;
1672                 }
1673
1674                 drm_gem_object_unreference(target_obj);
1675         }
1676
1677         if (reloc_page != NULL)
1678                 iounmap(reloc_page);
1679
1680 #if WATCH_BUF
1681         if (0)
1682                 i915_gem_dump_object(obj, 128, __func__, ~0);
1683 #endif
1684         return 0;
1685 }
1686
1687 /** Dispatch a batchbuffer to the ring
1688  */
1689 static int
1690 i915_dispatch_gem_execbuffer(struct drm_device *dev,
1691                               struct drm_i915_gem_execbuffer *exec,
1692                               uint64_t exec_offset)
1693 {
1694         drm_i915_private_t *dev_priv = dev->dev_private;
1695         struct drm_clip_rect __user *boxes = (struct drm_clip_rect __user *)
1696                                              (uintptr_t) exec->cliprects_ptr;
1697         int nbox = exec->num_cliprects;
1698         int i = 0, count;
1699         uint32_t        exec_start, exec_len;
1700         RING_LOCALS;
1701
1702         exec_start = (uint32_t) exec_offset + exec->batch_start_offset;
1703         exec_len = (uint32_t) exec->batch_len;
1704
1705         if ((exec_start | exec_len) & 0x7) {
1706                 DRM_ERROR("alignment\n");
1707                 return -EINVAL;
1708         }
1709
1710         if (!exec_start)
1711                 return -EINVAL;
1712
1713         count = nbox ? nbox : 1;
1714
1715         for (i = 0; i < count; i++) {
1716                 if (i < nbox) {
1717                         int ret = i915_emit_box(dev, boxes, i,
1718                                                 exec->DR1, exec->DR4);
1719                         if (ret)
1720                                 return ret;
1721                 }
1722
1723                 if (IS_I830(dev) || IS_845G(dev)) {
1724                         BEGIN_LP_RING(4);
1725                         OUT_RING(MI_BATCH_BUFFER);
1726                         OUT_RING(exec_start | MI_BATCH_NON_SECURE);
1727                         OUT_RING(exec_start + exec_len - 4);
1728                         OUT_RING(0);
1729                         ADVANCE_LP_RING();
1730                 } else {
1731                         BEGIN_LP_RING(2);
1732                         if (IS_I965G(dev)) {
1733                                 OUT_RING(MI_BATCH_BUFFER_START |
1734                                          (2 << 6) |
1735                                          MI_BATCH_NON_SECURE_I965);
1736                                 OUT_RING(exec_start);
1737                         } else {
1738                                 OUT_RING(MI_BATCH_BUFFER_START |
1739                                          (2 << 6));
1740                                 OUT_RING(exec_start | MI_BATCH_NON_SECURE);
1741                         }
1742                         ADVANCE_LP_RING();
1743                 }
1744         }
1745
1746         /* XXX breadcrumb */
1747         return 0;
1748 }
1749
1750 /* Throttle our rendering by waiting until the ring has completed our requests
1751  * emitted over 20 msec ago.
1752  *
1753  * This should get us reasonable parallelism between CPU and GPU but also
1754  * relatively low latency when blocking on a particular request to finish.
1755  */
1756 static int
1757 i915_gem_ring_throttle(struct drm_device *dev, struct drm_file *file_priv)
1758 {
1759         struct drm_i915_file_private *i915_file_priv = file_priv->driver_priv;
1760         int ret = 0;
1761         uint32_t seqno;
1762
1763         mutex_lock(&dev->struct_mutex);
1764         seqno = i915_file_priv->mm.last_gem_throttle_seqno;
1765         i915_file_priv->mm.last_gem_throttle_seqno =
1766                 i915_file_priv->mm.last_gem_seqno;
1767         if (seqno)
1768                 ret = i915_wait_request(dev, seqno);
1769         mutex_unlock(&dev->struct_mutex);
1770         return ret;
1771 }
1772
1773 int
1774 i915_gem_execbuffer(struct drm_device *dev, void *data,
1775                     struct drm_file *file_priv)
1776 {
1777         drm_i915_private_t *dev_priv = dev->dev_private;
1778         struct drm_i915_file_private *i915_file_priv = file_priv->driver_priv;
1779         struct drm_i915_gem_execbuffer *args = data;
1780         struct drm_i915_gem_exec_object *exec_list = NULL;
1781         struct drm_gem_object **object_list = NULL;
1782         struct drm_gem_object *batch_obj;
1783         int ret, i, pinned = 0;
1784         uint64_t exec_offset;
1785         uint32_t seqno, flush_domains;
1786
1787 #if WATCH_EXEC
1788         DRM_INFO("buffers_ptr %d buffer_count %d len %08x\n",
1789                   (int) args->buffers_ptr, args->buffer_count, args->batch_len);
1790 #endif
1791
1792         if (args->buffer_count < 1) {
1793                 DRM_ERROR("execbuf with %d buffers\n", args->buffer_count);
1794                 return -EINVAL;
1795         }
1796         /* Copy in the exec list from userland */
1797         exec_list = drm_calloc(sizeof(*exec_list), args->buffer_count,
1798                                DRM_MEM_DRIVER);
1799         object_list = drm_calloc(sizeof(*object_list), args->buffer_count,
1800                                  DRM_MEM_DRIVER);
1801         if (exec_list == NULL || object_list == NULL) {
1802                 DRM_ERROR("Failed to allocate exec or object list "
1803                           "for %d buffers\n",
1804                           args->buffer_count);
1805                 ret = -ENOMEM;
1806                 goto pre_mutex_err;
1807         }
1808         ret = copy_from_user(exec_list,
1809                              (struct drm_i915_relocation_entry __user *)
1810                              (uintptr_t) args->buffers_ptr,
1811                              sizeof(*exec_list) * args->buffer_count);
1812         if (ret != 0) {
1813                 DRM_ERROR("copy %d exec entries failed %d\n",
1814                           args->buffer_count, ret);
1815                 goto pre_mutex_err;
1816         }
1817
1818         mutex_lock(&dev->struct_mutex);
1819
1820         i915_verify_inactive(dev, __FILE__, __LINE__);
1821
1822         if (dev_priv->mm.wedged) {
1823                 DRM_ERROR("Execbuf while wedged\n");
1824                 mutex_unlock(&dev->struct_mutex);
1825                 return -EIO;
1826         }
1827
1828         if (dev_priv->mm.suspended) {
1829                 DRM_ERROR("Execbuf while VT-switched.\n");
1830                 mutex_unlock(&dev->struct_mutex);
1831                 return -EBUSY;
1832         }
1833
1834         /* Zero the gloabl flush/invalidate flags. These
1835          * will be modified as each object is bound to the
1836          * gtt
1837          */
1838         dev->invalidate_domains = 0;
1839         dev->flush_domains = 0;
1840
1841         /* Look up object handles and perform the relocations */
1842         for (i = 0; i < args->buffer_count; i++) {
1843                 object_list[i] = drm_gem_object_lookup(dev, file_priv,
1844                                                        exec_list[i].handle);
1845                 if (object_list[i] == NULL) {
1846                         DRM_ERROR("Invalid object handle %d at index %d\n",
1847                                    exec_list[i].handle, i);
1848                         ret = -EBADF;
1849                         goto err;
1850                 }
1851
1852                 object_list[i]->pending_read_domains = 0;
1853                 object_list[i]->pending_write_domain = 0;
1854                 ret = i915_gem_object_pin_and_relocate(object_list[i],
1855                                                        file_priv,
1856                                                        &exec_list[i]);
1857                 if (ret) {
1858                         DRM_ERROR("object bind and relocate failed %d\n", ret);
1859                         goto err;
1860                 }
1861                 pinned = i + 1;
1862         }
1863
1864         /* Set the pending read domains for the batch buffer to COMMAND */
1865         batch_obj = object_list[args->buffer_count-1];
1866         batch_obj->pending_read_domains = I915_GEM_DOMAIN_COMMAND;
1867         batch_obj->pending_write_domain = 0;
1868
1869         i915_verify_inactive(dev, __FILE__, __LINE__);
1870
1871         for (i = 0; i < args->buffer_count; i++) {
1872                 struct drm_gem_object *obj = object_list[i];
1873                 struct drm_i915_gem_object *obj_priv = obj->driver_private;
1874
1875                 if (obj_priv->gtt_space == NULL) {
1876                         /* We evicted the buffer in the process of validating
1877                          * our set of buffers in.  We could try to recover by
1878                          * kicking them everything out and trying again from
1879                          * the start.
1880                          */
1881                         ret = -ENOMEM;
1882                         goto err;
1883                 }
1884
1885                 /* make sure all previous memory operations have passed */
1886                 ret = i915_gem_object_set_domain(obj,
1887                                                  obj->pending_read_domains,
1888                                                  obj->pending_write_domain);
1889                 if (ret)
1890                         goto err;
1891         }
1892
1893         i915_verify_inactive(dev, __FILE__, __LINE__);
1894
1895         /* Flush/invalidate caches and chipset buffer */
1896         flush_domains = i915_gem_dev_set_domain(dev);
1897
1898         i915_verify_inactive(dev, __FILE__, __LINE__);
1899
1900 #if WATCH_COHERENCY
1901         for (i = 0; i < args->buffer_count; i++) {
1902                 i915_gem_object_check_coherency(object_list[i],
1903                                                 exec_list[i].handle);
1904         }
1905 #endif
1906
1907         exec_offset = exec_list[args->buffer_count - 1].offset;
1908
1909 #if WATCH_EXEC
1910         i915_gem_dump_object(object_list[args->buffer_count - 1],
1911                               args->batch_len,
1912                               __func__,
1913                               ~0);
1914 #endif
1915
1916         (void)i915_add_request(dev, flush_domains);
1917
1918         /* Exec the batchbuffer */
1919         ret = i915_dispatch_gem_execbuffer(dev, args, exec_offset);
1920         if (ret) {
1921                 DRM_ERROR("dispatch failed %d\n", ret);
1922                 goto err;
1923         }
1924
1925         /*
1926          * Ensure that the commands in the batch buffer are
1927          * finished before the interrupt fires
1928          */
1929         flush_domains = i915_retire_commands(dev);
1930
1931         i915_verify_inactive(dev, __FILE__, __LINE__);
1932
1933         /*
1934          * Get a seqno representing the execution of the current buffer,
1935          * which we can wait on.  We would like to mitigate these interrupts,
1936          * likely by only creating seqnos occasionally (so that we have
1937          * *some* interrupts representing completion of buffers that we can
1938          * wait on when trying to clear up gtt space).
1939          */
1940         seqno = i915_add_request(dev, flush_domains);
1941         BUG_ON(seqno == 0);
1942         i915_file_priv->mm.last_gem_seqno = seqno;
1943         for (i = 0; i < args->buffer_count; i++) {
1944                 struct drm_gem_object *obj = object_list[i];
1945                 struct drm_i915_gem_object *obj_priv = obj->driver_private;
1946
1947                 i915_gem_object_move_to_active(obj);
1948                 obj_priv->last_rendering_seqno = seqno;
1949 #if WATCH_LRU
1950                 DRM_INFO("%s: move to exec list %p\n", __func__, obj);
1951 #endif
1952         }
1953 #if WATCH_LRU
1954         i915_dump_lru(dev, __func__);
1955 #endif
1956
1957         i915_verify_inactive(dev, __FILE__, __LINE__);
1958
1959         /* Copy the new buffer offsets back to the user's exec list. */
1960         ret = copy_to_user((struct drm_i915_relocation_entry __user *)
1961                            (uintptr_t) args->buffers_ptr,
1962                            exec_list,
1963                            sizeof(*exec_list) * args->buffer_count);
1964         if (ret)
1965                 DRM_ERROR("failed to copy %d exec entries "
1966                           "back to user (%d)\n",
1967                            args->buffer_count, ret);
1968 err:
1969         if (object_list != NULL) {
1970                 for (i = 0; i < pinned; i++)
1971                         i915_gem_object_unpin(object_list[i]);
1972
1973                 for (i = 0; i < args->buffer_count; i++)
1974                         drm_gem_object_unreference(object_list[i]);
1975         }
1976         mutex_unlock(&dev->struct_mutex);
1977
1978 pre_mutex_err:
1979         drm_free(object_list, sizeof(*object_list) * args->buffer_count,
1980                  DRM_MEM_DRIVER);
1981         drm_free(exec_list, sizeof(*exec_list) * args->buffer_count,
1982                  DRM_MEM_DRIVER);
1983
1984         return ret;
1985 }
1986
1987 int
1988 i915_gem_object_pin(struct drm_gem_object *obj, uint32_t alignment)
1989 {
1990         struct drm_device *dev = obj->dev;
1991         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1992         int ret;
1993
1994         i915_verify_inactive(dev, __FILE__, __LINE__);
1995         if (obj_priv->gtt_space == NULL) {
1996                 ret = i915_gem_object_bind_to_gtt(obj, alignment);
1997                 if (ret != 0) {
1998                         DRM_ERROR("Failure to bind: %d", ret);
1999                         return ret;
2000                 }
2001         }
2002         obj_priv->pin_count++;
2003
2004         /* If the object is not active and not pending a flush,
2005          * remove it from the inactive list
2006          */
2007         if (obj_priv->pin_count == 1) {
2008                 atomic_inc(&dev->pin_count);
2009                 atomic_add(obj->size, &dev->pin_memory);
2010                 if (!obj_priv->active &&
2011                     (obj->write_domain & ~(I915_GEM_DOMAIN_CPU |
2012                                            I915_GEM_DOMAIN_GTT)) == 0 &&
2013                     !list_empty(&obj_priv->list))
2014                         list_del_init(&obj_priv->list);
2015         }
2016         i915_verify_inactive(dev, __FILE__, __LINE__);
2017
2018         return 0;
2019 }
2020
2021 void
2022 i915_gem_object_unpin(struct drm_gem_object *obj)
2023 {
2024         struct drm_device *dev = obj->dev;
2025         drm_i915_private_t *dev_priv = dev->dev_private;
2026         struct drm_i915_gem_object *obj_priv = obj->driver_private;
2027
2028         i915_verify_inactive(dev, __FILE__, __LINE__);
2029         obj_priv->pin_count--;
2030         BUG_ON(obj_priv->pin_count < 0);
2031         BUG_ON(obj_priv->gtt_space == NULL);
2032
2033         /* If the object is no longer pinned, and is
2034          * neither active nor being flushed, then stick it on
2035          * the inactive list
2036          */
2037         if (obj_priv->pin_count == 0) {
2038                 if (!obj_priv->active &&
2039                     (obj->write_domain & ~(I915_GEM_DOMAIN_CPU |
2040                                            I915_GEM_DOMAIN_GTT)) == 0)
2041                         list_move_tail(&obj_priv->list,
2042                                        &dev_priv->mm.inactive_list);
2043                 atomic_dec(&dev->pin_count);
2044                 atomic_sub(obj->size, &dev->pin_memory);
2045         }
2046         i915_verify_inactive(dev, __FILE__, __LINE__);
2047 }
2048
2049 int
2050 i915_gem_pin_ioctl(struct drm_device *dev, void *data,
2051                    struct drm_file *file_priv)
2052 {
2053         struct drm_i915_gem_pin *args = data;
2054         struct drm_gem_object *obj;
2055         struct drm_i915_gem_object *obj_priv;
2056         int ret;
2057
2058         mutex_lock(&dev->struct_mutex);
2059
2060         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
2061         if (obj == NULL) {
2062                 DRM_ERROR("Bad handle in i915_gem_pin_ioctl(): %d\n",
2063                           args->handle);
2064                 mutex_unlock(&dev->struct_mutex);
2065                 return -EBADF;
2066         }
2067         obj_priv = obj->driver_private;
2068
2069         ret = i915_gem_object_pin(obj, args->alignment);
2070         if (ret != 0) {
2071                 drm_gem_object_unreference(obj);
2072                 mutex_unlock(&dev->struct_mutex);
2073                 return ret;
2074         }
2075
2076         /* XXX - flush the CPU caches for pinned objects
2077          * as the X server doesn't manage domains yet
2078          */
2079         if (obj->write_domain & I915_GEM_DOMAIN_CPU) {
2080                 i915_gem_clflush_object(obj);
2081                 drm_agp_chipset_flush(dev);
2082                 obj->write_domain = 0;
2083         }
2084         args->offset = obj_priv->gtt_offset;
2085         drm_gem_object_unreference(obj);
2086         mutex_unlock(&dev->struct_mutex);
2087
2088         return 0;
2089 }
2090
2091 int
2092 i915_gem_unpin_ioctl(struct drm_device *dev, void *data,
2093                      struct drm_file *file_priv)
2094 {
2095         struct drm_i915_gem_pin *args = data;
2096         struct drm_gem_object *obj;
2097
2098         mutex_lock(&dev->struct_mutex);
2099
2100         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
2101         if (obj == NULL) {
2102                 DRM_ERROR("Bad handle in i915_gem_unpin_ioctl(): %d\n",
2103                           args->handle);
2104                 mutex_unlock(&dev->struct_mutex);
2105                 return -EBADF;
2106         }
2107
2108         i915_gem_object_unpin(obj);
2109
2110         drm_gem_object_unreference(obj);
2111         mutex_unlock(&dev->struct_mutex);
2112         return 0;
2113 }
2114
2115 int
2116 i915_gem_busy_ioctl(struct drm_device *dev, void *data,
2117                     struct drm_file *file_priv)
2118 {
2119         struct drm_i915_gem_busy *args = data;
2120         struct drm_gem_object *obj;
2121         struct drm_i915_gem_object *obj_priv;
2122
2123         mutex_lock(&dev->struct_mutex);
2124         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
2125         if (obj == NULL) {
2126                 DRM_ERROR("Bad handle in i915_gem_busy_ioctl(): %d\n",
2127                           args->handle);
2128                 mutex_unlock(&dev->struct_mutex);
2129                 return -EBADF;
2130         }
2131
2132         obj_priv = obj->driver_private;
2133         args->busy = obj_priv->active;
2134
2135         drm_gem_object_unreference(obj);
2136         mutex_unlock(&dev->struct_mutex);
2137         return 0;
2138 }
2139
2140 int
2141 i915_gem_throttle_ioctl(struct drm_device *dev, void *data,
2142                         struct drm_file *file_priv)
2143 {
2144     return i915_gem_ring_throttle(dev, file_priv);
2145 }
2146
2147 int i915_gem_init_object(struct drm_gem_object *obj)
2148 {
2149         struct drm_i915_gem_object *obj_priv;
2150
2151         obj_priv = drm_calloc(1, sizeof(*obj_priv), DRM_MEM_DRIVER);
2152         if (obj_priv == NULL)
2153                 return -ENOMEM;
2154
2155         /*
2156          * We've just allocated pages from the kernel,
2157          * so they've just been written by the CPU with
2158          * zeros. They'll need to be clflushed before we
2159          * use them with the GPU.
2160          */
2161         obj->write_domain = I915_GEM_DOMAIN_CPU;
2162         obj->read_domains = I915_GEM_DOMAIN_CPU;
2163
2164         obj_priv->agp_type = AGP_USER_MEMORY;
2165
2166         obj->driver_private = obj_priv;
2167         obj_priv->obj = obj;
2168         INIT_LIST_HEAD(&obj_priv->list);
2169         return 0;
2170 }
2171
2172 void i915_gem_free_object(struct drm_gem_object *obj)
2173 {
2174         struct drm_i915_gem_object *obj_priv = obj->driver_private;
2175
2176         while (obj_priv->pin_count > 0)
2177                 i915_gem_object_unpin(obj);
2178
2179         i915_gem_object_unbind(obj);
2180
2181         drm_free(obj_priv->page_cpu_valid, 1, DRM_MEM_DRIVER);
2182         drm_free(obj->driver_private, 1, DRM_MEM_DRIVER);
2183 }
2184
2185 static int
2186 i915_gem_set_domain(struct drm_gem_object *obj,
2187                     struct drm_file *file_priv,
2188                     uint32_t read_domains,
2189                     uint32_t write_domain)
2190 {
2191         struct drm_device *dev = obj->dev;
2192         int ret;
2193         uint32_t flush_domains;
2194
2195         BUG_ON(!mutex_is_locked(&dev->struct_mutex));
2196
2197         ret = i915_gem_object_set_domain(obj, read_domains, write_domain);
2198         if (ret)
2199                 return ret;
2200         flush_domains = i915_gem_dev_set_domain(obj->dev);
2201
2202         if (flush_domains & ~(I915_GEM_DOMAIN_CPU|I915_GEM_DOMAIN_GTT))
2203                 (void) i915_add_request(dev, flush_domains);
2204
2205         return 0;
2206 }
2207
2208 /** Unbinds all objects that are on the given buffer list. */
2209 static int
2210 i915_gem_evict_from_list(struct drm_device *dev, struct list_head *head)
2211 {
2212         struct drm_gem_object *obj;
2213         struct drm_i915_gem_object *obj_priv;
2214         int ret;
2215
2216         while (!list_empty(head)) {
2217                 obj_priv = list_first_entry(head,
2218                                             struct drm_i915_gem_object,
2219                                             list);
2220                 obj = obj_priv->obj;
2221
2222                 if (obj_priv->pin_count != 0) {
2223                         DRM_ERROR("Pinned object in unbind list\n");
2224                         mutex_unlock(&dev->struct_mutex);
2225                         return -EINVAL;
2226                 }
2227
2228                 ret = i915_gem_object_unbind(obj);
2229                 if (ret != 0) {
2230                         DRM_ERROR("Error unbinding object in LeaveVT: %d\n",
2231                                   ret);
2232                         mutex_unlock(&dev->struct_mutex);
2233                         return ret;
2234                 }
2235         }
2236
2237
2238         return 0;
2239 }
2240
2241 static int
2242 i915_gem_idle(struct drm_device *dev)
2243 {
2244         drm_i915_private_t *dev_priv = dev->dev_private;
2245         uint32_t seqno, cur_seqno, last_seqno;
2246         int stuck, ret;
2247
2248         mutex_lock(&dev->struct_mutex);
2249
2250         if (dev_priv->mm.suspended || dev_priv->ring.ring_obj == NULL) {
2251                 mutex_unlock(&dev->struct_mutex);
2252                 return 0;
2253         }
2254
2255         /* Hack!  Don't let anybody do execbuf while we don't control the chip.
2256          * We need to replace this with a semaphore, or something.
2257          */
2258         dev_priv->mm.suspended = 1;
2259
2260         /* Cancel the retire work handler, wait for it to finish if running
2261          */
2262         mutex_unlock(&dev->struct_mutex);
2263         cancel_delayed_work_sync(&dev_priv->mm.retire_work);
2264         mutex_lock(&dev->struct_mutex);
2265
2266         i915_kernel_lost_context(dev);
2267
2268         /* Flush the GPU along with all non-CPU write domains
2269          */
2270         i915_gem_flush(dev, ~(I915_GEM_DOMAIN_CPU|I915_GEM_DOMAIN_GTT),
2271                        ~(I915_GEM_DOMAIN_CPU|I915_GEM_DOMAIN_GTT));
2272         seqno = i915_add_request(dev, ~(I915_GEM_DOMAIN_CPU |
2273                                         I915_GEM_DOMAIN_GTT));
2274
2275         if (seqno == 0) {
2276                 mutex_unlock(&dev->struct_mutex);
2277                 return -ENOMEM;
2278         }
2279
2280         dev_priv->mm.waiting_gem_seqno = seqno;
2281         last_seqno = 0;
2282         stuck = 0;
2283         for (;;) {
2284                 cur_seqno = i915_get_gem_seqno(dev);
2285                 if (i915_seqno_passed(cur_seqno, seqno))
2286                         break;
2287                 if (last_seqno == cur_seqno) {
2288                         if (stuck++ > 100) {
2289                                 DRM_ERROR("hardware wedged\n");
2290                                 dev_priv->mm.wedged = 1;
2291                                 DRM_WAKEUP(&dev_priv->irq_queue);
2292                                 break;
2293                         }
2294                 }
2295                 msleep(10);
2296                 last_seqno = cur_seqno;
2297         }
2298         dev_priv->mm.waiting_gem_seqno = 0;
2299
2300         i915_gem_retire_requests(dev);
2301
2302         /* Active and flushing should now be empty as we've
2303          * waited for a sequence higher than any pending execbuffer
2304          */
2305         BUG_ON(!list_empty(&dev_priv->mm.active_list));
2306         BUG_ON(!list_empty(&dev_priv->mm.flushing_list));
2307
2308         /* Request should now be empty as we've also waited
2309          * for the last request in the list
2310          */
2311         BUG_ON(!list_empty(&dev_priv->mm.request_list));
2312
2313         /* Move all buffers out of the GTT. */
2314         ret = i915_gem_evict_from_list(dev, &dev_priv->mm.inactive_list);
2315         if (ret) {
2316                 mutex_unlock(&dev->struct_mutex);
2317                 return ret;
2318         }
2319
2320         BUG_ON(!list_empty(&dev_priv->mm.active_list));
2321         BUG_ON(!list_empty(&dev_priv->mm.flushing_list));
2322         BUG_ON(!list_empty(&dev_priv->mm.inactive_list));
2323         BUG_ON(!list_empty(&dev_priv->mm.request_list));
2324
2325         i915_gem_cleanup_ringbuffer(dev);
2326         mutex_unlock(&dev->struct_mutex);
2327
2328         return 0;
2329 }
2330
2331 static int
2332 i915_gem_init_hws(struct drm_device *dev)
2333 {
2334         drm_i915_private_t *dev_priv = dev->dev_private;
2335         struct drm_gem_object *obj;
2336         struct drm_i915_gem_object *obj_priv;
2337         int ret;
2338
2339         /* If we need a physical address for the status page, it's already
2340          * initialized at driver load time.
2341          */
2342         if (!I915_NEED_GFX_HWS(dev))
2343                 return 0;
2344
2345         obj = drm_gem_object_alloc(dev, 4096);
2346         if (obj == NULL) {
2347                 DRM_ERROR("Failed to allocate status page\n");
2348                 return -ENOMEM;
2349         }
2350         obj_priv = obj->driver_private;
2351         obj_priv->agp_type = AGP_USER_CACHED_MEMORY;
2352
2353         ret = i915_gem_object_pin(obj, 4096);
2354         if (ret != 0) {
2355                 drm_gem_object_unreference(obj);
2356                 return ret;
2357         }
2358
2359         dev_priv->status_gfx_addr = obj_priv->gtt_offset;
2360
2361         dev_priv->hw_status_page = kmap(obj_priv->page_list[0]);
2362         if (dev_priv->hw_status_page == NULL) {
2363                 DRM_ERROR("Failed to map status page.\n");
2364                 memset(&dev_priv->hws_map, 0, sizeof(dev_priv->hws_map));
2365                 drm_gem_object_unreference(obj);
2366                 return -EINVAL;
2367         }
2368         dev_priv->hws_obj = obj;
2369         memset(dev_priv->hw_status_page, 0, PAGE_SIZE);
2370         I915_WRITE(HWS_PGA, dev_priv->status_gfx_addr);
2371         I915_READ(HWS_PGA); /* posting read */
2372         DRM_DEBUG("hws offset: 0x%08x\n", dev_priv->status_gfx_addr);
2373
2374         return 0;
2375 }
2376
2377 static int
2378 i915_gem_init_ringbuffer(struct drm_device *dev)
2379 {
2380         drm_i915_private_t *dev_priv = dev->dev_private;
2381         struct drm_gem_object *obj;
2382         struct drm_i915_gem_object *obj_priv;
2383         int ret;
2384         u32 head;
2385
2386         ret = i915_gem_init_hws(dev);
2387         if (ret != 0)
2388                 return ret;
2389
2390         obj = drm_gem_object_alloc(dev, 128 * 1024);
2391         if (obj == NULL) {
2392                 DRM_ERROR("Failed to allocate ringbuffer\n");
2393                 return -ENOMEM;
2394         }
2395         obj_priv = obj->driver_private;
2396
2397         ret = i915_gem_object_pin(obj, 4096);
2398         if (ret != 0) {
2399                 drm_gem_object_unreference(obj);
2400                 return ret;
2401         }
2402
2403         /* Set up the kernel mapping for the ring. */
2404         dev_priv->ring.Size = obj->size;
2405         dev_priv->ring.tail_mask = obj->size - 1;
2406
2407         dev_priv->ring.map.offset = dev->agp->base + obj_priv->gtt_offset;
2408         dev_priv->ring.map.size = obj->size;
2409         dev_priv->ring.map.type = 0;
2410         dev_priv->ring.map.flags = 0;
2411         dev_priv->ring.map.mtrr = 0;
2412
2413         drm_core_ioremap_wc(&dev_priv->ring.map, dev);
2414         if (dev_priv->ring.map.handle == NULL) {
2415                 DRM_ERROR("Failed to map ringbuffer.\n");
2416                 memset(&dev_priv->ring, 0, sizeof(dev_priv->ring));
2417                 drm_gem_object_unreference(obj);
2418                 return -EINVAL;
2419         }
2420         dev_priv->ring.ring_obj = obj;
2421         dev_priv->ring.virtual_start = dev_priv->ring.map.handle;
2422
2423         /* Stop the ring if it's running. */
2424         I915_WRITE(PRB0_CTL, 0);
2425         I915_WRITE(PRB0_TAIL, 0);
2426         I915_WRITE(PRB0_HEAD, 0);
2427
2428         /* Initialize the ring. */
2429         I915_WRITE(PRB0_START, obj_priv->gtt_offset);
2430         head = I915_READ(PRB0_HEAD) & HEAD_ADDR;
2431
2432         /* G45 ring initialization fails to reset head to zero */
2433         if (head != 0) {
2434                 DRM_ERROR("Ring head not reset to zero "
2435                           "ctl %08x head %08x tail %08x start %08x\n",
2436                           I915_READ(PRB0_CTL),
2437                           I915_READ(PRB0_HEAD),
2438                           I915_READ(PRB0_TAIL),
2439                           I915_READ(PRB0_START));
2440                 I915_WRITE(PRB0_HEAD, 0);
2441
2442                 DRM_ERROR("Ring head forced to zero "
2443                           "ctl %08x head %08x tail %08x start %08x\n",
2444                           I915_READ(PRB0_CTL),
2445                           I915_READ(PRB0_HEAD),
2446                           I915_READ(PRB0_TAIL),
2447                           I915_READ(PRB0_START));
2448         }
2449
2450         I915_WRITE(PRB0_CTL,
2451                    ((obj->size - 4096) & RING_NR_PAGES) |
2452                    RING_NO_REPORT |
2453                    RING_VALID);
2454
2455         head = I915_READ(PRB0_HEAD) & HEAD_ADDR;
2456
2457         /* If the head is still not zero, the ring is dead */
2458         if (head != 0) {
2459                 DRM_ERROR("Ring initialization failed "
2460                           "ctl %08x head %08x tail %08x start %08x\n",
2461                           I915_READ(PRB0_CTL),
2462                           I915_READ(PRB0_HEAD),
2463                           I915_READ(PRB0_TAIL),
2464                           I915_READ(PRB0_START));
2465                 return -EIO;
2466         }
2467
2468         /* Update our cache of the ring state */
2469         i915_kernel_lost_context(dev);
2470
2471         return 0;
2472 }
2473
2474 static void
2475 i915_gem_cleanup_ringbuffer(struct drm_device *dev)
2476 {
2477         drm_i915_private_t *dev_priv = dev->dev_private;
2478
2479         if (dev_priv->ring.ring_obj == NULL)
2480                 return;
2481
2482         drm_core_ioremapfree(&dev_priv->ring.map, dev);
2483
2484         i915_gem_object_unpin(dev_priv->ring.ring_obj);
2485         drm_gem_object_unreference(dev_priv->ring.ring_obj);
2486         dev_priv->ring.ring_obj = NULL;
2487         memset(&dev_priv->ring, 0, sizeof(dev_priv->ring));
2488
2489         if (dev_priv->hws_obj != NULL) {
2490                 struct drm_gem_object *obj = dev_priv->hws_obj;
2491                 struct drm_i915_gem_object *obj_priv = obj->driver_private;
2492
2493                 kunmap(obj_priv->page_list[0]);
2494                 i915_gem_object_unpin(obj);
2495                 drm_gem_object_unreference(obj);
2496                 dev_priv->hws_obj = NULL;
2497                 memset(&dev_priv->hws_map, 0, sizeof(dev_priv->hws_map));
2498                 dev_priv->hw_status_page = NULL;
2499
2500                 /* Write high address into HWS_PGA when disabling. */
2501                 I915_WRITE(HWS_PGA, 0x1ffff000);
2502         }
2503 }
2504
2505 int
2506 i915_gem_entervt_ioctl(struct drm_device *dev, void *data,
2507                        struct drm_file *file_priv)
2508 {
2509         drm_i915_private_t *dev_priv = dev->dev_private;
2510         int ret;
2511
2512         if (dev_priv->mm.wedged) {
2513                 DRM_ERROR("Reenabling wedged hardware, good luck\n");
2514                 dev_priv->mm.wedged = 0;
2515         }
2516
2517         ret = i915_gem_init_ringbuffer(dev);
2518         if (ret != 0)
2519                 return ret;
2520
2521         mutex_lock(&dev->struct_mutex);
2522         BUG_ON(!list_empty(&dev_priv->mm.active_list));
2523         BUG_ON(!list_empty(&dev_priv->mm.flushing_list));
2524         BUG_ON(!list_empty(&dev_priv->mm.inactive_list));
2525         BUG_ON(!list_empty(&dev_priv->mm.request_list));
2526         dev_priv->mm.suspended = 0;
2527         mutex_unlock(&dev->struct_mutex);
2528
2529         drm_irq_install(dev);
2530
2531         return 0;
2532 }
2533
2534 int
2535 i915_gem_leavevt_ioctl(struct drm_device *dev, void *data,
2536                        struct drm_file *file_priv)
2537 {
2538         int ret;
2539
2540         ret = i915_gem_idle(dev);
2541         drm_irq_uninstall(dev);
2542
2543         return ret;
2544 }
2545
2546 void
2547 i915_gem_lastclose(struct drm_device *dev)
2548 {
2549         int ret;
2550
2551         ret = i915_gem_idle(dev);
2552         if (ret)
2553                 DRM_ERROR("failed to idle hardware: %d\n", ret);
2554 }
2555
2556 void
2557 i915_gem_load(struct drm_device *dev)
2558 {
2559         drm_i915_private_t *dev_priv = dev->dev_private;
2560
2561         INIT_LIST_HEAD(&dev_priv->mm.active_list);
2562         INIT_LIST_HEAD(&dev_priv->mm.flushing_list);
2563         INIT_LIST_HEAD(&dev_priv->mm.inactive_list);
2564         INIT_LIST_HEAD(&dev_priv->mm.request_list);
2565         INIT_DELAYED_WORK(&dev_priv->mm.retire_work,
2566                           i915_gem_retire_work_handler);
2567         INIT_WORK(&dev_priv->mm.vblank_work,
2568                   i915_gem_vblank_work_handler);
2569         dev_priv->mm.next_gem_seqno = 1;
2570
2571         i915_gem_detect_bit_6_swizzle(dev);
2572 }