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