Merge remote branch 'airlied/drm-fixes' into drm-intel-fixes
[pandora-kernel.git] / drivers / gpu / drm / i915 / i915_gem.c
1 /*
2  * Copyright © 2008 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  *
23  * Authors:
24  *    Eric Anholt <eric@anholt.net>
25  *
26  */
27
28 #include "drmP.h"
29 #include "drm.h"
30 #include "i915_drm.h"
31 #include "i915_drv.h"
32 #include "i915_trace.h"
33 #include "intel_drv.h"
34 #include <linux/slab.h>
35 #include <linux/swap.h>
36 #include <linux/pci.h>
37 #include <linux/intel-gtt.h>
38
39 static uint32_t i915_gem_get_gtt_alignment(struct drm_gem_object *obj);
40
41 static int i915_gem_object_flush_gpu_write_domain(struct drm_gem_object *obj,
42                                                   bool pipelined);
43 static void i915_gem_object_flush_gtt_write_domain(struct drm_gem_object *obj);
44 static void i915_gem_object_flush_cpu_write_domain(struct drm_gem_object *obj);
45 static int i915_gem_object_set_to_cpu_domain(struct drm_gem_object *obj,
46                                              int write);
47 static int i915_gem_object_set_cpu_read_domain_range(struct drm_gem_object *obj,
48                                                      uint64_t offset,
49                                                      uint64_t size);
50 static void i915_gem_object_set_to_full_cpu_read_domain(struct drm_gem_object *obj);
51 static int i915_gem_object_wait_rendering(struct drm_gem_object *obj,
52                                           bool interruptible);
53 static int i915_gem_object_bind_to_gtt(struct drm_gem_object *obj,
54                                            unsigned alignment);
55 static void i915_gem_clear_fence_reg(struct drm_gem_object *obj);
56 static int i915_gem_phys_pwrite(struct drm_device *dev, struct drm_gem_object *obj,
57                                 struct drm_i915_gem_pwrite *args,
58                                 struct drm_file *file_priv);
59 static void i915_gem_free_object_tail(struct drm_gem_object *obj);
60
61 static int
62 i915_gem_object_get_pages(struct drm_gem_object *obj,
63                           gfp_t gfpmask);
64
65 static void
66 i915_gem_object_put_pages(struct drm_gem_object *obj);
67
68 static LIST_HEAD(shrink_list);
69 static DEFINE_SPINLOCK(shrink_list_lock);
70
71 /* some bookkeeping */
72 static void i915_gem_info_add_obj(struct drm_i915_private *dev_priv,
73                                   size_t size)
74 {
75         dev_priv->mm.object_count++;
76         dev_priv->mm.object_memory += size;
77 }
78
79 static void i915_gem_info_remove_obj(struct drm_i915_private *dev_priv,
80                                      size_t size)
81 {
82         dev_priv->mm.object_count--;
83         dev_priv->mm.object_memory -= size;
84 }
85
86 static void i915_gem_info_add_gtt(struct drm_i915_private *dev_priv,
87                                   size_t size)
88 {
89         dev_priv->mm.gtt_count++;
90         dev_priv->mm.gtt_memory += size;
91 }
92
93 static void i915_gem_info_remove_gtt(struct drm_i915_private *dev_priv,
94                                      size_t size)
95 {
96         dev_priv->mm.gtt_count--;
97         dev_priv->mm.gtt_memory -= size;
98 }
99
100 static void i915_gem_info_add_pin(struct drm_i915_private *dev_priv,
101                                   size_t size)
102 {
103         dev_priv->mm.pin_count++;
104         dev_priv->mm.pin_memory += size;
105 }
106
107 static void i915_gem_info_remove_pin(struct drm_i915_private *dev_priv,
108                                      size_t size)
109 {
110         dev_priv->mm.pin_count--;
111         dev_priv->mm.pin_memory -= size;
112 }
113
114 int
115 i915_gem_check_is_wedged(struct drm_device *dev)
116 {
117         struct drm_i915_private *dev_priv = dev->dev_private;
118         struct completion *x = &dev_priv->error_completion;
119         unsigned long flags;
120         int ret;
121
122         if (!atomic_read(&dev_priv->mm.wedged))
123                 return 0;
124
125         ret = wait_for_completion_interruptible(x);
126         if (ret)
127                 return ret;
128
129         /* Success, we reset the GPU! */
130         if (!atomic_read(&dev_priv->mm.wedged))
131                 return 0;
132
133         /* GPU is hung, bump the completion count to account for
134          * the token we just consumed so that we never hit zero and
135          * end up waiting upon a subsequent completion event that
136          * will never happen.
137          */
138         spin_lock_irqsave(&x->wait.lock, flags);
139         x->done++;
140         spin_unlock_irqrestore(&x->wait.lock, flags);
141         return -EIO;
142 }
143
144 static int i915_mutex_lock_interruptible(struct drm_device *dev)
145 {
146         struct drm_i915_private *dev_priv = dev->dev_private;
147         int ret;
148
149         ret = i915_gem_check_is_wedged(dev);
150         if (ret)
151                 return ret;
152
153         ret = mutex_lock_interruptible(&dev->struct_mutex);
154         if (ret)
155                 return ret;
156
157         if (atomic_read(&dev_priv->mm.wedged)) {
158                 mutex_unlock(&dev->struct_mutex);
159                 return -EAGAIN;
160         }
161
162         WARN_ON(i915_verify_lists(dev));
163         return 0;
164 }
165
166 static inline bool
167 i915_gem_object_is_inactive(struct drm_i915_gem_object *obj_priv)
168 {
169         return obj_priv->gtt_space &&
170                 !obj_priv->active &&
171                 obj_priv->pin_count == 0;
172 }
173
174 int i915_gem_do_init(struct drm_device *dev,
175                      unsigned long start,
176                      unsigned long end)
177 {
178         drm_i915_private_t *dev_priv = dev->dev_private;
179
180         if (start >= end ||
181             (start & (PAGE_SIZE - 1)) != 0 ||
182             (end & (PAGE_SIZE - 1)) != 0) {
183                 return -EINVAL;
184         }
185
186         drm_mm_init(&dev_priv->mm.gtt_space, start,
187                     end - start);
188
189         dev_priv->mm.gtt_total = end - start;
190
191         return 0;
192 }
193
194 int
195 i915_gem_init_ioctl(struct drm_device *dev, void *data,
196                     struct drm_file *file_priv)
197 {
198         struct drm_i915_gem_init *args = data;
199         int ret;
200
201         mutex_lock(&dev->struct_mutex);
202         ret = i915_gem_do_init(dev, args->gtt_start, args->gtt_end);
203         mutex_unlock(&dev->struct_mutex);
204
205         return ret;
206 }
207
208 int
209 i915_gem_get_aperture_ioctl(struct drm_device *dev, void *data,
210                             struct drm_file *file_priv)
211 {
212         struct drm_i915_private *dev_priv = dev->dev_private;
213         struct drm_i915_gem_get_aperture *args = data;
214
215         if (!(dev->driver->driver_features & DRIVER_GEM))
216                 return -ENODEV;
217
218         mutex_lock(&dev->struct_mutex);
219         args->aper_size = dev_priv->mm.gtt_total;
220         args->aper_available_size = args->aper_size - dev_priv->mm.pin_memory;
221         mutex_unlock(&dev->struct_mutex);
222
223         return 0;
224 }
225
226
227 /**
228  * Creates a new mm object and returns a handle to it.
229  */
230 int
231 i915_gem_create_ioctl(struct drm_device *dev, void *data,
232                       struct drm_file *file_priv)
233 {
234         struct drm_i915_gem_create *args = data;
235         struct drm_gem_object *obj;
236         int ret;
237         u32 handle;
238
239         args->size = roundup(args->size, PAGE_SIZE);
240
241         /* Allocate the new object */
242         obj = i915_gem_alloc_object(dev, args->size);
243         if (obj == NULL)
244                 return -ENOMEM;
245
246         ret = drm_gem_handle_create(file_priv, obj, &handle);
247         if (ret) {
248                 drm_gem_object_release(obj);
249                 i915_gem_info_remove_obj(dev->dev_private, obj->size);
250                 kfree(obj);
251                 return ret;
252         }
253
254         /* drop reference from allocate - handle holds it now */
255         drm_gem_object_unreference(obj);
256         trace_i915_gem_object_create(obj);
257
258         args->handle = handle;
259         return 0;
260 }
261
262 static inline int
263 fast_shmem_read(struct page **pages,
264                 loff_t page_base, int page_offset,
265                 char __user *data,
266                 int length)
267 {
268         char *vaddr;
269         int ret;
270
271         vaddr = kmap_atomic(pages[page_base >> PAGE_SHIFT]);
272         ret = __copy_to_user_inatomic(data, vaddr + page_offset, length);
273         kunmap_atomic(vaddr);
274
275         return ret;
276 }
277
278 static int i915_gem_object_needs_bit17_swizzle(struct drm_gem_object *obj)
279 {
280         drm_i915_private_t *dev_priv = obj->dev->dev_private;
281         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
282
283         return dev_priv->mm.bit_6_swizzle_x == I915_BIT_6_SWIZZLE_9_10_17 &&
284                 obj_priv->tiling_mode != I915_TILING_NONE;
285 }
286
287 static inline void
288 slow_shmem_copy(struct page *dst_page,
289                 int dst_offset,
290                 struct page *src_page,
291                 int src_offset,
292                 int length)
293 {
294         char *dst_vaddr, *src_vaddr;
295
296         dst_vaddr = kmap(dst_page);
297         src_vaddr = kmap(src_page);
298
299         memcpy(dst_vaddr + dst_offset, src_vaddr + src_offset, length);
300
301         kunmap(src_page);
302         kunmap(dst_page);
303 }
304
305 static inline void
306 slow_shmem_bit17_copy(struct page *gpu_page,
307                       int gpu_offset,
308                       struct page *cpu_page,
309                       int cpu_offset,
310                       int length,
311                       int is_read)
312 {
313         char *gpu_vaddr, *cpu_vaddr;
314
315         /* Use the unswizzled path if this page isn't affected. */
316         if ((page_to_phys(gpu_page) & (1 << 17)) == 0) {
317                 if (is_read)
318                         return slow_shmem_copy(cpu_page, cpu_offset,
319                                                gpu_page, gpu_offset, length);
320                 else
321                         return slow_shmem_copy(gpu_page, gpu_offset,
322                                                cpu_page, cpu_offset, length);
323         }
324
325         gpu_vaddr = kmap(gpu_page);
326         cpu_vaddr = kmap(cpu_page);
327
328         /* Copy the data, XORing A6 with A17 (1). The user already knows he's
329          * XORing with the other bits (A9 for Y, A9 and A10 for X)
330          */
331         while (length > 0) {
332                 int cacheline_end = ALIGN(gpu_offset + 1, 64);
333                 int this_length = min(cacheline_end - gpu_offset, length);
334                 int swizzled_gpu_offset = gpu_offset ^ 64;
335
336                 if (is_read) {
337                         memcpy(cpu_vaddr + cpu_offset,
338                                gpu_vaddr + swizzled_gpu_offset,
339                                this_length);
340                 } else {
341                         memcpy(gpu_vaddr + swizzled_gpu_offset,
342                                cpu_vaddr + cpu_offset,
343                                this_length);
344                 }
345                 cpu_offset += this_length;
346                 gpu_offset += this_length;
347                 length -= this_length;
348         }
349
350         kunmap(cpu_page);
351         kunmap(gpu_page);
352 }
353
354 /**
355  * This is the fast shmem pread path, which attempts to copy_from_user directly
356  * from the backing pages of the object to the user's address space.  On a
357  * fault, it fails so we can fall back to i915_gem_shmem_pwrite_slow().
358  */
359 static int
360 i915_gem_shmem_pread_fast(struct drm_device *dev, struct drm_gem_object *obj,
361                           struct drm_i915_gem_pread *args,
362                           struct drm_file *file_priv)
363 {
364         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
365         ssize_t remain;
366         loff_t offset, page_base;
367         char __user *user_data;
368         int page_offset, page_length;
369
370         user_data = (char __user *) (uintptr_t) args->data_ptr;
371         remain = args->size;
372
373         obj_priv = to_intel_bo(obj);
374         offset = args->offset;
375
376         while (remain > 0) {
377                 /* Operation in this page
378                  *
379                  * page_base = page offset within aperture
380                  * page_offset = offset within page
381                  * page_length = bytes to copy for this page
382                  */
383                 page_base = (offset & ~(PAGE_SIZE-1));
384                 page_offset = offset & (PAGE_SIZE-1);
385                 page_length = remain;
386                 if ((page_offset + remain) > PAGE_SIZE)
387                         page_length = PAGE_SIZE - page_offset;
388
389                 if (fast_shmem_read(obj_priv->pages,
390                                     page_base, page_offset,
391                                     user_data, page_length))
392                         return -EFAULT;
393
394                 remain -= page_length;
395                 user_data += page_length;
396                 offset += page_length;
397         }
398
399         return 0;
400 }
401
402 static int
403 i915_gem_object_get_pages_or_evict(struct drm_gem_object *obj)
404 {
405         int ret;
406
407         ret = i915_gem_object_get_pages(obj, __GFP_NORETRY | __GFP_NOWARN);
408
409         /* If we've insufficient memory to map in the pages, attempt
410          * to make some space by throwing out some old buffers.
411          */
412         if (ret == -ENOMEM) {
413                 struct drm_device *dev = obj->dev;
414
415                 ret = i915_gem_evict_something(dev, obj->size,
416                                                i915_gem_get_gtt_alignment(obj));
417                 if (ret)
418                         return ret;
419
420                 ret = i915_gem_object_get_pages(obj, 0);
421         }
422
423         return ret;
424 }
425
426 /**
427  * This is the fallback shmem pread path, which allocates temporary storage
428  * in kernel space to copy_to_user into outside of the struct_mutex, so we
429  * can copy out of the object's backing pages while holding the struct mutex
430  * and not take page faults.
431  */
432 static int
433 i915_gem_shmem_pread_slow(struct drm_device *dev, struct drm_gem_object *obj,
434                           struct drm_i915_gem_pread *args,
435                           struct drm_file *file_priv)
436 {
437         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
438         struct mm_struct *mm = current->mm;
439         struct page **user_pages;
440         ssize_t remain;
441         loff_t offset, pinned_pages, i;
442         loff_t first_data_page, last_data_page, num_pages;
443         int shmem_page_index, shmem_page_offset;
444         int data_page_index,  data_page_offset;
445         int page_length;
446         int ret;
447         uint64_t data_ptr = args->data_ptr;
448         int do_bit17_swizzling;
449
450         remain = args->size;
451
452         /* Pin the user pages containing the data.  We can't fault while
453          * holding the struct mutex, yet we want to hold it while
454          * dereferencing the user data.
455          */
456         first_data_page = data_ptr / PAGE_SIZE;
457         last_data_page = (data_ptr + args->size - 1) / PAGE_SIZE;
458         num_pages = last_data_page - first_data_page + 1;
459
460         user_pages = drm_malloc_ab(num_pages, sizeof(struct page *));
461         if (user_pages == NULL)
462                 return -ENOMEM;
463
464         mutex_unlock(&dev->struct_mutex);
465         down_read(&mm->mmap_sem);
466         pinned_pages = get_user_pages(current, mm, (uintptr_t)args->data_ptr,
467                                       num_pages, 1, 0, user_pages, NULL);
468         up_read(&mm->mmap_sem);
469         mutex_lock(&dev->struct_mutex);
470         if (pinned_pages < num_pages) {
471                 ret = -EFAULT;
472                 goto out;
473         }
474
475         ret = i915_gem_object_set_cpu_read_domain_range(obj,
476                                                         args->offset,
477                                                         args->size);
478         if (ret)
479                 goto out;
480
481         do_bit17_swizzling = i915_gem_object_needs_bit17_swizzle(obj);
482
483         obj_priv = to_intel_bo(obj);
484         offset = args->offset;
485
486         while (remain > 0) {
487                 /* Operation in this page
488                  *
489                  * shmem_page_index = page number within shmem file
490                  * shmem_page_offset = offset within page in shmem file
491                  * data_page_index = page number in get_user_pages return
492                  * data_page_offset = offset with data_page_index page.
493                  * page_length = bytes to copy for this page
494                  */
495                 shmem_page_index = offset / PAGE_SIZE;
496                 shmem_page_offset = offset & ~PAGE_MASK;
497                 data_page_index = data_ptr / PAGE_SIZE - first_data_page;
498                 data_page_offset = data_ptr & ~PAGE_MASK;
499
500                 page_length = remain;
501                 if ((shmem_page_offset + page_length) > PAGE_SIZE)
502                         page_length = PAGE_SIZE - shmem_page_offset;
503                 if ((data_page_offset + page_length) > PAGE_SIZE)
504                         page_length = PAGE_SIZE - data_page_offset;
505
506                 if (do_bit17_swizzling) {
507                         slow_shmem_bit17_copy(obj_priv->pages[shmem_page_index],
508                                               shmem_page_offset,
509                                               user_pages[data_page_index],
510                                               data_page_offset,
511                                               page_length,
512                                               1);
513                 } else {
514                         slow_shmem_copy(user_pages[data_page_index],
515                                         data_page_offset,
516                                         obj_priv->pages[shmem_page_index],
517                                         shmem_page_offset,
518                                         page_length);
519                 }
520
521                 remain -= page_length;
522                 data_ptr += page_length;
523                 offset += page_length;
524         }
525
526 out:
527         for (i = 0; i < pinned_pages; i++) {
528                 SetPageDirty(user_pages[i]);
529                 page_cache_release(user_pages[i]);
530         }
531         drm_free_large(user_pages);
532
533         return ret;
534 }
535
536 /**
537  * Reads data from the object referenced by handle.
538  *
539  * On error, the contents of *data are undefined.
540  */
541 int
542 i915_gem_pread_ioctl(struct drm_device *dev, void *data,
543                      struct drm_file *file_priv)
544 {
545         struct drm_i915_gem_pread *args = data;
546         struct drm_gem_object *obj;
547         struct drm_i915_gem_object *obj_priv;
548         int ret = 0;
549
550         ret = i915_mutex_lock_interruptible(dev);
551         if (ret)
552                 return ret;
553
554         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
555         if (obj == NULL) {
556                 ret = -ENOENT;
557                 goto unlock;
558         }
559         obj_priv = to_intel_bo(obj);
560
561         /* Bounds check source.  */
562         if (args->offset > obj->size || args->size > obj->size - args->offset) {
563                 ret = -EINVAL;
564                 goto out;
565         }
566
567         if (args->size == 0)
568                 goto out;
569
570         if (!access_ok(VERIFY_WRITE,
571                        (char __user *)(uintptr_t)args->data_ptr,
572                        args->size)) {
573                 ret = -EFAULT;
574                 goto out;
575         }
576
577         ret = fault_in_pages_writeable((char __user *)(uintptr_t)args->data_ptr,
578                                        args->size);
579         if (ret) {
580                 ret = -EFAULT;
581                 goto out;
582         }
583
584         ret = i915_gem_object_get_pages_or_evict(obj);
585         if (ret)
586                 goto out;
587
588         ret = i915_gem_object_set_cpu_read_domain_range(obj,
589                                                         args->offset,
590                                                         args->size);
591         if (ret)
592                 goto out_put;
593
594         ret = -EFAULT;
595         if (!i915_gem_object_needs_bit17_swizzle(obj))
596                 ret = i915_gem_shmem_pread_fast(dev, obj, args, file_priv);
597         if (ret == -EFAULT)
598                 ret = i915_gem_shmem_pread_slow(dev, obj, args, file_priv);
599
600 out_put:
601         i915_gem_object_put_pages(obj);
602 out:
603         drm_gem_object_unreference(obj);
604 unlock:
605         mutex_unlock(&dev->struct_mutex);
606         return ret;
607 }
608
609 /* This is the fast write path which cannot handle
610  * page faults in the source data
611  */
612
613 static inline int
614 fast_user_write(struct io_mapping *mapping,
615                 loff_t page_base, int page_offset,
616                 char __user *user_data,
617                 int length)
618 {
619         char *vaddr_atomic;
620         unsigned long unwritten;
621
622         vaddr_atomic = io_mapping_map_atomic_wc(mapping, page_base);
623         unwritten = __copy_from_user_inatomic_nocache(vaddr_atomic + page_offset,
624                                                       user_data, length);
625         io_mapping_unmap_atomic(vaddr_atomic);
626         return unwritten;
627 }
628
629 /* Here's the write path which can sleep for
630  * page faults
631  */
632
633 static inline void
634 slow_kernel_write(struct io_mapping *mapping,
635                   loff_t gtt_base, int gtt_offset,
636                   struct page *user_page, int user_offset,
637                   int length)
638 {
639         char __iomem *dst_vaddr;
640         char *src_vaddr;
641
642         dst_vaddr = io_mapping_map_wc(mapping, gtt_base);
643         src_vaddr = kmap(user_page);
644
645         memcpy_toio(dst_vaddr + gtt_offset,
646                     src_vaddr + user_offset,
647                     length);
648
649         kunmap(user_page);
650         io_mapping_unmap(dst_vaddr);
651 }
652
653 static inline int
654 fast_shmem_write(struct page **pages,
655                  loff_t page_base, int page_offset,
656                  char __user *data,
657                  int length)
658 {
659         char *vaddr;
660         int ret;
661
662         vaddr = kmap_atomic(pages[page_base >> PAGE_SHIFT]);
663         ret = __copy_from_user_inatomic(vaddr + page_offset, data, length);
664         kunmap_atomic(vaddr);
665
666         return ret;
667 }
668
669 /**
670  * This is the fast pwrite path, where we copy the data directly from the
671  * user into the GTT, uncached.
672  */
673 static int
674 i915_gem_gtt_pwrite_fast(struct drm_device *dev, struct drm_gem_object *obj,
675                          struct drm_i915_gem_pwrite *args,
676                          struct drm_file *file_priv)
677 {
678         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
679         drm_i915_private_t *dev_priv = dev->dev_private;
680         ssize_t remain;
681         loff_t offset, page_base;
682         char __user *user_data;
683         int page_offset, page_length;
684
685         user_data = (char __user *) (uintptr_t) args->data_ptr;
686         remain = args->size;
687
688         obj_priv = to_intel_bo(obj);
689         offset = obj_priv->gtt_offset + args->offset;
690
691         while (remain > 0) {
692                 /* Operation in this page
693                  *
694                  * page_base = page offset within aperture
695                  * page_offset = offset within page
696                  * page_length = bytes to copy for this page
697                  */
698                 page_base = (offset & ~(PAGE_SIZE-1));
699                 page_offset = offset & (PAGE_SIZE-1);
700                 page_length = remain;
701                 if ((page_offset + remain) > PAGE_SIZE)
702                         page_length = PAGE_SIZE - page_offset;
703
704                 /* If we get a fault while copying data, then (presumably) our
705                  * source page isn't available.  Return the error and we'll
706                  * retry in the slow path.
707                  */
708                 if (fast_user_write(dev_priv->mm.gtt_mapping, page_base,
709                                     page_offset, user_data, page_length))
710
711                         return -EFAULT;
712
713                 remain -= page_length;
714                 user_data += page_length;
715                 offset += page_length;
716         }
717
718         return 0;
719 }
720
721 /**
722  * This is the fallback GTT pwrite path, which uses get_user_pages to pin
723  * the memory and maps it using kmap_atomic for copying.
724  *
725  * This code resulted in x11perf -rgb10text consuming about 10% more CPU
726  * than using i915_gem_gtt_pwrite_fast on a G45 (32-bit).
727  */
728 static int
729 i915_gem_gtt_pwrite_slow(struct drm_device *dev, struct drm_gem_object *obj,
730                          struct drm_i915_gem_pwrite *args,
731                          struct drm_file *file_priv)
732 {
733         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
734         drm_i915_private_t *dev_priv = dev->dev_private;
735         ssize_t remain;
736         loff_t gtt_page_base, offset;
737         loff_t first_data_page, last_data_page, num_pages;
738         loff_t pinned_pages, i;
739         struct page **user_pages;
740         struct mm_struct *mm = current->mm;
741         int gtt_page_offset, data_page_offset, data_page_index, page_length;
742         int ret;
743         uint64_t data_ptr = args->data_ptr;
744
745         remain = args->size;
746
747         /* Pin the user pages containing the data.  We can't fault while
748          * holding the struct mutex, and all of the pwrite implementations
749          * want to hold it while dereferencing the user data.
750          */
751         first_data_page = data_ptr / PAGE_SIZE;
752         last_data_page = (data_ptr + args->size - 1) / PAGE_SIZE;
753         num_pages = last_data_page - first_data_page + 1;
754
755         user_pages = drm_malloc_ab(num_pages, sizeof(struct page *));
756         if (user_pages == NULL)
757                 return -ENOMEM;
758
759         mutex_unlock(&dev->struct_mutex);
760         down_read(&mm->mmap_sem);
761         pinned_pages = get_user_pages(current, mm, (uintptr_t)args->data_ptr,
762                                       num_pages, 0, 0, user_pages, NULL);
763         up_read(&mm->mmap_sem);
764         mutex_lock(&dev->struct_mutex);
765         if (pinned_pages < num_pages) {
766                 ret = -EFAULT;
767                 goto out_unpin_pages;
768         }
769
770         ret = i915_gem_object_set_to_gtt_domain(obj, 1);
771         if (ret)
772                 goto out_unpin_pages;
773
774         obj_priv = to_intel_bo(obj);
775         offset = obj_priv->gtt_offset + args->offset;
776
777         while (remain > 0) {
778                 /* Operation in this page
779                  *
780                  * gtt_page_base = page offset within aperture
781                  * gtt_page_offset = offset within page in aperture
782                  * data_page_index = page number in get_user_pages return
783                  * data_page_offset = offset with data_page_index page.
784                  * page_length = bytes to copy for this page
785                  */
786                 gtt_page_base = offset & PAGE_MASK;
787                 gtt_page_offset = offset & ~PAGE_MASK;
788                 data_page_index = data_ptr / PAGE_SIZE - first_data_page;
789                 data_page_offset = data_ptr & ~PAGE_MASK;
790
791                 page_length = remain;
792                 if ((gtt_page_offset + page_length) > PAGE_SIZE)
793                         page_length = PAGE_SIZE - gtt_page_offset;
794                 if ((data_page_offset + page_length) > PAGE_SIZE)
795                         page_length = PAGE_SIZE - data_page_offset;
796
797                 slow_kernel_write(dev_priv->mm.gtt_mapping,
798                                   gtt_page_base, gtt_page_offset,
799                                   user_pages[data_page_index],
800                                   data_page_offset,
801                                   page_length);
802
803                 remain -= page_length;
804                 offset += page_length;
805                 data_ptr += page_length;
806         }
807
808 out_unpin_pages:
809         for (i = 0; i < pinned_pages; i++)
810                 page_cache_release(user_pages[i]);
811         drm_free_large(user_pages);
812
813         return ret;
814 }
815
816 /**
817  * This is the fast shmem pwrite path, which attempts to directly
818  * copy_from_user into the kmapped pages backing the object.
819  */
820 static int
821 i915_gem_shmem_pwrite_fast(struct drm_device *dev, struct drm_gem_object *obj,
822                            struct drm_i915_gem_pwrite *args,
823                            struct drm_file *file_priv)
824 {
825         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
826         ssize_t remain;
827         loff_t offset, page_base;
828         char __user *user_data;
829         int page_offset, page_length;
830
831         user_data = (char __user *) (uintptr_t) args->data_ptr;
832         remain = args->size;
833
834         obj_priv = to_intel_bo(obj);
835         offset = args->offset;
836         obj_priv->dirty = 1;
837
838         while (remain > 0) {
839                 /* Operation in this page
840                  *
841                  * page_base = page offset within aperture
842                  * page_offset = offset within page
843                  * page_length = bytes to copy for this page
844                  */
845                 page_base = (offset & ~(PAGE_SIZE-1));
846                 page_offset = offset & (PAGE_SIZE-1);
847                 page_length = remain;
848                 if ((page_offset + remain) > PAGE_SIZE)
849                         page_length = PAGE_SIZE - page_offset;
850
851                 if (fast_shmem_write(obj_priv->pages,
852                                        page_base, page_offset,
853                                        user_data, page_length))
854                         return -EFAULT;
855
856                 remain -= page_length;
857                 user_data += page_length;
858                 offset += page_length;
859         }
860
861         return 0;
862 }
863
864 /**
865  * This is the fallback shmem pwrite path, which uses get_user_pages to pin
866  * the memory and maps it using kmap_atomic for copying.
867  *
868  * This avoids taking mmap_sem for faulting on the user's address while the
869  * struct_mutex is held.
870  */
871 static int
872 i915_gem_shmem_pwrite_slow(struct drm_device *dev, struct drm_gem_object *obj,
873                            struct drm_i915_gem_pwrite *args,
874                            struct drm_file *file_priv)
875 {
876         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
877         struct mm_struct *mm = current->mm;
878         struct page **user_pages;
879         ssize_t remain;
880         loff_t offset, pinned_pages, i;
881         loff_t first_data_page, last_data_page, num_pages;
882         int shmem_page_index, shmem_page_offset;
883         int data_page_index,  data_page_offset;
884         int page_length;
885         int ret;
886         uint64_t data_ptr = args->data_ptr;
887         int do_bit17_swizzling;
888
889         remain = args->size;
890
891         /* Pin the user pages containing the data.  We can't fault while
892          * holding the struct mutex, and all of the pwrite implementations
893          * want to hold it while dereferencing the user data.
894          */
895         first_data_page = data_ptr / PAGE_SIZE;
896         last_data_page = (data_ptr + args->size - 1) / PAGE_SIZE;
897         num_pages = last_data_page - first_data_page + 1;
898
899         user_pages = drm_malloc_ab(num_pages, sizeof(struct page *));
900         if (user_pages == NULL)
901                 return -ENOMEM;
902
903         mutex_unlock(&dev->struct_mutex);
904         down_read(&mm->mmap_sem);
905         pinned_pages = get_user_pages(current, mm, (uintptr_t)args->data_ptr,
906                                       num_pages, 0, 0, user_pages, NULL);
907         up_read(&mm->mmap_sem);
908         mutex_lock(&dev->struct_mutex);
909         if (pinned_pages < num_pages) {
910                 ret = -EFAULT;
911                 goto out;
912         }
913
914         ret = i915_gem_object_set_to_cpu_domain(obj, 1);
915         if (ret)
916                 goto out;
917
918         do_bit17_swizzling = i915_gem_object_needs_bit17_swizzle(obj);
919
920         obj_priv = to_intel_bo(obj);
921         offset = args->offset;
922         obj_priv->dirty = 1;
923
924         while (remain > 0) {
925                 /* Operation in this page
926                  *
927                  * shmem_page_index = page number within shmem file
928                  * shmem_page_offset = offset within page in shmem file
929                  * data_page_index = page number in get_user_pages return
930                  * data_page_offset = offset with data_page_index page.
931                  * page_length = bytes to copy for this page
932                  */
933                 shmem_page_index = offset / PAGE_SIZE;
934                 shmem_page_offset = offset & ~PAGE_MASK;
935                 data_page_index = data_ptr / PAGE_SIZE - first_data_page;
936                 data_page_offset = data_ptr & ~PAGE_MASK;
937
938                 page_length = remain;
939                 if ((shmem_page_offset + page_length) > PAGE_SIZE)
940                         page_length = PAGE_SIZE - shmem_page_offset;
941                 if ((data_page_offset + page_length) > PAGE_SIZE)
942                         page_length = PAGE_SIZE - data_page_offset;
943
944                 if (do_bit17_swizzling) {
945                         slow_shmem_bit17_copy(obj_priv->pages[shmem_page_index],
946                                               shmem_page_offset,
947                                               user_pages[data_page_index],
948                                               data_page_offset,
949                                               page_length,
950                                               0);
951                 } else {
952                         slow_shmem_copy(obj_priv->pages[shmem_page_index],
953                                         shmem_page_offset,
954                                         user_pages[data_page_index],
955                                         data_page_offset,
956                                         page_length);
957                 }
958
959                 remain -= page_length;
960                 data_ptr += page_length;
961                 offset += page_length;
962         }
963
964 out:
965         for (i = 0; i < pinned_pages; i++)
966                 page_cache_release(user_pages[i]);
967         drm_free_large(user_pages);
968
969         return ret;
970 }
971
972 /**
973  * Writes data to the object referenced by handle.
974  *
975  * On error, the contents of the buffer that were to be modified are undefined.
976  */
977 int
978 i915_gem_pwrite_ioctl(struct drm_device *dev, void *data,
979                       struct drm_file *file)
980 {
981         struct drm_i915_gem_pwrite *args = data;
982         struct drm_gem_object *obj;
983         struct drm_i915_gem_object *obj_priv;
984         int ret = 0;
985
986         ret = i915_mutex_lock_interruptible(dev);
987         if (ret)
988                 return ret;
989
990         obj = drm_gem_object_lookup(dev, file, args->handle);
991         if (obj == NULL) {
992                 ret = -ENOENT;
993                 goto unlock;
994         }
995         obj_priv = to_intel_bo(obj);
996
997
998         /* Bounds check destination. */
999         if (args->offset > obj->size || args->size > obj->size - args->offset) {
1000                 ret = -EINVAL;
1001                 goto out;
1002         }
1003
1004         if (args->size == 0)
1005                 goto out;
1006
1007         if (!access_ok(VERIFY_READ,
1008                        (char __user *)(uintptr_t)args->data_ptr,
1009                        args->size)) {
1010                 ret = -EFAULT;
1011                 goto out;
1012         }
1013
1014         ret = fault_in_pages_readable((char __user *)(uintptr_t)args->data_ptr,
1015                                       args->size);
1016         if (ret) {
1017                 ret = -EFAULT;
1018                 goto out;
1019         }
1020
1021         /* We can only do the GTT pwrite on untiled buffers, as otherwise
1022          * it would end up going through the fenced access, and we'll get
1023          * different detiling behavior between reading and writing.
1024          * pread/pwrite currently are reading and writing from the CPU
1025          * perspective, requiring manual detiling by the client.
1026          */
1027         if (obj_priv->phys_obj)
1028                 ret = i915_gem_phys_pwrite(dev, obj, args, file);
1029         else if (obj_priv->tiling_mode == I915_TILING_NONE &&
1030                  obj_priv->gtt_space &&
1031                  obj->write_domain != I915_GEM_DOMAIN_CPU) {
1032                 ret = i915_gem_object_pin(obj, 0);
1033                 if (ret)
1034                         goto out;
1035
1036                 ret = i915_gem_object_set_to_gtt_domain(obj, 1);
1037                 if (ret)
1038                         goto out_unpin;
1039
1040                 ret = i915_gem_gtt_pwrite_fast(dev, obj, args, file);
1041                 if (ret == -EFAULT)
1042                         ret = i915_gem_gtt_pwrite_slow(dev, obj, args, file);
1043
1044 out_unpin:
1045                 i915_gem_object_unpin(obj);
1046         } else {
1047                 ret = i915_gem_object_get_pages_or_evict(obj);
1048                 if (ret)
1049                         goto out;
1050
1051                 ret = i915_gem_object_set_to_cpu_domain(obj, 1);
1052                 if (ret)
1053                         goto out_put;
1054
1055                 ret = -EFAULT;
1056                 if (!i915_gem_object_needs_bit17_swizzle(obj))
1057                         ret = i915_gem_shmem_pwrite_fast(dev, obj, args, file);
1058                 if (ret == -EFAULT)
1059                         ret = i915_gem_shmem_pwrite_slow(dev, obj, args, file);
1060
1061 out_put:
1062                 i915_gem_object_put_pages(obj);
1063         }
1064
1065 out:
1066         drm_gem_object_unreference(obj);
1067 unlock:
1068         mutex_unlock(&dev->struct_mutex);
1069         return ret;
1070 }
1071
1072 /**
1073  * Called when user space prepares to use an object with the CPU, either
1074  * through the mmap ioctl's mapping or a GTT mapping.
1075  */
1076 int
1077 i915_gem_set_domain_ioctl(struct drm_device *dev, void *data,
1078                           struct drm_file *file_priv)
1079 {
1080         struct drm_i915_private *dev_priv = dev->dev_private;
1081         struct drm_i915_gem_set_domain *args = data;
1082         struct drm_gem_object *obj;
1083         struct drm_i915_gem_object *obj_priv;
1084         uint32_t read_domains = args->read_domains;
1085         uint32_t write_domain = args->write_domain;
1086         int ret;
1087
1088         if (!(dev->driver->driver_features & DRIVER_GEM))
1089                 return -ENODEV;
1090
1091         /* Only handle setting domains to types used by the CPU. */
1092         if (write_domain & I915_GEM_GPU_DOMAINS)
1093                 return -EINVAL;
1094
1095         if (read_domains & I915_GEM_GPU_DOMAINS)
1096                 return -EINVAL;
1097
1098         /* Having something in the write domain implies it's in the read
1099          * domain, and only that read domain.  Enforce that in the request.
1100          */
1101         if (write_domain != 0 && read_domains != write_domain)
1102                 return -EINVAL;
1103
1104         ret = i915_mutex_lock_interruptible(dev);
1105         if (ret)
1106                 return ret;
1107
1108         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
1109         if (obj == NULL) {
1110                 ret = -ENOENT;
1111                 goto unlock;
1112         }
1113         obj_priv = to_intel_bo(obj);
1114
1115         intel_mark_busy(dev, obj);
1116
1117         if (read_domains & I915_GEM_DOMAIN_GTT) {
1118                 ret = i915_gem_object_set_to_gtt_domain(obj, write_domain != 0);
1119
1120                 /* Update the LRU on the fence for the CPU access that's
1121                  * about to occur.
1122                  */
1123                 if (obj_priv->fence_reg != I915_FENCE_REG_NONE) {
1124                         struct drm_i915_fence_reg *reg =
1125                                 &dev_priv->fence_regs[obj_priv->fence_reg];
1126                         list_move_tail(&reg->lru_list,
1127                                        &dev_priv->mm.fence_list);
1128                 }
1129
1130                 /* Silently promote "you're not bound, there was nothing to do"
1131                  * to success, since the client was just asking us to
1132                  * make sure everything was done.
1133                  */
1134                 if (ret == -EINVAL)
1135                         ret = 0;
1136         } else {
1137                 ret = i915_gem_object_set_to_cpu_domain(obj, write_domain != 0);
1138         }
1139
1140         /* Maintain LRU order of "inactive" objects */
1141         if (ret == 0 && i915_gem_object_is_inactive(obj_priv))
1142                 list_move_tail(&obj_priv->mm_list, &dev_priv->mm.inactive_list);
1143
1144         drm_gem_object_unreference(obj);
1145 unlock:
1146         mutex_unlock(&dev->struct_mutex);
1147         return ret;
1148 }
1149
1150 /**
1151  * Called when user space has done writes to this buffer
1152  */
1153 int
1154 i915_gem_sw_finish_ioctl(struct drm_device *dev, void *data,
1155                       struct drm_file *file_priv)
1156 {
1157         struct drm_i915_gem_sw_finish *args = data;
1158         struct drm_gem_object *obj;
1159         int ret = 0;
1160
1161         if (!(dev->driver->driver_features & DRIVER_GEM))
1162                 return -ENODEV;
1163
1164         ret = i915_mutex_lock_interruptible(dev);
1165         if (ret)
1166                 return ret;
1167
1168         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
1169         if (obj == NULL) {
1170                 ret = -ENOENT;
1171                 goto unlock;
1172         }
1173
1174         /* Pinned buffers may be scanout, so flush the cache */
1175         if (to_intel_bo(obj)->pin_count)
1176                 i915_gem_object_flush_cpu_write_domain(obj);
1177
1178         drm_gem_object_unreference(obj);
1179 unlock:
1180         mutex_unlock(&dev->struct_mutex);
1181         return ret;
1182 }
1183
1184 /**
1185  * Maps the contents of an object, returning the address it is mapped
1186  * into.
1187  *
1188  * While the mapping holds a reference on the contents of the object, it doesn't
1189  * imply a ref on the object itself.
1190  */
1191 int
1192 i915_gem_mmap_ioctl(struct drm_device *dev, void *data,
1193                    struct drm_file *file_priv)
1194 {
1195         struct drm_i915_gem_mmap *args = data;
1196         struct drm_gem_object *obj;
1197         loff_t offset;
1198         unsigned long addr;
1199
1200         if (!(dev->driver->driver_features & DRIVER_GEM))
1201                 return -ENODEV;
1202
1203         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
1204         if (obj == NULL)
1205                 return -ENOENT;
1206
1207         offset = args->offset;
1208
1209         down_write(&current->mm->mmap_sem);
1210         addr = do_mmap(obj->filp, 0, args->size,
1211                        PROT_READ | PROT_WRITE, MAP_SHARED,
1212                        args->offset);
1213         up_write(&current->mm->mmap_sem);
1214         drm_gem_object_unreference_unlocked(obj);
1215         if (IS_ERR((void *)addr))
1216                 return addr;
1217
1218         args->addr_ptr = (uint64_t) addr;
1219
1220         return 0;
1221 }
1222
1223 /**
1224  * i915_gem_fault - fault a page into the GTT
1225  * vma: VMA in question
1226  * vmf: fault info
1227  *
1228  * The fault handler is set up by drm_gem_mmap() when a object is GTT mapped
1229  * from userspace.  The fault handler takes care of binding the object to
1230  * the GTT (if needed), allocating and programming a fence register (again,
1231  * only if needed based on whether the old reg is still valid or the object
1232  * is tiled) and inserting a new PTE into the faulting process.
1233  *
1234  * Note that the faulting process may involve evicting existing objects
1235  * from the GTT and/or fence registers to make room.  So performance may
1236  * suffer if the GTT working set is large or there are few fence registers
1237  * left.
1238  */
1239 int i915_gem_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1240 {
1241         struct drm_gem_object *obj = vma->vm_private_data;
1242         struct drm_device *dev = obj->dev;
1243         drm_i915_private_t *dev_priv = dev->dev_private;
1244         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
1245         pgoff_t page_offset;
1246         unsigned long pfn;
1247         int ret = 0;
1248         bool write = !!(vmf->flags & FAULT_FLAG_WRITE);
1249
1250         /* We don't use vmf->pgoff since that has the fake offset */
1251         page_offset = ((unsigned long)vmf->virtual_address - vma->vm_start) >>
1252                 PAGE_SHIFT;
1253
1254         /* Now bind it into the GTT if needed */
1255         mutex_lock(&dev->struct_mutex);
1256         if (!obj_priv->gtt_space) {
1257                 ret = i915_gem_object_bind_to_gtt(obj, 0);
1258                 if (ret)
1259                         goto unlock;
1260
1261                 ret = i915_gem_object_set_to_gtt_domain(obj, write);
1262                 if (ret)
1263                         goto unlock;
1264         }
1265
1266         /* Need a new fence register? */
1267         if (obj_priv->tiling_mode != I915_TILING_NONE) {
1268                 ret = i915_gem_object_get_fence_reg(obj, true);
1269                 if (ret)
1270                         goto unlock;
1271         }
1272
1273         if (i915_gem_object_is_inactive(obj_priv))
1274                 list_move_tail(&obj_priv->mm_list, &dev_priv->mm.inactive_list);
1275
1276         pfn = ((dev->agp->base + obj_priv->gtt_offset) >> PAGE_SHIFT) +
1277                 page_offset;
1278
1279         /* Finally, remap it using the new GTT offset */
1280         ret = vm_insert_pfn(vma, (unsigned long)vmf->virtual_address, pfn);
1281 unlock:
1282         mutex_unlock(&dev->struct_mutex);
1283
1284         switch (ret) {
1285         case 0:
1286         case -ERESTARTSYS:
1287                 return VM_FAULT_NOPAGE;
1288         case -ENOMEM:
1289         case -EAGAIN:
1290                 return VM_FAULT_OOM;
1291         default:
1292                 return VM_FAULT_SIGBUS;
1293         }
1294 }
1295
1296 /**
1297  * i915_gem_create_mmap_offset - create a fake mmap offset for an object
1298  * @obj: obj in question
1299  *
1300  * GEM memory mapping works by handing back to userspace a fake mmap offset
1301  * it can use in a subsequent mmap(2) call.  The DRM core code then looks
1302  * up the object based on the offset and sets up the various memory mapping
1303  * structures.
1304  *
1305  * This routine allocates and attaches a fake offset for @obj.
1306  */
1307 static int
1308 i915_gem_create_mmap_offset(struct drm_gem_object *obj)
1309 {
1310         struct drm_device *dev = obj->dev;
1311         struct drm_gem_mm *mm = dev->mm_private;
1312         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
1313         struct drm_map_list *list;
1314         struct drm_local_map *map;
1315         int ret = 0;
1316
1317         /* Set the object up for mmap'ing */
1318         list = &obj->map_list;
1319         list->map = kzalloc(sizeof(struct drm_map_list), GFP_KERNEL);
1320         if (!list->map)
1321                 return -ENOMEM;
1322
1323         map = list->map;
1324         map->type = _DRM_GEM;
1325         map->size = obj->size;
1326         map->handle = obj;
1327
1328         /* Get a DRM GEM mmap offset allocated... */
1329         list->file_offset_node = drm_mm_search_free(&mm->offset_manager,
1330                                                     obj->size / PAGE_SIZE, 0, 0);
1331         if (!list->file_offset_node) {
1332                 DRM_ERROR("failed to allocate offset for bo %d\n", obj->name);
1333                 ret = -ENOSPC;
1334                 goto out_free_list;
1335         }
1336
1337         list->file_offset_node = drm_mm_get_block(list->file_offset_node,
1338                                                   obj->size / PAGE_SIZE, 0);
1339         if (!list->file_offset_node) {
1340                 ret = -ENOMEM;
1341                 goto out_free_list;
1342         }
1343
1344         list->hash.key = list->file_offset_node->start;
1345         ret = drm_ht_insert_item(&mm->offset_hash, &list->hash);
1346         if (ret) {
1347                 DRM_ERROR("failed to add to map hash\n");
1348                 goto out_free_mm;
1349         }
1350
1351         /* By now we should be all set, any drm_mmap request on the offset
1352          * below will get to our mmap & fault handler */
1353         obj_priv->mmap_offset = ((uint64_t) list->hash.key) << PAGE_SHIFT;
1354
1355         return 0;
1356
1357 out_free_mm:
1358         drm_mm_put_block(list->file_offset_node);
1359 out_free_list:
1360         kfree(list->map);
1361
1362         return ret;
1363 }
1364
1365 /**
1366  * i915_gem_release_mmap - remove physical page mappings
1367  * @obj: obj in question
1368  *
1369  * Preserve the reservation of the mmapping with the DRM core code, but
1370  * relinquish ownership of the pages back to the system.
1371  *
1372  * It is vital that we remove the page mapping if we have mapped a tiled
1373  * object through the GTT and then lose the fence register due to
1374  * resource pressure. Similarly if the object has been moved out of the
1375  * aperture, than pages mapped into userspace must be revoked. Removing the
1376  * mapping will then trigger a page fault on the next user access, allowing
1377  * fixup by i915_gem_fault().
1378  */
1379 void
1380 i915_gem_release_mmap(struct drm_gem_object *obj)
1381 {
1382         struct drm_device *dev = obj->dev;
1383         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
1384
1385         if (dev->dev_mapping)
1386                 unmap_mapping_range(dev->dev_mapping,
1387                                     obj_priv->mmap_offset, obj->size, 1);
1388 }
1389
1390 static void
1391 i915_gem_free_mmap_offset(struct drm_gem_object *obj)
1392 {
1393         struct drm_device *dev = obj->dev;
1394         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
1395         struct drm_gem_mm *mm = dev->mm_private;
1396         struct drm_map_list *list;
1397
1398         list = &obj->map_list;
1399         drm_ht_remove_item(&mm->offset_hash, &list->hash);
1400
1401         if (list->file_offset_node) {
1402                 drm_mm_put_block(list->file_offset_node);
1403                 list->file_offset_node = NULL;
1404         }
1405
1406         if (list->map) {
1407                 kfree(list->map);
1408                 list->map = NULL;
1409         }
1410
1411         obj_priv->mmap_offset = 0;
1412 }
1413
1414 /**
1415  * i915_gem_get_gtt_alignment - return required GTT alignment for an object
1416  * @obj: object to check
1417  *
1418  * Return the required GTT alignment for an object, taking into account
1419  * potential fence register mapping if needed.
1420  */
1421 static uint32_t
1422 i915_gem_get_gtt_alignment(struct drm_gem_object *obj)
1423 {
1424         struct drm_device *dev = obj->dev;
1425         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
1426         int start, i;
1427
1428         /*
1429          * Minimum alignment is 4k (GTT page size), but might be greater
1430          * if a fence register is needed for the object.
1431          */
1432         if (INTEL_INFO(dev)->gen >= 4 || obj_priv->tiling_mode == I915_TILING_NONE)
1433                 return 4096;
1434
1435         /*
1436          * Previous chips need to be aligned to the size of the smallest
1437          * fence register that can contain the object.
1438          */
1439         if (INTEL_INFO(dev)->gen == 3)
1440                 start = 1024*1024;
1441         else
1442                 start = 512*1024;
1443
1444         for (i = start; i < obj->size; i <<= 1)
1445                 ;
1446
1447         return i;
1448 }
1449
1450 /**
1451  * i915_gem_mmap_gtt_ioctl - prepare an object for GTT mmap'ing
1452  * @dev: DRM device
1453  * @data: GTT mapping ioctl data
1454  * @file_priv: GEM object info
1455  *
1456  * Simply returns the fake offset to userspace so it can mmap it.
1457  * The mmap call will end up in drm_gem_mmap(), which will set things
1458  * up so we can get faults in the handler above.
1459  *
1460  * The fault handler will take care of binding the object into the GTT
1461  * (since it may have been evicted to make room for something), allocating
1462  * a fence register, and mapping the appropriate aperture address into
1463  * userspace.
1464  */
1465 int
1466 i915_gem_mmap_gtt_ioctl(struct drm_device *dev, void *data,
1467                         struct drm_file *file_priv)
1468 {
1469         struct drm_i915_gem_mmap_gtt *args = data;
1470         struct drm_gem_object *obj;
1471         struct drm_i915_gem_object *obj_priv;
1472         int ret;
1473
1474         if (!(dev->driver->driver_features & DRIVER_GEM))
1475                 return -ENODEV;
1476
1477         ret = i915_mutex_lock_interruptible(dev);
1478         if (ret)
1479                 return ret;
1480
1481         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
1482         if (obj == NULL) {
1483                 ret = -ENOENT;
1484                 goto unlock;
1485         }
1486         obj_priv = to_intel_bo(obj);
1487
1488         if (obj_priv->madv != I915_MADV_WILLNEED) {
1489                 DRM_ERROR("Attempting to mmap a purgeable buffer\n");
1490                 ret = -EINVAL;
1491                 goto out;
1492         }
1493
1494         if (!obj_priv->mmap_offset) {
1495                 ret = i915_gem_create_mmap_offset(obj);
1496                 if (ret)
1497                         goto out;
1498         }
1499
1500         args->offset = obj_priv->mmap_offset;
1501
1502         /*
1503          * Pull it into the GTT so that we have a page list (makes the
1504          * initial fault faster and any subsequent flushing possible).
1505          */
1506         if (!obj_priv->agp_mem) {
1507                 ret = i915_gem_object_bind_to_gtt(obj, 0);
1508                 if (ret)
1509                         goto out;
1510         }
1511
1512 out:
1513         drm_gem_object_unreference(obj);
1514 unlock:
1515         mutex_unlock(&dev->struct_mutex);
1516         return ret;
1517 }
1518
1519 static void
1520 i915_gem_object_put_pages(struct drm_gem_object *obj)
1521 {
1522         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
1523         int page_count = obj->size / PAGE_SIZE;
1524         int i;
1525
1526         BUG_ON(obj_priv->pages_refcount == 0);
1527         BUG_ON(obj_priv->madv == __I915_MADV_PURGED);
1528
1529         if (--obj_priv->pages_refcount != 0)
1530                 return;
1531
1532         if (obj_priv->tiling_mode != I915_TILING_NONE)
1533                 i915_gem_object_save_bit_17_swizzle(obj);
1534
1535         if (obj_priv->madv == I915_MADV_DONTNEED)
1536                 obj_priv->dirty = 0;
1537
1538         for (i = 0; i < page_count; i++) {
1539                 if (obj_priv->dirty)
1540                         set_page_dirty(obj_priv->pages[i]);
1541
1542                 if (obj_priv->madv == I915_MADV_WILLNEED)
1543                         mark_page_accessed(obj_priv->pages[i]);
1544
1545                 page_cache_release(obj_priv->pages[i]);
1546         }
1547         obj_priv->dirty = 0;
1548
1549         drm_free_large(obj_priv->pages);
1550         obj_priv->pages = NULL;
1551 }
1552
1553 static uint32_t
1554 i915_gem_next_request_seqno(struct drm_device *dev,
1555                             struct intel_ring_buffer *ring)
1556 {
1557         drm_i915_private_t *dev_priv = dev->dev_private;
1558
1559         ring->outstanding_lazy_request = true;
1560         return dev_priv->next_seqno;
1561 }
1562
1563 static void
1564 i915_gem_object_move_to_active(struct drm_gem_object *obj,
1565                                struct intel_ring_buffer *ring)
1566 {
1567         struct drm_device *dev = obj->dev;
1568         struct drm_i915_private *dev_priv = dev->dev_private;
1569         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
1570         uint32_t seqno = i915_gem_next_request_seqno(dev, ring);
1571
1572         BUG_ON(ring == NULL);
1573         obj_priv->ring = ring;
1574
1575         /* Add a reference if we're newly entering the active list. */
1576         if (!obj_priv->active) {
1577                 drm_gem_object_reference(obj);
1578                 obj_priv->active = 1;
1579         }
1580
1581         /* Move from whatever list we were on to the tail of execution. */
1582         list_move_tail(&obj_priv->mm_list, &dev_priv->mm.active_list);
1583         list_move_tail(&obj_priv->ring_list, &ring->active_list);
1584         obj_priv->last_rendering_seqno = seqno;
1585 }
1586
1587 static void
1588 i915_gem_object_move_to_flushing(struct drm_gem_object *obj)
1589 {
1590         struct drm_device *dev = obj->dev;
1591         drm_i915_private_t *dev_priv = dev->dev_private;
1592         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
1593
1594         BUG_ON(!obj_priv->active);
1595         list_move_tail(&obj_priv->mm_list, &dev_priv->mm.flushing_list);
1596         list_del_init(&obj_priv->ring_list);
1597         obj_priv->last_rendering_seqno = 0;
1598 }
1599
1600 /* Immediately discard the backing storage */
1601 static void
1602 i915_gem_object_truncate(struct drm_gem_object *obj)
1603 {
1604         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
1605         struct inode *inode;
1606
1607         /* Our goal here is to return as much of the memory as
1608          * is possible back to the system as we are called from OOM.
1609          * To do this we must instruct the shmfs to drop all of its
1610          * backing pages, *now*. Here we mirror the actions taken
1611          * when by shmem_delete_inode() to release the backing store.
1612          */
1613         inode = obj->filp->f_path.dentry->d_inode;
1614         truncate_inode_pages(inode->i_mapping, 0);
1615         if (inode->i_op->truncate_range)
1616                 inode->i_op->truncate_range(inode, 0, (loff_t)-1);
1617
1618         obj_priv->madv = __I915_MADV_PURGED;
1619 }
1620
1621 static inline int
1622 i915_gem_object_is_purgeable(struct drm_i915_gem_object *obj_priv)
1623 {
1624         return obj_priv->madv == I915_MADV_DONTNEED;
1625 }
1626
1627 static void
1628 i915_gem_object_move_to_inactive(struct drm_gem_object *obj)
1629 {
1630         struct drm_device *dev = obj->dev;
1631         drm_i915_private_t *dev_priv = dev->dev_private;
1632         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
1633
1634         if (obj_priv->pin_count != 0)
1635                 list_move_tail(&obj_priv->mm_list, &dev_priv->mm.pinned_list);
1636         else
1637                 list_move_tail(&obj_priv->mm_list, &dev_priv->mm.inactive_list);
1638         list_del_init(&obj_priv->ring_list);
1639
1640         BUG_ON(!list_empty(&obj_priv->gpu_write_list));
1641
1642         obj_priv->last_rendering_seqno = 0;
1643         obj_priv->ring = NULL;
1644         if (obj_priv->active) {
1645                 obj_priv->active = 0;
1646                 drm_gem_object_unreference(obj);
1647         }
1648         WARN_ON(i915_verify_lists(dev));
1649 }
1650
1651 static void
1652 i915_gem_process_flushing_list(struct drm_device *dev,
1653                                uint32_t flush_domains,
1654                                struct intel_ring_buffer *ring)
1655 {
1656         drm_i915_private_t *dev_priv = dev->dev_private;
1657         struct drm_i915_gem_object *obj_priv, *next;
1658
1659         list_for_each_entry_safe(obj_priv, next,
1660                                  &ring->gpu_write_list,
1661                                  gpu_write_list) {
1662                 struct drm_gem_object *obj = &obj_priv->base;
1663
1664                 if (obj->write_domain & flush_domains) {
1665                         uint32_t old_write_domain = obj->write_domain;
1666
1667                         obj->write_domain = 0;
1668                         list_del_init(&obj_priv->gpu_write_list);
1669                         i915_gem_object_move_to_active(obj, ring);
1670
1671                         /* update the fence lru list */
1672                         if (obj_priv->fence_reg != I915_FENCE_REG_NONE) {
1673                                 struct drm_i915_fence_reg *reg =
1674                                         &dev_priv->fence_regs[obj_priv->fence_reg];
1675                                 list_move_tail(&reg->lru_list,
1676                                                 &dev_priv->mm.fence_list);
1677                         }
1678
1679                         trace_i915_gem_object_change_domain(obj,
1680                                                             obj->read_domains,
1681                                                             old_write_domain);
1682                 }
1683         }
1684 }
1685
1686 uint32_t
1687 i915_add_request(struct drm_device *dev,
1688                  struct drm_file *file,
1689                  struct drm_i915_gem_request *request,
1690                  struct intel_ring_buffer *ring)
1691 {
1692         drm_i915_private_t *dev_priv = dev->dev_private;
1693         struct drm_i915_file_private *file_priv = NULL;
1694         uint32_t seqno;
1695         int was_empty;
1696
1697         if (file != NULL)
1698                 file_priv = file->driver_priv;
1699
1700         if (request == NULL) {
1701                 request = kzalloc(sizeof(*request), GFP_KERNEL);
1702                 if (request == NULL)
1703                         return 0;
1704         }
1705
1706         seqno = ring->add_request(dev, ring, 0);
1707         ring->outstanding_lazy_request = false;
1708
1709         request->seqno = seqno;
1710         request->ring = ring;
1711         request->emitted_jiffies = jiffies;
1712         was_empty = list_empty(&ring->request_list);
1713         list_add_tail(&request->list, &ring->request_list);
1714
1715         if (file_priv) {
1716                 spin_lock(&file_priv->mm.lock);
1717                 request->file_priv = file_priv;
1718                 list_add_tail(&request->client_list,
1719                               &file_priv->mm.request_list);
1720                 spin_unlock(&file_priv->mm.lock);
1721         }
1722
1723         if (!dev_priv->mm.suspended) {
1724                 mod_timer(&dev_priv->hangcheck_timer,
1725                           jiffies + msecs_to_jiffies(DRM_I915_HANGCHECK_PERIOD));
1726                 if (was_empty)
1727                         queue_delayed_work(dev_priv->wq,
1728                                            &dev_priv->mm.retire_work, HZ);
1729         }
1730         return seqno;
1731 }
1732
1733 /**
1734  * Command execution barrier
1735  *
1736  * Ensures that all commands in the ring are finished
1737  * before signalling the CPU
1738  */
1739 static void
1740 i915_retire_commands(struct drm_device *dev, struct intel_ring_buffer *ring)
1741 {
1742         uint32_t flush_domains = 0;
1743
1744         /* The sampler always gets flushed on i965 (sigh) */
1745         if (INTEL_INFO(dev)->gen >= 4)
1746                 flush_domains |= I915_GEM_DOMAIN_SAMPLER;
1747
1748         ring->flush(dev, ring,
1749                         I915_GEM_DOMAIN_COMMAND, flush_domains);
1750 }
1751
1752 static inline void
1753 i915_gem_request_remove_from_client(struct drm_i915_gem_request *request)
1754 {
1755         struct drm_i915_file_private *file_priv = request->file_priv;
1756
1757         if (!file_priv)
1758                 return;
1759
1760         spin_lock(&file_priv->mm.lock);
1761         list_del(&request->client_list);
1762         request->file_priv = NULL;
1763         spin_unlock(&file_priv->mm.lock);
1764 }
1765
1766 static void i915_gem_reset_ring_lists(struct drm_i915_private *dev_priv,
1767                                       struct intel_ring_buffer *ring)
1768 {
1769         while (!list_empty(&ring->request_list)) {
1770                 struct drm_i915_gem_request *request;
1771
1772                 request = list_first_entry(&ring->request_list,
1773                                            struct drm_i915_gem_request,
1774                                            list);
1775
1776                 list_del(&request->list);
1777                 i915_gem_request_remove_from_client(request);
1778                 kfree(request);
1779         }
1780
1781         while (!list_empty(&ring->active_list)) {
1782                 struct drm_i915_gem_object *obj_priv;
1783
1784                 obj_priv = list_first_entry(&ring->active_list,
1785                                             struct drm_i915_gem_object,
1786                                             ring_list);
1787
1788                 obj_priv->base.write_domain = 0;
1789                 list_del_init(&obj_priv->gpu_write_list);
1790                 i915_gem_object_move_to_inactive(&obj_priv->base);
1791         }
1792 }
1793
1794 void i915_gem_reset(struct drm_device *dev)
1795 {
1796         struct drm_i915_private *dev_priv = dev->dev_private;
1797         struct drm_i915_gem_object *obj_priv;
1798         int i;
1799
1800         i915_gem_reset_ring_lists(dev_priv, &dev_priv->render_ring);
1801         i915_gem_reset_ring_lists(dev_priv, &dev_priv->bsd_ring);
1802         i915_gem_reset_ring_lists(dev_priv, &dev_priv->blt_ring);
1803
1804         /* Remove anything from the flushing lists. The GPU cache is likely
1805          * to be lost on reset along with the data, so simply move the
1806          * lost bo to the inactive list.
1807          */
1808         while (!list_empty(&dev_priv->mm.flushing_list)) {
1809                 obj_priv = list_first_entry(&dev_priv->mm.flushing_list,
1810                                             struct drm_i915_gem_object,
1811                                             mm_list);
1812
1813                 obj_priv->base.write_domain = 0;
1814                 list_del_init(&obj_priv->gpu_write_list);
1815                 i915_gem_object_move_to_inactive(&obj_priv->base);
1816         }
1817
1818         /* Move everything out of the GPU domains to ensure we do any
1819          * necessary invalidation upon reuse.
1820          */
1821         list_for_each_entry(obj_priv,
1822                             &dev_priv->mm.inactive_list,
1823                             mm_list)
1824         {
1825                 obj_priv->base.read_domains &= ~I915_GEM_GPU_DOMAINS;
1826         }
1827
1828         /* The fence registers are invalidated so clear them out */
1829         for (i = 0; i < 16; i++) {
1830                 struct drm_i915_fence_reg *reg;
1831
1832                 reg = &dev_priv->fence_regs[i];
1833                 if (!reg->obj)
1834                         continue;
1835
1836                 i915_gem_clear_fence_reg(reg->obj);
1837         }
1838 }
1839
1840 /**
1841  * This function clears the request list as sequence numbers are passed.
1842  */
1843 static void
1844 i915_gem_retire_requests_ring(struct drm_device *dev,
1845                               struct intel_ring_buffer *ring)
1846 {
1847         drm_i915_private_t *dev_priv = dev->dev_private;
1848         uint32_t seqno;
1849
1850         if (!ring->status_page.page_addr ||
1851             list_empty(&ring->request_list))
1852                 return;
1853
1854         WARN_ON(i915_verify_lists(dev));
1855
1856         seqno = ring->get_seqno(dev, ring);
1857         while (!list_empty(&ring->request_list)) {
1858                 struct drm_i915_gem_request *request;
1859
1860                 request = list_first_entry(&ring->request_list,
1861                                            struct drm_i915_gem_request,
1862                                            list);
1863
1864                 if (!i915_seqno_passed(seqno, request->seqno))
1865                         break;
1866
1867                 trace_i915_gem_request_retire(dev, request->seqno);
1868
1869                 list_del(&request->list);
1870                 i915_gem_request_remove_from_client(request);
1871                 kfree(request);
1872         }
1873
1874         /* Move any buffers on the active list that are no longer referenced
1875          * by the ringbuffer to the flushing/inactive lists as appropriate.
1876          */
1877         while (!list_empty(&ring->active_list)) {
1878                 struct drm_gem_object *obj;
1879                 struct drm_i915_gem_object *obj_priv;
1880
1881                 obj_priv = list_first_entry(&ring->active_list,
1882                                             struct drm_i915_gem_object,
1883                                             ring_list);
1884
1885                 if (!i915_seqno_passed(seqno, obj_priv->last_rendering_seqno))
1886                         break;
1887
1888                 obj = &obj_priv->base;
1889                 if (obj->write_domain != 0)
1890                         i915_gem_object_move_to_flushing(obj);
1891                 else
1892                         i915_gem_object_move_to_inactive(obj);
1893         }
1894
1895         if (unlikely (dev_priv->trace_irq_seqno &&
1896                       i915_seqno_passed(dev_priv->trace_irq_seqno, seqno))) {
1897                 ring->user_irq_put(dev, ring);
1898                 dev_priv->trace_irq_seqno = 0;
1899         }
1900
1901         WARN_ON(i915_verify_lists(dev));
1902 }
1903
1904 void
1905 i915_gem_retire_requests(struct drm_device *dev)
1906 {
1907         drm_i915_private_t *dev_priv = dev->dev_private;
1908
1909         if (!list_empty(&dev_priv->mm.deferred_free_list)) {
1910             struct drm_i915_gem_object *obj_priv, *tmp;
1911
1912             /* We must be careful that during unbind() we do not
1913              * accidentally infinitely recurse into retire requests.
1914              * Currently:
1915              *   retire -> free -> unbind -> wait -> retire_ring
1916              */
1917             list_for_each_entry_safe(obj_priv, tmp,
1918                                      &dev_priv->mm.deferred_free_list,
1919                                      mm_list)
1920                     i915_gem_free_object_tail(&obj_priv->base);
1921         }
1922
1923         i915_gem_retire_requests_ring(dev, &dev_priv->render_ring);
1924         i915_gem_retire_requests_ring(dev, &dev_priv->bsd_ring);
1925         i915_gem_retire_requests_ring(dev, &dev_priv->blt_ring);
1926 }
1927
1928 static void
1929 i915_gem_retire_work_handler(struct work_struct *work)
1930 {
1931         drm_i915_private_t *dev_priv;
1932         struct drm_device *dev;
1933
1934         dev_priv = container_of(work, drm_i915_private_t,
1935                                 mm.retire_work.work);
1936         dev = dev_priv->dev;
1937
1938         /* Come back later if the device is busy... */
1939         if (!mutex_trylock(&dev->struct_mutex)) {
1940                 queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work, HZ);
1941                 return;
1942         }
1943
1944         i915_gem_retire_requests(dev);
1945
1946         if (!dev_priv->mm.suspended &&
1947                 (!list_empty(&dev_priv->render_ring.request_list) ||
1948                  !list_empty(&dev_priv->bsd_ring.request_list) ||
1949                  !list_empty(&dev_priv->blt_ring.request_list)))
1950                 queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work, HZ);
1951         mutex_unlock(&dev->struct_mutex);
1952 }
1953
1954 int
1955 i915_do_wait_request(struct drm_device *dev, uint32_t seqno,
1956                      bool interruptible, struct intel_ring_buffer *ring)
1957 {
1958         drm_i915_private_t *dev_priv = dev->dev_private;
1959         u32 ier;
1960         int ret = 0;
1961
1962         BUG_ON(seqno == 0);
1963
1964         if (atomic_read(&dev_priv->mm.wedged))
1965                 return -EAGAIN;
1966
1967         if (ring->outstanding_lazy_request) {
1968                 seqno = i915_add_request(dev, NULL, NULL, ring);
1969                 if (seqno == 0)
1970                         return -ENOMEM;
1971         }
1972         BUG_ON(seqno == dev_priv->next_seqno);
1973
1974         if (!i915_seqno_passed(ring->get_seqno(dev, ring), seqno)) {
1975                 if (HAS_PCH_SPLIT(dev))
1976                         ier = I915_READ(DEIER) | I915_READ(GTIER);
1977                 else
1978                         ier = I915_READ(IER);
1979                 if (!ier) {
1980                         DRM_ERROR("something (likely vbetool) disabled "
1981                                   "interrupts, re-enabling\n");
1982                         i915_driver_irq_preinstall(dev);
1983                         i915_driver_irq_postinstall(dev);
1984                 }
1985
1986                 trace_i915_gem_request_wait_begin(dev, seqno);
1987
1988                 ring->waiting_gem_seqno = seqno;
1989                 ring->user_irq_get(dev, ring);
1990                 if (interruptible)
1991                         ret = wait_event_interruptible(ring->irq_queue,
1992                                 i915_seqno_passed(
1993                                         ring->get_seqno(dev, ring), seqno)
1994                                 || atomic_read(&dev_priv->mm.wedged));
1995                 else
1996                         wait_event(ring->irq_queue,
1997                                 i915_seqno_passed(
1998                                         ring->get_seqno(dev, ring), seqno)
1999                                 || atomic_read(&dev_priv->mm.wedged));
2000
2001                 ring->user_irq_put(dev, ring);
2002                 ring->waiting_gem_seqno = 0;
2003
2004                 trace_i915_gem_request_wait_end(dev, seqno);
2005         }
2006         if (atomic_read(&dev_priv->mm.wedged))
2007                 ret = -EAGAIN;
2008
2009         if (ret && ret != -ERESTARTSYS)
2010                 DRM_ERROR("%s returns %d (awaiting %d at %d, next %d)\n",
2011                           __func__, ret, seqno, ring->get_seqno(dev, ring),
2012                           dev_priv->next_seqno);
2013
2014         /* Directly dispatch request retiring.  While we have the work queue
2015          * to handle this, the waiter on a request often wants an associated
2016          * buffer to have made it to the inactive list, and we would need
2017          * a separate wait queue to handle that.
2018          */
2019         if (ret == 0)
2020                 i915_gem_retire_requests_ring(dev, ring);
2021
2022         return ret;
2023 }
2024
2025 /**
2026  * Waits for a sequence number to be signaled, and cleans up the
2027  * request and object lists appropriately for that event.
2028  */
2029 static int
2030 i915_wait_request(struct drm_device *dev, uint32_t seqno,
2031                   struct intel_ring_buffer *ring)
2032 {
2033         return i915_do_wait_request(dev, seqno, 1, ring);
2034 }
2035
2036 static void
2037 i915_gem_flush_ring(struct drm_device *dev,
2038                     struct drm_file *file_priv,
2039                     struct intel_ring_buffer *ring,
2040                     uint32_t invalidate_domains,
2041                     uint32_t flush_domains)
2042 {
2043         ring->flush(dev, ring, invalidate_domains, flush_domains);
2044         i915_gem_process_flushing_list(dev, flush_domains, ring);
2045 }
2046
2047 static void
2048 i915_gem_flush(struct drm_device *dev,
2049                struct drm_file *file_priv,
2050                uint32_t invalidate_domains,
2051                uint32_t flush_domains,
2052                uint32_t flush_rings)
2053 {
2054         drm_i915_private_t *dev_priv = dev->dev_private;
2055
2056         if (flush_domains & I915_GEM_DOMAIN_CPU)
2057                 drm_agp_chipset_flush(dev);
2058
2059         if ((flush_domains | invalidate_domains) & I915_GEM_GPU_DOMAINS) {
2060                 if (flush_rings & RING_RENDER)
2061                         i915_gem_flush_ring(dev, file_priv,
2062                                             &dev_priv->render_ring,
2063                                             invalidate_domains, flush_domains);
2064                 if (flush_rings & RING_BSD)
2065                         i915_gem_flush_ring(dev, file_priv,
2066                                             &dev_priv->bsd_ring,
2067                                             invalidate_domains, flush_domains);
2068                 if (flush_rings & RING_BLT)
2069                         i915_gem_flush_ring(dev, file_priv,
2070                                             &dev_priv->blt_ring,
2071                                             invalidate_domains, flush_domains);
2072         }
2073 }
2074
2075 /**
2076  * Ensures that all rendering to the object has completed and the object is
2077  * safe to unbind from the GTT or access from the CPU.
2078  */
2079 static int
2080 i915_gem_object_wait_rendering(struct drm_gem_object *obj,
2081                                bool interruptible)
2082 {
2083         struct drm_device *dev = obj->dev;
2084         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2085         int ret;
2086
2087         /* This function only exists to support waiting for existing rendering,
2088          * not for emitting required flushes.
2089          */
2090         BUG_ON((obj->write_domain & I915_GEM_GPU_DOMAINS) != 0);
2091
2092         /* If there is rendering queued on the buffer being evicted, wait for
2093          * it.
2094          */
2095         if (obj_priv->active) {
2096                 ret = i915_do_wait_request(dev,
2097                                            obj_priv->last_rendering_seqno,
2098                                            interruptible,
2099                                            obj_priv->ring);
2100                 if (ret)
2101                         return ret;
2102         }
2103
2104         return 0;
2105 }
2106
2107 /**
2108  * Unbinds an object from the GTT aperture.
2109  */
2110 int
2111 i915_gem_object_unbind(struct drm_gem_object *obj)
2112 {
2113         struct drm_device *dev = obj->dev;
2114         struct drm_i915_private *dev_priv = dev->dev_private;
2115         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2116         int ret = 0;
2117
2118         if (obj_priv->gtt_space == NULL)
2119                 return 0;
2120
2121         if (obj_priv->pin_count != 0) {
2122                 DRM_ERROR("Attempting to unbind pinned buffer\n");
2123                 return -EINVAL;
2124         }
2125
2126         /* blow away mappings if mapped through GTT */
2127         i915_gem_release_mmap(obj);
2128
2129         /* Move the object to the CPU domain to ensure that
2130          * any possible CPU writes while it's not in the GTT
2131          * are flushed when we go to remap it. This will
2132          * also ensure that all pending GPU writes are finished
2133          * before we unbind.
2134          */
2135         ret = i915_gem_object_set_to_cpu_domain(obj, 1);
2136         if (ret == -ERESTARTSYS)
2137                 return ret;
2138         /* Continue on if we fail due to EIO, the GPU is hung so we
2139          * should be safe and we need to cleanup or else we might
2140          * cause memory corruption through use-after-free.
2141          */
2142         if (ret) {
2143                 i915_gem_clflush_object(obj);
2144                 obj->read_domains = obj->write_domain = I915_GEM_DOMAIN_CPU;
2145         }
2146
2147         /* release the fence reg _after_ flushing */
2148         if (obj_priv->fence_reg != I915_FENCE_REG_NONE)
2149                 i915_gem_clear_fence_reg(obj);
2150
2151         drm_unbind_agp(obj_priv->agp_mem);
2152         drm_free_agp(obj_priv->agp_mem, obj->size / PAGE_SIZE);
2153
2154         i915_gem_object_put_pages(obj);
2155         BUG_ON(obj_priv->pages_refcount);
2156
2157         i915_gem_info_remove_gtt(dev_priv, obj->size);
2158         list_del_init(&obj_priv->mm_list);
2159
2160         drm_mm_put_block(obj_priv->gtt_space);
2161         obj_priv->gtt_space = NULL;
2162         obj_priv->gtt_offset = 0;
2163
2164         if (i915_gem_object_is_purgeable(obj_priv))
2165                 i915_gem_object_truncate(obj);
2166
2167         trace_i915_gem_object_unbind(obj);
2168
2169         return ret;
2170 }
2171
2172 static int i915_ring_idle(struct drm_device *dev,
2173                           struct intel_ring_buffer *ring)
2174 {
2175         if (list_empty(&ring->gpu_write_list) && list_empty(&ring->active_list))
2176                 return 0;
2177
2178         i915_gem_flush_ring(dev, NULL, ring,
2179                             I915_GEM_GPU_DOMAINS, I915_GEM_GPU_DOMAINS);
2180         return i915_wait_request(dev,
2181                                  i915_gem_next_request_seqno(dev, ring),
2182                                  ring);
2183 }
2184
2185 int
2186 i915_gpu_idle(struct drm_device *dev)
2187 {
2188         drm_i915_private_t *dev_priv = dev->dev_private;
2189         bool lists_empty;
2190         int ret;
2191
2192         lists_empty = (list_empty(&dev_priv->mm.flushing_list) &&
2193                        list_empty(&dev_priv->mm.active_list));
2194         if (lists_empty)
2195                 return 0;
2196
2197         /* Flush everything onto the inactive list. */
2198         ret = i915_ring_idle(dev, &dev_priv->render_ring);
2199         if (ret)
2200                 return ret;
2201
2202         ret = i915_ring_idle(dev, &dev_priv->bsd_ring);
2203         if (ret)
2204                 return ret;
2205
2206         ret = i915_ring_idle(dev, &dev_priv->blt_ring);
2207         if (ret)
2208                 return ret;
2209
2210         return 0;
2211 }
2212
2213 static int
2214 i915_gem_object_get_pages(struct drm_gem_object *obj,
2215                           gfp_t gfpmask)
2216 {
2217         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2218         int page_count, i;
2219         struct address_space *mapping;
2220         struct inode *inode;
2221         struct page *page;
2222
2223         BUG_ON(obj_priv->pages_refcount
2224                         == DRM_I915_GEM_OBJECT_MAX_PAGES_REFCOUNT);
2225
2226         if (obj_priv->pages_refcount++ != 0)
2227                 return 0;
2228
2229         /* Get the list of pages out of our struct file.  They'll be pinned
2230          * at this point until we release them.
2231          */
2232         page_count = obj->size / PAGE_SIZE;
2233         BUG_ON(obj_priv->pages != NULL);
2234         obj_priv->pages = drm_calloc_large(page_count, sizeof(struct page *));
2235         if (obj_priv->pages == NULL) {
2236                 obj_priv->pages_refcount--;
2237                 return -ENOMEM;
2238         }
2239
2240         inode = obj->filp->f_path.dentry->d_inode;
2241         mapping = inode->i_mapping;
2242         for (i = 0; i < page_count; i++) {
2243                 page = read_cache_page_gfp(mapping, i,
2244                                            GFP_HIGHUSER |
2245                                            __GFP_COLD |
2246                                            __GFP_RECLAIMABLE |
2247                                            gfpmask);
2248                 if (IS_ERR(page))
2249                         goto err_pages;
2250
2251                 obj_priv->pages[i] = page;
2252         }
2253
2254         if (obj_priv->tiling_mode != I915_TILING_NONE)
2255                 i915_gem_object_do_bit_17_swizzle(obj);
2256
2257         return 0;
2258
2259 err_pages:
2260         while (i--)
2261                 page_cache_release(obj_priv->pages[i]);
2262
2263         drm_free_large(obj_priv->pages);
2264         obj_priv->pages = NULL;
2265         obj_priv->pages_refcount--;
2266         return PTR_ERR(page);
2267 }
2268
2269 static void sandybridge_write_fence_reg(struct drm_i915_fence_reg *reg)
2270 {
2271         struct drm_gem_object *obj = reg->obj;
2272         struct drm_device *dev = obj->dev;
2273         drm_i915_private_t *dev_priv = dev->dev_private;
2274         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2275         int regnum = obj_priv->fence_reg;
2276         uint64_t val;
2277
2278         val = (uint64_t)((obj_priv->gtt_offset + obj->size - 4096) &
2279                     0xfffff000) << 32;
2280         val |= obj_priv->gtt_offset & 0xfffff000;
2281         val |= (uint64_t)((obj_priv->stride / 128) - 1) <<
2282                 SANDYBRIDGE_FENCE_PITCH_SHIFT;
2283
2284         if (obj_priv->tiling_mode == I915_TILING_Y)
2285                 val |= 1 << I965_FENCE_TILING_Y_SHIFT;
2286         val |= I965_FENCE_REG_VALID;
2287
2288         I915_WRITE64(FENCE_REG_SANDYBRIDGE_0 + (regnum * 8), val);
2289 }
2290
2291 static void i965_write_fence_reg(struct drm_i915_fence_reg *reg)
2292 {
2293         struct drm_gem_object *obj = reg->obj;
2294         struct drm_device *dev = obj->dev;
2295         drm_i915_private_t *dev_priv = dev->dev_private;
2296         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2297         int regnum = obj_priv->fence_reg;
2298         uint64_t val;
2299
2300         val = (uint64_t)((obj_priv->gtt_offset + obj->size - 4096) &
2301                     0xfffff000) << 32;
2302         val |= obj_priv->gtt_offset & 0xfffff000;
2303         val |= ((obj_priv->stride / 128) - 1) << I965_FENCE_PITCH_SHIFT;
2304         if (obj_priv->tiling_mode == I915_TILING_Y)
2305                 val |= 1 << I965_FENCE_TILING_Y_SHIFT;
2306         val |= I965_FENCE_REG_VALID;
2307
2308         I915_WRITE64(FENCE_REG_965_0 + (regnum * 8), val);
2309 }
2310
2311 static void i915_write_fence_reg(struct drm_i915_fence_reg *reg)
2312 {
2313         struct drm_gem_object *obj = reg->obj;
2314         struct drm_device *dev = obj->dev;
2315         drm_i915_private_t *dev_priv = dev->dev_private;
2316         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2317         int regnum = obj_priv->fence_reg;
2318         int tile_width;
2319         uint32_t fence_reg, val;
2320         uint32_t pitch_val;
2321
2322         if ((obj_priv->gtt_offset & ~I915_FENCE_START_MASK) ||
2323             (obj_priv->gtt_offset & (obj->size - 1))) {
2324                 WARN(1, "%s: object 0x%08x not 1M or size (0x%zx) aligned\n",
2325                      __func__, obj_priv->gtt_offset, obj->size);
2326                 return;
2327         }
2328
2329         if (obj_priv->tiling_mode == I915_TILING_Y &&
2330             HAS_128_BYTE_Y_TILING(dev))
2331                 tile_width = 128;
2332         else
2333                 tile_width = 512;
2334
2335         /* Note: pitch better be a power of two tile widths */
2336         pitch_val = obj_priv->stride / tile_width;
2337         pitch_val = ffs(pitch_val) - 1;
2338
2339         if (obj_priv->tiling_mode == I915_TILING_Y &&
2340             HAS_128_BYTE_Y_TILING(dev))
2341                 WARN_ON(pitch_val > I830_FENCE_MAX_PITCH_VAL);
2342         else
2343                 WARN_ON(pitch_val > I915_FENCE_MAX_PITCH_VAL);
2344
2345         val = obj_priv->gtt_offset;
2346         if (obj_priv->tiling_mode == I915_TILING_Y)
2347                 val |= 1 << I830_FENCE_TILING_Y_SHIFT;
2348         val |= I915_FENCE_SIZE_BITS(obj->size);
2349         val |= pitch_val << I830_FENCE_PITCH_SHIFT;
2350         val |= I830_FENCE_REG_VALID;
2351
2352         if (regnum < 8)
2353                 fence_reg = FENCE_REG_830_0 + (regnum * 4);
2354         else
2355                 fence_reg = FENCE_REG_945_8 + ((regnum - 8) * 4);
2356         I915_WRITE(fence_reg, val);
2357 }
2358
2359 static void i830_write_fence_reg(struct drm_i915_fence_reg *reg)
2360 {
2361         struct drm_gem_object *obj = reg->obj;
2362         struct drm_device *dev = obj->dev;
2363         drm_i915_private_t *dev_priv = dev->dev_private;
2364         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2365         int regnum = obj_priv->fence_reg;
2366         uint32_t val;
2367         uint32_t pitch_val;
2368         uint32_t fence_size_bits;
2369
2370         if ((obj_priv->gtt_offset & ~I830_FENCE_START_MASK) ||
2371             (obj_priv->gtt_offset & (obj->size - 1))) {
2372                 WARN(1, "%s: object 0x%08x not 512K or size aligned\n",
2373                      __func__, obj_priv->gtt_offset);
2374                 return;
2375         }
2376
2377         pitch_val = obj_priv->stride / 128;
2378         pitch_val = ffs(pitch_val) - 1;
2379         WARN_ON(pitch_val > I830_FENCE_MAX_PITCH_VAL);
2380
2381         val = obj_priv->gtt_offset;
2382         if (obj_priv->tiling_mode == I915_TILING_Y)
2383                 val |= 1 << I830_FENCE_TILING_Y_SHIFT;
2384         fence_size_bits = I830_FENCE_SIZE_BITS(obj->size);
2385         WARN_ON(fence_size_bits & ~0x00000f00);
2386         val |= fence_size_bits;
2387         val |= pitch_val << I830_FENCE_PITCH_SHIFT;
2388         val |= I830_FENCE_REG_VALID;
2389
2390         I915_WRITE(FENCE_REG_830_0 + (regnum * 4), val);
2391 }
2392
2393 static int i915_find_fence_reg(struct drm_device *dev,
2394                                bool interruptible)
2395 {
2396         struct drm_i915_fence_reg *reg = NULL;
2397         struct drm_i915_gem_object *obj_priv = NULL;
2398         struct drm_i915_private *dev_priv = dev->dev_private;
2399         struct drm_gem_object *obj = NULL;
2400         int i, avail, ret;
2401
2402         /* First try to find a free reg */
2403         avail = 0;
2404         for (i = dev_priv->fence_reg_start; i < dev_priv->num_fence_regs; i++) {
2405                 reg = &dev_priv->fence_regs[i];
2406                 if (!reg->obj)
2407                         return i;
2408
2409                 obj_priv = to_intel_bo(reg->obj);
2410                 if (!obj_priv->pin_count)
2411                     avail++;
2412         }
2413
2414         if (avail == 0)
2415                 return -ENOSPC;
2416
2417         /* None available, try to steal one or wait for a user to finish */
2418         i = I915_FENCE_REG_NONE;
2419         list_for_each_entry(reg, &dev_priv->mm.fence_list,
2420                             lru_list) {
2421                 obj = reg->obj;
2422                 obj_priv = to_intel_bo(obj);
2423
2424                 if (obj_priv->pin_count)
2425                         continue;
2426
2427                 /* found one! */
2428                 i = obj_priv->fence_reg;
2429                 break;
2430         }
2431
2432         BUG_ON(i == I915_FENCE_REG_NONE);
2433
2434         /* We only have a reference on obj from the active list. put_fence_reg
2435          * might drop that one, causing a use-after-free in it. So hold a
2436          * private reference to obj like the other callers of put_fence_reg
2437          * (set_tiling ioctl) do. */
2438         drm_gem_object_reference(obj);
2439         ret = i915_gem_object_put_fence_reg(obj, interruptible);
2440         drm_gem_object_unreference(obj);
2441         if (ret != 0)
2442                 return ret;
2443
2444         return i;
2445 }
2446
2447 /**
2448  * i915_gem_object_get_fence_reg - set up a fence reg for an object
2449  * @obj: object to map through a fence reg
2450  *
2451  * When mapping objects through the GTT, userspace wants to be able to write
2452  * to them without having to worry about swizzling if the object is tiled.
2453  *
2454  * This function walks the fence regs looking for a free one for @obj,
2455  * stealing one if it can't find any.
2456  *
2457  * It then sets up the reg based on the object's properties: address, pitch
2458  * and tiling format.
2459  */
2460 int
2461 i915_gem_object_get_fence_reg(struct drm_gem_object *obj,
2462                               bool interruptible)
2463 {
2464         struct drm_device *dev = obj->dev;
2465         struct drm_i915_private *dev_priv = dev->dev_private;
2466         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2467         struct drm_i915_fence_reg *reg = NULL;
2468         int ret;
2469
2470         /* Just update our place in the LRU if our fence is getting used. */
2471         if (obj_priv->fence_reg != I915_FENCE_REG_NONE) {
2472                 reg = &dev_priv->fence_regs[obj_priv->fence_reg];
2473                 list_move_tail(&reg->lru_list, &dev_priv->mm.fence_list);
2474                 return 0;
2475         }
2476
2477         switch (obj_priv->tiling_mode) {
2478         case I915_TILING_NONE:
2479                 WARN(1, "allocating a fence for non-tiled object?\n");
2480                 break;
2481         case I915_TILING_X:
2482                 if (!obj_priv->stride)
2483                         return -EINVAL;
2484                 WARN((obj_priv->stride & (512 - 1)),
2485                      "object 0x%08x is X tiled but has non-512B pitch\n",
2486                      obj_priv->gtt_offset);
2487                 break;
2488         case I915_TILING_Y:
2489                 if (!obj_priv->stride)
2490                         return -EINVAL;
2491                 WARN((obj_priv->stride & (128 - 1)),
2492                      "object 0x%08x is Y tiled but has non-128B pitch\n",
2493                      obj_priv->gtt_offset);
2494                 break;
2495         }
2496
2497         ret = i915_find_fence_reg(dev, interruptible);
2498         if (ret < 0)
2499                 return ret;
2500
2501         obj_priv->fence_reg = ret;
2502         reg = &dev_priv->fence_regs[obj_priv->fence_reg];
2503         list_add_tail(&reg->lru_list, &dev_priv->mm.fence_list);
2504
2505         reg->obj = obj;
2506
2507         switch (INTEL_INFO(dev)->gen) {
2508         case 6:
2509                 sandybridge_write_fence_reg(reg);
2510                 break;
2511         case 5:
2512         case 4:
2513                 i965_write_fence_reg(reg);
2514                 break;
2515         case 3:
2516                 i915_write_fence_reg(reg);
2517                 break;
2518         case 2:
2519                 i830_write_fence_reg(reg);
2520                 break;
2521         }
2522
2523         trace_i915_gem_object_get_fence(obj, obj_priv->fence_reg,
2524                         obj_priv->tiling_mode);
2525
2526         return 0;
2527 }
2528
2529 /**
2530  * i915_gem_clear_fence_reg - clear out fence register info
2531  * @obj: object to clear
2532  *
2533  * Zeroes out the fence register itself and clears out the associated
2534  * data structures in dev_priv and obj_priv.
2535  */
2536 static void
2537 i915_gem_clear_fence_reg(struct drm_gem_object *obj)
2538 {
2539         struct drm_device *dev = obj->dev;
2540         drm_i915_private_t *dev_priv = dev->dev_private;
2541         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2542         struct drm_i915_fence_reg *reg =
2543                 &dev_priv->fence_regs[obj_priv->fence_reg];
2544         uint32_t fence_reg;
2545
2546         switch (INTEL_INFO(dev)->gen) {
2547         case 6:
2548                 I915_WRITE64(FENCE_REG_SANDYBRIDGE_0 +
2549                              (obj_priv->fence_reg * 8), 0);
2550                 break;
2551         case 5:
2552         case 4:
2553                 I915_WRITE64(FENCE_REG_965_0 + (obj_priv->fence_reg * 8), 0);
2554                 break;
2555         case 3:
2556                 if (obj_priv->fence_reg >= 8)
2557                         fence_reg = FENCE_REG_945_8 + (obj_priv->fence_reg - 8) * 4;
2558                 else
2559         case 2:
2560                         fence_reg = FENCE_REG_830_0 + obj_priv->fence_reg * 4;
2561
2562                 I915_WRITE(fence_reg, 0);
2563                 break;
2564         }
2565
2566         reg->obj = NULL;
2567         obj_priv->fence_reg = I915_FENCE_REG_NONE;
2568         list_del_init(&reg->lru_list);
2569 }
2570
2571 /**
2572  * i915_gem_object_put_fence_reg - waits on outstanding fenced access
2573  * to the buffer to finish, and then resets the fence register.
2574  * @obj: tiled object holding a fence register.
2575  * @bool: whether the wait upon the fence is interruptible
2576  *
2577  * Zeroes out the fence register itself and clears out the associated
2578  * data structures in dev_priv and obj_priv.
2579  */
2580 int
2581 i915_gem_object_put_fence_reg(struct drm_gem_object *obj,
2582                               bool interruptible)
2583 {
2584         struct drm_device *dev = obj->dev;
2585         struct drm_i915_private *dev_priv = dev->dev_private;
2586         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2587         struct drm_i915_fence_reg *reg;
2588
2589         if (obj_priv->fence_reg == I915_FENCE_REG_NONE)
2590                 return 0;
2591
2592         /* If we've changed tiling, GTT-mappings of the object
2593          * need to re-fault to ensure that the correct fence register
2594          * setup is in place.
2595          */
2596         i915_gem_release_mmap(obj);
2597
2598         /* On the i915, GPU access to tiled buffers is via a fence,
2599          * therefore we must wait for any outstanding access to complete
2600          * before clearing the fence.
2601          */
2602         reg = &dev_priv->fence_regs[obj_priv->fence_reg];
2603         if (reg->gpu) {
2604                 int ret;
2605
2606                 ret = i915_gem_object_flush_gpu_write_domain(obj, true);
2607                 if (ret)
2608                         return ret;
2609
2610                 ret = i915_gem_object_wait_rendering(obj, interruptible);
2611                 if (ret)
2612                         return ret;
2613
2614                 reg->gpu = false;
2615         }
2616
2617         i915_gem_object_flush_gtt_write_domain(obj);
2618         i915_gem_clear_fence_reg(obj);
2619
2620         return 0;
2621 }
2622
2623 /**
2624  * Finds free space in the GTT aperture and binds the object there.
2625  */
2626 static int
2627 i915_gem_object_bind_to_gtt(struct drm_gem_object *obj, unsigned alignment)
2628 {
2629         struct drm_device *dev = obj->dev;
2630         drm_i915_private_t *dev_priv = dev->dev_private;
2631         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2632         struct drm_mm_node *free_space;
2633         gfp_t gfpmask =  __GFP_NORETRY | __GFP_NOWARN;
2634         int ret;
2635
2636         if (obj_priv->madv != I915_MADV_WILLNEED) {
2637                 DRM_ERROR("Attempting to bind a purgeable object\n");
2638                 return -EINVAL;
2639         }
2640
2641         if (alignment == 0)
2642                 alignment = i915_gem_get_gtt_alignment(obj);
2643         if (alignment & (i915_gem_get_gtt_alignment(obj) - 1)) {
2644                 DRM_ERROR("Invalid object alignment requested %u\n", alignment);
2645                 return -EINVAL;
2646         }
2647
2648         /* If the object is bigger than the entire aperture, reject it early
2649          * before evicting everything in a vain attempt to find space.
2650          */
2651         if (obj->size > dev_priv->mm.gtt_total) {
2652                 DRM_ERROR("Attempting to bind an object larger than the aperture\n");
2653                 return -E2BIG;
2654         }
2655
2656  search_free:
2657         free_space = drm_mm_search_free(&dev_priv->mm.gtt_space,
2658                                         obj->size, alignment, 0);
2659         if (free_space != NULL)
2660                 obj_priv->gtt_space = drm_mm_get_block(free_space, obj->size,
2661                                                        alignment);
2662         if (obj_priv->gtt_space == NULL) {
2663                 /* If the gtt is empty and we're still having trouble
2664                  * fitting our object in, we're out of memory.
2665                  */
2666                 ret = i915_gem_evict_something(dev, obj->size, alignment);
2667                 if (ret)
2668                         return ret;
2669
2670                 goto search_free;
2671         }
2672
2673         ret = i915_gem_object_get_pages(obj, gfpmask);
2674         if (ret) {
2675                 drm_mm_put_block(obj_priv->gtt_space);
2676                 obj_priv->gtt_space = NULL;
2677
2678                 if (ret == -ENOMEM) {
2679                         /* first try to clear up some space from the GTT */
2680                         ret = i915_gem_evict_something(dev, obj->size,
2681                                                        alignment);
2682                         if (ret) {
2683                                 /* now try to shrink everyone else */
2684                                 if (gfpmask) {
2685                                         gfpmask = 0;
2686                                         goto search_free;
2687                                 }
2688
2689                                 return ret;
2690                         }
2691
2692                         goto search_free;
2693                 }
2694
2695                 return ret;
2696         }
2697
2698         /* Create an AGP memory structure pointing at our pages, and bind it
2699          * into the GTT.
2700          */
2701         obj_priv->agp_mem = drm_agp_bind_pages(dev,
2702                                                obj_priv->pages,
2703                                                obj->size >> PAGE_SHIFT,
2704                                                obj_priv->gtt_space->start,
2705                                                obj_priv->agp_type);
2706         if (obj_priv->agp_mem == NULL) {
2707                 i915_gem_object_put_pages(obj);
2708                 drm_mm_put_block(obj_priv->gtt_space);
2709                 obj_priv->gtt_space = NULL;
2710
2711                 ret = i915_gem_evict_something(dev, obj->size, alignment);
2712                 if (ret)
2713                         return ret;
2714
2715                 goto search_free;
2716         }
2717
2718         /* keep track of bounds object by adding it to the inactive list */
2719         list_add_tail(&obj_priv->mm_list, &dev_priv->mm.inactive_list);
2720         i915_gem_info_add_gtt(dev_priv, obj->size);
2721
2722         /* Assert that the object is not currently in any GPU domain. As it
2723          * wasn't in the GTT, there shouldn't be any way it could have been in
2724          * a GPU cache
2725          */
2726         BUG_ON(obj->read_domains & I915_GEM_GPU_DOMAINS);
2727         BUG_ON(obj->write_domain & I915_GEM_GPU_DOMAINS);
2728
2729         obj_priv->gtt_offset = obj_priv->gtt_space->start;
2730         trace_i915_gem_object_bind(obj, obj_priv->gtt_offset);
2731
2732         return 0;
2733 }
2734
2735 void
2736 i915_gem_clflush_object(struct drm_gem_object *obj)
2737 {
2738         struct drm_i915_gem_object      *obj_priv = to_intel_bo(obj);
2739
2740         /* If we don't have a page list set up, then we're not pinned
2741          * to GPU, and we can ignore the cache flush because it'll happen
2742          * again at bind time.
2743          */
2744         if (obj_priv->pages == NULL)
2745                 return;
2746
2747         trace_i915_gem_object_clflush(obj);
2748
2749         drm_clflush_pages(obj_priv->pages, obj->size / PAGE_SIZE);
2750 }
2751
2752 /** Flushes any GPU write domain for the object if it's dirty. */
2753 static int
2754 i915_gem_object_flush_gpu_write_domain(struct drm_gem_object *obj,
2755                                        bool pipelined)
2756 {
2757         struct drm_device *dev = obj->dev;
2758         uint32_t old_write_domain;
2759
2760         if ((obj->write_domain & I915_GEM_GPU_DOMAINS) == 0)
2761                 return 0;
2762
2763         /* Queue the GPU write cache flushing we need. */
2764         old_write_domain = obj->write_domain;
2765         i915_gem_flush_ring(dev, NULL,
2766                             to_intel_bo(obj)->ring,
2767                             0, obj->write_domain);
2768         BUG_ON(obj->write_domain);
2769
2770         trace_i915_gem_object_change_domain(obj,
2771                                             obj->read_domains,
2772                                             old_write_domain);
2773
2774         if (pipelined)
2775                 return 0;
2776
2777         return i915_gem_object_wait_rendering(obj, true);
2778 }
2779
2780 /** Flushes the GTT write domain for the object if it's dirty. */
2781 static void
2782 i915_gem_object_flush_gtt_write_domain(struct drm_gem_object *obj)
2783 {
2784         uint32_t old_write_domain;
2785
2786         if (obj->write_domain != I915_GEM_DOMAIN_GTT)
2787                 return;
2788
2789         /* No actual flushing is required for the GTT write domain.   Writes
2790          * to it immediately go to main memory as far as we know, so there's
2791          * no chipset flush.  It also doesn't land in render cache.
2792          */
2793         old_write_domain = obj->write_domain;
2794         obj->write_domain = 0;
2795
2796         trace_i915_gem_object_change_domain(obj,
2797                                             obj->read_domains,
2798                                             old_write_domain);
2799 }
2800
2801 /** Flushes the CPU write domain for the object if it's dirty. */
2802 static void
2803 i915_gem_object_flush_cpu_write_domain(struct drm_gem_object *obj)
2804 {
2805         struct drm_device *dev = obj->dev;
2806         uint32_t old_write_domain;
2807
2808         if (obj->write_domain != I915_GEM_DOMAIN_CPU)
2809                 return;
2810
2811         i915_gem_clflush_object(obj);
2812         drm_agp_chipset_flush(dev);
2813         old_write_domain = obj->write_domain;
2814         obj->write_domain = 0;
2815
2816         trace_i915_gem_object_change_domain(obj,
2817                                             obj->read_domains,
2818                                             old_write_domain);
2819 }
2820
2821 /**
2822  * Moves a single object to the GTT read, and possibly write domain.
2823  *
2824  * This function returns when the move is complete, including waiting on
2825  * flushes to occur.
2826  */
2827 int
2828 i915_gem_object_set_to_gtt_domain(struct drm_gem_object *obj, int write)
2829 {
2830         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2831         uint32_t old_write_domain, old_read_domains;
2832         int ret;
2833
2834         /* Not valid to be called on unbound objects. */
2835         if (obj_priv->gtt_space == NULL)
2836                 return -EINVAL;
2837
2838         ret = i915_gem_object_flush_gpu_write_domain(obj, false);
2839         if (ret != 0)
2840                 return ret;
2841
2842         i915_gem_object_flush_cpu_write_domain(obj);
2843
2844         if (write) {
2845                 ret = i915_gem_object_wait_rendering(obj, true);
2846                 if (ret)
2847                         return ret;
2848         }
2849
2850         old_write_domain = obj->write_domain;
2851         old_read_domains = obj->read_domains;
2852
2853         /* It should now be out of any other write domains, and we can update
2854          * the domain values for our changes.
2855          */
2856         BUG_ON((obj->write_domain & ~I915_GEM_DOMAIN_GTT) != 0);
2857         obj->read_domains |= I915_GEM_DOMAIN_GTT;
2858         if (write) {
2859                 obj->read_domains = I915_GEM_DOMAIN_GTT;
2860                 obj->write_domain = I915_GEM_DOMAIN_GTT;
2861                 obj_priv->dirty = 1;
2862         }
2863
2864         trace_i915_gem_object_change_domain(obj,
2865                                             old_read_domains,
2866                                             old_write_domain);
2867
2868         return 0;
2869 }
2870
2871 /*
2872  * Prepare buffer for display plane. Use uninterruptible for possible flush
2873  * wait, as in modesetting process we're not supposed to be interrupted.
2874  */
2875 int
2876 i915_gem_object_set_to_display_plane(struct drm_gem_object *obj,
2877                                      bool pipelined)
2878 {
2879         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2880         uint32_t old_read_domains;
2881         int ret;
2882
2883         /* Not valid to be called on unbound objects. */
2884         if (obj_priv->gtt_space == NULL)
2885                 return -EINVAL;
2886
2887         ret = i915_gem_object_flush_gpu_write_domain(obj, true);
2888         if (ret)
2889                 return ret;
2890
2891         /* Currently, we are always called from an non-interruptible context. */
2892         if (!pipelined) {
2893                 ret = i915_gem_object_wait_rendering(obj, false);
2894                 if (ret)
2895                         return ret;
2896         }
2897
2898         i915_gem_object_flush_cpu_write_domain(obj);
2899
2900         old_read_domains = obj->read_domains;
2901         obj->read_domains |= I915_GEM_DOMAIN_GTT;
2902
2903         trace_i915_gem_object_change_domain(obj,
2904                                             old_read_domains,
2905                                             obj->write_domain);
2906
2907         return 0;
2908 }
2909
2910 int
2911 i915_gem_object_flush_gpu(struct drm_i915_gem_object *obj,
2912                           bool interruptible)
2913 {
2914         if (!obj->active)
2915                 return 0;
2916
2917         if (obj->base.write_domain & I915_GEM_GPU_DOMAINS)
2918                 i915_gem_flush_ring(obj->base.dev, NULL, obj->ring,
2919                                     0, obj->base.write_domain);
2920
2921         return i915_gem_object_wait_rendering(&obj->base, interruptible);
2922 }
2923
2924 /**
2925  * Moves a single object to the CPU read, and possibly write domain.
2926  *
2927  * This function returns when the move is complete, including waiting on
2928  * flushes to occur.
2929  */
2930 static int
2931 i915_gem_object_set_to_cpu_domain(struct drm_gem_object *obj, int write)
2932 {
2933         uint32_t old_write_domain, old_read_domains;
2934         int ret;
2935
2936         ret = i915_gem_object_flush_gpu_write_domain(obj, false);
2937         if (ret != 0)
2938                 return ret;
2939
2940         i915_gem_object_flush_gtt_write_domain(obj);
2941
2942         /* If we have a partially-valid cache of the object in the CPU,
2943          * finish invalidating it and free the per-page flags.
2944          */
2945         i915_gem_object_set_to_full_cpu_read_domain(obj);
2946
2947         if (write) {
2948                 ret = i915_gem_object_wait_rendering(obj, true);
2949                 if (ret)
2950                         return ret;
2951         }
2952
2953         old_write_domain = obj->write_domain;
2954         old_read_domains = obj->read_domains;
2955
2956         /* Flush the CPU cache if it's still invalid. */
2957         if ((obj->read_domains & I915_GEM_DOMAIN_CPU) == 0) {
2958                 i915_gem_clflush_object(obj);
2959
2960                 obj->read_domains |= I915_GEM_DOMAIN_CPU;
2961         }
2962
2963         /* It should now be out of any other write domains, and we can update
2964          * the domain values for our changes.
2965          */
2966         BUG_ON((obj->write_domain & ~I915_GEM_DOMAIN_CPU) != 0);
2967
2968         /* If we're writing through the CPU, then the GPU read domains will
2969          * need to be invalidated at next use.
2970          */
2971         if (write) {
2972                 obj->read_domains = I915_GEM_DOMAIN_CPU;
2973                 obj->write_domain = I915_GEM_DOMAIN_CPU;
2974         }
2975
2976         trace_i915_gem_object_change_domain(obj,
2977                                             old_read_domains,
2978                                             old_write_domain);
2979
2980         return 0;
2981 }
2982
2983 /*
2984  * Set the next domain for the specified object. This
2985  * may not actually perform the necessary flushing/invaliding though,
2986  * as that may want to be batched with other set_domain operations
2987  *
2988  * This is (we hope) the only really tricky part of gem. The goal
2989  * is fairly simple -- track which caches hold bits of the object
2990  * and make sure they remain coherent. A few concrete examples may
2991  * help to explain how it works. For shorthand, we use the notation
2992  * (read_domains, write_domain), e.g. (CPU, CPU) to indicate the
2993  * a pair of read and write domain masks.
2994  *
2995  * Case 1: the batch buffer
2996  *
2997  *      1. Allocated
2998  *      2. Written by CPU
2999  *      3. Mapped to GTT
3000  *      4. Read by GPU
3001  *      5. Unmapped from GTT
3002  *      6. Freed
3003  *
3004  *      Let's take these a step at a time
3005  *
3006  *      1. Allocated
3007  *              Pages allocated from the kernel may still have
3008  *              cache contents, so we set them to (CPU, CPU) always.
3009  *      2. Written by CPU (using pwrite)
3010  *              The pwrite function calls set_domain (CPU, CPU) and
3011  *              this function does nothing (as nothing changes)
3012  *      3. Mapped by GTT
3013  *              This function asserts that the object is not
3014  *              currently in any GPU-based read or write domains
3015  *      4. Read by GPU
3016  *              i915_gem_execbuffer calls set_domain (COMMAND, 0).
3017  *              As write_domain is zero, this function adds in the
3018  *              current read domains (CPU+COMMAND, 0).
3019  *              flush_domains is set to CPU.
3020  *              invalidate_domains is set to COMMAND
3021  *              clflush is run to get data out of the CPU caches
3022  *              then i915_dev_set_domain calls i915_gem_flush to
3023  *              emit an MI_FLUSH and drm_agp_chipset_flush
3024  *      5. Unmapped from GTT
3025  *              i915_gem_object_unbind calls set_domain (CPU, CPU)
3026  *              flush_domains and invalidate_domains end up both zero
3027  *              so no flushing/invalidating happens
3028  *      6. Freed
3029  *              yay, done
3030  *
3031  * Case 2: The shared render buffer
3032  *
3033  *      1. Allocated
3034  *      2. Mapped to GTT
3035  *      3. Read/written by GPU
3036  *      4. set_domain to (CPU,CPU)
3037  *      5. Read/written by CPU
3038  *      6. Read/written by GPU
3039  *
3040  *      1. Allocated
3041  *              Same as last example, (CPU, CPU)
3042  *      2. Mapped to GTT
3043  *              Nothing changes (assertions find that it is not in the GPU)
3044  *      3. Read/written by GPU
3045  *              execbuffer calls set_domain (RENDER, RENDER)
3046  *              flush_domains gets CPU
3047  *              invalidate_domains gets GPU
3048  *              clflush (obj)
3049  *              MI_FLUSH and drm_agp_chipset_flush
3050  *      4. set_domain (CPU, CPU)
3051  *              flush_domains gets GPU
3052  *              invalidate_domains gets CPU
3053  *              wait_rendering (obj) to make sure all drawing is complete.
3054  *              This will include an MI_FLUSH to get the data from GPU
3055  *              to memory
3056  *              clflush (obj) to invalidate the CPU cache
3057  *              Another MI_FLUSH in i915_gem_flush (eliminate this somehow?)
3058  *      5. Read/written by CPU
3059  *              cache lines are loaded and dirtied
3060  *      6. Read written by GPU
3061  *              Same as last GPU access
3062  *
3063  * Case 3: The constant buffer
3064  *
3065  *      1. Allocated
3066  *      2. Written by CPU
3067  *      3. Read by GPU
3068  *      4. Updated (written) by CPU again
3069  *      5. Read by GPU
3070  *
3071  *      1. Allocated
3072  *              (CPU, CPU)
3073  *      2. Written by CPU
3074  *              (CPU, CPU)
3075  *      3. Read by GPU
3076  *              (CPU+RENDER, 0)
3077  *              flush_domains = CPU
3078  *              invalidate_domains = RENDER
3079  *              clflush (obj)
3080  *              MI_FLUSH
3081  *              drm_agp_chipset_flush
3082  *      4. Updated (written) by CPU again
3083  *              (CPU, CPU)
3084  *              flush_domains = 0 (no previous write domain)
3085  *              invalidate_domains = 0 (no new read domains)
3086  *      5. Read by GPU
3087  *              (CPU+RENDER, 0)
3088  *              flush_domains = CPU
3089  *              invalidate_domains = RENDER
3090  *              clflush (obj)
3091  *              MI_FLUSH
3092  *              drm_agp_chipset_flush
3093  */
3094 static void
3095 i915_gem_object_set_to_gpu_domain(struct drm_gem_object *obj,
3096                                   struct intel_ring_buffer *ring)
3097 {
3098         struct drm_device               *dev = obj->dev;
3099         struct drm_i915_private         *dev_priv = dev->dev_private;
3100         struct drm_i915_gem_object      *obj_priv = to_intel_bo(obj);
3101         uint32_t                        invalidate_domains = 0;
3102         uint32_t                        flush_domains = 0;
3103         uint32_t                        old_read_domains;
3104
3105         intel_mark_busy(dev, obj);
3106
3107         /*
3108          * If the object isn't moving to a new write domain,
3109          * let the object stay in multiple read domains
3110          */
3111         if (obj->pending_write_domain == 0)
3112                 obj->pending_read_domains |= obj->read_domains;
3113         else
3114                 obj_priv->dirty = 1;
3115
3116         /*
3117          * Flush the current write domain if
3118          * the new read domains don't match. Invalidate
3119          * any read domains which differ from the old
3120          * write domain
3121          */