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