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