Linux 2.6.30-rc8
[linux-2.6.git] / drivers / gpu / drm / i915 / i915_gem.c
1 /*
2  * Copyright © 2008 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  *
23  * Authors:
24  *    Eric Anholt <eric@anholt.net>
25  *
26  */
27
28 #include "drmP.h"
29 #include "drm.h"
30 #include "i915_drm.h"
31 #include "i915_drv.h"
32 #include <linux/swap.h>
33 #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 = drm_calloc_large(num_pages, sizeof(struct page *));
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         drm_free_large(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 = drm_calloc_large(num_pages, sizeof(struct page *));
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         drm_free_large(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 = drm_calloc_large(num_pages, sizeof(struct page *));
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         drm_free_large(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
1149                 ret = i915_gem_object_set_to_gtt_domain(obj, write);
1150                 if (ret) {
1151                         mutex_unlock(&dev->struct_mutex);
1152                         return VM_FAULT_SIGBUS;
1153                 }
1154
1155                 list_add_tail(&obj_priv->list, &dev_priv->mm.inactive_list);
1156         }
1157
1158         /* Need a new fence register? */
1159         if (obj_priv->fence_reg == I915_FENCE_REG_NONE &&
1160             obj_priv->tiling_mode != I915_TILING_NONE) {
1161                 ret = i915_gem_object_get_fence_reg(obj, write);
1162                 if (ret) {
1163                         mutex_unlock(&dev->struct_mutex);
1164                         return VM_FAULT_SIGBUS;
1165                 }
1166         }
1167
1168         pfn = ((dev->agp->base + obj_priv->gtt_offset) >> PAGE_SHIFT) +
1169                 page_offset;
1170
1171         /* Finally, remap it using the new GTT offset */
1172         ret = vm_insert_pfn(vma, (unsigned long)vmf->virtual_address, pfn);
1173
1174         mutex_unlock(&dev->struct_mutex);
1175
1176         switch (ret) {
1177         case -ENOMEM:
1178         case -EAGAIN:
1179                 return VM_FAULT_OOM;
1180         case -EFAULT:
1181         case -EINVAL:
1182                 return VM_FAULT_SIGBUS;
1183         default:
1184                 return VM_FAULT_NOPAGE;
1185         }
1186 }
1187
1188 /**
1189  * i915_gem_create_mmap_offset - create a fake mmap offset for an object
1190  * @obj: obj in question
1191  *
1192  * GEM memory mapping works by handing back to userspace a fake mmap offset
1193  * it can use in a subsequent mmap(2) call.  The DRM core code then looks
1194  * up the object based on the offset and sets up the various memory mapping
1195  * structures.
1196  *
1197  * This routine allocates and attaches a fake offset for @obj.
1198  */
1199 static int
1200 i915_gem_create_mmap_offset(struct drm_gem_object *obj)
1201 {
1202         struct drm_device *dev = obj->dev;
1203         struct drm_gem_mm *mm = dev->mm_private;
1204         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1205         struct drm_map_list *list;
1206         struct drm_local_map *map;
1207         int ret = 0;
1208
1209         /* Set the object up for mmap'ing */
1210         list = &obj->map_list;
1211         list->map = drm_calloc(1, sizeof(struct drm_map_list),
1212                                DRM_MEM_DRIVER);
1213         if (!list->map)
1214                 return -ENOMEM;
1215
1216         map = list->map;
1217         map->type = _DRM_GEM;
1218         map->size = obj->size;
1219         map->handle = obj;
1220
1221         /* Get a DRM GEM mmap offset allocated... */
1222         list->file_offset_node = drm_mm_search_free(&mm->offset_manager,
1223                                                     obj->size / PAGE_SIZE, 0, 0);
1224         if (!list->file_offset_node) {
1225                 DRM_ERROR("failed to allocate offset for bo %d\n", obj->name);
1226                 ret = -ENOMEM;
1227                 goto out_free_list;
1228         }
1229
1230         list->file_offset_node = drm_mm_get_block(list->file_offset_node,
1231                                                   obj->size / PAGE_SIZE, 0);
1232         if (!list->file_offset_node) {
1233                 ret = -ENOMEM;
1234                 goto out_free_list;
1235         }
1236
1237         list->hash.key = list->file_offset_node->start;
1238         if (drm_ht_insert_item(&mm->offset_hash, &list->hash)) {
1239                 DRM_ERROR("failed to add to map hash\n");
1240                 goto out_free_mm;
1241         }
1242
1243         /* By now we should be all set, any drm_mmap request on the offset
1244          * below will get to our mmap & fault handler */
1245         obj_priv->mmap_offset = ((uint64_t) list->hash.key) << PAGE_SHIFT;
1246
1247         return 0;
1248
1249 out_free_mm:
1250         drm_mm_put_block(list->file_offset_node);
1251 out_free_list:
1252         drm_free(list->map, sizeof(struct drm_map_list), DRM_MEM_DRIVER);
1253
1254         return ret;
1255 }
1256
1257 static void
1258 i915_gem_free_mmap_offset(struct drm_gem_object *obj)
1259 {
1260         struct drm_device *dev = obj->dev;
1261         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1262         struct drm_gem_mm *mm = dev->mm_private;
1263         struct drm_map_list *list;
1264
1265         list = &obj->map_list;
1266         drm_ht_remove_item(&mm->offset_hash, &list->hash);
1267
1268         if (list->file_offset_node) {
1269                 drm_mm_put_block(list->file_offset_node);
1270                 list->file_offset_node = NULL;
1271         }
1272
1273         if (list->map) {
1274                 drm_free(list->map, sizeof(struct drm_map), DRM_MEM_DRIVER);
1275                 list->map = NULL;
1276         }
1277
1278         obj_priv->mmap_offset = 0;
1279 }
1280
1281 /**
1282  * i915_gem_get_gtt_alignment - return required GTT alignment for an object
1283  * @obj: object to check
1284  *
1285  * Return the required GTT alignment for an object, taking into account
1286  * potential fence register mapping if needed.
1287  */
1288 static uint32_t
1289 i915_gem_get_gtt_alignment(struct drm_gem_object *obj)
1290 {
1291         struct drm_device *dev = obj->dev;
1292         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1293         int start, i;
1294
1295         /*
1296          * Minimum alignment is 4k (GTT page size), but might be greater
1297          * if a fence register is needed for the object.
1298          */
1299         if (IS_I965G(dev) || obj_priv->tiling_mode == I915_TILING_NONE)
1300                 return 4096;
1301
1302         /*
1303          * Previous chips need to be aligned to the size of the smallest
1304          * fence register that can contain the object.
1305          */
1306         if (IS_I9XX(dev))
1307                 start = 1024*1024;
1308         else
1309                 start = 512*1024;
1310
1311         for (i = start; i < obj->size; i <<= 1)
1312                 ;
1313
1314         return i;
1315 }
1316
1317 /**
1318  * i915_gem_mmap_gtt_ioctl - prepare an object for GTT mmap'ing
1319  * @dev: DRM device
1320  * @data: GTT mapping ioctl data
1321  * @file_priv: GEM object info
1322  *
1323  * Simply returns the fake offset to userspace so it can mmap it.
1324  * The mmap call will end up in drm_gem_mmap(), which will set things
1325  * up so we can get faults in the handler above.
1326  *
1327  * The fault handler will take care of binding the object into the GTT
1328  * (since it may have been evicted to make room for something), allocating
1329  * a fence register, and mapping the appropriate aperture address into
1330  * userspace.
1331  */
1332 int
1333 i915_gem_mmap_gtt_ioctl(struct drm_device *dev, void *data,
1334                         struct drm_file *file_priv)
1335 {
1336         struct drm_i915_gem_mmap_gtt *args = data;
1337         struct drm_i915_private *dev_priv = dev->dev_private;
1338         struct drm_gem_object *obj;
1339         struct drm_i915_gem_object *obj_priv;
1340         int ret;
1341
1342         if (!(dev->driver->driver_features & DRIVER_GEM))
1343                 return -ENODEV;
1344
1345         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
1346         if (obj == NULL)
1347                 return -EBADF;
1348
1349         mutex_lock(&dev->struct_mutex);
1350
1351         obj_priv = obj->driver_private;
1352
1353         if (!obj_priv->mmap_offset) {
1354                 ret = i915_gem_create_mmap_offset(obj);
1355                 if (ret) {
1356                         drm_gem_object_unreference(obj);
1357                         mutex_unlock(&dev->struct_mutex);
1358                         return ret;
1359                 }
1360         }
1361
1362         args->offset = obj_priv->mmap_offset;
1363
1364         obj_priv->gtt_alignment = i915_gem_get_gtt_alignment(obj);
1365
1366         /* Make sure the alignment is correct for fence regs etc */
1367         if (obj_priv->agp_mem &&
1368             (obj_priv->gtt_offset & (obj_priv->gtt_alignment - 1))) {
1369                 drm_gem_object_unreference(obj);
1370                 mutex_unlock(&dev->struct_mutex);
1371                 return -EINVAL;
1372         }
1373
1374         /*
1375          * Pull it into the GTT so that we have a page list (makes the
1376          * initial fault faster and any subsequent flushing possible).
1377          */
1378         if (!obj_priv->agp_mem) {
1379                 ret = i915_gem_object_bind_to_gtt(obj, obj_priv->gtt_alignment);
1380                 if (ret) {
1381                         drm_gem_object_unreference(obj);
1382                         mutex_unlock(&dev->struct_mutex);
1383                         return ret;
1384                 }
1385                 list_add_tail(&obj_priv->list, &dev_priv->mm.inactive_list);
1386         }
1387
1388         drm_gem_object_unreference(obj);
1389         mutex_unlock(&dev->struct_mutex);
1390
1391         return 0;
1392 }
1393
1394 void
1395 i915_gem_object_put_pages(struct drm_gem_object *obj)
1396 {
1397         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1398         int page_count = obj->size / PAGE_SIZE;
1399         int i;
1400
1401         BUG_ON(obj_priv->pages_refcount == 0);
1402
1403         if (--obj_priv->pages_refcount != 0)
1404                 return;
1405
1406         if (obj_priv->tiling_mode != I915_TILING_NONE)
1407                 i915_gem_object_save_bit_17_swizzle(obj);
1408
1409         for (i = 0; i < page_count; i++)
1410                 if (obj_priv->pages[i] != NULL) {
1411                         if (obj_priv->dirty)
1412                                 set_page_dirty(obj_priv->pages[i]);
1413                         mark_page_accessed(obj_priv->pages[i]);
1414                         page_cache_release(obj_priv->pages[i]);
1415                 }
1416         obj_priv->dirty = 0;
1417
1418         drm_free_large(obj_priv->pages);
1419         obj_priv->pages = NULL;
1420 }
1421
1422 static void
1423 i915_gem_object_move_to_active(struct drm_gem_object *obj, uint32_t seqno)
1424 {
1425         struct drm_device *dev = obj->dev;
1426         drm_i915_private_t *dev_priv = dev->dev_private;
1427         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1428
1429         /* Add a reference if we're newly entering the active list. */
1430         if (!obj_priv->active) {
1431                 drm_gem_object_reference(obj);
1432                 obj_priv->active = 1;
1433         }
1434         /* Move from whatever list we were on to the tail of execution. */
1435         spin_lock(&dev_priv->mm.active_list_lock);
1436         list_move_tail(&obj_priv->list,
1437                        &dev_priv->mm.active_list);
1438         spin_unlock(&dev_priv->mm.active_list_lock);
1439         obj_priv->last_rendering_seqno = seqno;
1440 }
1441
1442 static void
1443 i915_gem_object_move_to_flushing(struct drm_gem_object *obj)
1444 {
1445         struct drm_device *dev = obj->dev;
1446         drm_i915_private_t *dev_priv = dev->dev_private;
1447         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1448
1449         BUG_ON(!obj_priv->active);
1450         list_move_tail(&obj_priv->list, &dev_priv->mm.flushing_list);
1451         obj_priv->last_rendering_seqno = 0;
1452 }
1453
1454 static void
1455 i915_gem_object_move_to_inactive(struct drm_gem_object *obj)
1456 {
1457         struct drm_device *dev = obj->dev;
1458         drm_i915_private_t *dev_priv = dev->dev_private;
1459         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1460
1461         i915_verify_inactive(dev, __FILE__, __LINE__);
1462         if (obj_priv->pin_count != 0)
1463                 list_del_init(&obj_priv->list);
1464         else
1465                 list_move_tail(&obj_priv->list, &dev_priv->mm.inactive_list);
1466
1467         obj_priv->last_rendering_seqno = 0;
1468         if (obj_priv->active) {
1469                 obj_priv->active = 0;
1470                 drm_gem_object_unreference(obj);
1471         }
1472         i915_verify_inactive(dev, __FILE__, __LINE__);
1473 }
1474
1475 /**
1476  * Creates a new sequence number, emitting a write of it to the status page
1477  * plus an interrupt, which will trigger i915_user_interrupt_handler.
1478  *
1479  * Must be called with struct_lock held.
1480  *
1481  * Returned sequence numbers are nonzero on success.
1482  */
1483 static uint32_t
1484 i915_add_request(struct drm_device *dev, uint32_t flush_domains)
1485 {
1486         drm_i915_private_t *dev_priv = dev->dev_private;
1487         struct drm_i915_gem_request *request;
1488         uint32_t seqno;
1489         int was_empty;
1490         RING_LOCALS;
1491
1492         request = drm_calloc(1, sizeof(*request), DRM_MEM_DRIVER);
1493         if (request == NULL)
1494                 return 0;
1495
1496         /* Grab the seqno we're going to make this request be, and bump the
1497          * next (skipping 0 so it can be the reserved no-seqno value).
1498          */
1499         seqno = dev_priv->mm.next_gem_seqno;
1500         dev_priv->mm.next_gem_seqno++;
1501         if (dev_priv->mm.next_gem_seqno == 0)
1502                 dev_priv->mm.next_gem_seqno++;
1503
1504         BEGIN_LP_RING(4);
1505         OUT_RING(MI_STORE_DWORD_INDEX);
1506         OUT_RING(I915_GEM_HWS_INDEX << MI_STORE_DWORD_INDEX_SHIFT);
1507         OUT_RING(seqno);
1508
1509         OUT_RING(MI_USER_INTERRUPT);
1510         ADVANCE_LP_RING();
1511
1512         DRM_DEBUG("%d\n", seqno);
1513
1514         request->seqno = seqno;
1515         request->emitted_jiffies = jiffies;
1516         was_empty = list_empty(&dev_priv->mm.request_list);
1517         list_add_tail(&request->list, &dev_priv->mm.request_list);
1518
1519         /* Associate any objects on the flushing list matching the write
1520          * domain we're flushing with our flush.
1521          */
1522         if (flush_domains != 0) {
1523                 struct drm_i915_gem_object *obj_priv, *next;
1524
1525                 list_for_each_entry_safe(obj_priv, next,
1526                                          &dev_priv->mm.flushing_list, list) {
1527                         struct drm_gem_object *obj = obj_priv->obj;
1528
1529                         if ((obj->write_domain & flush_domains) ==
1530                             obj->write_domain) {
1531                                 obj->write_domain = 0;
1532                                 i915_gem_object_move_to_active(obj, seqno);
1533                         }
1534                 }
1535
1536         }
1537
1538         if (was_empty && !dev_priv->mm.suspended)
1539                 schedule_delayed_work(&dev_priv->mm.retire_work, HZ);
1540         return seqno;
1541 }
1542
1543 /**
1544  * Command execution barrier
1545  *
1546  * Ensures that all commands in the ring are finished
1547  * before signalling the CPU
1548  */
1549 static uint32_t
1550 i915_retire_commands(struct drm_device *dev)
1551 {
1552         drm_i915_private_t *dev_priv = dev->dev_private;
1553         uint32_t cmd = MI_FLUSH | MI_NO_WRITE_FLUSH;
1554         uint32_t flush_domains = 0;
1555         RING_LOCALS;
1556
1557         /* The sampler always gets flushed on i965 (sigh) */
1558         if (IS_I965G(dev))
1559                 flush_domains |= I915_GEM_DOMAIN_SAMPLER;
1560         BEGIN_LP_RING(2);
1561         OUT_RING(cmd);
1562         OUT_RING(0); /* noop */
1563         ADVANCE_LP_RING();
1564         return flush_domains;
1565 }
1566
1567 /**
1568  * Moves buffers associated only with the given active seqno from the active
1569  * to inactive list, potentially freeing them.
1570  */
1571 static void
1572 i915_gem_retire_request(struct drm_device *dev,
1573                         struct drm_i915_gem_request *request)
1574 {
1575         drm_i915_private_t *dev_priv = dev->dev_private;
1576
1577         /* Move any buffers on the active list that are no longer referenced
1578          * by the ringbuffer to the flushing/inactive lists as appropriate.
1579          */
1580         spin_lock(&dev_priv->mm.active_list_lock);
1581         while (!list_empty(&dev_priv->mm.active_list)) {
1582                 struct drm_gem_object *obj;
1583                 struct drm_i915_gem_object *obj_priv;
1584
1585                 obj_priv = list_first_entry(&dev_priv->mm.active_list,
1586                                             struct drm_i915_gem_object,
1587                                             list);
1588                 obj = obj_priv->obj;
1589
1590                 /* If the seqno being retired doesn't match the oldest in the
1591                  * list, then the oldest in the list must still be newer than
1592                  * this seqno.
1593                  */
1594                 if (obj_priv->last_rendering_seqno != request->seqno)
1595                         goto out;
1596
1597 #if WATCH_LRU
1598                 DRM_INFO("%s: retire %d moves to inactive list %p\n",
1599                          __func__, request->seqno, obj);
1600 #endif
1601
1602                 if (obj->write_domain != 0)
1603                         i915_gem_object_move_to_flushing(obj);
1604                 else {
1605                         /* Take a reference on the object so it won't be
1606                          * freed while the spinlock is held.  The list
1607                          * protection for this spinlock is safe when breaking
1608                          * the lock like this since the next thing we do
1609                          * is just get the head of the list again.
1610                          */
1611                         drm_gem_object_reference(obj);
1612                         i915_gem_object_move_to_inactive(obj);
1613                         spin_unlock(&dev_priv->mm.active_list_lock);
1614                         drm_gem_object_unreference(obj);
1615                         spin_lock(&dev_priv->mm.active_list_lock);
1616                 }
1617         }
1618 out:
1619         spin_unlock(&dev_priv->mm.active_list_lock);
1620 }
1621
1622 /**
1623  * Returns true if seq1 is later than seq2.
1624  */
1625 static int
1626 i915_seqno_passed(uint32_t seq1, uint32_t seq2)
1627 {
1628         return (int32_t)(seq1 - seq2) >= 0;
1629 }
1630
1631 uint32_t
1632 i915_get_gem_seqno(struct drm_device *dev)
1633 {
1634         drm_i915_private_t *dev_priv = dev->dev_private;
1635
1636         return READ_HWSP(dev_priv, I915_GEM_HWS_INDEX);
1637 }
1638
1639 /**
1640  * This function clears the request list as sequence numbers are passed.
1641  */
1642 void
1643 i915_gem_retire_requests(struct drm_device *dev)
1644 {
1645         drm_i915_private_t *dev_priv = dev->dev_private;
1646         uint32_t seqno;
1647
1648         if (!dev_priv->hw_status_page)
1649                 return;
1650
1651         seqno = i915_get_gem_seqno(dev);
1652
1653         while (!list_empty(&dev_priv->mm.request_list)) {
1654                 struct drm_i915_gem_request *request;
1655                 uint32_t retiring_seqno;
1656
1657                 request = list_first_entry(&dev_priv->mm.request_list,
1658                                            struct drm_i915_gem_request,
1659                                            list);
1660                 retiring_seqno = request->seqno;
1661
1662                 if (i915_seqno_passed(seqno, retiring_seqno) ||
1663                     dev_priv->mm.wedged) {
1664                         i915_gem_retire_request(dev, request);
1665
1666                         list_del(&request->list);
1667                         drm_free(request, sizeof(*request), DRM_MEM_DRIVER);
1668                 } else
1669                         break;
1670         }
1671 }
1672
1673 void
1674 i915_gem_retire_work_handler(struct work_struct *work)
1675 {
1676         drm_i915_private_t *dev_priv;
1677         struct drm_device *dev;
1678
1679         dev_priv = container_of(work, drm_i915_private_t,
1680                                 mm.retire_work.work);
1681         dev = dev_priv->dev;
1682
1683         mutex_lock(&dev->struct_mutex);
1684         i915_gem_retire_requests(dev);
1685         if (!dev_priv->mm.suspended &&
1686             !list_empty(&dev_priv->mm.request_list))
1687                 schedule_delayed_work(&dev_priv->mm.retire_work, HZ);
1688         mutex_unlock(&dev->struct_mutex);
1689 }
1690
1691 /**
1692  * Waits for a sequence number to be signaled, and cleans up the
1693  * request and object lists appropriately for that event.
1694  */
1695 static int
1696 i915_wait_request(struct drm_device *dev, uint32_t seqno)
1697 {
1698         drm_i915_private_t *dev_priv = dev->dev_private;
1699         u32 ier;
1700         int ret = 0;
1701
1702         BUG_ON(seqno == 0);
1703
1704         if (!i915_seqno_passed(i915_get_gem_seqno(dev), seqno)) {
1705                 ier = I915_READ(IER);
1706                 if (!ier) {
1707                         DRM_ERROR("something (likely vbetool) disabled "
1708                                   "interrupts, re-enabling\n");
1709                         i915_driver_irq_preinstall(dev);
1710                         i915_driver_irq_postinstall(dev);
1711                 }
1712
1713                 dev_priv->mm.waiting_gem_seqno = seqno;
1714                 i915_user_irq_get(dev);
1715                 ret = wait_event_interruptible(dev_priv->irq_queue,
1716                                                i915_seqno_passed(i915_get_gem_seqno(dev),
1717                                                                  seqno) ||
1718                                                dev_priv->mm.wedged);
1719                 i915_user_irq_put(dev);
1720                 dev_priv->mm.waiting_gem_seqno = 0;
1721         }
1722         if (dev_priv->mm.wedged)
1723                 ret = -EIO;
1724
1725         if (ret && ret != -ERESTARTSYS)
1726                 DRM_ERROR("%s returns %d (awaiting %d at %d)\n",
1727                           __func__, ret, seqno, i915_get_gem_seqno(dev));
1728
1729         /* Directly dispatch request retiring.  While we have the work queue
1730          * to handle this, the waiter on a request often wants an associated
1731          * buffer to have made it to the inactive list, and we would need
1732          * a separate wait queue to handle that.
1733          */
1734         if (ret == 0)
1735                 i915_gem_retire_requests(dev);
1736
1737         return ret;
1738 }
1739
1740 static void
1741 i915_gem_flush(struct drm_device *dev,
1742                uint32_t invalidate_domains,
1743                uint32_t flush_domains)
1744 {
1745         drm_i915_private_t *dev_priv = dev->dev_private;
1746         uint32_t cmd;
1747         RING_LOCALS;
1748
1749 #if WATCH_EXEC
1750         DRM_INFO("%s: invalidate %08x flush %08x\n", __func__,
1751                   invalidate_domains, flush_domains);
1752 #endif
1753
1754         if (flush_domains & I915_GEM_DOMAIN_CPU)
1755                 drm_agp_chipset_flush(dev);
1756
1757         if ((invalidate_domains | flush_domains) & ~(I915_GEM_DOMAIN_CPU |
1758                                                      I915_GEM_DOMAIN_GTT)) {
1759                 /*
1760                  * read/write caches:
1761                  *
1762                  * I915_GEM_DOMAIN_RENDER is always invalidated, but is
1763                  * only flushed if MI_NO_WRITE_FLUSH is unset.  On 965, it is
1764                  * also flushed at 2d versus 3d pipeline switches.
1765                  *
1766                  * read-only caches:
1767                  *
1768                  * I915_GEM_DOMAIN_SAMPLER is flushed on pre-965 if
1769                  * MI_READ_FLUSH is set, and is always flushed on 965.
1770                  *
1771                  * I915_GEM_DOMAIN_COMMAND may not exist?
1772                  *
1773                  * I915_GEM_DOMAIN_INSTRUCTION, which exists on 965, is
1774                  * invalidated when MI_EXE_FLUSH is set.
1775                  *
1776                  * I915_GEM_DOMAIN_VERTEX, which exists on 965, is
1777                  * invalidated with every MI_FLUSH.
1778                  *
1779                  * TLBs:
1780                  *
1781                  * On 965, TLBs associated with I915_GEM_DOMAIN_COMMAND
1782                  * and I915_GEM_DOMAIN_CPU in are invalidated at PTE write and
1783                  * I915_GEM_DOMAIN_RENDER and I915_GEM_DOMAIN_SAMPLER
1784                  * are flushed at any MI_FLUSH.
1785                  */
1786
1787                 cmd = MI_FLUSH | MI_NO_WRITE_FLUSH;
1788                 if ((invalidate_domains|flush_domains) &
1789                     I915_GEM_DOMAIN_RENDER)
1790                         cmd &= ~MI_NO_WRITE_FLUSH;
1791                 if (!IS_I965G(dev)) {
1792                         /*
1793                          * On the 965, the sampler cache always gets flushed
1794                          * and this bit is reserved.
1795                          */
1796                         if (invalidate_domains & I915_GEM_DOMAIN_SAMPLER)
1797                                 cmd |= MI_READ_FLUSH;
1798                 }
1799                 if (invalidate_domains & I915_GEM_DOMAIN_INSTRUCTION)
1800                         cmd |= MI_EXE_FLUSH;
1801
1802 #if WATCH_EXEC
1803                 DRM_INFO("%s: queue flush %08x to ring\n", __func__, cmd);
1804 #endif
1805                 BEGIN_LP_RING(2);
1806                 OUT_RING(cmd);
1807                 OUT_RING(0); /* noop */
1808                 ADVANCE_LP_RING();
1809         }
1810 }
1811
1812 /**
1813  * Ensures that all rendering to the object has completed and the object is
1814  * safe to unbind from the GTT or access from the CPU.
1815  */
1816 static int
1817 i915_gem_object_wait_rendering(struct drm_gem_object *obj)
1818 {
1819         struct drm_device *dev = obj->dev;
1820         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1821         int ret;
1822
1823         /* This function only exists to support waiting for existing rendering,
1824          * not for emitting required flushes.
1825          */
1826         BUG_ON((obj->write_domain & I915_GEM_GPU_DOMAINS) != 0);
1827
1828         /* If there is rendering queued on the buffer being evicted, wait for
1829          * it.
1830          */
1831         if (obj_priv->active) {
1832 #if WATCH_BUF
1833                 DRM_INFO("%s: object %p wait for seqno %08x\n",
1834                           __func__, obj, obj_priv->last_rendering_seqno);
1835 #endif
1836                 ret = i915_wait_request(dev, obj_priv->last_rendering_seqno);
1837                 if (ret != 0)
1838                         return ret;
1839         }
1840
1841         return 0;
1842 }
1843
1844 /**
1845  * Unbinds an object from the GTT aperture.
1846  */
1847 int
1848 i915_gem_object_unbind(struct drm_gem_object *obj)
1849 {
1850         struct drm_device *dev = obj->dev;
1851         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1852         loff_t offset;
1853         int ret = 0;
1854
1855 #if WATCH_BUF
1856         DRM_INFO("%s:%d %p\n", __func__, __LINE__, obj);
1857         DRM_INFO("gtt_space %p\n", obj_priv->gtt_space);
1858 #endif
1859         if (obj_priv->gtt_space == NULL)
1860                 return 0;
1861
1862         if (obj_priv->pin_count != 0) {
1863                 DRM_ERROR("Attempting to unbind pinned buffer\n");
1864                 return -EINVAL;
1865         }
1866
1867         /* Move the object to the CPU domain to ensure that
1868          * any possible CPU writes while it's not in the GTT
1869          * are flushed when we go to remap it. This will
1870          * also ensure that all pending GPU writes are finished
1871          * before we unbind.
1872          */
1873         ret = i915_gem_object_set_to_cpu_domain(obj, 1);
1874         if (ret) {
1875                 if (ret != -ERESTARTSYS)
1876                         DRM_ERROR("set_domain failed: %d\n", ret);
1877                 return ret;
1878         }
1879
1880         if (obj_priv->agp_mem != NULL) {
1881                 drm_unbind_agp(obj_priv->agp_mem);
1882                 drm_free_agp(obj_priv->agp_mem, obj->size / PAGE_SIZE);
1883                 obj_priv->agp_mem = NULL;
1884         }
1885
1886         BUG_ON(obj_priv->active);
1887
1888         /* blow away mappings if mapped through GTT */
1889         offset = ((loff_t) obj->map_list.hash.key) << PAGE_SHIFT;
1890         if (dev->dev_mapping)
1891                 unmap_mapping_range(dev->dev_mapping, offset, obj->size, 1);
1892
1893         if (obj_priv->fence_reg != I915_FENCE_REG_NONE)
1894                 i915_gem_clear_fence_reg(obj);
1895
1896         i915_gem_object_put_pages(obj);
1897
1898         if (obj_priv->gtt_space) {
1899                 atomic_dec(&dev->gtt_count);
1900                 atomic_sub(obj->size, &dev->gtt_memory);
1901
1902                 drm_mm_put_block(obj_priv->gtt_space);
1903                 obj_priv->gtt_space = NULL;
1904         }
1905
1906         /* Remove ourselves from the LRU list if present. */
1907         if (!list_empty(&obj_priv->list))
1908                 list_del_init(&obj_priv->list);
1909
1910         return 0;
1911 }
1912
1913 static int
1914 i915_gem_evict_something(struct drm_device *dev)
1915 {
1916         drm_i915_private_t *dev_priv = dev->dev_private;
1917         struct drm_gem_object *obj;
1918         struct drm_i915_gem_object *obj_priv;
1919         int ret = 0;
1920
1921         for (;;) {
1922                 /* If there's an inactive buffer available now, grab it
1923                  * and be done.
1924                  */
1925                 if (!list_empty(&dev_priv->mm.inactive_list)) {
1926                         obj_priv = list_first_entry(&dev_priv->mm.inactive_list,
1927                                                     struct drm_i915_gem_object,
1928                                                     list);
1929                         obj = obj_priv->obj;
1930                         BUG_ON(obj_priv->pin_count != 0);
1931 #if WATCH_LRU
1932                         DRM_INFO("%s: evicting %p\n", __func__, obj);
1933 #endif
1934                         BUG_ON(obj_priv->active);
1935
1936                         /* Wait on the rendering and unbind the buffer. */
1937                         ret = i915_gem_object_unbind(obj);
1938                         break;
1939                 }
1940
1941                 /* If we didn't get anything, but the ring is still processing
1942                  * things, wait for one of those things to finish and hopefully
1943                  * leave us a buffer to evict.
1944                  */
1945                 if (!list_empty(&dev_priv->mm.request_list)) {
1946                         struct drm_i915_gem_request *request;
1947
1948                         request = list_first_entry(&dev_priv->mm.request_list,
1949                                                    struct drm_i915_gem_request,
1950                                                    list);
1951
1952                         ret = i915_wait_request(dev, request->seqno);
1953                         if (ret)
1954                                 break;
1955
1956                         /* if waiting caused an object to become inactive,
1957                          * then loop around and wait for it. Otherwise, we
1958                          * assume that waiting freed and unbound something,
1959                          * so there should now be some space in the GTT
1960                          */
1961                         if (!list_empty(&dev_priv->mm.inactive_list))
1962                                 continue;
1963                         break;
1964                 }
1965
1966                 /* If we didn't have anything on the request list but there
1967                  * are buffers awaiting a flush, emit one and try again.
1968                  * When we wait on it, those buffers waiting for that flush
1969                  * will get moved to inactive.
1970                  */
1971                 if (!list_empty(&dev_priv->mm.flushing_list)) {
1972                         obj_priv = list_first_entry(&dev_priv->mm.flushing_list,
1973                                                     struct drm_i915_gem_object,
1974                                                     list);
1975                         obj = obj_priv->obj;
1976
1977                         i915_gem_flush(dev,
1978                                        obj->write_domain,
1979                                        obj->write_domain);
1980                         i915_add_request(dev, obj->write_domain);
1981
1982                         obj = NULL;
1983                         continue;
1984                 }
1985
1986                 DRM_ERROR("inactive empty %d request empty %d "
1987                           "flushing empty %d\n",
1988                           list_empty(&dev_priv->mm.inactive_list),
1989                           list_empty(&dev_priv->mm.request_list),
1990                           list_empty(&dev_priv->mm.flushing_list));
1991                 /* If we didn't do any of the above, there's nothing to be done
1992                  * and we just can't fit it in.
1993                  */
1994                 return -ENOMEM;
1995         }
1996         return ret;
1997 }
1998
1999 static int
2000 i915_gem_evict_everything(struct drm_device *dev)
2001 {
2002         int ret;
2003
2004         for (;;) {
2005                 ret = i915_gem_evict_something(dev);
2006                 if (ret != 0)
2007                         break;
2008         }
2009         if (ret == -ENOMEM)
2010                 return 0;
2011         return ret;
2012 }
2013
2014 int
2015 i915_gem_object_get_pages(struct drm_gem_object *obj)
2016 {
2017         struct drm_i915_gem_object *obj_priv = obj->driver_private;
2018         int page_count, i;
2019         struct address_space *mapping;
2020         struct inode *inode;
2021         struct page *page;
2022         int ret;
2023
2024         if (obj_priv->pages_refcount++ != 0)
2025                 return 0;
2026
2027         /* Get the list of pages out of our struct file.  They'll be pinned
2028          * at this point until we release them.
2029          */
2030         page_count = obj->size / PAGE_SIZE;
2031         BUG_ON(obj_priv->pages != NULL);
2032         obj_priv->pages = drm_calloc_large(page_count, sizeof(struct page *));
2033         if (obj_priv->pages == NULL) {
2034                 DRM_ERROR("Faled to allocate page list\n");
2035                 obj_priv->pages_refcount--;
2036                 return -ENOMEM;
2037         }
2038
2039         inode = obj->filp->f_path.dentry->d_inode;
2040         mapping = inode->i_mapping;
2041         for (i = 0; i < page_count; i++) {
2042                 page = read_mapping_page(mapping, i, NULL);
2043                 if (IS_ERR(page)) {
2044                         ret = PTR_ERR(page);
2045                         DRM_ERROR("read_mapping_page failed: %d\n", ret);
2046                         i915_gem_object_put_pages(obj);
2047                         return ret;
2048                 }
2049                 obj_priv->pages[i] = page;
2050         }
2051
2052         if (obj_priv->tiling_mode != I915_TILING_NONE)
2053                 i915_gem_object_do_bit_17_swizzle(obj);
2054
2055         return 0;
2056 }
2057
2058 static void i965_write_fence_reg(struct drm_i915_fence_reg *reg)
2059 {
2060         struct drm_gem_object *obj = reg->obj;
2061         struct drm_device *dev = obj->dev;
2062         drm_i915_private_t *dev_priv = dev->dev_private;
2063         struct drm_i915_gem_object *obj_priv = obj->driver_private;
2064         int regnum = obj_priv->fence_reg;
2065         uint64_t val;
2066
2067         val = (uint64_t)((obj_priv->gtt_offset + obj->size - 4096) &
2068                     0xfffff000) << 32;
2069         val |= obj_priv->gtt_offset & 0xfffff000;
2070         val |= ((obj_priv->stride / 128) - 1) << I965_FENCE_PITCH_SHIFT;
2071         if (obj_priv->tiling_mode == I915_TILING_Y)
2072                 val |= 1 << I965_FENCE_TILING_Y_SHIFT;
2073         val |= I965_FENCE_REG_VALID;
2074
2075         I915_WRITE64(FENCE_REG_965_0 + (regnum * 8), val);
2076 }
2077
2078 static void i915_write_fence_reg(struct drm_i915_fence_reg *reg)
2079 {
2080         struct drm_gem_object *obj = reg->obj;
2081         struct drm_device *dev = obj->dev;
2082         drm_i915_private_t *dev_priv = dev->dev_private;
2083         struct drm_i915_gem_object *obj_priv = obj->driver_private;
2084         int regnum = obj_priv->fence_reg;
2085         int tile_width;
2086         uint32_t fence_reg, val;
2087         uint32_t pitch_val;
2088
2089         if ((obj_priv->gtt_offset & ~I915_FENCE_START_MASK) ||
2090             (obj_priv->gtt_offset & (obj->size - 1))) {
2091                 WARN(1, "%s: object 0x%08x not 1M or size (0x%zx) aligned\n",
2092                      __func__, obj_priv->gtt_offset, obj->size);
2093                 return;
2094         }
2095
2096         if (obj_priv->tiling_mode == I915_TILING_Y &&
2097             HAS_128_BYTE_Y_TILING(dev))
2098                 tile_width = 128;
2099         else
2100                 tile_width = 512;
2101
2102         /* Note: pitch better be a power of two tile widths */
2103         pitch_val = obj_priv->stride / tile_width;
2104         pitch_val = ffs(pitch_val) - 1;
2105
2106         val = obj_priv->gtt_offset;
2107         if (obj_priv->tiling_mode == I915_TILING_Y)
2108                 val |= 1 << I830_FENCE_TILING_Y_SHIFT;
2109         val |= I915_FENCE_SIZE_BITS(obj->size);
2110         val |= pitch_val << I830_FENCE_PITCH_SHIFT;
2111         val |= I830_FENCE_REG_VALID;
2112
2113         if (regnum < 8)
2114                 fence_reg = FENCE_REG_830_0 + (regnum * 4);
2115         else
2116                 fence_reg = FENCE_REG_945_8 + ((regnum - 8) * 4);
2117         I915_WRITE(fence_reg, val);
2118 }
2119
2120 static void i830_write_fence_reg(struct drm_i915_fence_reg *reg)
2121 {
2122         struct drm_gem_object *obj = reg->obj;
2123         struct drm_device *dev = obj->dev;
2124         drm_i915_private_t *dev_priv = dev->dev_private;
2125         struct drm_i915_gem_object *obj_priv = obj->driver_private;
2126         int regnum = obj_priv->fence_reg;
2127         uint32_t val;
2128         uint32_t pitch_val;
2129         uint32_t fence_size_bits;
2130
2131         if ((obj_priv->gtt_offset & ~I830_FENCE_START_MASK) ||
2132             (obj_priv->gtt_offset & (obj->size - 1))) {
2133                 WARN(1, "%s: object 0x%08x not 512K or size aligned\n",
2134                      __func__, obj_priv->gtt_offset);
2135                 return;
2136         }
2137
2138         pitch_val = obj_priv->stride / 128;
2139         pitch_val = ffs(pitch_val) - 1;
2140         WARN_ON(pitch_val > I830_FENCE_MAX_PITCH_VAL);
2141
2142         val = obj_priv->gtt_offset;
2143         if (obj_priv->tiling_mode == I915_TILING_Y)
2144                 val |= 1 << I830_FENCE_TILING_Y_SHIFT;
2145         fence_size_bits = I830_FENCE_SIZE_BITS(obj->size);
2146         WARN_ON(fence_size_bits & ~0x00000f00);
2147         val |= fence_size_bits;
2148         val |= pitch_val << I830_FENCE_PITCH_SHIFT;
2149         val |= I830_FENCE_REG_VALID;
2150
2151         I915_WRITE(FENCE_REG_830_0 + (regnum * 4), val);
2152
2153 }
2154
2155 /**
2156  * i915_gem_object_get_fence_reg - set up a fence reg for an object
2157  * @obj: object to map through a fence reg
2158  * @write: object is about to be written
2159  *
2160  * When mapping objects through the GTT, userspace wants to be able to write
2161  * to them without having to worry about swizzling if the object is tiled.
2162  *
2163  * This function walks the fence regs looking for a free one for @obj,
2164  * stealing one if it can't find any.
2165  *
2166  * It then sets up the reg based on the object's properties: address, pitch
2167  * and tiling format.
2168  */
2169 static int
2170 i915_gem_object_get_fence_reg(struct drm_gem_object *obj, bool write)
2171 {
2172         struct drm_device *dev = obj->dev;
2173         struct drm_i915_private *dev_priv = dev->dev_private;
2174         struct drm_i915_gem_object *obj_priv = obj->driver_private;
2175         struct drm_i915_fence_reg *reg = NULL;
2176         struct drm_i915_gem_object *old_obj_priv = NULL;
2177         int i, ret, avail;
2178
2179         switch (obj_priv->tiling_mode) {
2180         case I915_TILING_NONE:
2181                 WARN(1, "allocating a fence for non-tiled object?\n");
2182                 break;
2183         case I915_TILING_X:
2184                 if (!obj_priv->stride)
2185                         return -EINVAL;
2186                 WARN((obj_priv->stride & (512 - 1)),
2187                      "object 0x%08x is X tiled but has non-512B pitch\n",
2188                      obj_priv->gtt_offset);
2189                 break;
2190         case I915_TILING_Y:
2191                 if (!obj_priv->stride)
2192                         return -EINVAL;
2193                 WARN((obj_priv->stride & (128 - 1)),
2194                      "object 0x%08x is Y tiled but has non-128B pitch\n",
2195                      obj_priv->gtt_offset);
2196                 break;
2197         }
2198
2199         /* First try to find a free reg */
2200 try_again:
2201         avail = 0;
2202         for (i = dev_priv->fence_reg_start; i < dev_priv->num_fence_regs; i++) {
2203                 reg = &dev_priv->fence_regs[i];
2204                 if (!reg->obj)
2205                         break;
2206
2207                 old_obj_priv = reg->obj->driver_private;
2208                 if (!old_obj_priv->pin_count)
2209                     avail++;
2210         }
2211
2212         /* None available, try to steal one or wait for a user to finish */
2213         if (i == dev_priv->num_fence_regs) {
2214                 uint32_t seqno = dev_priv->mm.next_gem_seqno;
2215                 loff_t offset;
2216
2217                 if (avail == 0)
2218                         return -ENOMEM;
2219
2220                 for (i = dev_priv->fence_reg_start;
2221                      i < dev_priv->num_fence_regs; i++) {
2222                         uint32_t this_seqno;
2223
2224                         reg = &dev_priv->fence_regs[i];
2225                         old_obj_priv = reg->obj->driver_private;
2226
2227                         if (old_obj_priv->pin_count)
2228                                 continue;
2229
2230                         /* i915 uses fences for GPU access to tiled buffers */
2231                         if (IS_I965G(dev) || !old_obj_priv->active)
2232                                 break;
2233
2234                         /* find the seqno of the first available fence */
2235                         this_seqno = old_obj_priv->last_rendering_seqno;
2236                         if (this_seqno != 0 &&
2237                             reg->obj->write_domain == 0 &&
2238                             i915_seqno_passed(seqno, this_seqno))
2239                                 seqno = this_seqno;
2240                 }
2241
2242                 /*
2243                  * Now things get ugly... we have to wait for one of the
2244                  * objects to finish before trying again.
2245                  */
2246                 if (i == dev_priv->num_fence_regs) {
2247                         if (seqno == dev_priv->mm.next_gem_seqno) {
2248                                 i915_gem_flush(dev,
2249                                                I915_GEM_GPU_DOMAINS,
2250                                                I915_GEM_GPU_DOMAINS);
2251                                 seqno = i915_add_request(dev,
2252                                                          I915_GEM_GPU_DOMAINS);
2253                                 if (seqno == 0)
2254                                         return -ENOMEM;
2255                         }
2256
2257                         ret = i915_wait_request(dev, seqno);
2258                         if (ret)
2259                                 return ret;
2260                         goto try_again;
2261                 }
2262
2263                 BUG_ON(old_obj_priv->active ||
2264                        (reg->obj->write_domain & I915_GEM_GPU_DOMAINS));
2265
2266                 /*
2267                  * Zap this virtual mapping so we can set up a fence again
2268                  * for this object next time we need it.
2269                  */
2270                 offset = ((loff_t) reg->obj->map_list.hash.key) << PAGE_SHIFT;
2271                 if (dev->dev_mapping)
2272                         unmap_mapping_range(dev->dev_mapping, offset,
2273                                             reg->obj->size, 1);
2274                 old_obj_priv->fence_reg = I915_FENCE_REG_NONE;
2275         }
2276
2277         obj_priv->fence_reg = i;
2278         reg->obj = obj;
2279
2280         if (IS_I965G(dev))
2281                 i965_write_fence_reg(reg);
2282         else if (IS_I9XX(dev))
2283                 i915_write_fence_reg(reg);
2284         else
2285                 i830_write_fence_reg(reg);
2286
2287         return 0;
2288 }
2289
2290 /**
2291  * i915_gem_clear_fence_reg - clear out fence register info
2292  * @obj: object to clear
2293  *
2294  * Zeroes out the fence register itself and clears out the associated
2295  * data structures in dev_priv and obj_priv.
2296  */
2297 static void
2298 i915_gem_clear_fence_reg(struct drm_gem_object *obj)
2299 {
2300         struct drm_device *dev = obj->dev;
2301         drm_i915_private_t *dev_priv = dev->dev_private;
2302         struct drm_i915_gem_object *obj_priv = obj->driver_private;
2303
2304         if (IS_I965G(dev))
2305                 I915_WRITE64(FENCE_REG_965_0 + (obj_priv->fence_reg * 8), 0);
2306         else {
2307                 uint32_t fence_reg;
2308
2309                 if (obj_priv->fence_reg < 8)
2310                         fence_reg = FENCE_REG_830_0 + obj_priv->fence_reg * 4;
2311                 else
2312                         fence_reg = FENCE_REG_945_8 + (obj_priv->fence_reg -
2313                                                        8) * 4;
2314
2315                 I915_WRITE(fence_reg, 0);
2316         }
2317
2318         dev_priv->fence_regs[obj_priv->fence_reg].obj = NULL;
2319         obj_priv->fence_reg = I915_FENCE_REG_NONE;
2320 }
2321
2322 /**
2323  * Finds free space in the GTT aperture and binds the object there.
2324  */
2325 static int
2326 i915_gem_object_bind_to_gtt(struct drm_gem_object *obj, unsigned alignment)
2327 {
2328         struct drm_device *dev = obj->dev;
2329         drm_i915_private_t *dev_priv = dev->dev_private;
2330         struct drm_i915_gem_object *obj_priv = obj->driver_private;
2331         struct drm_mm_node *free_space;
2332         int page_count, ret;
2333
2334         if (dev_priv->mm.suspended)
2335                 return -EBUSY;
2336         if (alignment == 0)
2337                 alignment = i915_gem_get_gtt_alignment(obj);
2338         if (alignment & (i915_gem_get_gtt_alignment(obj) - 1)) {
2339                 DRM_ERROR("Invalid object alignment requested %u\n", alignment);
2340                 return -EINVAL;
2341         }
2342
2343  search_free:
2344         free_space = drm_mm_search_free(&dev_priv->mm.gtt_space,
2345                                         obj->size, alignment, 0);
2346         if (free_space != NULL) {
2347                 obj_priv->gtt_space = drm_mm_get_block(free_space, obj->size,
2348                                                        alignment);
2349                 if (obj_priv->gtt_space != NULL) {
2350                         obj_priv->gtt_space->private = obj;
2351                         obj_priv->gtt_offset = obj_priv->gtt_space->start;
2352                 }
2353         }
2354         if (obj_priv->gtt_space == NULL) {
2355                 bool lists_empty;
2356
2357                 /* If the gtt is empty and we're still having trouble
2358                  * fitting our object in, we're out of memory.
2359                  */
2360 #if WATCH_LRU
2361                 DRM_INFO("%s: GTT full, evicting something\n", __func__);
2362 #endif
2363                 spin_lock(&dev_priv->mm.active_list_lock);
2364                 lists_empty = (list_empty(&dev_priv->mm.inactive_list) &&
2365                                list_empty(&dev_priv->mm.flushing_list) &&
2366                                list_empty(&dev_priv->mm.active_list));
2367                 spin_unlock(&dev_priv->mm.active_list_lock);
2368                 if (lists_empty) {
2369                         DRM_ERROR("GTT full, but LRU list empty\n");
2370                         return -ENOMEM;
2371                 }
2372
2373                 ret = i915_gem_evict_something(dev);
2374                 if (ret != 0) {
2375                         if (ret != -ERESTARTSYS)
2376                                 DRM_ERROR("Failed to evict a buffer %d\n", ret);
2377                         return ret;
2378                 }
2379                 goto search_free;
2380         }
2381
2382 #if WATCH_BUF
2383         DRM_INFO("Binding object of size %d at 0x%08x\n",
2384                  obj->size, obj_priv->gtt_offset);
2385 #endif
2386         ret = i915_gem_object_get_pages(obj);
2387         if (ret) {
2388                 drm_mm_put_block(obj_priv->gtt_space);
2389                 obj_priv->gtt_space = NULL;
2390                 return ret;
2391         }
2392
2393         page_count = obj->size / PAGE_SIZE;
2394         /* Create an AGP memory structure pointing at our pages, and bind it
2395          * into the GTT.
2396          */
2397         obj_priv->agp_mem = drm_agp_bind_pages(dev,
2398                                                obj_priv->pages,
2399                                                page_count,
2400                                                obj_priv->gtt_offset,
2401                                                obj_priv->agp_type);
2402         if (obj_priv->agp_mem == NULL) {
2403                 i915_gem_object_put_pages(obj);
2404                 drm_mm_put_block(obj_priv->gtt_space);
2405                 obj_priv->gtt_space = NULL;
2406                 return -ENOMEM;
2407         }
2408         atomic_inc(&dev->gtt_count);
2409         atomic_add(obj->size, &dev->gtt_memory);
2410
2411         /* Assert that the object is not currently in any GPU domain. As it
2412          * wasn't in the GTT, there shouldn't be any way it could have been in
2413          * a GPU cache
2414          */
2415         BUG_ON(obj->read_domains & ~(I915_GEM_DOMAIN_CPU|I915_GEM_DOMAIN_GTT));
2416         BUG_ON(obj->write_domain & ~(I915_GEM_DOMAIN_CPU|I915_GEM_DOMAIN_GTT));
2417
2418         return 0;
2419 }
2420
2421 void
2422 i915_gem_clflush_object(struct drm_gem_object *obj)
2423 {
2424         struct drm_i915_gem_object      *obj_priv = obj->driver_private;
2425
2426         /* If we don't have a page list set up, then we're not pinned
2427          * to GPU, and we can ignore the cache flush because it'll happen
2428          * again at bind time.
2429          */
2430         if (obj_priv->pages == NULL)
2431                 return;
2432
2433         /* XXX: The 865 in particular appears to be weird in how it handles
2434          * cache flushing.  We haven't figured it out, but the
2435          * clflush+agp_chipset_flush doesn't appear to successfully get the
2436          * data visible to the PGU, while wbinvd + agp_chipset_flush does.
2437          */
2438         if (IS_I865G(obj->dev)) {
2439                 wbinvd();
2440                 return;
2441         }
2442
2443         drm_clflush_pages(obj_priv->pages, obj->size / PAGE_SIZE);
2444 }
2445
2446 /** Flushes any GPU write domain for the object if it's dirty. */
2447 static void
2448 i915_gem_object_flush_gpu_write_domain(struct drm_gem_object *obj)
2449 {
2450         struct drm_device *dev = obj->dev;
2451         uint32_t seqno;
2452
2453         if ((obj->write_domain & I915_GEM_GPU_DOMAINS) == 0)
2454                 return;
2455
2456         /* Queue the GPU write cache flushing we need. */
2457         i915_gem_flush(dev, 0, obj->write_domain);
2458         seqno = i915_add_request(dev, obj->write_domain);
2459         obj->write_domain = 0;
2460         i915_gem_object_move_to_active(obj, seqno);
2461 }
2462
2463 /** Flushes the GTT write domain for the object if it's dirty. */
2464 static void
2465 i915_gem_object_flush_gtt_write_domain(struct drm_gem_object *obj)
2466 {
2467         if (obj->write_domain != I915_GEM_DOMAIN_GTT)
2468                 return;
2469
2470         /* No actual flushing is required for the GTT write domain.   Writes
2471          * to it immediately go to main memory as far as we know, so there's
2472          * no chipset flush.  It also doesn't land in render cache.
2473          */
2474         obj->write_domain = 0;
2475 }
2476
2477 /** Flushes the CPU write domain for the object if it's dirty. */
2478 static void
2479 i915_gem_object_flush_cpu_write_domain(struct drm_gem_object *obj)
2480 {
2481         struct drm_device *dev = obj->dev;
2482
2483         if (obj->write_domain != I915_GEM_DOMAIN_CPU)
2484                 return;
2485
2486         i915_gem_clflush_object(obj);
2487         drm_agp_chipset_flush(dev);
2488         obj->write_domain = 0;
2489 }
2490
2491 /**
2492  * Moves a single object to the GTT read, and possibly write domain.
2493  *
2494  * This function returns when the move is complete, including waiting on
2495  * flushes to occur.
2496  */
2497 int
2498 i915_gem_object_set_to_gtt_domain(struct drm_gem_object *obj, int write)
2499 {
2500         struct drm_i915_gem_object *obj_priv = obj->driver_private;
2501         int ret;
2502
2503         /* Not valid to be called on unbound objects. */
2504         if (obj_priv->gtt_space == NULL)
2505                 return -EINVAL;
2506
2507         i915_gem_object_flush_gpu_write_domain(obj);
2508         /* Wait on any GPU rendering and flushing to occur. */
2509         ret = i915_gem_object_wait_rendering(obj);
2510         if (ret != 0)
2511                 return ret;
2512
2513         /* If we're writing through the GTT domain, then CPU and GPU caches
2514          * will need to be invalidated at next use.
2515          */
2516         if (write)
2517                 obj->read_domains &= I915_GEM_DOMAIN_GTT;
2518
2519         i915_gem_object_flush_cpu_write_domain(obj);
2520
2521         /* It should now be out of any other write domains, and we can update
2522          * the domain values for our changes.
2523          */
2524         BUG_ON((obj->write_domain & ~I915_GEM_DOMAIN_GTT) != 0);
2525         obj->read_domains |= I915_GEM_DOMAIN_GTT;
2526         if (write) {
2527                 obj->write_domain = I915_GEM_DOMAIN_GTT;
2528                 obj_priv->dirty = 1;
2529         }
2530
2531         return 0;
2532 }
2533
2534 /**
2535  * Moves a single object to the CPU read, and possibly write domain.
2536  *
2537  * This function returns when the move is complete, including waiting on
2538  * flushes to occur.
2539  */
2540 static int
2541 i915_gem_object_set_to_cpu_domain(struct drm_gem_object *obj, int write)
2542 {
2543         int ret;
2544
2545         i915_gem_object_flush_gpu_write_domain(obj);
2546         /* Wait on any GPU rendering and flushing to occur. */
2547         ret = i915_gem_object_wait_rendering(obj);
2548         if (ret != 0)
2549                 return ret;
2550
2551         i915_gem_object_flush_gtt_write_domain(obj);
2552
2553         /* If we have a partially-valid cache of the object in the CPU,
2554          * finish invalidating it and free the per-page flags.
2555          */
2556         i915_gem_object_set_to_full_cpu_read_domain(obj);
2557
2558         /* Flush the CPU cache if it's still invalid. */
2559         if ((obj->read_domains & I915_GEM_DOMAIN_CPU) == 0) {
2560                 i915_gem_clflush_object(obj);
2561
2562                 obj->read_domains |= I915_GEM_DOMAIN_CPU;
2563         }
2564
2565         /* It should now be out of any other write domains, and we can update
2566          * the domain values for our changes.
2567          */
2568         BUG_ON((obj->write_domain & ~I915_GEM_DOMAIN_CPU) != 0);
2569
2570         /* If we're writing through the CPU, then the GPU read domains will
2571          * need to be invalidated at next use.
2572          */
2573         if (write) {
2574                 obj->read_domains &= I915_GEM_DOMAIN_CPU;
2575                 obj->write_domain = I915_GEM_DOMAIN_CPU;
2576         }
2577
2578         return 0;
2579 }
2580
2581 /*
2582  * Set the next domain for the specified object. This
2583  * may not actually perform the necessary flushing/invaliding though,
2584  * as that may want to be batched with other set_domain operations
2585  *
2586  * This is (we hope) the only really tricky part of gem. The goal
2587  * is fairly simple -- track which caches hold bits of the object
2588  * and make sure they remain coherent. A few concrete examples may
2589  * help to explain how it works. For shorthand, we use the notation
2590  * (read_domains, write_domain), e.g. (CPU, CPU) to indicate the
2591  * a pair of read and write domain masks.
2592  *
2593  * Case 1: the batch buffer
2594  *
2595  *      1. Allocated
2596  *      2. Written by CPU
2597  *      3. Mapped to GTT
2598  *      4. Read by GPU
2599  *      5. Unmapped from GTT
2600  *      6. Freed
2601  *
2602  *      Let's take these a step at a time
2603  *
2604  *      1. Allocated
2605  *              Pages allocated from the kernel may still have
2606  *              cache contents, so we set them to (CPU, CPU) always.
2607  *      2. Written by CPU (using pwrite)
2608  *              The pwrite function calls set_domain (CPU, CPU) and
2609  *              this function does nothing (as nothing changes)
2610  *      3. Mapped by GTT
2611  *              This function asserts that the object is not
2612  *              currently in any GPU-based read or write domains
2613  *      4. Read by GPU
2614  *              i915_gem_execbuffer calls set_domain (COMMAND, 0).
2615  *              As write_domain is zero, this function adds in the
2616  *              current read domains (CPU+COMMAND, 0).
2617  *              flush_domains is set to CPU.
2618  *              invalidate_domains is set to COMMAND
2619  *              clflush is run to get data out of the CPU caches
2620  *              then i915_dev_set_domain calls i915_gem_flush to
2621  *              emit an MI_FLUSH and drm_agp_chipset_flush
2622  *      5. Unmapped from GTT
2623  *              i915_gem_object_unbind calls set_domain (CPU, CPU)
2624  *              flush_domains and invalidate_domains end up both zero
2625  *              so no flushing/invalidating happens
2626  *      6. Freed
2627  *              yay, done
2628  *
2629  * Case 2: The shared render buffer
2630  *
2631  *      1. Allocated
2632  *      2. Mapped to GTT
2633  *      3. Read/written by GPU
2634  *      4. set_domain to (CPU,CPU)
2635  *      5. Read/written by CPU
2636  *      6. Read/written by GPU
2637  *
2638  *      1. Allocated
2639  *              Same as last example, (CPU, CPU)
2640  *      2. Mapped to GTT
2641  *              Nothing changes (assertions find that it is not in the GPU)
2642  *      3. Read/written by GPU
2643  *              execbuffer calls set_domain (RENDER, RENDER)
2644  *              flush_domains gets CPU
2645  *              invalidate_domains gets GPU
2646  *              clflush (obj)
2647  *              MI_FLUSH and drm_agp_chipset_flush
2648  *      4. set_domain (CPU, CPU)
2649  *              flush_domains gets GPU
2650  *              invalidate_domains gets CPU
2651  *              wait_rendering (obj) to make sure all drawing is complete.
2652  *              This will include an MI_FLUSH to get the data from GPU
2653  *              to memory
2654  *              clflush (obj) to invalidate the CPU cache
2655  *              Another MI_FLUSH in i915_gem_flush (eliminate this somehow?)
2656  *      5. Read/written by CPU
2657  *              cache lines are loaded and dirtied
2658  *      6. Read written by GPU
2659  *              Same as last GPU access
2660  *
2661  * Case 3: The constant buffer
2662  *
2663  *      1. Allocated
2664  *      2. Written by CPU
2665  *      3. Read by GPU
2666  *      4. Updated (written) by CPU again
2667  *      5. Read by GPU
2668  *
2669  *      1. Allocated
2670  *              (CPU, CPU)
2671  *      2. Written by CPU
2672  *              (CPU, CPU)
2673  *      3. Read by GPU
2674  *              (CPU+RENDER, 0)
2675  *              flush_domains = CPU
2676  *              invalidate_domains = RENDER
2677  *              clflush (obj)
2678  *              MI_FLUSH
2679  *              drm_agp_chipset_flush
2680  *      4. Updated (written) by CPU again
2681  *              (CPU, CPU)
2682  *              flush_domains = 0 (no previous write domain)
2683  *              invalidate_domains = 0 (no new read domains)
2684  *      5. Read by GPU
2685  *              (CPU+RENDER, 0)
2686  *              flush_domains = CPU
2687  *              invalidate_domains = RENDER
2688  *              clflush (obj)
2689  *              MI_FLUSH
2690  *              drm_agp_chipset_flush
2691  */
2692 static void
2693 i915_gem_object_set_to_gpu_domain(struct drm_gem_object *obj)
2694 {
2695         struct drm_device               *dev = obj->dev;
2696         struct drm_i915_gem_object      *obj_priv = obj->driver_private;
2697         uint32_t                        invalidate_domains = 0;
2698         uint32_t                        flush_domains = 0;
2699
2700         BUG_ON(obj->pending_read_domains & I915_GEM_DOMAIN_CPU);
2701         BUG_ON(obj->pending_write_domain == I915_GEM_DOMAIN_CPU);
2702
2703 #if WATCH_BUF
2704         DRM_INFO("%s: object %p read %08x -> %08x write %08x -> %08x\n",
2705                  __func__, obj,
2706                  obj->read_domains, obj->pending_read_domains,
2707                  obj->write_domain, obj->pending_write_domain);
2708 #endif
2709         /*
2710          * If the object isn't moving to a new write domain,
2711          * let the object stay in multiple read domains
2712          */
2713         if (obj->pending_write_domain == 0)
2714                 obj->pending_read_domains |= obj->read_domains;
2715         else
2716                 obj_priv->dirty = 1;
2717
2718         /*
2719          * Flush the current write domain if
2720          * the new read domains don't match. Invalidate
2721          * any read domains which differ from the old
2722          * write domain
2723          */
2724         if (obj->write_domain &&
2725             obj->write_domain != obj->pending_read_domains) {
2726                 flush_domains |= obj->write_domain;
2727                 invalidate_domains |=
2728                         obj->pending_read_domains & ~obj->write_domain;
2729         }
2730         /*
2731          * Invalidate any read caches which may have
2732          * stale data. That is, any new read domains.
2733          */
2734         invalidate_domains |= obj->pending_read_domains & ~obj->read_domains;
2735         if ((flush_domains | invalidate_domains) & I915_GEM_DOMAIN_CPU) {
2736 #if WATCH_BUF
2737                 DRM_INFO("%s: CPU domain flush %08x invalidate %08x\n",
2738                          __func__, flush_domains, invalidate_domains);
2739 #endif
2740                 i915_gem_clflush_object(obj);
2741         }
2742
2743         /* The actual obj->write_domain will be updated with
2744          * pending_write_domain after we emit the accumulated flush for all
2745          * of our domain changes in execbuffers (which clears objects'
2746          * write_domains).  So if we have a current write domain that we
2747          * aren't changing, set pending_write_domain to that.
2748          */
2749         if (flush_domains == 0 && obj->pending_write_domain == 0)
2750                 obj->pending_write_domain = obj->write_domain;
2751         obj->read_domains = obj->pending_read_domains;
2752
2753         dev->invalidate_domains |= invalidate_domains;
2754         dev->flush_domains |= flush_domains;
2755 #if WATCH_BUF
2756         DRM_INFO("%s: read %08x write %08x invalidate %08x flush %08x\n",
2757                  __func__,
2758                  obj->read_domains, obj->write_domain,
2759                  dev->invalidate_domains, dev->flush_domains);
2760 #endif
2761 }
2762
2763 /**
2764  * Moves the object from a partially CPU read to a full one.
2765  *
2766  * Note that this only resolves i915_gem_object_set_cpu_read_domain_range(),
2767  * and doesn't handle transitioning from !(read_domains & I915_GEM_DOMAIN_CPU).
2768  */
2769 static void
2770 i915_gem_object_set_to_full_cpu_read_domain(struct drm_gem_object *obj)
2771 {
2772         struct drm_i915_gem_object *obj_priv = obj->driver_private;
2773
2774         if (!obj_priv->page_cpu_valid)
2775                 return;
2776
2777         /* If we're partially in the CPU read domain, finish moving it in.
2778          */
2779         if (obj->read_domains & I915_GEM_DOMAIN_CPU) {
2780                 int i;
2781
2782                 for (i = 0; i <= (obj->size - 1) / PAGE_SIZE; i++) {
2783                         if (obj_priv->page_cpu_valid[i])
2784                                 continue;
2785                         drm_clflush_pages(obj_priv->pages + i, 1);
2786                 }
2787         }
2788
2789         /* Free the page_cpu_valid mappings which are now stale, whether
2790          * or not we've got I915_GEM_DOMAIN_CPU.
2791          */
2792         drm_free(obj_priv->page_cpu_valid, obj->size / PAGE_SIZE,
2793                  DRM_MEM_DRIVER);
2794         obj_priv->page_cpu_valid = NULL;
2795 }
2796
2797 /**
2798  * Set the CPU read domain on a range of the object.
2799  *
2800  * The object ends up with I915_GEM_DOMAIN_CPU in its read flags although it's
2801  * not entirely valid.  The page_cpu_valid member of the object flags which
2802  * pages have been flushed, and will be respected by
2803  * i915_gem_object_set_to_cpu_domain() if it's called on to get a valid mapping
2804  * of the whole object.
2805  *
2806  * This function returns when the move is complete, including waiting on
2807  * flushes to occur.
2808  */
2809 static int
2810 i915_gem_object_set_cpu_read_domain_range(struct drm_gem_object *obj,
2811                                           uint64_t offset, uint64_t size)
2812 {
2813         struct drm_i915_gem_object *obj_priv = obj->driver_private;
2814         int i, ret;
2815
2816         if (offset == 0 && size == obj->size)
2817                 return i915_gem_object_set_to_cpu_domain(obj, 0);
2818
2819         i915_gem_object_flush_gpu_write_domain(obj);
2820         /* Wait on any GPU rendering and flushing to occur. */
2821         ret = i915_gem_object_wait_rendering(obj);
2822         if (ret != 0)
2823                 return ret;
2824         i915_gem_object_flush_gtt_write_domain(obj);
2825
2826         /* If we're already fully in the CPU read domain, we're done. */
2827         if (obj_priv->page_cpu_valid == NULL &&
2828             (obj->read_domains & I915_GEM_DOMAIN_CPU) != 0)
2829                 return 0;
2830
2831         /* Otherwise, create/clear the per-page CPU read domain flag if we're
2832          * newly adding I915_GEM_DOMAIN_CPU
2833          */
2834         if (obj_priv->page_cpu_valid == NULL) {
2835                 obj_priv->page_cpu_valid = drm_calloc(1, obj->size / PAGE_SIZE,
2836                                                       DRM_MEM_DRIVER);
2837                 if (obj_priv->page_cpu_valid == NULL)
2838                         return -ENOMEM;
2839         } else if ((obj->read_domains & I915_GEM_DOMAIN_CPU) == 0)
2840                 memset(obj_priv->page_cpu_valid, 0, obj->size / PAGE_SIZE);
2841
2842         /* Flush the cache on any pages that are still invalid from the CPU's
2843          * perspective.
2844          */
2845         for (i = offset / PAGE_SIZE; i <= (offset + size - 1) / PAGE_SIZE;
2846              i++) {
2847                 if (obj_priv->page_cpu_valid[i])
2848                         continue;
2849
2850                 drm_clflush_pages(obj_priv->pages + i, 1);
2851
2852                 obj_priv->page_cpu_valid[i] = 1;
2853         }
2854
2855         /* It should now be out of any other write domains, and we can update
2856          * the domain values for our changes.
2857          */
2858         BUG_ON((obj->write_domain & ~I915_GEM_DOMAIN_CPU) != 0);
2859
2860         obj->read_domains |= I915_GEM_DOMAIN_CPU;
2861
2862         return 0;
2863 }
2864
2865 /**
2866  * Pin an object to the GTT and evaluate the relocations landing in it.
2867  */
2868 static int
2869 i915_gem_object_pin_and_relocate(struct drm_gem_object *obj,
2870                                  struct drm_file *file_priv,
2871                                  struct drm_i915_gem_exec_object *entry,
2872                                  struct drm_i915_gem_relocation_entry *relocs)
2873 {
2874         struct drm_device *dev = obj->dev;
2875         drm_i915_private_t *dev_priv = dev->dev_private;
2876         struct drm_i915_gem_object *obj_priv = obj->driver_private;
2877         int i, ret;
2878         void __iomem *reloc_page;
2879
2880         /* Choose the GTT offset for our buffer and put it there. */
2881         ret = i915_gem_object_pin(obj, (uint32_t) entry->alignment);
2882         if (ret)
2883                 return ret;
2884
2885         entry->offset = obj_priv->gtt_offset;
2886
2887         /* Apply the relocations, using the GTT aperture to avoid cache
2888          * flushing requirements.
2889          */
2890         for (i = 0; i < entry->relocation_count; i++) {
2891                 struct drm_i915_gem_relocation_entry *reloc= &relocs[i];
2892                 struct drm_gem_object *target_obj;
2893                 struct drm_i915_gem_object *target_obj_priv;
2894                 uint32_t reloc_val, reloc_offset;
2895                 uint32_t __iomem *reloc_entry;
2896
2897                 target_obj = drm_gem_object_lookup(obj->dev, file_priv,
2898                                                    reloc->target_handle);
2899                 if (target_obj == NULL) {
2900                         i915_gem_object_unpin(obj);
2901                         return -EBADF;
2902                 }
2903                 target_obj_priv = target_obj->driver_private;
2904
2905                 /* The target buffer should have appeared before us in the
2906                  * exec_object list, so it should have a GTT space bound by now.
2907                  */
2908                 if (target_obj_priv->gtt_space == NULL) {
2909                         DRM_ERROR("No GTT space found for object %d\n",
2910                                   reloc->target_handle);
2911                         drm_gem_object_unreference(target_obj);
2912                         i915_gem_object_unpin(obj);
2913                         return -EINVAL;
2914                 }
2915
2916                 if (reloc->offset > obj->size - 4) {
2917                         DRM_ERROR("Relocation beyond object bounds: "
2918                                   "obj %p target %d offset %d size %d.\n",
2919                                   obj, reloc->target_handle,
2920                                   (int) reloc->offset, (int) obj->size);
2921                         drm_gem_object_unreference(target_obj);
2922                         i915_gem_object_unpin(obj);
2923                         return -EINVAL;
2924                 }
2925                 if (reloc->offset & 3) {
2926                         DRM_ERROR("Relocation not 4-byte aligned: "
2927                                   "obj %p target %d offset %d.\n",
2928                                   obj, reloc->target_handle,
2929                                   (int) reloc->offset);
2930                         drm_gem_object_unreference(target_obj);
2931                         i915_gem_object_unpin(obj);
2932                         return -EINVAL;
2933                 }
2934
2935                 if (reloc->write_domain & I915_GEM_DOMAIN_CPU ||
2936                     reloc->read_domains & I915_GEM_DOMAIN_CPU) {
2937                         DRM_ERROR("reloc with read/write CPU domains: "
2938                                   "obj %p target %d offset %d "
2939                                   "read %08x write %08x",
2940                                   obj, reloc->target_handle,
2941                                   (int) reloc->offset,
2942                                   reloc->read_domains,
2943                                   reloc->write_domain);
2944                         drm_gem_object_unreference(target_obj);
2945                         i915_gem_object_unpin(obj);
2946                         return -EINVAL;
2947                 }
2948
2949                 if (reloc->write_domain && target_obj->pending_write_domain &&
2950                     reloc->write_domain != target_obj->pending_write_domain) {
2951                         DRM_ERROR("Write domain conflict: "
2952                                   "obj %p target %d offset %d "
2953                                   "new %08x old %08x\n",
2954                                   obj, reloc->target_handle,
2955                                   (int) reloc->offset,
2956                                   reloc->write_domain,
2957                                   target_obj->pending_write_domain);
2958                         drm_gem_object_unreference(target_obj);
2959                         i915_gem_object_unpin(obj);
2960                         return -EINVAL;
2961                 }
2962
2963 #if WATCH_RELOC
2964                 DRM_INFO("%s: obj %p offset %08x target %d "
2965                          "read %08x write %08x gtt %08x "
2966                          "presumed %08x delta %08x\n",
2967                          __func__,
2968                          obj,
2969                          (int) reloc->offset,
2970                          (int) reloc->target_handle,
2971                          (int) reloc->read_domains,
2972                          (int) reloc->write_domain,
2973                          (int) target_obj_priv->gtt_offset,
2974                          (int) reloc->presumed_offset,
2975                          reloc->delta);
2976 #endif
2977
2978                 target_obj->pending_read_domains |= reloc->read_domains;
2979                 target_obj->pending_write_domain |= reloc->write_domain;
2980
2981                 /* If the relocation already has the right value in it, no
2982                  * more work needs to be done.
2983                  */
2984                 if (target_obj_priv->gtt_offset == reloc->presumed_offset) {
2985                         drm_gem_object_unreference(target_obj);
2986                         continue;
2987                 }
2988
2989                 ret = i915_gem_object_set_to_gtt_domain(obj, 1);
2990                 if (ret != 0) {
2991                         drm_gem_object_unreference(target_obj);
2992                         i915_gem_object_unpin(obj);
2993                         return -EINVAL;
2994                 }
2995
2996                 /* Map the page containing the relocation we're going to
2997                  * perform.
2998                  */
2999                 reloc_offset = obj_priv->gtt_offset + reloc->offset;
3000                 reloc_page = io_mapping_map_atomic_wc(dev_priv->mm.gtt_mapping,
3001                                                       (reloc_offset &
3002                                                        ~(PAGE_SIZE - 1)));
3003                 reloc_entry = (uint32_t __iomem *)(reloc_page +
3004                                                    (reloc_offset & (PAGE_SIZE - 1)));
3005                 reloc_val = target_obj_priv->gtt_offset + reloc->delta;
3006
3007 #if WATCH_BUF
3008                 DRM_INFO("Applied relocation: %p@0x%08x %08x -> %08x\n",
3009                           obj, (unsigned int) reloc->offset,
3010                           readl(reloc_entry), reloc_val);
3011 #endif
3012                 writel(reloc_val, reloc_entry);
3013                 io_mapping_unmap_atomic(reloc_page);
3014
3015                 /* The updated presumed offset for this entry will be
3016                  * copied back out to the user.
3017                  */
3018                 reloc->presumed_offset = target_obj_priv->gtt_offset;
3019
3020                 drm_gem_object_unreference(target_obj);
3021         }
3022
3023 #if WATCH_BUF
3024         if (0)
3025                 i915_gem_dump_object(obj, 128, __func__, ~0);
3026 #endif
3027         return 0;
3028 }
3029
3030 /** Dispatch a batchbuffer to the ring
3031  */
3032 static int
3033 i915_dispatch_gem_execbuffer(struct drm_device *dev,
3034                               struct drm_i915_gem_execbuffer *exec,
3035                               struct drm_clip_rect *cliprects,
3036                               uint64_t exec_offset)
3037 {
3038         drm_i915_private_t *dev_priv = dev->dev_private;
3039         int nbox = exec->num_cliprects;
3040         int i = 0, count;
3041         uint32_t        exec_start, exec_len;
3042         RING_LOCALS;
3043
3044         exec_start = (uint32_t) exec_offset + exec->batch_start_offset;
3045         exec_len = (uint32_t) exec->batch_len;
3046
3047         if ((exec_start | exec_len) & 0x7) {
3048                 DRM_ERROR("alignment\n");
3049                 return -EINVAL;
3050         }
3051
3052         if (!exec_start)
3053                 return -EINVAL;
3054
3055         count = nbox ? nbox : 1;
3056
3057         for (i = 0; i < count; i++) {
3058                 if (i < nbox) {
3059                         int ret = i915_emit_box(dev, cliprects, i,
3060                                                 exec->DR1, exec->DR4);
3061                         if (ret)
3062                                 return ret;
3063                 }
3064
3065                 if (IS_I830(dev) || IS_845G(dev)) {
3066                         BEGIN_LP_RING(4);
3067                         OUT_RING(MI_BATCH_BUFFER);
3068                         OUT_RING(exec_start | MI_BATCH_NON_SECURE);
3069                         OUT_RING(exec_start + exec_len - 4);
3070                         OUT_RING(0);
3071                         ADVANCE_LP_RING();
3072                 } else {
3073                         BEGIN_LP_RING(2);
3074                         if (IS_I965G(dev)) {
3075                                 OUT_RING(MI_BATCH_BUFFER_START |
3076                                          (2 << 6) |
3077                                          MI_BATCH_NON_SECURE_I965);
3078                                 OUT_RING(exec_start);
3079                         } else {
3080                                 OUT_RING(MI_BATCH_BUFFER_START |
3081                                          (2 << 6));
3082                                 OUT_RING(exec_start | MI_BATCH_NON_SECURE);
3083                         }
3084                         ADVANCE_LP_RING();
3085                 }
3086         }
3087
3088         /* XXX breadcrumb */
3089         return 0;
3090 }
3091
3092 /* Throttle our rendering by waiting until the ring has completed our requests
3093  * emitted over 20 msec ago.
3094  *
3095  * This should get us reasonable parallelism between CPU and GPU but also
3096  * relatively low latency when blocking on a particular request to finish.
3097  */
3098 static int
3099 i915_gem_ring_throttle(struct drm_device *dev, struct drm_file *file_priv)
3100 {
3101         struct drm_i915_file_private *i915_file_priv = file_priv->driver_priv;
3102         int ret = 0;
3103         uint32_t seqno;
3104
3105         mutex_lock(&dev->struct_mutex);
3106         seqno = i915_file_priv->mm.last_gem_throttle_seqno;
3107         i915_file_priv->mm.last_gem_throttle_seqno =
3108                 i915_file_priv->mm.last_gem_seqno;
3109         if (seqno)
3110                 ret = i915_wait_request(dev, seqno);
3111         mutex_unlock(&dev->struct_mutex);
3112         return ret;
3113 }
3114
3115 static int
3116 i915_gem_get_relocs_from_user(struct drm_i915_gem_exec_object *exec_list,
3117                               uint32_t buffer_count,
3118                               struct drm_i915_gem_relocation_entry **relocs)
3119 {
3120         uint32_t reloc_count = 0, reloc_index = 0, i;
3121         int ret;
3122
3123         *relocs = NULL;
3124         for (i = 0; i < buffer_count; i++) {
3125                 if (reloc_count + exec_list[i].relocation_count < reloc_count)
3126                         return -EINVAL;
3127                 reloc_count += exec_list[i].relocation_count;
3128         }
3129
3130         *relocs = drm_calloc_large(reloc_count, sizeof(**relocs));
3131         if (*relocs == NULL)
3132                 return -ENOMEM;
3133
3134         for (i = 0; i < buffer_count; i++) {
3135                 struct drm_i915_gem_relocation_entry __user *user_relocs;
3136
3137                 user_relocs = (void __user *)(uintptr_t)exec_list[i].relocs_ptr;
3138
3139                 ret = copy_from_user(&(*relocs)[reloc_index],
3140                                      user_relocs,
3141                                      exec_list[i].relocation_count *
3142                                      sizeof(**relocs));
3143                 if (ret != 0) {
3144                         drm_free_large(*relocs);
3145                         *relocs = NULL;
3146                         return -EFAULT;
3147                 }
3148
3149                 reloc_index += exec_list[i].relocation_count;
3150         }
3151
3152         return 0;
3153 }
3154
3155 static int
3156 i915_gem_put_relocs_to_user(struct drm_i915_gem_exec_object *exec_list,
3157                             uint32_t buffer_count,
3158                             struct drm_i915_gem_relocation_entry *relocs)
3159 {
3160         uint32_t reloc_count = 0, i;
3161         int ret = 0;
3162
3163         for (i = 0; i < buffer_count; i++) {
3164                 struct drm_i915_gem_relocation_entry __user *user_relocs;
3165                 int unwritten;
3166
3167                 user_relocs = (void __user *)(uintptr_t)exec_list[i].relocs_ptr;
3168
3169                 unwritten = copy_to_user(user_relocs,
3170                                          &relocs[reloc_count],
3171                                          exec_list[i].relocation_count *
3172                                          sizeof(*relocs));
3173
3174                 if (unwritten) {
3175                         ret = -EFAULT;
3176                         goto err;
3177                 }
3178
3179                 reloc_count += exec_list[i].relocation_count;
3180         }
3181
3182 err:
3183         drm_free_large(relocs);
3184
3185         return ret;
3186 }
3187
3188 int
3189 i915_gem_execbuffer(struct drm_device *dev, void *data,
3190                     struct drm_file *file_priv)
3191 {
3192         drm_i915_private_t *dev_priv = dev->dev_private;
3193         struct drm_i915_file_private *i915_file_priv = file_priv->driver_priv;
3194         struct drm_i915_gem_execbuffer *args = data;
3195         struct drm_i915_gem_exec_object *exec_list = NULL;
3196         struct drm_gem_object **object_list = NULL;
3197         struct drm_gem_object *batch_obj;
3198         struct drm_i915_gem_object *obj_priv;
3199         struct drm_clip_rect *cliprects = NULL;
3200         struct drm_i915_gem_relocation_entry *relocs;
3201         int ret, ret2, i, pinned = 0;
3202         uint64_t exec_offset;
3203         uint32_t seqno, flush_domains, reloc_index;
3204         int pin_tries;
3205
3206 #if WATCH_EXEC
3207         DRM_INFO("buffers_ptr %d buffer_count %d len %08x\n",
3208                   (int) args->buffers_ptr, args->buffer_count, args->batch_len);
3209 #endif
3210
3211         if (args->buffer_count < 1) {
3212                 DRM_ERROR("execbuf with %d buffers\n", args->buffer_count);
3213                 return -EINVAL;
3214         }
3215         /* Copy in the exec list from userland */
3216         exec_list = drm_calloc_large(sizeof(*exec_list), args->buffer_count);
3217         object_list = drm_calloc_large(sizeof(*object_list), args->buffer_count);
3218         if (exec_list == NULL || object_list == NULL) {
3219                 DRM_ERROR("Failed to allocate exec or object list "
3220                           "for %d buffers\n",
3221                           args->buffer_count);
3222                 ret = -ENOMEM;
3223                 goto pre_mutex_err;
3224         }
3225         ret = copy_from_user(exec_list,
3226                              (struct drm_i915_relocation_entry __user *)
3227                              (uintptr_t) args->buffers_ptr,
3228                              sizeof(*exec_list) * args->buffer_count);
3229         if (ret != 0) {
3230                 DRM_ERROR("copy %d exec entries failed %d\n",
3231                           args->buffer_count, ret);
3232                 goto pre_mutex_err;
3233         }
3234
3235         if (args->num_cliprects != 0) {
3236                 cliprects = drm_calloc(args->num_cliprects, sizeof(*cliprects),
3237                                        DRM_MEM_DRIVER);
3238                 if (cliprects == NULL)
3239                         goto pre_mutex_err;
3240
3241                 ret = copy_from_user(cliprects,
3242                                      (struct drm_clip_rect __user *)
3243                                      (uintptr_t) args->cliprects_ptr,
3244                                      sizeof(*cliprects) * args->num_cliprects);
3245                 if (ret != 0) {
3246                         DRM_ERROR("copy %d cliprects failed: %d\n",
3247                                   args->num_cliprects, ret);
3248                         goto pre_mutex_err;
3249                 }
3250         }
3251
3252         ret = i915_gem_get_relocs_from_user(exec_list, args->buffer_count,
3253                                             &relocs);
3254         if (ret != 0)
3255                 goto pre_mutex_err;
3256
3257         mutex_lock(&dev->struct_mutex);
3258
3259         i915_verify_inactive(dev, __FILE__, __LINE__);
3260
3261         if (dev_priv->mm.wedged) {
3262                 DRM_ERROR("Execbuf while wedged\n");
3263                 mutex_unlock(&dev->struct_mutex);
3264                 ret = -EIO;
3265                 goto pre_mutex_err;
3266         }
3267
3268         if (dev_priv->mm.suspended) {
3269                 DRM_ERROR("Execbuf while VT-switched.\n");
3270                 mutex_unlock(&dev->struct_mutex);
3271                 ret = -EBUSY;
3272                 goto pre_mutex_err;
3273         }
3274
3275         /* Look up object handles */
3276         for (i = 0; i < args->buffer_count; i++) {
3277                 object_list[i] = drm_gem_object_lookup(dev, file_priv,
3278                                                        exec_list[i].handle);
3279                 if (object_list[i] == NULL) {
3280                         DRM_ERROR("Invalid object handle %d at index %d\n",
3281                                    exec_list[i].handle, i);
3282                         ret = -EBADF;
3283                         goto err;
3284                 }
3285
3286                 obj_priv = object_list[i]->driver_private;
3287                 if (obj_priv->in_execbuffer) {
3288                         DRM_ERROR("Object %p appears more than once in object list\n",
3289                                    object_list[i]);
3290                         ret = -EBADF;
3291                         goto err;
3292                 }
3293                 obj_priv->in_execbuffer = true;
3294         }
3295
3296         /* Pin and relocate */
3297         for (pin_tries = 0; ; pin_tries++) {
3298                 ret = 0;
3299                 reloc_index = 0;
3300
3301                 for (i = 0; i < args->buffer_count; i++) {
3302                         object_list[i]->pending_read_domains = 0;
3303                         object_list[i]->pending_write_domain = 0;
3304                         ret = i915_gem_object_pin_and_relocate(object_list[i],
3305                                                                file_priv,
3306                                                                &exec_list[i],
3307                                                                &relocs[reloc_index]);
3308                         if (ret)
3309                                 break;
3310                         pinned = i + 1;
3311                         reloc_index += exec_list[i].relocation_count;
3312                 }
3313                 /* success */
3314                 if (ret == 0)
3315                         break;
3316
3317                 /* error other than GTT full, or we've already tried again */
3318                 if (ret != -ENOMEM || pin_tries >= 1) {
3319                         if (ret != -ERESTARTSYS)
3320                                 DRM_ERROR("Failed to pin buffers %d\n", ret);
3321                         goto err;
3322                 }
3323
3324                 /* unpin all of our buffers */
3325                 for (i = 0; i < pinned; i++)
3326                         i915_gem_object_unpin(object_list[i]);
3327                 pinned = 0;
3328
3329                 /* evict everyone we can from the aperture */
3330                 ret = i915_gem_evict_everything(dev);
3331                 if (ret)
3332                         goto err;
3333         }
3334
3335         /* Set the pending read domains for the batch buffer to COMMAND */
3336         batch_obj = object_list[args->buffer_count-1];
3337         batch_obj->pending_read_domains = I915_GEM_DOMAIN_COMMAND;
3338         batch_obj->pending_write_domain = 0;
3339
3340         i915_verify_inactive(dev, __FILE__, __LINE__);
3341
3342         /* Zero the global flush/invalidate flags. These
3343          * will be modified as new domains are computed
3344          * for each object
3345          */
3346         dev->invalidate_domains = 0;
3347         dev->flush_domains = 0;
3348
3349         for (i = 0; i < args->buffer_count; i++) {
3350                 struct drm_gem_object *obj = object_list[i];
3351
3352                 /* Compute new gpu domains and update invalidate/flush */
3353                 i915_gem_object_set_to_gpu_domain(obj);
3354         }
3355
3356         i915_verify_inactive(dev, __FILE__, __LINE__);
3357
3358         if (dev->invalidate_domains | dev->flush_domains) {
3359 #if WATCH_EXEC
3360                 DRM_INFO("%s: invalidate_domains %08x flush_domains %08x\n",
3361                           __func__,
3362                          dev->invalidate_domains,
3363                          dev->flush_domains);
3364 #endif
3365                 i915_gem_flush(dev,
3366                                dev->invalidate_domains,
3367                                dev->flush_domains);
3368                 if (dev->flush_domains)
3369                         (void)i915_add_request(dev, dev->flush_domains);
3370         }
3371
3372         for (i = 0; i < args->buffer_count; i++) {
3373                 struct drm_gem_object *obj = object_list[i];
3374
3375                 obj->write_domain = obj->pending_write_domain;
3376         }
3377
3378         i915_verify_inactive(dev, __FILE__, __LINE__);
3379
3380 #if WATCH_COHERENCY
3381         for (i = 0; i < args->buffer_count; i++) {
3382                 i915_gem_object_check_coherency(object_list[i],
3383                                                 exec_list[i].handle);
3384         }
3385 #endif
3386
3387         exec_offset = exec_list[args->buffer_count - 1].offset;
3388
3389 #if WATCH_EXEC
3390         i915_gem_dump_object(batch_obj,
3391                               args->batch_len,
3392                               __func__,
3393                               ~0);
3394 #endif
3395
3396         /* Exec the batchbuffer */
3397         ret = i915_dispatch_gem_execbuffer(dev, args, cliprects, exec_offset);
3398         if (ret) {
3399                 DRM_ERROR("dispatch failed %d\n", ret);
3400                 goto err;
3401         }
3402
3403         /*
3404          * Ensure that the commands in the batch buffer are
3405          * finished before the interrupt fires
3406          */
3407         flush_domains = i915_retire_commands(dev);
3408
3409         i915_verify_inactive(dev, __FILE__, __LINE__);
3410
3411         /*
3412          * Get a seqno representing the execution of the current buffer,
3413          * which we can wait on.  We would like to mitigate these interrupts,
3414          * likely by only creating seqnos occasionally (so that we have
3415          * *some* interrupts representing completion of buffers that we can
3416          * wait on when trying to clear up gtt space).
3417          */
3418         seqno = i915_add_request(dev, flush_domains);
3419         BUG_ON(seqno == 0);
3420         i915_file_priv->mm.last_gem_seqno = seqno;
3421         for (i = 0; i < args->buffer_count; i++) {
3422                 struct drm_gem_object *obj = object_list[i];
3423
3424                 i915_gem_object_move_to_active(obj, seqno);
3425 #if WATCH_LRU
3426                 DRM_INFO("%s: move to exec list %p\n", __func__, obj);
3427 #endif
3428         }
3429 #if WATCH_LRU
3430         i915_dump_lru(dev, __func__);
3431 #endif
3432
3433         i915_verify_inactive(dev, __FILE__, __LINE__);
3434
3435 err:
3436         for (i = 0; i < pinned; i++)
3437                 i915_gem_object_unpin(object_list[i]);
3438
3439         for (i = 0; i < args->buffer_count; i++) {
3440                 if (object_list[i]) {
3441                         obj_priv = object_list[i]->driver_private;
3442                         obj_priv->in_execbuffer = false;
3443                 }
3444                 drm_gem_object_unreference(object_list[i]);
3445         }
3446
3447         mutex_unlock(&dev->struct_mutex);
3448
3449         if (!ret) {
3450                 /* Copy the new buffer offsets back to the user's exec list. */
3451                 ret = copy_to_user((struct drm_i915_relocation_entry __user *)
3452                                    (uintptr_t) args->buffers_ptr,
3453                                    exec_list,
3454                                    sizeof(*exec_list) * args->buffer_count);
3455                 if (ret) {
3456                         ret = -EFAULT;
3457                         DRM_ERROR("failed to copy %d exec entries "
3458                                   "back to user (%d)\n",
3459                                   args->buffer_count, ret);
3460                 }
3461         }
3462
3463         /* Copy the updated relocations out regardless of current error
3464          * state.  Failure to update the relocs would mean that the next
3465          * time userland calls execbuf, it would do so with presumed offset
3466          * state that didn't match the actual object state.
3467          */
3468         ret2 = i915_gem_put_relocs_to_user(exec_list, args->buffer_count,
3469                                            relocs);
3470         if (ret2 != 0) {
3471                 DRM_ERROR("Failed to copy relocations back out: %d\n", ret2);
3472
3473                 if (ret == 0)
3474                         ret = ret2;
3475         }
3476
3477 pre_mutex_err:
3478         drm_free_large(object_list);
3479         drm_free_large(exec_list);
3480         drm_free(cliprects, sizeof(*cliprects) * args->num_cliprects,
3481                  DRM_MEM_DRIVER);
3482
3483         return ret;
3484 }
3485
3486 int
3487 i915_gem_object_pin(struct drm_gem_object *obj, uint32_t alignment)
3488 {
3489         struct drm_device *dev = obj->dev;
3490         struct drm_i915_gem_object *obj_priv = obj->driver_private;
3491         int ret;
3492
3493         i915_verify_inactive(dev, __FILE__, __LINE__);
3494         if (obj_priv->gtt_space == NULL) {
3495                 ret = i915_gem_object_bind_to_gtt(obj, alignment);
3496                 if (ret != 0) {
3497                         if (ret != -EBUSY && ret != -ERESTARTSYS)
3498                                 DRM_ERROR("Failure to bind: %d\n", ret);
3499                         return ret;
3500                 }
3501         }
3502         /*
3503          * Pre-965 chips need a fence register set up in order to
3504          * properly handle tiled surfaces.
3505          */
3506         if (!IS_I965G(dev) &&
3507             obj_priv->fence_reg == I915_FENCE_REG_NONE &&
3508             obj_priv->tiling_mode != I915_TILING_NONE) {
3509                 ret = i915_gem_object_get_fence_reg(obj, true);
3510                 if (ret != 0) {
3511                         if (ret != -EBUSY && ret != -ERESTARTSYS)
3512                                 DRM_ERROR("Failure to install fence: %d\n",
3513                                           ret);
3514                         return ret;
3515                 }
3516         }
3517         obj_priv->pin_count++;
3518
3519         /* If the object is not active and not pending a flush,
3520          * remove it from the inactive list
3521          */
3522         if (obj_priv->pin_count == 1) {
3523                 atomic_inc(&dev->pin_count);
3524                 atomic_add(obj->size, &dev->pin_memory);
3525                 if (!obj_priv->active &&
3526                     (obj->write_domain & ~(I915_GEM_DOMAIN_CPU |
3527                                            I915_GEM_DOMAIN_GTT)) == 0 &&
3528                     !list_empty(&obj_priv->list))
3529                         list_del_init(&obj_priv->list);
3530         }
3531         i915_verify_inactive(dev, __FILE__, __LINE__);
3532
3533         return 0;
3534 }
3535
3536 void
3537 i915_gem_object_unpin(struct drm_gem_object *obj)
3538 {
3539         struct drm_device *dev = obj->dev;
3540         drm_i915_private_t *dev_priv = dev->dev_private;
3541         struct drm_i915_gem_object *obj_priv = obj->driver_private;
3542
3543         i915_verify_inactive(dev, __FILE__, __LINE__);
3544         obj_priv->pin_count--;
3545         BUG_ON(obj_priv->pin_count < 0);
3546         BUG_ON(obj_priv->gtt_space == NULL);
3547
3548         /* If the object is no longer pinned, and is
3549          * neither active nor being flushed, then stick it on
3550          * the inactive list
3551          */
3552         if (obj_priv->pin_count == 0) {
3553                 if (!obj_priv->active &&
3554                     (obj->write_domain & ~(I915_GEM_DOMAIN_CPU |
3555                                            I915_GEM_DOMAIN_GTT)) == 0)
3556                         list_move_tail(&obj_priv->list,
3557                                        &dev_priv->mm.inactive_list);
3558                 atomic_dec(&dev->pin_count);
3559                 atomic_sub(obj->size, &dev->pin_memory);
3560         }
3561         i915_verify_inactive(dev, __FILE__, __LINE__);
3562 }
3563
3564 int
3565 i915_gem_pin_ioctl(struct drm_device *dev, void *data,
3566                    struct drm_file *file_priv)
3567 {
3568         struct drm_i915_gem_pin *args = data;
3569         struct drm_gem_object *obj;
3570         struct drm_i915_gem_object *obj_priv;
3571         int ret;
3572
3573         mutex_lock(&dev->struct_mutex);
3574
3575         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
3576         if (obj == NULL) {
3577                 DRM_ERROR("Bad handle in i915_gem_pin_ioctl(): %d\n",
3578                           args->handle);
3579                 mutex_unlock(&dev->struct_mutex);
3580                 return -EBADF;
3581         }
3582         obj_priv = obj->driver_private;
3583
3584         if (obj_priv->pin_filp != NULL && obj_priv->pin_filp != file_priv) {
3585                 DRM_ERROR("Already pinned in i915_gem_pin_ioctl(): %d\n",
3586                           args->handle);
3587                 drm_gem_object_unreference(obj);
3588                 mutex_unlock(&dev->struct_mutex);
3589                 return -EINVAL;
3590         }
3591
3592         obj_priv->user_pin_count++;
3593         obj_priv->pin_filp = file_priv;
3594         if (obj_priv->user_pin_count == 1) {
3595                 ret = i915_gem_object_pin(obj, args->alignment);
3596                 if (ret != 0) {
3597                         drm_gem_object_unreference(obj);
3598                         mutex_unlock(&dev->struct_mutex);
3599                         return ret;
3600                 }
3601         }
3602
3603         /* XXX - flush the CPU caches for pinned objects
3604          * as the X server doesn't manage domains yet
3605          */
3606         i915_gem_object_flush_cpu_write_domain(obj);
3607         args->offset = obj_priv->gtt_offset;
3608         drm_gem_object_unreference(obj);
3609         mutex_unlock(&dev->struct_mutex);
3610
3611         return 0;
3612 }
3613
3614 int
3615 i915_gem_unpin_ioctl(struct drm_device *dev, void *data,
3616                      struct drm_file *file_priv)
3617 {
3618         struct drm_i915_gem_pin *args = data;
3619         struct drm_gem_object *obj;
3620         struct drm_i915_gem_object *obj_priv;
3621
3622         mutex_lock(&dev->struct_mutex);
3623
3624         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
3625         if (obj == NULL) {
3626                 DRM_ERROR("Bad handle in i915_gem_unpin_ioctl(): %d\n",
3627                           args->handle);
3628                 mutex_unlock(&dev->struct_mutex);
3629                 return -EBADF;
3630         }
3631
3632         obj_priv = obj->driver_private;
3633         if (obj_priv->pin_filp != file_priv) {
3634                 DRM_ERROR("Not pinned by caller in i915_gem_pin_ioctl(): %d\n",
3635                           args->handle);
3636                 drm_gem_object_unreference(obj);
3637                 mutex_unlock(&dev->struct_mutex);
3638                 return -EINVAL;
3639         }
3640         obj_priv->user_pin_count--;
3641         if (obj_priv->user_pin_count == 0) {
3642                 obj_priv->pin_filp = NULL;
3643                 i915_gem_object_unpin(obj);
3644         }
3645
3646         drm_gem_object_unreference(obj);
3647         mutex_unlock(&dev->struct_mutex);
3648         return 0;
3649 }
3650
3651 int
3652 i915_gem_busy_ioctl(struct drm_device *dev, void *data,
3653                     struct drm_file *file_priv)
3654 {
3655         struct drm_i915_gem_busy *args = data;
3656         struct drm_gem_object *obj;
3657         struct drm_i915_gem_object *obj_priv;
3658
3659         mutex_lock(&dev->struct_mutex);
3660         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
3661         if (obj == NULL) {
3662                 DRM_ERROR("Bad handle in i915_gem_busy_ioctl(): %d\n",
3663                           args->handle);
3664                 mutex_unlock(&dev->struct_mutex);
3665                 return -EBADF;
3666         }
3667
3668         /* Update the active list for the hardware's current position.
3669          * Otherwise this only updates on a delayed timer or when irqs are
3670          * actually unmasked, and our working set ends up being larger than
3671          * required.
3672          */
3673         i915_gem_retire_requests(dev);
3674
3675         obj_priv = obj->driver_private;
3676         /* Don't count being on the flushing list against the object being
3677          * done.  Otherwise, a buffer left on the flushing list but not getting
3678          * flushed (because nobody's flushing that domain) won't ever return
3679          * unbusy and get reused by libdrm's bo cache.  The other expected
3680          * consumer of this interface, OpenGL's occlusion queries, also specs
3681          * that the objects get unbusy "eventually" without any interference.
3682          */
3683         args->busy = obj_priv->active && obj_priv->last_rendering_seqno != 0;
3684
3685         drm_gem_object_unreference(obj);
3686         mutex_unlock(&dev->struct_mutex);
3687         return 0;
3688 }
3689
3690 int
3691 i915_gem_throttle_ioctl(struct drm_device *dev, void *data,
3692                         struct drm_file *file_priv)
3693 {
3694     return i915_gem_ring_throttle(dev, file_priv);
3695 }
3696
3697 int i915_gem_init_object(struct drm_gem_object *obj)
3698 {
3699         struct drm_i915_gem_object *obj_priv;
3700
3701         obj_priv = drm_calloc(1, sizeof(*obj_priv), DRM_MEM_DRIVER);
3702         if (obj_priv == NULL)
3703                 return -ENOMEM;
3704
3705         /*
3706          * We've just allocated pages from the kernel,
3707          * so they've just been written by the CPU with
3708          * zeros. They'll need to be clflushed before we
3709          * use them with the GPU.
3710          */
3711         obj->write_domain = I915_GEM_DOMAIN_CPU;
3712         obj->read_domains = I915_GEM_DOMAIN_CPU;
3713
3714         obj_priv->agp_type = AGP_USER_MEMORY;
3715
3716         obj->driver_private = obj_priv;
3717         obj_priv->obj = obj;
3718         obj_priv->fence_reg = I915_FENCE_REG_NONE;
3719         INIT_LIST_HEAD(&obj_priv->list);
3720
3721         return 0;
3722 }
3723
3724 void i915_gem_free_object(struct drm_gem_object *obj)
3725 {
3726         struct drm_device *dev = obj->dev;
3727         struct drm_i915_gem_object *obj_priv = obj->driver_private;
3728
3729         while (obj_priv->pin_count > 0)
3730                 i915_gem_object_unpin(obj);
3731
3732         if (obj_priv->phys_obj)
3733                 i915_gem_detach_phys_object(dev, obj);
3734
3735         i915_gem_object_unbind(obj);
3736
3737         i915_gem_free_mmap_offset(obj);
3738
3739         drm_free(obj_priv->page_cpu_valid, 1, DRM_MEM_DRIVER);
3740         kfree(obj_priv->bit_17);
3741         drm_free(obj->driver_private, 1, DRM_MEM_DRIVER);
3742 }
3743
3744 /** Unbinds all objects that are on the given buffer list. */
3745 static int
3746 i915_gem_evict_from_list(struct drm_device *dev, struct list_head *head)
3747 {
3748         struct drm_gem_object *obj;
3749         struct drm_i915_gem_object *obj_priv;
3750         int ret;
3751
3752         while (!list_empty(head)) {
3753                 obj_priv = list_first_entry(head,
3754                                             struct drm_i915_gem_object,
3755                                             list);
3756                 obj = obj_priv->obj;
3757
3758                 if (obj_priv->pin_count != 0) {
3759                         DRM_ERROR("Pinned object in unbind list\n");
3760                         mutex_unlock(&dev->struct_mutex);
3761                         return -EINVAL;
3762                 }
3763
3764                 ret = i915_gem_object_unbind(obj);
3765                 if (ret != 0) {
3766                         DRM_ERROR("Error unbinding object in LeaveVT: %d\n",
3767                                   ret);
3768                         mutex_unlock(&dev->struct_mutex);
3769                         return ret;
3770                 }
3771         }
3772
3773
3774         return 0;
3775 }
3776
3777 int
3778 i915_gem_idle(struct drm_device *dev)
3779 {
3780         drm_i915_private_t *dev_priv = dev->dev_private;
3781         uint32_t seqno, cur_seqno, last_seqno;
3782         int stuck, ret;
3783
3784         mutex_lock(&dev->struct_mutex);
3785
3786         if (dev_priv->mm.suspended || dev_priv->ring.ring_obj == NULL) {
3787                 mutex_unlock(&dev->struct_mutex);
3788                 return 0;
3789         }
3790
3791         /* Hack!  Don't let anybody do execbuf while we don't control the chip.
3792          * We need to replace this with a semaphore, or something.
3793          */
3794         dev_priv->mm.suspended = 1;
3795
3796         /* Cancel the retire work handler, wait for it to finish if running
3797          */
3798         mutex_unlock(&dev->struct_mutex);
3799         cancel_delayed_work_sync(&dev_priv->mm.retire_work);
3800         mutex_lock(&dev->struct_mutex);
3801
3802         i915_kernel_lost_context(dev);
3803
3804         /* Flush the GPU along with all non-CPU write domains
3805          */
3806         i915_gem_flush(dev, ~(I915_GEM_DOMAIN_CPU|I915_GEM_DOMAIN_GTT),
3807                        ~(I915_GEM_DOMAIN_CPU|I915_GEM_DOMAIN_GTT));
3808         seqno = i915_add_request(dev, ~I915_GEM_DOMAIN_CPU);
3809
3810         if (seqno == 0) {
3811                 mutex_unlock(&dev->struct_mutex);
3812                 return -ENOMEM;
3813         }
3814
3815         dev_priv->mm.waiting_gem_seqno = seqno;
3816         last_seqno = 0;
3817         stuck = 0;
3818         for (;;) {
3819                 cur_seqno = i915_get_gem_seqno(dev);
3820                 if (i915_seqno_passed(cur_seqno, seqno))
3821                         break;
3822                 if (last_seqno == cur_seqno) {
3823                         if (stuck++ > 100) {
3824                                 DRM_ERROR("hardware wedged\n");
3825                                 dev_priv->mm.wedged = 1;
3826                                 DRM_WAKEUP(&dev_priv->irq_queue);
3827                                 break;
3828                         }
3829                 }
3830                 msleep(10);
3831                 last_seqno = cur_seqno;
3832         }
3833         dev_priv->mm.waiting_gem_seqno = 0;
3834
3835         i915_gem_retire_requests(dev);
3836
3837         spin_lock(&dev_priv->mm.active_list_lock);
3838         if (!dev_priv->mm.wedged) {
3839                 /* Active and flushing should now be empty as we've
3840                  * waited for a sequence higher than any pending execbuffer
3841                  */
3842                 WARN_ON(!list_empty(&dev_priv->mm.active_list));
3843                 WARN_ON(!list_empty(&dev_priv->mm.flushing_list));
3844                 /* Request should now be empty as we've also waited
3845                  * for the last request in the list
3846                  */
3847                 WARN_ON(!list_empty(&dev_priv->mm.request_list));
3848         }
3849
3850         /* Empty the active and flushing lists to inactive.  If there's
3851          * anything left at this point, it means that we're wedged and
3852          * nothing good's going to happen by leaving them there.  So strip
3853          * the GPU domains and just stuff them onto inactive.
3854          */
3855         while (!list_empty(&dev_priv->mm.active_list)) {
3856                 struct drm_i915_gem_object *obj_priv;
3857
3858                 obj_priv = list_first_entry(&dev_priv->mm.active_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         spin_unlock(&dev_priv->mm.active_list_lock);
3865
3866         while (!list_empty(&dev_priv->mm.flushing_list)) {
3867                 struct drm_i915_gem_object *obj_priv;
3868
3869                 obj_priv = list_first_entry(&dev_priv->mm.flushing_list,
3870                                             struct drm_i915_gem_object,
3871                                             list);
3872                 obj_priv->obj->write_domain &= ~I915_GEM_GPU_DOMAINS;
3873                 i915_gem_object_move_to_inactive(obj_priv->obj);
3874         }
3875
3876
3877         /* Move all inactive buffers out of the GTT. */
3878         ret = i915_gem_evict_from_list(dev, &dev_priv->mm.inactive_list);
3879         WARN_ON(!list_empty(&dev_priv->mm.inactive_list));
3880         if (ret) {
3881                 mutex_unlock(&dev->struct_mutex);
3882                 return ret;
3883         }
3884
3885         i915_gem_cleanup_ringbuffer(dev);
3886         mutex_unlock(&dev->struct_mutex);
3887
3888         return 0;
3889 }
3890
3891 static int
3892 i915_gem_init_hws(struct drm_device *dev)
3893 {
3894         drm_i915_private_t *dev_priv = dev->dev_private;
3895         struct drm_gem_object *obj;
3896         struct drm_i915_gem_object *obj_priv;
3897         int ret;
3898
3899         /* If we need a physical address for the status page, it's already
3900          * initialized at driver load time.
3901          */
3902         if (!I915_NEED_GFX_HWS(dev))
3903                 return 0;
3904
3905         obj = drm_gem_object_alloc(dev, 4096);
3906         if (obj == NULL) {
3907                 DRM_ERROR("Failed to allocate status page\n");
3908                 return -ENOMEM;
3909         }
3910         obj_priv = obj->driver_private;
3911         obj_priv->agp_type = AGP_USER_CACHED_MEMORY;
3912
3913         ret = i915_gem_object_pin(obj, 4096);
3914         if (ret != 0) {
3915                 drm_gem_object_unreference(obj);
3916                 return ret;
3917         }
3918
3919         dev_priv->status_gfx_addr = obj_priv->gtt_offset;
3920
3921         dev_priv->hw_status_page = kmap(obj_priv->pages[0]);
3922         if (dev_priv->hw_status_page == NULL) {
3923                 DRM_ERROR("Failed to map status page.\n");
3924                 memset(&dev_priv->hws_map, 0, sizeof(dev_priv->hws_map));
3925                 i915_gem_object_unpin(obj);
3926                 drm_gem_object_unreference(obj);
3927                 return -EINVAL;
3928         }
3929         dev_priv->hws_obj = obj;
3930         memset(dev_priv->hw_status_page, 0, PAGE_SIZE);
3931         I915_WRITE(HWS_PGA, dev_priv->status_gfx_addr);
3932         I915_READ(HWS_PGA); /* posting read */
3933         DRM_DEBUG("hws offset: 0x%08x\n", dev_priv->status_gfx_addr);
3934
3935         return 0;
3936 }
3937
3938 static void
3939 i915_gem_cleanup_hws(struct drm_device *dev)
3940 {
3941         drm_i915_private_t *dev_priv = dev->dev_private;
3942         struct drm_gem_object *obj;
3943         struct drm_i915_gem_object *obj_priv;
3944
3945         if (dev_priv->hws_obj == NULL)
3946                 return;
3947
3948         obj = dev_priv->hws_obj;
3949         obj_priv = obj->driver_private;
3950
3951         kunmap(obj_priv->pages[0]);
3952         i915_gem_object_unpin(obj);
3953         drm_gem_object_unreference(obj);
3954         dev_priv->hws_obj = NULL;
3955
3956         memset(&dev_priv->hws_map, 0, sizeof(dev_priv->hws_map));
3957         dev_priv->hw_status_page = NULL;
3958
3959         /* Write high address into HWS_PGA when disabling. */
3960         I915_WRITE(HWS_PGA, 0x1ffff000);
3961 }
3962
3963 int
3964 i915_gem_init_ringbuffer(struct drm_device *dev)
3965 {
3966         drm_i915_private_t *dev_priv = dev->dev_private;
3967         struct drm_gem_object *obj;
3968         struct drm_i915_gem_object *obj_priv;
3969         drm_i915_ring_buffer_t *ring = &dev_priv->ring;
3970         int ret;
3971         u32 head;
3972
3973         ret = i915_gem_init_hws(dev);
3974         if (ret != 0)
3975                 return ret;
3976
3977         obj = drm_gem_object_alloc(dev, 128 * 1024);
3978         if (obj == NULL) {
3979                 DRM_ERROR("Failed to allocate ringbuffer\n");
3980                 i915_gem_cleanup_hws(dev);
3981                 return -ENOMEM;
3982         }
3983         obj_priv = obj->driver_private;
3984
3985         ret = i915_gem_object_pin(obj, 4096);
3986         if (ret != 0) {
3987                 drm_gem_object_unreference(obj);
3988                 i915_gem_cleanup_hws(dev);
3989                 return ret;
3990         }
3991
3992         /* Set up the kernel mapping for the ring. */
3993         ring->Size = obj->size;
3994         ring->tail_mask = obj->size - 1;
3995
3996         ring->map.offset = dev->agp->base + obj_priv->gtt_offset;
3997         ring->map.size = obj->size;
3998         ring->map.type = 0;
3999         ring->map.flags = 0;
4000         ring->map.mtrr = 0;
4001
4002         drm_core_ioremap_wc(&ring->map, dev);
4003         if (ring->map.handle == NULL) {
4004                 DRM_ERROR("Failed to map ringbuffer.\n");
4005                 memset(&dev_priv->ring, 0, sizeof(dev_priv->ring));
4006                 i915_gem_object_unpin(obj);
4007                 drm_gem_object_unreference(obj);
4008                 i915_gem_cleanup_hws(dev);
4009                 return -EINVAL;
4010         }
4011         ring->ring_obj = obj;
4012         ring->virtual_start = ring->map.handle;
4013
4014         /* Stop the ring if it's running. */
4015         I915_WRITE(PRB0_CTL, 0);
4016         I915_WRITE(PRB0_TAIL, 0);
4017         I915_WRITE(PRB0_HEAD, 0);
4018
4019         /* Initialize the ring. */
4020         I915_WRITE(PRB0_START, obj_priv->gtt_offset);
4021         head = I915_READ(PRB0_HEAD) & HEAD_ADDR;
4022
4023         /* G45 ring initialization fails to reset head to zero */
4024         if (head != 0) {
4025                 DRM_ERROR("Ring head not reset to zero "
4026                           "ctl %08x head %08x tail %08x start %08x\n",
4027                           I915_READ(PRB0_CTL),
4028                           I915_READ(PRB0_HEAD),
4029                           I915_READ(PRB0_TAIL),
4030                           I915_READ(PRB0_START));
4031                 I915_WRITE(PRB0_HEAD, 0);
4032
4033                 DRM_ERROR("Ring head forced to zero "
4034                           "ctl %08x head %08x tail %08x start %08x\n",
4035                           I915_READ(PRB0_CTL),
4036                           I915_READ(PRB0_HEAD),
4037                           I915_READ(PRB0_TAIL),
4038                           I915_READ(PRB0_START));
4039         }
4040
4041         I915_WRITE(PRB0_CTL,
4042                    ((obj->size - 4096) & RING_NR_PAGES) |
4043                    RING_NO_REPORT |
4044                    RING_VALID);
4045
4046         head = I915_READ(PRB0_HEAD) & HEAD_ADDR;
4047
4048         /* If the head is still not zero, the ring is dead */
4049         if (head != 0) {
4050                 DRM_ERROR("Ring initialization failed "
4051                           "ctl %08x head %08x tail %08x start %08x\n",
4052                           I915_READ(PRB0_CTL),
4053                           I915_READ(PRB0_HEAD),
4054                           I915_READ(PRB0_TAIL),
4055                           I915_READ(PRB0_START));
4056                 return -EIO;
4057         }
4058
4059         /* Update our cache of the ring state */
4060         if (!drm_core_check_feature(dev, DRIVER_MODESET))
4061                 i915_kernel_lost_context(dev);
4062         else {
4063                 ring->head = I915_READ(PRB0_HEAD) & HEAD_ADDR;
4064                 ring->tail = I915_READ(PRB0_TAIL) & TAIL_ADDR;
4065                 ring->space = ring->head - (ring->tail + 8);
4066                 if (ring->space < 0)
4067                         ring->space += ring->Size;
4068         }
4069
4070         return 0;
4071 }
4072
4073 void
4074 i915_gem_cleanup_ringbuffer(struct drm_device *dev)
4075 {
4076         drm_i915_private_t *dev_priv = dev->dev_private;
4077
4078         if (dev_priv->ring.ring_obj == NULL)
4079                 return;
4080
4081         drm_core_ioremapfree(&dev_priv->ring.map, dev);
4082
4083         i915_gem_object_unpin(dev_priv->ring.ring_obj);
4084         drm_gem_object_unreference(dev_priv->ring.ring_obj);
4085         dev_priv->ring.ring_obj = NULL;
4086         memset(&dev_priv->ring, 0, sizeof(dev_priv->ring));
4087
4088         i915_gem_cleanup_hws(dev);
4089 }
4090
4091 int
4092 i915_gem_entervt_ioctl(struct drm_device *dev, void *data,
4093                        struct drm_file *file_priv)
4094 {
4095         drm_i915_private_t *dev_priv = dev->dev_private;
4096         int ret;
4097
4098         if (drm_core_check_feature(dev, DRIVER_MODESET))
4099                 return 0;
4100
4101         if (dev_priv->mm.wedged) {
4102                 DRM_ERROR("Reenabling wedged hardware, good luck\n");
4103                 dev_priv->mm.wedged = 0;
4104         }
4105
4106         mutex_lock(&dev->struct_mutex);
4107         dev_priv->mm.suspended = 0;
4108
4109         ret = i915_gem_init_ringbuffer(dev);
4110         if (ret != 0) {
4111                 mutex_unlock(&dev->struct_mutex);
4112                 return ret;
4113         }
4114
4115         spin_lock(&dev_priv->mm.active_list_lock);
4116         BUG_ON(!list_empty(&dev_priv->mm.active_list));
4117         spin_unlock(&dev_priv->mm.active_list_lock);
4118
4119         BUG_ON(!list_empty(&dev_priv->mm.flushing_list));
4120         BUG_ON(!list_empty(&dev_priv->mm.inactive_list));
4121         BUG_ON(!list_empty(&dev_priv->mm.request_list));
4122         mutex_unlock(&dev->struct_mutex);
4123
4124         drm_irq_install(dev);
4125
4126         return 0;
4127 }
4128
4129 int
4130 i915_gem_leavevt_ioctl(struct drm_device *dev, void *data,
4131                        struct drm_file *file_priv)
4132 {
4133         int ret;
4134
4135         if (drm_core_check_feature(dev, DRIVER_MODESET))
4136                 return 0;
4137
4138         ret = i915_gem_idle(dev);
4139         drm_irq_uninstall(dev);
4140
4141         return ret;
4142 }
4143
4144 void
4145 i915_gem_lastclose(struct drm_device *dev)
4146 {
4147         int ret;
4148
4149         if (drm_core_check_feature(dev, DRIVER_MODESET))
4150                 return;
4151
4152         ret = i915_gem_idle(dev);
4153         if (ret)
4154                 DRM_ERROR("failed to idle hardware: %d\n", ret);
4155 }
4156
4157 void
4158 i915_gem_load(struct drm_device *dev)
4159 {
4160         drm_i915_private_t *dev_priv = dev->dev_private;
4161
4162         spin_lock_init(&dev_priv->mm.active_list_lock);
4163         INIT_LIST_HEAD(&dev_priv->mm.active_list);
4164         INIT_LIST_HEAD(&dev_priv->mm.flushing_list);
4165         INIT_LIST_HEAD(&dev_priv->mm.inactive_list);
4166         INIT_LIST_HEAD(&dev_priv->mm.request_list);
4167         INIT_DELAYED_WORK(&dev_priv->mm.retire_work,
4168                           i915_gem_retire_work_handler);
4169         dev_priv->mm.next_gem_seqno = 1;
4170
4171         /* Old X drivers will take 0-2 for front, back, depth buffers */
4172         dev_priv->fence_reg_start = 3;
4173
4174         if (IS_I965G(dev) || IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev))
4175                 dev_priv->num_fence_regs = 16;
4176         else
4177                 dev_priv->num_fence_regs = 8;
4178
4179         i915_gem_detect_bit_6_swizzle(dev);
4180 }
4181
4182 /*
4183  * Create a physically contiguous memory object for this object
4184  * e.g. for cursor + overlay regs
4185  */
4186 int i915_gem_init_phys_object(struct drm_device *dev,
4187                               int id, int size)
4188 {
4189         drm_i915_private_t *dev_priv = dev->dev_private;
4190         struct drm_i915_gem_phys_object *phys_obj;
4191         int ret;
4192
4193         if (dev_priv->mm.phys_objs[id - 1] || !size)
4194                 return 0;
4195
4196         phys_obj = drm_calloc(1, sizeof(struct drm_i915_gem_phys_object), DRM_MEM_DRIVER);
4197         if (!phys_obj)
4198                 return -ENOMEM;
4199
4200         phys_obj->id = id;
4201
4202         phys_obj->handle = drm_pci_alloc(dev, size, 0, 0xffffffff);
4203         if (!phys_obj->handle) {
4204                 ret = -ENOMEM;
4205                 goto kfree_obj;
4206         }
4207 #ifdef CONFIG_X86
4208         set_memory_wc((unsigned long)phys_obj->handle->vaddr, phys_obj->handle->size / PAGE_SIZE);
4209 #endif
4210
4211         dev_priv->mm.phys_objs[id - 1] = phys_obj;
4212
4213         return 0;
4214 kfree_obj:
4215         drm_free(phys_obj, sizeof(struct drm_i915_gem_phys_object), DRM_MEM_DRIVER);
4216         return ret;
4217 }
4218
4219 void i915_gem_free_phys_object(struct drm_device *dev, int id)
4220 {
4221         drm_i915_private_t *dev_priv = dev->dev_private;
4222         struct drm_i915_gem_phys_object *phys_obj;
4223
4224         if (!dev_priv->mm.phys_objs[id - 1])
4225                 return;
4226
4227         phys_obj = dev_priv->mm.phys_objs[id - 1];
4228         if (phys_obj->cur_obj) {
4229                 i915_gem_detach_phys_object(dev, phys_obj->cur_obj);
4230         }
4231
4232 #ifdef CONFIG_X86
4233         set_memory_wb((unsigned long)phys_obj->handle->vaddr, phys_obj->handle->size / PAGE_SIZE);
4234 #endif
4235         drm_pci_free(dev, phys_obj->handle);
4236         kfree(phys_obj);
4237         dev_priv->mm.phys_objs[id - 1] = NULL;
4238 }
4239
4240 void i915_gem_free_all_phys_object(struct drm_device *dev)
4241 {
4242         int i;
4243
4244         for (i = I915_GEM_PHYS_CURSOR_0; i <= I915_MAX_PHYS_OBJECT; i++)
4245                 i915_gem_free_phys_object(dev, i);
4246 }
4247
4248 void i915_gem_detach_phys_object(struct drm_device *dev,
4249                                  struct drm_gem_object *obj)
4250 {
4251         struct drm_i915_gem_object *obj_priv;
4252         int i;
4253         int ret;
4254         int page_count;
4255
4256         obj_priv = obj->driver_private;
4257         if (!obj_priv->phys_obj)
4258                 return;
4259
4260         ret = i915_gem_object_get_pages(obj);
4261         if (ret)
4262                 goto out;
4263
4264         page_count = obj->size / PAGE_SIZE;
4265
4266         for (i = 0; i < page_count; i++) {
4267                 char *dst = kmap_atomic(obj_priv->pages[i], KM_USER0);
4268                 char *src = obj_priv->phys_obj->handle->vaddr + (i * PAGE_SIZE);
4269
4270                 memcpy(dst, src, PAGE_SIZE);
4271                 kunmap_atomic(dst, KM_USER0);
4272         }
4273         drm_clflush_pages(obj_priv->pages, page_count);
4274         drm_agp_chipset_flush(dev);
4275 out:
4276         obj_priv->phys_obj->cur_obj = NULL;
4277         obj_priv->phys_obj = NULL;
4278 }
4279
4280 int
4281 i915_gem_attach_phys_object(struct drm_device *dev,
4282                             struct drm_gem_object *obj, int id)
4283 {
4284         drm_i915_private_t *dev_priv = dev->dev_private;
4285         struct drm_i915_gem_object *obj_priv;
4286         int ret = 0;
4287         int page_count;
4288         int i;
4289
4290         if (id > I915_MAX_PHYS_OBJECT)
4291                 return -EINVAL;
4292
4293         obj_priv = obj->driver_private;
4294
4295         if (obj_priv->phys_obj) {
4296                 if (obj_priv->phys_obj->id == id)
4297                         return 0;
4298                 i915_gem_detach_phys_object(dev, obj);
4299         }
4300
4301
4302         /* create a new object */
4303         if (!dev_priv->mm.phys_objs[id - 1]) {
4304                 ret = i915_gem_init_phys_object(dev, id,
4305                                                 obj->size);
4306                 if (ret) {
4307                         DRM_ERROR("failed to init phys object %d size: %zu\n", id, obj->size);
4308                         goto out;
4309                 }
4310         }
4311
4312         /* bind to the object */
4313         obj_priv->phys_obj = dev_priv->mm.phys_objs[id - 1];
4314         obj_priv->phys_obj->cur_obj = obj;
4315
4316         ret = i915_gem_object_get_pages(obj);
4317         if (ret) {
4318                 DRM_ERROR("failed to get page list\n");
4319                 goto out;
4320         }
4321
4322         page_count = obj->size / PAGE_SIZE;
4323
4324         for (i = 0; i < page_count; i++) {
4325                 char *src = kmap_atomic(obj_priv->pages[i], KM_USER0);
4326                 char *dst = obj_priv->phys_obj->handle->vaddr + (i * PAGE_SIZE);
4327
4328                 memcpy(dst, src, PAGE_SIZE);
4329                 kunmap_atomic(src, KM_USER0);
4330         }
4331
4332         return 0;
4333 out:
4334         return ret;
4335 }
4336
4337 static int
4338 i915_gem_phys_pwrite(struct drm_device *dev, struct drm_gem_object *obj,
4339                      struct drm_i915_gem_pwrite *args,
4340                      struct drm_file *file_priv)
4341 {
4342         struct drm_i915_gem_object *obj_priv = obj->driver_private;
4343         void *obj_addr;
4344         int ret;
4345         char __user *user_data;
4346
4347         user_data = (char __user *) (uintptr_t) args->data_ptr;
4348         obj_addr = obj_priv->phys_obj->handle->vaddr + args->offset;
4349
4350         DRM_DEBUG("obj_addr %p, %lld\n", obj_addr, args->size);
4351         ret = copy_from_user(obj_addr, user_data, args->size);
4352         if (ret)
4353                 return -EFAULT;
4354
4355         drm_agp_chipset_flush(dev);
4356         return 0;
4357 }