Merge branch 'drm-tracepoints' into drm-testing
[sfrench/cifs-2.6.git] / drivers / gpu / drm / i915 / i915_gem.c
1 /*
2  * Copyright © 2008 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  *
23  * Authors:
24  *    Eric Anholt <eric@anholt.net>
25  *
26  */
27
28 #include "drmP.h"
29 #include "drm.h"
30 #include "i915_drm.h"
31 #include "i915_drv.h"
32 #include "i915_trace.h"
33 #include "intel_drv.h"
34 #include <linux/slab.h>
35 #include <linux/swap.h>
36 #include <linux/pci.h>
37
38 static void i915_gem_object_flush_gpu_write_domain(struct drm_gem_object *obj);
39 static void i915_gem_object_flush_gtt_write_domain(struct drm_gem_object *obj);
40 static void i915_gem_object_flush_cpu_write_domain(struct drm_gem_object *obj);
41 static int i915_gem_object_set_to_cpu_domain(struct drm_gem_object *obj,
42                                              int write);
43 static int i915_gem_object_set_cpu_read_domain_range(struct drm_gem_object *obj,
44                                                      uint64_t offset,
45                                                      uint64_t size);
46 static void i915_gem_object_set_to_full_cpu_read_domain(struct drm_gem_object *obj);
47 static int i915_gem_object_wait_rendering(struct drm_gem_object *obj);
48 static int i915_gem_object_bind_to_gtt(struct drm_gem_object *obj,
49                                            unsigned alignment);
50 static void i915_gem_clear_fence_reg(struct drm_gem_object *obj);
51 static int i915_gem_evict_something(struct drm_device *dev, int min_size);
52 static int i915_gem_evict_from_inactive_list(struct drm_device *dev);
53 static int i915_gem_phys_pwrite(struct drm_device *dev, struct drm_gem_object *obj,
54                                 struct drm_i915_gem_pwrite *args,
55                                 struct drm_file *file_priv);
56
57 static LIST_HEAD(shrink_list);
58 static DEFINE_SPINLOCK(shrink_list_lock);
59
60 int i915_gem_do_init(struct drm_device *dev, unsigned long start,
61                      unsigned long end)
62 {
63         drm_i915_private_t *dev_priv = dev->dev_private;
64
65         if (start >= end ||
66             (start & (PAGE_SIZE - 1)) != 0 ||
67             (end & (PAGE_SIZE - 1)) != 0) {
68                 return -EINVAL;
69         }
70
71         drm_mm_init(&dev_priv->mm.gtt_space, start,
72                     end - start);
73
74         dev->gtt_total = (uint32_t) (end - start);
75
76         return 0;
77 }
78
79 int
80 i915_gem_init_ioctl(struct drm_device *dev, void *data,
81                     struct drm_file *file_priv)
82 {
83         struct drm_i915_gem_init *args = data;
84         int ret;
85
86         mutex_lock(&dev->struct_mutex);
87         ret = i915_gem_do_init(dev, args->gtt_start, args->gtt_end);
88         mutex_unlock(&dev->struct_mutex);
89
90         return ret;
91 }
92
93 int
94 i915_gem_get_aperture_ioctl(struct drm_device *dev, void *data,
95                             struct drm_file *file_priv)
96 {
97         struct drm_i915_gem_get_aperture *args = data;
98
99         if (!(dev->driver->driver_features & DRIVER_GEM))
100                 return -ENODEV;
101
102         args->aper_size = dev->gtt_total;
103         args->aper_available_size = (args->aper_size -
104                                      atomic_read(&dev->pin_memory));
105
106         return 0;
107 }
108
109
110 /**
111  * Creates a new mm object and returns a handle to it.
112  */
113 int
114 i915_gem_create_ioctl(struct drm_device *dev, void *data,
115                       struct drm_file *file_priv)
116 {
117         struct drm_i915_gem_create *args = data;
118         struct drm_gem_object *obj;
119         int ret;
120         u32 handle;
121
122         args->size = roundup(args->size, PAGE_SIZE);
123
124         /* Allocate the new object */
125         obj = i915_gem_alloc_object(dev, args->size);
126         if (obj == NULL)
127                 return -ENOMEM;
128
129         ret = drm_gem_handle_create(file_priv, obj, &handle);
130         drm_gem_object_handle_unreference_unlocked(obj);
131
132         if (ret)
133                 return ret;
134
135         args->handle = handle;
136
137         return 0;
138 }
139
140 static inline int
141 fast_shmem_read(struct page **pages,
142                 loff_t page_base, int page_offset,
143                 char __user *data,
144                 int length)
145 {
146         char __iomem *vaddr;
147         int unwritten;
148
149         vaddr = kmap_atomic(pages[page_base >> PAGE_SHIFT], KM_USER0);
150         if (vaddr == NULL)
151                 return -ENOMEM;
152         unwritten = __copy_to_user_inatomic(data, vaddr + page_offset, length);
153         kunmap_atomic(vaddr, KM_USER0);
154
155         if (unwritten)
156                 return -EFAULT;
157
158         return 0;
159 }
160
161 static int i915_gem_object_needs_bit17_swizzle(struct drm_gem_object *obj)
162 {
163         drm_i915_private_t *dev_priv = obj->dev->dev_private;
164         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
165
166         return dev_priv->mm.bit_6_swizzle_x == I915_BIT_6_SWIZZLE_9_10_17 &&
167                 obj_priv->tiling_mode != I915_TILING_NONE;
168 }
169
170 static inline void
171 slow_shmem_copy(struct page *dst_page,
172                 int dst_offset,
173                 struct page *src_page,
174                 int src_offset,
175                 int length)
176 {
177         char *dst_vaddr, *src_vaddr;
178
179         dst_vaddr = kmap(dst_page);
180         src_vaddr = kmap(src_page);
181
182         memcpy(dst_vaddr + dst_offset, src_vaddr + src_offset, length);
183
184         kunmap(src_page);
185         kunmap(dst_page);
186 }
187
188 static inline void
189 slow_shmem_bit17_copy(struct page *gpu_page,
190                       int gpu_offset,
191                       struct page *cpu_page,
192                       int cpu_offset,
193                       int length,
194                       int is_read)
195 {
196         char *gpu_vaddr, *cpu_vaddr;
197
198         /* Use the unswizzled path if this page isn't affected. */
199         if ((page_to_phys(gpu_page) & (1 << 17)) == 0) {
200                 if (is_read)
201                         return slow_shmem_copy(cpu_page, cpu_offset,
202                                                gpu_page, gpu_offset, length);
203                 else
204                         return slow_shmem_copy(gpu_page, gpu_offset,
205                                                cpu_page, cpu_offset, length);
206         }
207
208         gpu_vaddr = kmap(gpu_page);
209         cpu_vaddr = kmap(cpu_page);
210
211         /* Copy the data, XORing A6 with A17 (1). The user already knows he's
212          * XORing with the other bits (A9 for Y, A9 and A10 for X)
213          */
214         while (length > 0) {
215                 int cacheline_end = ALIGN(gpu_offset + 1, 64);
216                 int this_length = min(cacheline_end - gpu_offset, length);
217                 int swizzled_gpu_offset = gpu_offset ^ 64;
218
219                 if (is_read) {
220                         memcpy(cpu_vaddr + cpu_offset,
221                                gpu_vaddr + swizzled_gpu_offset,
222                                this_length);
223                 } else {
224                         memcpy(gpu_vaddr + swizzled_gpu_offset,
225                                cpu_vaddr + cpu_offset,
226                                this_length);
227                 }
228                 cpu_offset += this_length;
229                 gpu_offset += this_length;
230                 length -= this_length;
231         }
232
233         kunmap(cpu_page);
234         kunmap(gpu_page);
235 }
236
237 /**
238  * This is the fast shmem pread path, which attempts to copy_from_user directly
239  * from the backing pages of the object to the user's address space.  On a
240  * fault, it fails so we can fall back to i915_gem_shmem_pwrite_slow().
241  */
242 static int
243 i915_gem_shmem_pread_fast(struct drm_device *dev, struct drm_gem_object *obj,
244                           struct drm_i915_gem_pread *args,
245                           struct drm_file *file_priv)
246 {
247         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
248         ssize_t remain;
249         loff_t offset, page_base;
250         char __user *user_data;
251         int page_offset, page_length;
252         int ret;
253
254         user_data = (char __user *) (uintptr_t) args->data_ptr;
255         remain = args->size;
256
257         mutex_lock(&dev->struct_mutex);
258
259         ret = i915_gem_object_get_pages(obj, 0);
260         if (ret != 0)
261                 goto fail_unlock;
262
263         ret = i915_gem_object_set_cpu_read_domain_range(obj, args->offset,
264                                                         args->size);
265         if (ret != 0)
266                 goto fail_put_pages;
267
268         obj_priv = to_intel_bo(obj);
269         offset = args->offset;
270
271         while (remain > 0) {
272                 /* Operation in this page
273                  *
274                  * page_base = page offset within aperture
275                  * page_offset = offset within page
276                  * page_length = bytes to copy for this page
277                  */
278                 page_base = (offset & ~(PAGE_SIZE-1));
279                 page_offset = offset & (PAGE_SIZE-1);
280                 page_length = remain;
281                 if ((page_offset + remain) > PAGE_SIZE)
282                         page_length = PAGE_SIZE - page_offset;
283
284                 ret = fast_shmem_read(obj_priv->pages,
285                                       page_base, page_offset,
286                                       user_data, page_length);
287                 if (ret)
288                         goto fail_put_pages;
289
290                 remain -= page_length;
291                 user_data += page_length;
292                 offset += page_length;
293         }
294
295 fail_put_pages:
296         i915_gem_object_put_pages(obj);
297 fail_unlock:
298         mutex_unlock(&dev->struct_mutex);
299
300         return ret;
301 }
302
303 static int
304 i915_gem_object_get_pages_or_evict(struct drm_gem_object *obj)
305 {
306         int ret;
307
308         ret = i915_gem_object_get_pages(obj, __GFP_NORETRY | __GFP_NOWARN);
309
310         /* If we've insufficient memory to map in the pages, attempt
311          * to make some space by throwing out some old buffers.
312          */
313         if (ret == -ENOMEM) {
314                 struct drm_device *dev = obj->dev;
315
316                 ret = i915_gem_evict_something(dev, obj->size);
317                 if (ret)
318                         return ret;
319
320                 ret = i915_gem_object_get_pages(obj, 0);
321         }
322
323         return ret;
324 }
325
326 /**
327  * This is the fallback shmem pread path, which allocates temporary storage
328  * in kernel space to copy_to_user into outside of the struct_mutex, so we
329  * can copy out of the object's backing pages while holding the struct mutex
330  * and not take page faults.
331  */
332 static int
333 i915_gem_shmem_pread_slow(struct drm_device *dev, struct drm_gem_object *obj,
334                           struct drm_i915_gem_pread *args,
335                           struct drm_file *file_priv)
336 {
337         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
338         struct mm_struct *mm = current->mm;
339         struct page **user_pages;
340         ssize_t remain;
341         loff_t offset, pinned_pages, i;
342         loff_t first_data_page, last_data_page, num_pages;
343         int shmem_page_index, shmem_page_offset;
344         int data_page_index,  data_page_offset;
345         int page_length;
346         int ret;
347         uint64_t data_ptr = args->data_ptr;
348         int do_bit17_swizzling;
349
350         remain = args->size;
351
352         /* Pin the user pages containing the data.  We can't fault while
353          * holding the struct mutex, yet we want to hold it while
354          * dereferencing the user data.
355          */
356         first_data_page = data_ptr / PAGE_SIZE;
357         last_data_page = (data_ptr + args->size - 1) / PAGE_SIZE;
358         num_pages = last_data_page - first_data_page + 1;
359
360         user_pages = drm_calloc_large(num_pages, sizeof(struct page *));
361         if (user_pages == NULL)
362                 return -ENOMEM;
363
364         down_read(&mm->mmap_sem);
365         pinned_pages = get_user_pages(current, mm, (uintptr_t)args->data_ptr,
366                                       num_pages, 1, 0, user_pages, NULL);
367         up_read(&mm->mmap_sem);
368         if (pinned_pages < num_pages) {
369                 ret = -EFAULT;
370                 goto fail_put_user_pages;
371         }
372
373         do_bit17_swizzling = i915_gem_object_needs_bit17_swizzle(obj);
374
375         mutex_lock(&dev->struct_mutex);
376
377         ret = i915_gem_object_get_pages_or_evict(obj);
378         if (ret)
379                 goto fail_unlock;
380
381         ret = i915_gem_object_set_cpu_read_domain_range(obj, args->offset,
382                                                         args->size);
383         if (ret != 0)
384                 goto fail_put_pages;
385
386         obj_priv = to_intel_bo(obj);
387         offset = args->offset;
388
389         while (remain > 0) {
390                 /* Operation in this page
391                  *
392                  * shmem_page_index = page number within shmem file
393                  * shmem_page_offset = offset within page in shmem file
394                  * data_page_index = page number in get_user_pages return
395                  * data_page_offset = offset with data_page_index page.
396                  * page_length = bytes to copy for this page
397                  */
398                 shmem_page_index = offset / PAGE_SIZE;
399                 shmem_page_offset = offset & ~PAGE_MASK;
400                 data_page_index = data_ptr / PAGE_SIZE - first_data_page;
401                 data_page_offset = data_ptr & ~PAGE_MASK;
402
403                 page_length = remain;
404                 if ((shmem_page_offset + page_length) > PAGE_SIZE)
405                         page_length = PAGE_SIZE - shmem_page_offset;
406                 if ((data_page_offset + page_length) > PAGE_SIZE)
407                         page_length = PAGE_SIZE - data_page_offset;
408
409                 if (do_bit17_swizzling) {
410                         slow_shmem_bit17_copy(obj_priv->pages[shmem_page_index],
411                                               shmem_page_offset,
412                                               user_pages[data_page_index],
413                                               data_page_offset,
414                                               page_length,
415                                               1);
416                 } else {
417                         slow_shmem_copy(user_pages[data_page_index],
418                                         data_page_offset,
419                                         obj_priv->pages[shmem_page_index],
420                                         shmem_page_offset,
421                                         page_length);
422                 }
423
424                 remain -= page_length;
425                 data_ptr += page_length;
426                 offset += page_length;
427         }
428
429 fail_put_pages:
430         i915_gem_object_put_pages(obj);
431 fail_unlock:
432         mutex_unlock(&dev->struct_mutex);
433 fail_put_user_pages:
434         for (i = 0; i < pinned_pages; i++) {
435                 SetPageDirty(user_pages[i]);
436                 page_cache_release(user_pages[i]);
437         }
438         drm_free_large(user_pages);
439
440         return ret;
441 }
442
443 /**
444  * Reads data from the object referenced by handle.
445  *
446  * On error, the contents of *data are undefined.
447  */
448 int
449 i915_gem_pread_ioctl(struct drm_device *dev, void *data,
450                      struct drm_file *file_priv)
451 {
452         struct drm_i915_gem_pread *args = data;
453         struct drm_gem_object *obj;
454         struct drm_i915_gem_object *obj_priv;
455         int ret;
456
457         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
458         if (obj == NULL)
459                 return -EBADF;
460         obj_priv = to_intel_bo(obj);
461
462         /* Bounds check source.
463          *
464          * XXX: This could use review for overflow issues...
465          */
466         if (args->offset > obj->size || args->size > obj->size ||
467             args->offset + args->size > obj->size) {
468                 drm_gem_object_unreference_unlocked(obj);
469                 return -EINVAL;
470         }
471
472         if (i915_gem_object_needs_bit17_swizzle(obj)) {
473                 ret = i915_gem_shmem_pread_slow(dev, obj, args, file_priv);
474         } else {
475                 ret = i915_gem_shmem_pread_fast(dev, obj, args, file_priv);
476                 if (ret != 0)
477                         ret = i915_gem_shmem_pread_slow(dev, obj, args,
478                                                         file_priv);
479         }
480
481         drm_gem_object_unreference_unlocked(obj);
482
483         return ret;
484 }
485
486 /* This is the fast write path which cannot handle
487  * page faults in the source data
488  */
489
490 static inline int
491 fast_user_write(struct io_mapping *mapping,
492                 loff_t page_base, int page_offset,
493                 char __user *user_data,
494                 int length)
495 {
496         char *vaddr_atomic;
497         unsigned long unwritten;
498
499         vaddr_atomic = io_mapping_map_atomic_wc(mapping, page_base);
500         unwritten = __copy_from_user_inatomic_nocache(vaddr_atomic + page_offset,
501                                                       user_data, length);
502         io_mapping_unmap_atomic(vaddr_atomic);
503         if (unwritten)
504                 return -EFAULT;
505         return 0;
506 }
507
508 /* Here's the write path which can sleep for
509  * page faults
510  */
511
512 static inline void
513 slow_kernel_write(struct io_mapping *mapping,
514                   loff_t gtt_base, int gtt_offset,
515                   struct page *user_page, int user_offset,
516                   int length)
517 {
518         char __iomem *dst_vaddr;
519         char *src_vaddr;
520
521         dst_vaddr = io_mapping_map_wc(mapping, gtt_base);
522         src_vaddr = kmap(user_page);
523
524         memcpy_toio(dst_vaddr + gtt_offset,
525                     src_vaddr + user_offset,
526                     length);
527
528         kunmap(user_page);
529         io_mapping_unmap(dst_vaddr);
530 }
531
532 static inline int
533 fast_shmem_write(struct page **pages,
534                  loff_t page_base, int page_offset,
535                  char __user *data,
536                  int length)
537 {
538         char __iomem *vaddr;
539         unsigned long unwritten;
540
541         vaddr = kmap_atomic(pages[page_base >> PAGE_SHIFT], KM_USER0);
542         if (vaddr == NULL)
543                 return -ENOMEM;
544         unwritten = __copy_from_user_inatomic(vaddr + page_offset, data, length);
545         kunmap_atomic(vaddr, KM_USER0);
546
547         if (unwritten)
548                 return -EFAULT;
549         return 0;
550 }
551
552 /**
553  * This is the fast pwrite path, where we copy the data directly from the
554  * user into the GTT, uncached.
555  */
556 static int
557 i915_gem_gtt_pwrite_fast(struct drm_device *dev, struct drm_gem_object *obj,
558                          struct drm_i915_gem_pwrite *args,
559                          struct drm_file *file_priv)
560 {
561         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
562         drm_i915_private_t *dev_priv = dev->dev_private;
563         ssize_t remain;
564         loff_t offset, page_base;
565         char __user *user_data;
566         int page_offset, page_length;
567         int ret;
568
569         user_data = (char __user *) (uintptr_t) args->data_ptr;
570         remain = args->size;
571         if (!access_ok(VERIFY_READ, user_data, remain))
572                 return -EFAULT;
573
574
575         mutex_lock(&dev->struct_mutex);
576         ret = i915_gem_object_pin(obj, 0);
577         if (ret) {
578                 mutex_unlock(&dev->struct_mutex);
579                 return ret;
580         }
581         ret = i915_gem_object_set_to_gtt_domain(obj, 1);
582         if (ret)
583                 goto fail;
584
585         obj_priv = to_intel_bo(obj);
586         offset = obj_priv->gtt_offset + args->offset;
587
588         while (remain > 0) {
589                 /* Operation in this page
590                  *
591                  * page_base = page offset within aperture
592                  * page_offset = offset within page
593                  * page_length = bytes to copy for this page
594                  */
595                 page_base = (offset & ~(PAGE_SIZE-1));
596                 page_offset = offset & (PAGE_SIZE-1);
597                 page_length = remain;
598                 if ((page_offset + remain) > PAGE_SIZE)
599                         page_length = PAGE_SIZE - page_offset;
600
601                 ret = fast_user_write (dev_priv->mm.gtt_mapping, page_base,
602                                        page_offset, user_data, page_length);
603
604                 /* If we get a fault while copying data, then (presumably) our
605                  * source page isn't available.  Return the error and we'll
606                  * retry in the slow path.
607                  */
608                 if (ret)
609                         goto fail;
610
611                 remain -= page_length;
612                 user_data += page_length;
613                 offset += page_length;
614         }
615
616 fail:
617         i915_gem_object_unpin(obj);
618         mutex_unlock(&dev->struct_mutex);
619
620         return ret;
621 }
622
623 /**
624  * This is the fallback GTT pwrite path, which uses get_user_pages to pin
625  * the memory and maps it using kmap_atomic for copying.
626  *
627  * This code resulted in x11perf -rgb10text consuming about 10% more CPU
628  * than using i915_gem_gtt_pwrite_fast on a G45 (32-bit).
629  */
630 static int
631 i915_gem_gtt_pwrite_slow(struct drm_device *dev, struct drm_gem_object *obj,
632                          struct drm_i915_gem_pwrite *args,
633                          struct drm_file *file_priv)
634 {
635         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
636         drm_i915_private_t *dev_priv = dev->dev_private;
637         ssize_t remain;
638         loff_t gtt_page_base, offset;
639         loff_t first_data_page, last_data_page, num_pages;
640         loff_t pinned_pages, i;
641         struct page **user_pages;
642         struct mm_struct *mm = current->mm;
643         int gtt_page_offset, data_page_offset, data_page_index, page_length;
644         int ret;
645         uint64_t data_ptr = args->data_ptr;
646
647         remain = args->size;
648
649         /* Pin the user pages containing the data.  We can't fault while
650          * holding the struct mutex, and all of the pwrite implementations
651          * want to hold it while dereferencing the user data.
652          */
653         first_data_page = data_ptr / PAGE_SIZE;
654         last_data_page = (data_ptr + args->size - 1) / PAGE_SIZE;
655         num_pages = last_data_page - first_data_page + 1;
656
657         user_pages = drm_calloc_large(num_pages, sizeof(struct page *));
658         if (user_pages == NULL)
659                 return -ENOMEM;
660
661         down_read(&mm->mmap_sem);
662         pinned_pages = get_user_pages(current, mm, (uintptr_t)args->data_ptr,
663                                       num_pages, 0, 0, user_pages, NULL);
664         up_read(&mm->mmap_sem);
665         if (pinned_pages < num_pages) {
666                 ret = -EFAULT;
667                 goto out_unpin_pages;
668         }
669
670         mutex_lock(&dev->struct_mutex);
671         ret = i915_gem_object_pin(obj, 0);
672         if (ret)
673                 goto out_unlock;
674
675         ret = i915_gem_object_set_to_gtt_domain(obj, 1);
676         if (ret)
677                 goto out_unpin_object;
678
679         obj_priv = to_intel_bo(obj);
680         offset = obj_priv->gtt_offset + args->offset;
681
682         while (remain > 0) {
683                 /* Operation in this page
684                  *
685                  * gtt_page_base = page offset within aperture
686                  * gtt_page_offset = offset within page in aperture
687                  * data_page_index = page number in get_user_pages return
688                  * data_page_offset = offset with data_page_index page.
689                  * page_length = bytes to copy for this page
690                  */
691                 gtt_page_base = offset & PAGE_MASK;
692                 gtt_page_offset = offset & ~PAGE_MASK;
693                 data_page_index = data_ptr / PAGE_SIZE - first_data_page;
694                 data_page_offset = data_ptr & ~PAGE_MASK;
695
696                 page_length = remain;
697                 if ((gtt_page_offset + page_length) > PAGE_SIZE)
698                         page_length = PAGE_SIZE - gtt_page_offset;
699                 if ((data_page_offset + page_length) > PAGE_SIZE)
700                         page_length = PAGE_SIZE - data_page_offset;
701
702                 slow_kernel_write(dev_priv->mm.gtt_mapping,
703                                   gtt_page_base, gtt_page_offset,
704                                   user_pages[data_page_index],
705                                   data_page_offset,
706                                   page_length);
707
708                 remain -= page_length;
709                 offset += page_length;
710                 data_ptr += page_length;
711         }
712
713 out_unpin_object:
714         i915_gem_object_unpin(obj);
715 out_unlock:
716         mutex_unlock(&dev->struct_mutex);
717 out_unpin_pages:
718         for (i = 0; i < pinned_pages; i++)
719                 page_cache_release(user_pages[i]);
720         drm_free_large(user_pages);
721
722         return ret;
723 }
724
725 /**
726  * This is the fast shmem pwrite path, which attempts to directly
727  * copy_from_user into the kmapped pages backing the object.
728  */
729 static int
730 i915_gem_shmem_pwrite_fast(struct drm_device *dev, struct drm_gem_object *obj,
731                            struct drm_i915_gem_pwrite *args,
732                            struct drm_file *file_priv)
733 {
734         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
735         ssize_t remain;
736         loff_t offset, page_base;
737         char __user *user_data;
738         int page_offset, page_length;
739         int ret;
740
741         user_data = (char __user *) (uintptr_t) args->data_ptr;
742         remain = args->size;
743
744         mutex_lock(&dev->struct_mutex);
745
746         ret = i915_gem_object_get_pages(obj, 0);
747         if (ret != 0)
748                 goto fail_unlock;
749
750         ret = i915_gem_object_set_to_cpu_domain(obj, 1);
751         if (ret != 0)
752                 goto fail_put_pages;
753
754         obj_priv = to_intel_bo(obj);
755         offset = args->offset;
756         obj_priv->dirty = 1;
757
758         while (remain > 0) {
759                 /* Operation in this page
760                  *
761                  * page_base = page offset within aperture
762                  * page_offset = offset within page
763                  * page_length = bytes to copy for this page
764                  */
765                 page_base = (offset & ~(PAGE_SIZE-1));
766                 page_offset = offset & (PAGE_SIZE-1);
767                 page_length = remain;
768                 if ((page_offset + remain) > PAGE_SIZE)
769                         page_length = PAGE_SIZE - page_offset;
770
771                 ret = fast_shmem_write(obj_priv->pages,
772                                        page_base, page_offset,
773                                        user_data, page_length);
774                 if (ret)
775                         goto fail_put_pages;
776
777                 remain -= page_length;
778                 user_data += page_length;
779                 offset += page_length;
780         }
781
782 fail_put_pages:
783         i915_gem_object_put_pages(obj);
784 fail_unlock:
785         mutex_unlock(&dev->struct_mutex);
786
787         return ret;
788 }
789
790 /**
791  * This is the fallback shmem pwrite path, which uses get_user_pages to pin
792  * the memory and maps it using kmap_atomic for copying.
793  *
794  * This avoids taking mmap_sem for faulting on the user's address while the
795  * struct_mutex is held.
796  */
797 static int
798 i915_gem_shmem_pwrite_slow(struct drm_device *dev, struct drm_gem_object *obj,
799                            struct drm_i915_gem_pwrite *args,
800                            struct drm_file *file_priv)
801 {
802         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
803         struct mm_struct *mm = current->mm;
804         struct page **user_pages;
805         ssize_t remain;
806         loff_t offset, pinned_pages, i;
807         loff_t first_data_page, last_data_page, num_pages;
808         int shmem_page_index, shmem_page_offset;
809         int data_page_index,  data_page_offset;
810         int page_length;
811         int ret;
812         uint64_t data_ptr = args->data_ptr;
813         int do_bit17_swizzling;
814
815         remain = args->size;
816
817         /* Pin the user pages containing the data.  We can't fault while
818          * holding the struct mutex, and all of the pwrite implementations
819          * want to hold it while dereferencing the user data.
820          */
821         first_data_page = data_ptr / PAGE_SIZE;
822         last_data_page = (data_ptr + args->size - 1) / PAGE_SIZE;
823         num_pages = last_data_page - first_data_page + 1;
824
825         user_pages = drm_calloc_large(num_pages, sizeof(struct page *));
826         if (user_pages == NULL)
827                 return -ENOMEM;
828
829         down_read(&mm->mmap_sem);
830         pinned_pages = get_user_pages(current, mm, (uintptr_t)args->data_ptr,
831                                       num_pages, 0, 0, user_pages, NULL);
832         up_read(&mm->mmap_sem);
833         if (pinned_pages < num_pages) {
834                 ret = -EFAULT;
835                 goto fail_put_user_pages;
836         }
837
838         do_bit17_swizzling = i915_gem_object_needs_bit17_swizzle(obj);
839
840         mutex_lock(&dev->struct_mutex);
841
842         ret = i915_gem_object_get_pages_or_evict(obj);
843         if (ret)
844                 goto fail_unlock;
845
846         ret = i915_gem_object_set_to_cpu_domain(obj, 1);
847         if (ret != 0)
848                 goto fail_put_pages;
849
850         obj_priv = to_intel_bo(obj);
851         offset = args->offset;
852         obj_priv->dirty = 1;
853
854         while (remain > 0) {
855                 /* Operation in this page
856                  *
857                  * shmem_page_index = page number within shmem file
858                  * shmem_page_offset = offset within page in shmem file
859                  * data_page_index = page number in get_user_pages return
860                  * data_page_offset = offset with data_page_index page.
861                  * page_length = bytes to copy for this page
862                  */
863                 shmem_page_index = offset / PAGE_SIZE;
864                 shmem_page_offset = offset & ~PAGE_MASK;
865                 data_page_index = data_ptr / PAGE_SIZE - first_data_page;
866                 data_page_offset = data_ptr & ~PAGE_MASK;
867
868                 page_length = remain;
869                 if ((shmem_page_offset + page_length) > PAGE_SIZE)
870                         page_length = PAGE_SIZE - shmem_page_offset;
871                 if ((data_page_offset + page_length) > PAGE_SIZE)
872                         page_length = PAGE_SIZE - data_page_offset;
873
874                 if (do_bit17_swizzling) {
875                         slow_shmem_bit17_copy(obj_priv->pages[shmem_page_index],
876                                               shmem_page_offset,
877                                               user_pages[data_page_index],
878                                               data_page_offset,
879                                               page_length,
880                                               0);
881                 } else {
882                         slow_shmem_copy(obj_priv->pages[shmem_page_index],
883                                         shmem_page_offset,
884                                         user_pages[data_page_index],
885                                         data_page_offset,
886                                         page_length);
887                 }
888
889                 remain -= page_length;
890                 data_ptr += page_length;
891                 offset += page_length;
892         }
893
894 fail_put_pages:
895         i915_gem_object_put_pages(obj);
896 fail_unlock:
897         mutex_unlock(&dev->struct_mutex);
898 fail_put_user_pages:
899         for (i = 0; i < pinned_pages; i++)
900                 page_cache_release(user_pages[i]);
901         drm_free_large(user_pages);
902
903         return ret;
904 }
905
906 /**
907  * Writes data to the object referenced by handle.
908  *
909  * On error, the contents of the buffer that were to be modified are undefined.
910  */
911 int
912 i915_gem_pwrite_ioctl(struct drm_device *dev, void *data,
913                       struct drm_file *file_priv)
914 {
915         struct drm_i915_gem_pwrite *args = data;
916         struct drm_gem_object *obj;
917         struct drm_i915_gem_object *obj_priv;
918         int ret = 0;
919
920         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
921         if (obj == NULL)
922                 return -EBADF;
923         obj_priv = to_intel_bo(obj);
924
925         /* Bounds check destination.
926          *
927          * XXX: This could use review for overflow issues...
928          */
929         if (args->offset > obj->size || args->size > obj->size ||
930             args->offset + args->size > obj->size) {
931                 drm_gem_object_unreference_unlocked(obj);
932                 return -EINVAL;
933         }
934
935         /* We can only do the GTT pwrite on untiled buffers, as otherwise
936          * it would end up going through the fenced access, and we'll get
937          * different detiling behavior between reading and writing.
938          * pread/pwrite currently are reading and writing from the CPU
939          * perspective, requiring manual detiling by the client.
940          */
941         if (obj_priv->phys_obj)
942                 ret = i915_gem_phys_pwrite(dev, obj, args, file_priv);
943         else if (obj_priv->tiling_mode == I915_TILING_NONE &&
944                  dev->gtt_total != 0 &&
945                  obj->write_domain != I915_GEM_DOMAIN_CPU) {
946                 ret = i915_gem_gtt_pwrite_fast(dev, obj, args, file_priv);
947                 if (ret == -EFAULT) {
948                         ret = i915_gem_gtt_pwrite_slow(dev, obj, args,
949                                                        file_priv);
950                 }
951         } else if (i915_gem_object_needs_bit17_swizzle(obj)) {
952                 ret = i915_gem_shmem_pwrite_slow(dev, obj, args, file_priv);
953         } else {
954                 ret = i915_gem_shmem_pwrite_fast(dev, obj, args, file_priv);
955                 if (ret == -EFAULT) {
956                         ret = i915_gem_shmem_pwrite_slow(dev, obj, args,
957                                                          file_priv);
958                 }
959         }
960
961 #if WATCH_PWRITE
962         if (ret)
963                 DRM_INFO("pwrite failed %d\n", ret);
964 #endif
965
966         drm_gem_object_unreference_unlocked(obj);
967
968         return ret;
969 }
970
971 /**
972  * Called when user space prepares to use an object with the CPU, either
973  * through the mmap ioctl's mapping or a GTT mapping.
974  */
975 int
976 i915_gem_set_domain_ioctl(struct drm_device *dev, void *data,
977                           struct drm_file *file_priv)
978 {
979         struct drm_i915_private *dev_priv = dev->dev_private;
980         struct drm_i915_gem_set_domain *args = data;
981         struct drm_gem_object *obj;
982         struct drm_i915_gem_object *obj_priv;
983         uint32_t read_domains = args->read_domains;
984         uint32_t write_domain = args->write_domain;
985         int ret;
986
987         if (!(dev->driver->driver_features & DRIVER_GEM))
988                 return -ENODEV;
989
990         /* Only handle setting domains to types used by the CPU. */
991         if (write_domain & I915_GEM_GPU_DOMAINS)
992                 return -EINVAL;
993
994         if (read_domains & I915_GEM_GPU_DOMAINS)
995                 return -EINVAL;
996
997         /* Having something in the write domain implies it's in the read
998          * domain, and only that read domain.  Enforce that in the request.
999          */
1000         if (write_domain != 0 && read_domains != write_domain)
1001                 return -EINVAL;
1002
1003         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
1004         if (obj == NULL)
1005                 return -EBADF;
1006         obj_priv = to_intel_bo(obj);
1007
1008         mutex_lock(&dev->struct_mutex);
1009
1010         intel_mark_busy(dev, obj);
1011
1012 #if WATCH_BUF
1013         DRM_INFO("set_domain_ioctl %p(%zd), %08x %08x\n",
1014                  obj, obj->size, read_domains, write_domain);
1015 #endif
1016         if (read_domains & I915_GEM_DOMAIN_GTT) {
1017                 ret = i915_gem_object_set_to_gtt_domain(obj, write_domain != 0);
1018
1019                 /* Update the LRU on the fence for the CPU access that's
1020                  * about to occur.
1021                  */
1022                 if (obj_priv->fence_reg != I915_FENCE_REG_NONE) {
1023                         struct drm_i915_fence_reg *reg =
1024                                 &dev_priv->fence_regs[obj_priv->fence_reg];
1025                         list_move_tail(&reg->lru_list,
1026                                        &dev_priv->mm.fence_list);
1027                 }
1028
1029                 /* Silently promote "you're not bound, there was nothing to do"
1030                  * to success, since the client was just asking us to
1031                  * make sure everything was done.
1032                  */
1033                 if (ret == -EINVAL)
1034                         ret = 0;
1035         } else {
1036                 ret = i915_gem_object_set_to_cpu_domain(obj, write_domain != 0);
1037         }
1038
1039         drm_gem_object_unreference(obj);
1040         mutex_unlock(&dev->struct_mutex);
1041         return ret;
1042 }
1043
1044 /**
1045  * Called when user space has done writes to this buffer
1046  */
1047 int
1048 i915_gem_sw_finish_ioctl(struct drm_device *dev, void *data,
1049                       struct drm_file *file_priv)
1050 {
1051         struct drm_i915_gem_sw_finish *args = data;
1052         struct drm_gem_object *obj;
1053         struct drm_i915_gem_object *obj_priv;
1054         int ret = 0;
1055
1056         if (!(dev->driver->driver_features & DRIVER_GEM))
1057                 return -ENODEV;
1058
1059         mutex_lock(&dev->struct_mutex);
1060         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
1061         if (obj == NULL) {
1062                 mutex_unlock(&dev->struct_mutex);
1063                 return -EBADF;
1064         }
1065
1066 #if WATCH_BUF
1067         DRM_INFO("%s: sw_finish %d (%p %zd)\n",
1068                  __func__, args->handle, obj, obj->size);
1069 #endif
1070         obj_priv = to_intel_bo(obj);
1071
1072         /* Pinned buffers may be scanout, so flush the cache */
1073         if (obj_priv->pin_count)
1074                 i915_gem_object_flush_cpu_write_domain(obj);
1075
1076         drm_gem_object_unreference(obj);
1077         mutex_unlock(&dev->struct_mutex);
1078         return ret;
1079 }
1080
1081 /**
1082  * Maps the contents of an object, returning the address it is mapped
1083  * into.
1084  *
1085  * While the mapping holds a reference on the contents of the object, it doesn't
1086  * imply a ref on the object itself.
1087  */
1088 int
1089 i915_gem_mmap_ioctl(struct drm_device *dev, void *data,
1090                    struct drm_file *file_priv)
1091 {
1092         struct drm_i915_gem_mmap *args = data;
1093         struct drm_gem_object *obj;
1094         loff_t offset;
1095         unsigned long addr;
1096
1097         if (!(dev->driver->driver_features & DRIVER_GEM))
1098                 return -ENODEV;
1099
1100         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
1101         if (obj == NULL)
1102                 return -EBADF;
1103
1104         offset = args->offset;
1105
1106         down_write(&current->mm->mmap_sem);
1107         addr = do_mmap(obj->filp, 0, args->size,
1108                        PROT_READ | PROT_WRITE, MAP_SHARED,
1109                        args->offset);
1110         up_write(&current->mm->mmap_sem);
1111         drm_gem_object_unreference_unlocked(obj);
1112         if (IS_ERR((void *)addr))
1113                 return addr;
1114
1115         args->addr_ptr = (uint64_t) addr;
1116
1117         return 0;
1118 }
1119
1120 /**
1121  * i915_gem_fault - fault a page into the GTT
1122  * vma: VMA in question
1123  * vmf: fault info
1124  *
1125  * The fault handler is set up by drm_gem_mmap() when a object is GTT mapped
1126  * from userspace.  The fault handler takes care of binding the object to
1127  * the GTT (if needed), allocating and programming a fence register (again,
1128  * only if needed based on whether the old reg is still valid or the object
1129  * is tiled) and inserting a new PTE into the faulting process.
1130  *
1131  * Note that the faulting process may involve evicting existing objects
1132  * from the GTT and/or fence registers to make room.  So performance may
1133  * suffer if the GTT working set is large or there are few fence registers
1134  * left.
1135  */
1136 int i915_gem_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1137 {
1138         struct drm_gem_object *obj = vma->vm_private_data;
1139         struct drm_device *dev = obj->dev;
1140         struct drm_i915_private *dev_priv = dev->dev_private;
1141         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
1142         pgoff_t page_offset;
1143         unsigned long pfn;
1144         int ret = 0;
1145         bool write = !!(vmf->flags & FAULT_FLAG_WRITE);
1146
1147         /* We don't use vmf->pgoff since that has the fake offset */
1148         page_offset = ((unsigned long)vmf->virtual_address - vma->vm_start) >>
1149                 PAGE_SHIFT;
1150
1151         /* Now bind it into the GTT if needed */
1152         mutex_lock(&dev->struct_mutex);
1153         if (!obj_priv->gtt_space) {
1154                 ret = i915_gem_object_bind_to_gtt(obj, 0);
1155                 if (ret)
1156                         goto unlock;
1157
1158                 list_add_tail(&obj_priv->list, &dev_priv->mm.inactive_list);
1159
1160                 ret = i915_gem_object_set_to_gtt_domain(obj, write);
1161                 if (ret)
1162                         goto unlock;
1163         }
1164
1165         /* Need a new fence register? */
1166         if (obj_priv->tiling_mode != I915_TILING_NONE) {
1167                 ret = i915_gem_object_get_fence_reg(obj);
1168                 if (ret)
1169                         goto unlock;
1170         }
1171
1172         pfn = ((dev->agp->base + obj_priv->gtt_offset) >> PAGE_SHIFT) +
1173                 page_offset;
1174
1175         /* Finally, remap it using the new GTT offset */
1176         ret = vm_insert_pfn(vma, (unsigned long)vmf->virtual_address, pfn);
1177 unlock:
1178         mutex_unlock(&dev->struct_mutex);
1179
1180         switch (ret) {
1181         case 0:
1182         case -ERESTARTSYS:
1183                 return VM_FAULT_NOPAGE;
1184         case -ENOMEM:
1185         case -EAGAIN:
1186                 return VM_FAULT_OOM;
1187         default:
1188                 return VM_FAULT_SIGBUS;
1189         }
1190 }
1191
1192 /**
1193  * i915_gem_create_mmap_offset - create a fake mmap offset for an object
1194  * @obj: obj in question
1195  *
1196  * GEM memory mapping works by handing back to userspace a fake mmap offset
1197  * it can use in a subsequent mmap(2) call.  The DRM core code then looks
1198  * up the object based on the offset and sets up the various memory mapping
1199  * structures.
1200  *
1201  * This routine allocates and attaches a fake offset for @obj.
1202  */
1203 static int
1204 i915_gem_create_mmap_offset(struct drm_gem_object *obj)
1205 {
1206         struct drm_device *dev = obj->dev;
1207         struct drm_gem_mm *mm = dev->mm_private;
1208         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
1209         struct drm_map_list *list;
1210         struct drm_local_map *map;
1211         int ret = 0;
1212
1213         /* Set the object up for mmap'ing */
1214         list = &obj->map_list;
1215         list->map = kzalloc(sizeof(struct drm_map_list), GFP_KERNEL);
1216         if (!list->map)
1217                 return -ENOMEM;
1218
1219         map = list->map;
1220         map->type = _DRM_GEM;
1221         map->size = obj->size;
1222         map->handle = obj;
1223
1224         /* Get a DRM GEM mmap offset allocated... */
1225         list->file_offset_node = drm_mm_search_free(&mm->offset_manager,
1226                                                     obj->size / PAGE_SIZE, 0, 0);
1227         if (!list->file_offset_node) {
1228                 DRM_ERROR("failed to allocate offset for bo %d\n", obj->name);
1229                 ret = -ENOMEM;
1230                 goto out_free_list;
1231         }
1232
1233         list->file_offset_node = drm_mm_get_block(list->file_offset_node,
1234                                                   obj->size / PAGE_SIZE, 0);
1235         if (!list->file_offset_node) {
1236                 ret = -ENOMEM;
1237                 goto out_free_list;
1238         }
1239
1240         list->hash.key = list->file_offset_node->start;
1241         if (drm_ht_insert_item(&mm->offset_hash, &list->hash)) {
1242                 DRM_ERROR("failed to add to map hash\n");
1243                 ret = -ENOMEM;
1244                 goto out_free_mm;
1245         }
1246
1247         /* By now we should be all set, any drm_mmap request on the offset
1248          * below will get to our mmap & fault handler */
1249         obj_priv->mmap_offset = ((uint64_t) list->hash.key) << PAGE_SHIFT;
1250
1251         return 0;
1252
1253 out_free_mm:
1254         drm_mm_put_block(list->file_offset_node);
1255 out_free_list:
1256         kfree(list->map);
1257
1258         return ret;
1259 }
1260
1261 /**
1262  * i915_gem_release_mmap - remove physical page mappings
1263  * @obj: obj in question
1264  *
1265  * Preserve the reservation of the mmapping with the DRM core code, but
1266  * relinquish ownership of the pages back to the system.
1267  *
1268  * It is vital that we remove the page mapping if we have mapped a tiled
1269  * object through the GTT and then lose the fence register due to
1270  * resource pressure. Similarly if the object has been moved out of the
1271  * aperture, than pages mapped into userspace must be revoked. Removing the
1272  * mapping will then trigger a page fault on the next user access, allowing
1273  * fixup by i915_gem_fault().
1274  */
1275 void
1276 i915_gem_release_mmap(struct drm_gem_object *obj)
1277 {
1278         struct drm_device *dev = obj->dev;
1279         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
1280
1281         if (dev->dev_mapping)
1282                 unmap_mapping_range(dev->dev_mapping,
1283                                     obj_priv->mmap_offset, obj->size, 1);
1284 }
1285
1286 static void
1287 i915_gem_free_mmap_offset(struct drm_gem_object *obj)
1288 {
1289         struct drm_device *dev = obj->dev;
1290         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
1291         struct drm_gem_mm *mm = dev->mm_private;
1292         struct drm_map_list *list;
1293
1294         list = &obj->map_list;
1295         drm_ht_remove_item(&mm->offset_hash, &list->hash);
1296
1297         if (list->file_offset_node) {
1298                 drm_mm_put_block(list->file_offset_node);
1299                 list->file_offset_node = NULL;
1300         }
1301
1302         if (list->map) {
1303                 kfree(list->map);
1304                 list->map = NULL;
1305         }
1306
1307         obj_priv->mmap_offset = 0;
1308 }
1309
1310 /**
1311  * i915_gem_get_gtt_alignment - return required GTT alignment for an object
1312  * @obj: object to check
1313  *
1314  * Return the required GTT alignment for an object, taking into account
1315  * potential fence register mapping if needed.
1316  */
1317 static uint32_t
1318 i915_gem_get_gtt_alignment(struct drm_gem_object *obj)
1319 {
1320         struct drm_device *dev = obj->dev;
1321         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
1322         int start, i;
1323
1324         /*
1325          * Minimum alignment is 4k (GTT page size), but might be greater
1326          * if a fence register is needed for the object.
1327          */
1328         if (IS_I965G(dev) || obj_priv->tiling_mode == I915_TILING_NONE)
1329                 return 4096;
1330
1331         /*
1332          * Previous chips need to be aligned to the size of the smallest
1333          * fence register that can contain the object.
1334          */
1335         if (IS_I9XX(dev))
1336                 start = 1024*1024;
1337         else
1338                 start = 512*1024;
1339
1340         for (i = start; i < obj->size; i <<= 1)
1341                 ;
1342
1343         return i;
1344 }
1345
1346 /**
1347  * i915_gem_mmap_gtt_ioctl - prepare an object for GTT mmap'ing
1348  * @dev: DRM device
1349  * @data: GTT mapping ioctl data
1350  * @file_priv: GEM object info
1351  *
1352  * Simply returns the fake offset to userspace so it can mmap it.
1353  * The mmap call will end up in drm_gem_mmap(), which will set things
1354  * up so we can get faults in the handler above.
1355  *
1356  * The fault handler will take care of binding the object into the GTT
1357  * (since it may have been evicted to make room for something), allocating
1358  * a fence register, and mapping the appropriate aperture address into
1359  * userspace.
1360  */
1361 int
1362 i915_gem_mmap_gtt_ioctl(struct drm_device *dev, void *data,
1363                         struct drm_file *file_priv)
1364 {
1365         struct drm_i915_gem_mmap_gtt *args = data;
1366         struct drm_i915_private *dev_priv = dev->dev_private;
1367         struct drm_gem_object *obj;
1368         struct drm_i915_gem_object *obj_priv;
1369         int ret;
1370
1371         if (!(dev->driver->driver_features & DRIVER_GEM))
1372                 return -ENODEV;
1373
1374         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
1375         if (obj == NULL)
1376                 return -EBADF;
1377
1378         mutex_lock(&dev->struct_mutex);
1379
1380         obj_priv = to_intel_bo(obj);
1381
1382         if (obj_priv->madv != I915_MADV_WILLNEED) {
1383                 DRM_ERROR("Attempting to mmap a purgeable buffer\n");
1384                 drm_gem_object_unreference(obj);
1385                 mutex_unlock(&dev->struct_mutex);
1386                 return -EINVAL;
1387         }
1388
1389
1390         if (!obj_priv->mmap_offset) {
1391                 ret = i915_gem_create_mmap_offset(obj);
1392                 if (ret) {
1393                         drm_gem_object_unreference(obj);
1394                         mutex_unlock(&dev->struct_mutex);
1395                         return ret;
1396                 }
1397         }
1398
1399         args->offset = obj_priv->mmap_offset;
1400
1401         /*
1402          * Pull it into the GTT so that we have a page list (makes the
1403          * initial fault faster and any subsequent flushing possible).
1404          */
1405         if (!obj_priv->agp_mem) {
1406                 ret = i915_gem_object_bind_to_gtt(obj, 0);
1407                 if (ret) {
1408                         drm_gem_object_unreference(obj);
1409                         mutex_unlock(&dev->struct_mutex);
1410                         return ret;
1411                 }
1412                 list_add_tail(&obj_priv->list, &dev_priv->mm.inactive_list);
1413         }
1414
1415         drm_gem_object_unreference(obj);
1416         mutex_unlock(&dev->struct_mutex);
1417
1418         return 0;
1419 }
1420
1421 void
1422 i915_gem_object_put_pages(struct drm_gem_object *obj)
1423 {
1424         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
1425         int page_count = obj->size / PAGE_SIZE;
1426         int i;
1427
1428         BUG_ON(obj_priv->pages_refcount == 0);
1429         BUG_ON(obj_priv->madv == __I915_MADV_PURGED);
1430
1431         if (--obj_priv->pages_refcount != 0)
1432                 return;
1433
1434         if (obj_priv->tiling_mode != I915_TILING_NONE)
1435                 i915_gem_object_save_bit_17_swizzle(obj);
1436
1437         if (obj_priv->madv == I915_MADV_DONTNEED)
1438                 obj_priv->dirty = 0;
1439
1440         for (i = 0; i < page_count; i++) {
1441                 if (obj_priv->dirty)
1442                         set_page_dirty(obj_priv->pages[i]);
1443
1444                 if (obj_priv->madv == I915_MADV_WILLNEED)
1445                         mark_page_accessed(obj_priv->pages[i]);
1446
1447                 page_cache_release(obj_priv->pages[i]);
1448         }
1449         obj_priv->dirty = 0;
1450
1451         drm_free_large(obj_priv->pages);
1452         obj_priv->pages = NULL;
1453 }
1454
1455 static void
1456 i915_gem_object_move_to_active(struct drm_gem_object *obj, uint32_t seqno,
1457                                struct intel_ring_buffer *ring)
1458 {
1459         struct drm_device *dev = obj->dev;
1460         drm_i915_private_t *dev_priv = dev->dev_private;
1461         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
1462         BUG_ON(ring == NULL);
1463         obj_priv->ring = ring;
1464
1465         /* Add a reference if we're newly entering the active list. */
1466         if (!obj_priv->active) {
1467                 drm_gem_object_reference(obj);
1468                 obj_priv->active = 1;
1469         }
1470         /* Move from whatever list we were on to the tail of execution. */
1471         spin_lock(&dev_priv->mm.active_list_lock);
1472         list_move_tail(&obj_priv->list, &ring->active_list);
1473         spin_unlock(&dev_priv->mm.active_list_lock);
1474         obj_priv->last_rendering_seqno = seqno;
1475 }
1476
1477 static void
1478 i915_gem_object_move_to_flushing(struct drm_gem_object *obj)
1479 {
1480         struct drm_device *dev = obj->dev;
1481         drm_i915_private_t *dev_priv = dev->dev_private;
1482         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
1483
1484         BUG_ON(!obj_priv->active);
1485         list_move_tail(&obj_priv->list, &dev_priv->mm.flushing_list);
1486         obj_priv->last_rendering_seqno = 0;
1487 }
1488
1489 /* Immediately discard the backing storage */
1490 static void
1491 i915_gem_object_truncate(struct drm_gem_object *obj)
1492 {
1493         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
1494         struct inode *inode;
1495
1496         inode = obj->filp->f_path.dentry->d_inode;
1497         if (inode->i_op->truncate)
1498                 inode->i_op->truncate (inode);
1499
1500         obj_priv->madv = __I915_MADV_PURGED;
1501 }
1502
1503 static inline int
1504 i915_gem_object_is_purgeable(struct drm_i915_gem_object *obj_priv)
1505 {
1506         return obj_priv->madv == I915_MADV_DONTNEED;
1507 }
1508
1509 static void
1510 i915_gem_object_move_to_inactive(struct drm_gem_object *obj)
1511 {
1512         struct drm_device *dev = obj->dev;
1513         drm_i915_private_t *dev_priv = dev->dev_private;
1514         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
1515
1516         i915_verify_inactive(dev, __FILE__, __LINE__);
1517         if (obj_priv->pin_count != 0)
1518                 list_del_init(&obj_priv->list);
1519         else
1520                 list_move_tail(&obj_priv->list, &dev_priv->mm.inactive_list);
1521
1522         BUG_ON(!list_empty(&obj_priv->gpu_write_list));
1523
1524         obj_priv->last_rendering_seqno = 0;
1525         obj_priv->ring = NULL;
1526         if (obj_priv->active) {
1527                 obj_priv->active = 0;
1528                 drm_gem_object_unreference(obj);
1529         }
1530         i915_verify_inactive(dev, __FILE__, __LINE__);
1531 }
1532
1533 static void
1534 i915_gem_process_flushing_list(struct drm_device *dev,
1535                                uint32_t flush_domains, uint32_t seqno,
1536                                struct intel_ring_buffer *ring)
1537 {
1538         drm_i915_private_t *dev_priv = dev->dev_private;
1539         struct drm_i915_gem_object *obj_priv, *next;
1540
1541         list_for_each_entry_safe(obj_priv, next,
1542                                  &dev_priv->mm.gpu_write_list,
1543                                  gpu_write_list) {
1544                 struct drm_gem_object *obj = &obj_priv->base;
1545
1546                 if ((obj->write_domain & flush_domains) ==
1547                     obj->write_domain &&
1548                     obj_priv->ring->ring_flag == ring->ring_flag) {
1549                         uint32_t old_write_domain = obj->write_domain;
1550
1551                         obj->write_domain = 0;
1552                         list_del_init(&obj_priv->gpu_write_list);
1553                         i915_gem_object_move_to_active(obj, seqno, ring);
1554
1555                         /* update the fence lru list */
1556                         if (obj_priv->fence_reg != I915_FENCE_REG_NONE) {
1557                                 struct drm_i915_fence_reg *reg =
1558                                         &dev_priv->fence_regs[obj_priv->fence_reg];
1559                                 list_move_tail(&reg->lru_list,
1560                                                 &dev_priv->mm.fence_list);
1561                         }
1562
1563                         trace_i915_gem_object_change_domain(obj,
1564                                                             obj->read_domains,
1565                                                             old_write_domain);
1566                 }
1567         }
1568 }
1569
1570 uint32_t
1571 i915_add_request(struct drm_device *dev, struct drm_file *file_priv,
1572                  uint32_t flush_domains, struct intel_ring_buffer *ring)
1573 {
1574         drm_i915_private_t *dev_priv = dev->dev_private;
1575         struct drm_i915_file_private *i915_file_priv = NULL;
1576         struct drm_i915_gem_request *request;
1577         uint32_t seqno;
1578         int was_empty;
1579
1580         if (file_priv != NULL)
1581                 i915_file_priv = file_priv->driver_priv;
1582
1583         request = kzalloc(sizeof(*request), GFP_KERNEL);
1584         if (request == NULL)
1585                 return 0;
1586
1587         seqno = ring->add_request(dev, ring, file_priv, flush_domains);
1588
1589         request->seqno = seqno;
1590         request->ring = ring;
1591         request->emitted_jiffies = jiffies;
1592         was_empty = list_empty(&ring->request_list);
1593         list_add_tail(&request->list, &ring->request_list);
1594
1595         if (i915_file_priv) {
1596                 list_add_tail(&request->client_list,
1597                               &i915_file_priv->mm.request_list);
1598         } else {
1599                 INIT_LIST_HEAD(&request->client_list);
1600         }
1601
1602         /* Associate any objects on the flushing list matching the write
1603          * domain we're flushing with our flush.
1604          */
1605         if (flush_domains != 0) 
1606                 i915_gem_process_flushing_list(dev, flush_domains, seqno, ring);
1607
1608         if (!dev_priv->mm.suspended) {
1609                 mod_timer(&dev_priv->hangcheck_timer, jiffies + DRM_I915_HANGCHECK_PERIOD);
1610                 if (was_empty)
1611                         queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work, HZ);
1612         }
1613         return seqno;
1614 }
1615
1616 /**
1617  * Command execution barrier
1618  *
1619  * Ensures that all commands in the ring are finished
1620  * before signalling the CPU
1621  */
1622 static uint32_t
1623 i915_retire_commands(struct drm_device *dev, struct intel_ring_buffer *ring)
1624 {
1625         uint32_t flush_domains = 0;
1626
1627         /* The sampler always gets flushed on i965 (sigh) */
1628         if (IS_I965G(dev))
1629                 flush_domains |= I915_GEM_DOMAIN_SAMPLER;
1630
1631         ring->flush(dev, ring,
1632                         I915_GEM_DOMAIN_COMMAND, flush_domains);
1633         return flush_domains;
1634 }
1635
1636 /**
1637  * Moves buffers associated only with the given active seqno from the active
1638  * to inactive list, potentially freeing them.
1639  */
1640 static void
1641 i915_gem_retire_request(struct drm_device *dev,
1642                         struct drm_i915_gem_request *request)
1643 {
1644         drm_i915_private_t *dev_priv = dev->dev_private;
1645
1646         trace_i915_gem_request_retire(dev, request->seqno);
1647
1648         /* Move any buffers on the active list that are no longer referenced
1649          * by the ringbuffer to the flushing/inactive lists as appropriate.
1650          */
1651         spin_lock(&dev_priv->mm.active_list_lock);
1652         while (!list_empty(&request->ring->active_list)) {
1653                 struct drm_gem_object *obj;
1654                 struct drm_i915_gem_object *obj_priv;
1655
1656                 obj_priv = list_first_entry(&request->ring->active_list,
1657                                             struct drm_i915_gem_object,
1658                                             list);
1659                 obj = &obj_priv->base;
1660
1661                 /* If the seqno being retired doesn't match the oldest in the
1662                  * list, then the oldest in the list must still be newer than
1663                  * this seqno.
1664                  */
1665                 if (obj_priv->last_rendering_seqno != request->seqno)
1666                         goto out;
1667
1668 #if WATCH_LRU
1669                 DRM_INFO("%s: retire %d moves to inactive list %p\n",
1670                          __func__, request->seqno, obj);
1671 #endif
1672
1673                 if (obj->write_domain != 0)
1674                         i915_gem_object_move_to_flushing(obj);
1675                 else {
1676                         /* Take a reference on the object so it won't be
1677                          * freed while the spinlock is held.  The list
1678                          * protection for this spinlock is safe when breaking
1679                          * the lock like this since the next thing we do
1680                          * is just get the head of the list again.
1681                          */
1682                         drm_gem_object_reference(obj);
1683                         i915_gem_object_move_to_inactive(obj);
1684                         spin_unlock(&dev_priv->mm.active_list_lock);
1685                         drm_gem_object_unreference(obj);
1686                         spin_lock(&dev_priv->mm.active_list_lock);
1687                 }
1688         }
1689 out:
1690         spin_unlock(&dev_priv->mm.active_list_lock);
1691 }
1692
1693 /**
1694  * Returns true if seq1 is later than seq2.
1695  */
1696 bool
1697 i915_seqno_passed(uint32_t seq1, uint32_t seq2)
1698 {
1699         return (int32_t)(seq1 - seq2) >= 0;
1700 }
1701
1702 uint32_t
1703 i915_get_gem_seqno(struct drm_device *dev,
1704                    struct intel_ring_buffer *ring)
1705 {
1706         return ring->get_gem_seqno(dev, ring);
1707 }
1708
1709 /**
1710  * This function clears the request list as sequence numbers are passed.
1711  */
1712 void
1713 i915_gem_retire_requests(struct drm_device *dev,
1714                 struct intel_ring_buffer *ring)
1715 {
1716         drm_i915_private_t *dev_priv = dev->dev_private;
1717         uint32_t seqno;
1718
1719         if (!ring->status_page.page_addr
1720                         || list_empty(&ring->request_list))
1721                 return;
1722
1723         seqno = i915_get_gem_seqno(dev, ring);
1724
1725         while (!list_empty(&ring->request_list)) {
1726                 struct drm_i915_gem_request *request;
1727                 uint32_t retiring_seqno;
1728
1729                 request = list_first_entry(&ring->request_list,
1730                                            struct drm_i915_gem_request,
1731                                            list);
1732                 retiring_seqno = request->seqno;
1733
1734                 if (i915_seqno_passed(seqno, retiring_seqno) ||
1735                     atomic_read(&dev_priv->mm.wedged)) {
1736                         i915_gem_retire_request(dev, request);
1737
1738                         list_del(&request->list);
1739                         list_del(&request->client_list);
1740                         kfree(request);
1741                 } else
1742                         break;
1743         }
1744
1745         if (unlikely (dev_priv->trace_irq_seqno &&
1746                       i915_seqno_passed(dev_priv->trace_irq_seqno, seqno))) {
1747
1748                 ring->user_irq_put(dev, ring);
1749                 dev_priv->trace_irq_seqno = 0;
1750         }
1751 }
1752
1753 void
1754 i915_gem_retire_work_handler(struct work_struct *work)
1755 {
1756         drm_i915_private_t *dev_priv;
1757         struct drm_device *dev;
1758
1759         dev_priv = container_of(work, drm_i915_private_t,
1760                                 mm.retire_work.work);
1761         dev = dev_priv->dev;
1762
1763         mutex_lock(&dev->struct_mutex);
1764         i915_gem_retire_requests(dev, &dev_priv->render_ring);
1765
1766         if (HAS_BSD(dev))
1767                 i915_gem_retire_requests(dev, &dev_priv->bsd_ring);
1768
1769         if (!dev_priv->mm.suspended &&
1770                 (!list_empty(&dev_priv->render_ring.request_list) ||
1771                         (HAS_BSD(dev) &&
1772                          !list_empty(&dev_priv->bsd_ring.request_list))))
1773                 queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work, HZ);
1774         mutex_unlock(&dev->struct_mutex);
1775 }
1776
1777 int
1778 i915_do_wait_request(struct drm_device *dev, uint32_t seqno,
1779                 int interruptible, struct intel_ring_buffer *ring)
1780 {
1781         drm_i915_private_t *dev_priv = dev->dev_private;
1782         u32 ier;
1783         int ret = 0;
1784
1785         BUG_ON(seqno == 0);
1786
1787         if (atomic_read(&dev_priv->mm.wedged))
1788                 return -EIO;
1789
1790         if (!i915_seqno_passed(ring->get_gem_seqno(dev, ring), seqno)) {
1791                 if (HAS_PCH_SPLIT(dev))
1792                         ier = I915_READ(DEIER) | I915_READ(GTIER);
1793                 else
1794                         ier = I915_READ(IER);
1795                 if (!ier) {
1796                         DRM_ERROR("something (likely vbetool) disabled "
1797                                   "interrupts, re-enabling\n");
1798                         i915_driver_irq_preinstall(dev);
1799                         i915_driver_irq_postinstall(dev);
1800                 }
1801
1802                 trace_i915_gem_request_wait_begin(dev, seqno);
1803
1804                 ring->waiting_gem_seqno = seqno;
1805                 ring->user_irq_get(dev, ring);
1806                 if (interruptible)
1807                         ret = wait_event_interruptible(ring->irq_queue,
1808                                 i915_seqno_passed(
1809                                         ring->get_gem_seqno(dev, ring), seqno)
1810                                 || atomic_read(&dev_priv->mm.wedged));
1811                 else
1812                         wait_event(ring->irq_queue,
1813                                 i915_seqno_passed(
1814                                         ring->get_gem_seqno(dev, ring), seqno)
1815                                 || atomic_read(&dev_priv->mm.wedged));
1816
1817                 ring->user_irq_put(dev, ring);
1818                 ring->waiting_gem_seqno = 0;
1819
1820                 trace_i915_gem_request_wait_end(dev, seqno);
1821         }
1822         if (atomic_read(&dev_priv->mm.wedged))
1823                 ret = -EIO;
1824
1825         if (ret && ret != -ERESTARTSYS)
1826                 DRM_ERROR("%s returns %d (awaiting %d at %d)\n",
1827                           __func__, ret, seqno, ring->get_gem_seqno(dev, ring));
1828
1829         /* Directly dispatch request retiring.  While we have the work queue
1830          * to handle this, the waiter on a request often wants an associated
1831          * buffer to have made it to the inactive list, and we would need
1832          * a separate wait queue to handle that.
1833          */
1834         if (ret == 0)
1835                 i915_gem_retire_requests(dev, ring);
1836
1837         return ret;
1838 }
1839
1840 /**
1841  * Waits for a sequence number to be signaled, and cleans up the
1842  * request and object lists appropriately for that event.
1843  */
1844 static int
1845 i915_wait_request(struct drm_device *dev, uint32_t seqno,
1846                 struct intel_ring_buffer *ring)
1847 {
1848         return i915_do_wait_request(dev, seqno, 1, ring);
1849 }
1850
1851 static void
1852 i915_gem_flush(struct drm_device *dev,
1853                uint32_t invalidate_domains,
1854                uint32_t flush_domains)
1855 {
1856         drm_i915_private_t *dev_priv = dev->dev_private;
1857         if (flush_domains & I915_GEM_DOMAIN_CPU)
1858                 drm_agp_chipset_flush(dev);
1859         dev_priv->render_ring.flush(dev, &dev_priv->render_ring,
1860                         invalidate_domains,
1861                         flush_domains);
1862
1863         if (HAS_BSD(dev))
1864                 dev_priv->bsd_ring.flush(dev, &dev_priv->bsd_ring,
1865                                 invalidate_domains,
1866                                 flush_domains);
1867 }
1868
1869 static void
1870 i915_gem_flush_ring(struct drm_device *dev,
1871                uint32_t invalidate_domains,
1872                uint32_t flush_domains,
1873                struct intel_ring_buffer *ring)
1874 {
1875         if (flush_domains & I915_GEM_DOMAIN_CPU)
1876                 drm_agp_chipset_flush(dev);
1877         ring->flush(dev, ring,
1878                         invalidate_domains,
1879                         flush_domains);
1880 }
1881
1882 /**
1883  * Ensures that all rendering to the object has completed and the object is
1884  * safe to unbind from the GTT or access from the CPU.
1885  */
1886 static int
1887 i915_gem_object_wait_rendering(struct drm_gem_object *obj)
1888 {
1889         struct drm_device *dev = obj->dev;
1890         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
1891         int ret;
1892
1893         /* This function only exists to support waiting for existing rendering,
1894          * not for emitting required flushes.
1895          */
1896         BUG_ON((obj->write_domain & I915_GEM_GPU_DOMAINS) != 0);
1897
1898         /* If there is rendering queued on the buffer being evicted, wait for
1899          * it.
1900          */
1901         if (obj_priv->active) {
1902 #if WATCH_BUF
1903                 DRM_INFO("%s: object %p wait for seqno %08x\n",
1904                           __func__, obj, obj_priv->last_rendering_seqno);
1905 #endif
1906                 ret = i915_wait_request(dev,
1907                                 obj_priv->last_rendering_seqno, obj_priv->ring);
1908                 if (ret != 0)
1909                         return ret;
1910         }
1911
1912         return 0;
1913 }
1914
1915 /**
1916  * Unbinds an object from the GTT aperture.
1917  */
1918 int
1919 i915_gem_object_unbind(struct drm_gem_object *obj)
1920 {
1921         struct drm_device *dev = obj->dev;
1922         drm_i915_private_t *dev_priv = dev->dev_private;
1923         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
1924         int ret = 0;
1925
1926 #if WATCH_BUF
1927         DRM_INFO("%s:%d %p\n", __func__, __LINE__, obj);
1928         DRM_INFO("gtt_space %p\n", obj_priv->gtt_space);
1929 #endif
1930         if (obj_priv->gtt_space == NULL)
1931                 return 0;
1932
1933         if (obj_priv->pin_count != 0) {
1934                 DRM_ERROR("Attempting to unbind pinned buffer\n");
1935                 return -EINVAL;
1936         }
1937
1938         /* blow away mappings if mapped through GTT */
1939         i915_gem_release_mmap(obj);
1940
1941         /* Move the object to the CPU domain to ensure that
1942          * any possible CPU writes while it's not in the GTT
1943          * are flushed when we go to remap it. This will
1944          * also ensure that all pending GPU writes are finished
1945          * before we unbind.
1946          */
1947         ret = i915_gem_object_set_to_cpu_domain(obj, 1);
1948         if (ret) {
1949                 if (ret != -ERESTARTSYS)
1950                         DRM_ERROR("set_domain failed: %d\n", ret);
1951                 return ret;
1952         }
1953
1954         BUG_ON(obj_priv->active);
1955
1956         /* release the fence reg _after_ flushing */
1957         if (obj_priv->fence_reg != I915_FENCE_REG_NONE)
1958                 i915_gem_clear_fence_reg(obj);
1959
1960         if (obj_priv->agp_mem != NULL) {
1961                 drm_unbind_agp(obj_priv->agp_mem);
1962                 drm_free_agp(obj_priv->agp_mem, obj->size / PAGE_SIZE);
1963                 obj_priv->agp_mem = NULL;
1964         }
1965
1966         i915_gem_object_put_pages(obj);
1967         BUG_ON(obj_priv->pages_refcount);
1968
1969         if (obj_priv->gtt_space) {
1970                 atomic_dec(&dev->gtt_count);
1971                 atomic_sub(obj->size, &dev->gtt_memory);
1972
1973                 drm_mm_put_block(obj_priv->gtt_space);
1974                 obj_priv->gtt_space = NULL;
1975         }
1976
1977         /* Remove ourselves from the LRU list if present. */
1978         spin_lock(&dev_priv->mm.active_list_lock);
1979         if (!list_empty(&obj_priv->list))
1980                 list_del_init(&obj_priv->list);
1981         spin_unlock(&dev_priv->mm.active_list_lock);
1982
1983         if (i915_gem_object_is_purgeable(obj_priv))
1984                 i915_gem_object_truncate(obj);
1985
1986         trace_i915_gem_object_unbind(obj);
1987
1988         return 0;
1989 }
1990
1991 static struct drm_gem_object *
1992 i915_gem_find_inactive_object(struct drm_device *dev, int min_size)
1993 {
1994         drm_i915_private_t *dev_priv = dev->dev_private;
1995         struct drm_i915_gem_object *obj_priv;
1996         struct drm_gem_object *best = NULL;
1997         struct drm_gem_object *first = NULL;
1998
1999         /* Try to find the smallest clean object */
2000         list_for_each_entry(obj_priv, &dev_priv->mm.inactive_list, list) {
2001                 struct drm_gem_object *obj = &obj_priv->base;
2002                 if (obj->size >= min_size) {
2003                         if ((!obj_priv->dirty ||
2004                              i915_gem_object_is_purgeable(obj_priv)) &&
2005                             (!best || obj->size < best->size)) {
2006                                 best = obj;
2007                                 if (best->size == min_size)
2008                                         return best;
2009                         }
2010                         if (!first)
2011                             first = obj;
2012                 }
2013         }
2014
2015         return best ? best : first;
2016 }
2017
2018 static int
2019 i915_gpu_idle(struct drm_device *dev)
2020 {
2021         drm_i915_private_t *dev_priv = dev->dev_private;
2022         bool lists_empty;
2023         uint32_t seqno1, seqno2;
2024         int ret;
2025
2026         spin_lock(&dev_priv->mm.active_list_lock);
2027         lists_empty = (list_empty(&dev_priv->mm.flushing_list) &&
2028                        list_empty(&dev_priv->render_ring.active_list) &&
2029                        (!HAS_BSD(dev) ||
2030                         list_empty(&dev_priv->bsd_ring.active_list)));
2031         spin_unlock(&dev_priv->mm.active_list_lock);
2032
2033         if (lists_empty)
2034                 return 0;
2035
2036         /* Flush everything onto the inactive list. */
2037         i915_gem_flush(dev, I915_GEM_GPU_DOMAINS, I915_GEM_GPU_DOMAINS);
2038         seqno1 = i915_add_request(dev, NULL, I915_GEM_GPU_DOMAINS,
2039                         &dev_priv->render_ring);
2040         if (seqno1 == 0)
2041                 return -ENOMEM;
2042         ret = i915_wait_request(dev, seqno1, &dev_priv->render_ring);
2043
2044         if (HAS_BSD(dev)) {
2045                 seqno2 = i915_add_request(dev, NULL, I915_GEM_GPU_DOMAINS,
2046                                 &dev_priv->bsd_ring);
2047                 if (seqno2 == 0)
2048                         return -ENOMEM;
2049
2050                 ret = i915_wait_request(dev, seqno2, &dev_priv->bsd_ring);
2051                 if (ret)
2052                         return ret;
2053         }
2054
2055
2056         return ret;
2057 }
2058
2059 static int
2060 i915_gem_evict_everything(struct drm_device *dev)
2061 {
2062         drm_i915_private_t *dev_priv = dev->dev_private;
2063         int ret;
2064         bool lists_empty;
2065
2066         spin_lock(&dev_priv->mm.active_list_lock);
2067         lists_empty = (list_empty(&dev_priv->mm.inactive_list) &&
2068                        list_empty(&dev_priv->mm.flushing_list) &&
2069                        list_empty(&dev_priv->render_ring.active_list) &&
2070                        (!HAS_BSD(dev)
2071                         || list_empty(&dev_priv->bsd_ring.active_list)));
2072         spin_unlock(&dev_priv->mm.active_list_lock);
2073
2074         if (lists_empty)
2075                 return -ENOSPC;
2076
2077         /* Flush everything (on to the inactive lists) and evict */
2078         ret = i915_gpu_idle(dev);
2079         if (ret)
2080                 return ret;
2081
2082         BUG_ON(!list_empty(&dev_priv->mm.flushing_list));
2083
2084         ret = i915_gem_evict_from_inactive_list(dev);
2085         if (ret)
2086                 return ret;
2087
2088         spin_lock(&dev_priv->mm.active_list_lock);
2089         lists_empty = (list_empty(&dev_priv->mm.inactive_list) &&
2090                        list_empty(&dev_priv->mm.flushing_list) &&
2091                        list_empty(&dev_priv->render_ring.active_list) &&
2092                        (!HAS_BSD(dev)
2093                         || list_empty(&dev_priv->bsd_ring.active_list)));
2094         spin_unlock(&dev_priv->mm.active_list_lock);
2095         BUG_ON(!lists_empty);
2096
2097         return 0;
2098 }
2099
2100 static int
2101 i915_gem_evict_something(struct drm_device *dev, int min_size)
2102 {
2103         drm_i915_private_t *dev_priv = dev->dev_private;
2104         struct drm_gem_object *obj;
2105         int ret;
2106
2107         struct intel_ring_buffer *render_ring = &dev_priv->render_ring;
2108         struct intel_ring_buffer *bsd_ring = &dev_priv->bsd_ring;
2109         for (;;) {
2110                 i915_gem_retire_requests(dev, render_ring);
2111
2112                 if (HAS_BSD(dev))
2113                         i915_gem_retire_requests(dev, bsd_ring);
2114
2115                 /* If there's an inactive buffer available now, grab it
2116                  * and be done.
2117                  */
2118                 obj = i915_gem_find_inactive_object(dev, min_size);
2119                 if (obj) {
2120                         struct drm_i915_gem_object *obj_priv;
2121
2122 #if WATCH_LRU
2123                         DRM_INFO("%s: evicting %p\n", __func__, obj);
2124 #endif
2125                         obj_priv = to_intel_bo(obj);
2126                         BUG_ON(obj_priv->pin_count != 0);
2127                         BUG_ON(obj_priv->active);
2128
2129                         /* Wait on the rendering and unbind the buffer. */
2130                         return i915_gem_object_unbind(obj);
2131                 }
2132
2133                 /* If we didn't get anything, but the ring is still processing
2134                  * things, wait for the next to finish and hopefully leave us
2135                  * a buffer to evict.
2136                  */
2137                 if (!list_empty(&render_ring->request_list)) {
2138                         struct drm_i915_gem_request *request;
2139
2140                         request = list_first_entry(&render_ring->request_list,
2141                                                    struct drm_i915_gem_request,
2142                                                    list);
2143
2144                         ret = i915_wait_request(dev,
2145                                         request->seqno, request->ring);
2146                         if (ret)
2147                                 return ret;
2148
2149                         continue;
2150                 }
2151
2152                 if (HAS_BSD(dev) && !list_empty(&bsd_ring->request_list)) {
2153                         struct drm_i915_gem_request *request;
2154
2155                         request = list_first_entry(&bsd_ring->request_list,
2156                                                    struct drm_i915_gem_request,
2157                                                    list);
2158
2159                         ret = i915_wait_request(dev,
2160                                         request->seqno, request->ring);
2161                         if (ret)
2162                                 return ret;
2163
2164                         continue;
2165                 }
2166
2167                 /* If we didn't have anything on the request list but there
2168                  * are buffers awaiting a flush, emit one and try again.
2169                  * When we wait on it, those buffers waiting for that flush
2170                  * will get moved to inactive.
2171                  */
2172                 if (!list_empty(&dev_priv->mm.flushing_list)) {
2173                         struct drm_i915_gem_object *obj_priv;
2174
2175                         /* Find an object that we can immediately reuse */
2176                         list_for_each_entry(obj_priv, &dev_priv->mm.flushing_list, list) {
2177                                 obj = &obj_priv->base;
2178                                 if (obj->size >= min_size)
2179                                         break;
2180
2181                                 obj = NULL;
2182                         }
2183
2184                         if (obj != NULL) {
2185                                 uint32_t seqno;
2186
2187                                 i915_gem_flush_ring(dev,
2188                                                obj->write_domain,
2189                                                obj->write_domain,
2190                                                obj_priv->ring);
2191                                 seqno = i915_add_request(dev, NULL,
2192                                                 obj->write_domain,
2193                                                 obj_priv->ring);
2194                                 if (seqno == 0)
2195                                         return -ENOMEM;
2196                                 continue;
2197                         }
2198                 }
2199
2200                 /* If we didn't do any of the above, there's no single buffer
2201                  * large enough to swap out for the new one, so just evict
2202                  * everything and start again. (This should be rare.)
2203                  */
2204                 if (!list_empty (&dev_priv->mm.inactive_list))
2205                         return i915_gem_evict_from_inactive_list(dev);
2206                 else
2207                         return i915_gem_evict_everything(dev);
2208         }
2209 }
2210
2211 int
2212 i915_gem_object_get_pages(struct drm_gem_object *obj,
2213                           gfp_t gfpmask)
2214 {
2215         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2216         int page_count, i;
2217         struct address_space *mapping;
2218         struct inode *inode;
2219         struct page *page;
2220
2221         BUG_ON(obj_priv->pages_refcount
2222                         == DRM_I915_GEM_OBJECT_MAX_PAGES_REFCOUNT);
2223
2224         if (obj_priv->pages_refcount++ != 0)
2225                 return 0;
2226
2227         /* Get the list of pages out of our struct file.  They'll be pinned
2228          * at this point until we release them.
2229          */
2230         page_count = obj->size / PAGE_SIZE;
2231         BUG_ON(obj_priv->pages != NULL);
2232         obj_priv->pages = drm_calloc_large(page_count, sizeof(struct page *));
2233         if (obj_priv->pages == NULL) {
2234                 obj_priv->pages_refcount--;
2235                 return -ENOMEM;
2236         }
2237
2238         inode = obj->filp->f_path.dentry->d_inode;
2239         mapping = inode->i_mapping;
2240         for (i = 0; i < page_count; i++) {
2241                 page = read_cache_page_gfp(mapping, i,
2242                                            GFP_HIGHUSER |
2243                                            __GFP_COLD |
2244                                            gfpmask);
2245                 if (IS_ERR(page))
2246                         goto err_pages;
2247
2248                 obj_priv->pages[i] = page;
2249         }
2250
2251         if (obj_priv->tiling_mode != I915_TILING_NONE)
2252                 i915_gem_object_do_bit_17_swizzle(obj);
2253
2254         return 0;
2255
2256 err_pages:
2257         while (i--)
2258                 page_cache_release(obj_priv->pages[i]);
2259
2260         drm_free_large(obj_priv->pages);
2261         obj_priv->pages = NULL;
2262         obj_priv->pages_refcount--;
2263         return PTR_ERR(page);
2264 }
2265
2266 static void sandybridge_write_fence_reg(struct drm_i915_fence_reg *reg)
2267 {
2268         struct drm_gem_object *obj = reg->obj;
2269         struct drm_device *dev = obj->dev;
2270         drm_i915_private_t *dev_priv = dev->dev_private;
2271         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2272         int regnum = obj_priv->fence_reg;
2273         uint64_t val;
2274
2275         val = (uint64_t)((obj_priv->gtt_offset + obj->size - 4096) &
2276                     0xfffff000) << 32;
2277         val |= obj_priv->gtt_offset & 0xfffff000;
2278         val |= (uint64_t)((obj_priv->stride / 128) - 1) <<
2279                 SANDYBRIDGE_FENCE_PITCH_SHIFT;
2280
2281         if (obj_priv->tiling_mode == I915_TILING_Y)
2282                 val |= 1 << I965_FENCE_TILING_Y_SHIFT;
2283         val |= I965_FENCE_REG_VALID;
2284
2285         I915_WRITE64(FENCE_REG_SANDYBRIDGE_0 + (regnum * 8), val);
2286 }
2287
2288 static void i965_write_fence_reg(struct drm_i915_fence_reg *reg)
2289 {
2290         struct drm_gem_object *obj = reg->obj;
2291         struct drm_device *dev = obj->dev;
2292         drm_i915_private_t *dev_priv = dev->dev_private;
2293         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2294         int regnum = obj_priv->fence_reg;
2295         uint64_t val;
2296
2297         val = (uint64_t)((obj_priv->gtt_offset + obj->size - 4096) &
2298                     0xfffff000) << 32;
2299         val |= obj_priv->gtt_offset & 0xfffff000;
2300         val |= ((obj_priv->stride / 128) - 1) << I965_FENCE_PITCH_SHIFT;
2301         if (obj_priv->tiling_mode == I915_TILING_Y)
2302                 val |= 1 << I965_FENCE_TILING_Y_SHIFT;
2303         val |= I965_FENCE_REG_VALID;
2304
2305         I915_WRITE64(FENCE_REG_965_0 + (regnum * 8), val);
2306 }
2307
2308 static void i915_write_fence_reg(struct drm_i915_fence_reg *reg)
2309 {
2310         struct drm_gem_object *obj = reg->obj;
2311         struct drm_device *dev = obj->dev;
2312         drm_i915_private_t *dev_priv = dev->dev_private;
2313         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2314         int regnum = obj_priv->fence_reg;
2315         int tile_width;
2316         uint32_t fence_reg, val;
2317         uint32_t pitch_val;
2318
2319         if ((obj_priv->gtt_offset & ~I915_FENCE_START_MASK) ||
2320             (obj_priv->gtt_offset & (obj->size - 1))) {
2321                 WARN(1, "%s: object 0x%08x not 1M or size (0x%zx) aligned\n",
2322                      __func__, obj_priv->gtt_offset, obj->size);
2323                 return;
2324         }
2325
2326         if (obj_priv->tiling_mode == I915_TILING_Y &&
2327             HAS_128_BYTE_Y_TILING(dev))
2328                 tile_width = 128;
2329         else
2330                 tile_width = 512;
2331
2332         /* Note: pitch better be a power of two tile widths */
2333         pitch_val = obj_priv->stride / tile_width;
2334         pitch_val = ffs(pitch_val) - 1;
2335
2336         if (obj_priv->tiling_mode == I915_TILING_Y &&
2337             HAS_128_BYTE_Y_TILING(dev))
2338                 WARN_ON(pitch_val > I830_FENCE_MAX_PITCH_VAL);
2339         else
2340                 WARN_ON(pitch_val > I915_FENCE_MAX_PITCH_VAL);
2341
2342         val = obj_priv->gtt_offset;
2343         if (obj_priv->tiling_mode == I915_TILING_Y)
2344                 val |= 1 << I830_FENCE_TILING_Y_SHIFT;
2345         val |= I915_FENCE_SIZE_BITS(obj->size);
2346         val |= pitch_val << I830_FENCE_PITCH_SHIFT;
2347         val |= I830_FENCE_REG_VALID;
2348
2349         if (regnum < 8)
2350                 fence_reg = FENCE_REG_830_0 + (regnum * 4);
2351         else
2352                 fence_reg = FENCE_REG_945_8 + ((regnum - 8) * 4);
2353         I915_WRITE(fence_reg, val);
2354 }
2355
2356 static void i830_write_fence_reg(struct drm_i915_fence_reg *reg)
2357 {
2358         struct drm_gem_object *obj = reg->obj;
2359         struct drm_device *dev = obj->dev;
2360         drm_i915_private_t *dev_priv = dev->dev_private;
2361         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2362         int regnum = obj_priv->fence_reg;
2363         uint32_t val;
2364         uint32_t pitch_val;
2365         uint32_t fence_size_bits;
2366
2367         if ((obj_priv->gtt_offset & ~I830_FENCE_START_MASK) ||
2368             (obj_priv->gtt_offset & (obj->size - 1))) {
2369                 WARN(1, "%s: object 0x%08x not 512K or size aligned\n",
2370                      __func__, obj_priv->gtt_offset);
2371                 return;
2372         }
2373
2374         pitch_val = obj_priv->stride / 128;
2375         pitch_val = ffs(pitch_val) - 1;
2376         WARN_ON(pitch_val > I830_FENCE_MAX_PITCH_VAL);
2377
2378         val = obj_priv->gtt_offset;
2379         if (obj_priv->tiling_mode == I915_TILING_Y)
2380                 val |= 1 << I830_FENCE_TILING_Y_SHIFT;
2381         fence_size_bits = I830_FENCE_SIZE_BITS(obj->size);
2382         WARN_ON(fence_size_bits & ~0x00000f00);
2383         val |= fence_size_bits;
2384         val |= pitch_val << I830_FENCE_PITCH_SHIFT;
2385         val |= I830_FENCE_REG_VALID;
2386
2387         I915_WRITE(FENCE_REG_830_0 + (regnum * 4), val);
2388 }
2389
2390 static int i915_find_fence_reg(struct drm_device *dev)
2391 {
2392         struct drm_i915_fence_reg *reg = NULL;
2393         struct drm_i915_gem_object *obj_priv = NULL;
2394         struct drm_i915_private *dev_priv = dev->dev_private;
2395         struct drm_gem_object *obj = NULL;
2396         int i, avail, ret;
2397
2398         /* First try to find a free reg */
2399         avail = 0;
2400         for (i = dev_priv->fence_reg_start; i < dev_priv->num_fence_regs; i++) {
2401                 reg = &dev_priv->fence_regs[i];
2402                 if (!reg->obj)
2403                         return i;
2404
2405                 obj_priv = to_intel_bo(reg->obj);
2406                 if (!obj_priv->pin_count)
2407                     avail++;
2408         }
2409
2410         if (avail == 0)
2411                 return -ENOSPC;
2412
2413         /* None available, try to steal one or wait for a user to finish */
2414         i = I915_FENCE_REG_NONE;
2415         list_for_each_entry(reg, &dev_priv->mm.fence_list,
2416                             lru_list) {
2417                 obj = reg->obj;
2418                 obj_priv = to_intel_bo(obj);
2419
2420                 if (obj_priv->pin_count)
2421                         continue;
2422
2423                 /* found one! */
2424                 i = obj_priv->fence_reg;
2425                 break;
2426         }
2427
2428         BUG_ON(i == I915_FENCE_REG_NONE);
2429
2430         /* We only have a reference on obj from the active list. put_fence_reg
2431          * might drop that one, causing a use-after-free in it. So hold a
2432          * private reference to obj like the other callers of put_fence_reg
2433          * (set_tiling ioctl) do. */
2434         drm_gem_object_reference(obj);
2435         ret = i915_gem_object_put_fence_reg(obj);
2436         drm_gem_object_unreference(obj);
2437         if (ret != 0)
2438                 return ret;
2439
2440         return i;
2441 }
2442
2443 /**
2444  * i915_gem_object_get_fence_reg - set up a fence reg for an object
2445  * @obj: object to map through a fence reg
2446  *
2447  * When mapping objects through the GTT, userspace wants to be able to write
2448  * to them without having to worry about swizzling if the object is tiled.
2449  *
2450  * This function walks the fence regs looking for a free one for @obj,
2451  * stealing one if it can't find any.
2452  *
2453  * It then sets up the reg based on the object's properties: address, pitch
2454  * and tiling format.
2455  */
2456 int
2457 i915_gem_object_get_fence_reg(struct drm_gem_object *obj)
2458 {
2459         struct drm_device *dev = obj->dev;
2460         struct drm_i915_private *dev_priv = dev->dev_private;
2461         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2462         struct drm_i915_fence_reg *reg = NULL;
2463         int ret;
2464
2465         /* Just update our place in the LRU if our fence is getting used. */
2466         if (obj_priv->fence_reg != I915_FENCE_REG_NONE) {
2467                 reg = &dev_priv->fence_regs[obj_priv->fence_reg];
2468                 list_move_tail(&reg->lru_list, &dev_priv->mm.fence_list);
2469                 return 0;
2470         }
2471
2472         switch (obj_priv->tiling_mode) {
2473         case I915_TILING_NONE:
2474                 WARN(1, "allocating a fence for non-tiled object?\n");
2475                 break;
2476         case I915_TILING_X:
2477                 if (!obj_priv->stride)
2478                         return -EINVAL;
2479                 WARN((obj_priv->stride & (512 - 1)),
2480                      "object 0x%08x is X tiled but has non-512B pitch\n",
2481                      obj_priv->gtt_offset);
2482                 break;
2483         case I915_TILING_Y:
2484                 if (!obj_priv->stride)
2485                         return -EINVAL;
2486                 WARN((obj_priv->stride & (128 - 1)),
2487                      "object 0x%08x is Y tiled but has non-128B pitch\n",
2488                      obj_priv->gtt_offset);
2489                 break;
2490         }
2491
2492         ret = i915_find_fence_reg(dev);
2493         if (ret < 0)
2494                 return ret;
2495
2496         obj_priv->fence_reg = ret;
2497         reg = &dev_priv->fence_regs[obj_priv->fence_reg];
2498         list_add_tail(&reg->lru_list, &dev_priv->mm.fence_list);
2499
2500         reg->obj = obj;
2501
2502         if (IS_GEN6(dev))
2503                 sandybridge_write_fence_reg(reg);
2504         else if (IS_I965G(dev))
2505                 i965_write_fence_reg(reg);
2506         else if (IS_I9XX(dev))
2507                 i915_write_fence_reg(reg);
2508         else
2509                 i830_write_fence_reg(reg);
2510
2511         trace_i915_gem_object_get_fence(obj, obj_priv->fence_reg,
2512                         obj_priv->tiling_mode);
2513
2514         return 0;
2515 }
2516
2517 /**
2518  * i915_gem_clear_fence_reg - clear out fence register info
2519  * @obj: object to clear
2520  *
2521  * Zeroes out the fence register itself and clears out the associated
2522  * data structures in dev_priv and obj_priv.
2523  */
2524 static void
2525 i915_gem_clear_fence_reg(struct drm_gem_object *obj)
2526 {
2527         struct drm_device *dev = obj->dev;
2528         drm_i915_private_t *dev_priv = dev->dev_private;
2529         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2530         struct drm_i915_fence_reg *reg =
2531                 &dev_priv->fence_regs[obj_priv->fence_reg];
2532
2533         if (IS_GEN6(dev)) {
2534                 I915_WRITE64(FENCE_REG_SANDYBRIDGE_0 +
2535                              (obj_priv->fence_reg * 8), 0);
2536         } else if (IS_I965G(dev)) {
2537                 I915_WRITE64(FENCE_REG_965_0 + (obj_priv->fence_reg * 8), 0);
2538         } else {
2539                 uint32_t fence_reg;
2540
2541                 if (obj_priv->fence_reg < 8)
2542                         fence_reg = FENCE_REG_830_0 + obj_priv->fence_reg * 4;
2543                 else
2544                         fence_reg = FENCE_REG_945_8 + (obj_priv->fence_reg -
2545                                                        8) * 4;
2546
2547                 I915_WRITE(fence_reg, 0);
2548         }
2549
2550         reg->obj = NULL;
2551         obj_priv->fence_reg = I915_FENCE_REG_NONE;
2552         list_del_init(&reg->lru_list);
2553 }
2554
2555 /**
2556  * i915_gem_object_put_fence_reg - waits on outstanding fenced access
2557  * to the buffer to finish, and then resets the fence register.
2558  * @obj: tiled object holding a fence register.
2559  *
2560  * Zeroes out the fence register itself and clears out the associated
2561  * data structures in dev_priv and obj_priv.
2562  */
2563 int
2564 i915_gem_object_put_fence_reg(struct drm_gem_object *obj)
2565 {
2566         struct drm_device *dev = obj->dev;
2567         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2568
2569         if (obj_priv->fence_reg == I915_FENCE_REG_NONE)
2570                 return 0;
2571
2572         /* If we've changed tiling, GTT-mappings of the object
2573          * need to re-fault to ensure that the correct fence register
2574          * setup is in place.
2575          */
2576         i915_gem_release_mmap(obj);
2577
2578         /* On the i915, GPU access to tiled buffers is via a fence,
2579          * therefore we must wait for any outstanding access to complete
2580          * before clearing the fence.
2581          */
2582         if (!IS_I965G(dev)) {
2583                 int ret;
2584
2585                 i915_gem_object_flush_gpu_write_domain(obj);
2586                 ret = i915_gem_object_wait_rendering(obj);
2587                 if (ret != 0)
2588                         return ret;
2589         }
2590
2591         i915_gem_object_flush_gtt_write_domain(obj);
2592         i915_gem_clear_fence_reg (obj);
2593
2594         return 0;
2595 }
2596
2597 /**
2598  * Finds free space in the GTT aperture and binds the object there.
2599  */
2600 static int
2601 i915_gem_object_bind_to_gtt(struct drm_gem_object *obj, unsigned alignment)
2602 {
2603         struct drm_device *dev = obj->dev;
2604         drm_i915_private_t *dev_priv = dev->dev_private;
2605         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2606         struct drm_mm_node *free_space;
2607         gfp_t gfpmask =  __GFP_NORETRY | __GFP_NOWARN;
2608         int ret;
2609
2610         if (obj_priv->madv != I915_MADV_WILLNEED) {
2611                 DRM_ERROR("Attempting to bind a purgeable object\n");
2612                 return -EINVAL;
2613         }
2614
2615         if (alignment == 0)
2616                 alignment = i915_gem_get_gtt_alignment(obj);
2617         if (alignment & (i915_gem_get_gtt_alignment(obj) - 1)) {
2618                 DRM_ERROR("Invalid object alignment requested %u\n", alignment);
2619                 return -EINVAL;
2620         }
2621
2622         /* If the object is bigger than the entire aperture, reject it early
2623          * before evicting everything in a vain attempt to find space.
2624          */
2625         if (obj->size > dev->gtt_total) {
2626                 DRM_ERROR("Attempting to bind an object larger than the aperture\n");
2627                 return -E2BIG;
2628         }
2629
2630  search_free:
2631         free_space = drm_mm_search_free(&dev_priv->mm.gtt_space,
2632                                         obj->size, alignment, 0);
2633         if (free_space != NULL) {
2634                 obj_priv->gtt_space = drm_mm_get_block(free_space, obj->size,
2635                                                        alignment);
2636                 if (obj_priv->gtt_space != NULL)
2637                         obj_priv->gtt_offset = obj_priv->gtt_space->start;
2638         }
2639         if (obj_priv->gtt_space == NULL) {
2640                 /* If the gtt is empty and we're still having trouble
2641                  * fitting our object in, we're out of memory.
2642                  */
2643 #if WATCH_LRU
2644                 DRM_INFO("%s: GTT full, evicting something\n", __func__);
2645 #endif
2646                 ret = i915_gem_evict_something(dev, obj->size);
2647                 if (ret)
2648                         return ret;
2649
2650                 goto search_free;
2651         }
2652
2653 #if WATCH_BUF
2654         DRM_INFO("Binding object of size %zd at 0x%08x\n",
2655                  obj->size, obj_priv->gtt_offset);
2656 #endif
2657         ret = i915_gem_object_get_pages(obj, gfpmask);
2658         if (ret) {
2659                 drm_mm_put_block(obj_priv->gtt_space);
2660                 obj_priv->gtt_space = NULL;
2661
2662                 if (ret == -ENOMEM) {
2663                         /* first try to clear up some space from the GTT */
2664                         ret = i915_gem_evict_something(dev, obj->size);
2665                         if (ret) {
2666                                 /* now try to shrink everyone else */
2667                                 if (gfpmask) {
2668                                         gfpmask = 0;
2669                                         goto search_free;
2670                                 }
2671
2672                                 return ret;
2673                         }
2674
2675                         goto search_free;
2676                 }
2677
2678                 return ret;
2679         }
2680
2681         /* Create an AGP memory structure pointing at our pages, and bind it
2682          * into the GTT.
2683          */
2684         obj_priv->agp_mem = drm_agp_bind_pages(dev,
2685                                                obj_priv->pages,
2686                                                obj->size >> PAGE_SHIFT,
2687                                                obj_priv->gtt_offset,
2688                                                obj_priv->agp_type);
2689         if (obj_priv->agp_mem == NULL) {
2690                 i915_gem_object_put_pages(obj);
2691                 drm_mm_put_block(obj_priv->gtt_space);
2692                 obj_priv->gtt_space = NULL;
2693
2694                 ret = i915_gem_evict_something(dev, obj->size);
2695                 if (ret)
2696                         return ret;
2697
2698                 goto search_free;
2699         }
2700         atomic_inc(&dev->gtt_count);
2701         atomic_add(obj->size, &dev->gtt_memory);
2702
2703         /* Assert that the object is not currently in any GPU domain. As it
2704          * wasn't in the GTT, there shouldn't be any way it could have been in
2705          * a GPU cache
2706          */
2707         BUG_ON(obj->read_domains & I915_GEM_GPU_DOMAINS);
2708         BUG_ON(obj->write_domain & I915_GEM_GPU_DOMAINS);
2709
2710         trace_i915_gem_object_bind(obj, obj_priv->gtt_offset);
2711
2712         return 0;
2713 }
2714
2715 void
2716 i915_gem_clflush_object(struct drm_gem_object *obj)
2717 {
2718         struct drm_i915_gem_object      *obj_priv = to_intel_bo(obj);
2719
2720         /* If we don't have a page list set up, then we're not pinned
2721          * to GPU, and we can ignore the cache flush because it'll happen
2722          * again at bind time.
2723          */
2724         if (obj_priv->pages == NULL)
2725                 return;
2726
2727         trace_i915_gem_object_clflush(obj);
2728
2729         drm_clflush_pages(obj_priv->pages, obj->size / PAGE_SIZE);
2730 }
2731
2732 /** Flushes any GPU write domain for the object if it's dirty. */
2733 static void
2734 i915_gem_object_flush_gpu_write_domain(struct drm_gem_object *obj)
2735 {
2736         struct drm_device *dev = obj->dev;
2737         uint32_t old_write_domain;
2738         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2739
2740         if ((obj->write_domain & I915_GEM_GPU_DOMAINS) == 0)
2741                 return;
2742
2743         /* Queue the GPU write cache flushing we need. */
2744         old_write_domain = obj->write_domain;
2745         i915_gem_flush(dev, 0, obj->write_domain);
2746         (void) i915_add_request(dev, NULL, obj->write_domain, obj_priv->ring);
2747         BUG_ON(obj->write_domain);
2748
2749         trace_i915_gem_object_change_domain(obj,
2750                                             obj->read_domains,
2751                                             old_write_domain);
2752 }
2753
2754 /** Flushes the GTT write domain for the object if it's dirty. */
2755 static void
2756 i915_gem_object_flush_gtt_write_domain(struct drm_gem_object *obj)
2757 {
2758         uint32_t old_write_domain;
2759
2760         if (obj->write_domain != I915_GEM_DOMAIN_GTT)
2761                 return;
2762
2763         /* No actual flushing is required for the GTT write domain.   Writes
2764          * to it immediately go to main memory as far as we know, so there's
2765          * no chipset flush.  It also doesn't land in render cache.
2766          */
2767         old_write_domain = obj->write_domain;
2768         obj->write_domain = 0;
2769
2770         trace_i915_gem_object_change_domain(obj,
2771                                             obj->read_domains,
2772                                             old_write_domain);
2773 }
2774
2775 /** Flushes the CPU write domain for the object if it's dirty. */
2776 static void
2777 i915_gem_object_flush_cpu_write_domain(struct drm_gem_object *obj)
2778 {
2779         struct drm_device *dev = obj->dev;
2780         uint32_t old_write_domain;
2781
2782         if (obj->write_domain != I915_GEM_DOMAIN_CPU)
2783                 return;
2784
2785         i915_gem_clflush_object(obj);
2786         drm_agp_chipset_flush(dev);
2787         old_write_domain = obj->write_domain;
2788         obj->write_domain = 0;
2789
2790         trace_i915_gem_object_change_domain(obj,
2791                                             obj->read_domains,
2792                                             old_write_domain);
2793 }
2794
2795 void
2796 i915_gem_object_flush_write_domain(struct drm_gem_object *obj)
2797 {
2798         switch (obj->write_domain) {
2799         case I915_GEM_DOMAIN_GTT:
2800                 i915_gem_object_flush_gtt_write_domain(obj);
2801                 break;
2802         case I915_GEM_DOMAIN_CPU:
2803                 i915_gem_object_flush_cpu_write_domain(obj);
2804                 break;
2805         default:
2806                 i915_gem_object_flush_gpu_write_domain(obj);
2807                 break;
2808         }
2809 }
2810
2811 /**
2812  * Moves a single object to the GTT read, and possibly write domain.
2813  *
2814  * This function returns when the move is complete, including waiting on
2815  * flushes to occur.
2816  */
2817 int
2818 i915_gem_object_set_to_gtt_domain(struct drm_gem_object *obj, int write)
2819 {
2820         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2821         uint32_t old_write_domain, old_read_domains;
2822         int ret;
2823
2824         /* Not valid to be called on unbound objects. */
2825         if (obj_priv->gtt_space == NULL)
2826                 return -EINVAL;
2827
2828         i915_gem_object_flush_gpu_write_domain(obj);
2829         /* Wait on any GPU rendering and flushing to occur. */
2830         ret = i915_gem_object_wait_rendering(obj);
2831         if (ret != 0)
2832                 return ret;
2833
2834         old_write_domain = obj->write_domain;
2835         old_read_domains = obj->read_domains;
2836
2837         /* If we're writing through the GTT domain, then CPU and GPU caches
2838          * will need to be invalidated at next use.
2839          */
2840         if (write)
2841                 obj->read_domains &= I915_GEM_DOMAIN_GTT;
2842
2843         i915_gem_object_flush_cpu_write_domain(obj);
2844
2845         /* It should now be out of any other write domains, and we can update
2846          * the domain values for our changes.
2847          */
2848         BUG_ON((obj->write_domain & ~I915_GEM_DOMAIN_GTT) != 0);
2849         obj->read_domains |= I915_GEM_DOMAIN_GTT;
2850         if (write) {
2851                 obj->write_domain = I915_GEM_DOMAIN_GTT;
2852                 obj_priv->dirty = 1;
2853         }
2854
2855         trace_i915_gem_object_change_domain(obj,
2856                                             old_read_domains,
2857                                             old_write_domain);
2858
2859         return 0;
2860 }
2861
2862 /*
2863  * Prepare buffer for display plane. Use uninterruptible for possible flush
2864  * wait, as in modesetting process we're not supposed to be interrupted.
2865  */
2866 int
2867 i915_gem_object_set_to_display_plane(struct drm_gem_object *obj)
2868 {
2869         struct drm_device *dev = obj->dev;
2870         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2871         uint32_t old_write_domain, old_read_domains;
2872         int ret;
2873
2874         /* Not valid to be called on unbound objects. */
2875         if (obj_priv->gtt_space == NULL)
2876                 return -EINVAL;
2877
2878         i915_gem_object_flush_gpu_write_domain(obj);
2879
2880         /* Wait on any GPU rendering and flushing to occur. */
2881         if (obj_priv->active) {
2882 #if WATCH_BUF
2883                 DRM_INFO("%s: object %p wait for seqno %08x\n",
2884                           __func__, obj, obj_priv->last_rendering_seqno);
2885 #endif
2886                 ret = i915_do_wait_request(dev,
2887                                 obj_priv->last_rendering_seqno,
2888                                 0,
2889                                 obj_priv->ring);
2890                 if (ret != 0)
2891                         return ret;
2892         }
2893
2894         i915_gem_object_flush_cpu_write_domain(obj);
2895
2896         old_write_domain = obj->write_domain;
2897         old_read_domains = obj->read_domains;
2898
2899         /* It should now be out of any other write domains, and we can update
2900          * the domain values for our changes.
2901          */
2902         BUG_ON((obj->write_domain & ~I915_GEM_DOMAIN_GTT) != 0);
2903         obj->read_domains = I915_GEM_DOMAIN_GTT;
2904         obj->write_domain = I915_GEM_DOMAIN_GTT;
2905         obj_priv->dirty = 1;
2906
2907         trace_i915_gem_object_change_domain(obj,
2908                                             old_read_domains,
2909                                             old_write_domain);
2910
2911         return 0;
2912 }
2913
2914 /**
2915  * Moves a single object to the CPU read, and possibly write domain.
2916  *
2917  * This function returns when the move is complete, including waiting on
2918  * flushes to occur.
2919  */
2920 static int
2921 i915_gem_object_set_to_cpu_domain(struct drm_gem_object *obj, int write)
2922 {
2923         uint32_t old_write_domain, old_read_domains;
2924         int ret;
2925
2926         i915_gem_object_flush_gpu_write_domain(obj);
2927         /* Wait on any GPU rendering and flushing to occur. */
2928         ret = i915_gem_object_wait_rendering(obj);
2929         if (ret != 0)
2930                 return ret;
2931
2932         i915_gem_object_flush_gtt_write_domain(obj);
2933
2934         /* If we have a partially-valid cache of the object in the CPU,
2935          * finish invalidating it and free the per-page flags.
2936          */
2937         i915_gem_object_set_to_full_cpu_read_domain(obj);
2938
2939         old_write_domain = obj->write_domain;
2940         old_read_domains = obj->read_domains;
2941
2942         /* Flush the CPU cache if it's still invalid. */
2943         if ((obj->read_domains & I915_GEM_DOMAIN_CPU) == 0) {
2944                 i915_gem_clflush_object(obj);
2945
2946                 obj->read_domains |= I915_GEM_DOMAIN_CPU;
2947         }
2948
2949         /* It should now be out of any other write domains, and we can update
2950          * the domain values for our changes.
2951          */
2952         BUG_ON((obj->write_domain & ~I915_GEM_DOMAIN_CPU) != 0);
2953
2954         /* If we're writing through the CPU, then the GPU read domains will
2955          * need to be invalidated at next use.
2956          */
2957         if (write) {
2958                 obj->read_domains &= I915_GEM_DOMAIN_CPU;
2959                 obj->write_domain = I915_GEM_DOMAIN_CPU;
2960         }
2961
2962         trace_i915_gem_object_change_domain(obj,
2963                                             old_read_domains,
2964                                             old_write_domain);
2965
2966         return 0;
2967 }
2968
2969 /*
2970  * Set the next domain for the specified object. This
2971  * may not actually perform the necessary flushing/invaliding though,
2972  * as that may want to be batched with other set_domain operations
2973  *
2974  * This is (we hope) the only really tricky part of gem. The goal
2975  * is fairly simple -- track which caches hold bits of the object
2976  * and make sure they remain coherent. A few concrete examples may
2977  * help to explain how it works. For shorthand, we use the notation
2978  * (read_domains, write_domain), e.g. (CPU, CPU) to indicate the
2979  * a pair of read and write domain masks.
2980  *
2981  * Case 1: the batch buffer
2982  *
2983  *      1. Allocated
2984  *      2. Written by CPU
2985  *      3. Mapped to GTT
2986  *      4. Read by GPU
2987  *      5. Unmapped from GTT
2988  *      6. Freed
2989  *
2990  *      Let's take these a step at a time
2991  *
2992  *      1. Allocated
2993  *              Pages allocated from the kernel may still have
2994  *              cache contents, so we set them to (CPU, CPU) always.
2995  *      2. Written by CPU (using pwrite)
2996  *              The pwrite function calls set_domain (CPU, CPU) and
2997  *              this function does nothing (as nothing changes)
2998  *      3. Mapped by GTT
2999  *              This function asserts that the object is not
3000  *              currently in any GPU-based read or write domains
3001  *      4. Read by GPU
3002  *              i915_gem_execbuffer calls set_domain (COMMAND, 0).
3003  *              As write_domain is zero, this function adds in the
3004  *              current read domains (CPU+COMMAND, 0).
3005  *              flush_domains is set to CPU.
3006  *              invalidate_domains is set to COMMAND
3007  *              clflush is run to get data out of the CPU caches
3008  *              then i915_dev_set_domain calls i915_gem_flush to
3009  *              emit an MI_FLUSH and drm_agp_chipset_flush
3010  *      5. Unmapped from GTT
3011  *              i915_gem_object_unbind calls set_domain (CPU, CPU)
3012  *              flush_domains and invalidate_domains end up both zero
3013  *              so no flushing/invalidating happens
3014  *      6. Freed
3015  *              yay, done
3016  *
3017  * Case 2: The shared render buffer
3018  *
3019  *      1. Allocated
3020  *      2. Mapped to GTT
3021  *      3. Read/written by GPU
3022  *      4. set_domain to (CPU,CPU)
3023  *      5. Read/written by CPU
3024  *      6. Read/written by GPU
3025  *
3026  *      1. Allocated
3027  *              Same as last example, (CPU, CPU)
3028  *      2. Mapped to GTT
3029  *              Nothing changes (assertions find that it is not in the GPU)
3030  *      3. Read/written by GPU
3031  *              execbuffer calls set_domain (RENDER, RENDER)
3032  *              flush_domains gets CPU
3033  *              invalidate_domains gets GPU
3034  *              clflush (obj)
3035  *              MI_FLUSH and drm_agp_chipset_flush
3036  *      4. set_domain (CPU, CPU)
3037  *              flush_domains gets GPU
3038  *              invalidate_domains gets CPU
3039  *              wait_rendering (obj) to make sure all drawing is complete.
3040  *              This will include an MI_FLUSH to get the data from GPU
3041  *              to memory
3042  *              clflush (obj) to invalidate the CPU cache
3043  *              Another MI_FLUSH in i915_gem_flush (eliminate this somehow?)
3044  *      5. Read/written by CPU
3045  *              cache lines are loaded and dirtied
3046  *      6. Read written by GPU
3047  *              Same as last GPU access
3048  *
3049  * Case 3: The constant buffer
3050  *
3051  *      1. Allocated
3052  *      2. Written by CPU
3053  *      3. Read by GPU
3054  *      4. Updated (written) by CPU again
3055  *      5. Read by GPU
3056  *
3057  *      1. Allocated
3058  *              (CPU, CPU)
3059  *      2. Written by CPU
3060  *              (CPU, CPU)
3061  *      3. Read by GPU
3062  *              (CPU+RENDER, 0)
3063  *              flush_domains = CPU
3064  *              invalidate_domains = RENDER
3065  *              clflush (obj)
3066  *              MI_FLUSH
3067  *              drm_agp_chipset_flush
3068  *      4. Updated (written) by CPU again
3069  *              (CPU, CPU)
3070  *              flush_domains = 0 (no previous write domain)
3071  *              invalidate_domains = 0 (no new read domains)
3072  *      5. Read by GPU
3073  *              (CPU+RENDER, 0)
3074  *              flush_domains = CPU
3075  *              invalidate_domains = RENDER
3076  *              clflush (obj)
3077  *              MI_FLUSH
3078  *              drm_agp_chipset_flush
3079  */
3080 static void
3081 i915_gem_object_set_to_gpu_domain(struct drm_gem_object *obj)
3082 {
3083         struct drm_device               *dev = obj->dev;
3084         struct drm_i915_gem_object      *obj_priv = to_intel_bo(obj);
3085         uint32_t                        invalidate_domains = 0;
3086         uint32_t                        flush_domains = 0;
3087         uint32_t                        old_read_domains;
3088
3089         BUG_ON(obj->pending_read_domains & I915_GEM_DOMAIN_CPU);
3090         BUG_ON(obj->pending_write_domain == I915_GEM_DOMAIN_CPU);
3091
3092         intel_mark_busy(dev, obj);
3093
3094 #if WATCH_BUF
3095         DRM_INFO("%s: object %p read %08x -> %08x write %08x -> %08x\n",
3096                  __func__, obj,
3097                  obj->read_domains, obj->pending_read_domains,
3098                  obj->write_domain, obj->pending_write_domain);
3099 #endif
3100         /*
3101          * If the object isn't moving to a new write domain,
3102          * let the object stay in multiple read domains
3103          */
3104         if (obj->pending_write_domain == 0)
3105                 obj->pending_read_domains |= obj->read_domains;
3106         else
3107                 obj_priv->dirty = 1;
3108
3109         /*
3110          * Flush the current write domain if
3111          * the new read domains don't match. Invalidate
3112          * any read domains which differ from the old
3113          * write domain
3114          */
3115         if (obj->write_domain &&
3116             obj->write_domain != obj->pending_read_domains) {
3117                 flush_domains |= obj->write_domain;
3118                 invalidate_domains |=
3119                         obj->pending_read_domains & ~obj->write_domain;
3120         }
3121         /*
3122          * Invalidate any read caches which may have
3123          * stale data. That is, any new read domains.
3124          */
3125         invalidate_domains |= obj->pending_read_domains & ~obj->read_domains;
3126         if ((flush_domains | invalidate_domains) & I915_GEM_DOMAIN_CPU) {
3127 #if WATCH_BUF
3128                 DRM_INFO("%s: CPU domain flush %08x invalidate %08x\n",
3129                          __func__, flush_domains, invalidate_domains);
3130 #endif
3131                 i915_gem_clflush_object(obj);
3132         }
3133
3134         old_read_domains = obj->read_domains;
3135
3136         /* The actual obj->write_domain will be updated with
3137          * pending_write_domain after we emit the accumulated flush for all
3138          * of our domain changes in execbuffers (which clears objects'
3139          * write_domains).  So if we have a current write domain that we
3140          * aren't changing, set pending_write_domain to that.
3141          */
3142         if (flush_domains == 0 && obj->pending_write_domain == 0)
3143                 obj->pending_write_domain = obj->write_domain;
3144         obj->read_domains = obj->pending_read_domains;
3145
3146         dev->invalidate_domains |= invalidate_domains;
3147         dev->flush_domains |= flush_domains;
3148 #if WATCH_BUF
3149         DRM_INFO("%s: read %08x write %08x invalidate %08x flush %08x\n",
3150                  __func__,
3151                  obj->read_domains, obj->write_domain,
3152                  dev->invalidate_domains, dev->flush_domains);
3153 #endif
3154
3155         trace_i915_gem_object_change_domain(obj,
3156                                             old_read_domains,
3157                                             obj->write_domain);
3158 }
3159
3160 /**
3161  * Moves the object from a partially CPU read to a full one.
3162  *
3163  * Note that this only resolves i915_gem_object_set_cpu_read_domain_range(),
3164  * and doesn't handle transitioning from !(read_domains & I915_GEM_DOMAIN_CPU).
3165  */
3166 static void
3167 i915_gem_object_set_to_full_cpu_read_domain(struct drm_gem_object *obj)
3168 {
3169         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
3170
3171         if (!obj_priv->page_cpu_valid)
3172                 return;
3173
3174         /* If we're partially in the CPU read domain, finish moving it in.
3175          */
3176         if (obj->read_domains & I915_GEM_DOMAIN_CPU) {
3177                 int i;
3178
3179                 for (i = 0; i <= (obj->size - 1) / PAGE_SIZE; i++) {
3180                         if (obj_priv->page_cpu_valid[i])
3181                                 continue;
3182                         drm_clflush_pages(obj_priv->pages + i, 1);
3183                 }
3184         }
3185
3186         /* Free the page_cpu_valid mappings which are now stale, whether
3187          * or not we've got I915_GEM_DOMAIN_CPU.
3188          */
3189         kfree(obj_priv->page_cpu_valid);
3190         obj_priv->page_cpu_valid = NULL;
3191 }
3192
3193 /**
3194  * Set the CPU read domain on a range of the object.
3195  *
3196  * The object ends up with I915_GEM_DOMAIN_CPU in its read flags although it's
3197  * not entirely valid.  The page_cpu_valid member of the object flags which
3198  * pages have been flushed, and will be respected by
3199  * i915_gem_object_set_to_cpu_domain() if it's called on to get a valid mapping
3200  * of the whole object.
3201  *
3202  * This function returns when the move is complete, including waiting on
3203  * flushes to occur.
3204  */
3205 static int
3206 i915_gem_object_set_cpu_read_domain_range(struct drm_gem_object *obj,
3207                                           uint64_t offset, uint64_t size)
3208 {
3209         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
3210         uint32_t old_read_domains;
3211         int i, ret;
3212
3213         if (offset == 0 && size == obj->size)
3214                 return i915_gem_object_set_to_cpu_domain(obj, 0);
3215
3216         i915_gem_object_flush_gpu_write_domain(obj);
3217         /* Wait on any GPU rendering and flushing to occur. */
3218         ret = i915_gem_object_wait_rendering(obj);
3219         if (ret != 0)
3220                 return ret;
3221         i915_gem_object_flush_gtt_write_domain(obj);
3222
3223         /* If we're already fully in the CPU read domain, we're done. */
3224         if (obj_priv->page_cpu_valid == NULL &&
3225             (obj->read_domains & I915_GEM_DOMAIN_CPU) != 0)
3226                 return 0;
3227
3228         /* Otherwise, create/clear the per-page CPU read domain flag if we're
3229          * newly adding I915_GEM_DOMAIN_CPU
3230          */
3231         if (obj_priv->page_cpu_valid == NULL) {
3232                 obj_priv->page_cpu_valid = kzalloc(obj->size / PAGE_SIZE,
3233                                                    GFP_KERNEL);
3234                 if (obj_priv->page_cpu_valid == NULL)
3235                         return -ENOMEM;
3236         } else if ((obj->read_domains & I915_GEM_DOMAIN_CPU) == 0)
3237                 memset(obj_priv->page_cpu_valid, 0, obj->size / PAGE_SIZE);
3238
3239         /* Flush the cache on any pages that are still invalid from the CPU's
3240          * perspective.
3241          */
3242         for (i = offset / PAGE_SIZE; i <= (offset + size - 1) / PAGE_SIZE;
3243              i++) {
3244                 if (obj_priv->page_cpu_valid[i])
3245                         continue;
3246
3247                 drm_clflush_pages(obj_priv->pages + i, 1);
3248
3249                 obj_priv->page_cpu_valid[i] = 1;
3250         }
3251
3252         /* It should now be out of any other write domains, and we can update
3253          * the domain values for our changes.
3254          */
3255         BUG_ON((obj->write_domain & ~I915_GEM_DOMAIN_CPU) != 0);
3256
3257         old_read_domains = obj->read_domains;
3258         obj->read_domains |= I915_GEM_DOMAIN_CPU;
3259
3260         trace_i915_gem_object_change_domain(obj,
3261                                             old_read_domains,
3262                                             obj->write_domain);
3263
3264         return 0;
3265 }
3266
3267 /**
3268  * Pin an object to the GTT and evaluate the relocations landing in it.
3269  */
3270 static int
3271 i915_gem_object_pin_and_relocate(struct drm_gem_object *obj,
3272                                  struct drm_file *file_priv,
3273                                  struct drm_i915_gem_exec_object2 *entry,
3274                                  struct drm_i915_gem_relocation_entry *relocs)
3275 {
3276         struct drm_device *dev = obj->dev;
3277         drm_i915_private_t *dev_priv = dev->dev_private;
3278         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
3279         int i, ret;
3280         void __iomem *reloc_page;
3281         bool need_fence;
3282
3283         need_fence = entry->flags & EXEC_OBJECT_NEEDS_FENCE &&
3284                      obj_priv->tiling_mode != I915_TILING_NONE;
3285
3286         /* Check fence reg constraints and rebind if necessary */
3287         if (need_fence &&
3288             !i915_gem_object_fence_offset_ok(obj,
3289                                              obj_priv->tiling_mode)) {
3290                 ret = i915_gem_object_unbind(obj);
3291                 if (ret)
3292                         return ret;
3293         }
3294
3295         /* Choose the GTT offset for our buffer and put it there. */
3296         ret = i915_gem_object_pin(obj, (uint32_t) entry->alignment);
3297         if (ret)
3298                 return ret;
3299
3300         /*
3301          * Pre-965 chips need a fence register set up in order to
3302          * properly handle blits to/from tiled surfaces.
3303          */
3304         if (need_fence) {
3305                 ret = i915_gem_object_get_fence_reg(obj);
3306                 if (ret != 0) {
3307                         i915_gem_object_unpin(obj);
3308                         return ret;
3309                 }
3310         }
3311
3312         entry->offset = obj_priv->gtt_offset;
3313
3314         /* Apply the relocations, using the GTT aperture to avoid cache
3315          * flushing requirements.
3316          */
3317         for (i = 0; i < entry->relocation_count; i++) {
3318                 struct drm_i915_gem_relocation_entry *reloc= &relocs[i];
3319                 struct drm_gem_object *target_obj;
3320                 struct drm_i915_gem_object *target_obj_priv;
3321                 uint32_t reloc_val, reloc_offset;
3322                 uint32_t __iomem *reloc_entry;
3323
3324                 target_obj = drm_gem_object_lookup(obj->dev, file_priv,
3325                                                    reloc->target_handle);
3326                 if (target_obj == NULL) {
3327                         i915_gem_object_unpin(obj);
3328                         return -EBADF;
3329                 }
3330                 target_obj_priv = to_intel_bo(target_obj);
3331
3332 #if WATCH_RELOC
3333                 DRM_INFO("%s: obj %p offset %08x target %d "
3334                          "read %08x write %08x gtt %08x "
3335                          "presumed %08x delta %08x\n",
3336                          __func__,
3337                          obj,
3338                          (int) reloc->offset,
3339                          (int) reloc->target_handle,
3340                          (int) reloc->read_domains,
3341                          (int) reloc->write_domain,
3342                          (int) target_obj_priv->gtt_offset,
3343                          (int) reloc->presumed_offset,
3344                          reloc->delta);
3345 #endif
3346
3347                 /* The target buffer should have appeared before us in the
3348                  * exec_object list, so it should have a GTT space bound by now.
3349                  */
3350                 if (target_obj_priv->gtt_space == NULL) {
3351                         DRM_ERROR("No GTT space found for object %d\n",
3352                                   reloc->target_handle);
3353                         drm_gem_object_unreference(target_obj);
3354                         i915_gem_object_unpin(obj);
3355                         return -EINVAL;
3356                 }
3357
3358                 /* Validate that the target is in a valid r/w GPU domain */
3359                 if (reloc->write_domain & (reloc->write_domain - 1)) {
3360                         DRM_ERROR("reloc with multiple write domains: "
3361                                   "obj %p target %d offset %d "
3362                                   "read %08x write %08x",
3363                                   obj, reloc->target_handle,
3364                                   (int) reloc->offset,
3365                                   reloc->read_domains,
3366                                   reloc->write_domain);
3367                         return -EINVAL;
3368                 }
3369                 if (reloc->write_domain & I915_GEM_DOMAIN_CPU ||
3370                     reloc->read_domains & I915_GEM_DOMAIN_CPU) {
3371                         DRM_ERROR("reloc with read/write CPU domains: "
3372                                   "obj %p target %d offset %d "
3373                                   "read %08x write %08x",
3374                                   obj, reloc->target_handle,
3375                                   (int) reloc->offset,
3376                                   reloc->read_domains,
3377                                   reloc->write_domain);
3378                         drm_gem_object_unreference(target_obj);
3379                         i915_gem_object_unpin(obj);
3380                         return -EINVAL;
3381                 }
3382                 if (reloc->write_domain && target_obj->pending_write_domain &&
3383                     reloc->write_domain != target_obj->pending_write_domain) {
3384                         DRM_ERROR("Write domain conflict: "
3385                                   "obj %p target %d offset %d "
3386                                   "new %08x old %08x\n",
3387                                   obj, reloc->target_handle,
3388                                   (int) reloc->offset,
3389                                   reloc->write_domain,
3390                                   target_obj->pending_write_domain);
3391                         drm_gem_object_unreference(target_obj);
3392                         i915_gem_object_unpin(obj);
3393                         return -EINVAL;
3394                 }
3395
3396                 target_obj->pending_read_domains |= reloc->read_domains;
3397                 target_obj->pending_write_domain |= reloc->write_domain;
3398
3399                 /* If the relocation already has the right value in it, no
3400                  * more work needs to be done.
3401                  */
3402                 if (target_obj_priv->gtt_offset == reloc->presumed_offset) {
3403                         drm_gem_object_unreference(target_obj);
3404                         continue;
3405                 }
3406
3407                 /* Check that the relocation address is valid... */
3408                 if (reloc->offset > obj->size - 4) {
3409                         DRM_ERROR("Relocation beyond object bounds: "
3410                                   "obj %p target %d offset %d size %d.\n",
3411                                   obj, reloc->target_handle,
3412                                   (int) reloc->offset, (int) obj->size);
3413                         drm_gem_object_unreference(target_obj);
3414                         i915_gem_object_unpin(obj);
3415                         return -EINVAL;
3416                 }
3417                 if (reloc->offset & 3) {
3418                         DRM_ERROR("Relocation not 4-byte aligned: "
3419                                   "obj %p target %d offset %d.\n",
3420                                   obj, reloc->target_handle,
3421                                   (int) reloc->offset);
3422                         drm_gem_object_unreference(target_obj);
3423                         i915_gem_object_unpin(obj);
3424                         return -EINVAL;
3425                 }
3426
3427                 /* and points to somewhere within the target object. */
3428                 if (reloc->delta >= target_obj->size) {
3429                         DRM_ERROR("Relocation beyond target object bounds: "
3430                                   "obj %p target %d delta %d size %d.\n",
3431                                   obj, reloc->target_handle,
3432                                   (int) reloc->delta, (int) target_obj->size);
3433                         drm_gem_object_unreference(target_obj);
3434                         i915_gem_object_unpin(obj);
3435                         return -EINVAL;
3436                 }
3437
3438                 ret = i915_gem_object_set_to_gtt_domain(obj, 1);
3439                 if (ret != 0) {
3440                         drm_gem_object_unreference(target_obj);
3441                         i915_gem_object_unpin(obj);
3442                         return -EINVAL;
3443                 }
3444
3445                 /* Map the page containing the relocation we're going to
3446                  * perform.
3447                  */
3448                 reloc_offset = obj_priv->gtt_offset + reloc->offset;
3449                 reloc_page = io_mapping_map_atomic_wc(dev_priv->mm.gtt_mapping,
3450                                                       (reloc_offset &
3451                                                        ~(PAGE_SIZE - 1)));
3452                 reloc_entry = (uint32_t __iomem *)(reloc_page +
3453                                                    (reloc_offset & (PAGE_SIZE - 1)));
3454                 reloc_val = target_obj_priv->gtt_offset + reloc->delta;
3455
3456 #if WATCH_BUF
3457                 DRM_INFO("Applied relocation: %p@0x%08x %08x -> %08x\n",
3458                           obj, (unsigned int) reloc->offset,
3459                           readl(reloc_entry), reloc_val);
3460 #endif
3461                 writel(reloc_val, reloc_entry);
3462                 io_mapping_unmap_atomic(reloc_page);
3463
3464                 /* The updated presumed offset for this entry will be
3465                  * copied back out to the user.
3466                  */
3467                 reloc->presumed_offset = target_obj_priv->gtt_offset;
3468
3469                 drm_gem_object_unreference(target_obj);
3470         }
3471
3472 #if WATCH_BUF
3473         if (0)
3474                 i915_gem_dump_object(obj, 128, __func__, ~0);
3475 #endif
3476         return 0;
3477 }
3478
3479 /* Throttle our rendering by waiting until the ring has completed our requests
3480  * emitted over 20 msec ago.
3481  *
3482  * Note that if we were to use the current jiffies each time around the loop,
3483  * we wouldn't escape the function with any frames outstanding if the time to
3484  * render a frame was over 20ms.
3485  *
3486  * This should get us reasonable parallelism between CPU and GPU but also
3487  * relatively low latency when blocking on a particular request to finish.
3488  */
3489 static int
3490 i915_gem_ring_throttle(struct drm_device *dev, struct drm_file *file_priv)
3491 {
3492         struct drm_i915_file_private *i915_file_priv = file_priv->driver_priv;
3493         int ret = 0;
3494         unsigned long recent_enough = jiffies - msecs_to_jiffies(20);
3495
3496         mutex_lock(&dev->struct_mutex);
3497         while (!list_empty(&i915_file_priv->mm.request_list)) {
3498                 struct drm_i915_gem_request *request;
3499
3500                 request = list_first_entry(&i915_file_priv->mm.request_list,
3501                                            struct drm_i915_gem_request,
3502                                            client_list);
3503
3504                 if (time_after_eq(request->emitted_jiffies, recent_enough))
3505                         break;
3506
3507                 ret = i915_wait_request(dev, request->seqno, request->ring);
3508                 if (ret != 0)
3509                         break;
3510         }
3511         mutex_unlock(&dev->struct_mutex);
3512
3513         return ret;
3514 }
3515
3516 static int
3517 i915_gem_get_relocs_from_user(struct drm_i915_gem_exec_object2 *exec_list,
3518                               uint32_t buffer_count,
3519                               struct drm_i915_gem_relocation_entry **relocs)
3520 {
3521         uint32_t reloc_count = 0, reloc_index = 0, i;
3522         int ret;
3523
3524         *relocs = NULL;
3525         for (i = 0; i < buffer_count; i++) {
3526                 if (reloc_count + exec_list[i].relocation_count < reloc_count)
3527                         return -EINVAL;
3528                 reloc_count += exec_list[i].relocation_count;
3529         }
3530
3531         *relocs = drm_calloc_large(reloc_count, sizeof(**relocs));
3532         if (*relocs == NULL) {
3533                 DRM_ERROR("failed to alloc relocs, count %d\n", reloc_count);
3534                 return -ENOMEM;
3535         }
3536
3537         for (i = 0; i < buffer_count; i++) {
3538                 struct drm_i915_gem_relocation_entry __user *user_relocs;
3539
3540                 user_relocs = (void __user *)(uintptr_t)exec_list[i].relocs_ptr;
3541
3542                 ret = copy_from_user(&(*relocs)[reloc_index],
3543                                      user_relocs,
3544                                      exec_list[i].relocation_count *
3545                                      sizeof(**relocs));
3546                 if (ret != 0) {
3547                         drm_free_large(*relocs);
3548                         *relocs = NULL;
3549                         return -EFAULT;
3550                 }
3551
3552                 reloc_index += exec_list[i].relocation_count;
3553         }
3554
3555         return 0;
3556 }
3557
3558 static int
3559 i915_gem_put_relocs_to_user(struct drm_i915_gem_exec_object2 *exec_list,
3560                             uint32_t buffer_count,
3561                             struct drm_i915_gem_relocation_entry *relocs)
3562 {
3563         uint32_t reloc_count = 0, i;
3564         int ret = 0;
3565
3566         if (relocs == NULL)
3567             return 0;
3568
3569         for (i = 0; i < buffer_count; i++) {
3570                 struct drm_i915_gem_relocation_entry __user *user_relocs;
3571                 int unwritten;
3572
3573                 user_relocs = (void __user *)(uintptr_t)exec_list[i].relocs_ptr;
3574
3575                 unwritten = copy_to_user(user_relocs,
3576                                          &relocs[reloc_count],
3577                                          exec_list[i].relocation_count *
3578                                          sizeof(*relocs));
3579
3580                 if (unwritten) {
3581                         ret = -EFAULT;
3582                         goto err;
3583                 }
3584
3585                 reloc_count += exec_list[i].relocation_count;
3586         }
3587
3588 err:
3589         drm_free_large(relocs);
3590
3591         return ret;
3592 }
3593
3594 static int
3595 i915_gem_check_execbuffer (struct drm_i915_gem_execbuffer2 *exec,
3596                            uint64_t exec_offset)
3597 {
3598         uint32_t exec_start, exec_len;
3599
3600         exec_start = (uint32_t) exec_offset + exec->batch_start_offset;
3601         exec_len = (uint32_t) exec->batch_len;
3602
3603         if ((exec_start | exec_len) & 0x7)
3604                 return -EINVAL;
3605
3606         if (!exec_start)
3607                 return -EINVAL;
3608
3609         return 0;
3610 }
3611
3612 static int
3613 i915_gem_wait_for_pending_flip(struct drm_device *dev,
3614                                struct drm_gem_object **object_list,
3615                                int count)
3616 {
3617         drm_i915_private_t *dev_priv = dev->dev_private;
3618         struct drm_i915_gem_object *obj_priv;
3619         DEFINE_WAIT(wait);
3620         int i, ret = 0;
3621
3622         for (;;) {
3623                 prepare_to_wait(&dev_priv->pending_flip_queue,
3624                                 &wait, TASK_INTERRUPTIBLE);
3625                 for (i = 0; i < count; i++) {
3626                         obj_priv = to_intel_bo(object_list[i]);
3627                         if (atomic_read(&obj_priv->pending_flip) > 0)
3628                                 break;
3629                 }
3630                 if (i == count)
3631                         break;
3632
3633                 if (!signal_pending(current)) {
3634                         mutex_unlock(&dev->struct_mutex);
3635                         schedule();
3636                         mutex_lock(&dev->struct_mutex);
3637                         continue;
3638                 }
3639                 ret = -ERESTARTSYS;
3640                 break;
3641         }
3642         finish_wait(&dev_priv->pending_flip_queue, &wait);
3643
3644         return ret;
3645 }
3646
3647 int
3648 i915_gem_do_execbuffer(struct drm_device *dev, void *data,
3649                        struct drm_file *file_priv,
3650                        struct drm_i915_gem_execbuffer2 *args,
3651                        struct drm_i915_gem_exec_object2 *exec_list)
3652 {
3653         drm_i915_private_t *dev_priv = dev->dev_private;
3654         struct drm_gem_object **object_list = NULL;
3655         struct drm_gem_object *batch_obj;
3656         struct drm_i915_gem_object *obj_priv;
3657         struct drm_clip_rect *cliprects = NULL;
3658         struct drm_i915_gem_relocation_entry *relocs = NULL;
3659         int ret = 0, ret2, i, pinned = 0;
3660         uint64_t exec_offset;
3661         uint32_t seqno, flush_domains, reloc_index;
3662         int pin_tries, flips;
3663
3664         struct intel_ring_buffer *ring = NULL;
3665
3666 #if WATCH_EXEC
3667         DRM_INFO("buffers_ptr %d buffer_count %d len %08x\n",
3668                   (int) args->buffers_ptr, args->buffer_count, args->batch_len);
3669 #endif
3670         if (args->flags & I915_EXEC_BSD) {
3671                 if (!HAS_BSD(dev)) {
3672                         DRM_ERROR("execbuf with wrong flag\n");
3673                         return -EINVAL;
3674                 }
3675                 ring = &dev_priv->bsd_ring;
3676         } else {
3677                 ring = &dev_priv->render_ring;
3678         }
3679
3680
3681         if (args->buffer_count < 1) {
3682                 DRM_ERROR("execbuf with %d buffers\n", args->buffer_count);
3683                 return -EINVAL;
3684         }
3685         object_list = drm_malloc_ab(sizeof(*object_list), args->buffer_count);
3686         if (object_list == NULL) {
3687                 DRM_ERROR("Failed to allocate object list for %d buffers\n",
3688                           args->buffer_count);
3689                 ret = -ENOMEM;
3690                 goto pre_mutex_err;
3691         }
3692
3693         if (args->num_cliprects != 0) {
3694                 cliprects = kcalloc(args->num_cliprects, sizeof(*cliprects),
3695                                     GFP_KERNEL);
3696                 if (cliprects == NULL) {
3697                         ret = -ENOMEM;
3698                         goto pre_mutex_err;
3699                 }
3700
3701                 ret = copy_from_user(cliprects,
3702                                      (struct drm_clip_rect __user *)
3703                                      (uintptr_t) args->cliprects_ptr,
3704                                      sizeof(*cliprects) * args->num_cliprects);
3705                 if (ret != 0) {
3706                         DRM_ERROR("copy %d cliprects failed: %d\n",
3707                                   args->num_cliprects, ret);
3708                         goto pre_mutex_err;
3709                 }
3710         }
3711
3712         ret = i915_gem_get_relocs_from_user(exec_list, args->buffer_count,
3713                                             &relocs);
3714         if (ret != 0)
3715                 goto pre_mutex_err;
3716
3717         mutex_lock(&dev->struct_mutex);
3718
3719         i915_verify_inactive(dev, __FILE__, __LINE__);
3720
3721         if (atomic_read(&dev_priv->mm.wedged)) {
3722                 mutex_unlock(&dev->struct_mutex);
3723                 ret = -EIO;
3724                 goto pre_mutex_err;
3725         }
3726
3727         if (dev_priv->mm.suspended) {
3728                 mutex_unlock(&dev->struct_mutex);
3729                 ret = -EBUSY;
3730                 goto pre_mutex_err;
3731         }
3732
3733         /* Look up object handles */
3734         flips = 0;
3735         for (i = 0; i < args->buffer_count; i++) {
3736                 object_list[i] = drm_gem_object_lookup(dev, file_priv,
3737                                                        exec_list[i].handle);
3738                 if (object_list[i] == NULL) {
3739                         DRM_ERROR("Invalid object handle %d at index %d\n",
3740                                    exec_list[i].handle, i);
3741                         /* prevent error path from reading uninitialized data */
3742                         args->buffer_count = i + 1;
3743                         ret = -EBADF;
3744                         goto err;
3745                 }
3746
3747                 obj_priv = to_intel_bo(object_list[i]);
3748                 if (obj_priv->in_execbuffer) {
3749                         DRM_ERROR("Object %p appears more than once in object list\n",
3750                                    object_list[i]);
3751                         /* prevent error path from reading uninitialized data */
3752                         args->buffer_count = i + 1;
3753                         ret = -EBADF;
3754                         goto err;
3755                 }
3756                 obj_priv->in_execbuffer = true;
3757                 flips += atomic_read(&obj_priv->pending_flip);
3758         }
3759
3760         if (flips > 0) {
3761                 ret = i915_gem_wait_for_pending_flip(dev, object_list,
3762                                                      args->buffer_count);
3763                 if (ret)
3764                         goto err;
3765         }
3766
3767         /* Pin and relocate */
3768         for (pin_tries = 0; ; pin_tries++) {
3769                 ret = 0;
3770                 reloc_index = 0;
3771
3772                 for (i = 0; i < args->buffer_count; i++) {
3773                         object_list[i]->pending_read_domains = 0;
3774                         object_list[i]->pending_write_domain = 0;
3775                         ret = i915_gem_object_pin_and_relocate(object_list[i],
3776                                                                file_priv,
3777                                                                &exec_list[i],
3778                                                                &relocs[reloc_index]);
3779                         if (ret)
3780                                 break;
3781                         pinned = i + 1;
3782                         reloc_index += exec_list[i].relocation_count;
3783                 }
3784                 /* success */
3785                 if (ret == 0)
3786                         break;
3787
3788                 /* error other than GTT full, or we've already tried again */
3789                 if (ret != -ENOSPC || pin_tries >= 1) {
3790                         if (ret != -ERESTARTSYS) {
3791                                 unsigned long long total_size = 0;
3792                                 int num_fences = 0;
3793                                 for (i = 0; i < args->buffer_count; i++) {
3794                                         obj_priv = object_list[i]->driver_private;
3795
3796                                         total_size += object_list[i]->size;
3797                                         num_fences +=
3798                                                 exec_list[i].flags & EXEC_OBJECT_NEEDS_FENCE &&
3799                                                 obj_priv->tiling_mode != I915_TILING_NONE;
3800                                 }
3801                                 DRM_ERROR("Failed to pin buffer %d of %d, total %llu bytes, %d fences: %d\n",
3802                                           pinned+1, args->buffer_count,
3803                                           total_size, num_fences,
3804                                           ret);
3805                                 DRM_ERROR("%d objects [%d pinned], "
3806                                           "%d object bytes [%d pinned], "
3807                                           "%d/%d gtt bytes\n",
3808                                           atomic_read(&dev->object_count),
3809                                           atomic_read(&dev->pin_count),
3810                                           atomic_read(&dev->object_memory),
3811                                           atomic_read(&dev->pin_memory),
3812                                           atomic_read(&dev->gtt_memory),
3813                                           dev->gtt_total);
3814                         }
3815                         goto err;
3816                 }
3817
3818                 /* unpin all of our buffers */
3819                 for (i = 0; i < pinned; i++)
3820                         i915_gem_object_unpin(object_list[i]);
3821                 pinned = 0;
3822
3823                 /* evict everyone we can from the aperture */
3824                 ret = i915_gem_evict_everything(dev);
3825                 if (ret && ret != -ENOSPC)
3826                         goto err;
3827         }
3828
3829         /* Set the pending read domains for the batch buffer to COMMAND */
3830         batch_obj = object_list[args->buffer_count-1];
3831         if (batch_obj->pending_write_domain) {
3832                 DRM_ERROR("Attempting to use self-modifying batch buffer\n");
3833                 ret = -EINVAL;
3834                 goto err;
3835         }
3836         batch_obj->pending_read_domains |= I915_GEM_DOMAIN_COMMAND;
3837
3838         /* Sanity check the batch buffer, prior to moving objects */
3839         exec_offset = exec_list[args->buffer_count - 1].offset;
3840         ret = i915_gem_check_execbuffer (args, exec_offset);
3841         if (ret != 0) {
3842                 DRM_ERROR("execbuf with invalid offset/length\n");
3843                 goto err;
3844         }
3845
3846         i915_verify_inactive(dev, __FILE__, __LINE__);
3847
3848         /* Zero the global flush/invalidate flags. These
3849          * will be modified as new domains are computed
3850          * for each object
3851          */
3852         dev->invalidate_domains = 0;
3853         dev->flush_domains = 0;
3854
3855         for (i = 0; i < args->buffer_count; i++) {
3856                 struct drm_gem_object *obj = object_list[i];
3857
3858                 /* Compute new gpu domains and update invalidate/flush */
3859                 i915_gem_object_set_to_gpu_domain(obj);
3860         }
3861
3862         i915_verify_inactive(dev, __FILE__, __LINE__);
3863
3864         if (dev->invalidate_domains | dev->flush_domains) {
3865 #if WATCH_EXEC
3866                 DRM_INFO("%s: invalidate_domains %08x flush_domains %08x\n",
3867                           __func__,
3868                          dev->invalidate_domains,
3869                          dev->flush_domains);
3870 #endif
3871                 i915_gem_flush(dev,
3872                                dev->invalidate_domains,
3873                                dev->flush_domains);
3874                 if (dev->flush_domains & I915_GEM_GPU_DOMAINS) {
3875                         (void)i915_add_request(dev, file_priv,
3876                                         dev->flush_domains,
3877                                         &dev_priv->render_ring);
3878
3879                         if (HAS_BSD(dev))
3880                                 (void)i915_add_request(dev, file_priv,
3881                                                 dev->flush_domains,
3882                                                 &dev_priv->bsd_ring);
3883                 }
3884         }
3885
3886         for (i = 0; i < args->buffer_count; i++) {
3887                 struct drm_gem_object *obj = object_list[i];
3888                 struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
3889                 uint32_t old_write_domain = obj->write_domain;
3890
3891                 obj->write_domain = obj->pending_write_domain;
3892                 if (obj->write_domain)
3893                         list_move_tail(&obj_priv->gpu_write_list,
3894                                        &dev_priv->mm.gpu_write_list);
3895                 else
3896                         list_del_init(&obj_priv->gpu_write_list);
3897
3898                 trace_i915_gem_object_change_domain(obj,
3899                                                     obj->read_domains,
3900                                                     old_write_domain);
3901         }
3902
3903         i915_verify_inactive(dev, __FILE__, __LINE__);
3904
3905 #if WATCH_COHERENCY
3906         for (i = 0; i < args->buffer_count; i++) {
3907                 i915_gem_object_check_coherency(object_list[i],
3908                                                 exec_list[i].handle);
3909         }
3910 #endif
3911
3912 #if WATCH_EXEC
3913         i915_gem_dump_object(batch_obj,
3914                               args->batch_len,
3915                               __func__,
3916                               ~0);
3917 #endif
3918
3919         /* Exec the batchbuffer */
3920         ret = ring->dispatch_gem_execbuffer(dev, ring, args,
3921                         cliprects, exec_offset);
3922         if (ret) {
3923                 DRM_ERROR("dispatch failed %d\n", ret);
3924                 goto err;
3925         }
3926
3927         /*
3928          * Ensure that the commands in the batch buffer are
3929          * finished before the interrupt fires
3930          */
3931         flush_domains = i915_retire_commands(dev, ring);
3932
3933         i915_verify_inactive(dev, __FILE__, __LINE__);
3934
3935         /*
3936          * Get a seqno representing the execution of the current buffer,
3937          * which we can wait on.  We would like to mitigate these interrupts,
3938          * likely by only creating seqnos occasionally (so that we have
3939          * *some* interrupts representing completion of buffers that we can
3940          * wait on when trying to clear up gtt space).
3941          */
3942         seqno = i915_add_request(dev, file_priv, flush_domains, ring);
3943         BUG_ON(seqno == 0);
3944         for (i = 0; i < args->buffer_count; i++) {
3945                 struct drm_gem_object *obj = object_list[i];
3946                 obj_priv = to_intel_bo(obj);
3947
3948                 i915_gem_object_move_to_active(obj, seqno, ring);
3949 #if WATCH_LRU
3950                 DRM_INFO("%s: move to exec list %p\n", __func__, obj);
3951 #endif
3952         }
3953 #if WATCH_LRU
3954         i915_dump_lru(dev, __func__);
3955 #endif
3956
3957         i915_verify_inactive(dev, __FILE__, __LINE__);
3958
3959 err:
3960         for (i = 0; i < pinned; i++)
3961                 i915_gem_object_unpin(object_list[i]);
3962
3963         for (i = 0; i < args->buffer_count; i++) {
3964                 if (object_list[i]) {
3965                         obj_priv = to_intel_bo(object_list[i]);
3966                         obj_priv->in_execbuffer = false;
3967                 }
3968                 drm_gem_object_unreference(object_list[i]);
3969         }
3970
3971         mutex_unlock(&dev->struct_mutex);
3972
3973 pre_mutex_err:
3974         /* Copy the updated relocations out regardless of current error
3975          * state.  Failure to update the relocs would mean that the next
3976          * time userland calls execbuf, it would do so with presumed offset
3977          * state that didn't match the actual object state.
3978          */
3979         ret2 = i915_gem_put_relocs_to_user(exec_list, args->buffer_count,
3980                                            relocs);
3981         if (ret2 != 0) {
3982                 DRM_ERROR("Failed to copy relocations back out: %d\n", ret2);
3983
3984                 if (ret == 0)
3985                         ret = ret2;
3986         }
3987
3988         drm_free_large(object_list);
3989         kfree(cliprects);
3990
3991         return ret;
3992 }
3993
3994 /*
3995  * Legacy execbuffer just creates an exec2 list from the original exec object
3996  * list array and passes it to the real function.
3997  */
3998 int
3999 i915_gem_execbuffer(struct drm_device *dev, void *data,
4000                     struct drm_file *file_priv)
4001 {
4002         struct drm_i915_gem_execbuffer *args = data;
4003         struct drm_i915_gem_execbuffer2 exec2;
4004         struct drm_i915_gem_exec_object *exec_list = NULL;
4005         struct drm_i915_gem_exec_object2 *exec2_list = NULL;
4006         int ret, i;
4007
4008 #if WATCH_EXEC
4009         DRM_INFO("buffers_ptr %d buffer_count %d len %08x\n",
4010                   (int) args->buffers_ptr, args->buffer_count, args->batch_len);
4011 #endif
4012
4013         if (args->buffer_count < 1) {
4014                 DRM_ERROR("execbuf with %d buffers\n", args->buffer_count);
4015                 return -EINVAL;
4016         }
4017
4018         /* Copy in the exec list from userland */
4019         exec_list = drm_malloc_ab(sizeof(*exec_list), args->buffer_count);
4020         exec2_list = drm_malloc_ab(sizeof(*exec2_list), args->buffer_count);
4021         if (exec_list == NULL || exec2_list == NULL) {
4022                 DRM_ERROR("Failed to allocate exec list for %d buffers\n",
4023                           args->buffer_count);
4024                 drm_free_large(exec_list);
4025                 drm_free_large(exec2_list);
4026                 return -ENOMEM;
4027         }
4028         ret = copy_from_user(exec_list,
4029                              (struct drm_i915_relocation_entry __user *)
4030                              (uintptr_t) args->buffers_ptr,
4031                              sizeof(*exec_list) * args->buffer_count);
4032         if (ret != 0) {
4033                 DRM_ERROR("copy %d exec entries failed %d\n",
4034                           args->buffer_count, ret);
4035                 drm_free_large(exec_list);
4036                 drm_free_large(exec2_list);
4037                 return -EFAULT;
4038         }
4039
4040         for (i = 0; i < args->buffer_count; i++) {
4041                 exec2_list[i].handle = exec_list[i].handle;
4042                 exec2_list[i].relocation_count = exec_list[i].relocation_count;
4043                 exec2_list[i].relocs_ptr = exec_list[i].relocs_ptr;
4044                 exec2_list[i].alignment = exec_list[i].alignment;
4045                 exec2_list[i].offset = exec_list[i].offset;
4046                 if (!IS_I965G(dev))
4047                         exec2_list[i].flags = EXEC_OBJECT_NEEDS_FENCE;
4048                 else
4049                         exec2_list[i].flags = 0;
4050         }
4051
4052         exec2.buffers_ptr = args->buffers_ptr;
4053         exec2.buffer_count = args->buffer_count;
4054         exec2.batch_start_offset = args->batch_start_offset;
4055         exec2.batch_len = args->batch_len;
4056         exec2.DR1 = args->DR1;
4057         exec2.DR4 = args->DR4;
4058         exec2.num_cliprects = args->num_cliprects;
4059         exec2.cliprects_ptr = args->cliprects_ptr;
4060         exec2.flags = I915_EXEC_RENDER;
4061
4062         ret = i915_gem_do_execbuffer(dev, data, file_priv, &exec2, exec2_list);
4063         if (!ret) {
4064                 /* Copy the new buffer offsets back to the user's exec list. */
4065                 for (i = 0; i < args->buffer_count; i++)
4066                         exec_list[i].offset = exec2_list[i].offset;
4067                 /* ... and back out to userspace */
4068                 ret = copy_to_user((struct drm_i915_relocation_entry __user *)
4069                                    (uintptr_t) args->buffers_ptr,
4070                                    exec_list,
4071                                    sizeof(*exec_list) * args->buffer_count);
4072                 if (ret) {
4073                         ret = -EFAULT;
4074                         DRM_ERROR("failed to copy %d exec entries "
4075                                   "back to user (%d)\n",
4076                                   args->buffer_count, ret);
4077                 }
4078         }
4079
4080         drm_free_large(exec_list);
4081         drm_free_large(exec2_list);
4082         return ret;
4083 }
4084
4085 int
4086 i915_gem_execbuffer2(struct drm_device *dev, void *data,
4087                      struct drm_file *file_priv)
4088 {
4089         struct drm_i915_gem_execbuffer2 *args = data;
4090         struct drm_i915_gem_exec_object2 *exec2_list = NULL;
4091         int ret;
4092
4093 #if WATCH_EXEC
4094         DRM_INFO("buffers_ptr %d buffer_count %d len %08x\n",
4095                   (int) args->buffers_ptr, args->buffer_count, args->batch_len);
4096 #endif
4097
4098         if (args->buffer_count < 1) {
4099                 DRM_ERROR("execbuf2 with %d buffers\n", args->buffer_count);
4100                 return -EINVAL;
4101         }
4102
4103         exec2_list = drm_malloc_ab(sizeof(*exec2_list), args->buffer_count);
4104         if (exec2_list == NULL) {
4105                 DRM_ERROR("Failed to allocate exec list for %d buffers\n",
4106                           args->buffer_count);
4107                 return -ENOMEM;
4108         }
4109         ret = copy_from_user(exec2_list,
4110                              (struct drm_i915_relocation_entry __user *)
4111                              (uintptr_t) args->buffers_ptr,
4112                              sizeof(*exec2_list) * args->buffer_count);
4113         if (ret != 0) {
4114                 DRM_ERROR("copy %d exec entries failed %d\n",
4115                           args->buffer_count, ret);
4116                 drm_free_large(exec2_list);
4117                 return -EFAULT;
4118         }
4119
4120         ret = i915_gem_do_execbuffer(dev, data, file_priv, args, exec2_list);
4121         if (!ret) {
4122                 /* Copy the new buffer offsets back to the user's exec list. */
4123                 ret = copy_to_user((struct drm_i915_relocation_entry __user *)
4124                                    (uintptr_t) args->buffers_ptr,
4125                                    exec2_list,
4126                                    sizeof(*exec2_list) * args->buffer_count);
4127                 if (ret) {
4128                         ret = -EFAULT;
4129                         DRM_ERROR("failed to copy %d exec entries "
4130                                   "back to user (%d)\n",
4131                                   args->buffer_count, ret);
4132                 }
4133         }
4134
4135         drm_free_large(exec2_list);
4136         return ret;
4137 }
4138
4139 int
4140 i915_gem_object_pin(struct drm_gem_object *obj, uint32_t alignment)
4141 {
4142         struct drm_device *dev = obj->dev;
4143         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
4144         int ret;
4145
4146         BUG_ON(obj_priv->pin_count == DRM_I915_GEM_OBJECT_MAX_PIN_COUNT);
4147
4148         i915_verify_inactive(dev, __FILE__, __LINE__);
4149
4150         if (obj_priv->gtt_space != NULL) {
4151                 if (alignment == 0)
4152                         alignment = i915_gem_get_gtt_alignment(obj);
4153                 if (obj_priv->gtt_offset & (alignment - 1)) {
4154                         ret = i915_gem_object_unbind(obj);
4155                         if (ret)
4156                                 return ret;
4157                 }
4158         }
4159
4160         if (obj_priv->gtt_space == NULL) {
4161                 ret = i915_gem_object_bind_to_gtt(obj, alignment);
4162                 if (ret)
4163                         return ret;
4164         }
4165
4166         obj_priv->pin_count++;
4167
4168         /* If the object is not active and not pending a flush,
4169          * remove it from the inactive list
4170          */
4171         if (obj_priv->pin_count == 1) {
4172                 atomic_inc(&dev->pin_count);
4173                 atomic_add(obj->size, &dev->pin_memory);
4174                 if (!obj_priv->active &&
4175                     (obj->write_domain & I915_GEM_GPU_DOMAINS) == 0 &&
4176                     !list_empty(&obj_priv->list))
4177                         list_del_init(&obj_priv->list);
4178         }
4179         i915_verify_inactive(dev, __FILE__, __LINE__);
4180
4181         return 0;
4182 }
4183
4184 void
4185 i915_gem_object_unpin(struct drm_gem_object *obj)
4186 {
4187         struct drm_device *dev = obj->dev;
4188         drm_i915_private_t *dev_priv = dev->dev_private;
4189         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
4190
4191         i915_verify_inactive(dev, __FILE__, __LINE__);
4192         obj_priv->pin_count--;
4193         BUG_ON(obj_priv->pin_count < 0);
4194         BUG_ON(obj_priv->gtt_space == NULL);
4195
4196         /* If the object is no longer pinned, and is
4197          * neither active nor being flushed, then stick it on
4198          * the inactive list
4199          */
4200         if (obj_priv->pin_count == 0) {
4201                 if (!obj_priv->active &&
4202                     (obj->write_domain & I915_GEM_GPU_DOMAINS) == 0)
4203                         list_move_tail(&obj_priv->list,
4204                                        &dev_priv->mm.inactive_list);
4205                 atomic_dec(&dev->pin_count);
4206                 atomic_sub(obj->size, &dev->pin_memory);
4207         }
4208         i915_verify_inactive(dev, __FILE__, __LINE__);
4209 }
4210
4211 int
4212 i915_gem_pin_ioctl(struct drm_device *dev, void *data,
4213                    struct drm_file *file_priv)
4214 {
4215         struct drm_i915_gem_pin *args = data;
4216         struct drm_gem_object *obj;
4217         struct drm_i915_gem_object *obj_priv;
4218         int ret;
4219
4220         mutex_lock(&dev->struct_mutex);
4221
4222         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
4223         if (obj == NULL) {
4224                 DRM_ERROR("Bad handle in i915_gem_pin_ioctl(): %d\n",
4225                           args->handle);
4226                 mutex_unlock(&dev->struct_mutex);
4227                 return -EBADF;
4228         }
4229         obj_priv = to_intel_bo(obj);
4230
4231         if (obj_priv->madv != I915_MADV_WILLNEED) {
4232                 DRM_ERROR("Attempting to pin a purgeable buffer\n");
4233                 drm_gem_object_unreference(obj);
4234                 mutex_unlock(&dev->struct_mutex);
4235                 return -EINVAL;
4236         }
4237
4238         if (obj_priv->pin_filp != NULL && obj_priv->pin_filp != file_priv) {
4239                 DRM_ERROR("Already pinned in i915_gem_pin_ioctl(): %d\n",
4240                           args->handle);
4241                 drm_gem_object_unreference(obj);
4242                 mutex_unlock(&dev->struct_mutex);
4243                 return -EINVAL;
4244         }
4245
4246         obj_priv->user_pin_count++;
4247         obj_priv->pin_filp = file_priv;
4248         if (obj_priv->user_pin_count == 1) {
4249                 ret = i915_gem_object_pin(obj, args->alignment);
4250                 if (ret != 0) {
4251                         drm_gem_object_unreference(obj);
4252                         mutex_unlock(&dev->struct_mutex);
4253                         return ret;
4254                 }
4255         }
4256
4257         /* XXX - flush the CPU caches for pinned objects
4258          * as the X server doesn't manage domains yet
4259          */
4260         i915_gem_object_flush_cpu_write_domain(obj);
4261         args->offset = obj_priv->gtt_offset;
4262         drm_gem_object_unreference(obj);
4263         mutex_unlock(&dev->struct_mutex);
4264
4265         return 0;
4266 }
4267
4268 int
4269 i915_gem_unpin_ioctl(struct drm_device *dev, void *data,
4270                      struct drm_file *file_priv)
4271 {
4272         struct drm_i915_gem_pin *args = data;
4273         struct drm_gem_object *obj;
4274         struct drm_i915_gem_object *obj_priv;
4275
4276         mutex_lock(&dev->struct_mutex);
4277
4278         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
4279         if (obj == NULL) {
4280                 DRM_ERROR("Bad handle in i915_gem_unpin_ioctl(): %d\n",
4281                           args->handle);
4282                 mutex_unlock(&dev->struct_mutex);
4283                 return -EBADF;
4284         }
4285
4286         obj_priv = to_intel_bo(obj);
4287         if (obj_priv->pin_filp != file_priv) {
4288                 DRM_ERROR("Not pinned by caller in i915_gem_pin_ioctl(): %d\n",
4289                           args->handle);
4290                 drm_gem_object_unreference(obj);
4291                 mutex_unlock(&dev->struct_mutex);
4292                 return -EINVAL;
4293         }
4294         obj_priv->user_pin_count--;
4295         if (obj_priv->user_pin_count == 0) {
4296                 obj_priv->pin_filp = NULL;
4297                 i915_gem_object_unpin(obj);
4298         }
4299
4300         drm_gem_object_unreference(obj);
4301         mutex_unlock(&dev->struct_mutex);
4302         return 0;
4303 }
4304
4305 int
4306 i915_gem_busy_ioctl(struct drm_device *dev, void *data,
4307                     struct drm_file *file_priv)
4308 {
4309         struct drm_i915_gem_busy *args = data;
4310         struct drm_gem_object *obj;
4311         struct drm_i915_gem_object *obj_priv;
4312         drm_i915_private_t *dev_priv = dev->dev_private;
4313
4314         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
4315         if (obj == NULL) {
4316                 DRM_ERROR("Bad handle in i915_gem_busy_ioctl(): %d\n",
4317                           args->handle);
4318                 return -EBADF;
4319         }
4320
4321         mutex_lock(&dev->struct_mutex);
4322         /* Update the active list for the hardware's current position.
4323          * Otherwise this only updates on a delayed timer or when irqs are
4324          * actually unmasked, and our working set ends up being larger than
4325          * required.
4326          */
4327         i915_gem_retire_requests(dev, &dev_priv->render_ring);
4328
4329         if (HAS_BSD(dev))
4330                 i915_gem_retire_requests(dev, &dev_priv->bsd_ring);
4331
4332         obj_priv = to_intel_bo(obj);
4333         /* Don't count being on the flushing list against the object being
4334          * done.  Otherwise, a buffer left on the flushing list but not getting
4335          * flushed (because nobody's flushing that domain) won't ever return
4336          * unbusy and get reused by libdrm's bo cache.  The other expected
4337          * consumer of this interface, OpenGL's occlusion queries, also specs
4338          * that the objects get unbusy "eventually" without any interference.
4339          */
4340         args->busy = obj_priv->active && obj_priv->last_rendering_seqno != 0;
4341
4342         drm_gem_object_unreference(obj);
4343         mutex_unlock(&dev->struct_mutex);
4344         return 0;
4345 }
4346
4347 int
4348 i915_gem_throttle_ioctl(struct drm_device *dev, void *data,
4349                         struct drm_file *file_priv)
4350 {
4351     return i915_gem_ring_throttle(dev, file_priv);
4352 }
4353
4354 int
4355 i915_gem_madvise_ioctl(struct drm_device *dev, void *data,
4356                        struct drm_file *file_priv)
4357 {
4358         struct drm_i915_gem_madvise *args = data;
4359         struct drm_gem_object *obj;
4360         struct drm_i915_gem_object *obj_priv;
4361
4362         switch (args->madv) {
4363         case I915_MADV_DONTNEED:
4364         case I915_MADV_WILLNEED:
4365             break;
4366         default:
4367             return -EINVAL;
4368         }
4369
4370         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
4371         if (obj == NULL) {
4372                 DRM_ERROR("Bad handle in i915_gem_madvise_ioctl(): %d\n",
4373                           args->handle);
4374                 return -EBADF;
4375         }
4376
4377         mutex_lock(&dev->struct_mutex);
4378         obj_priv = to_intel_bo(obj);
4379
4380         if (obj_priv->pin_count) {
4381                 drm_gem_object_unreference(obj);
4382                 mutex_unlock(&dev->struct_mutex);
4383
4384                 DRM_ERROR("Attempted i915_gem_madvise_ioctl() on a pinned object\n");
4385                 return -EINVAL;
4386         }
4387
4388         if (obj_priv->madv != __I915_MADV_PURGED)
4389                 obj_priv->madv = args->madv;
4390
4391         /* if the object is no longer bound, discard its backing storage */
4392         if (i915_gem_object_is_purgeable(obj_priv) &&
4393             obj_priv->gtt_space == NULL)
4394                 i915_gem_object_truncate(obj);
4395
4396         args->retained = obj_priv->madv != __I915_MADV_PURGED;
4397
4398         drm_gem_object_unreference(obj);
4399         mutex_unlock(&dev->struct_mutex);
4400
4401         return 0;
4402 }
4403
4404 struct drm_gem_object * i915_gem_alloc_object(struct drm_device *dev,
4405                                               size_t size)
4406 {
4407         struct drm_i915_gem_object *obj;
4408
4409         obj = kzalloc(sizeof(*obj), GFP_KERNEL);
4410         if (obj == NULL)
4411                 return NULL;
4412
4413         if (drm_gem_object_init(dev, &obj->base, size) != 0) {
4414                 kfree(obj);
4415                 return NULL;
4416         }
4417
4418         obj->base.write_domain = I915_GEM_DOMAIN_CPU;
4419         obj->base.read_domains = I915_GEM_DOMAIN_CPU;
4420
4421         obj->agp_type = AGP_USER_MEMORY;
4422         obj->base.driver_private = NULL;
4423         obj->fence_reg = I915_FENCE_REG_NONE;
4424         INIT_LIST_HEAD(&obj->list);
4425         INIT_LIST_HEAD(&obj->gpu_write_list);
4426         obj->madv = I915_MADV_WILLNEED;
4427
4428         trace_i915_gem_object_create(&obj->base);
4429
4430         return &obj->base;
4431 }
4432
4433 int i915_gem_init_object(struct drm_gem_object *obj)
4434 {
4435         BUG();
4436
4437         return 0;
4438 }
4439
4440 void i915_gem_free_object(struct drm_gem_object *obj)
4441 {
4442         struct drm_device *dev = obj->dev;
4443         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
4444
4445         trace_i915_gem_object_destroy(obj);
4446
4447         while (obj_priv->pin_count > 0)
4448                 i915_gem_object_unpin(obj);
4449
4450         if (obj_priv->phys_obj)
4451                 i915_gem_detach_phys_object(dev, obj);
4452
4453         i915_gem_object_unbind(obj);
4454
4455         if (obj_priv->mmap_offset)
4456                 i915_gem_free_mmap_offset(obj);
4457
4458         drm_gem_object_release(obj);
4459
4460         kfree(obj_priv->page_cpu_valid);
4461         kfree(obj_priv->bit_17);
4462         kfree(obj_priv);
4463 }
4464
4465 /** Unbinds all inactive objects. */
4466 static int
4467 i915_gem_evict_from_inactive_list(struct drm_device *dev)
4468 {
4469         drm_i915_private_t *dev_priv = dev->dev_private;
4470
4471         while (!list_empty(&dev_priv->mm.inactive_list)) {
4472                 struct drm_gem_object *obj;
4473                 int ret;
4474
4475                 obj = &list_first_entry(&dev_priv->mm.inactive_list,
4476                                         struct drm_i915_gem_object,
4477                                         list)->base;
4478
4479                 ret = i915_gem_object_unbind(obj);
4480                 if (ret != 0) {
4481                         DRM_ERROR("Error unbinding object: %d\n", ret);
4482                         return ret;
4483                 }
4484         }
4485
4486         return 0;
4487 }
4488
4489 int
4490 i915_gem_idle(struct drm_device *dev)
4491 {
4492         drm_i915_private_t *dev_priv = dev->dev_private;
4493         int ret;
4494
4495         mutex_lock(&dev->struct_mutex);
4496
4497         if (dev_priv->mm.suspended ||
4498                         (dev_priv->render_ring.gem_object == NULL) ||
4499                         (HAS_BSD(dev) &&
4500                          dev_priv->bsd_ring.gem_object == NULL)) {
4501                 mutex_unlock(&dev->struct_mutex);
4502                 return 0;
4503         }
4504
4505         ret = i915_gpu_idle(dev);
4506         if (ret) {
4507                 mutex_unlock(&dev->struct_mutex);
4508                 return ret;
4509         }
4510
4511         /* Under UMS, be paranoid and evict. */
4512         if (!drm_core_check_feature(dev, DRIVER_MODESET)) {
4513                 ret = i915_gem_evict_from_inactive_list(dev);
4514                 if (ret) {
4515                         mutex_unlock(&dev->struct_mutex);
4516                         return ret;
4517                 }
4518         }
4519
4520         /* Hack!  Don't let anybody do execbuf while we don't control the chip.
4521          * We need to replace this with a semaphore, or something.
4522          * And not confound mm.suspended!
4523          */
4524         dev_priv->mm.suspended = 1;
4525         del_timer(&dev_priv->hangcheck_timer);
4526
4527         i915_kernel_lost_context(dev);
4528         i915_gem_cleanup_ringbuffer(dev);
4529
4530         mutex_unlock(&dev->struct_mutex);
4531
4532         /* Cancel the retire work handler, which should be idle now. */
4533         cancel_delayed_work_sync(&dev_priv->mm.retire_work);
4534
4535         return 0;
4536 }
4537
4538 /*
4539  * 965+ support PIPE_CONTROL commands, which provide finer grained control
4540  * over cache flushing.
4541  */
4542 static int
4543 i915_gem_init_pipe_control(struct drm_device *dev)
4544 {
4545         drm_i915_private_t *dev_priv = dev->dev_private;
4546         struct drm_gem_object *obj;
4547         struct drm_i915_gem_object *obj_priv;
4548         int ret;
4549
4550         obj = i915_gem_alloc_object(dev, 4096);
4551         if (obj == NULL) {
4552                 DRM_ERROR("Failed to allocate seqno page\n");
4553                 ret = -ENOMEM;
4554                 goto err;
4555         }
4556         obj_priv = to_intel_bo(obj);
4557         obj_priv->agp_type = AGP_USER_CACHED_MEMORY;
4558
4559         ret = i915_gem_object_pin(obj, 4096);
4560         if (ret)
4561                 goto err_unref;
4562
4563         dev_priv->seqno_gfx_addr = obj_priv->gtt_offset;
4564         dev_priv->seqno_page =  kmap(obj_priv->pages[0]);
4565         if (dev_priv->seqno_page == NULL)
4566                 goto err_unpin;
4567
4568         dev_priv->seqno_obj = obj;
4569         memset(dev_priv->seqno_page, 0, PAGE_SIZE);
4570
4571         return 0;
4572
4573 err_unpin:
4574         i915_gem_object_unpin(obj);
4575 err_unref:
4576         drm_gem_object_unreference(obj);
4577 err:
4578         return ret;
4579 }
4580
4581
4582 static void
4583 i915_gem_cleanup_pipe_control(struct drm_device *dev)
4584 {
4585         drm_i915_private_t *dev_priv = dev->dev_private;
4586         struct drm_gem_object *obj;
4587         struct drm_i915_gem_object *obj_priv;
4588
4589         obj = dev_priv->seqno_obj;
4590         obj_priv = to_intel_bo(obj);
4591         kunmap(obj_priv->pages[0]);
4592         i915_gem_object_unpin(obj);
4593         drm_gem_object_unreference(obj);
4594         dev_priv->seqno_obj = NULL;
4595
4596         dev_priv->seqno_page = NULL;
4597 }
4598
4599 int
4600 i915_gem_init_ringbuffer(struct drm_device *dev)
4601 {
4602         drm_i915_private_t *dev_priv = dev->dev_private;
4603         int ret;
4604
4605         dev_priv->render_ring = render_ring;
4606
4607         if (!I915_NEED_GFX_HWS(dev)) {
4608                 dev_priv->render_ring.status_page.page_addr
4609                         = dev_priv->status_page_dmah->vaddr;
4610                 memset(dev_priv->render_ring.status_page.page_addr,
4611                                 0, PAGE_SIZE);
4612         }
4613
4614         if (HAS_PIPE_CONTROL(dev)) {
4615                 ret = i915_gem_init_pipe_control(dev);
4616                 if (ret)
4617                         return ret;
4618         }
4619
4620         ret = intel_init_ring_buffer(dev, &dev_priv->render_ring);
4621         if (ret)
4622                 goto cleanup_pipe_control;
4623
4624         if (HAS_BSD(dev)) {
4625                 dev_priv->bsd_ring = bsd_ring;
4626                 ret = intel_init_ring_buffer(dev, &dev_priv->bsd_ring);
4627                 if (ret)
4628                         goto cleanup_render_ring;
4629         }
4630
4631         return 0;
4632
4633 cleanup_render_ring:
4634         intel_cleanup_ring_buffer(dev, &dev_priv->render_ring);
4635 cleanup_pipe_control:
4636         if (HAS_PIPE_CONTROL(dev))
4637                 i915_gem_cleanup_pipe_control(dev);
4638         return ret;
4639 }
4640
4641 void
4642 i915_gem_cleanup_ringbuffer(struct drm_device *dev)
4643 {
4644         drm_i915_private_t *dev_priv = dev->dev_private;
4645
4646         intel_cleanup_ring_buffer(dev, &dev_priv->render_ring);
4647         if (HAS_BSD(dev))
4648                 intel_cleanup_ring_buffer(dev, &dev_priv->bsd_ring);
4649         if (HAS_PIPE_CONTROL(dev))
4650                 i915_gem_cleanup_pipe_control(dev);
4651 }
4652
4653 int
4654 i915_gem_entervt_ioctl(struct drm_device *dev, void *data,
4655                        struct drm_file *file_priv)
4656 {
4657         drm_i915_private_t *dev_priv = dev->dev_private;
4658         int ret;
4659
4660         if (drm_core_check_feature(dev, DRIVER_MODESET))
4661                 return 0;
4662
4663         if (atomic_read(&dev_priv->mm.wedged)) {
4664                 DRM_ERROR("Reenabling wedged hardware, good luck\n");
4665                 atomic_set(&dev_priv->mm.wedged, 0);
4666         }
4667
4668         mutex_lock(&dev->struct_mutex);
4669         dev_priv->mm.suspended = 0;
4670
4671         ret = i915_gem_init_ringbuffer(dev);
4672         if (ret != 0) {
4673                 mutex_unlock(&dev->struct_mutex);
4674                 return ret;
4675         }
4676
4677         spin_lock(&dev_priv->mm.active_list_lock);
4678         BUG_ON(!list_empty(&dev_priv->render_ring.active_list));
4679         BUG_ON(HAS_BSD(dev) && !list_empty(&dev_priv->bsd_ring.active_list));
4680         spin_unlock(&dev_priv->mm.active_list_lock);
4681
4682         BUG_ON(!list_empty(&dev_priv->mm.flushing_list));
4683         BUG_ON(!list_empty(&dev_priv->mm.inactive_list));
4684         BUG_ON(!list_empty(&dev_priv->render_ring.request_list));
4685         BUG_ON(HAS_BSD(dev) && !list_empty(&dev_priv->bsd_ring.request_list));
4686         mutex_unlock(&dev->struct_mutex);
4687
4688         drm_irq_install(dev);
4689
4690         return 0;
4691 }
4692
4693 int
4694 i915_gem_leavevt_ioctl(struct drm_device *dev, void *data,
4695                        struct drm_file *file_priv)
4696 {
4697         if (drm_core_check_feature(dev, DRIVER_MODESET))
4698                 return 0;
4699
4700         drm_irq_uninstall(dev);
4701         return i915_gem_idle(dev);
4702 }
4703
4704 void
4705 i915_gem_lastclose(struct drm_device *dev)
4706 {
4707         int ret;
4708
4709         if (drm_core_check_feature(dev, DRIVER_MODESET))
4710                 return;
4711
4712         ret = i915_gem_idle(dev);
4713         if (ret)
4714                 DRM_ERROR("failed to idle hardware: %d\n", ret);
4715 }
4716
4717 void
4718 i915_gem_load(struct drm_device *dev)
4719 {
4720         int i;
4721         drm_i915_private_t *dev_priv = dev->dev_private;
4722
4723         spin_lock_init(&dev_priv->mm.active_list_lock);
4724         INIT_LIST_HEAD(&dev_priv->mm.flushing_list);
4725         INIT_LIST_HEAD(&dev_priv->mm.gpu_write_list);
4726         INIT_LIST_HEAD(&dev_priv->mm.inactive_list);
4727         INIT_LIST_HEAD(&dev_priv->mm.fence_list);
4728         INIT_LIST_HEAD(&dev_priv->render_ring.active_list);
4729         INIT_LIST_HEAD(&dev_priv->render_ring.request_list);
4730         if (HAS_BSD(dev)) {
4731                 INIT_LIST_HEAD(&dev_priv->bsd_ring.active_list);
4732                 INIT_LIST_HEAD(&dev_priv->bsd_ring.request_list);
4733         }
4734         for (i = 0; i < 16; i++)
4735                 INIT_LIST_HEAD(&dev_priv->fence_regs[i].lru_list);
4736         INIT_DELAYED_WORK(&dev_priv->mm.retire_work,
4737                           i915_gem_retire_work_handler);
4738         spin_lock(&shrink_list_lock);
4739         list_add(&dev_priv->mm.shrink_list, &shrink_list);
4740         spin_unlock(&shrink_list_lock);
4741
4742         /* Old X drivers will take 0-2 for front, back, depth buffers */
4743         if (!drm_core_check_feature(dev, DRIVER_MODESET))
4744                 dev_priv->fence_reg_start = 3;
4745
4746         if (IS_I965G(dev) || IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev))
4747                 dev_priv->num_fence_regs = 16;
4748         else
4749                 dev_priv->num_fence_regs = 8;
4750
4751         /* Initialize fence registers to zero */
4752         if (IS_I965G(dev)) {
4753                 for (i = 0; i < 16; i++)
4754                         I915_WRITE64(FENCE_REG_965_0 + (i * 8), 0);
4755         } else {
4756                 for (i = 0; i < 8; i++)
4757                         I915_WRITE(FENCE_REG_830_0 + (i * 4), 0);
4758                 if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev))
4759                         for (i = 0; i < 8; i++)
4760                                 I915_WRITE(FENCE_REG_945_8 + (i * 4), 0);
4761         }
4762         i915_gem_detect_bit_6_swizzle(dev);
4763         init_waitqueue_head(&dev_priv->pending_flip_queue);
4764 }
4765
4766 /*
4767  * Create a physically contiguous memory object for this object
4768  * e.g. for cursor + overlay regs
4769  */
4770 int i915_gem_init_phys_object(struct drm_device *dev,
4771                               int id, int size)
4772 {
4773         drm_i915_private_t *dev_priv = dev->dev_private;
4774         struct drm_i915_gem_phys_object *phys_obj;
4775         int ret;
4776
4777         if (dev_priv->mm.phys_objs[id - 1] || !size)
4778                 return 0;
4779
4780         phys_obj = kzalloc(sizeof(struct drm_i915_gem_phys_object), GFP_KERNEL);
4781         if (!phys_obj)
4782                 return -ENOMEM;
4783
4784         phys_obj->id = id;
4785
4786         phys_obj->handle = drm_pci_alloc(dev, size, 0);
4787         if (!phys_obj->handle) {
4788                 ret = -ENOMEM;
4789                 goto kfree_obj;
4790         }
4791 #ifdef CONFIG_X86
4792         set_memory_wc((unsigned long)phys_obj->handle->vaddr, phys_obj->handle->size / PAGE_SIZE);
4793 #endif
4794
4795         dev_priv->mm.phys_objs[id - 1] = phys_obj;
4796
4797         return 0;
4798 kfree_obj:
4799         kfree(phys_obj);
4800         return ret;
4801 }
4802
4803 void i915_gem_free_phys_object(struct drm_device *dev, int id)
4804 {
4805         drm_i915_private_t *dev_priv = dev->dev_private;
4806         struct drm_i915_gem_phys_object *phys_obj;
4807
4808         if (!dev_priv->mm.phys_objs[id - 1])
4809                 return;
4810
4811         phys_obj = dev_priv->mm.phys_objs[id - 1];
4812         if (phys_obj->cur_obj) {
4813                 i915_gem_detach_phys_object(dev, phys_obj->cur_obj);
4814         }
4815
4816 #ifdef CONFIG_X86
4817         set_memory_wb((unsigned long)phys_obj->handle->vaddr, phys_obj->handle->size / PAGE_SIZE);
4818 #endif
4819         drm_pci_free(dev, phys_obj->handle);
4820         kfree(phys_obj);
4821         dev_priv->mm.phys_objs[id - 1] = NULL;
4822 }
4823
4824 void i915_gem_free_all_phys_object(struct drm_device *dev)
4825 {
4826         int i;
4827
4828         for (i = I915_GEM_PHYS_CURSOR_0; i <= I915_MAX_PHYS_OBJECT; i++)
4829                 i915_gem_free_phys_object(dev, i);
4830 }
4831
4832 void i915_gem_detach_phys_object(struct drm_device *dev,
4833                                  struct drm_gem_object *obj)
4834 {
4835         struct drm_i915_gem_object *obj_priv;
4836         int i;
4837         int ret;
4838         int page_count;
4839
4840         obj_priv = to_intel_bo(obj);
4841         if (!obj_priv->phys_obj)
4842                 return;
4843
4844         ret = i915_gem_object_get_pages(obj, 0);
4845         if (ret)
4846                 goto out;
4847
4848         page_count = obj->size / PAGE_SIZE;
4849
4850         for (i = 0; i < page_count; i++) {
4851                 char *dst = kmap_atomic(obj_priv->pages[i], KM_USER0);
4852                 char *src = obj_priv->phys_obj->handle->vaddr + (i * PAGE_SIZE);
4853
4854                 memcpy(dst, src, PAGE_SIZE);
4855                 kunmap_atomic(dst, KM_USER0);
4856         }
4857         drm_clflush_pages(obj_priv->pages, page_count);
4858         drm_agp_chipset_flush(dev);
4859
4860         i915_gem_object_put_pages(obj);
4861 out:
4862         obj_priv->phys_obj->cur_obj = NULL;
4863         obj_priv->phys_obj = NULL;
4864 }
4865
4866 int
4867 i915_gem_attach_phys_object(struct drm_device *dev,
4868                             struct drm_gem_object *obj, int id)
4869 {
4870         drm_i915_private_t *dev_priv = dev->dev_private;
4871         struct drm_i915_gem_object *obj_priv;
4872         int ret = 0;
4873         int page_count;
4874         int i;
4875
4876         if (id > I915_MAX_PHYS_OBJECT)
4877                 return -EINVAL;
4878
4879         obj_priv = to_intel_bo(obj);
4880
4881         if (obj_priv->phys_obj) {
4882                 if (obj_priv->phys_obj->id == id)
4883                         return 0;
4884                 i915_gem_detach_phys_object(dev, obj);
4885         }
4886
4887
4888         /* create a new object */
4889         if (!dev_priv->mm.phys_objs[id - 1]) {
4890                 ret = i915_gem_init_phys_object(dev, id,
4891                                                 obj->size);
4892                 if (ret) {
4893                         DRM_ERROR("failed to init phys object %d size: %zu\n", id, obj->size);
4894                         goto out;
4895                 }
4896         }
4897
4898         /* bind to the object */
4899         obj_priv->phys_obj = dev_priv->mm.phys_objs[id - 1];
4900         obj_priv->phys_obj->cur_obj = obj;
4901
4902         ret = i915_gem_object_get_pages(obj, 0);
4903         if (ret) {
4904                 DRM_ERROR("failed to get page list\n");
4905                 goto out;
4906         }
4907
4908         page_count = obj->size / PAGE_SIZE;
4909
4910         for (i = 0; i < page_count; i++) {
4911                 char *src = kmap_atomic(obj_priv->pages[i], KM_USER0);
4912                 char *dst = obj_priv->phys_obj->handle->vaddr + (i * PAGE_SIZE);
4913
4914                 memcpy(dst, src, PAGE_SIZE);
4915                 kunmap_atomic(src, KM_USER0);
4916         }
4917
4918         i915_gem_object_put_pages(obj);
4919
4920         return 0;
4921 out:
4922         return ret;
4923 }
4924
4925 static int
4926 i915_gem_phys_pwrite(struct drm_device *dev, struct drm_gem_object *obj,
4927                      struct drm_i915_gem_pwrite *args,
4928                      struct drm_file *file_priv)
4929 {
4930         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
4931         void *obj_addr;
4932         int ret;
4933         char __user *user_data;
4934
4935         user_data = (char __user *) (uintptr_t) args->data_ptr;
4936         obj_addr = obj_priv->phys_obj->handle->vaddr + args->offset;
4937
4938         DRM_DEBUG_DRIVER("obj_addr %p, %lld\n", obj_addr, args->size);
4939         ret = copy_from_user(obj_addr, user_data, args->size);
4940         if (ret)
4941                 return -EFAULT;
4942
4943         drm_agp_chipset_flush(dev);
4944         return 0;
4945 }
4946
4947 void i915_gem_release(struct drm_device * dev, struct drm_file *file_priv)
4948 {
4949         struct drm_i915_file_private *i915_file_priv = file_priv->driver_priv;
4950
4951         /* Clean up our request list when the client is going away, so that
4952          * later retire_requests won't dereference our soon-to-be-gone
4953          * file_priv.
4954          */
4955         mutex_lock(&dev->struct_mutex);
4956         while (!list_empty(&i915_file_priv->mm.request_list))
4957                 list_del_init(i915_file_priv->mm.request_list.next);
4958         mutex_unlock(&dev->struct_mutex);
4959 }
4960
4961 static int
4962 i915_gpu_is_active(struct drm_device *dev)
4963 {
4964         drm_i915_private_t *dev_priv = dev->dev_private;
4965         int lists_empty;
4966
4967         spin_lock(&dev_priv->mm.active_list_lock);
4968         lists_empty = list_empty(&dev_priv->mm.flushing_list) &&
4969                       list_empty(&dev_priv->render_ring.active_list);
4970         if (HAS_BSD(dev))
4971                 lists_empty &= list_empty(&dev_priv->bsd_ring.active_list);
4972         spin_unlock(&dev_priv->mm.active_list_lock);
4973
4974         return !lists_empty;
4975 }
4976
4977 static int
4978 i915_gem_shrink(int nr_to_scan, gfp_t gfp_mask)
4979 {
4980         drm_i915_private_t *dev_priv, *next_dev;
4981         struct drm_i915_gem_object *obj_priv, *next_obj;
4982         int cnt = 0;
4983         int would_deadlock = 1;
4984
4985         /* "fast-path" to count number of available objects */
4986         if (nr_to_scan == 0) {
4987                 spin_lock(&shrink_list_lock);
4988                 list_for_each_entry(dev_priv, &shrink_list, mm.shrink_list) {
4989                         struct drm_device *dev = dev_priv->dev;
4990
4991                         if (mutex_trylock(&dev->struct_mutex)) {
4992                                 list_for_each_entry(obj_priv,
4993                                                     &dev_priv->mm.inactive_list,
4994                                                     list)
4995                                         cnt++;
4996                                 mutex_unlock(&dev->struct_mutex);
4997                         }
4998                 }
4999                 spin_unlock(&shrink_list_lock);
5000
5001                 return (cnt / 100) * sysctl_vfs_cache_pressure;
5002         }
5003
5004         spin_lock(&shrink_list_lock);
5005
5006 rescan:
5007         /* first scan for clean buffers */
5008         list_for_each_entry_safe(dev_priv, next_dev,
5009                                  &shrink_list, mm.shrink_list) {
5010                 struct drm_device *dev = dev_priv->dev;
5011
5012                 if (! mutex_trylock(&dev->struct_mutex))
5013                         continue;
5014
5015                 spin_unlock(&shrink_list_lock);
5016                 i915_gem_retire_requests(dev, &dev_priv->render_ring);
5017
5018                 if (HAS_BSD(dev))
5019                         i915_gem_retire_requests(dev, &dev_priv->bsd_ring);
5020
5021                 list_for_each_entry_safe(obj_priv, next_obj,
5022                                          &dev_priv->mm.inactive_list,
5023                                          list) {
5024                         if (i915_gem_object_is_purgeable(obj_priv)) {
5025                                 i915_gem_object_unbind(&obj_priv->base);
5026                                 if (--nr_to_scan <= 0)
5027                                         break;
5028                         }
5029                 }
5030
5031                 spin_lock(&shrink_list_lock);
5032                 mutex_unlock(&dev->struct_mutex);
5033
5034                 would_deadlock = 0;
5035
5036                 if (nr_to_scan <= 0)
5037                         break;
5038         }
5039
5040         /* second pass, evict/count anything still on the inactive list */
5041         list_for_each_entry_safe(dev_priv, next_dev,
5042                                  &shrink_list, mm.shrink_list) {
5043                 struct drm_device *dev = dev_priv->dev;
5044
5045                 if (! mutex_trylock(&dev->struct_mutex))
5046                         continue;
5047
5048                 spin_unlock(&shrink_list_lock);
5049
5050                 list_for_each_entry_safe(obj_priv, next_obj,
5051                                          &dev_priv->mm.inactive_list,
5052                                          list) {
5053                         if (nr_to_scan > 0) {
5054                                 i915_gem_object_unbind(&obj_priv->base);
5055                                 nr_to_scan--;
5056                         } else
5057                                 cnt++;
5058                 }
5059
5060                 spin_lock(&shrink_list_lock);
5061                 mutex_unlock(&dev->struct_mutex);
5062
5063                 would_deadlock = 0;
5064         }
5065
5066         if (nr_to_scan) {
5067                 int active = 0;
5068
5069                 /*
5070                  * We are desperate for pages, so as a last resort, wait
5071                  * for the GPU to finish and discard whatever we can.
5072                  * This has a dramatic impact to reduce the number of
5073                  * OOM-killer events whilst running the GPU aggressively.
5074                  */
5075                 list_for_each_entry(dev_priv, &shrink_list, mm.shrink_list) {
5076                         struct drm_device *dev = dev_priv->dev;
5077
5078                         if (!mutex_trylock(&dev->struct_mutex))
5079                                 continue;
5080
5081                         spin_unlock(&shrink_list_lock);
5082
5083                         if (i915_gpu_is_active(dev)) {
5084                                 i915_gpu_idle(dev);
5085                                 active++;
5086                         }
5087
5088                         spin_lock(&shrink_list_lock);
5089                         mutex_unlock(&dev->struct_mutex);
5090                 }
5091
5092                 if (active)
5093                         goto rescan;
5094         }
5095
5096         spin_unlock(&shrink_list_lock);
5097
5098         if (would_deadlock)
5099                 return -1;
5100         else if (cnt > 0)
5101                 return (cnt / 100) * sysctl_vfs_cache_pressure;
5102         else
5103                 return 0;
5104 }
5105
5106 static struct shrinker shrinker = {
5107         .shrink = i915_gem_shrink,
5108         .seeks = DEFAULT_SEEKS,
5109 };
5110
5111 __init void
5112 i915_gem_shrinker_init(void)
5113 {
5114     register_shrinker(&shrinker);
5115 }
5116
5117 __exit void
5118 i915_gem_shrinker_exit(void)
5119 {
5120     unregister_shrinker(&shrinker);
5121 }