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