drm/i915: Implement batch and ring buffer dumping
[linux-2.6] / 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 #include <linux/pci.h>
34
35 #define I915_GEM_GPU_DOMAINS    (~(I915_GEM_DOMAIN_CPU | I915_GEM_DOMAIN_GTT))
36
37 static void i915_gem_object_flush_gpu_write_domain(struct drm_gem_object *obj);
38 static void i915_gem_object_flush_gtt_write_domain(struct drm_gem_object *obj);
39 static void i915_gem_object_flush_cpu_write_domain(struct drm_gem_object *obj);
40 static int i915_gem_object_set_to_cpu_domain(struct drm_gem_object *obj,
41                                              int write);
42 static int i915_gem_object_set_cpu_read_domain_range(struct drm_gem_object *obj,
43                                                      uint64_t offset,
44                                                      uint64_t size);
45 static void i915_gem_object_set_to_full_cpu_read_domain(struct drm_gem_object *obj);
46 static int i915_gem_object_wait_rendering(struct drm_gem_object *obj);
47 static int i915_gem_object_bind_to_gtt(struct drm_gem_object *obj,
48                                            unsigned alignment);
49 static int i915_gem_object_get_fence_reg(struct drm_gem_object *obj, bool write);
50 static void i915_gem_clear_fence_reg(struct drm_gem_object *obj);
51 static int i915_gem_evict_something(struct drm_device *dev);
52 static int i915_gem_phys_pwrite(struct drm_device *dev, struct drm_gem_object *obj,
53                                 struct drm_i915_gem_pwrite *args,
54                                 struct drm_file *file_priv);
55
56 int i915_gem_do_init(struct drm_device *dev, unsigned long start,
57                      unsigned long end)
58 {
59         drm_i915_private_t *dev_priv = dev->dev_private;
60
61         if (start >= end ||
62             (start & (PAGE_SIZE - 1)) != 0 ||
63             (end & (PAGE_SIZE - 1)) != 0) {
64                 return -EINVAL;
65         }
66
67         drm_mm_init(&dev_priv->mm.gtt_space, start,
68                     end - start);
69
70         dev->gtt_total = (uint32_t) (end - start);
71
72         return 0;
73 }
74
75 int
76 i915_gem_init_ioctl(struct drm_device *dev, void *data,
77                     struct drm_file *file_priv)
78 {
79         struct drm_i915_gem_init *args = data;
80         int ret;
81
82         mutex_lock(&dev->struct_mutex);
83         ret = i915_gem_do_init(dev, args->gtt_start, args->gtt_end);
84         mutex_unlock(&dev->struct_mutex);
85
86         return ret;
87 }
88
89 int
90 i915_gem_get_aperture_ioctl(struct drm_device *dev, void *data,
91                             struct drm_file *file_priv)
92 {
93         struct drm_i915_gem_get_aperture *args = data;
94
95         if (!(dev->driver->driver_features & DRIVER_GEM))
96                 return -ENODEV;
97
98         args->aper_size = dev->gtt_total;
99         args->aper_available_size = (args->aper_size -
100                                      atomic_read(&dev->pin_memory));
101
102         return 0;
103 }
104
105
106 /**
107  * Creates a new mm object and returns a handle to it.
108  */
109 int
110 i915_gem_create_ioctl(struct drm_device *dev, void *data,
111                       struct drm_file *file_priv)
112 {
113         struct drm_i915_gem_create *args = data;
114         struct drm_gem_object *obj;
115         int handle, ret;
116
117         args->size = roundup(args->size, PAGE_SIZE);
118
119         /* Allocate the new object */
120         obj = drm_gem_object_alloc(dev, args->size);
121         if (obj == NULL)
122                 return -ENOMEM;
123
124         ret = drm_gem_handle_create(file_priv, obj, &handle);
125         mutex_lock(&dev->struct_mutex);
126         drm_gem_object_handle_unreference(obj);
127         mutex_unlock(&dev->struct_mutex);
128
129         if (ret)
130                 return ret;
131
132         args->handle = handle;
133
134         return 0;
135 }
136
137 static inline int
138 fast_shmem_read(struct page **pages,
139                 loff_t page_base, int page_offset,
140                 char __user *data,
141                 int length)
142 {
143         char __iomem *vaddr;
144         int ret;
145
146         vaddr = kmap_atomic(pages[page_base >> PAGE_SHIFT], KM_USER0);
147         if (vaddr == NULL)
148                 return -ENOMEM;
149         ret = __copy_to_user_inatomic(data, vaddr + page_offset, length);
150         kunmap_atomic(vaddr, KM_USER0);
151
152         return ret;
153 }
154
155 static inline int
156 slow_shmem_copy(struct page *dst_page,
157                 int dst_offset,
158                 struct page *src_page,
159                 int src_offset,
160                 int length)
161 {
162         char *dst_vaddr, *src_vaddr;
163
164         dst_vaddr = kmap_atomic(dst_page, KM_USER0);
165         if (dst_vaddr == NULL)
166                 return -ENOMEM;
167
168         src_vaddr = kmap_atomic(src_page, KM_USER1);
169         if (src_vaddr == NULL) {
170                 kunmap_atomic(dst_vaddr, KM_USER0);
171                 return -ENOMEM;
172         }
173
174         memcpy(dst_vaddr + dst_offset, src_vaddr + src_offset, length);
175
176         kunmap_atomic(src_vaddr, KM_USER1);
177         kunmap_atomic(dst_vaddr, KM_USER0);
178
179         return 0;
180 }
181
182 /**
183  * This is the fast shmem pread path, which attempts to copy_from_user directly
184  * from the backing pages of the object to the user's address space.  On a
185  * fault, it fails so we can fall back to i915_gem_shmem_pwrite_slow().
186  */
187 static int
188 i915_gem_shmem_pread_fast(struct drm_device *dev, struct drm_gem_object *obj,
189                           struct drm_i915_gem_pread *args,
190                           struct drm_file *file_priv)
191 {
192         struct drm_i915_gem_object *obj_priv = obj->driver_private;
193         ssize_t remain;
194         loff_t offset, page_base;
195         char __user *user_data;
196         int page_offset, page_length;
197         int ret;
198
199         user_data = (char __user *) (uintptr_t) args->data_ptr;
200         remain = args->size;
201
202         mutex_lock(&dev->struct_mutex);
203
204         ret = i915_gem_object_get_pages(obj);
205         if (ret != 0)
206                 goto fail_unlock;
207
208         ret = i915_gem_object_set_cpu_read_domain_range(obj, args->offset,
209                                                         args->size);
210         if (ret != 0)
211                 goto fail_put_pages;
212
213         obj_priv = obj->driver_private;
214         offset = args->offset;
215
216         while (remain > 0) {
217                 /* Operation in this page
218                  *
219                  * page_base = page offset within aperture
220                  * page_offset = offset within page
221                  * page_length = bytes to copy for this page
222                  */
223                 page_base = (offset & ~(PAGE_SIZE-1));
224                 page_offset = offset & (PAGE_SIZE-1);
225                 page_length = remain;
226                 if ((page_offset + remain) > PAGE_SIZE)
227                         page_length = PAGE_SIZE - page_offset;
228
229                 ret = fast_shmem_read(obj_priv->pages,
230                                       page_base, page_offset,
231                                       user_data, page_length);
232                 if (ret)
233                         goto fail_put_pages;
234
235                 remain -= page_length;
236                 user_data += page_length;
237                 offset += page_length;
238         }
239
240 fail_put_pages:
241         i915_gem_object_put_pages(obj);
242 fail_unlock:
243         mutex_unlock(&dev->struct_mutex);
244
245         return ret;
246 }
247
248 /**
249  * This is the fallback shmem pread path, which allocates temporary storage
250  * in kernel space to copy_to_user into outside of the struct_mutex, so we
251  * can copy out of the object's backing pages while holding the struct mutex
252  * and not take page faults.
253  */
254 static int
255 i915_gem_shmem_pread_slow(struct drm_device *dev, struct drm_gem_object *obj,
256                           struct drm_i915_gem_pread *args,
257                           struct drm_file *file_priv)
258 {
259         struct drm_i915_gem_object *obj_priv = obj->driver_private;
260         struct mm_struct *mm = current->mm;
261         struct page **user_pages;
262         ssize_t remain;
263         loff_t offset, pinned_pages, i;
264         loff_t first_data_page, last_data_page, num_pages;
265         int shmem_page_index, shmem_page_offset;
266         int data_page_index,  data_page_offset;
267         int page_length;
268         int ret;
269         uint64_t data_ptr = args->data_ptr;
270
271         remain = args->size;
272
273         /* Pin the user pages containing the data.  We can't fault while
274          * holding the struct mutex, yet we want to hold it while
275          * dereferencing the user data.
276          */
277         first_data_page = data_ptr / PAGE_SIZE;
278         last_data_page = (data_ptr + args->size - 1) / PAGE_SIZE;
279         num_pages = last_data_page - first_data_page + 1;
280
281         user_pages = kcalloc(num_pages, sizeof(struct page *), GFP_KERNEL);
282         if (user_pages == NULL)
283                 return -ENOMEM;
284
285         down_read(&mm->mmap_sem);
286         pinned_pages = get_user_pages(current, mm, (uintptr_t)args->data_ptr,
287                                       num_pages, 0, 0, user_pages, NULL);
288         up_read(&mm->mmap_sem);
289         if (pinned_pages < num_pages) {
290                 ret = -EFAULT;
291                 goto fail_put_user_pages;
292         }
293
294         mutex_lock(&dev->struct_mutex);
295
296         ret = i915_gem_object_get_pages(obj);
297         if (ret != 0)
298                 goto fail_unlock;
299
300         ret = i915_gem_object_set_cpu_read_domain_range(obj, args->offset,
301                                                         args->size);
302         if (ret != 0)
303                 goto fail_put_pages;
304
305         obj_priv = obj->driver_private;
306         offset = args->offset;
307
308         while (remain > 0) {
309                 /* Operation in this page
310                  *
311                  * shmem_page_index = page number within shmem file
312                  * shmem_page_offset = offset within page in shmem file
313                  * data_page_index = page number in get_user_pages return
314                  * data_page_offset = offset with data_page_index page.
315                  * page_length = bytes to copy for this page
316                  */
317                 shmem_page_index = offset / PAGE_SIZE;
318                 shmem_page_offset = offset & ~PAGE_MASK;
319                 data_page_index = data_ptr / PAGE_SIZE - first_data_page;
320                 data_page_offset = data_ptr & ~PAGE_MASK;
321
322                 page_length = remain;
323                 if ((shmem_page_offset + page_length) > PAGE_SIZE)
324                         page_length = PAGE_SIZE - shmem_page_offset;
325                 if ((data_page_offset + page_length) > PAGE_SIZE)
326                         page_length = PAGE_SIZE - data_page_offset;
327
328                 ret = slow_shmem_copy(user_pages[data_page_index],
329                                       data_page_offset,
330                                       obj_priv->pages[shmem_page_index],
331                                       shmem_page_offset,
332                                       page_length);
333                 if (ret)
334                         goto fail_put_pages;
335
336                 remain -= page_length;
337                 data_ptr += page_length;
338                 offset += page_length;
339         }
340
341 fail_put_pages:
342         i915_gem_object_put_pages(obj);
343 fail_unlock:
344         mutex_unlock(&dev->struct_mutex);
345 fail_put_user_pages:
346         for (i = 0; i < pinned_pages; i++) {
347                 SetPageDirty(user_pages[i]);
348                 page_cache_release(user_pages[i]);
349         }
350         kfree(user_pages);
351
352         return ret;
353 }
354
355 /**
356  * Reads data from the object referenced by handle.
357  *
358  * On error, the contents of *data are undefined.
359  */
360 int
361 i915_gem_pread_ioctl(struct drm_device *dev, void *data,
362                      struct drm_file *file_priv)
363 {
364         struct drm_i915_gem_pread *args = data;
365         struct drm_gem_object *obj;
366         struct drm_i915_gem_object *obj_priv;
367         int ret;
368
369         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
370         if (obj == NULL)
371                 return -EBADF;
372         obj_priv = obj->driver_private;
373
374         /* Bounds check source.
375          *
376          * XXX: This could use review for overflow issues...
377          */
378         if (args->offset > obj->size || args->size > obj->size ||
379             args->offset + args->size > obj->size) {
380                 drm_gem_object_unreference(obj);
381                 return -EINVAL;
382         }
383
384         ret = i915_gem_shmem_pread_fast(dev, obj, args, file_priv);
385         if (ret != 0)
386                 ret = i915_gem_shmem_pread_slow(dev, obj, args, file_priv);
387
388         drm_gem_object_unreference(obj);
389
390         return ret;
391 }
392
393 /* This is the fast write path which cannot handle
394  * page faults in the source data
395  */
396
397 static inline int
398 fast_user_write(struct io_mapping *mapping,
399                 loff_t page_base, int page_offset,
400                 char __user *user_data,
401                 int length)
402 {
403         char *vaddr_atomic;
404         unsigned long unwritten;
405
406         vaddr_atomic = io_mapping_map_atomic_wc(mapping, page_base);
407         unwritten = __copy_from_user_inatomic_nocache(vaddr_atomic + page_offset,
408                                                       user_data, length);
409         io_mapping_unmap_atomic(vaddr_atomic);
410         if (unwritten)
411                 return -EFAULT;
412         return 0;
413 }
414
415 /* Here's the write path which can sleep for
416  * page faults
417  */
418
419 static inline int
420 slow_kernel_write(struct io_mapping *mapping,
421                   loff_t gtt_base, int gtt_offset,
422                   struct page *user_page, int user_offset,
423                   int length)
424 {
425         char *src_vaddr, *dst_vaddr;
426         unsigned long unwritten;
427
428         dst_vaddr = io_mapping_map_atomic_wc(mapping, gtt_base);
429         src_vaddr = kmap_atomic(user_page, KM_USER1);
430         unwritten = __copy_from_user_inatomic_nocache(dst_vaddr + gtt_offset,
431                                                       src_vaddr + user_offset,
432                                                       length);
433         kunmap_atomic(src_vaddr, KM_USER1);
434         io_mapping_unmap_atomic(dst_vaddr);
435         if (unwritten)
436                 return -EFAULT;
437         return 0;
438 }
439
440 static inline int
441 fast_shmem_write(struct page **pages,
442                  loff_t page_base, int page_offset,
443                  char __user *data,
444                  int length)
445 {
446         char __iomem *vaddr;
447         unsigned long unwritten;
448
449         vaddr = kmap_atomic(pages[page_base >> PAGE_SHIFT], KM_USER0);
450         if (vaddr == NULL)
451                 return -ENOMEM;
452         unwritten = __copy_from_user_inatomic(vaddr + page_offset, data, length);
453         kunmap_atomic(vaddr, KM_USER0);
454
455         if (unwritten)
456                 return -EFAULT;
457         return 0;
458 }
459
460 /**
461  * This is the fast pwrite path, where we copy the data directly from the
462  * user into the GTT, uncached.
463  */
464 static int
465 i915_gem_gtt_pwrite_fast(struct drm_device *dev, struct drm_gem_object *obj,
466                          struct drm_i915_gem_pwrite *args,
467                          struct drm_file *file_priv)
468 {
469         struct drm_i915_gem_object *obj_priv = obj->driver_private;
470         drm_i915_private_t *dev_priv = dev->dev_private;
471         ssize_t remain;
472         loff_t offset, page_base;
473         char __user *user_data;
474         int page_offset, page_length;
475         int ret;
476
477         user_data = (char __user *) (uintptr_t) args->data_ptr;
478         remain = args->size;
479         if (!access_ok(VERIFY_READ, user_data, remain))
480                 return -EFAULT;
481
482
483         mutex_lock(&dev->struct_mutex);
484         ret = i915_gem_object_pin(obj, 0);
485         if (ret) {
486                 mutex_unlock(&dev->struct_mutex);
487                 return ret;
488         }
489         ret = i915_gem_object_set_to_gtt_domain(obj, 1);
490         if (ret)
491                 goto fail;
492
493         obj_priv = obj->driver_private;
494         offset = obj_priv->gtt_offset + args->offset;
495
496         while (remain > 0) {
497                 /* Operation in this page
498                  *
499                  * page_base = page offset within aperture
500                  * page_offset = offset within page
501                  * page_length = bytes to copy for this page
502                  */
503                 page_base = (offset & ~(PAGE_SIZE-1));
504                 page_offset = offset & (PAGE_SIZE-1);
505                 page_length = remain;
506                 if ((page_offset + remain) > PAGE_SIZE)
507                         page_length = PAGE_SIZE - page_offset;
508
509                 ret = fast_user_write (dev_priv->mm.gtt_mapping, page_base,
510                                        page_offset, user_data, page_length);
511
512                 /* If we get a fault while copying data, then (presumably) our
513                  * source page isn't available.  Return the error and we'll
514                  * retry in the slow path.
515                  */
516                 if (ret)
517                         goto fail;
518
519                 remain -= page_length;
520                 user_data += page_length;
521                 offset += page_length;
522         }
523
524 fail:
525         i915_gem_object_unpin(obj);
526         mutex_unlock(&dev->struct_mutex);
527
528         return ret;
529 }
530
531 /**
532  * This is the fallback GTT pwrite path, which uses get_user_pages to pin
533  * the memory and maps it using kmap_atomic for copying.
534  *
535  * This code resulted in x11perf -rgb10text consuming about 10% more CPU
536  * than using i915_gem_gtt_pwrite_fast on a G45 (32-bit).
537  */
538 static int
539 i915_gem_gtt_pwrite_slow(struct drm_device *dev, struct drm_gem_object *obj,
540                          struct drm_i915_gem_pwrite *args,
541                          struct drm_file *file_priv)
542 {
543         struct drm_i915_gem_object *obj_priv = obj->driver_private;
544         drm_i915_private_t *dev_priv = dev->dev_private;
545         ssize_t remain;
546         loff_t gtt_page_base, offset;
547         loff_t first_data_page, last_data_page, num_pages;
548         loff_t pinned_pages, i;
549         struct page **user_pages;
550         struct mm_struct *mm = current->mm;
551         int gtt_page_offset, data_page_offset, data_page_index, page_length;
552         int ret;
553         uint64_t data_ptr = args->data_ptr;
554
555         remain = args->size;
556
557         /* Pin the user pages containing the data.  We can't fault while
558          * holding the struct mutex, and all of the pwrite implementations
559          * want to hold it while dereferencing the user data.
560          */
561         first_data_page = data_ptr / PAGE_SIZE;
562         last_data_page = (data_ptr + args->size - 1) / PAGE_SIZE;
563         num_pages = last_data_page - first_data_page + 1;
564
565         user_pages = kcalloc(num_pages, sizeof(struct page *), GFP_KERNEL);
566         if (user_pages == NULL)
567                 return -ENOMEM;
568
569         down_read(&mm->mmap_sem);
570         pinned_pages = get_user_pages(current, mm, (uintptr_t)args->data_ptr,
571                                       num_pages, 0, 0, user_pages, NULL);
572         up_read(&mm->mmap_sem);
573         if (pinned_pages < num_pages) {
574                 ret = -EFAULT;
575                 goto out_unpin_pages;
576         }
577
578         mutex_lock(&dev->struct_mutex);
579         ret = i915_gem_object_pin(obj, 0);
580         if (ret)
581                 goto out_unlock;
582
583         ret = i915_gem_object_set_to_gtt_domain(obj, 1);
584         if (ret)
585                 goto out_unpin_object;
586
587         obj_priv = obj->driver_private;
588         offset = obj_priv->gtt_offset + args->offset;
589
590         while (remain > 0) {
591                 /* Operation in this page
592                  *
593                  * gtt_page_base = page offset within aperture
594                  * gtt_page_offset = offset within page in aperture
595                  * data_page_index = page number in get_user_pages return
596                  * data_page_offset = offset with data_page_index page.
597                  * page_length = bytes to copy for this page
598                  */
599                 gtt_page_base = offset & PAGE_MASK;
600                 gtt_page_offset = offset & ~PAGE_MASK;
601                 data_page_index = data_ptr / PAGE_SIZE - first_data_page;
602                 data_page_offset = data_ptr & ~PAGE_MASK;
603
604                 page_length = remain;
605                 if ((gtt_page_offset + page_length) > PAGE_SIZE)
606                         page_length = PAGE_SIZE - gtt_page_offset;
607                 if ((data_page_offset + page_length) > PAGE_SIZE)
608                         page_length = PAGE_SIZE - data_page_offset;
609
610                 ret = slow_kernel_write(dev_priv->mm.gtt_mapping,
611                                         gtt_page_base, gtt_page_offset,
612                                         user_pages[data_page_index],
613                                         data_page_offset,
614                                         page_length);
615
616                 /* If we get a fault while copying data, then (presumably) our
617                  * source page isn't available.  Return the error and we'll
618                  * retry in the slow path.
619                  */
620                 if (ret)
621                         goto out_unpin_object;
622
623                 remain -= page_length;
624                 offset += page_length;
625                 data_ptr += page_length;
626         }
627
628 out_unpin_object:
629         i915_gem_object_unpin(obj);
630 out_unlock:
631         mutex_unlock(&dev->struct_mutex);
632 out_unpin_pages:
633         for (i = 0; i < pinned_pages; i++)
634                 page_cache_release(user_pages[i]);
635         kfree(user_pages);
636
637         return ret;
638 }
639
640 /**
641  * This is the fast shmem pwrite path, which attempts to directly
642  * copy_from_user into the kmapped pages backing the object.
643  */
644 static int
645 i915_gem_shmem_pwrite_fast(struct drm_device *dev, struct drm_gem_object *obj,
646                            struct drm_i915_gem_pwrite *args,
647                            struct drm_file *file_priv)
648 {
649         struct drm_i915_gem_object *obj_priv = obj->driver_private;
650         ssize_t remain;
651         loff_t offset, page_base;
652         char __user *user_data;
653         int page_offset, page_length;
654         int ret;
655
656         user_data = (char __user *) (uintptr_t) args->data_ptr;
657         remain = args->size;
658
659         mutex_lock(&dev->struct_mutex);
660
661         ret = i915_gem_object_get_pages(obj);
662         if (ret != 0)
663                 goto fail_unlock;
664
665         ret = i915_gem_object_set_to_cpu_domain(obj, 1);
666         if (ret != 0)
667                 goto fail_put_pages;
668
669         obj_priv = obj->driver_private;
670         offset = args->offset;
671         obj_priv->dirty = 1;
672
673         while (remain > 0) {
674                 /* Operation in this page
675                  *
676                  * page_base = page offset within aperture
677                  * page_offset = offset within page
678                  * page_length = bytes to copy for this page
679                  */
680                 page_base = (offset & ~(PAGE_SIZE-1));
681                 page_offset = offset & (PAGE_SIZE-1);
682                 page_length = remain;
683                 if ((page_offset + remain) > PAGE_SIZE)
684                         page_length = PAGE_SIZE - page_offset;
685
686                 ret = fast_shmem_write(obj_priv->pages,
687                                        page_base, page_offset,
688                                        user_data, page_length);
689                 if (ret)
690                         goto fail_put_pages;
691
692                 remain -= page_length;
693                 user_data += page_length;
694                 offset += page_length;
695         }
696
697 fail_put_pages:
698         i915_gem_object_put_pages(obj);
699 fail_unlock:
700         mutex_unlock(&dev->struct_mutex);
701
702         return ret;
703 }
704
705 /**
706  * This is the fallback shmem pwrite path, which uses get_user_pages to pin
707  * the memory and maps it using kmap_atomic for copying.
708  *
709  * This avoids taking mmap_sem for faulting on the user's address while the
710  * struct_mutex is held.
711  */
712 static int
713 i915_gem_shmem_pwrite_slow(struct drm_device *dev, struct drm_gem_object *obj,
714                            struct drm_i915_gem_pwrite *args,
715                            struct drm_file *file_priv)
716 {
717         struct drm_i915_gem_object *obj_priv = obj->driver_private;
718         struct mm_struct *mm = current->mm;
719         struct page **user_pages;
720         ssize_t remain;
721         loff_t offset, pinned_pages, i;
722         loff_t first_data_page, last_data_page, num_pages;
723         int shmem_page_index, shmem_page_offset;
724         int data_page_index,  data_page_offset;
725         int page_length;
726         int ret;
727         uint64_t data_ptr = args->data_ptr;
728
729         remain = args->size;
730
731         /* Pin the user pages containing the data.  We can't fault while
732          * holding the struct mutex, and all of the pwrite implementations
733          * want to hold it while dereferencing the user data.
734          */
735         first_data_page = data_ptr / PAGE_SIZE;
736         last_data_page = (data_ptr + args->size - 1) / PAGE_SIZE;
737         num_pages = last_data_page - first_data_page + 1;
738
739         user_pages = kcalloc(num_pages, sizeof(struct page *), GFP_KERNEL);
740         if (user_pages == NULL)
741                 return -ENOMEM;
742
743         down_read(&mm->mmap_sem);
744         pinned_pages = get_user_pages(current, mm, (uintptr_t)args->data_ptr,
745                                       num_pages, 0, 0, user_pages, NULL);
746         up_read(&mm->mmap_sem);
747         if (pinned_pages < num_pages) {
748                 ret = -EFAULT;
749                 goto fail_put_user_pages;
750         }
751
752         mutex_lock(&dev->struct_mutex);
753
754         ret = i915_gem_object_get_pages(obj);
755         if (ret != 0)
756                 goto fail_unlock;
757
758         ret = i915_gem_object_set_to_cpu_domain(obj, 1);
759         if (ret != 0)
760                 goto fail_put_pages;
761
762         obj_priv = obj->driver_private;
763         offset = args->offset;
764         obj_priv->dirty = 1;
765
766         while (remain > 0) {
767                 /* Operation in this page
768                  *
769                  * shmem_page_index = page number within shmem file
770                  * shmem_page_offset = offset within page in shmem file
771                  * data_page_index = page number in get_user_pages return
772                  * data_page_offset = offset with data_page_index page.
773                  * page_length = bytes to copy for this page
774                  */
775                 shmem_page_index = offset / PAGE_SIZE;
776                 shmem_page_offset = offset & ~PAGE_MASK;
777                 data_page_index = data_ptr / PAGE_SIZE - first_data_page;
778                 data_page_offset = data_ptr & ~PAGE_MASK;
779
780                 page_length = remain;
781                 if ((shmem_page_offset + page_length) > PAGE_SIZE)
782                         page_length = PAGE_SIZE - shmem_page_offset;
783                 if ((data_page_offset + page_length) > PAGE_SIZE)
784                         page_length = PAGE_SIZE - data_page_offset;
785
786                 ret = slow_shmem_copy(obj_priv->pages[shmem_page_index],
787                                       shmem_page_offset,
788                                       user_pages[data_page_index],
789                                       data_page_offset,
790                                       page_length);
791                 if (ret)
792                         goto fail_put_pages;
793
794                 remain -= page_length;
795                 data_ptr += page_length;
796                 offset += page_length;
797         }
798
799 fail_put_pages:
800         i915_gem_object_put_pages(obj);
801 fail_unlock:
802         mutex_unlock(&dev->struct_mutex);
803 fail_put_user_pages:
804         for (i = 0; i < pinned_pages; i++)
805                 page_cache_release(user_pages[i]);
806         kfree(user_pages);
807
808         return ret;
809 }
810
811 /**
812  * Writes data to the object referenced by handle.
813  *
814  * On error, the contents of the buffer that were to be modified are undefined.
815  */
816 int
817 i915_gem_pwrite_ioctl(struct drm_device *dev, void *data,
818                       struct drm_file *file_priv)
819 {
820         struct drm_i915_gem_pwrite *args = data;
821         struct drm_gem_object *obj;
822         struct drm_i915_gem_object *obj_priv;
823         int ret = 0;
824
825         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
826         if (obj == NULL)
827                 return -EBADF;
828         obj_priv = obj->driver_private;
829
830         /* Bounds check destination.
831          *
832          * XXX: This could use review for overflow issues...
833          */
834         if (args->offset > obj->size || args->size > obj->size ||
835             args->offset + args->size > obj->size) {
836                 drm_gem_object_unreference(obj);
837                 return -EINVAL;
838         }
839
840         /* We can only do the GTT pwrite on untiled buffers, as otherwise
841          * it would end up going through the fenced access, and we'll get
842          * different detiling behavior between reading and writing.
843          * pread/pwrite currently are reading and writing from the CPU
844          * perspective, requiring manual detiling by the client.
845          */
846         if (obj_priv->phys_obj)
847                 ret = i915_gem_phys_pwrite(dev, obj, args, file_priv);
848         else if (obj_priv->tiling_mode == I915_TILING_NONE &&
849                  dev->gtt_total != 0) {
850                 ret = i915_gem_gtt_pwrite_fast(dev, obj, args, file_priv);
851                 if (ret == -EFAULT) {
852                         ret = i915_gem_gtt_pwrite_slow(dev, obj, args,
853                                                        file_priv);
854                 }
855         } else {
856                 ret = i915_gem_shmem_pwrite_fast(dev, obj, args, file_priv);
857                 if (ret == -EFAULT) {
858                         ret = i915_gem_shmem_pwrite_slow(dev, obj, args,
859                                                          file_priv);
860                 }
861         }
862
863 #if WATCH_PWRITE
864         if (ret)
865                 DRM_INFO("pwrite failed %d\n", ret);
866 #endif
867
868         drm_gem_object_unreference(obj);
869
870         return ret;
871 }
872
873 /**
874  * Called when user space prepares to use an object with the CPU, either
875  * through the mmap ioctl's mapping or a GTT mapping.
876  */
877 int
878 i915_gem_set_domain_ioctl(struct drm_device *dev, void *data,
879                           struct drm_file *file_priv)
880 {
881         struct drm_i915_gem_set_domain *args = data;
882         struct drm_gem_object *obj;
883         uint32_t read_domains = args->read_domains;
884         uint32_t write_domain = args->write_domain;
885         int ret;
886
887         if (!(dev->driver->driver_features & DRIVER_GEM))
888                 return -ENODEV;
889
890         /* Only handle setting domains to types used by the CPU. */
891         if (write_domain & ~(I915_GEM_DOMAIN_CPU | I915_GEM_DOMAIN_GTT))
892                 return -EINVAL;
893
894         if (read_domains & ~(I915_GEM_DOMAIN_CPU | I915_GEM_DOMAIN_GTT))
895                 return -EINVAL;
896
897         /* Having something in the write domain implies it's in the read
898          * domain, and only that read domain.  Enforce that in the request.
899          */
900         if (write_domain != 0 && read_domains != write_domain)
901                 return -EINVAL;
902
903         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
904         if (obj == NULL)
905                 return -EBADF;
906
907         mutex_lock(&dev->struct_mutex);
908 #if WATCH_BUF
909         DRM_INFO("set_domain_ioctl %p(%d), %08x %08x\n",
910                  obj, obj->size, read_domains, write_domain);
911 #endif
912         if (read_domains & I915_GEM_DOMAIN_GTT) {
913                 ret = i915_gem_object_set_to_gtt_domain(obj, write_domain != 0);
914
915                 /* Silently promote "you're not bound, there was nothing to do"
916                  * to success, since the client was just asking us to
917                  * make sure everything was done.
918                  */
919                 if (ret == -EINVAL)
920                         ret = 0;
921         } else {
922                 ret = i915_gem_object_set_to_cpu_domain(obj, write_domain != 0);
923         }
924
925         drm_gem_object_unreference(obj);
926         mutex_unlock(&dev->struct_mutex);
927         return ret;
928 }
929
930 /**
931  * Called when user space has done writes to this buffer
932  */
933 int
934 i915_gem_sw_finish_ioctl(struct drm_device *dev, void *data,
935                       struct drm_file *file_priv)
936 {
937         struct drm_i915_gem_sw_finish *args = data;
938         struct drm_gem_object *obj;
939         struct drm_i915_gem_object *obj_priv;
940         int ret = 0;
941
942         if (!(dev->driver->driver_features & DRIVER_GEM))
943                 return -ENODEV;
944
945         mutex_lock(&dev->struct_mutex);
946         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
947         if (obj == NULL) {
948                 mutex_unlock(&dev->struct_mutex);
949                 return -EBADF;
950         }
951
952 #if WATCH_BUF
953         DRM_INFO("%s: sw_finish %d (%p %d)\n",
954                  __func__, args->handle, obj, obj->size);
955 #endif
956         obj_priv = obj->driver_private;
957
958         /* Pinned buffers may be scanout, so flush the cache */
959         if (obj_priv->pin_count)
960                 i915_gem_object_flush_cpu_write_domain(obj);
961
962         drm_gem_object_unreference(obj);
963         mutex_unlock(&dev->struct_mutex);
964         return ret;
965 }
966
967 /**
968  * Maps the contents of an object, returning the address it is mapped
969  * into.
970  *
971  * While the mapping holds a reference on the contents of the object, it doesn't
972  * imply a ref on the object itself.
973  */
974 int
975 i915_gem_mmap_ioctl(struct drm_device *dev, void *data,
976                    struct drm_file *file_priv)
977 {
978         struct drm_i915_gem_mmap *args = data;
979         struct drm_gem_object *obj;
980         loff_t offset;
981         unsigned long addr;
982
983         if (!(dev->driver->driver_features & DRIVER_GEM))
984                 return -ENODEV;
985
986         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
987         if (obj == NULL)
988                 return -EBADF;
989
990         offset = args->offset;
991
992         down_write(&current->mm->mmap_sem);
993         addr = do_mmap(obj->filp, 0, args->size,
994                        PROT_READ | PROT_WRITE, MAP_SHARED,
995                        args->offset);
996         up_write(&current->mm->mmap_sem);
997         mutex_lock(&dev->struct_mutex);
998         drm_gem_object_unreference(obj);
999         mutex_unlock(&dev->struct_mutex);
1000         if (IS_ERR((void *)addr))
1001                 return addr;
1002
1003         args->addr_ptr = (uint64_t) addr;
1004
1005         return 0;
1006 }
1007
1008 /**
1009  * i915_gem_fault - fault a page into the GTT
1010  * vma: VMA in question
1011  * vmf: fault info
1012  *
1013  * The fault handler is set up by drm_gem_mmap() when a object is GTT mapped
1014  * from userspace.  The fault handler takes care of binding the object to
1015  * the GTT (if needed), allocating and programming a fence register (again,
1016  * only if needed based on whether the old reg is still valid or the object
1017  * is tiled) and inserting a new PTE into the faulting process.
1018  *
1019  * Note that the faulting process may involve evicting existing objects
1020  * from the GTT and/or fence registers to make room.  So performance may
1021  * suffer if the GTT working set is large or there are few fence registers
1022  * left.
1023  */
1024 int i915_gem_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1025 {
1026         struct drm_gem_object *obj = vma->vm_private_data;
1027         struct drm_device *dev = obj->dev;
1028         struct drm_i915_private *dev_priv = dev->dev_private;
1029         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1030         pgoff_t page_offset;
1031         unsigned long pfn;
1032         int ret = 0;
1033         bool write = !!(vmf->flags & FAULT_FLAG_WRITE);
1034
1035         /* We don't use vmf->pgoff since that has the fake offset */
1036         page_offset = ((unsigned long)vmf->virtual_address - vma->vm_start) >>
1037                 PAGE_SHIFT;
1038
1039         /* Now bind it into the GTT if needed */
1040         mutex_lock(&dev->struct_mutex);
1041         if (!obj_priv->gtt_space) {
1042                 ret = i915_gem_object_bind_to_gtt(obj, obj_priv->gtt_alignment);
1043                 if (ret) {
1044                         mutex_unlock(&dev->struct_mutex);
1045                         return VM_FAULT_SIGBUS;
1046                 }
1047                 list_add(&obj_priv->list, &dev_priv->mm.inactive_list);
1048         }
1049
1050         /* Need a new fence register? */
1051         if (obj_priv->fence_reg == I915_FENCE_REG_NONE &&
1052             obj_priv->tiling_mode != I915_TILING_NONE) {
1053                 ret = i915_gem_object_get_fence_reg(obj, write);
1054                 if (ret) {
1055                         mutex_unlock(&dev->struct_mutex);
1056                         return VM_FAULT_SIGBUS;
1057                 }
1058         }
1059
1060         pfn = ((dev->agp->base + obj_priv->gtt_offset) >> PAGE_SHIFT) +
1061                 page_offset;
1062
1063         /* Finally, remap it using the new GTT offset */
1064         ret = vm_insert_pfn(vma, (unsigned long)vmf->virtual_address, pfn);
1065
1066         mutex_unlock(&dev->struct_mutex);
1067
1068         switch (ret) {
1069         case -ENOMEM:
1070         case -EAGAIN:
1071                 return VM_FAULT_OOM;
1072         case -EFAULT:
1073         case -EINVAL:
1074                 return VM_FAULT_SIGBUS;
1075         default:
1076                 return VM_FAULT_NOPAGE;
1077         }
1078 }
1079
1080 /**
1081  * i915_gem_create_mmap_offset - create a fake mmap offset for an object
1082  * @obj: obj in question
1083  *
1084  * GEM memory mapping works by handing back to userspace a fake mmap offset
1085  * it can use in a subsequent mmap(2) call.  The DRM core code then looks
1086  * up the object based on the offset and sets up the various memory mapping
1087  * structures.
1088  *
1089  * This routine allocates and attaches a fake offset for @obj.
1090  */
1091 static int
1092 i915_gem_create_mmap_offset(struct drm_gem_object *obj)
1093 {
1094         struct drm_device *dev = obj->dev;
1095         struct drm_gem_mm *mm = dev->mm_private;
1096         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1097         struct drm_map_list *list;
1098         struct drm_local_map *map;
1099         int ret = 0;
1100
1101         /* Set the object up for mmap'ing */
1102         list = &obj->map_list;
1103         list->map = drm_calloc(1, sizeof(struct drm_map_list),
1104                                DRM_MEM_DRIVER);
1105         if (!list->map)
1106                 return -ENOMEM;
1107
1108         map = list->map;
1109         map->type = _DRM_GEM;
1110         map->size = obj->size;
1111         map->handle = obj;
1112
1113         /* Get a DRM GEM mmap offset allocated... */
1114         list->file_offset_node = drm_mm_search_free(&mm->offset_manager,
1115                                                     obj->size / PAGE_SIZE, 0, 0);
1116         if (!list->file_offset_node) {
1117                 DRM_ERROR("failed to allocate offset for bo %d\n", obj->name);
1118                 ret = -ENOMEM;
1119                 goto out_free_list;
1120         }
1121
1122         list->file_offset_node = drm_mm_get_block(list->file_offset_node,
1123                                                   obj->size / PAGE_SIZE, 0);
1124         if (!list->file_offset_node) {
1125                 ret = -ENOMEM;
1126                 goto out_free_list;
1127         }
1128
1129         list->hash.key = list->file_offset_node->start;
1130         if (drm_ht_insert_item(&mm->offset_hash, &list->hash)) {
1131                 DRM_ERROR("failed to add to map hash\n");
1132                 goto out_free_mm;
1133         }
1134
1135         /* By now we should be all set, any drm_mmap request on the offset
1136          * below will get to our mmap & fault handler */
1137         obj_priv->mmap_offset = ((uint64_t) list->hash.key) << PAGE_SHIFT;
1138
1139         return 0;
1140
1141 out_free_mm:
1142         drm_mm_put_block(list->file_offset_node);
1143 out_free_list:
1144         drm_free(list->map, sizeof(struct drm_map_list), DRM_MEM_DRIVER);
1145
1146         return ret;
1147 }
1148
1149 static void
1150 i915_gem_free_mmap_offset(struct drm_gem_object *obj)
1151 {
1152         struct drm_device *dev = obj->dev;
1153         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1154         struct drm_gem_mm *mm = dev->mm_private;
1155         struct drm_map_list *list;
1156
1157         list = &obj->map_list;
1158         drm_ht_remove_item(&mm->offset_hash, &list->hash);
1159
1160         if (list->file_offset_node) {
1161                 drm_mm_put_block(list->file_offset_node);
1162                 list->file_offset_node = NULL;
1163         }
1164
1165         if (list->map) {
1166                 drm_free(list->map, sizeof(struct drm_map), DRM_MEM_DRIVER);
1167                 list->map = NULL;
1168         }
1169
1170         obj_priv->mmap_offset = 0;
1171 }
1172
1173 /**
1174  * i915_gem_get_gtt_alignment - return required GTT alignment for an object
1175  * @obj: object to check
1176  *
1177  * Return the required GTT alignment for an object, taking into account
1178  * potential fence register mapping if needed.
1179  */
1180 static uint32_t
1181 i915_gem_get_gtt_alignment(struct drm_gem_object *obj)
1182 {
1183         struct drm_device *dev = obj->dev;
1184         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1185         int start, i;
1186
1187         /*
1188          * Minimum alignment is 4k (GTT page size), but might be greater
1189          * if a fence register is needed for the object.
1190          */
1191         if (IS_I965G(dev) || obj_priv->tiling_mode == I915_TILING_NONE)
1192                 return 4096;
1193
1194         /*
1195          * Previous chips need to be aligned to the size of the smallest
1196          * fence register that can contain the object.
1197          */
1198         if (IS_I9XX(dev))
1199                 start = 1024*1024;
1200         else
1201                 start = 512*1024;
1202
1203         for (i = start; i < obj->size; i <<= 1)
1204                 ;
1205
1206         return i;
1207 }
1208
1209 /**
1210  * i915_gem_mmap_gtt_ioctl - prepare an object for GTT mmap'ing
1211  * @dev: DRM device
1212  * @data: GTT mapping ioctl data
1213  * @file_priv: GEM object info
1214  *
1215  * Simply returns the fake offset to userspace so it can mmap it.
1216  * The mmap call will end up in drm_gem_mmap(), which will set things
1217  * up so we can get faults in the handler above.
1218  *
1219  * The fault handler will take care of binding the object into the GTT
1220  * (since it may have been evicted to make room for something), allocating
1221  * a fence register, and mapping the appropriate aperture address into
1222  * userspace.
1223  */
1224 int
1225 i915_gem_mmap_gtt_ioctl(struct drm_device *dev, void *data,
1226                         struct drm_file *file_priv)
1227 {
1228         struct drm_i915_gem_mmap_gtt *args = data;
1229         struct drm_i915_private *dev_priv = dev->dev_private;
1230         struct drm_gem_object *obj;
1231         struct drm_i915_gem_object *obj_priv;
1232         int ret;
1233
1234         if (!(dev->driver->driver_features & DRIVER_GEM))
1235                 return -ENODEV;
1236
1237         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
1238         if (obj == NULL)
1239                 return -EBADF;
1240
1241         mutex_lock(&dev->struct_mutex);
1242
1243         obj_priv = obj->driver_private;
1244
1245         if (!obj_priv->mmap_offset) {
1246                 ret = i915_gem_create_mmap_offset(obj);
1247                 if (ret) {
1248                         drm_gem_object_unreference(obj);
1249                         mutex_unlock(&dev->struct_mutex);
1250                         return ret;
1251                 }
1252         }
1253
1254         args->offset = obj_priv->mmap_offset;
1255
1256         obj_priv->gtt_alignment = i915_gem_get_gtt_alignment(obj);
1257
1258         /* Make sure the alignment is correct for fence regs etc */
1259         if (obj_priv->agp_mem &&
1260             (obj_priv->gtt_offset & (obj_priv->gtt_alignment - 1))) {
1261                 drm_gem_object_unreference(obj);
1262                 mutex_unlock(&dev->struct_mutex);
1263                 return -EINVAL;
1264         }
1265
1266         /*
1267          * Pull it into the GTT so that we have a page list (makes the
1268          * initial fault faster and any subsequent flushing possible).
1269          */
1270         if (!obj_priv->agp_mem) {
1271                 ret = i915_gem_object_bind_to_gtt(obj, obj_priv->gtt_alignment);
1272                 if (ret) {
1273                         drm_gem_object_unreference(obj);
1274                         mutex_unlock(&dev->struct_mutex);
1275                         return ret;
1276                 }
1277                 list_add(&obj_priv->list, &dev_priv->mm.inactive_list);
1278         }
1279
1280         drm_gem_object_unreference(obj);
1281         mutex_unlock(&dev->struct_mutex);
1282
1283         return 0;
1284 }
1285
1286 void
1287 i915_gem_object_put_pages(struct drm_gem_object *obj)
1288 {
1289         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1290         int page_count = obj->size / PAGE_SIZE;
1291         int i;
1292
1293         BUG_ON(obj_priv->pages_refcount == 0);
1294
1295         if (--obj_priv->pages_refcount != 0)
1296                 return;
1297
1298         for (i = 0; i < page_count; i++)
1299                 if (obj_priv->pages[i] != NULL) {
1300                         if (obj_priv->dirty)
1301                                 set_page_dirty(obj_priv->pages[i]);
1302                         mark_page_accessed(obj_priv->pages[i]);
1303                         page_cache_release(obj_priv->pages[i]);
1304                 }
1305         obj_priv->dirty = 0;
1306
1307         drm_free(obj_priv->pages,
1308                  page_count * sizeof(struct page *),
1309                  DRM_MEM_DRIVER);
1310         obj_priv->pages = NULL;
1311 }
1312
1313 static void
1314 i915_gem_object_move_to_active(struct drm_gem_object *obj, uint32_t seqno)
1315 {
1316         struct drm_device *dev = obj->dev;
1317         drm_i915_private_t *dev_priv = dev->dev_private;
1318         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1319
1320         /* Add a reference if we're newly entering the active list. */
1321         if (!obj_priv->active) {
1322                 drm_gem_object_reference(obj);
1323                 obj_priv->active = 1;
1324         }
1325         /* Move from whatever list we were on to the tail of execution. */
1326         spin_lock(&dev_priv->mm.active_list_lock);
1327         list_move_tail(&obj_priv->list,
1328                        &dev_priv->mm.active_list);
1329         spin_unlock(&dev_priv->mm.active_list_lock);
1330         obj_priv->last_rendering_seqno = seqno;
1331 }
1332
1333 static void
1334 i915_gem_object_move_to_flushing(struct drm_gem_object *obj)
1335 {
1336         struct drm_device *dev = obj->dev;
1337         drm_i915_private_t *dev_priv = dev->dev_private;
1338         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1339
1340         BUG_ON(!obj_priv->active);
1341         list_move_tail(&obj_priv->list, &dev_priv->mm.flushing_list);
1342         obj_priv->last_rendering_seqno = 0;
1343 }
1344
1345 static void
1346 i915_gem_object_move_to_inactive(struct drm_gem_object *obj)
1347 {
1348         struct drm_device *dev = obj->dev;
1349         drm_i915_private_t *dev_priv = dev->dev_private;
1350         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1351
1352         i915_verify_inactive(dev, __FILE__, __LINE__);
1353         if (obj_priv->pin_count != 0)
1354                 list_del_init(&obj_priv->list);
1355         else
1356                 list_move_tail(&obj_priv->list, &dev_priv->mm.inactive_list);
1357
1358         obj_priv->last_rendering_seqno = 0;
1359         if (obj_priv->active) {
1360                 obj_priv->active = 0;
1361                 drm_gem_object_unreference(obj);
1362         }
1363         i915_verify_inactive(dev, __FILE__, __LINE__);
1364 }
1365
1366 /**
1367  * Creates a new sequence number, emitting a write of it to the status page
1368  * plus an interrupt, which will trigger i915_user_interrupt_handler.
1369  *
1370  * Must be called with struct_lock held.
1371  *
1372  * Returned sequence numbers are nonzero on success.
1373  */
1374 static uint32_t
1375 i915_add_request(struct drm_device *dev, uint32_t flush_domains)
1376 {
1377         drm_i915_private_t *dev_priv = dev->dev_private;
1378         struct drm_i915_gem_request *request;
1379         uint32_t seqno;
1380         int was_empty;
1381         RING_LOCALS;
1382
1383         request = drm_calloc(1, sizeof(*request), DRM_MEM_DRIVER);
1384         if (request == NULL)
1385                 return 0;
1386
1387         /* Grab the seqno we're going to make this request be, and bump the
1388          * next (skipping 0 so it can be the reserved no-seqno value).
1389          */
1390         seqno = dev_priv->mm.next_gem_seqno;
1391         dev_priv->mm.next_gem_seqno++;
1392         if (dev_priv->mm.next_gem_seqno == 0)
1393                 dev_priv->mm.next_gem_seqno++;
1394
1395         BEGIN_LP_RING(4);
1396         OUT_RING(MI_STORE_DWORD_INDEX);
1397         OUT_RING(I915_GEM_HWS_INDEX << MI_STORE_DWORD_INDEX_SHIFT);
1398         OUT_RING(seqno);
1399
1400         OUT_RING(MI_USER_INTERRUPT);
1401         ADVANCE_LP_RING();
1402
1403         DRM_DEBUG("%d\n", seqno);
1404
1405         request->seqno = seqno;
1406         request->emitted_jiffies = jiffies;
1407         was_empty = list_empty(&dev_priv->mm.request_list);
1408         list_add_tail(&request->list, &dev_priv->mm.request_list);
1409
1410         /* Associate any objects on the flushing list matching the write
1411          * domain we're flushing with our flush.
1412          */
1413         if (flush_domains != 0) {
1414                 struct drm_i915_gem_object *obj_priv, *next;
1415
1416                 list_for_each_entry_safe(obj_priv, next,
1417                                          &dev_priv->mm.flushing_list, list) {
1418                         struct drm_gem_object *obj = obj_priv->obj;
1419
1420                         if ((obj->write_domain & flush_domains) ==
1421                             obj->write_domain) {
1422                                 obj->write_domain = 0;
1423                                 i915_gem_object_move_to_active(obj, seqno);
1424                         }
1425                 }
1426
1427         }
1428
1429         if (was_empty && !dev_priv->mm.suspended)
1430                 schedule_delayed_work(&dev_priv->mm.retire_work, HZ);
1431         return seqno;
1432 }
1433
1434 /**
1435  * Command execution barrier
1436  *
1437  * Ensures that all commands in the ring are finished
1438  * before signalling the CPU
1439  */
1440 static uint32_t
1441 i915_retire_commands(struct drm_device *dev)
1442 {
1443         drm_i915_private_t *dev_priv = dev->dev_private;
1444         uint32_t cmd = MI_FLUSH | MI_NO_WRITE_FLUSH;
1445         uint32_t flush_domains = 0;
1446         RING_LOCALS;
1447
1448         /* The sampler always gets flushed on i965 (sigh) */
1449         if (IS_I965G(dev))
1450                 flush_domains |= I915_GEM_DOMAIN_SAMPLER;
1451         BEGIN_LP_RING(2);
1452         OUT_RING(cmd);
1453         OUT_RING(0); /* noop */
1454         ADVANCE_LP_RING();
1455         return flush_domains;
1456 }
1457
1458 /**
1459  * Moves buffers associated only with the given active seqno from the active
1460  * to inactive list, potentially freeing them.
1461  */
1462 static void
1463 i915_gem_retire_request(struct drm_device *dev,
1464                         struct drm_i915_gem_request *request)
1465 {
1466         drm_i915_private_t *dev_priv = dev->dev_private;
1467
1468         /* Move any buffers on the active list that are no longer referenced
1469          * by the ringbuffer to the flushing/inactive lists as appropriate.
1470          */
1471         spin_lock(&dev_priv->mm.active_list_lock);
1472         while (!list_empty(&dev_priv->mm.active_list)) {
1473                 struct drm_gem_object *obj;
1474                 struct drm_i915_gem_object *obj_priv;
1475
1476                 obj_priv = list_first_entry(&dev_priv->mm.active_list,
1477                                             struct drm_i915_gem_object,
1478                                             list);
1479                 obj = obj_priv->obj;
1480
1481                 /* If the seqno being retired doesn't match the oldest in the
1482                  * list, then the oldest in the list must still be newer than
1483                  * this seqno.
1484                  */
1485                 if (obj_priv->last_rendering_seqno != request->seqno)
1486                         goto out;
1487
1488 #if WATCH_LRU
1489                 DRM_INFO("%s: retire %d moves to inactive list %p\n",
1490                          __func__, request->seqno, obj);
1491 #endif
1492
1493                 if (obj->write_domain != 0)
1494                         i915_gem_object_move_to_flushing(obj);
1495                 else
1496                         i915_gem_object_move_to_inactive(obj);
1497         }
1498 out:
1499         spin_unlock(&dev_priv->mm.active_list_lock);
1500 }
1501
1502 /**
1503  * Returns true if seq1 is later than seq2.
1504  */
1505 static int
1506 i915_seqno_passed(uint32_t seq1, uint32_t seq2)
1507 {
1508         return (int32_t)(seq1 - seq2) >= 0;
1509 }
1510
1511 uint32_t
1512 i915_get_gem_seqno(struct drm_device *dev)
1513 {
1514         drm_i915_private_t *dev_priv = dev->dev_private;
1515
1516         return READ_HWSP(dev_priv, I915_GEM_HWS_INDEX);
1517 }
1518
1519 /**
1520  * This function clears the request list as sequence numbers are passed.
1521  */
1522 void
1523 i915_gem_retire_requests(struct drm_device *dev)
1524 {
1525         drm_i915_private_t *dev_priv = dev->dev_private;
1526         uint32_t seqno;
1527
1528         if (!dev_priv->hw_status_page)
1529                 return;
1530
1531         seqno = i915_get_gem_seqno(dev);
1532
1533         while (!list_empty(&dev_priv->mm.request_list)) {
1534                 struct drm_i915_gem_request *request;
1535                 uint32_t retiring_seqno;
1536
1537                 request = list_first_entry(&dev_priv->mm.request_list,
1538                                            struct drm_i915_gem_request,
1539                                            list);
1540                 retiring_seqno = request->seqno;
1541
1542                 if (i915_seqno_passed(seqno, retiring_seqno) ||
1543                     dev_priv->mm.wedged) {
1544                         i915_gem_retire_request(dev, request);
1545
1546                         list_del(&request->list);
1547                         drm_free(request, sizeof(*request), DRM_MEM_DRIVER);
1548                 } else
1549                         break;
1550         }
1551 }
1552
1553 void
1554 i915_gem_retire_work_handler(struct work_struct *work)
1555 {
1556         drm_i915_private_t *dev_priv;
1557         struct drm_device *dev;
1558
1559         dev_priv = container_of(work, drm_i915_private_t,
1560                                 mm.retire_work.work);
1561         dev = dev_priv->dev;
1562
1563         mutex_lock(&dev->struct_mutex);
1564         i915_gem_retire_requests(dev);
1565         if (!dev_priv->mm.suspended &&
1566             !list_empty(&dev_priv->mm.request_list))
1567                 schedule_delayed_work(&dev_priv->mm.retire_work, HZ);
1568         mutex_unlock(&dev->struct_mutex);
1569 }
1570
1571 /**
1572  * Waits for a sequence number to be signaled, and cleans up the
1573  * request and object lists appropriately for that event.
1574  */
1575 static int
1576 i915_wait_request(struct drm_device *dev, uint32_t seqno)
1577 {
1578         drm_i915_private_t *dev_priv = dev->dev_private;
1579         int ret = 0;
1580
1581         BUG_ON(seqno == 0);
1582
1583         if (!i915_seqno_passed(i915_get_gem_seqno(dev), seqno)) {
1584                 dev_priv->mm.waiting_gem_seqno = seqno;
1585                 i915_user_irq_get(dev);
1586                 ret = wait_event_interruptible(dev_priv->irq_queue,
1587                                                i915_seqno_passed(i915_get_gem_seqno(dev),
1588                                                                  seqno) ||
1589                                                dev_priv->mm.wedged);
1590                 i915_user_irq_put(dev);
1591                 dev_priv->mm.waiting_gem_seqno = 0;
1592         }
1593         if (dev_priv->mm.wedged)
1594                 ret = -EIO;
1595
1596         if (ret && ret != -ERESTARTSYS)
1597                 DRM_ERROR("%s returns %d (awaiting %d at %d)\n",
1598                           __func__, ret, seqno, i915_get_gem_seqno(dev));
1599
1600         /* Directly dispatch request retiring.  While we have the work queue
1601          * to handle this, the waiter on a request often wants an associated
1602          * buffer to have made it to the inactive list, and we would need
1603          * a separate wait queue to handle that.
1604          */
1605         if (ret == 0)
1606                 i915_gem_retire_requests(dev);
1607
1608         return ret;
1609 }
1610
1611 static void
1612 i915_gem_flush(struct drm_device *dev,
1613                uint32_t invalidate_domains,
1614                uint32_t flush_domains)
1615 {
1616         drm_i915_private_t *dev_priv = dev->dev_private;
1617         uint32_t cmd;
1618         RING_LOCALS;
1619
1620 #if WATCH_EXEC
1621         DRM_INFO("%s: invalidate %08x flush %08x\n", __func__,
1622                   invalidate_domains, flush_domains);
1623 #endif
1624
1625         if (flush_domains & I915_GEM_DOMAIN_CPU)
1626                 drm_agp_chipset_flush(dev);
1627
1628         if ((invalidate_domains | flush_domains) & ~(I915_GEM_DOMAIN_CPU |
1629                                                      I915_GEM_DOMAIN_GTT)) {
1630                 /*
1631                  * read/write caches:
1632                  *
1633                  * I915_GEM_DOMAIN_RENDER is always invalidated, but is
1634                  * only flushed if MI_NO_WRITE_FLUSH is unset.  On 965, it is
1635                  * also flushed at 2d versus 3d pipeline switches.
1636                  *
1637                  * read-only caches:
1638                  *
1639                  * I915_GEM_DOMAIN_SAMPLER is flushed on pre-965 if
1640                  * MI_READ_FLUSH is set, and is always flushed on 965.
1641                  *
1642                  * I915_GEM_DOMAIN_COMMAND may not exist?
1643                  *
1644                  * I915_GEM_DOMAIN_INSTRUCTION, which exists on 965, is
1645                  * invalidated when MI_EXE_FLUSH is set.
1646                  *
1647                  * I915_GEM_DOMAIN_VERTEX, which exists on 965, is
1648                  * invalidated with every MI_FLUSH.
1649                  *
1650                  * TLBs:
1651                  *
1652                  * On 965, TLBs associated with I915_GEM_DOMAIN_COMMAND
1653                  * and I915_GEM_DOMAIN_CPU in are invalidated at PTE write and
1654                  * I915_GEM_DOMAIN_RENDER and I915_GEM_DOMAIN_SAMPLER
1655                  * are flushed at any MI_FLUSH.
1656                  */
1657
1658                 cmd = MI_FLUSH | MI_NO_WRITE_FLUSH;
1659                 if ((invalidate_domains|flush_domains) &
1660                     I915_GEM_DOMAIN_RENDER)
1661                         cmd &= ~MI_NO_WRITE_FLUSH;
1662                 if (!IS_I965G(dev)) {
1663                         /*
1664                          * On the 965, the sampler cache always gets flushed
1665                          * and this bit is reserved.
1666                          */
1667                         if (invalidate_domains & I915_GEM_DOMAIN_SAMPLER)
1668                                 cmd |= MI_READ_FLUSH;
1669                 }
1670                 if (invalidate_domains & I915_GEM_DOMAIN_INSTRUCTION)
1671                         cmd |= MI_EXE_FLUSH;
1672
1673 #if WATCH_EXEC
1674                 DRM_INFO("%s: queue flush %08x to ring\n", __func__, cmd);
1675 #endif
1676                 BEGIN_LP_RING(2);
1677                 OUT_RING(cmd);
1678                 OUT_RING(0); /* noop */
1679                 ADVANCE_LP_RING();
1680         }
1681 }
1682
1683 /**
1684  * Ensures that all rendering to the object has completed and the object is
1685  * safe to unbind from the GTT or access from the CPU.
1686  */
1687 static int
1688 i915_gem_object_wait_rendering(struct drm_gem_object *obj)
1689 {
1690         struct drm_device *dev = obj->dev;
1691         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1692         int ret;
1693
1694         /* This function only exists to support waiting for existing rendering,
1695          * not for emitting required flushes.
1696          */
1697         BUG_ON((obj->write_domain & I915_GEM_GPU_DOMAINS) != 0);
1698
1699         /* If there is rendering queued on the buffer being evicted, wait for
1700          * it.
1701          */
1702         if (obj_priv->active) {
1703 #if WATCH_BUF
1704                 DRM_INFO("%s: object %p wait for seqno %08x\n",
1705                           __func__, obj, obj_priv->last_rendering_seqno);
1706 #endif
1707                 ret = i915_wait_request(dev, obj_priv->last_rendering_seqno);
1708                 if (ret != 0)
1709                         return ret;
1710         }
1711
1712         return 0;
1713 }
1714
1715 /**
1716  * Unbinds an object from the GTT aperture.
1717  */
1718 int
1719 i915_gem_object_unbind(struct drm_gem_object *obj)
1720 {
1721         struct drm_device *dev = obj->dev;
1722         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1723         loff_t offset;
1724         int ret = 0;
1725
1726 #if WATCH_BUF
1727         DRM_INFO("%s:%d %p\n", __func__, __LINE__, obj);
1728         DRM_INFO("gtt_space %p\n", obj_priv->gtt_space);
1729 #endif
1730         if (obj_priv->gtt_space == NULL)
1731                 return 0;
1732
1733         if (obj_priv->pin_count != 0) {
1734                 DRM_ERROR("Attempting to unbind pinned buffer\n");
1735                 return -EINVAL;
1736         }
1737
1738         /* Move the object to the CPU domain to ensure that
1739          * any possible CPU writes while it's not in the GTT
1740          * are flushed when we go to remap it. This will
1741          * also ensure that all pending GPU writes are finished
1742          * before we unbind.
1743          */
1744         ret = i915_gem_object_set_to_cpu_domain(obj, 1);
1745         if (ret) {
1746                 if (ret != -ERESTARTSYS)
1747                         DRM_ERROR("set_domain failed: %d\n", ret);
1748                 return ret;
1749         }
1750
1751         if (obj_priv->agp_mem != NULL) {
1752                 drm_unbind_agp(obj_priv->agp_mem);
1753                 drm_free_agp(obj_priv->agp_mem, obj->size / PAGE_SIZE);
1754                 obj_priv->agp_mem = NULL;
1755         }
1756
1757         BUG_ON(obj_priv->active);
1758
1759         /* blow away mappings if mapped through GTT */
1760         offset = ((loff_t) obj->map_list.hash.key) << PAGE_SHIFT;
1761         if (dev->dev_mapping)
1762                 unmap_mapping_range(dev->dev_mapping, offset, obj->size, 1);
1763
1764         if (obj_priv->fence_reg != I915_FENCE_REG_NONE)
1765                 i915_gem_clear_fence_reg(obj);
1766
1767         i915_gem_object_put_pages(obj);
1768
1769         if (obj_priv->gtt_space) {
1770                 atomic_dec(&dev->gtt_count);
1771                 atomic_sub(obj->size, &dev->gtt_memory);
1772
1773                 drm_mm_put_block(obj_priv->gtt_space);
1774                 obj_priv->gtt_space = NULL;
1775         }
1776
1777         /* Remove ourselves from the LRU list if present. */
1778         if (!list_empty(&obj_priv->list))
1779                 list_del_init(&obj_priv->list);
1780
1781         return 0;
1782 }
1783
1784 static int
1785 i915_gem_evict_something(struct drm_device *dev)
1786 {
1787         drm_i915_private_t *dev_priv = dev->dev_private;
1788         struct drm_gem_object *obj;
1789         struct drm_i915_gem_object *obj_priv;
1790         int ret = 0;
1791
1792         for (;;) {
1793                 /* If there's an inactive buffer available now, grab it
1794                  * and be done.
1795                  */
1796                 if (!list_empty(&dev_priv->mm.inactive_list)) {
1797                         obj_priv = list_first_entry(&dev_priv->mm.inactive_list,
1798                                                     struct drm_i915_gem_object,
1799                                                     list);
1800                         obj = obj_priv->obj;
1801                         BUG_ON(obj_priv->pin_count != 0);
1802 #if WATCH_LRU
1803                         DRM_INFO("%s: evicting %p\n", __func__, obj);
1804 #endif
1805                         BUG_ON(obj_priv->active);
1806
1807                         /* Wait on the rendering and unbind the buffer. */
1808                         ret = i915_gem_object_unbind(obj);
1809                         break;
1810                 }
1811
1812                 /* If we didn't get anything, but the ring is still processing
1813                  * things, wait for one of those things to finish and hopefully
1814                  * leave us a buffer to evict.
1815                  */
1816                 if (!list_empty(&dev_priv->mm.request_list)) {
1817                         struct drm_i915_gem_request *request;
1818
1819                         request = list_first_entry(&dev_priv->mm.request_list,
1820                                                    struct drm_i915_gem_request,
1821                                                    list);
1822
1823                         ret = i915_wait_request(dev, request->seqno);
1824                         if (ret)
1825                                 break;
1826
1827                         /* if waiting caused an object to become inactive,
1828                          * then loop around and wait for it. Otherwise, we
1829                          * assume that waiting freed and unbound something,
1830                          * so there should now be some space in the GTT
1831                          */
1832                         if (!list_empty(&dev_priv->mm.inactive_list))
1833                                 continue;
1834                         break;
1835                 }
1836
1837                 /* If we didn't have anything on the request list but there
1838                  * are buffers awaiting a flush, emit one and try again.
1839                  * When we wait on it, those buffers waiting for that flush
1840                  * will get moved to inactive.
1841                  */
1842                 if (!list_empty(&dev_priv->mm.flushing_list)) {
1843                         obj_priv = list_first_entry(&dev_priv->mm.flushing_list,
1844                                                     struct drm_i915_gem_object,
1845                                                     list);
1846                         obj = obj_priv->obj;
1847
1848                         i915_gem_flush(dev,
1849                                        obj->write_domain,
1850                                        obj->write_domain);
1851                         i915_add_request(dev, obj->write_domain);
1852
1853                         obj = NULL;
1854                         continue;
1855                 }
1856
1857                 DRM_ERROR("inactive empty %d request empty %d "
1858                           "flushing empty %d\n",
1859                           list_empty(&dev_priv->mm.inactive_list),
1860                           list_empty(&dev_priv->mm.request_list),
1861                           list_empty(&dev_priv->mm.flushing_list));
1862                 /* If we didn't do any of the above, there's nothing to be done
1863                  * and we just can't fit it in.
1864                  */
1865                 return -ENOMEM;
1866         }
1867         return ret;
1868 }
1869
1870 static int
1871 i915_gem_evict_everything(struct drm_device *dev)
1872 {
1873         int ret;
1874
1875         for (;;) {
1876                 ret = i915_gem_evict_something(dev);
1877                 if (ret != 0)
1878                         break;
1879         }
1880         if (ret == -ENOMEM)
1881                 return 0;
1882         return ret;
1883 }
1884
1885 int
1886 i915_gem_object_get_pages(struct drm_gem_object *obj)
1887 {
1888         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1889         int page_count, i;
1890         struct address_space *mapping;
1891         struct inode *inode;
1892         struct page *page;
1893         int ret;
1894
1895         if (obj_priv->pages_refcount++ != 0)
1896                 return 0;
1897
1898         /* Get the list of pages out of our struct file.  They'll be pinned
1899          * at this point until we release them.
1900          */
1901         page_count = obj->size / PAGE_SIZE;
1902         BUG_ON(obj_priv->pages != NULL);
1903         obj_priv->pages = drm_calloc(page_count, sizeof(struct page *),
1904                                      DRM_MEM_DRIVER);
1905         if (obj_priv->pages == NULL) {
1906                 DRM_ERROR("Faled to allocate page list\n");
1907                 obj_priv->pages_refcount--;
1908                 return -ENOMEM;
1909         }
1910
1911         inode = obj->filp->f_path.dentry->d_inode;
1912         mapping = inode->i_mapping;
1913         for (i = 0; i < page_count; i++) {
1914                 page = read_mapping_page(mapping, i, NULL);
1915                 if (IS_ERR(page)) {
1916                         ret = PTR_ERR(page);
1917                         DRM_ERROR("read_mapping_page failed: %d\n", ret);
1918                         i915_gem_object_put_pages(obj);
1919                         return ret;
1920                 }
1921                 obj_priv->pages[i] = page;
1922         }
1923         return 0;
1924 }
1925
1926 static void i965_write_fence_reg(struct drm_i915_fence_reg *reg)
1927 {
1928         struct drm_gem_object *obj = reg->obj;
1929         struct drm_device *dev = obj->dev;
1930         drm_i915_private_t *dev_priv = dev->dev_private;
1931         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1932         int regnum = obj_priv->fence_reg;
1933         uint64_t val;
1934
1935         val = (uint64_t)((obj_priv->gtt_offset + obj->size - 4096) &
1936                     0xfffff000) << 32;
1937         val |= obj_priv->gtt_offset & 0xfffff000;
1938         val |= ((obj_priv->stride / 128) - 1) << I965_FENCE_PITCH_SHIFT;
1939         if (obj_priv->tiling_mode == I915_TILING_Y)
1940                 val |= 1 << I965_FENCE_TILING_Y_SHIFT;
1941         val |= I965_FENCE_REG_VALID;
1942
1943         I915_WRITE64(FENCE_REG_965_0 + (regnum * 8), val);
1944 }
1945
1946 static void i915_write_fence_reg(struct drm_i915_fence_reg *reg)
1947 {
1948         struct drm_gem_object *obj = reg->obj;
1949         struct drm_device *dev = obj->dev;
1950         drm_i915_private_t *dev_priv = dev->dev_private;
1951         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1952         int regnum = obj_priv->fence_reg;
1953         int tile_width;
1954         uint32_t fence_reg, val;
1955         uint32_t pitch_val;
1956
1957         if ((obj_priv->gtt_offset & ~I915_FENCE_START_MASK) ||
1958             (obj_priv->gtt_offset & (obj->size - 1))) {
1959                 WARN(1, "%s: object 0x%08x not 1M or size (0x%zx) aligned\n",
1960                      __func__, obj_priv->gtt_offset, obj->size);
1961                 return;
1962         }
1963
1964         if (obj_priv->tiling_mode == I915_TILING_Y &&
1965             HAS_128_BYTE_Y_TILING(dev))
1966                 tile_width = 128;
1967         else
1968                 tile_width = 512;
1969
1970         /* Note: pitch better be a power of two tile widths */
1971         pitch_val = obj_priv->stride / tile_width;
1972         pitch_val = ffs(pitch_val) - 1;
1973
1974         val = obj_priv->gtt_offset;
1975         if (obj_priv->tiling_mode == I915_TILING_Y)
1976                 val |= 1 << I830_FENCE_TILING_Y_SHIFT;
1977         val |= I915_FENCE_SIZE_BITS(obj->size);
1978         val |= pitch_val << I830_FENCE_PITCH_SHIFT;
1979         val |= I830_FENCE_REG_VALID;
1980
1981         if (regnum < 8)
1982                 fence_reg = FENCE_REG_830_0 + (regnum * 4);
1983         else
1984                 fence_reg = FENCE_REG_945_8 + ((regnum - 8) * 4);
1985         I915_WRITE(fence_reg, val);
1986 }
1987
1988 static void i830_write_fence_reg(struct drm_i915_fence_reg *reg)
1989 {
1990         struct drm_gem_object *obj = reg->obj;
1991         struct drm_device *dev = obj->dev;
1992         drm_i915_private_t *dev_priv = dev->dev_private;
1993         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1994         int regnum = obj_priv->fence_reg;
1995         uint32_t val;
1996         uint32_t pitch_val;
1997         uint32_t fence_size_bits;
1998
1999         if ((obj_priv->gtt_offset & ~I830_FENCE_START_MASK) ||
2000             (obj_priv->gtt_offset & (obj->size - 1))) {
2001                 WARN(1, "%s: object 0x%08x not 512K or size aligned\n",
2002                      __func__, obj_priv->gtt_offset);
2003                 return;
2004         }
2005
2006         pitch_val = (obj_priv->stride / 128) - 1;
2007         WARN_ON(pitch_val & ~0x0000000f);
2008         val = obj_priv->gtt_offset;
2009         if (obj_priv->tiling_mode == I915_TILING_Y)
2010                 val |= 1 << I830_FENCE_TILING_Y_SHIFT;
2011         fence_size_bits = I830_FENCE_SIZE_BITS(obj->size);
2012         WARN_ON(fence_size_bits & ~0x00000f00);
2013         val |= fence_size_bits;
2014         val |= pitch_val << I830_FENCE_PITCH_SHIFT;
2015         val |= I830_FENCE_REG_VALID;
2016
2017         I915_WRITE(FENCE_REG_830_0 + (regnum * 4), val);
2018
2019 }
2020
2021 /**
2022  * i915_gem_object_get_fence_reg - set up a fence reg for an object
2023  * @obj: object to map through a fence reg
2024  * @write: object is about to be written
2025  *
2026  * When mapping objects through the GTT, userspace wants to be able to write
2027  * to them without having to worry about swizzling if the object is tiled.
2028  *
2029  * This function walks the fence regs looking for a free one for @obj,
2030  * stealing one if it can't find any.
2031  *
2032  * It then sets up the reg based on the object's properties: address, pitch
2033  * and tiling format.
2034  */
2035 static int
2036 i915_gem_object_get_fence_reg(struct drm_gem_object *obj, bool write)
2037 {
2038         struct drm_device *dev = obj->dev;
2039         struct drm_i915_private *dev_priv = dev->dev_private;
2040         struct drm_i915_gem_object *obj_priv = obj->driver_private;
2041         struct drm_i915_fence_reg *reg = NULL;
2042         struct drm_i915_gem_object *old_obj_priv = NULL;
2043         int i, ret, avail;
2044
2045         switch (obj_priv->tiling_mode) {
2046         case I915_TILING_NONE:
2047                 WARN(1, "allocating a fence for non-tiled object?\n");
2048                 break;
2049         case I915_TILING_X:
2050                 if (!obj_priv->stride)
2051                         return -EINVAL;
2052                 WARN((obj_priv->stride & (512 - 1)),
2053                      "object 0x%08x is X tiled but has non-512B pitch\n",
2054                      obj_priv->gtt_offset);
2055                 break;
2056         case I915_TILING_Y:
2057                 if (!obj_priv->stride)
2058                         return -EINVAL;
2059                 WARN((obj_priv->stride & (128 - 1)),
2060                      "object 0x%08x is Y tiled but has non-128B pitch\n",
2061                      obj_priv->gtt_offset);
2062                 break;
2063         }
2064
2065         /* First try to find a free reg */
2066 try_again:
2067         avail = 0;
2068         for (i = dev_priv->fence_reg_start; i < dev_priv->num_fence_regs; i++) {
2069                 reg = &dev_priv->fence_regs[i];
2070                 if (!reg->obj)
2071                         break;
2072
2073                 old_obj_priv = reg->obj->driver_private;
2074                 if (!old_obj_priv->pin_count)
2075                     avail++;
2076         }
2077
2078         /* None available, try to steal one or wait for a user to finish */
2079         if (i == dev_priv->num_fence_regs) {
2080                 uint32_t seqno = dev_priv->mm.next_gem_seqno;
2081                 loff_t offset;
2082
2083                 if (avail == 0)
2084                         return -ENOMEM;
2085
2086                 for (i = dev_priv->fence_reg_start;
2087                      i < dev_priv->num_fence_regs; i++) {
2088                         uint32_t this_seqno;
2089
2090                         reg = &dev_priv->fence_regs[i];
2091                         old_obj_priv = reg->obj->driver_private;
2092
2093                         if (old_obj_priv->pin_count)
2094                                 continue;
2095
2096                         /* i915 uses fences for GPU access to tiled buffers */
2097                         if (IS_I965G(dev) || !old_obj_priv->active)
2098                                 break;
2099
2100                         /* find the seqno of the first available fence */
2101                         this_seqno = old_obj_priv->last_rendering_seqno;
2102                         if (this_seqno != 0 &&
2103                             reg->obj->write_domain == 0 &&
2104                             i915_seqno_passed(seqno, this_seqno))
2105                                 seqno = this_seqno;
2106                 }
2107
2108                 /*
2109                  * Now things get ugly... we have to wait for one of the
2110                  * objects to finish before trying again.
2111                  */
2112                 if (i == dev_priv->num_fence_regs) {
2113                         if (seqno == dev_priv->mm.next_gem_seqno) {
2114                                 i915_gem_flush(dev,
2115                                                I915_GEM_GPU_DOMAINS,
2116                                                I915_GEM_GPU_DOMAINS);
2117                                 seqno = i915_add_request(dev,
2118                                                          I915_GEM_GPU_DOMAINS);
2119                                 if (seqno == 0)
2120                                         return -ENOMEM;
2121                         }
2122
2123                         ret = i915_wait_request(dev, seqno);
2124                         if (ret)
2125                                 return ret;
2126                         goto try_again;
2127                 }
2128
2129                 BUG_ON(old_obj_priv->active ||
2130                        (reg->obj->write_domain & I915_GEM_GPU_DOMAINS));
2131
2132                 /*
2133                  * Zap this virtual mapping so we can set up a fence again
2134                  * for this object next time we need it.
2135                  */
2136                 offset = ((loff_t) reg->obj->map_list.hash.key) << PAGE_SHIFT;
2137                 if (dev->dev_mapping)
2138                         unmap_mapping_range(dev->dev_mapping, offset,
2139                                             reg->obj->size, 1);
2140                 old_obj_priv->fence_reg = I915_FENCE_REG_NONE;
2141         }
2142
2143         obj_priv->fence_reg = i;
2144         reg->obj = obj;
2145
2146         if (IS_I965G(dev))
2147                 i965_write_fence_reg(reg);
2148         else if (IS_I9XX(dev))
2149                 i915_write_fence_reg(reg);
2150         else
2151                 i830_write_fence_reg(reg);
2152
2153         return 0;
2154 }
2155
2156 /**
2157  * i915_gem_clear_fence_reg - clear out fence register info
2158  * @obj: object to clear
2159  *
2160  * Zeroes out the fence register itself and clears out the associated
2161  * data structures in dev_priv and obj_priv.
2162  */
2163 static void
2164 i915_gem_clear_fence_reg(struct drm_gem_object *obj)
2165 {
2166         struct drm_device *dev = obj->dev;
2167         drm_i915_private_t *dev_priv = dev->dev_private;
2168         struct drm_i915_gem_object *obj_priv = obj->driver_private;
2169
2170         if (IS_I965G(dev))
2171                 I915_WRITE64(FENCE_REG_965_0 + (obj_priv->fence_reg * 8), 0);
2172         else {
2173                 uint32_t fence_reg;
2174
2175                 if (obj_priv->fence_reg < 8)
2176                         fence_reg = FENCE_REG_830_0 + obj_priv->fence_reg * 4;
2177                 else
2178                         fence_reg = FENCE_REG_945_8 + (obj_priv->fence_reg -
2179                                                        8) * 4;
2180
2181                 I915_WRITE(fence_reg, 0);
2182         }
2183
2184         dev_priv->fence_regs[obj_priv->fence_reg].obj = NULL;
2185         obj_priv->fence_reg = I915_FENCE_REG_NONE;
2186 }
2187
2188 /**
2189  * Finds free space in the GTT aperture and binds the object there.
2190  */
2191 static int
2192 i915_gem_object_bind_to_gtt(struct drm_gem_object *obj, unsigned alignment)
2193 {
2194         struct drm_device *dev = obj->dev;
2195         drm_i915_private_t *dev_priv = dev->dev_private;
2196         struct drm_i915_gem_object *obj_priv = obj->driver_private;
2197         struct drm_mm_node *free_space;
2198         int page_count, ret;
2199
2200         if (dev_priv->mm.suspended)
2201                 return -EBUSY;
2202         if (alignment == 0)
2203                 alignment = i915_gem_get_gtt_alignment(obj);
2204         if (alignment & (i915_gem_get_gtt_alignment(obj) - 1)) {
2205                 DRM_ERROR("Invalid object alignment requested %u\n", alignment);
2206                 return -EINVAL;
2207         }
2208
2209  search_free:
2210         free_space = drm_mm_search_free(&dev_priv->mm.gtt_space,
2211                                         obj->size, alignment, 0);
2212         if (free_space != NULL) {
2213                 obj_priv->gtt_space = drm_mm_get_block(free_space, obj->size,
2214                                                        alignment);
2215                 if (obj_priv->gtt_space != NULL) {
2216                         obj_priv->gtt_space->private = obj;
2217                         obj_priv->gtt_offset = obj_priv->gtt_space->start;
2218                 }
2219         }
2220         if (obj_priv->gtt_space == NULL) {
2221                 bool lists_empty;
2222
2223                 /* If the gtt is empty and we're still having trouble
2224                  * fitting our object in, we're out of memory.
2225                  */
2226 #if WATCH_LRU
2227                 DRM_INFO("%s: GTT full, evicting something\n", __func__);
2228 #endif
2229                 spin_lock(&dev_priv->mm.active_list_lock);
2230                 lists_empty = (list_empty(&dev_priv->mm.inactive_list) &&
2231                                list_empty(&dev_priv->mm.flushing_list) &&
2232                                list_empty(&dev_priv->mm.active_list));
2233                 spin_unlock(&dev_priv->mm.active_list_lock);
2234                 if (lists_empty) {
2235                         DRM_ERROR("GTT full, but LRU list empty\n");
2236                         return -ENOMEM;
2237                 }
2238
2239                 ret = i915_gem_evict_something(dev);
2240                 if (ret != 0) {
2241                         if (ret != -ERESTARTSYS)
2242                                 DRM_ERROR("Failed to evict a buffer %d\n", ret);
2243                         return ret;
2244                 }
2245                 goto search_free;
2246         }
2247
2248 #if WATCH_BUF
2249         DRM_INFO("Binding object of size %d at 0x%08x\n",
2250                  obj->size, obj_priv->gtt_offset);
2251 #endif
2252         ret = i915_gem_object_get_pages(obj);
2253         if (ret) {
2254                 drm_mm_put_block(obj_priv->gtt_space);
2255                 obj_priv->gtt_space = NULL;
2256                 return ret;
2257         }
2258
2259         page_count = obj->size / PAGE_SIZE;
2260         /* Create an AGP memory structure pointing at our pages, and bind it
2261          * into the GTT.
2262          */
2263         obj_priv->agp_mem = drm_agp_bind_pages(dev,
2264                                                obj_priv->pages,
2265                                                page_count,
2266                                                obj_priv->gtt_offset,
2267                                                obj_priv->agp_type);
2268         if (obj_priv->agp_mem == NULL) {
2269                 i915_gem_object_put_pages(obj);
2270                 drm_mm_put_block(obj_priv->gtt_space);
2271                 obj_priv->gtt_space = NULL;
2272                 return -ENOMEM;
2273         }
2274         atomic_inc(&dev->gtt_count);
2275         atomic_add(obj->size, &dev->gtt_memory);
2276
2277         /* Assert that the object is not currently in any GPU domain. As it
2278          * wasn't in the GTT, there shouldn't be any way it could have been in
2279          * a GPU cache
2280          */
2281         BUG_ON(obj->read_domains & ~(I915_GEM_DOMAIN_CPU|I915_GEM_DOMAIN_GTT));
2282         BUG_ON(obj->write_domain & ~(I915_GEM_DOMAIN_CPU|I915_GEM_DOMAIN_GTT));
2283
2284         return 0;
2285 }
2286
2287 void
2288 i915_gem_clflush_object(struct drm_gem_object *obj)
2289 {
2290         struct drm_i915_gem_object      *obj_priv = obj->driver_private;
2291
2292         /* If we don't have a page list set up, then we're not pinned
2293          * to GPU, and we can ignore the cache flush because it'll happen
2294          * again at bind time.
2295          */
2296         if (obj_priv->pages == NULL)
2297                 return;
2298
2299         drm_clflush_pages(obj_priv->pages, obj->size / PAGE_SIZE);
2300 }
2301
2302 /** Flushes any GPU write domain for the object if it's dirty. */
2303 static void
2304 i915_gem_object_flush_gpu_write_domain(struct drm_gem_object *obj)
2305 {
2306         struct drm_device *dev = obj->dev;
2307         uint32_t seqno;
2308
2309         if ((obj->write_domain & I915_GEM_GPU_DOMAINS) == 0)
2310                 return;
2311
2312         /* Queue the GPU write cache flushing we need. */
2313         i915_gem_flush(dev, 0, obj->write_domain);
2314         seqno = i915_add_request(dev, obj->write_domain);
2315         obj->write_domain = 0;
2316         i915_gem_object_move_to_active(obj, seqno);
2317 }
2318
2319 /** Flushes the GTT write domain for the object if it's dirty. */
2320 static void
2321 i915_gem_object_flush_gtt_write_domain(struct drm_gem_object *obj)
2322 {
2323         if (obj->write_domain != I915_GEM_DOMAIN_GTT)
2324                 return;
2325
2326         /* No actual flushing is required for the GTT write domain.   Writes
2327          * to it immediately go to main memory as far as we know, so there's
2328          * no chipset flush.  It also doesn't land in render cache.
2329          */
2330         obj->write_domain = 0;
2331 }
2332
2333 /** Flushes the CPU write domain for the object if it's dirty. */
2334 static void
2335 i915_gem_object_flush_cpu_write_domain(struct drm_gem_object *obj)
2336 {
2337         struct drm_device *dev = obj->dev;
2338
2339         if (obj->write_domain != I915_GEM_DOMAIN_CPU)
2340                 return;
2341
2342         i915_gem_clflush_object(obj);
2343         drm_agp_chipset_flush(dev);
2344         obj->write_domain = 0;
2345 }
2346
2347 /**
2348  * Moves a single object to the GTT read, and possibly write domain.
2349  *
2350  * This function returns when the move is complete, including waiting on
2351  * flushes to occur.
2352  */
2353 int
2354 i915_gem_object_set_to_gtt_domain(struct drm_gem_object *obj, int write)
2355 {
2356         struct drm_i915_gem_object *obj_priv = obj->driver_private;
2357         int ret;
2358
2359         /* Not valid to be called on unbound objects. */
2360         if (obj_priv->gtt_space == NULL)
2361                 return -EINVAL;
2362
2363         i915_gem_object_flush_gpu_write_domain(obj);
2364         /* Wait on any GPU rendering and flushing to occur. */
2365         ret = i915_gem_object_wait_rendering(obj);
2366         if (ret != 0)
2367                 return ret;
2368
2369         /* If we're writing through the GTT domain, then CPU and GPU caches
2370          * will need to be invalidated at next use.
2371          */
2372         if (write)
2373                 obj->read_domains &= I915_GEM_DOMAIN_GTT;
2374
2375         i915_gem_object_flush_cpu_write_domain(obj);
2376
2377         /* It should now be out of any other write domains, and we can update
2378          * the domain values for our changes.
2379          */
2380         BUG_ON((obj->write_domain & ~I915_GEM_DOMAIN_GTT) != 0);
2381         obj->read_domains |= I915_GEM_DOMAIN_GTT;
2382         if (write) {
2383                 obj->write_domain = I915_GEM_DOMAIN_GTT;
2384                 obj_priv->dirty = 1;
2385         }
2386
2387         return 0;
2388 }
2389
2390 /**
2391  * Moves a single object to the CPU read, and possibly write domain.
2392  *
2393  * This function returns when the move is complete, including waiting on
2394  * flushes to occur.
2395  */
2396 static int
2397 i915_gem_object_set_to_cpu_domain(struct drm_gem_object *obj, int write)
2398 {
2399         int ret;
2400
2401         i915_gem_object_flush_gpu_write_domain(obj);
2402         /* Wait on any GPU rendering and flushing to occur. */
2403         ret = i915_gem_object_wait_rendering(obj);
2404         if (ret != 0)
2405                 return ret;
2406
2407         i915_gem_object_flush_gtt_write_domain(obj);
2408
2409         /* If we have a partially-valid cache of the object in the CPU,
2410          * finish invalidating it and free the per-page flags.
2411          */
2412         i915_gem_object_set_to_full_cpu_read_domain(obj);
2413
2414         /* Flush the CPU cache if it's still invalid. */
2415         if ((obj->read_domains & I915_GEM_DOMAIN_CPU) == 0) {
2416                 i915_gem_clflush_object(obj);
2417
2418                 obj->read_domains |= I915_GEM_DOMAIN_CPU;
2419         }
2420
2421         /* It should now be out of any other write domains, and we can update
2422          * the domain values for our changes.
2423          */
2424         BUG_ON((obj->write_domain & ~I915_GEM_DOMAIN_CPU) != 0);
2425
2426         /* If we're writing through the CPU, then the GPU read domains will
2427          * need to be invalidated at next use.
2428          */
2429         if (write) {
2430                 obj->read_domains &= I915_GEM_DOMAIN_CPU;
2431                 obj->write_domain = I915_GEM_DOMAIN_CPU;
2432         }
2433
2434         return 0;
2435 }
2436
2437 /*
2438  * Set the next domain for the specified object. This
2439  * may not actually perform the necessary flushing/invaliding though,
2440  * as that may want to be batched with other set_domain operations
2441  *
2442  * This is (we hope) the only really tricky part of gem. The goal
2443  * is fairly simple -- track which caches hold bits of the object
2444  * and make sure they remain coherent. A few concrete examples may
2445  * help to explain how it works. For shorthand, we use the notation
2446  * (read_domains, write_domain), e.g. (CPU, CPU) to indicate the
2447  * a pair of read and write domain masks.
2448  *
2449  * Case 1: the batch buffer
2450  *
2451  *      1. Allocated
2452  *      2. Written by CPU
2453  *      3. Mapped to GTT
2454  *      4. Read by GPU
2455  *      5. Unmapped from GTT
2456  *      6. Freed
2457  *
2458  *      Let's take these a step at a time
2459  *
2460  *      1. Allocated
2461  *              Pages allocated from the kernel may still have
2462  *              cache contents, so we set them to (CPU, CPU) always.
2463  *      2. Written by CPU (using pwrite)
2464  *              The pwrite function calls set_domain (CPU, CPU) and
2465  *              this function does nothing (as nothing changes)
2466  *      3. Mapped by GTT
2467  *              This function asserts that the object is not
2468  *              currently in any GPU-based read or write domains
2469  *      4. Read by GPU
2470  *              i915_gem_execbuffer calls set_domain (COMMAND, 0).
2471  *              As write_domain is zero, this function adds in the
2472  *              current read domains (CPU+COMMAND, 0).
2473  *              flush_domains is set to CPU.
2474  *              invalidate_domains is set to COMMAND
2475  *              clflush is run to get data out of the CPU caches
2476  *              then i915_dev_set_domain calls i915_gem_flush to
2477  *              emit an MI_FLUSH and drm_agp_chipset_flush
2478  *      5. Unmapped from GTT
2479  *              i915_gem_object_unbind calls set_domain (CPU, CPU)
2480  *              flush_domains and invalidate_domains end up both zero
2481  *              so no flushing/invalidating happens
2482  *      6. Freed
2483  *              yay, done
2484  *
2485  * Case 2: The shared render buffer
2486  *
2487  *      1. Allocated
2488  *      2. Mapped to GTT
2489  *      3. Read/written by GPU
2490  *      4. set_domain to (CPU,CPU)
2491  *      5. Read/written by CPU
2492  *      6. Read/written by GPU
2493  *
2494  *      1. Allocated
2495  *              Same as last example, (CPU, CPU)
2496  *      2. Mapped to GTT
2497  *              Nothing changes (assertions find that it is not in the GPU)
2498  *      3. Read/written by GPU
2499  *              execbuffer calls set_domain (RENDER, RENDER)
2500  *              flush_domains gets CPU
2501  *              invalidate_domains gets GPU
2502  *              clflush (obj)
2503  *              MI_FLUSH and drm_agp_chipset_flush
2504  *      4. set_domain (CPU, CPU)
2505  *              flush_domains gets GPU
2506  *              invalidate_domains gets CPU
2507  *              wait_rendering (obj) to make sure all drawing is complete.
2508  *              This will include an MI_FLUSH to get the data from GPU
2509  *              to memory
2510  *              clflush (obj) to invalidate the CPU cache
2511  *              Another MI_FLUSH in i915_gem_flush (eliminate this somehow?)
2512  *      5. Read/written by CPU
2513  *              cache lines are loaded and dirtied
2514  *      6. Read written by GPU
2515  *              Same as last GPU access
2516  *
2517  * Case 3: The constant buffer
2518  *
2519  *      1. Allocated
2520  *      2. Written by CPU
2521  *      3. Read by GPU
2522  *      4. Updated (written) by CPU again
2523  *      5. Read by GPU
2524  *
2525  *      1. Allocated
2526  *              (CPU, CPU)
2527  *      2. Written by CPU
2528  *              (CPU, CPU)
2529  *      3. Read by GPU
2530  *              (CPU+RENDER, 0)
2531  *              flush_domains = CPU
2532  *              invalidate_domains = RENDER
2533  *              clflush (obj)
2534  *              MI_FLUSH
2535  *              drm_agp_chipset_flush
2536  *      4. Updated (written) by CPU again
2537  *              (CPU, CPU)
2538  *              flush_domains = 0 (no previous write domain)
2539  *              invalidate_domains = 0 (no new read domains)
2540  *      5. Read by GPU
2541  *              (CPU+RENDER, 0)
2542  *              flush_domains = CPU
2543  *              invalidate_domains = RENDER
2544  *              clflush (obj)
2545  *              MI_FLUSH
2546  *              drm_agp_chipset_flush
2547  */
2548 static void
2549 i915_gem_object_set_to_gpu_domain(struct drm_gem_object *obj)
2550 {
2551         struct drm_device               *dev = obj->dev;
2552         struct drm_i915_gem_object      *obj_priv = obj->driver_private;
2553         uint32_t                        invalidate_domains = 0;
2554         uint32_t                        flush_domains = 0;
2555
2556         BUG_ON(obj->pending_read_domains & I915_GEM_DOMAIN_CPU);
2557         BUG_ON(obj->pending_write_domain == I915_GEM_DOMAIN_CPU);
2558
2559 #if WATCH_BUF
2560         DRM_INFO("%s: object %p read %08x -> %08x write %08x -> %08x\n",
2561                  __func__, obj,
2562                  obj->read_domains, obj->pending_read_domains,
2563                  obj->write_domain, obj->pending_write_domain);
2564 #endif
2565         /*
2566          * If the object isn't moving to a new write domain,
2567          * let the object stay in multiple read domains
2568          */
2569         if (obj->pending_write_domain == 0)
2570                 obj->pending_read_domains |= obj->read_domains;
2571         else
2572                 obj_priv->dirty = 1;
2573
2574         /*
2575          * Flush the current write domain if
2576          * the new read domains don't match. Invalidate
2577          * any read domains which differ from the old
2578          * write domain
2579          */
2580         if (obj->write_domain &&
2581             obj->write_domain != obj->pending_read_domains) {
2582                 flush_domains |= obj->write_domain;
2583                 invalidate_domains |=
2584                         obj->pending_read_domains & ~obj->write_domain;
2585         }
2586         /*
2587          * Invalidate any read caches which may have
2588          * stale data. That is, any new read domains.
2589          */
2590         invalidate_domains |= obj->pending_read_domains & ~obj->read_domains;
2591         if ((flush_domains | invalidate_domains) & I915_GEM_DOMAIN_CPU) {
2592 #if WATCH_BUF
2593                 DRM_INFO("%s: CPU domain flush %08x invalidate %08x\n",
2594                          __func__, flush_domains, invalidate_domains);
2595 #endif
2596                 i915_gem_clflush_object(obj);
2597         }
2598
2599         /* The actual obj->write_domain will be updated with
2600          * pending_write_domain after we emit the accumulated flush for all
2601          * of our domain changes in execbuffers (which clears objects'
2602          * write_domains).  So if we have a current write domain that we
2603          * aren't changing, set pending_write_domain to that.
2604          */
2605         if (flush_domains == 0 && obj->pending_write_domain == 0)
2606                 obj->pending_write_domain = obj->write_domain;
2607         obj->read_domains = obj->pending_read_domains;
2608
2609         dev->invalidate_domains |= invalidate_domains;
2610         dev->flush_domains |= flush_domains;
2611 #if WATCH_BUF
2612         DRM_INFO("%s: read %08x write %08x invalidate %08x flush %08x\n",
2613                  __func__,
2614                  obj->read_domains, obj->write_domain,
2615                  dev->invalidate_domains, dev->flush_domains);
2616 #endif
2617 }
2618
2619 /**
2620  * Moves the object from a partially CPU read to a full one.
2621  *
2622  * Note that this only resolves i915_gem_object_set_cpu_read_domain_range(),
2623  * and doesn't handle transitioning from !(read_domains & I915_GEM_DOMAIN_CPU).
2624  */
2625 static void
2626 i915_gem_object_set_to_full_cpu_read_domain(struct drm_gem_object *obj)
2627 {
2628         struct drm_i915_gem_object *obj_priv = obj->driver_private;
2629
2630         if (!obj_priv->page_cpu_valid)
2631                 return;
2632
2633         /* If we're partially in the CPU read domain, finish moving it in.
2634          */
2635         if (obj->read_domains & I915_GEM_DOMAIN_CPU) {
2636                 int i;
2637
2638                 for (i = 0; i <= (obj->size - 1) / PAGE_SIZE; i++) {
2639                         if (obj_priv->page_cpu_valid[i])
2640                                 continue;
2641                         drm_clflush_pages(obj_priv->pages + i, 1);
2642                 }
2643         }
2644
2645         /* Free the page_cpu_valid mappings which are now stale, whether
2646          * or not we've got I915_GEM_DOMAIN_CPU.
2647          */
2648         drm_free(obj_priv->page_cpu_valid, obj->size / PAGE_SIZE,
2649                  DRM_MEM_DRIVER);
2650         obj_priv->page_cpu_valid = NULL;
2651 }
2652
2653 /**
2654  * Set the CPU read domain on a range of the object.
2655  *
2656  * The object ends up with I915_GEM_DOMAIN_CPU in its read flags although it's
2657  * not entirely valid.  The page_cpu_valid member of the object flags which
2658  * pages have been flushed, and will be respected by
2659  * i915_gem_object_set_to_cpu_domain() if it's called on to get a valid mapping
2660  * of the whole object.
2661  *
2662  * This function returns when the move is complete, including waiting on
2663  * flushes to occur.
2664  */
2665 static int
2666 i915_gem_object_set_cpu_read_domain_range(struct drm_gem_object *obj,
2667                                           uint64_t offset, uint64_t size)
2668 {
2669         struct drm_i915_gem_object *obj_priv = obj->driver_private;
2670         int i, ret;
2671
2672         if (offset == 0 && size == obj->size)
2673                 return i915_gem_object_set_to_cpu_domain(obj, 0);
2674
2675         i915_gem_object_flush_gpu_write_domain(obj);
2676         /* Wait on any GPU rendering and flushing to occur. */
2677         ret = i915_gem_object_wait_rendering(obj);
2678         if (ret != 0)
2679                 return ret;
2680         i915_gem_object_flush_gtt_write_domain(obj);
2681
2682         /* If we're already fully in the CPU read domain, we're done. */
2683         if (obj_priv->page_cpu_valid == NULL &&
2684             (obj->read_domains & I915_GEM_DOMAIN_CPU) != 0)
2685                 return 0;
2686
2687         /* Otherwise, create/clear the per-page CPU read domain flag if we're
2688          * newly adding I915_GEM_DOMAIN_CPU
2689          */
2690         if (obj_priv->page_cpu_valid == NULL) {
2691                 obj_priv->page_cpu_valid = drm_calloc(1, obj->size / PAGE_SIZE,
2692                                                       DRM_MEM_DRIVER);
2693                 if (obj_priv->page_cpu_valid == NULL)
2694                         return -ENOMEM;
2695         } else if ((obj->read_domains & I915_GEM_DOMAIN_CPU) == 0)
2696                 memset(obj_priv->page_cpu_valid, 0, obj->size / PAGE_SIZE);
2697
2698         /* Flush the cache on any pages that are still invalid from the CPU's
2699          * perspective.
2700          */
2701         for (i = offset / PAGE_SIZE; i <= (offset + size - 1) / PAGE_SIZE;
2702              i++) {
2703                 if (obj_priv->page_cpu_valid[i])
2704                         continue;
2705
2706                 drm_clflush_pages(obj_priv->pages + i, 1);
2707
2708                 obj_priv->page_cpu_valid[i] = 1;
2709         }
2710
2711         /* It should now be out of any other write domains, and we can update
2712          * the domain values for our changes.
2713          */
2714         BUG_ON((obj->write_domain & ~I915_GEM_DOMAIN_CPU) != 0);
2715
2716         obj->read_domains |= I915_GEM_DOMAIN_CPU;
2717
2718         return 0;
2719 }
2720
2721 /**
2722  * Pin an object to the GTT and evaluate the relocations landing in it.
2723  */
2724 static int
2725 i915_gem_object_pin_and_relocate(struct drm_gem_object *obj,
2726                                  struct drm_file *file_priv,
2727                                  struct drm_i915_gem_exec_object *entry,
2728                                  struct drm_i915_gem_relocation_entry *relocs)
2729 {
2730         struct drm_device *dev = obj->dev;
2731         drm_i915_private_t *dev_priv = dev->dev_private;
2732         struct drm_i915_gem_object *obj_priv = obj->driver_private;
2733         int i, ret;
2734         void __iomem *reloc_page;
2735
2736         /* Choose the GTT offset for our buffer and put it there. */
2737         ret = i915_gem_object_pin(obj, (uint32_t) entry->alignment);
2738         if (ret)
2739                 return ret;
2740
2741         entry->offset = obj_priv->gtt_offset;
2742
2743         /* Apply the relocations, using the GTT aperture to avoid cache
2744          * flushing requirements.
2745          */
2746         for (i = 0; i < entry->relocation_count; i++) {
2747                 struct drm_i915_gem_relocation_entry *reloc= &relocs[i];
2748                 struct drm_gem_object *target_obj;
2749                 struct drm_i915_gem_object *target_obj_priv;
2750                 uint32_t reloc_val, reloc_offset;
2751                 uint32_t __iomem *reloc_entry;
2752
2753                 target_obj = drm_gem_object_lookup(obj->dev, file_priv,
2754                                                    reloc->target_handle);
2755                 if (target_obj == NULL) {
2756                         i915_gem_object_unpin(obj);
2757                         return -EBADF;
2758                 }
2759                 target_obj_priv = target_obj->driver_private;
2760
2761                 /* The target buffer should have appeared before us in the
2762                  * exec_object list, so it should have a GTT space bound by now.
2763                  */
2764                 if (target_obj_priv->gtt_space == NULL) {
2765                         DRM_ERROR("No GTT space found for object %d\n",
2766                                   reloc->target_handle);
2767                         drm_gem_object_unreference(target_obj);
2768                         i915_gem_object_unpin(obj);
2769                         return -EINVAL;
2770                 }
2771
2772                 if (reloc->offset > obj->size - 4) {
2773                         DRM_ERROR("Relocation beyond object bounds: "
2774                                   "obj %p target %d offset %d size %d.\n",
2775                                   obj, reloc->target_handle,
2776                                   (int) reloc->offset, (int) obj->size);
2777                         drm_gem_object_unreference(target_obj);
2778                         i915_gem_object_unpin(obj);
2779                         return -EINVAL;
2780                 }
2781                 if (reloc->offset & 3) {
2782                         DRM_ERROR("Relocation not 4-byte aligned: "
2783                                   "obj %p target %d offset %d.\n",
2784                                   obj, reloc->target_handle,
2785                                   (int) reloc->offset);
2786                         drm_gem_object_unreference(target_obj);
2787                         i915_gem_object_unpin(obj);
2788                         return -EINVAL;
2789                 }
2790
2791                 if (reloc->write_domain & I915_GEM_DOMAIN_CPU ||
2792                     reloc->read_domains & I915_GEM_DOMAIN_CPU) {
2793                         DRM_ERROR("reloc with read/write CPU domains: "
2794                                   "obj %p target %d offset %d "
2795                                   "read %08x write %08x",
2796                                   obj, reloc->target_handle,
2797                                   (int) reloc->offset,
2798                                   reloc->read_domains,
2799                                   reloc->write_domain);
2800                         drm_gem_object_unreference(target_obj);
2801                         i915_gem_object_unpin(obj);
2802                         return -EINVAL;
2803                 }
2804
2805                 if (reloc->write_domain && target_obj->pending_write_domain &&
2806                     reloc->write_domain != target_obj->pending_write_domain) {
2807                         DRM_ERROR("Write domain conflict: "
2808                                   "obj %p target %d offset %d "
2809                                   "new %08x old %08x\n",
2810                                   obj, reloc->target_handle,
2811                                   (int) reloc->offset,
2812                                   reloc->write_domain,
2813                                   target_obj->pending_write_domain);
2814                         drm_gem_object_unreference(target_obj);
2815                         i915_gem_object_unpin(obj);
2816                         return -EINVAL;
2817                 }
2818
2819 #if WATCH_RELOC
2820                 DRM_INFO("%s: obj %p offset %08x target %d "
2821                          "read %08x write %08x gtt %08x "
2822                          "presumed %08x delta %08x\n",
2823                          __func__,
2824                          obj,
2825                          (int) reloc->offset,
2826                          (int) reloc->target_handle,
2827                          (int) reloc->read_domains,
2828                          (int) reloc->write_domain,
2829                          (int) target_obj_priv->gtt_offset,
2830                          (int) reloc->presumed_offset,
2831                          reloc->delta);
2832 #endif
2833
2834                 target_obj->pending_read_domains |= reloc->read_domains;
2835                 target_obj->pending_write_domain |= reloc->write_domain;
2836
2837                 /* If the relocation already has the right value in it, no
2838                  * more work needs to be done.
2839                  */
2840                 if (target_obj_priv->gtt_offset == reloc->presumed_offset) {
2841                         drm_gem_object_unreference(target_obj);
2842                         continue;
2843                 }
2844
2845                 ret = i915_gem_object_set_to_gtt_domain(obj, 1);
2846                 if (ret != 0) {
2847                         drm_gem_object_unreference(target_obj);
2848                         i915_gem_object_unpin(obj);
2849                         return -EINVAL;
2850                 }
2851
2852                 /* Map the page containing the relocation we're going to
2853                  * perform.
2854                  */
2855                 reloc_offset = obj_priv->gtt_offset + reloc->offset;
2856                 reloc_page = io_mapping_map_atomic_wc(dev_priv->mm.gtt_mapping,
2857                                                       (reloc_offset &
2858                                                        ~(PAGE_SIZE - 1)));
2859                 reloc_entry = (uint32_t __iomem *)(reloc_page +
2860                                                    (reloc_offset & (PAGE_SIZE - 1)));
2861                 reloc_val = target_obj_priv->gtt_offset + reloc->delta;
2862
2863 #if WATCH_BUF
2864                 DRM_INFO("Applied relocation: %p@0x%08x %08x -> %08x\n",
2865                           obj, (unsigned int) reloc->offset,
2866                           readl(reloc_entry), reloc_val);
2867 #endif
2868                 writel(reloc_val, reloc_entry);
2869                 io_mapping_unmap_atomic(reloc_page);
2870
2871                 /* The updated presumed offset for this entry will be
2872                  * copied back out to the user.
2873                  */
2874                 reloc->presumed_offset = target_obj_priv->gtt_offset;
2875
2876                 drm_gem_object_unreference(target_obj);
2877         }
2878
2879 #if WATCH_BUF
2880         if (0)
2881                 i915_gem_dump_object(obj, 128, __func__, ~0);
2882 #endif
2883         return 0;
2884 }
2885
2886 /** Dispatch a batchbuffer to the ring
2887  */
2888 static int
2889 i915_dispatch_gem_execbuffer(struct drm_device *dev,
2890                               struct drm_i915_gem_execbuffer *exec,
2891                               struct drm_clip_rect *cliprects,
2892                               uint64_t exec_offset)
2893 {
2894         drm_i915_private_t *dev_priv = dev->dev_private;
2895         int nbox = exec->num_cliprects;
2896         int i = 0, count;
2897         uint32_t        exec_start, exec_len;
2898         RING_LOCALS;
2899
2900         exec_start = (uint32_t) exec_offset + exec->batch_start_offset;
2901         exec_len = (uint32_t) exec->batch_len;
2902
2903         if ((exec_start | exec_len) & 0x7) {
2904                 DRM_ERROR("alignment\n");
2905                 return -EINVAL;
2906         }
2907
2908         if (!exec_start)
2909                 return -EINVAL;
2910
2911         count = nbox ? nbox : 1;
2912
2913         for (i = 0; i < count; i++) {
2914                 if (i < nbox) {
2915                         int ret = i915_emit_box(dev, cliprects, i,
2916                                                 exec->DR1, exec->DR4);
2917                         if (ret)
2918                                 return ret;
2919                 }
2920
2921                 if (IS_I830(dev) || IS_845G(dev)) {
2922                         BEGIN_LP_RING(4);
2923                         OUT_RING(MI_BATCH_BUFFER);
2924                         OUT_RING(exec_start | MI_BATCH_NON_SECURE);
2925                         OUT_RING(exec_start + exec_len - 4);
2926                         OUT_RING(0);
2927                         ADVANCE_LP_RING();
2928                 } else {
2929                         BEGIN_LP_RING(2);
2930                         if (IS_I965G(dev)) {
2931                                 OUT_RING(MI_BATCH_BUFFER_START |
2932                                          (2 << 6) |
2933                                          MI_BATCH_NON_SECURE_I965);
2934                                 OUT_RING(exec_start);
2935                         } else {
2936                                 OUT_RING(MI_BATCH_BUFFER_START |
2937                                          (2 << 6));
2938                                 OUT_RING(exec_start | MI_BATCH_NON_SECURE);
2939                         }
2940                         ADVANCE_LP_RING();
2941                 }
2942         }
2943
2944         /* XXX breadcrumb */
2945         return 0;
2946 }
2947
2948 /* Throttle our rendering by waiting until the ring has completed our requests
2949  * emitted over 20 msec ago.
2950  *
2951  * This should get us reasonable parallelism between CPU and GPU but also
2952  * relatively low latency when blocking on a particular request to finish.
2953  */
2954 static int
2955 i915_gem_ring_throttle(struct drm_device *dev, struct drm_file *file_priv)
2956 {
2957         struct drm_i915_file_private *i915_file_priv = file_priv->driver_priv;
2958         int ret = 0;
2959         uint32_t seqno;
2960
2961         mutex_lock(&dev->struct_mutex);
2962         seqno = i915_file_priv->mm.last_gem_throttle_seqno;
2963         i915_file_priv->mm.last_gem_throttle_seqno =
2964                 i915_file_priv->mm.last_gem_seqno;
2965         if (seqno)
2966                 ret = i915_wait_request(dev, seqno);
2967         mutex_unlock(&dev->struct_mutex);
2968         return ret;
2969 }
2970
2971 static int
2972 i915_gem_get_relocs_from_user(struct drm_i915_gem_exec_object *exec_list,
2973                               uint32_t buffer_count,
2974                               struct drm_i915_gem_relocation_entry **relocs)
2975 {
2976         uint32_t reloc_count = 0, reloc_index = 0, i;
2977         int ret;
2978
2979         *relocs = NULL;
2980         for (i = 0; i < buffer_count; i++) {
2981                 if (reloc_count + exec_list[i].relocation_count < reloc_count)
2982                         return -EINVAL;
2983                 reloc_count += exec_list[i].relocation_count;
2984         }
2985
2986         *relocs = drm_calloc(reloc_count, sizeof(**relocs), DRM_MEM_DRIVER);
2987         if (*relocs == NULL)
2988                 return -ENOMEM;
2989
2990         for (i = 0; i < buffer_count; i++) {
2991                 struct drm_i915_gem_relocation_entry __user *user_relocs;
2992
2993                 user_relocs = (void __user *)(uintptr_t)exec_list[i].relocs_ptr;
2994
2995                 ret = copy_from_user(&(*relocs)[reloc_index],
2996                                      user_relocs,
2997                                      exec_list[i].relocation_count *
2998                                      sizeof(**relocs));
2999                 if (ret != 0) {
3000                         drm_free(*relocs, reloc_count * sizeof(**relocs),
3001                                  DRM_MEM_DRIVER);
3002                         *relocs = NULL;
3003                         return ret;
3004                 }
3005
3006                 reloc_index += exec_list[i].relocation_count;
3007         }
3008
3009         return ret;
3010 }
3011
3012 static int
3013 i915_gem_put_relocs_to_user(struct drm_i915_gem_exec_object *exec_list,
3014                             uint32_t buffer_count,
3015                             struct drm_i915_gem_relocation_entry *relocs)
3016 {
3017         uint32_t reloc_count = 0, i;
3018         int ret;
3019
3020         for (i = 0; i < buffer_count; i++) {
3021                 struct drm_i915_gem_relocation_entry __user *user_relocs;
3022
3023                 user_relocs = (void __user *)(uintptr_t)exec_list[i].relocs_ptr;
3024
3025                 if (ret == 0) {
3026                         ret = copy_to_user(user_relocs,
3027                                            &relocs[reloc_count],
3028                                            exec_list[i].relocation_count *
3029                                            sizeof(*relocs));
3030                 }
3031
3032                 reloc_count += exec_list[i].relocation_count;
3033         }
3034
3035         drm_free(relocs, reloc_count * sizeof(*relocs), DRM_MEM_DRIVER);
3036
3037         return ret;
3038 }
3039
3040 int
3041 i915_gem_execbuffer(struct drm_device *dev, void *data,
3042                     struct drm_file *file_priv)
3043 {
3044         drm_i915_private_t *dev_priv = dev->dev_private;
3045         struct drm_i915_file_private *i915_file_priv = file_priv->driver_priv;
3046         struct drm_i915_gem_execbuffer *args = data;
3047         struct drm_i915_gem_exec_object *exec_list = NULL;
3048         struct drm_gem_object **object_list = NULL;
3049         struct drm_gem_object *batch_obj;
3050         struct drm_i915_gem_object *obj_priv;
3051         struct drm_clip_rect *cliprects = NULL;
3052         struct drm_i915_gem_relocation_entry *relocs;
3053         int ret, ret2, i, pinned = 0;
3054         uint64_t exec_offset;
3055         uint32_t seqno, flush_domains, reloc_index;
3056         int pin_tries;
3057
3058 #if WATCH_EXEC
3059         DRM_INFO("buffers_ptr %d buffer_count %d len %08x\n",
3060                   (int) args->buffers_ptr, args->buffer_count, args->batch_len);
3061 #endif
3062
3063         if (args->buffer_count < 1) {
3064                 DRM_ERROR("execbuf with %d buffers\n", args->buffer_count);
3065                 return -EINVAL;
3066         }
3067         /* Copy in the exec list from userland */
3068         exec_list = drm_calloc(sizeof(*exec_list), args->buffer_count,
3069                                DRM_MEM_DRIVER);
3070         object_list = drm_calloc(sizeof(*object_list), args->buffer_count,
3071                                  DRM_MEM_DRIVER);
3072         if (exec_list == NULL || object_list == NULL) {
3073                 DRM_ERROR("Failed to allocate exec or object list "
3074                           "for %d buffers\n",
3075                           args->buffer_count);
3076                 ret = -ENOMEM;
3077                 goto pre_mutex_err;
3078         }
3079         ret = copy_from_user(exec_list,
3080                              (struct drm_i915_relocation_entry __user *)
3081                              (uintptr_t) args->buffers_ptr,
3082                              sizeof(*exec_list) * args->buffer_count);
3083         if (ret != 0) {
3084                 DRM_ERROR("copy %d exec entries failed %d\n",
3085                           args->buffer_count, ret);
3086                 goto pre_mutex_err;
3087         }
3088
3089         if (args->num_cliprects != 0) {
3090                 cliprects = drm_calloc(args->num_cliprects, sizeof(*cliprects),
3091                                        DRM_MEM_DRIVER);
3092                 if (cliprects == NULL)
3093                         goto pre_mutex_err;
3094
3095                 ret = copy_from_user(cliprects,
3096                                      (struct drm_clip_rect __user *)
3097                                      (uintptr_t) args->cliprects_ptr,
3098                                      sizeof(*cliprects) * args->num_cliprects);
3099                 if (ret != 0) {
3100                         DRM_ERROR("copy %d cliprects failed: %d\n",
3101                                   args->num_cliprects, ret);
3102                         goto pre_mutex_err;
3103                 }
3104         }
3105
3106         ret = i915_gem_get_relocs_from_user(exec_list, args->buffer_count,
3107                                             &relocs);
3108         if (ret != 0)
3109                 goto pre_mutex_err;
3110
3111         mutex_lock(&dev->struct_mutex);
3112
3113         i915_verify_inactive(dev, __FILE__, __LINE__);
3114
3115         if (dev_priv->mm.wedged) {
3116                 DRM_ERROR("Execbuf while wedged\n");
3117                 mutex_unlock(&dev->struct_mutex);
3118                 ret = -EIO;
3119                 goto pre_mutex_err;
3120         }
3121
3122         if (dev_priv->mm.suspended) {
3123                 DRM_ERROR("Execbuf while VT-switched.\n");
3124                 mutex_unlock(&dev->struct_mutex);
3125                 ret = -EBUSY;
3126                 goto pre_mutex_err;
3127         }
3128
3129         /* Look up object handles */
3130         for (i = 0; i < args->buffer_count; i++) {
3131                 object_list[i] = drm_gem_object_lookup(dev, file_priv,
3132                                                        exec_list[i].handle);
3133                 if (object_list[i] == NULL) {
3134                         DRM_ERROR("Invalid object handle %d at index %d\n",
3135                                    exec_list[i].handle, i);
3136                         ret = -EBADF;
3137                         goto err;
3138                 }
3139
3140                 obj_priv = object_list[i]->driver_private;
3141                 if (obj_priv->in_execbuffer) {
3142                         DRM_ERROR("Object %p appears more than once in object list\n",
3143                                    object_list[i]);
3144                         ret = -EBADF;
3145                         goto err;
3146                 }
3147                 obj_priv->in_execbuffer = true;
3148         }
3149
3150         /* Pin and relocate */
3151         for (pin_tries = 0; ; pin_tries++) {
3152                 ret = 0;
3153                 reloc_index = 0;
3154
3155                 for (i = 0; i < args->buffer_count; i++) {
3156                         object_list[i]->pending_read_domains = 0;
3157                         object_list[i]->pending_write_domain = 0;
3158                         ret = i915_gem_object_pin_and_relocate(object_list[i],
3159                                                                file_priv,
3160                                                                &exec_list[i],
3161                                                                &relocs[reloc_index]);
3162                         if (ret)
3163                                 break;
3164                         pinned = i + 1;
3165                         reloc_index += exec_list[i].relocation_count;
3166                 }
3167                 /* success */
3168                 if (ret == 0)
3169                         break;
3170
3171                 /* error other than GTT full, or we've already tried again */
3172                 if (ret != -ENOMEM || pin_tries >= 1) {
3173                         if (ret != -ERESTARTSYS)
3174                                 DRM_ERROR("Failed to pin buffers %d\n", ret);
3175                         goto err;
3176                 }
3177
3178                 /* unpin all of our buffers */
3179                 for (i = 0; i < pinned; i++)
3180                         i915_gem_object_unpin(object_list[i]);
3181                 pinned = 0;
3182
3183                 /* evict everyone we can from the aperture */
3184                 ret = i915_gem_evict_everything(dev);
3185                 if (ret)
3186                         goto err;
3187         }
3188
3189         /* Set the pending read domains for the batch buffer to COMMAND */
3190         batch_obj = object_list[args->buffer_count-1];
3191         batch_obj->pending_read_domains = I915_GEM_DOMAIN_COMMAND;
3192         batch_obj->pending_write_domain = 0;
3193
3194         i915_verify_inactive(dev, __FILE__, __LINE__);
3195
3196         /* Zero the global flush/invalidate flags. These
3197          * will be modified as new domains are computed
3198          * for each object
3199          */
3200         dev->invalidate_domains = 0;
3201         dev->flush_domains = 0;
3202
3203         for (i = 0; i < args->buffer_count; i++) {
3204                 struct drm_gem_object *obj = object_list[i];
3205
3206                 /* Compute new gpu domains and update invalidate/flush */
3207                 i915_gem_object_set_to_gpu_domain(obj);
3208         }
3209
3210         i915_verify_inactive(dev, __FILE__, __LINE__);
3211
3212         if (dev->invalidate_domains | dev->flush_domains) {
3213 #if WATCH_EXEC
3214                 DRM_INFO("%s: invalidate_domains %08x flush_domains %08x\n",
3215                           __func__,
3216                          dev->invalidate_domains,
3217                          dev->flush_domains);
3218 #endif
3219                 i915_gem_flush(dev,
3220                                dev->invalidate_domains,
3221                                dev->flush_domains);
3222                 if (dev->flush_domains)
3223                         (void)i915_add_request(dev, dev->flush_domains);
3224         }
3225
3226         for (i = 0; i < args->buffer_count; i++) {
3227                 struct drm_gem_object *obj = object_list[i];
3228
3229                 obj->write_domain = obj->pending_write_domain;
3230         }
3231
3232         i915_verify_inactive(dev, __FILE__, __LINE__);
3233
3234 #if WATCH_COHERENCY
3235         for (i = 0; i < args->buffer_count; i++) {
3236                 i915_gem_object_check_coherency(object_list[i],
3237                                                 exec_list[i].handle);
3238         }
3239 #endif
3240
3241         exec_offset = exec_list[args->buffer_count - 1].offset;
3242
3243 #if WATCH_EXEC
3244         i915_gem_dump_object(batch_obj,
3245                               args->batch_len,
3246                               __func__,
3247                               ~0);
3248 #endif
3249
3250         /* Exec the batchbuffer */
3251         ret = i915_dispatch_gem_execbuffer(dev, args, cliprects, exec_offset);
3252         if (ret) {
3253                 DRM_ERROR("dispatch failed %d\n", ret);
3254                 goto err;
3255         }
3256
3257         /*
3258          * Ensure that the commands in the batch buffer are
3259          * finished before the interrupt fires
3260          */
3261         flush_domains = i915_retire_commands(dev);
3262
3263         i915_verify_inactive(dev, __FILE__, __LINE__);
3264
3265         /*
3266          * Get a seqno representing the execution of the current buffer,
3267          * which we can wait on.  We would like to mitigate these interrupts,
3268          * likely by only creating seqnos occasionally (so that we have
3269          * *some* interrupts representing completion of buffers that we can
3270          * wait on when trying to clear up gtt space).
3271          */
3272         seqno = i915_add_request(dev, flush_domains);
3273         BUG_ON(seqno == 0);
3274         i915_file_priv->mm.last_gem_seqno = seqno;
3275         for (i = 0; i < args->buffer_count; i++) {
3276                 struct drm_gem_object *obj = object_list[i];
3277
3278                 i915_gem_object_move_to_active(obj, seqno);
3279 #if WATCH_LRU
3280                 DRM_INFO("%s: move to exec list %p\n", __func__, obj);
3281 #endif
3282         }
3283 #if WATCH_LRU
3284         i915_dump_lru(dev, __func__);
3285 #endif
3286
3287         i915_verify_inactive(dev, __FILE__, __LINE__);
3288
3289 err:
3290         for (i = 0; i < pinned; i++)
3291                 i915_gem_object_unpin(object_list[i]);
3292
3293         for (i = 0; i < args->buffer_count; i++) {
3294                 if (object_list[i]) {
3295                         obj_priv = object_list[i]->driver_private;
3296                         obj_priv->in_execbuffer = false;
3297                 }
3298                 drm_gem_object_unreference(object_list[i]);
3299         }
3300
3301         mutex_unlock(&dev->struct_mutex);
3302
3303         if (!ret) {
3304                 /* Copy the new buffer offsets back to the user's exec list. */
3305                 ret = copy_to_user((struct drm_i915_relocation_entry __user *)
3306                                    (uintptr_t) args->buffers_ptr,
3307                                    exec_list,
3308                                    sizeof(*exec_list) * args->buffer_count);
3309                 if (ret)
3310                         DRM_ERROR("failed to copy %d exec entries "
3311                                   "back to user (%d)\n",
3312                                   args->buffer_count, ret);
3313         }
3314
3315         /* Copy the updated relocations out regardless of current error
3316          * state.  Failure to update the relocs would mean that the next
3317          * time userland calls execbuf, it would do so with presumed offset
3318          * state that didn't match the actual object state.
3319          */
3320         ret2 = i915_gem_put_relocs_to_user(exec_list, args->buffer_count,
3321                                            relocs);
3322         if (ret2 != 0) {
3323                 DRM_ERROR("Failed to copy relocations back out: %d\n", ret2);
3324
3325                 if (ret == 0)
3326                         ret = ret2;
3327         }
3328
3329 pre_mutex_err:
3330         drm_free(object_list, sizeof(*object_list) * args->buffer_count,
3331                  DRM_MEM_DRIVER);
3332         drm_free(exec_list, sizeof(*exec_list) * args->buffer_count,
3333                  DRM_MEM_DRIVER);
3334         drm_free(cliprects, sizeof(*cliprects) * args->num_cliprects,
3335                  DRM_MEM_DRIVER);
3336
3337         return ret;
3338 }
3339
3340 int
3341 i915_gem_object_pin(struct drm_gem_object *obj, uint32_t alignment)
3342 {
3343         struct drm_device *dev = obj->dev;
3344         struct drm_i915_gem_object *obj_priv = obj->driver_private;
3345         int ret;
3346
3347         i915_verify_inactive(dev, __FILE__, __LINE__);
3348         if (obj_priv->gtt_space == NULL) {
3349                 ret = i915_gem_object_bind_to_gtt(obj, alignment);
3350                 if (ret != 0) {
3351                         if (ret != -EBUSY && ret != -ERESTARTSYS)
3352                                 DRM_ERROR("Failure to bind: %d\n", ret);
3353                         return ret;
3354                 }
3355         }
3356         /*
3357          * Pre-965 chips need a fence register set up in order to
3358          * properly handle tiled surfaces.
3359          */
3360         if (!IS_I965G(dev) &&
3361             obj_priv->fence_reg == I915_FENCE_REG_NONE &&
3362             obj_priv->tiling_mode != I915_TILING_NONE) {
3363                 ret = i915_gem_object_get_fence_reg(obj, true);
3364                 if (ret != 0) {
3365                         if (ret != -EBUSY && ret != -ERESTARTSYS)
3366                                 DRM_ERROR("Failure to install fence: %d\n",
3367                                           ret);
3368                         return ret;
3369                 }
3370         }
3371         obj_priv->pin_count++;
3372
3373         /* If the object is not active and not pending a flush,
3374          * remove it from the inactive list
3375          */
3376         if (obj_priv->pin_count == 1) {
3377                 atomic_inc(&dev->pin_count);
3378                 atomic_add(obj->size, &dev->pin_memory);
3379                 if (!obj_priv->active &&
3380                     (obj->write_domain & ~(I915_GEM_DOMAIN_CPU |
3381                                            I915_GEM_DOMAIN_GTT)) == 0 &&
3382                     !list_empty(&obj_priv->list))
3383                         list_del_init(&obj_priv->list);
3384         }
3385         i915_verify_inactive(dev, __FILE__, __LINE__);
3386
3387         return 0;
3388 }
3389
3390 void
3391 i915_gem_object_unpin(struct drm_gem_object *obj)
3392 {
3393         struct drm_device *dev = obj->dev;
3394         drm_i915_private_t *dev_priv = dev->dev_private;
3395         struct drm_i915_gem_object *obj_priv = obj->driver_private;
3396
3397         i915_verify_inactive(dev, __FILE__, __LINE__);
3398         obj_priv->pin_count--;
3399         BUG_ON(obj_priv->pin_count < 0);
3400         BUG_ON(obj_priv->gtt_space == NULL);
3401
3402         /* If the object is no longer pinned, and is
3403          * neither active nor being flushed, then stick it on
3404          * the inactive list
3405          */
3406         if (obj_priv->pin_count == 0) {
3407                 if (!obj_priv->active &&
3408                     (obj->write_domain & ~(I915_GEM_DOMAIN_CPU |
3409                                            I915_GEM_DOMAIN_GTT)) == 0)
3410                         list_move_tail(&obj_priv->list,
3411                                        &dev_priv->mm.inactive_list);
3412                 atomic_dec(&dev->pin_count);
3413                 atomic_sub(obj->size, &dev->pin_memory);
3414         }
3415         i915_verify_inactive(dev, __FILE__, __LINE__);
3416 }
3417
3418 int
3419 i915_gem_pin_ioctl(struct drm_device *dev, void *data,
3420                    struct drm_file *file_priv)
3421 {
3422         struct drm_i915_gem_pin *args = data;
3423         struct drm_gem_object *obj;
3424         struct drm_i915_gem_object *obj_priv;
3425         int ret;
3426
3427         mutex_lock(&dev->struct_mutex);
3428
3429         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
3430         if (obj == NULL) {
3431                 DRM_ERROR("Bad handle in i915_gem_pin_ioctl(): %d\n",
3432                           args->handle);
3433                 mutex_unlock(&dev->struct_mutex);
3434                 return -EBADF;
3435         }
3436         obj_priv = obj->driver_private;
3437
3438         if (obj_priv->pin_filp != NULL && obj_priv->pin_filp != file_priv) {
3439                 DRM_ERROR("Already pinned in i915_gem_pin_ioctl(): %d\n",
3440                           args->handle);
3441                 drm_gem_object_unreference(obj);
3442                 mutex_unlock(&dev->struct_mutex);
3443                 return -EINVAL;
3444         }
3445
3446         obj_priv->user_pin_count++;
3447         obj_priv->pin_filp = file_priv;
3448         if (obj_priv->user_pin_count == 1) {
3449                 ret = i915_gem_object_pin(obj, args->alignment);
3450                 if (ret != 0) {
3451                         drm_gem_object_unreference(obj);
3452                         mutex_unlock(&dev->struct_mutex);
3453                         return ret;
3454                 }
3455         }
3456
3457         /* XXX - flush the CPU caches for pinned objects
3458          * as the X server doesn't manage domains yet
3459          */
3460         i915_gem_object_flush_cpu_write_domain(obj);
3461         args->offset = obj_priv->gtt_offset;
3462         drm_gem_object_unreference(obj);
3463         mutex_unlock(&dev->struct_mutex);
3464
3465         return 0;
3466 }
3467
3468 int
3469 i915_gem_unpin_ioctl(struct drm_device *dev, void *data,
3470                      struct drm_file *file_priv)
3471 {
3472         struct drm_i915_gem_pin *args = data;
3473         struct drm_gem_object *obj;
3474         struct drm_i915_gem_object *obj_priv;
3475
3476         mutex_lock(&dev->struct_mutex);
3477
3478         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
3479         if (obj == NULL) {
3480                 DRM_ERROR("Bad handle in i915_gem_unpin_ioctl(): %d\n",
3481                           args->handle);
3482                 mutex_unlock(&dev->struct_mutex);
3483                 return -EBADF;
3484         }
3485
3486         obj_priv = obj->driver_private;
3487         if (obj_priv->pin_filp != file_priv) {
3488                 DRM_ERROR("Not pinned by caller in i915_gem_pin_ioctl(): %d\n",
3489                           args->handle);
3490                 drm_gem_object_unreference(obj);
3491                 mutex_unlock(&dev->struct_mutex);
3492                 return -EINVAL;
3493         }
3494         obj_priv->user_pin_count--;
3495         if (obj_priv->user_pin_count == 0) {
3496                 obj_priv->pin_filp = NULL;
3497                 i915_gem_object_unpin(obj);
3498         }
3499
3500         drm_gem_object_unreference(obj);
3501         mutex_unlock(&dev->struct_mutex);
3502         return 0;
3503 }
3504
3505 int
3506 i915_gem_busy_ioctl(struct drm_device *dev, void *data,
3507                     struct drm_file *file_priv)
3508 {
3509         struct drm_i915_gem_busy *args = data;
3510         struct drm_gem_object *obj;
3511         struct drm_i915_gem_object *obj_priv;
3512
3513         mutex_lock(&dev->struct_mutex);
3514         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
3515         if (obj == NULL) {
3516                 DRM_ERROR("Bad handle in i915_gem_busy_ioctl(): %d\n",
3517                           args->handle);
3518                 mutex_unlock(&dev->struct_mutex);
3519                 return -EBADF;
3520         }
3521
3522         /* Update the active list for the hardware's current position.
3523          * Otherwise this only updates on a delayed timer or when irqs are
3524          * actually unmasked, and our working set ends up being larger than
3525          * required.
3526          */
3527         i915_gem_retire_requests(dev);
3528
3529         obj_priv = obj->driver_private;
3530         /* Don't count being on the flushing list against the object being
3531          * done.  Otherwise, a buffer left on the flushing list but not getting
3532          * flushed (because nobody's flushing that domain) won't ever return
3533          * unbusy and get reused by libdrm's bo cache.  The other expected
3534          * consumer of this interface, OpenGL's occlusion queries, also specs
3535          * that the objects get unbusy "eventually" without any interference.
3536          */
3537         args->busy = obj_priv->active && obj_priv->last_rendering_seqno != 0;
3538
3539         drm_gem_object_unreference(obj);
3540         mutex_unlock(&dev->struct_mutex);
3541         return 0;
3542 }
3543
3544 int
3545 i915_gem_throttle_ioctl(struct drm_device *dev, void *data,
3546                         struct drm_file *file_priv)
3547 {
3548     return i915_gem_ring_throttle(dev, file_priv);
3549 }
3550
3551 int i915_gem_init_object(struct drm_gem_object *obj)
3552 {
3553         struct drm_i915_gem_object *obj_priv;
3554
3555         obj_priv = drm_calloc(1, sizeof(*obj_priv), DRM_MEM_DRIVER);
3556         if (obj_priv == NULL)
3557                 return -ENOMEM;
3558
3559         /*
3560          * We've just allocated pages from the kernel,
3561          * so they've just been written by the CPU with
3562          * zeros. They'll need to be clflushed before we
3563          * use them with the GPU.
3564          */
3565         obj->write_domain = I915_GEM_DOMAIN_CPU;
3566         obj->read_domains = I915_GEM_DOMAIN_CPU;
3567
3568         obj_priv->agp_type = AGP_USER_MEMORY;
3569
3570         obj->driver_private = obj_priv;
3571         obj_priv->obj = obj;
3572         obj_priv->fence_reg = I915_FENCE_REG_NONE;
3573         INIT_LIST_HEAD(&obj_priv->list);
3574
3575         return 0;
3576 }
3577
3578 void i915_gem_free_object(struct drm_gem_object *obj)
3579 {
3580         struct drm_device *dev = obj->dev;
3581         struct drm_i915_gem_object *obj_priv = obj->driver_private;
3582
3583         while (obj_priv->pin_count > 0)
3584                 i915_gem_object_unpin(obj);
3585
3586         if (obj_priv->phys_obj)
3587                 i915_gem_detach_phys_object(dev, obj);
3588
3589         i915_gem_object_unbind(obj);
3590
3591         i915_gem_free_mmap_offset(obj);
3592
3593         drm_free(obj_priv->page_cpu_valid, 1, DRM_MEM_DRIVER);
3594         drm_free(obj->driver_private, 1, DRM_MEM_DRIVER);
3595 }
3596
3597 /** Unbinds all objects that are on the given buffer list. */
3598 static int
3599 i915_gem_evict_from_list(struct drm_device *dev, struct list_head *head)
3600 {
3601         struct drm_gem_object *obj;
3602         struct drm_i915_gem_object *obj_priv;
3603         int ret;
3604
3605         while (!list_empty(head)) {
3606                 obj_priv = list_first_entry(head,
3607                                             struct drm_i915_gem_object,
3608                                             list);
3609                 obj = obj_priv->obj;
3610
3611                 if (obj_priv->pin_count != 0) {
3612                         DRM_ERROR("Pinned object in unbind list\n");
3613                         mutex_unlock(&dev->struct_mutex);
3614                         return -EINVAL;
3615                 }
3616
3617                 ret = i915_gem_object_unbind(obj);
3618                 if (ret != 0) {
3619                         DRM_ERROR("Error unbinding object in LeaveVT: %d\n",
3620                                   ret);
3621                         mutex_unlock(&dev->struct_mutex);
3622                         return ret;
3623                 }
3624         }
3625
3626
3627         return 0;
3628 }
3629
3630 int
3631 i915_gem_idle(struct drm_device *dev)
3632 {
3633         drm_i915_private_t *dev_priv = dev->dev_private;
3634         uint32_t seqno, cur_seqno, last_seqno;
3635         int stuck, ret;
3636
3637         mutex_lock(&dev->struct_mutex);
3638
3639         if (dev_priv->mm.suspended || dev_priv->ring.ring_obj == NULL) {
3640                 mutex_unlock(&dev->struct_mutex);
3641                 return 0;
3642         }
3643
3644         /* Hack!  Don't let anybody do execbuf while we don't control the chip.
3645          * We need to replace this with a semaphore, or something.
3646          */
3647         dev_priv->mm.suspended = 1;
3648
3649         /* Cancel the retire work handler, wait for it to finish if running
3650          */
3651         mutex_unlock(&dev->struct_mutex);
3652         cancel_delayed_work_sync(&dev_priv->mm.retire_work);
3653         mutex_lock(&dev->struct_mutex);
3654
3655         i915_kernel_lost_context(dev);
3656
3657         /* Flush the GPU along with all non-CPU write domains
3658          */
3659         i915_gem_flush(dev, ~(I915_GEM_DOMAIN_CPU|I915_GEM_DOMAIN_GTT),
3660                        ~(I915_GEM_DOMAIN_CPU|I915_GEM_DOMAIN_GTT));
3661         seqno = i915_add_request(dev, ~I915_GEM_DOMAIN_CPU);
3662
3663         if (seqno == 0) {
3664                 mutex_unlock(&dev->struct_mutex);
3665                 return -ENOMEM;
3666         }
3667
3668         dev_priv->mm.waiting_gem_seqno = seqno;
3669         last_seqno = 0;
3670         stuck = 0;
3671         for (;;) {
3672                 cur_seqno = i915_get_gem_seqno(dev);
3673                 if (i915_seqno_passed(cur_seqno, seqno))
3674                         break;
3675                 if (last_seqno == cur_seqno) {
3676                         if (stuck++ > 100) {
3677                                 DRM_ERROR("hardware wedged\n");
3678                                 dev_priv->mm.wedged = 1;
3679                                 DRM_WAKEUP(&dev_priv->irq_queue);
3680                                 break;
3681                         }
3682                 }
3683                 msleep(10);
3684                 last_seqno = cur_seqno;
3685         }
3686         dev_priv->mm.waiting_gem_seqno = 0;
3687
3688         i915_gem_retire_requests(dev);
3689
3690         spin_lock(&dev_priv->mm.active_list_lock);
3691         if (!dev_priv->mm.wedged) {
3692                 /* Active and flushing should now be empty as we've
3693                  * waited for a sequence higher than any pending execbuffer
3694                  */
3695                 WARN_ON(!list_empty(&dev_priv->mm.active_list));
3696                 WARN_ON(!list_empty(&dev_priv->mm.flushing_list));
3697                 /* Request should now be empty as we've also waited
3698                  * for the last request in the list
3699                  */
3700                 WARN_ON(!list_empty(&dev_priv->mm.request_list));
3701         }
3702
3703         /* Empty the active and flushing lists to inactive.  If there's
3704          * anything left at this point, it means that we're wedged and
3705          * nothing good's going to happen by leaving them there.  So strip
3706          * the GPU domains and just stuff them onto inactive.
3707          */
3708         while (!list_empty(&dev_priv->mm.active_list)) {
3709                 struct drm_i915_gem_object *obj_priv;
3710
3711                 obj_priv = list_first_entry(&dev_priv->mm.active_list,
3712                                             struct drm_i915_gem_object,
3713                                             list);
3714                 obj_priv->obj->write_domain &= ~I915_GEM_GPU_DOMAINS;
3715                 i915_gem_object_move_to_inactive(obj_priv->obj);
3716         }
3717         spin_unlock(&dev_priv->mm.active_list_lock);
3718
3719         while (!list_empty(&dev_priv->mm.flushing_list)) {
3720                 struct drm_i915_gem_object *obj_priv;
3721
3722                 obj_priv = list_first_entry(&dev_priv->mm.flushing_list,
3723                                             struct drm_i915_gem_object,
3724                                             list);
3725                 obj_priv->obj->write_domain &= ~I915_GEM_GPU_DOMAINS;
3726                 i915_gem_object_move_to_inactive(obj_priv->obj);
3727         }
3728
3729
3730         /* Move all inactive buffers out of the GTT. */
3731         ret = i915_gem_evict_from_list(dev, &dev_priv->mm.inactive_list);
3732         WARN_ON(!list_empty(&dev_priv->mm.inactive_list));
3733         if (ret) {
3734                 mutex_unlock(&dev->struct_mutex);
3735                 return ret;
3736         }
3737
3738         i915_gem_cleanup_ringbuffer(dev);
3739         mutex_unlock(&dev->struct_mutex);
3740
3741         return 0;
3742 }
3743
3744 static int
3745 i915_gem_init_hws(struct drm_device *dev)
3746 {
3747         drm_i915_private_t *dev_priv = dev->dev_private;
3748         struct drm_gem_object *obj;
3749         struct drm_i915_gem_object *obj_priv;
3750         int ret;
3751
3752         /* If we need a physical address for the status page, it's already
3753          * initialized at driver load time.
3754          */
3755         if (!I915_NEED_GFX_HWS(dev))
3756                 return 0;
3757
3758         obj = drm_gem_object_alloc(dev, 4096);
3759         if (obj == NULL) {
3760                 DRM_ERROR("Failed to allocate status page\n");
3761                 return -ENOMEM;
3762         }
3763         obj_priv = obj->driver_private;
3764         obj_priv->agp_type = AGP_USER_CACHED_MEMORY;
3765
3766         ret = i915_gem_object_pin(obj, 4096);
3767         if (ret != 0) {
3768                 drm_gem_object_unreference(obj);
3769                 return ret;
3770         }
3771
3772         dev_priv->status_gfx_addr = obj_priv->gtt_offset;
3773
3774         dev_priv->hw_status_page = kmap(obj_priv->pages[0]);
3775         if (dev_priv->hw_status_page == NULL) {
3776                 DRM_ERROR("Failed to map status page.\n");
3777                 memset(&dev_priv->hws_map, 0, sizeof(dev_priv->hws_map));
3778                 i915_gem_object_unpin(obj);
3779                 drm_gem_object_unreference(obj);
3780                 return -EINVAL;
3781         }
3782         dev_priv->hws_obj = obj;
3783         memset(dev_priv->hw_status_page, 0, PAGE_SIZE);
3784         I915_WRITE(HWS_PGA, dev_priv->status_gfx_addr);
3785         I915_READ(HWS_PGA); /* posting read */
3786         DRM_DEBUG("hws offset: 0x%08x\n", dev_priv->status_gfx_addr);
3787
3788         return 0;
3789 }
3790
3791 static void
3792 i915_gem_cleanup_hws(struct drm_device *dev)
3793 {
3794         drm_i915_private_t *dev_priv = dev->dev_private;
3795         struct drm_gem_object *obj;
3796         struct drm_i915_gem_object *obj_priv;
3797
3798         if (dev_priv->hws_obj == NULL)
3799                 return;
3800
3801         obj = dev_priv->hws_obj;
3802         obj_priv = obj->driver_private;
3803
3804         kunmap(obj_priv->pages[0]);
3805         i915_gem_object_unpin(obj);
3806         drm_gem_object_unreference(obj);
3807         dev_priv->hws_obj = NULL;
3808
3809         memset(&dev_priv->hws_map, 0, sizeof(dev_priv->hws_map));
3810         dev_priv->hw_status_page = NULL;
3811
3812         /* Write high address into HWS_PGA when disabling. */
3813         I915_WRITE(HWS_PGA, 0x1ffff000);
3814 }
3815
3816 int
3817 i915_gem_init_ringbuffer(struct drm_device *dev)
3818 {
3819         drm_i915_private_t *dev_priv = dev->dev_private;
3820         struct drm_gem_object *obj;
3821         struct drm_i915_gem_object *obj_priv;
3822         drm_i915_ring_buffer_t *ring = &dev_priv->ring;
3823         int ret;
3824         u32 head;
3825
3826         ret = i915_gem_init_hws(dev);
3827         if (ret != 0)
3828                 return ret;
3829
3830         obj = drm_gem_object_alloc(dev, 128 * 1024);
3831         if (obj == NULL) {
3832                 DRM_ERROR("Failed to allocate ringbuffer\n");
3833                 i915_gem_cleanup_hws(dev);
3834                 return -ENOMEM;
3835         }
3836         obj_priv = obj->driver_private;
3837
3838         ret = i915_gem_object_pin(obj, 4096);
3839         if (ret != 0) {
3840                 drm_gem_object_unreference(obj);
3841                 i915_gem_cleanup_hws(dev);
3842                 return ret;
3843         }
3844
3845         /* Set up the kernel mapping for the ring. */
3846         ring->Size = obj->size;
3847         ring->tail_mask = obj->size - 1;
3848
3849         ring->map.offset = dev->agp->base + obj_priv->gtt_offset;
3850         ring->map.size = obj->size;
3851         ring->map.type = 0;
3852         ring->map.flags = 0;
3853         ring->map.mtrr = 0;
3854
3855         drm_core_ioremap_wc(&ring->map, dev);
3856         if (ring->map.handle == NULL) {
3857                 DRM_ERROR("Failed to map ringbuffer.\n");
3858                 memset(&dev_priv->ring, 0, sizeof(dev_priv->ring));
3859                 i915_gem_object_unpin(obj);
3860                 drm_gem_object_unreference(obj);
3861                 i915_gem_cleanup_hws(dev);
3862                 return -EINVAL;
3863         }
3864         ring->ring_obj = obj;
3865         ring->virtual_start = ring->map.handle;
3866
3867         /* Stop the ring if it's running. */
3868         I915_WRITE(PRB0_CTL, 0);
3869         I915_WRITE(PRB0_TAIL, 0);
3870         I915_WRITE(PRB0_HEAD, 0);
3871
3872         /* Initialize the ring. */
3873         I915_WRITE(PRB0_START, obj_priv->gtt_offset);
3874         head = I915_READ(PRB0_HEAD) & HEAD_ADDR;
3875
3876         /* G45 ring initialization fails to reset head to zero */
3877         if (head != 0) {
3878                 DRM_ERROR("Ring head not reset to zero "
3879                           "ctl %08x head %08x tail %08x start %08x\n",
3880                           I915_READ(PRB0_CTL),
3881                           I915_READ(PRB0_HEAD),
3882                           I915_READ(PRB0_TAIL),
3883                           I915_READ(PRB0_START));
3884                 I915_WRITE(PRB0_HEAD, 0);
3885
3886                 DRM_ERROR("Ring head forced to zero "
3887                           "ctl %08x head %08x tail %08x start %08x\n",
3888                           I915_READ(PRB0_CTL),
3889                           I915_READ(PRB0_HEAD),
3890                           I915_READ(PRB0_TAIL),
3891                           I915_READ(PRB0_START));
3892         }
3893
3894         I915_WRITE(PRB0_CTL,
3895                    ((obj->size - 4096) & RING_NR_PAGES) |
3896                    RING_NO_REPORT |
3897                    RING_VALID);
3898
3899         head = I915_READ(PRB0_HEAD) & HEAD_ADDR;
3900
3901         /* If the head is still not zero, the ring is dead */
3902         if (head != 0) {
3903                 DRM_ERROR("Ring initialization failed "
3904                           "ctl %08x head %08x tail %08x start %08x\n",
3905                           I915_READ(PRB0_CTL),
3906                           I915_READ(PRB0_HEAD),
3907                           I915_READ(PRB0_TAIL),
3908                           I915_READ(PRB0_START));
3909                 return -EIO;
3910         }
3911
3912         /* Update our cache of the ring state */
3913         if (!drm_core_check_feature(dev, DRIVER_MODESET))
3914                 i915_kernel_lost_context(dev);
3915         else {
3916                 ring->head = I915_READ(PRB0_HEAD) & HEAD_ADDR;
3917                 ring->tail = I915_READ(PRB0_TAIL) & TAIL_ADDR;
3918                 ring->space = ring->head - (ring->tail + 8);
3919                 if (ring->space < 0)
3920                         ring->space += ring->Size;
3921         }
3922
3923         return 0;
3924 }
3925
3926 void
3927 i915_gem_cleanup_ringbuffer(struct drm_device *dev)
3928 {
3929         drm_i915_private_t *dev_priv = dev->dev_private;
3930
3931         if (dev_priv->ring.ring_obj == NULL)
3932                 return;
3933
3934         drm_core_ioremapfree(&dev_priv->ring.map, dev);
3935
3936         i915_gem_object_unpin(dev_priv->ring.ring_obj);
3937         drm_gem_object_unreference(dev_priv->ring.ring_obj);
3938         dev_priv->ring.ring_obj = NULL;
3939         memset(&dev_priv->ring, 0, sizeof(dev_priv->ring));
3940
3941         i915_gem_cleanup_hws(dev);
3942 }
3943
3944 int
3945 i915_gem_entervt_ioctl(struct drm_device *dev, void *data,
3946                        struct drm_file *file_priv)
3947 {
3948         drm_i915_private_t *dev_priv = dev->dev_private;
3949         int ret;
3950
3951         if (drm_core_check_feature(dev, DRIVER_MODESET))
3952                 return 0;
3953
3954         if (dev_priv->mm.wedged) {
3955                 DRM_ERROR("Reenabling wedged hardware, good luck\n");
3956                 dev_priv->mm.wedged = 0;
3957         }
3958
3959         mutex_lock(&dev->struct_mutex);
3960         dev_priv->mm.suspended = 0;
3961
3962         ret = i915_gem_init_ringbuffer(dev);
3963         if (ret != 0)
3964                 return ret;
3965
3966         spin_lock(&dev_priv->mm.active_list_lock);
3967         BUG_ON(!list_empty(&dev_priv->mm.active_list));
3968         spin_unlock(&dev_priv->mm.active_list_lock);
3969
3970         BUG_ON(!list_empty(&dev_priv->mm.flushing_list));
3971         BUG_ON(!list_empty(&dev_priv->mm.inactive_list));
3972         BUG_ON(!list_empty(&dev_priv->mm.request_list));
3973         mutex_unlock(&dev->struct_mutex);
3974
3975         drm_irq_install(dev);
3976
3977         return 0;
3978 }
3979
3980 int
3981 i915_gem_leavevt_ioctl(struct drm_device *dev, void *data,
3982                        struct drm_file *file_priv)
3983 {
3984         int ret;
3985
3986         if (drm_core_check_feature(dev, DRIVER_MODESET))
3987                 return 0;
3988
3989         ret = i915_gem_idle(dev);
3990         drm_irq_uninstall(dev);
3991
3992         return ret;
3993 }
3994
3995 void
3996 i915_gem_lastclose(struct drm_device *dev)
3997 {
3998         int ret;
3999
4000         if (drm_core_check_feature(dev, DRIVER_MODESET))
4001                 return;
4002
4003         ret = i915_gem_idle(dev);
4004         if (ret)
4005                 DRM_ERROR("failed to idle hardware: %d\n", ret);
4006 }
4007
4008 void
4009 i915_gem_load(struct drm_device *dev)
4010 {
4011         drm_i915_private_t *dev_priv = dev->dev_private;
4012
4013         spin_lock_init(&dev_priv->mm.active_list_lock);
4014         INIT_LIST_HEAD(&dev_priv->mm.active_list);
4015         INIT_LIST_HEAD(&dev_priv->mm.flushing_list);
4016         INIT_LIST_HEAD(&dev_priv->mm.inactive_list);
4017         INIT_LIST_HEAD(&dev_priv->mm.request_list);
4018         INIT_DELAYED_WORK(&dev_priv->mm.retire_work,
4019                           i915_gem_retire_work_handler);
4020         dev_priv->mm.next_gem_seqno = 1;
4021
4022         /* Old X drivers will take 0-2 for front, back, depth buffers */
4023         dev_priv->fence_reg_start = 3;
4024
4025         if (IS_I965G(dev) || IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev))
4026                 dev_priv->num_fence_regs = 16;
4027         else
4028                 dev_priv->num_fence_regs = 8;
4029
4030         i915_gem_detect_bit_6_swizzle(dev);
4031 }
4032
4033 /*
4034  * Create a physically contiguous memory object for this object
4035  * e.g. for cursor + overlay regs
4036  */
4037 int i915_gem_init_phys_object(struct drm_device *dev,
4038                               int id, int size)
4039 {
4040         drm_i915_private_t *dev_priv = dev->dev_private;
4041         struct drm_i915_gem_phys_object *phys_obj;
4042         int ret;
4043
4044         if (dev_priv->mm.phys_objs[id - 1] || !size)
4045                 return 0;
4046
4047         phys_obj = drm_calloc(1, sizeof(struct drm_i915_gem_phys_object), DRM_MEM_DRIVER);
4048         if (!phys_obj)
4049                 return -ENOMEM;
4050
4051         phys_obj->id = id;
4052
4053         phys_obj->handle = drm_pci_alloc(dev, size, 0, 0xffffffff);
4054         if (!phys_obj->handle) {
4055                 ret = -ENOMEM;
4056                 goto kfree_obj;
4057         }
4058 #ifdef CONFIG_X86
4059         set_memory_wc((unsigned long)phys_obj->handle->vaddr, phys_obj->handle->size / PAGE_SIZE);
4060 #endif
4061
4062         dev_priv->mm.phys_objs[id - 1] = phys_obj;
4063
4064         return 0;
4065 kfree_obj:
4066         drm_free(phys_obj, sizeof(struct drm_i915_gem_phys_object), DRM_MEM_DRIVER);
4067         return ret;
4068 }
4069
4070 void i915_gem_free_phys_object(struct drm_device *dev, int id)
4071 {
4072         drm_i915_private_t *dev_priv = dev->dev_private;
4073         struct drm_i915_gem_phys_object *phys_obj;
4074
4075         if (!dev_priv->mm.phys_objs[id - 1])
4076                 return;
4077
4078         phys_obj = dev_priv->mm.phys_objs[id - 1];
4079         if (phys_obj->cur_obj) {
4080                 i915_gem_detach_phys_object(dev, phys_obj->cur_obj);
4081         }
4082
4083 #ifdef CONFIG_X86
4084         set_memory_wb((unsigned long)phys_obj->handle->vaddr, phys_obj->handle->size / PAGE_SIZE);
4085 #endif
4086         drm_pci_free(dev, phys_obj->handle);
4087         kfree(phys_obj);
4088         dev_priv->mm.phys_objs[id - 1] = NULL;
4089 }
4090
4091 void i915_gem_free_all_phys_object(struct drm_device *dev)
4092 {
4093         int i;
4094
4095         for (i = I915_GEM_PHYS_CURSOR_0; i <= I915_MAX_PHYS_OBJECT; i++)
4096                 i915_gem_free_phys_object(dev, i);
4097 }
4098
4099 void i915_gem_detach_phys_object(struct drm_device *dev,
4100                                  struct drm_gem_object *obj)
4101 {
4102         struct drm_i915_gem_object *obj_priv;
4103         int i;
4104         int ret;
4105         int page_count;
4106
4107         obj_priv = obj->driver_private;
4108         if (!obj_priv->phys_obj)
4109                 return;
4110
4111         ret = i915_gem_object_get_pages(obj);
4112         if (ret)
4113                 goto out;
4114
4115         page_count = obj->size / PAGE_SIZE;
4116
4117         for (i = 0; i < page_count; i++) {
4118                 char *dst = kmap_atomic(obj_priv->pages[i], KM_USER0);
4119                 char *src = obj_priv->phys_obj->handle->vaddr + (i * PAGE_SIZE);
4120
4121                 memcpy(dst, src, PAGE_SIZE);
4122                 kunmap_atomic(dst, KM_USER0);
4123         }
4124         drm_clflush_pages(obj_priv->pages, page_count);
4125         drm_agp_chipset_flush(dev);
4126 out:
4127         obj_priv->phys_obj->cur_obj = NULL;
4128         obj_priv->phys_obj = NULL;
4129 }
4130
4131 int
4132 i915_gem_attach_phys_object(struct drm_device *dev,
4133                             struct drm_gem_object *obj, int id)
4134 {
4135         drm_i915_private_t *dev_priv = dev->dev_private;
4136         struct drm_i915_gem_object *obj_priv;
4137         int ret = 0;
4138         int page_count;
4139         int i;
4140
4141         if (id > I915_MAX_PHYS_OBJECT)
4142                 return -EINVAL;
4143
4144         obj_priv = obj->driver_private;
4145
4146         if (obj_priv->phys_obj) {
4147                 if (obj_priv->phys_obj->id == id)
4148                         return 0;
4149                 i915_gem_detach_phys_object(dev, obj);
4150         }
4151
4152
4153         /* create a new object */
4154         if (!dev_priv->mm.phys_objs[id - 1]) {
4155                 ret = i915_gem_init_phys_object(dev, id,
4156                                                 obj->size);
4157                 if (ret) {
4158                         DRM_ERROR("failed to init phys object %d size: %zu\n", id, obj->size);
4159                         goto out;
4160                 }
4161         }
4162
4163         /* bind to the object */
4164         obj_priv->phys_obj = dev_priv->mm.phys_objs[id - 1];
4165         obj_priv->phys_obj->cur_obj = obj;
4166
4167         ret = i915_gem_object_get_pages(obj);
4168         if (ret) {
4169                 DRM_ERROR("failed to get page list\n");
4170                 goto out;
4171         }
4172
4173         page_count = obj->size / PAGE_SIZE;
4174
4175         for (i = 0; i < page_count; i++) {
4176                 char *src = kmap_atomic(obj_priv->pages[i], KM_USER0);
4177                 char *dst = obj_priv->phys_obj->handle->vaddr + (i * PAGE_SIZE);
4178
4179                 memcpy(dst, src, PAGE_SIZE);
4180                 kunmap_atomic(src, KM_USER0);
4181         }
4182
4183         return 0;
4184 out:
4185         return ret;
4186 }
4187
4188 static int
4189 i915_gem_phys_pwrite(struct drm_device *dev, struct drm_gem_object *obj,
4190                      struct drm_i915_gem_pwrite *args,
4191                      struct drm_file *file_priv)
4192 {
4193         struct drm_i915_gem_object *obj_priv = obj->driver_private;
4194         void *obj_addr;
4195         int ret;
4196         char __user *user_data;
4197
4198         user_data = (char __user *) (uintptr_t) args->data_ptr;
4199         obj_addr = obj_priv->phys_obj->handle->vaddr + args->offset;
4200
4201         DRM_DEBUG("obj_addr %p, %lld\n", obj_addr, args->size);
4202         ret = copy_from_user(obj_addr, user_data, args->size);
4203         if (ret)
4204                 return -EFAULT;
4205
4206         drm_agp_chipset_flush(dev);
4207         return 0;
4208 }