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