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