drm/i915: use shmem_read_mapping_page
[linux-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/shmem_fs.h>
35 #include <linux/slab.h>
36 #include <linux/swap.h>
37 #include <linux/pci.h>
38
39 static __must_check int i915_gem_object_flush_gpu_write_domain(struct drm_i915_gem_object *obj);
40 static void i915_gem_object_flush_gtt_write_domain(struct drm_i915_gem_object *obj);
41 static void i915_gem_object_flush_cpu_write_domain(struct drm_i915_gem_object *obj);
42 static __must_check int i915_gem_object_set_to_cpu_domain(struct drm_i915_gem_object *obj,
43                                                           bool write);
44 static __must_check int i915_gem_object_set_cpu_read_domain_range(struct drm_i915_gem_object *obj,
45                                                                   uint64_t offset,
46                                                                   uint64_t size);
47 static void i915_gem_object_set_to_full_cpu_read_domain(struct drm_i915_gem_object *obj);
48 static __must_check int i915_gem_object_bind_to_gtt(struct drm_i915_gem_object *obj,
49                                                     unsigned alignment,
50                                                     bool map_and_fenceable);
51 static void i915_gem_clear_fence_reg(struct drm_device *dev,
52                                      struct drm_i915_fence_reg *reg);
53 static int i915_gem_phys_pwrite(struct drm_device *dev,
54                                 struct drm_i915_gem_object *obj,
55                                 struct drm_i915_gem_pwrite *args,
56                                 struct drm_file *file);
57 static void i915_gem_free_object_tail(struct drm_i915_gem_object *obj);
58
59 static int i915_gem_inactive_shrink(struct shrinker *shrinker,
60                                     struct shrink_control *sc);
61
62 /* some bookkeeping */
63 static void i915_gem_info_add_obj(struct drm_i915_private *dev_priv,
64                                   size_t size)
65 {
66         dev_priv->mm.object_count++;
67         dev_priv->mm.object_memory += size;
68 }
69
70 static void i915_gem_info_remove_obj(struct drm_i915_private *dev_priv,
71                                      size_t size)
72 {
73         dev_priv->mm.object_count--;
74         dev_priv->mm.object_memory -= size;
75 }
76
77 static int
78 i915_gem_wait_for_error(struct drm_device *dev)
79 {
80         struct drm_i915_private *dev_priv = dev->dev_private;
81         struct completion *x = &dev_priv->error_completion;
82         unsigned long flags;
83         int ret;
84
85         if (!atomic_read(&dev_priv->mm.wedged))
86                 return 0;
87
88         ret = wait_for_completion_interruptible(x);
89         if (ret)
90                 return ret;
91
92         if (atomic_read(&dev_priv->mm.wedged)) {
93                 /* GPU is hung, bump the completion count to account for
94                  * the token we just consumed so that we never hit zero and
95                  * end up waiting upon a subsequent completion event that
96                  * will never happen.
97                  */
98                 spin_lock_irqsave(&x->wait.lock, flags);
99                 x->done++;
100                 spin_unlock_irqrestore(&x->wait.lock, flags);
101         }
102         return 0;
103 }
104
105 int i915_mutex_lock_interruptible(struct drm_device *dev)
106 {
107         int ret;
108
109         ret = i915_gem_wait_for_error(dev);
110         if (ret)
111                 return ret;
112
113         ret = mutex_lock_interruptible(&dev->struct_mutex);
114         if (ret)
115                 return ret;
116
117         WARN_ON(i915_verify_lists(dev));
118         return 0;
119 }
120
121 static inline bool
122 i915_gem_object_is_inactive(struct drm_i915_gem_object *obj)
123 {
124         return obj->gtt_space && !obj->active && obj->pin_count == 0;
125 }
126
127 void i915_gem_do_init(struct drm_device *dev,
128                       unsigned long start,
129                       unsigned long mappable_end,
130                       unsigned long end)
131 {
132         drm_i915_private_t *dev_priv = dev->dev_private;
133
134         drm_mm_init(&dev_priv->mm.gtt_space, start, end - start);
135
136         dev_priv->mm.gtt_start = start;
137         dev_priv->mm.gtt_mappable_end = mappable_end;
138         dev_priv->mm.gtt_end = end;
139         dev_priv->mm.gtt_total = end - start;
140         dev_priv->mm.mappable_gtt_total = min(end, mappable_end) - start;
141
142         /* Take over this portion of the GTT */
143         intel_gtt_clear_range(start / PAGE_SIZE, (end-start) / PAGE_SIZE);
144 }
145
146 int
147 i915_gem_init_ioctl(struct drm_device *dev, void *data,
148                     struct drm_file *file)
149 {
150         struct drm_i915_gem_init *args = data;
151
152         if (args->gtt_start >= args->gtt_end ||
153             (args->gtt_end | args->gtt_start) & (PAGE_SIZE - 1))
154                 return -EINVAL;
155
156         mutex_lock(&dev->struct_mutex);
157         i915_gem_do_init(dev, args->gtt_start, args->gtt_end, args->gtt_end);
158         mutex_unlock(&dev->struct_mutex);
159
160         return 0;
161 }
162
163 int
164 i915_gem_get_aperture_ioctl(struct drm_device *dev, void *data,
165                             struct drm_file *file)
166 {
167         struct drm_i915_private *dev_priv = dev->dev_private;
168         struct drm_i915_gem_get_aperture *args = data;
169         struct drm_i915_gem_object *obj;
170         size_t pinned;
171
172         if (!(dev->driver->driver_features & DRIVER_GEM))
173                 return -ENODEV;
174
175         pinned = 0;
176         mutex_lock(&dev->struct_mutex);
177         list_for_each_entry(obj, &dev_priv->mm.pinned_list, mm_list)
178                 pinned += obj->gtt_space->size;
179         mutex_unlock(&dev->struct_mutex);
180
181         args->aper_size = dev_priv->mm.gtt_total;
182         args->aper_available_size = args->aper_size -pinned;
183
184         return 0;
185 }
186
187 static int
188 i915_gem_create(struct drm_file *file,
189                 struct drm_device *dev,
190                 uint64_t size,
191                 uint32_t *handle_p)
192 {
193         struct drm_i915_gem_object *obj;
194         int ret;
195         u32 handle;
196
197         size = roundup(size, PAGE_SIZE);
198
199         /* Allocate the new object */
200         obj = i915_gem_alloc_object(dev, size);
201         if (obj == NULL)
202                 return -ENOMEM;
203
204         ret = drm_gem_handle_create(file, &obj->base, &handle);
205         if (ret) {
206                 drm_gem_object_release(&obj->base);
207                 i915_gem_info_remove_obj(dev->dev_private, obj->base.size);
208                 kfree(obj);
209                 return ret;
210         }
211
212         /* drop reference from allocate - handle holds it now */
213         drm_gem_object_unreference(&obj->base);
214         trace_i915_gem_object_create(obj);
215
216         *handle_p = handle;
217         return 0;
218 }
219
220 int
221 i915_gem_dumb_create(struct drm_file *file,
222                      struct drm_device *dev,
223                      struct drm_mode_create_dumb *args)
224 {
225         /* have to work out size/pitch and return them */
226         args->pitch = ALIGN(args->width * ((args->bpp + 7) / 8), 64);
227         args->size = args->pitch * args->height;
228         return i915_gem_create(file, dev,
229                                args->size, &args->handle);
230 }
231
232 int i915_gem_dumb_destroy(struct drm_file *file,
233                           struct drm_device *dev,
234                           uint32_t handle)
235 {
236         return drm_gem_handle_delete(file, handle);
237 }
238
239 /**
240  * Creates a new mm object and returns a handle to it.
241  */
242 int
243 i915_gem_create_ioctl(struct drm_device *dev, void *data,
244                       struct drm_file *file)
245 {
246         struct drm_i915_gem_create *args = data;
247         return i915_gem_create(file, dev,
248                                args->size, &args->handle);
249 }
250
251 static int i915_gem_object_needs_bit17_swizzle(struct drm_i915_gem_object *obj)
252 {
253         drm_i915_private_t *dev_priv = obj->base.dev->dev_private;
254
255         return dev_priv->mm.bit_6_swizzle_x == I915_BIT_6_SWIZZLE_9_10_17 &&
256                 obj->tiling_mode != I915_TILING_NONE;
257 }
258
259 static inline void
260 slow_shmem_copy(struct page *dst_page,
261                 int dst_offset,
262                 struct page *src_page,
263                 int src_offset,
264                 int length)
265 {
266         char *dst_vaddr, *src_vaddr;
267
268         dst_vaddr = kmap(dst_page);
269         src_vaddr = kmap(src_page);
270
271         memcpy(dst_vaddr + dst_offset, src_vaddr + src_offset, length);
272
273         kunmap(src_page);
274         kunmap(dst_page);
275 }
276
277 static inline void
278 slow_shmem_bit17_copy(struct page *gpu_page,
279                       int gpu_offset,
280                       struct page *cpu_page,
281                       int cpu_offset,
282                       int length,
283                       int is_read)
284 {
285         char *gpu_vaddr, *cpu_vaddr;
286
287         /* Use the unswizzled path if this page isn't affected. */
288         if ((page_to_phys(gpu_page) & (1 << 17)) == 0) {
289                 if (is_read)
290                         return slow_shmem_copy(cpu_page, cpu_offset,
291                                                gpu_page, gpu_offset, length);
292                 else
293                         return slow_shmem_copy(gpu_page, gpu_offset,
294                                                cpu_page, cpu_offset, length);
295         }
296
297         gpu_vaddr = kmap(gpu_page);
298         cpu_vaddr = kmap(cpu_page);
299
300         /* Copy the data, XORing A6 with A17 (1). The user already knows he's
301          * XORing with the other bits (A9 for Y, A9 and A10 for X)
302          */
303         while (length > 0) {
304                 int cacheline_end = ALIGN(gpu_offset + 1, 64);
305                 int this_length = min(cacheline_end - gpu_offset, length);
306                 int swizzled_gpu_offset = gpu_offset ^ 64;
307
308                 if (is_read) {
309                         memcpy(cpu_vaddr + cpu_offset,
310                                gpu_vaddr + swizzled_gpu_offset,
311                                this_length);
312                 } else {
313                         memcpy(gpu_vaddr + swizzled_gpu_offset,
314                                cpu_vaddr + cpu_offset,
315                                this_length);
316                 }
317                 cpu_offset += this_length;
318                 gpu_offset += this_length;
319                 length -= this_length;
320         }
321
322         kunmap(cpu_page);
323         kunmap(gpu_page);
324 }
325
326 /**
327  * This is the fast shmem pread path, which attempts to copy_from_user directly
328  * from the backing pages of the object to the user's address space.  On a
329  * fault, it fails so we can fall back to i915_gem_shmem_pwrite_slow().
330  */
331 static int
332 i915_gem_shmem_pread_fast(struct drm_device *dev,
333                           struct drm_i915_gem_object *obj,
334                           struct drm_i915_gem_pread *args,
335                           struct drm_file *file)
336 {
337         struct address_space *mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
338         ssize_t remain;
339         loff_t offset;
340         char __user *user_data;
341         int page_offset, page_length;
342
343         user_data = (char __user *) (uintptr_t) args->data_ptr;
344         remain = args->size;
345
346         offset = args->offset;
347
348         while (remain > 0) {
349                 struct page *page;
350                 char *vaddr;
351                 int ret;
352
353                 /* Operation in this page
354                  *
355                  * page_offset = offset within page
356                  * page_length = bytes to copy for this page
357                  */
358                 page_offset = offset_in_page(offset);
359                 page_length = remain;
360                 if ((page_offset + remain) > PAGE_SIZE)
361                         page_length = PAGE_SIZE - page_offset;
362
363                 page = shmem_read_mapping_page(mapping, offset >> PAGE_SHIFT);
364                 if (IS_ERR(page))
365                         return PTR_ERR(page);
366
367                 vaddr = kmap_atomic(page);
368                 ret = __copy_to_user_inatomic(user_data,
369                                               vaddr + page_offset,
370                                               page_length);
371                 kunmap_atomic(vaddr);
372
373                 mark_page_accessed(page);
374                 page_cache_release(page);
375                 if (ret)
376                         return -EFAULT;
377
378                 remain -= page_length;
379                 user_data += page_length;
380                 offset += page_length;
381         }
382
383         return 0;
384 }
385
386 /**
387  * This is the fallback shmem pread path, which allocates temporary storage
388  * in kernel space to copy_to_user into outside of the struct_mutex, so we
389  * can copy out of the object's backing pages while holding the struct mutex
390  * and not take page faults.
391  */
392 static int
393 i915_gem_shmem_pread_slow(struct drm_device *dev,
394                           struct drm_i915_gem_object *obj,
395                           struct drm_i915_gem_pread *args,
396                           struct drm_file *file)
397 {
398         struct address_space *mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
399         struct mm_struct *mm = current->mm;
400         struct page **user_pages;
401         ssize_t remain;
402         loff_t offset, pinned_pages, i;
403         loff_t first_data_page, last_data_page, num_pages;
404         int shmem_page_offset;
405         int data_page_index, data_page_offset;
406         int page_length;
407         int ret;
408         uint64_t data_ptr = args->data_ptr;
409         int do_bit17_swizzling;
410
411         remain = args->size;
412
413         /* Pin the user pages containing the data.  We can't fault while
414          * holding the struct mutex, yet we want to hold it while
415          * dereferencing the user data.
416          */
417         first_data_page = data_ptr / PAGE_SIZE;
418         last_data_page = (data_ptr + args->size - 1) / PAGE_SIZE;
419         num_pages = last_data_page - first_data_page + 1;
420
421         user_pages = drm_malloc_ab(num_pages, sizeof(struct page *));
422         if (user_pages == NULL)
423                 return -ENOMEM;
424
425         mutex_unlock(&dev->struct_mutex);
426         down_read(&mm->mmap_sem);
427         pinned_pages = get_user_pages(current, mm, (uintptr_t)args->data_ptr,
428                                       num_pages, 1, 0, user_pages, NULL);
429         up_read(&mm->mmap_sem);
430         mutex_lock(&dev->struct_mutex);
431         if (pinned_pages < num_pages) {
432                 ret = -EFAULT;
433                 goto out;
434         }
435
436         ret = i915_gem_object_set_cpu_read_domain_range(obj,
437                                                         args->offset,
438                                                         args->size);
439         if (ret)
440                 goto out;
441
442         do_bit17_swizzling = i915_gem_object_needs_bit17_swizzle(obj);
443
444         offset = args->offset;
445
446         while (remain > 0) {
447                 struct page *page;
448
449                 /* Operation in this page
450                  *
451                  * shmem_page_offset = offset within page in shmem file
452                  * data_page_index = page number in get_user_pages return
453                  * data_page_offset = offset with data_page_index page.
454                  * page_length = bytes to copy for this page
455                  */
456                 shmem_page_offset = offset_in_page(offset);
457                 data_page_index = data_ptr / PAGE_SIZE - first_data_page;
458                 data_page_offset = offset_in_page(data_ptr);
459
460                 page_length = remain;
461                 if ((shmem_page_offset + page_length) > PAGE_SIZE)
462                         page_length = PAGE_SIZE - shmem_page_offset;
463                 if ((data_page_offset + page_length) > PAGE_SIZE)
464                         page_length = PAGE_SIZE - data_page_offset;
465
466                 page = shmem_read_mapping_page(mapping, offset >> PAGE_SHIFT);
467                 if (IS_ERR(page)) {
468                         ret = PTR_ERR(page);
469                         goto out;
470                 }
471
472                 if (do_bit17_swizzling) {
473                         slow_shmem_bit17_copy(page,
474                                               shmem_page_offset,
475                                               user_pages[data_page_index],
476                                               data_page_offset,
477                                               page_length,
478                                               1);
479                 } else {
480                         slow_shmem_copy(user_pages[data_page_index],
481                                         data_page_offset,
482                                         page,
483                                         shmem_page_offset,
484                                         page_length);
485                 }
486
487                 mark_page_accessed(page);
488                 page_cache_release(page);
489
490                 remain -= page_length;
491                 data_ptr += page_length;
492                 offset += page_length;
493         }
494
495 out:
496         for (i = 0; i < pinned_pages; i++) {
497                 SetPageDirty(user_pages[i]);
498                 mark_page_accessed(user_pages[i]);
499                 page_cache_release(user_pages[i]);
500         }
501         drm_free_large(user_pages);
502
503         return ret;
504 }
505
506 /**
507  * Reads data from the object referenced by handle.
508  *
509  * On error, the contents of *data are undefined.
510  */
511 int
512 i915_gem_pread_ioctl(struct drm_device *dev, void *data,
513                      struct drm_file *file)
514 {
515         struct drm_i915_gem_pread *args = data;
516         struct drm_i915_gem_object *obj;
517         int ret = 0;
518
519         if (args->size == 0)
520                 return 0;
521
522         if (!access_ok(VERIFY_WRITE,
523                        (char __user *)(uintptr_t)args->data_ptr,
524                        args->size))
525                 return -EFAULT;
526
527         ret = fault_in_pages_writeable((char __user *)(uintptr_t)args->data_ptr,
528                                        args->size);
529         if (ret)
530                 return -EFAULT;
531
532         ret = i915_mutex_lock_interruptible(dev);
533         if (ret)
534                 return ret;
535
536         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
537         if (&obj->base == NULL) {
538                 ret = -ENOENT;
539                 goto unlock;
540         }
541
542         /* Bounds check source.  */
543         if (args->offset > obj->base.size ||
544             args->size > obj->base.size - args->offset) {
545                 ret = -EINVAL;
546                 goto out;
547         }
548
549         trace_i915_gem_object_pread(obj, args->offset, args->size);
550
551         ret = i915_gem_object_set_cpu_read_domain_range(obj,
552                                                         args->offset,
553                                                         args->size);
554         if (ret)
555                 goto out;
556
557         ret = -EFAULT;
558         if (!i915_gem_object_needs_bit17_swizzle(obj))
559                 ret = i915_gem_shmem_pread_fast(dev, obj, args, file);
560         if (ret == -EFAULT)
561                 ret = i915_gem_shmem_pread_slow(dev, obj, args, file);
562
563 out:
564         drm_gem_object_unreference(&obj->base);
565 unlock:
566         mutex_unlock(&dev->struct_mutex);
567         return ret;
568 }
569
570 /* This is the fast write path which cannot handle
571  * page faults in the source data
572  */
573
574 static inline int
575 fast_user_write(struct io_mapping *mapping,
576                 loff_t page_base, int page_offset,
577                 char __user *user_data,
578                 int length)
579 {
580         char *vaddr_atomic;
581         unsigned long unwritten;
582
583         vaddr_atomic = io_mapping_map_atomic_wc(mapping, page_base);
584         unwritten = __copy_from_user_inatomic_nocache(vaddr_atomic + page_offset,
585                                                       user_data, length);
586         io_mapping_unmap_atomic(vaddr_atomic);
587         return unwritten;
588 }
589
590 /* Here's the write path which can sleep for
591  * page faults
592  */
593
594 static inline void
595 slow_kernel_write(struct io_mapping *mapping,
596                   loff_t gtt_base, int gtt_offset,
597                   struct page *user_page, int user_offset,
598                   int length)
599 {
600         char __iomem *dst_vaddr;
601         char *src_vaddr;
602
603         dst_vaddr = io_mapping_map_wc(mapping, gtt_base);
604         src_vaddr = kmap(user_page);
605
606         memcpy_toio(dst_vaddr + gtt_offset,
607                     src_vaddr + user_offset,
608                     length);
609
610         kunmap(user_page);
611         io_mapping_unmap(dst_vaddr);
612 }
613
614 /**
615  * This is the fast pwrite path, where we copy the data directly from the
616  * user into the GTT, uncached.
617  */
618 static int
619 i915_gem_gtt_pwrite_fast(struct drm_device *dev,
620                          struct drm_i915_gem_object *obj,
621                          struct drm_i915_gem_pwrite *args,
622                          struct drm_file *file)
623 {
624         drm_i915_private_t *dev_priv = dev->dev_private;
625         ssize_t remain;
626         loff_t offset, page_base;
627         char __user *user_data;
628         int page_offset, page_length;
629
630         user_data = (char __user *) (uintptr_t) args->data_ptr;
631         remain = args->size;
632
633         offset = obj->gtt_offset + args->offset;
634
635         while (remain > 0) {
636                 /* Operation in this page
637                  *
638                  * page_base = page offset within aperture
639                  * page_offset = offset within page
640                  * page_length = bytes to copy for this page
641                  */
642                 page_base = offset & PAGE_MASK;
643                 page_offset = offset_in_page(offset);
644                 page_length = remain;
645                 if ((page_offset + remain) > PAGE_SIZE)
646                         page_length = PAGE_SIZE - page_offset;
647
648                 /* If we get a fault while copying data, then (presumably) our
649                  * source page isn't available.  Return the error and we'll
650                  * retry in the slow path.
651                  */
652                 if (fast_user_write(dev_priv->mm.gtt_mapping, page_base,
653                                     page_offset, user_data, page_length))
654                         return -EFAULT;
655
656                 remain -= page_length;
657                 user_data += page_length;
658                 offset += page_length;
659         }
660
661         return 0;
662 }
663
664 /**
665  * This is the fallback GTT pwrite path, which uses get_user_pages to pin
666  * the memory and maps it using kmap_atomic for copying.
667  *
668  * This code resulted in x11perf -rgb10text consuming about 10% more CPU
669  * than using i915_gem_gtt_pwrite_fast on a G45 (32-bit).
670  */
671 static int
672 i915_gem_gtt_pwrite_slow(struct drm_device *dev,
673                          struct drm_i915_gem_object *obj,
674                          struct drm_i915_gem_pwrite *args,
675                          struct drm_file *file)
676 {
677         drm_i915_private_t *dev_priv = dev->dev_private;
678         ssize_t remain;
679         loff_t gtt_page_base, offset;
680         loff_t first_data_page, last_data_page, num_pages;
681         loff_t pinned_pages, i;
682         struct page **user_pages;
683         struct mm_struct *mm = current->mm;
684         int gtt_page_offset, data_page_offset, data_page_index, page_length;
685         int ret;
686         uint64_t data_ptr = args->data_ptr;
687
688         remain = args->size;
689
690         /* Pin the user pages containing the data.  We can't fault while
691          * holding the struct mutex, and all of the pwrite implementations
692          * want to hold it while dereferencing the user data.
693          */
694         first_data_page = data_ptr / PAGE_SIZE;
695         last_data_page = (data_ptr + args->size - 1) / PAGE_SIZE;
696         num_pages = last_data_page - first_data_page + 1;
697
698         user_pages = drm_malloc_ab(num_pages, sizeof(struct page *));
699         if (user_pages == NULL)
700                 return -ENOMEM;
701
702         mutex_unlock(&dev->struct_mutex);
703         down_read(&mm->mmap_sem);
704         pinned_pages = get_user_pages(current, mm, (uintptr_t)args->data_ptr,
705                                       num_pages, 0, 0, user_pages, NULL);
706         up_read(&mm->mmap_sem);
707         mutex_lock(&dev->struct_mutex);
708         if (pinned_pages < num_pages) {
709                 ret = -EFAULT;
710                 goto out_unpin_pages;
711         }
712
713         ret = i915_gem_object_set_to_gtt_domain(obj, true);
714         if (ret)
715                 goto out_unpin_pages;
716
717         ret = i915_gem_object_put_fence(obj);
718         if (ret)
719                 goto out_unpin_pages;
720
721         offset = obj->gtt_offset + args->offset;
722
723         while (remain > 0) {
724                 /* Operation in this page
725                  *
726                  * gtt_page_base = page offset within aperture
727                  * gtt_page_offset = offset within page in aperture
728                  * data_page_index = page number in get_user_pages return
729                  * data_page_offset = offset with data_page_index page.
730                  * page_length = bytes to copy for this page
731                  */
732                 gtt_page_base = offset & PAGE_MASK;
733                 gtt_page_offset = offset_in_page(offset);
734                 data_page_index = data_ptr / PAGE_SIZE - first_data_page;
735                 data_page_offset = offset_in_page(data_ptr);
736
737                 page_length = remain;
738                 if ((gtt_page_offset + page_length) > PAGE_SIZE)
739                         page_length = PAGE_SIZE - gtt_page_offset;
740                 if ((data_page_offset + page_length) > PAGE_SIZE)
741                         page_length = PAGE_SIZE - data_page_offset;
742
743                 slow_kernel_write(dev_priv->mm.gtt_mapping,
744                                   gtt_page_base, gtt_page_offset,
745                                   user_pages[data_page_index],
746                                   data_page_offset,
747                                   page_length);
748
749                 remain -= page_length;
750                 offset += page_length;
751                 data_ptr += page_length;
752         }
753
754 out_unpin_pages:
755         for (i = 0; i < pinned_pages; i++)
756                 page_cache_release(user_pages[i]);
757         drm_free_large(user_pages);
758
759         return ret;
760 }
761
762 /**
763  * This is the fast shmem pwrite path, which attempts to directly
764  * copy_from_user into the kmapped pages backing the object.
765  */
766 static int
767 i915_gem_shmem_pwrite_fast(struct drm_device *dev,
768                            struct drm_i915_gem_object *obj,
769                            struct drm_i915_gem_pwrite *args,
770                            struct drm_file *file)
771 {
772         struct address_space *mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
773         ssize_t remain;
774         loff_t offset;
775         char __user *user_data;
776         int page_offset, page_length;
777
778         user_data = (char __user *) (uintptr_t) args->data_ptr;
779         remain = args->size;
780
781         offset = args->offset;
782         obj->dirty = 1;
783
784         while (remain > 0) {
785                 struct page *page;
786                 char *vaddr;
787                 int ret;
788
789                 /* Operation in this page
790                  *
791                  * page_offset = offset within page
792                  * page_length = bytes to copy for this page
793                  */
794                 page_offset = offset_in_page(offset);
795                 page_length = remain;
796                 if ((page_offset + remain) > PAGE_SIZE)
797                         page_length = PAGE_SIZE - page_offset;
798
799                 page = shmem_read_mapping_page(mapping, offset >> PAGE_SHIFT);
800                 if (IS_ERR(page))
801                         return PTR_ERR(page);
802
803                 vaddr = kmap_atomic(page, KM_USER0);
804                 ret = __copy_from_user_inatomic(vaddr + page_offset,
805                                                 user_data,
806                                                 page_length);
807                 kunmap_atomic(vaddr, KM_USER0);
808
809                 set_page_dirty(page);
810                 mark_page_accessed(page);
811                 page_cache_release(page);
812
813                 /* If we get a fault while copying data, then (presumably) our
814                  * source page isn't available.  Return the error and we'll
815                  * retry in the slow path.
816                  */
817                 if (ret)
818                         return -EFAULT;
819
820                 remain -= page_length;
821                 user_data += page_length;
822                 offset += page_length;
823         }
824
825         return 0;
826 }
827
828 /**
829  * This is the fallback shmem pwrite path, which uses get_user_pages to pin
830  * the memory and maps it using kmap_atomic for copying.
831  *
832  * This avoids taking mmap_sem for faulting on the user's address while the
833  * struct_mutex is held.
834  */
835 static int
836 i915_gem_shmem_pwrite_slow(struct drm_device *dev,
837                            struct drm_i915_gem_object *obj,
838                            struct drm_i915_gem_pwrite *args,
839                            struct drm_file *file)
840 {
841         struct address_space *mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
842         struct mm_struct *mm = current->mm;
843         struct page **user_pages;
844         ssize_t remain;
845         loff_t offset, pinned_pages, i;
846         loff_t first_data_page, last_data_page, num_pages;
847         int shmem_page_offset;
848         int data_page_index,  data_page_offset;
849         int page_length;
850         int ret;
851         uint64_t data_ptr = args->data_ptr;
852         int do_bit17_swizzling;
853
854         remain = args->size;
855
856         /* Pin the user pages containing the data.  We can't fault while
857          * holding the struct mutex, and all of the pwrite implementations
858          * want to hold it while dereferencing the user data.
859          */
860         first_data_page = data_ptr / PAGE_SIZE;
861         last_data_page = (data_ptr + args->size - 1) / PAGE_SIZE;
862         num_pages = last_data_page - first_data_page + 1;
863
864         user_pages = drm_malloc_ab(num_pages, sizeof(struct page *));
865         if (user_pages == NULL)
866                 return -ENOMEM;
867
868         mutex_unlock(&dev->struct_mutex);
869         down_read(&mm->mmap_sem);
870         pinned_pages = get_user_pages(current, mm, (uintptr_t)args->data_ptr,
871                                       num_pages, 0, 0, user_pages, NULL);
872         up_read(&mm->mmap_sem);
873         mutex_lock(&dev->struct_mutex);
874         if (pinned_pages < num_pages) {
875                 ret = -EFAULT;
876                 goto out;
877         }
878
879         ret = i915_gem_object_set_to_cpu_domain(obj, 1);
880         if (ret)
881                 goto out;
882
883         do_bit17_swizzling = i915_gem_object_needs_bit17_swizzle(obj);
884
885         offset = args->offset;
886         obj->dirty = 1;
887
888         while (remain > 0) {
889                 struct page *page;
890
891                 /* Operation in this page
892                  *
893                  * shmem_page_offset = offset within page in shmem file
894                  * data_page_index = page number in get_user_pages return
895                  * data_page_offset = offset with data_page_index page.
896                  * page_length = bytes to copy for this page
897                  */
898                 shmem_page_offset = offset_in_page(offset);
899                 data_page_index = data_ptr / PAGE_SIZE - first_data_page;
900                 data_page_offset = offset_in_page(data_ptr);
901
902                 page_length = remain;
903                 if ((shmem_page_offset + page_length) > PAGE_SIZE)
904                         page_length = PAGE_SIZE - shmem_page_offset;
905                 if ((data_page_offset + page_length) > PAGE_SIZE)
906                         page_length = PAGE_SIZE - data_page_offset;
907
908                 page = shmem_read_mapping_page(mapping, offset >> PAGE_SHIFT);
909                 if (IS_ERR(page)) {
910                         ret = PTR_ERR(page);
911                         goto out;
912                 }
913
914                 if (do_bit17_swizzling) {
915                         slow_shmem_bit17_copy(page,
916                                               shmem_page_offset,
917                                               user_pages[data_page_index],
918                                               data_page_offset,
919                                               page_length,
920                                               0);
921                 } else {
922                         slow_shmem_copy(page,
923                                         shmem_page_offset,
924                                         user_pages[data_page_index],
925                                         data_page_offset,
926                                         page_length);
927                 }
928
929                 set_page_dirty(page);
930                 mark_page_accessed(page);
931                 page_cache_release(page);
932
933                 remain -= page_length;
934                 data_ptr += page_length;
935                 offset += page_length;
936         }
937
938 out:
939         for (i = 0; i < pinned_pages; i++)
940                 page_cache_release(user_pages[i]);
941         drm_free_large(user_pages);
942
943         return ret;
944 }
945
946 /**
947  * Writes data to the object referenced by handle.
948  *
949  * On error, the contents of the buffer that were to be modified are undefined.
950  */
951 int
952 i915_gem_pwrite_ioctl(struct drm_device *dev, void *data,
953                       struct drm_file *file)
954 {
955         struct drm_i915_gem_pwrite *args = data;
956         struct drm_i915_gem_object *obj;
957         int ret;
958
959         if (args->size == 0)
960                 return 0;
961
962         if (!access_ok(VERIFY_READ,
963                        (char __user *)(uintptr_t)args->data_ptr,
964                        args->size))
965                 return -EFAULT;
966
967         ret = fault_in_pages_readable((char __user *)(uintptr_t)args->data_ptr,
968                                       args->size);
969         if (ret)
970                 return -EFAULT;
971
972         ret = i915_mutex_lock_interruptible(dev);
973         if (ret)
974                 return ret;
975
976         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
977         if (&obj->base == NULL) {
978                 ret = -ENOENT;
979                 goto unlock;
980         }
981
982         /* Bounds check destination. */
983         if (args->offset > obj->base.size ||
984             args->size > obj->base.size - args->offset) {
985                 ret = -EINVAL;
986                 goto out;
987         }
988
989         trace_i915_gem_object_pwrite(obj, args->offset, args->size);
990
991         /* We can only do the GTT pwrite on untiled buffers, as otherwise
992          * it would end up going through the fenced access, and we'll get
993          * different detiling behavior between reading and writing.
994          * pread/pwrite currently are reading and writing from the CPU
995          * perspective, requiring manual detiling by the client.
996          */
997         if (obj->phys_obj)
998                 ret = i915_gem_phys_pwrite(dev, obj, args, file);
999         else if (obj->gtt_space &&
1000                  obj->base.write_domain != I915_GEM_DOMAIN_CPU) {
1001                 ret = i915_gem_object_pin(obj, 0, true);
1002                 if (ret)
1003                         goto out;
1004
1005                 ret = i915_gem_object_set_to_gtt_domain(obj, true);
1006                 if (ret)
1007                         goto out_unpin;
1008
1009                 ret = i915_gem_object_put_fence(obj);
1010                 if (ret)
1011                         goto out_unpin;
1012
1013                 ret = i915_gem_gtt_pwrite_fast(dev, obj, args, file);
1014                 if (ret == -EFAULT)
1015                         ret = i915_gem_gtt_pwrite_slow(dev, obj, args, file);
1016
1017 out_unpin:
1018                 i915_gem_object_unpin(obj);
1019         } else {
1020                 ret = i915_gem_object_set_to_cpu_domain(obj, 1);
1021                 if (ret)
1022                         goto out;
1023
1024                 ret = -EFAULT;
1025                 if (!i915_gem_object_needs_bit17_swizzle(obj))
1026                         ret = i915_gem_shmem_pwrite_fast(dev, obj, args, file);
1027                 if (ret == -EFAULT)
1028                         ret = i915_gem_shmem_pwrite_slow(dev, obj, args, file);
1029         }
1030
1031 out:
1032         drm_gem_object_unreference(&obj->base);
1033 unlock:
1034         mutex_unlock(&dev->struct_mutex);
1035         return ret;
1036 }
1037
1038 /**
1039  * Called when user space prepares to use an object with the CPU, either
1040  * through the mmap ioctl's mapping or a GTT mapping.
1041  */
1042 int
1043 i915_gem_set_domain_ioctl(struct drm_device *dev, void *data,
1044                           struct drm_file *file)
1045 {
1046         struct drm_i915_gem_set_domain *args = data;
1047         struct drm_i915_gem_object *obj;
1048         uint32_t read_domains = args->read_domains;
1049         uint32_t write_domain = args->write_domain;
1050         int ret;
1051
1052         if (!(dev->driver->driver_features & DRIVER_GEM))
1053                 return -ENODEV;
1054
1055         /* Only handle setting domains to types used by the CPU. */
1056         if (write_domain & I915_GEM_GPU_DOMAINS)
1057                 return -EINVAL;
1058
1059         if (read_domains & I915_GEM_GPU_DOMAINS)
1060                 return -EINVAL;
1061
1062         /* Having something in the write domain implies it's in the read
1063          * domain, and only that read domain.  Enforce that in the request.
1064          */
1065         if (write_domain != 0 && read_domains != write_domain)
1066                 return -EINVAL;
1067
1068         ret = i915_mutex_lock_interruptible(dev);
1069         if (ret)
1070                 return ret;
1071
1072         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
1073         if (&obj->base == NULL) {
1074                 ret = -ENOENT;
1075                 goto unlock;
1076         }
1077
1078         if (read_domains & I915_GEM_DOMAIN_GTT) {
1079                 ret = i915_gem_object_set_to_gtt_domain(obj, write_domain != 0);
1080
1081                 /* Silently promote "you're not bound, there was nothing to do"
1082                  * to success, since the client was just asking us to
1083                  * make sure everything was done.
1084                  */
1085                 if (ret == -EINVAL)
1086                         ret = 0;
1087         } else {
1088                 ret = i915_gem_object_set_to_cpu_domain(obj, write_domain != 0);
1089         }
1090
1091         drm_gem_object_unreference(&obj->base);
1092 unlock:
1093         mutex_unlock(&dev->struct_mutex);
1094         return ret;
1095 }
1096
1097 /**
1098  * Called when user space has done writes to this buffer
1099  */
1100 int
1101 i915_gem_sw_finish_ioctl(struct drm_device *dev, void *data,
1102                          struct drm_file *file)
1103 {
1104         struct drm_i915_gem_sw_finish *args = data;
1105         struct drm_i915_gem_object *obj;
1106         int ret = 0;
1107
1108         if (!(dev->driver->driver_features & DRIVER_GEM))
1109                 return -ENODEV;
1110
1111         ret = i915_mutex_lock_interruptible(dev);
1112         if (ret)
1113                 return ret;
1114
1115         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
1116         if (&obj->base == NULL) {
1117                 ret = -ENOENT;
1118                 goto unlock;
1119         }
1120
1121         /* Pinned buffers may be scanout, so flush the cache */
1122         if (obj->pin_count)
1123                 i915_gem_object_flush_cpu_write_domain(obj);
1124
1125         drm_gem_object_unreference(&obj->base);
1126 unlock:
1127         mutex_unlock(&dev->struct_mutex);
1128         return ret;
1129 }
1130
1131 /**
1132  * Maps the contents of an object, returning the address it is mapped
1133  * into.
1134  *
1135  * While the mapping holds a reference on the contents of the object, it doesn't
1136  * imply a ref on the object itself.
1137  */
1138 int
1139 i915_gem_mmap_ioctl(struct drm_device *dev, void *data,
1140                     struct drm_file *file)
1141 {
1142         struct drm_i915_private *dev_priv = dev->dev_private;
1143         struct drm_i915_gem_mmap *args = data;
1144         struct drm_gem_object *obj;
1145         unsigned long addr;
1146
1147         if (!(dev->driver->driver_features & DRIVER_GEM))
1148                 return -ENODEV;
1149
1150         obj = drm_gem_object_lookup(dev, file, args->handle);
1151         if (obj == NULL)
1152                 return -ENOENT;
1153
1154         if (obj->size > dev_priv->mm.gtt_mappable_end) {
1155                 drm_gem_object_unreference_unlocked(obj);
1156                 return -E2BIG;
1157         }
1158
1159         down_write(&current->mm->mmap_sem);
1160         addr = do_mmap(obj->filp, 0, args->size,
1161                        PROT_READ | PROT_WRITE, MAP_SHARED,
1162                        args->offset);
1163         up_write(&current->mm->mmap_sem);
1164         drm_gem_object_unreference_unlocked(obj);
1165         if (IS_ERR((void *)addr))
1166                 return addr;
1167
1168         args->addr_ptr = (uint64_t) addr;
1169
1170         return 0;
1171 }
1172
1173 /**
1174  * i915_gem_fault - fault a page into the GTT
1175  * vma: VMA in question
1176  * vmf: fault info
1177  *
1178  * The fault handler is set up by drm_gem_mmap() when a object is GTT mapped
1179  * from userspace.  The fault handler takes care of binding the object to
1180  * the GTT (if needed), allocating and programming a fence register (again,
1181  * only if needed based on whether the old reg is still valid or the object
1182  * is tiled) and inserting a new PTE into the faulting process.
1183  *
1184  * Note that the faulting process may involve evicting existing objects
1185  * from the GTT and/or fence registers to make room.  So performance may
1186  * suffer if the GTT working set is large or there are few fence registers
1187  * left.
1188  */
1189 int i915_gem_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1190 {
1191         struct drm_i915_gem_object *obj = to_intel_bo(vma->vm_private_data);
1192         struct drm_device *dev = obj->base.dev;
1193         drm_i915_private_t *dev_priv = dev->dev_private;
1194         pgoff_t page_offset;
1195         unsigned long pfn;
1196         int ret = 0;
1197         bool write = !!(vmf->flags & FAULT_FLAG_WRITE);
1198
1199         /* We don't use vmf->pgoff since that has the fake offset */
1200         page_offset = ((unsigned long)vmf->virtual_address - vma->vm_start) >>
1201                 PAGE_SHIFT;
1202
1203         ret = i915_mutex_lock_interruptible(dev);
1204         if (ret)
1205                 goto out;
1206
1207         trace_i915_gem_object_fault(obj, page_offset, true, write);
1208
1209         /* Now bind it into the GTT if needed */
1210         if (!obj->map_and_fenceable) {
1211                 ret = i915_gem_object_unbind(obj);
1212                 if (ret)
1213                         goto unlock;
1214         }
1215         if (!obj->gtt_space) {
1216                 ret = i915_gem_object_bind_to_gtt(obj, 0, true);
1217                 if (ret)
1218                         goto unlock;
1219
1220                 ret = i915_gem_object_set_to_gtt_domain(obj, write);
1221                 if (ret)
1222                         goto unlock;
1223         }
1224
1225         if (obj->tiling_mode == I915_TILING_NONE)
1226                 ret = i915_gem_object_put_fence(obj);
1227         else
1228                 ret = i915_gem_object_get_fence(obj, NULL);
1229         if (ret)
1230                 goto unlock;
1231
1232         if (i915_gem_object_is_inactive(obj))
1233                 list_move_tail(&obj->mm_list, &dev_priv->mm.inactive_list);
1234
1235         obj->fault_mappable = true;
1236
1237         pfn = ((dev->agp->base + obj->gtt_offset) >> PAGE_SHIFT) +
1238                 page_offset;
1239
1240         /* Finally, remap it using the new GTT offset */
1241         ret = vm_insert_pfn(vma, (unsigned long)vmf->virtual_address, pfn);
1242 unlock:
1243         mutex_unlock(&dev->struct_mutex);
1244 out:
1245         switch (ret) {
1246         case -EIO:
1247         case -EAGAIN:
1248                 /* Give the error handler a chance to run and move the
1249                  * objects off the GPU active list. Next time we service the
1250                  * fault, we should be able to transition the page into the
1251                  * GTT without touching the GPU (and so avoid further
1252                  * EIO/EGAIN). If the GPU is wedged, then there is no issue
1253                  * with coherency, just lost writes.
1254                  */
1255                 set_need_resched();
1256         case 0:
1257         case -ERESTARTSYS:
1258         case -EINTR:
1259                 return VM_FAULT_NOPAGE;
1260         case -ENOMEM:
1261                 return VM_FAULT_OOM;
1262         default:
1263                 return VM_FAULT_SIGBUS;
1264         }
1265 }
1266
1267 /**
1268  * i915_gem_create_mmap_offset - create a fake mmap offset for an object
1269  * @obj: obj in question
1270  *
1271  * GEM memory mapping works by handing back to userspace a fake mmap offset
1272  * it can use in a subsequent mmap(2) call.  The DRM core code then looks
1273  * up the object based on the offset and sets up the various memory mapping
1274  * structures.
1275  *
1276  * This routine allocates and attaches a fake offset for @obj.
1277  */
1278 static int
1279 i915_gem_create_mmap_offset(struct drm_i915_gem_object *obj)
1280 {
1281         struct drm_device *dev = obj->base.dev;
1282         struct drm_gem_mm *mm = dev->mm_private;
1283         struct drm_map_list *list;
1284         struct drm_local_map *map;
1285         int ret = 0;
1286
1287         /* Set the object up for mmap'ing */
1288         list = &obj->base.map_list;
1289         list->map = kzalloc(sizeof(struct drm_map_list), GFP_KERNEL);
1290         if (!list->map)
1291                 return -ENOMEM;
1292
1293         map = list->map;
1294         map->type = _DRM_GEM;
1295         map->size = obj->base.size;
1296         map->handle = obj;
1297
1298         /* Get a DRM GEM mmap offset allocated... */
1299         list->file_offset_node = drm_mm_search_free(&mm->offset_manager,
1300                                                     obj->base.size / PAGE_SIZE,
1301                                                     0, 0);
1302         if (!list->file_offset_node) {
1303                 DRM_ERROR("failed to allocate offset for bo %d\n",
1304                           obj->base.name);
1305                 ret = -ENOSPC;
1306                 goto out_free_list;
1307         }
1308
1309         list->file_offset_node = drm_mm_get_block(list->file_offset_node,
1310                                                   obj->base.size / PAGE_SIZE,
1311                                                   0);
1312         if (!list->file_offset_node) {
1313                 ret = -ENOMEM;
1314                 goto out_free_list;
1315         }
1316
1317         list->hash.key = list->file_offset_node->start;
1318         ret = drm_ht_insert_item(&mm->offset_hash, &list->hash);
1319         if (ret) {
1320                 DRM_ERROR("failed to add to map hash\n");
1321                 goto out_free_mm;
1322         }
1323
1324         return 0;
1325
1326 out_free_mm:
1327         drm_mm_put_block(list->file_offset_node);
1328 out_free_list:
1329         kfree(list->map);
1330         list->map = NULL;
1331
1332         return ret;
1333 }
1334
1335 /**
1336  * i915_gem_release_mmap - remove physical page mappings
1337  * @obj: obj in question
1338  *
1339  * Preserve the reservation of the mmapping with the DRM core code, but
1340  * relinquish ownership of the pages back to the system.
1341  *
1342  * It is vital that we remove the page mapping if we have mapped a tiled
1343  * object through the GTT and then lose the fence register due to
1344  * resource pressure. Similarly if the object has been moved out of the
1345  * aperture, than pages mapped into userspace must be revoked. Removing the
1346  * mapping will then trigger a page fault on the next user access, allowing
1347  * fixup by i915_gem_fault().
1348  */
1349 void
1350 i915_gem_release_mmap(struct drm_i915_gem_object *obj)
1351 {
1352         if (!obj->fault_mappable)
1353                 return;
1354
1355         if (obj->base.dev->dev_mapping)
1356                 unmap_mapping_range(obj->base.dev->dev_mapping,
1357                                     (loff_t)obj->base.map_list.hash.key<<PAGE_SHIFT,
1358                                     obj->base.size, 1);
1359
1360         obj->fault_mappable = false;
1361 }
1362
1363 static void
1364 i915_gem_free_mmap_offset(struct drm_i915_gem_object *obj)
1365 {
1366         struct drm_device *dev = obj->base.dev;
1367         struct drm_gem_mm *mm = dev->mm_private;
1368         struct drm_map_list *list = &obj->base.map_list;
1369
1370         drm_ht_remove_item(&mm->offset_hash, &list->hash);
1371         drm_mm_put_block(list->file_offset_node);
1372         kfree(list->map);
1373         list->map = NULL;
1374 }
1375
1376 static uint32_t
1377 i915_gem_get_gtt_size(struct drm_i915_gem_object *obj)
1378 {
1379         struct drm_device *dev = obj->base.dev;
1380         uint32_t size;
1381
1382         if (INTEL_INFO(dev)->gen >= 4 ||
1383             obj->tiling_mode == I915_TILING_NONE)
1384                 return obj->base.size;
1385
1386         /* Previous chips need a power-of-two fence region when tiling */
1387         if (INTEL_INFO(dev)->gen == 3)
1388                 size = 1024*1024;
1389         else
1390                 size = 512*1024;
1391
1392         while (size < obj->base.size)
1393                 size <<= 1;
1394
1395         return size;
1396 }
1397
1398 /**
1399  * i915_gem_get_gtt_alignment - return required GTT alignment for an object
1400  * @obj: object to check
1401  *
1402  * Return the required GTT alignment for an object, taking into account
1403  * potential fence register mapping.
1404  */
1405 static uint32_t
1406 i915_gem_get_gtt_alignment(struct drm_i915_gem_object *obj)
1407 {
1408         struct drm_device *dev = obj->base.dev;
1409
1410         /*
1411          * Minimum alignment is 4k (GTT page size), but might be greater
1412          * if a fence register is needed for the object.
1413          */
1414         if (INTEL_INFO(dev)->gen >= 4 ||
1415             obj->tiling_mode == I915_TILING_NONE)
1416                 return 4096;
1417
1418         /*
1419          * Previous chips need to be aligned to the size of the smallest
1420          * fence register that can contain the object.
1421          */
1422         return i915_gem_get_gtt_size(obj);
1423 }
1424
1425 /**
1426  * i915_gem_get_unfenced_gtt_alignment - return required GTT alignment for an
1427  *                                       unfenced object
1428  * @obj: object to check
1429  *
1430  * Return the required GTT alignment for an object, only taking into account
1431  * unfenced tiled surface requirements.
1432  */
1433 uint32_t
1434 i915_gem_get_unfenced_gtt_alignment(struct drm_i915_gem_object *obj)
1435 {
1436         struct drm_device *dev = obj->base.dev;
1437         int tile_height;
1438
1439         /*
1440          * Minimum alignment is 4k (GTT page size) for sane hw.
1441          */
1442         if (INTEL_INFO(dev)->gen >= 4 || IS_G33(dev) ||
1443             obj->tiling_mode == I915_TILING_NONE)
1444                 return 4096;
1445
1446         /*
1447          * Older chips need unfenced tiled buffers to be aligned to the left
1448          * edge of an even tile row (where tile rows are counted as if the bo is
1449          * placed in a fenced gtt region).
1450          */
1451         if (IS_GEN2(dev))
1452                 tile_height = 16;
1453         else if (obj->tiling_mode == I915_TILING_Y && HAS_128_BYTE_Y_TILING(dev))
1454                 tile_height = 32;
1455         else
1456                 tile_height = 8;
1457
1458         return tile_height * obj->stride * 2;
1459 }
1460
1461 int
1462 i915_gem_mmap_gtt(struct drm_file *file,
1463                   struct drm_device *dev,
1464                   uint32_t handle,
1465                   uint64_t *offset)
1466 {
1467         struct drm_i915_private *dev_priv = dev->dev_private;
1468         struct drm_i915_gem_object *obj;
1469         int ret;
1470
1471         if (!(dev->driver->driver_features & DRIVER_GEM))
1472                 return -ENODEV;
1473
1474         ret = i915_mutex_lock_interruptible(dev);
1475         if (ret)
1476                 return ret;
1477
1478         obj = to_intel_bo(drm_gem_object_lookup(dev, file, handle));
1479         if (&obj->base == NULL) {
1480                 ret = -ENOENT;
1481                 goto unlock;
1482         }
1483
1484         if (obj->base.size > dev_priv->mm.gtt_mappable_end) {
1485                 ret = -E2BIG;
1486                 goto unlock;
1487         }
1488
1489         if (obj->madv != I915_MADV_WILLNEED) {
1490                 DRM_ERROR("Attempting to mmap a purgeable buffer\n");
1491                 ret = -EINVAL;
1492                 goto out;
1493         }
1494
1495         if (!obj->base.map_list.map) {
1496                 ret = i915_gem_create_mmap_offset(obj);
1497                 if (ret)
1498                         goto out;
1499         }
1500
1501         *offset = (u64)obj->base.map_list.hash.key << PAGE_SHIFT;
1502
1503 out:
1504         drm_gem_object_unreference(&obj->base);
1505 unlock:
1506         mutex_unlock(&dev->struct_mutex);
1507         return ret;
1508 }
1509
1510 /**
1511  * i915_gem_mmap_gtt_ioctl - prepare an object for GTT mmap'ing
1512  * @dev: DRM device
1513  * @data: GTT mapping ioctl data
1514  * @file: GEM object info
1515  *
1516  * Simply returns the fake offset to userspace so it can mmap it.
1517  * The mmap call will end up in drm_gem_mmap(), which will set things
1518  * up so we can get faults in the handler above.
1519  *
1520  * The fault handler will take care of binding the object into the GTT
1521  * (since it may have been evicted to make room for something), allocating
1522  * a fence register, and mapping the appropriate aperture address into
1523  * userspace.
1524  */
1525 int
1526 i915_gem_mmap_gtt_ioctl(struct drm_device *dev, void *data,
1527                         struct drm_file *file)
1528 {
1529         struct drm_i915_gem_mmap_gtt *args = data;
1530
1531         if (!(dev->driver->driver_features & DRIVER_GEM))
1532                 return -ENODEV;
1533
1534         return i915_gem_mmap_gtt(file, dev, args->handle, &args->offset);
1535 }
1536
1537
1538 static int
1539 i915_gem_object_get_pages_gtt(struct drm_i915_gem_object *obj,
1540                               gfp_t gfpmask)
1541 {
1542         int page_count, i;
1543         struct address_space *mapping;
1544         struct inode *inode;
1545         struct page *page;
1546
1547         /* Get the list of pages out of our struct file.  They'll be pinned
1548          * at this point until we release them.
1549          */
1550         page_count = obj->base.size / PAGE_SIZE;
1551         BUG_ON(obj->pages != NULL);
1552         obj->pages = drm_malloc_ab(page_count, sizeof(struct page *));
1553         if (obj->pages == NULL)
1554                 return -ENOMEM;
1555
1556         inode = obj->base.filp->f_path.dentry->d_inode;
1557         mapping = inode->i_mapping;
1558         gfpmask |= mapping_gfp_mask(mapping);
1559
1560         for (i = 0; i < page_count; i++) {
1561                 page = shmem_read_mapping_page_gfp(mapping, i, gfpmask);
1562                 if (IS_ERR(page))
1563                         goto err_pages;
1564
1565                 obj->pages[i] = page;
1566         }
1567
1568         if (obj->tiling_mode != I915_TILING_NONE)
1569                 i915_gem_object_do_bit_17_swizzle(obj);
1570
1571         return 0;
1572
1573 err_pages:
1574         while (i--)
1575                 page_cache_release(obj->pages[i]);
1576
1577         drm_free_large(obj->pages);
1578         obj->pages = NULL;
1579         return PTR_ERR(page);
1580 }
1581
1582 static void
1583 i915_gem_object_put_pages_gtt(struct drm_i915_gem_object *obj)
1584 {
1585         int page_count = obj->base.size / PAGE_SIZE;
1586         int i;
1587
1588         BUG_ON(obj->madv == __I915_MADV_PURGED);
1589
1590         if (obj->tiling_mode != I915_TILING_NONE)
1591                 i915_gem_object_save_bit_17_swizzle(obj);
1592
1593         if (obj->madv == I915_MADV_DONTNEED)
1594                 obj->dirty = 0;
1595
1596         for (i = 0; i < page_count; i++) {
1597                 if (obj->dirty)
1598                         set_page_dirty(obj->pages[i]);
1599
1600                 if (obj->madv == I915_MADV_WILLNEED)
1601                         mark_page_accessed(obj->pages[i]);
1602
1603                 page_cache_release(obj->pages[i]);
1604         }
1605         obj->dirty = 0;
1606
1607         drm_free_large(obj->pages);
1608         obj->pages = NULL;
1609 }
1610
1611 void
1612 i915_gem_object_move_to_active(struct drm_i915_gem_object *obj,
1613                                struct intel_ring_buffer *ring,
1614                                u32 seqno)
1615 {
1616         struct drm_device *dev = obj->base.dev;
1617         struct drm_i915_private *dev_priv = dev->dev_private;
1618
1619         BUG_ON(ring == NULL);
1620         obj->ring = ring;
1621
1622         /* Add a reference if we're newly entering the active list. */
1623         if (!obj->active) {
1624                 drm_gem_object_reference(&obj->base);
1625                 obj->active = 1;
1626         }
1627
1628         /* Move from whatever list we were on to the tail of execution. */
1629         list_move_tail(&obj->mm_list, &dev_priv->mm.active_list);
1630         list_move_tail(&obj->ring_list, &ring->active_list);
1631
1632         obj->last_rendering_seqno = seqno;
1633         if (obj->fenced_gpu_access) {
1634                 struct drm_i915_fence_reg *reg;
1635
1636                 BUG_ON(obj->fence_reg == I915_FENCE_REG_NONE);
1637
1638                 obj->last_fenced_seqno = seqno;
1639                 obj->last_fenced_ring = ring;
1640
1641                 reg = &dev_priv->fence_regs[obj->fence_reg];
1642                 list_move_tail(&reg->lru_list, &dev_priv->mm.fence_list);
1643         }
1644 }
1645
1646 static void
1647 i915_gem_object_move_off_active(struct drm_i915_gem_object *obj)
1648 {
1649         list_del_init(&obj->ring_list);
1650         obj->last_rendering_seqno = 0;
1651 }
1652
1653 static void
1654 i915_gem_object_move_to_flushing(struct drm_i915_gem_object *obj)
1655 {
1656         struct drm_device *dev = obj->base.dev;
1657         drm_i915_private_t *dev_priv = dev->dev_private;
1658
1659         BUG_ON(!obj->active);
1660         list_move_tail(&obj->mm_list, &dev_priv->mm.flushing_list);
1661
1662         i915_gem_object_move_off_active(obj);
1663 }
1664
1665 static void
1666 i915_gem_object_move_to_inactive(struct drm_i915_gem_object *obj)
1667 {
1668         struct drm_device *dev = obj->base.dev;
1669         struct drm_i915_private *dev_priv = dev->dev_private;
1670
1671         if (obj->pin_count != 0)
1672                 list_move_tail(&obj->mm_list, &dev_priv->mm.pinned_list);
1673         else
1674                 list_move_tail(&obj->mm_list, &dev_priv->mm.inactive_list);
1675
1676         BUG_ON(!list_empty(&obj->gpu_write_list));
1677         BUG_ON(!obj->active);
1678         obj->ring = NULL;
1679
1680         i915_gem_object_move_off_active(obj);
1681         obj->fenced_gpu_access = false;
1682
1683         obj->active = 0;
1684         obj->pending_gpu_write = false;
1685         drm_gem_object_unreference(&obj->base);
1686
1687         WARN_ON(i915_verify_lists(dev));
1688 }
1689
1690 /* Immediately discard the backing storage */
1691 static void
1692 i915_gem_object_truncate(struct drm_i915_gem_object *obj)
1693 {
1694         struct inode *inode;
1695
1696         /* Our goal here is to return as much of the memory as
1697          * is possible back to the system as we are called from OOM.
1698          * To do this we must instruct the shmfs to drop all of its
1699          * backing pages, *now*. Here we mirror the actions taken
1700          * when by shmem_delete_inode() to release the backing store.
1701          */
1702         inode = obj->base.filp->f_path.dentry->d_inode;
1703         truncate_inode_pages(inode->i_mapping, 0);
1704         if (inode->i_op->truncate_range)
1705                 inode->i_op->truncate_range(inode, 0, (loff_t)-1);
1706
1707         obj->madv = __I915_MADV_PURGED;
1708 }
1709
1710 static inline int
1711 i915_gem_object_is_purgeable(struct drm_i915_gem_object *obj)
1712 {
1713         return obj->madv == I915_MADV_DONTNEED;
1714 }
1715
1716 static void
1717 i915_gem_process_flushing_list(struct intel_ring_buffer *ring,
1718                                uint32_t flush_domains)
1719 {
1720         struct drm_i915_gem_object *obj, *next;
1721
1722         list_for_each_entry_safe(obj, next,
1723                                  &ring->gpu_write_list,
1724                                  gpu_write_list) {
1725                 if (obj->base.write_domain & flush_domains) {
1726                         uint32_t old_write_domain = obj->base.write_domain;
1727
1728                         obj->base.write_domain = 0;
1729                         list_del_init(&obj->gpu_write_list);
1730                         i915_gem_object_move_to_active(obj, ring,
1731                                                        i915_gem_next_request_seqno(ring));
1732
1733                         trace_i915_gem_object_change_domain(obj,
1734                                                             obj->base.read_domains,
1735                                                             old_write_domain);
1736                 }
1737         }
1738 }
1739
1740 int
1741 i915_add_request(struct intel_ring_buffer *ring,
1742                  struct drm_file *file,
1743                  struct drm_i915_gem_request *request)
1744 {
1745         drm_i915_private_t *dev_priv = ring->dev->dev_private;
1746         uint32_t seqno;
1747         int was_empty;
1748         int ret;
1749
1750         BUG_ON(request == NULL);
1751
1752         ret = ring->add_request(ring, &seqno);
1753         if (ret)
1754             return ret;
1755
1756         trace_i915_gem_request_add(ring, seqno);
1757
1758         request->seqno = seqno;
1759         request->ring = ring;
1760         request->emitted_jiffies = jiffies;
1761         was_empty = list_empty(&ring->request_list);
1762         list_add_tail(&request->list, &ring->request_list);
1763
1764         if (file) {
1765                 struct drm_i915_file_private *file_priv = file->driver_priv;
1766
1767                 spin_lock(&file_priv->mm.lock);
1768                 request->file_priv = file_priv;
1769                 list_add_tail(&request->client_list,
1770                               &file_priv->mm.request_list);
1771                 spin_unlock(&file_priv->mm.lock);
1772         }
1773
1774         ring->outstanding_lazy_request = false;
1775
1776         if (!dev_priv->mm.suspended) {
1777                 mod_timer(&dev_priv->hangcheck_timer,
1778                           jiffies + msecs_to_jiffies(DRM_I915_HANGCHECK_PERIOD));
1779                 if (was_empty)
1780                         queue_delayed_work(dev_priv->wq,
1781                                            &dev_priv->mm.retire_work, HZ);
1782         }
1783         return 0;
1784 }
1785
1786 static inline void
1787 i915_gem_request_remove_from_client(struct drm_i915_gem_request *request)
1788 {
1789         struct drm_i915_file_private *file_priv = request->file_priv;
1790
1791         if (!file_priv)
1792                 return;
1793
1794         spin_lock(&file_priv->mm.lock);
1795         if (request->file_priv) {
1796                 list_del(&request->client_list);
1797                 request->file_priv = NULL;
1798         }
1799         spin_unlock(&file_priv->mm.lock);
1800 }
1801
1802 static void i915_gem_reset_ring_lists(struct drm_i915_private *dev_priv,
1803                                       struct intel_ring_buffer *ring)
1804 {
1805         while (!list_empty(&ring->request_list)) {
1806                 struct drm_i915_gem_request *request;
1807
1808                 request = list_first_entry(&ring->request_list,
1809                                            struct drm_i915_gem_request,
1810                                            list);
1811
1812                 list_del(&request->list);
1813                 i915_gem_request_remove_from_client(request);
1814                 kfree(request);
1815         }
1816
1817         while (!list_empty(&ring->active_list)) {
1818                 struct drm_i915_gem_object *obj;
1819
1820                 obj = list_first_entry(&ring->active_list,
1821                                        struct drm_i915_gem_object,
1822                                        ring_list);
1823
1824                 obj->base.write_domain = 0;
1825                 list_del_init(&obj->gpu_write_list);
1826                 i915_gem_object_move_to_inactive(obj);
1827         }
1828 }
1829
1830 static void i915_gem_reset_fences(struct drm_device *dev)
1831 {
1832         struct drm_i915_private *dev_priv = dev->dev_private;
1833         int i;
1834
1835         for (i = 0; i < 16; i++) {
1836                 struct drm_i915_fence_reg *reg = &dev_priv->fence_regs[i];
1837                 struct drm_i915_gem_object *obj = reg->obj;
1838
1839                 if (!obj)
1840                         continue;
1841
1842                 if (obj->tiling_mode)
1843                         i915_gem_release_mmap(obj);
1844
1845                 reg->obj->fence_reg = I915_FENCE_REG_NONE;
1846                 reg->obj->fenced_gpu_access = false;
1847                 reg->obj->last_fenced_seqno = 0;
1848                 reg->obj->last_fenced_ring = NULL;
1849                 i915_gem_clear_fence_reg(dev, reg);
1850         }
1851 }
1852
1853 void i915_gem_reset(struct drm_device *dev)
1854 {
1855         struct drm_i915_private *dev_priv = dev->dev_private;
1856         struct drm_i915_gem_object *obj;
1857         int i;
1858
1859         for (i = 0; i < I915_NUM_RINGS; i++)
1860                 i915_gem_reset_ring_lists(dev_priv, &dev_priv->ring[i]);
1861
1862         /* Remove anything from the flushing lists. The GPU cache is likely
1863          * to be lost on reset along with the data, so simply move the
1864          * lost bo to the inactive list.
1865          */
1866         while (!list_empty(&dev_priv->mm.flushing_list)) {
1867                 obj= list_first_entry(&dev_priv->mm.flushing_list,
1868                                       struct drm_i915_gem_object,
1869                                       mm_list);
1870
1871                 obj->base.write_domain = 0;
1872                 list_del_init(&obj->gpu_write_list);
1873                 i915_gem_object_move_to_inactive(obj);
1874         }
1875
1876         /* Move everything out of the GPU domains to ensure we do any
1877          * necessary invalidation upon reuse.
1878          */
1879         list_for_each_entry(obj,
1880                             &dev_priv->mm.inactive_list,
1881                             mm_list)
1882         {
1883                 obj->base.read_domains &= ~I915_GEM_GPU_DOMAINS;
1884         }
1885
1886         /* The fence registers are invalidated so clear them out */
1887         i915_gem_reset_fences(dev);
1888 }
1889
1890 /**
1891  * This function clears the request list as sequence numbers are passed.
1892  */
1893 static void
1894 i915_gem_retire_requests_ring(struct intel_ring_buffer *ring)
1895 {
1896         uint32_t seqno;
1897         int i;
1898
1899         if (list_empty(&ring->request_list))
1900                 return;
1901
1902         WARN_ON(i915_verify_lists(ring->dev));
1903
1904         seqno = ring->get_seqno(ring);
1905
1906         for (i = 0; i < ARRAY_SIZE(ring->sync_seqno); i++)
1907                 if (seqno >= ring->sync_seqno[i])
1908                         ring->sync_seqno[i] = 0;
1909
1910         while (!list_empty(&ring->request_list)) {
1911                 struct drm_i915_gem_request *request;
1912
1913                 request = list_first_entry(&ring->request_list,
1914                                            struct drm_i915_gem_request,
1915                                            list);
1916
1917                 if (!i915_seqno_passed(seqno, request->seqno))
1918                         break;
1919
1920                 trace_i915_gem_request_retire(ring, request->seqno);
1921
1922                 list_del(&request->list);
1923                 i915_gem_request_remove_from_client(request);
1924                 kfree(request);
1925         }
1926
1927         /* Move any buffers on the active list that are no longer referenced
1928          * by the ringbuffer to the flushing/inactive lists as appropriate.
1929          */
1930         while (!list_empty(&ring->active_list)) {
1931                 struct drm_i915_gem_object *obj;
1932
1933                 obj= list_first_entry(&ring->active_list,
1934                                       struct drm_i915_gem_object,
1935                                       ring_list);
1936
1937                 if (!i915_seqno_passed(seqno, obj->last_rendering_seqno))
1938                         break;
1939
1940                 if (obj->base.write_domain != 0)
1941                         i915_gem_object_move_to_flushing(obj);
1942                 else
1943                         i915_gem_object_move_to_inactive(obj);
1944         }
1945
1946         if (unlikely(ring->trace_irq_seqno &&
1947                      i915_seqno_passed(seqno, ring->trace_irq_seqno))) {
1948                 ring->irq_put(ring);
1949                 ring->trace_irq_seqno = 0;
1950         }
1951
1952         WARN_ON(i915_verify_lists(ring->dev));
1953 }
1954
1955 void
1956 i915_gem_retire_requests(struct drm_device *dev)
1957 {
1958         drm_i915_private_t *dev_priv = dev->dev_private;
1959         int i;
1960
1961         if (!list_empty(&dev_priv->mm.deferred_free_list)) {
1962             struct drm_i915_gem_object *obj, *next;
1963
1964             /* We must be careful that during unbind() we do not
1965              * accidentally infinitely recurse into retire requests.
1966              * Currently:
1967              *   retire -> free -> unbind -> wait -> retire_ring
1968              */
1969             list_for_each_entry_safe(obj, next,
1970                                      &dev_priv->mm.deferred_free_list,
1971                                      mm_list)
1972                     i915_gem_free_object_tail(obj);
1973         }
1974
1975         for (i = 0; i < I915_NUM_RINGS; i++)
1976                 i915_gem_retire_requests_ring(&dev_priv->ring[i]);
1977 }
1978
1979 static void
1980 i915_gem_retire_work_handler(struct work_struct *work)
1981 {
1982         drm_i915_private_t *dev_priv;
1983         struct drm_device *dev;
1984         bool idle;
1985         int i;
1986
1987         dev_priv = container_of(work, drm_i915_private_t,
1988                                 mm.retire_work.work);
1989         dev = dev_priv->dev;
1990
1991         /* Come back later if the device is busy... */
1992         if (!mutex_trylock(&dev->struct_mutex)) {
1993                 queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work, HZ);
1994                 return;
1995         }
1996
1997         i915_gem_retire_requests(dev);
1998
1999         /* Send a periodic flush down the ring so we don't hold onto GEM
2000          * objects indefinitely.
2001          */
2002         idle = true;
2003         for (i = 0; i < I915_NUM_RINGS; i++) {
2004                 struct intel_ring_buffer *ring = &dev_priv->ring[i];
2005
2006                 if (!list_empty(&ring->gpu_write_list)) {
2007                         struct drm_i915_gem_request *request;
2008                         int ret;
2009
2010                         ret = i915_gem_flush_ring(ring,
2011                                                   0, I915_GEM_GPU_DOMAINS);
2012                         request = kzalloc(sizeof(*request), GFP_KERNEL);
2013                         if (ret || request == NULL ||
2014                             i915_add_request(ring, NULL, request))
2015                             kfree(request);
2016                 }
2017
2018                 idle &= list_empty(&ring->request_list);
2019         }
2020
2021         if (!dev_priv->mm.suspended && !idle)
2022                 queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work, HZ);
2023
2024         mutex_unlock(&dev->struct_mutex);
2025 }
2026
2027 /**
2028  * Waits for a sequence number to be signaled, and cleans up the
2029  * request and object lists appropriately for that event.
2030  */
2031 int
2032 i915_wait_request(struct intel_ring_buffer *ring,
2033                   uint32_t seqno)
2034 {
2035         drm_i915_private_t *dev_priv = ring->dev->dev_private;
2036         u32 ier;
2037         int ret = 0;
2038
2039         BUG_ON(seqno == 0);
2040
2041         if (atomic_read(&dev_priv->mm.wedged)) {
2042                 struct completion *x = &dev_priv->error_completion;
2043                 bool recovery_complete;
2044                 unsigned long flags;
2045
2046                 /* Give the error handler a chance to run. */
2047                 spin_lock_irqsave(&x->wait.lock, flags);
2048                 recovery_complete = x->done > 0;
2049                 spin_unlock_irqrestore(&x->wait.lock, flags);
2050
2051                 return recovery_complete ? -EIO : -EAGAIN;
2052         }
2053
2054         if (seqno == ring->outstanding_lazy_request) {
2055                 struct drm_i915_gem_request *request;
2056
2057                 request = kzalloc(sizeof(*request), GFP_KERNEL);
2058                 if (request == NULL)
2059                         return -ENOMEM;
2060
2061                 ret = i915_add_request(ring, NULL, request);
2062                 if (ret) {
2063                         kfree(request);
2064                         return ret;
2065                 }
2066
2067                 seqno = request->seqno;
2068         }
2069
2070         if (!i915_seqno_passed(ring->get_seqno(ring), seqno)) {
2071                 if (HAS_PCH_SPLIT(ring->dev))
2072                         ier = I915_READ(DEIER) | I915_READ(GTIER);
2073                 else
2074                         ier = I915_READ(IER);
2075                 if (!ier) {
2076                         DRM_ERROR("something (likely vbetool) disabled "
2077                                   "interrupts, re-enabling\n");
2078                         i915_driver_irq_preinstall(ring->dev);
2079                         i915_driver_irq_postinstall(ring->dev);
2080                 }
2081
2082                 trace_i915_gem_request_wait_begin(ring, seqno);
2083
2084                 ring->waiting_seqno = seqno;
2085                 if (ring->irq_get(ring)) {
2086                         if (dev_priv->mm.interruptible)
2087                                 ret = wait_event_interruptible(ring->irq_queue,
2088                                                                i915_seqno_passed(ring->get_seqno(ring), seqno)
2089                                                                || atomic_read(&dev_priv->mm.wedged));
2090                         else
2091                                 wait_event(ring->irq_queue,
2092                                            i915_seqno_passed(ring->get_seqno(ring), seqno)
2093                                            || atomic_read(&dev_priv->mm.wedged));
2094
2095                         ring->irq_put(ring);
2096                 } else if (wait_for(i915_seqno_passed(ring->get_seqno(ring),
2097                                                       seqno) ||
2098                                     atomic_read(&dev_priv->mm.wedged), 3000))
2099                         ret = -EBUSY;
2100                 ring->waiting_seqno = 0;
2101
2102                 trace_i915_gem_request_wait_end(ring, seqno);
2103         }
2104         if (atomic_read(&dev_priv->mm.wedged))
2105                 ret = -EAGAIN;
2106
2107         if (ret && ret != -ERESTARTSYS)
2108                 DRM_ERROR("%s returns %d (awaiting %d at %d, next %d)\n",
2109                           __func__, ret, seqno, ring->get_seqno(ring),
2110                           dev_priv->next_seqno);
2111
2112         /* Directly dispatch request retiring.  While we have the work queue
2113          * to handle this, the waiter on a request often wants an associated
2114          * buffer to have made it to the inactive list, and we would need
2115          * a separate wait queue to handle that.
2116          */
2117         if (ret == 0)
2118                 i915_gem_retire_requests_ring(ring);
2119
2120         return ret;
2121 }
2122
2123 /**
2124  * Ensures that all rendering to the object has completed and the object is
2125  * safe to unbind from the GTT or access from the CPU.
2126  */
2127 int
2128 i915_gem_object_wait_rendering(struct drm_i915_gem_object *obj)
2129 {
2130         int ret;
2131
2132         /* This function only exists to support waiting for existing rendering,
2133          * not for emitting required flushes.
2134          */
2135         BUG_ON((obj->base.write_domain & I915_GEM_GPU_DOMAINS) != 0);
2136
2137         /* If there is rendering queued on the buffer being evicted, wait for
2138          * it.
2139          */
2140         if (obj->active) {
2141                 ret = i915_wait_request(obj->ring, obj->last_rendering_seqno);
2142                 if (ret)
2143                         return ret;
2144         }
2145
2146         return 0;
2147 }
2148
2149 /**
2150  * Unbinds an object from the GTT aperture.
2151  */
2152 int
2153 i915_gem_object_unbind(struct drm_i915_gem_object *obj)
2154 {
2155         int ret = 0;
2156
2157         if (obj->gtt_space == NULL)
2158                 return 0;
2159
2160         if (obj->pin_count != 0) {
2161                 DRM_ERROR("Attempting to unbind pinned buffer\n");
2162                 return -EINVAL;
2163         }
2164
2165         /* blow away mappings if mapped through GTT */
2166         i915_gem_release_mmap(obj);
2167
2168         /* Move the object to the CPU domain to ensure that
2169          * any possible CPU writes while it's not in the GTT
2170          * are flushed when we go to remap it. This will
2171          * also ensure that all pending GPU writes are finished
2172          * before we unbind.
2173          */
2174         ret = i915_gem_object_set_to_cpu_domain(obj, 1);
2175         if (ret == -ERESTARTSYS)
2176                 return ret;
2177         /* Continue on if we fail due to EIO, the GPU is hung so we
2178          * should be safe and we need to cleanup or else we might
2179          * cause memory corruption through use-after-free.
2180          */
2181         if (ret) {
2182                 i915_gem_clflush_object(obj);
2183                 obj->base.read_domains = obj->base.write_domain = I915_GEM_DOMAIN_CPU;
2184         }
2185
2186         /* release the fence reg _after_ flushing */
2187         ret = i915_gem_object_put_fence(obj);
2188         if (ret == -ERESTARTSYS)
2189                 return ret;
2190
2191         trace_i915_gem_object_unbind(obj);
2192
2193         i915_gem_gtt_unbind_object(obj);
2194         i915_gem_object_put_pages_gtt(obj);
2195
2196         list_del_init(&obj->gtt_list);
2197         list_del_init(&obj->mm_list);
2198         /* Avoid an unnecessary call to unbind on rebind. */
2199         obj->map_and_fenceable = true;
2200
2201         drm_mm_put_block(obj->gtt_space);
2202         obj->gtt_space = NULL;
2203         obj->gtt_offset = 0;
2204
2205         if (i915_gem_object_is_purgeable(obj))
2206                 i915_gem_object_truncate(obj);
2207
2208         return ret;
2209 }
2210
2211 int
2212 i915_gem_flush_ring(struct intel_ring_buffer *ring,
2213                     uint32_t invalidate_domains,
2214                     uint32_t flush_domains)
2215 {
2216         int ret;
2217
2218         if (((invalidate_domains | flush_domains) & I915_GEM_GPU_DOMAINS) == 0)
2219                 return 0;
2220
2221         trace_i915_gem_ring_flush(ring, invalidate_domains, flush_domains);
2222
2223         ret = ring->flush(ring, invalidate_domains, flush_domains);
2224         if (ret)
2225                 return ret;
2226
2227         if (flush_domains & I915_GEM_GPU_DOMAINS)
2228                 i915_gem_process_flushing_list(ring, flush_domains);
2229
2230         return 0;
2231 }
2232
2233 static int i915_ring_idle(struct intel_ring_buffer *ring)
2234 {
2235         int ret;
2236
2237         if (list_empty(&ring->gpu_write_list) && list_empty(&ring->active_list))
2238                 return 0;
2239
2240         if (!list_empty(&ring->gpu_write_list)) {
2241                 ret = i915_gem_flush_ring(ring,
2242                                     I915_GEM_GPU_DOMAINS, I915_GEM_GPU_DOMAINS);
2243                 if (ret)
2244                         return ret;
2245         }
2246
2247         return i915_wait_request(ring, i915_gem_next_request_seqno(ring));
2248 }
2249
2250 int
2251 i915_gpu_idle(struct drm_device *dev)
2252 {
2253         drm_i915_private_t *dev_priv = dev->dev_private;
2254         bool lists_empty;
2255         int ret, i;
2256
2257         lists_empty = (list_empty(&dev_priv->mm.flushing_list) &&
2258                        list_empty(&dev_priv->mm.active_list));
2259         if (lists_empty)
2260                 return 0;
2261
2262         /* Flush everything onto the inactive list. */
2263         for (i = 0; i < I915_NUM_RINGS; i++) {
2264                 ret = i915_ring_idle(&dev_priv->ring[i]);
2265                 if (ret)
2266                         return ret;
2267         }
2268
2269         return 0;
2270 }
2271
2272 static int sandybridge_write_fence_reg(struct drm_i915_gem_object *obj,
2273                                        struct intel_ring_buffer *pipelined)
2274 {
2275         struct drm_device *dev = obj->base.dev;
2276         drm_i915_private_t *dev_priv = dev->dev_private;
2277         u32 size = obj->gtt_space->size;
2278         int regnum = obj->fence_reg;
2279         uint64_t val;
2280
2281         val = (uint64_t)((obj->gtt_offset + size - 4096) &
2282                          0xfffff000) << 32;
2283         val |= obj->gtt_offset & 0xfffff000;
2284         val |= (uint64_t)((obj->stride / 128) - 1) <<
2285                 SANDYBRIDGE_FENCE_PITCH_SHIFT;
2286
2287         if (obj->tiling_mode == I915_TILING_Y)
2288                 val |= 1 << I965_FENCE_TILING_Y_SHIFT;
2289         val |= I965_FENCE_REG_VALID;
2290
2291         if (pipelined) {
2292                 int ret = intel_ring_begin(pipelined, 6);
2293                 if (ret)
2294                         return ret;
2295
2296                 intel_ring_emit(pipelined, MI_NOOP);
2297                 intel_ring_emit(pipelined, MI_LOAD_REGISTER_IMM(2));
2298                 intel_ring_emit(pipelined, FENCE_REG_SANDYBRIDGE_0 + regnum*8);
2299                 intel_ring_emit(pipelined, (u32)val);
2300                 intel_ring_emit(pipelined, FENCE_REG_SANDYBRIDGE_0 + regnum*8 + 4);
2301                 intel_ring_emit(pipelined, (u32)(val >> 32));
2302                 intel_ring_advance(pipelined);
2303         } else
2304                 I915_WRITE64(FENCE_REG_SANDYBRIDGE_0 + regnum * 8, val);
2305
2306         return 0;
2307 }
2308
2309 static int i965_write_fence_reg(struct drm_i915_gem_object *obj,
2310                                 struct intel_ring_buffer *pipelined)
2311 {
2312         struct drm_device *dev = obj->base.dev;
2313         drm_i915_private_t *dev_priv = dev->dev_private;
2314         u32 size = obj->gtt_space->size;
2315         int regnum = obj->fence_reg;
2316         uint64_t val;
2317
2318         val = (uint64_t)((obj->gtt_offset + size - 4096) &
2319                     0xfffff000) << 32;
2320         val |= obj->gtt_offset & 0xfffff000;
2321         val |= ((obj->stride / 128) - 1) << I965_FENCE_PITCH_SHIFT;
2322         if (obj->tiling_mode == I915_TILING_Y)
2323                 val |= 1 << I965_FENCE_TILING_Y_SHIFT;
2324         val |= I965_FENCE_REG_VALID;
2325
2326         if (pipelined) {
2327                 int ret = intel_ring_begin(pipelined, 6);
2328                 if (ret)
2329                         return ret;
2330
2331                 intel_ring_emit(pipelined, MI_NOOP);
2332                 intel_ring_emit(pipelined, MI_LOAD_REGISTER_IMM(2));
2333                 intel_ring_emit(pipelined, FENCE_REG_965_0 + regnum*8);
2334                 intel_ring_emit(pipelined, (u32)val);
2335                 intel_ring_emit(pipelined, FENCE_REG_965_0 + regnum*8 + 4);
2336                 intel_ring_emit(pipelined, (u32)(val >> 32));
2337                 intel_ring_advance(pipelined);
2338         } else
2339                 I915_WRITE64(FENCE_REG_965_0 + regnum * 8, val);
2340
2341         return 0;
2342 }
2343
2344 static int i915_write_fence_reg(struct drm_i915_gem_object *obj,
2345                                 struct intel_ring_buffer *pipelined)
2346 {
2347         struct drm_device *dev = obj->base.dev;
2348         drm_i915_private_t *dev_priv = dev->dev_private;
2349         u32 size = obj->gtt_space->size;
2350         u32 fence_reg, val, pitch_val;
2351         int tile_width;
2352
2353         if (WARN((obj->gtt_offset & ~I915_FENCE_START_MASK) ||
2354                  (size & -size) != size ||
2355                  (obj->gtt_offset & (size - 1)),
2356                  "object 0x%08x [fenceable? %d] not 1M or pot-size (0x%08x) aligned\n",
2357                  obj->gtt_offset, obj->map_and_fenceable, size))
2358                 return -EINVAL;
2359
2360         if (obj->tiling_mode == I915_TILING_Y && HAS_128_BYTE_Y_TILING(dev))
2361                 tile_width = 128;
2362         else
2363                 tile_width = 512;
2364
2365         /* Note: pitch better be a power of two tile widths */
2366         pitch_val = obj->stride / tile_width;
2367         pitch_val = ffs(pitch_val) - 1;
2368
2369         val = obj->gtt_offset;
2370         if (obj->tiling_mode == I915_TILING_Y)
2371                 val |= 1 << I830_FENCE_TILING_Y_SHIFT;
2372         val |= I915_FENCE_SIZE_BITS(size);
2373         val |= pitch_val << I830_FENCE_PITCH_SHIFT;
2374         val |= I830_FENCE_REG_VALID;
2375
2376         fence_reg = obj->fence_reg;
2377         if (fence_reg < 8)
2378                 fence_reg = FENCE_REG_830_0 + fence_reg * 4;
2379         else
2380                 fence_reg = FENCE_REG_945_8 + (fence_reg - 8) * 4;
2381
2382         if (pipelined) {
2383                 int ret = intel_ring_begin(pipelined, 4);
2384                 if (ret)
2385                         return ret;
2386
2387                 intel_ring_emit(pipelined, MI_NOOP);
2388                 intel_ring_emit(pipelined, MI_LOAD_REGISTER_IMM(1));
2389                 intel_ring_emit(pipelined, fence_reg);
2390                 intel_ring_emit(pipelined, val);
2391                 intel_ring_advance(pipelined);
2392         } else
2393                 I915_WRITE(fence_reg, val);
2394
2395         return 0;
2396 }
2397
2398 static int i830_write_fence_reg(struct drm_i915_gem_object *obj,
2399                                 struct intel_ring_buffer *pipelined)
2400 {
2401         struct drm_device *dev = obj->base.dev;
2402         drm_i915_private_t *dev_priv = dev->dev_private;
2403         u32 size = obj->gtt_space->size;
2404         int regnum = obj->fence_reg;
2405         uint32_t val;
2406         uint32_t pitch_val;
2407
2408         if (WARN((obj->gtt_offset & ~I830_FENCE_START_MASK) ||
2409                  (size & -size) != size ||
2410                  (obj->gtt_offset & (size - 1)),
2411                  "object 0x%08x not 512K or pot-size 0x%08x aligned\n",
2412                  obj->gtt_offset, size))
2413                 return -EINVAL;
2414
2415         pitch_val = obj->stride / 128;
2416         pitch_val = ffs(pitch_val) - 1;
2417
2418         val = obj->gtt_offset;
2419         if (obj->tiling_mode == I915_TILING_Y)
2420                 val |= 1 << I830_FENCE_TILING_Y_SHIFT;
2421         val |= I830_FENCE_SIZE_BITS(size);
2422         val |= pitch_val << I830_FENCE_PITCH_SHIFT;
2423         val |= I830_FENCE_REG_VALID;
2424
2425         if (pipelined) {
2426                 int ret = intel_ring_begin(pipelined, 4);
2427                 if (ret)
2428                         return ret;
2429
2430                 intel_ring_emit(pipelined, MI_NOOP);
2431                 intel_ring_emit(pipelined, MI_LOAD_REGISTER_IMM(1));
2432                 intel_ring_emit(pipelined, FENCE_REG_830_0 + regnum*4);
2433                 intel_ring_emit(pipelined, val);
2434                 intel_ring_advance(pipelined);
2435         } else
2436                 I915_WRITE(FENCE_REG_830_0 + regnum * 4, val);
2437
2438         return 0;
2439 }
2440
2441 static bool ring_passed_seqno(struct intel_ring_buffer *ring, u32 seqno)
2442 {
2443         return i915_seqno_passed(ring->get_seqno(ring), seqno);
2444 }
2445
2446 static int
2447 i915_gem_object_flush_fence(struct drm_i915_gem_object *obj,
2448                             struct intel_ring_buffer *pipelined)
2449 {
2450         int ret;
2451
2452         if (obj->fenced_gpu_access) {
2453                 if (obj->base.write_domain & I915_GEM_GPU_DOMAINS) {
2454                         ret = i915_gem_flush_ring(obj->last_fenced_ring,
2455                                                   0, obj->base.write_domain);
2456                         if (ret)
2457                                 return ret;
2458                 }
2459
2460                 obj->fenced_gpu_access = false;
2461         }
2462
2463         if (obj->last_fenced_seqno && pipelined != obj->last_fenced_ring) {
2464                 if (!ring_passed_seqno(obj->last_fenced_ring,
2465                                        obj->last_fenced_seqno)) {
2466                         ret = i915_wait_request(obj->last_fenced_ring,
2467                                                 obj->last_fenced_seqno);
2468                         if (ret)
2469                                 return ret;
2470                 }
2471
2472                 obj->last_fenced_seqno = 0;
2473                 obj->last_fenced_ring = NULL;
2474         }
2475
2476         /* Ensure that all CPU reads are completed before installing a fence
2477          * and all writes before removing the fence.
2478          */
2479         if (obj->base.read_domains & I915_GEM_DOMAIN_GTT)
2480                 mb();
2481
2482         return 0;
2483 }
2484
2485 int
2486 i915_gem_object_put_fence(struct drm_i915_gem_object *obj)
2487 {
2488         int ret;
2489
2490         if (obj->tiling_mode)
2491                 i915_gem_release_mmap(obj);
2492
2493         ret = i915_gem_object_flush_fence(obj, NULL);
2494         if (ret)
2495                 return ret;
2496
2497         if (obj->fence_reg != I915_FENCE_REG_NONE) {
2498                 struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
2499                 i915_gem_clear_fence_reg(obj->base.dev,
2500                                          &dev_priv->fence_regs[obj->fence_reg]);
2501
2502                 obj->fence_reg = I915_FENCE_REG_NONE;
2503         }
2504
2505         return 0;
2506 }
2507
2508 static struct drm_i915_fence_reg *
2509 i915_find_fence_reg(struct drm_device *dev,
2510                     struct intel_ring_buffer *pipelined)
2511 {
2512         struct drm_i915_private *dev_priv = dev->dev_private;
2513         struct drm_i915_fence_reg *reg, *first, *avail;
2514         int i;
2515
2516         /* First try to find a free reg */
2517         avail = NULL;
2518         for (i = dev_priv->fence_reg_start; i < dev_priv->num_fence_regs; i++) {
2519                 reg = &dev_priv->fence_regs[i];
2520                 if (!reg->obj)
2521                         return reg;
2522
2523                 if (!reg->obj->pin_count)
2524                         avail = reg;
2525         }
2526
2527         if (avail == NULL)
2528                 return NULL;
2529
2530         /* None available, try to steal one or wait for a user to finish */
2531         avail = first = NULL;
2532         list_for_each_entry(reg, &dev_priv->mm.fence_list, lru_list) {
2533                 if (reg->obj->pin_count)
2534                         continue;
2535
2536                 if (first == NULL)
2537                         first = reg;
2538
2539                 if (!pipelined ||
2540                     !reg->obj->last_fenced_ring ||
2541                     reg->obj->last_fenced_ring == pipelined) {
2542                         avail = reg;
2543                         break;
2544                 }
2545         }
2546
2547         if (avail == NULL)
2548                 avail = first;
2549
2550         return avail;
2551 }
2552
2553 /**
2554  * i915_gem_object_get_fence - set up a fence reg for an object
2555  * @obj: object to map through a fence reg
2556  * @pipelined: ring on which to queue the change, or NULL for CPU access
2557  * @interruptible: must we wait uninterruptibly for the register to retire?
2558  *
2559  * When mapping objects through the GTT, userspace wants to be able to write
2560  * to them without having to worry about swizzling if the object is tiled.
2561  *
2562  * This function walks the fence regs looking for a free one for @obj,
2563  * stealing one if it can't find any.
2564  *
2565  * It then sets up the reg based on the object's properties: address, pitch
2566  * and tiling format.
2567  */
2568 int
2569 i915_gem_object_get_fence(struct drm_i915_gem_object *obj,
2570                           struct intel_ring_buffer *pipelined)
2571 {
2572         struct drm_device *dev = obj->base.dev;
2573         struct drm_i915_private *dev_priv = dev->dev_private;
2574         struct drm_i915_fence_reg *reg;
2575         int ret;
2576
2577         /* XXX disable pipelining. There are bugs. Shocking. */
2578         pipelined = NULL;
2579
2580         /* Just update our place in the LRU if our fence is getting reused. */
2581         if (obj->fence_reg != I915_FENCE_REG_NONE) {
2582                 reg = &dev_priv->fence_regs[obj->fence_reg];
2583                 list_move_tail(&reg->lru_list, &dev_priv->mm.fence_list);
2584
2585                 if (obj->tiling_changed) {
2586                         ret = i915_gem_object_flush_fence(obj, pipelined);
2587                         if (ret)
2588                                 return ret;
2589
2590                         if (!obj->fenced_gpu_access && !obj->last_fenced_seqno)
2591                                 pipelined = NULL;
2592
2593                         if (pipelined) {
2594                                 reg->setup_seqno =
2595                                         i915_gem_next_request_seqno(pipelined);
2596                                 obj->last_fenced_seqno = reg->setup_seqno;
2597                                 obj->last_fenced_ring = pipelined;
2598                         }
2599
2600                         goto update;
2601                 }
2602
2603                 if (!pipelined) {
2604                         if (reg->setup_seqno) {
2605                                 if (!ring_passed_seqno(obj->last_fenced_ring,
2606                                                        reg->setup_seqno)) {
2607                                         ret = i915_wait_request(obj->last_fenced_ring,
2608                                                                 reg->setup_seqno);
2609                                         if (ret)
2610                                                 return ret;
2611                                 }
2612
2613                                 reg->setup_seqno = 0;
2614                         }
2615                 } else if (obj->last_fenced_ring &&
2616                            obj->last_fenced_ring != pipelined) {
2617                         ret = i915_gem_object_flush_fence(obj, pipelined);
2618                         if (ret)
2619                                 return ret;
2620                 }
2621
2622                 return 0;
2623         }
2624
2625         reg = i915_find_fence_reg(dev, pipelined);
2626         if (reg == NULL)
2627                 return -ENOSPC;
2628
2629         ret = i915_gem_object_flush_fence(obj, pipelined);
2630         if (ret)
2631                 return ret;
2632
2633         if (reg->obj) {
2634                 struct drm_i915_gem_object *old = reg->obj;
2635
2636                 drm_gem_object_reference(&old->base);
2637
2638                 if (old->tiling_mode)
2639                         i915_gem_release_mmap(old);
2640
2641                 ret = i915_gem_object_flush_fence(old, pipelined);
2642                 if (ret) {
2643                         drm_gem_object_unreference(&old->base);
2644                         return ret;
2645                 }
2646
2647                 if (old->last_fenced_seqno == 0 && obj->last_fenced_seqno == 0)
2648                         pipelined = NULL;
2649
2650                 old->fence_reg = I915_FENCE_REG_NONE;
2651                 old->last_fenced_ring = pipelined;
2652                 old->last_fenced_seqno =
2653                         pipelined ? i915_gem_next_request_seqno(pipelined) : 0;
2654
2655                 drm_gem_object_unreference(&old->base);
2656         } else if (obj->last_fenced_seqno == 0)
2657                 pipelined = NULL;
2658
2659         reg->obj = obj;
2660         list_move_tail(&reg->lru_list, &dev_priv->mm.fence_list);
2661         obj->fence_reg = reg - dev_priv->fence_regs;
2662         obj->last_fenced_ring = pipelined;
2663
2664         reg->setup_seqno =
2665                 pipelined ? i915_gem_next_request_seqno(pipelined) : 0;
2666         obj->last_fenced_seqno = reg->setup_seqno;
2667
2668 update:
2669         obj->tiling_changed = false;
2670         switch (INTEL_INFO(dev)->gen) {
2671         case 7:
2672         case 6:
2673                 ret = sandybridge_write_fence_reg(obj, pipelined);
2674                 break;
2675         case 5:
2676         case 4:
2677                 ret = i965_write_fence_reg(obj, pipelined);
2678                 break;
2679         case 3:
2680                 ret = i915_write_fence_reg(obj, pipelined);
2681                 break;
2682         case 2:
2683                 ret = i830_write_fence_reg(obj, pipelined);
2684                 break;
2685         }
2686
2687         return ret;
2688 }
2689
2690 /**
2691  * i915_gem_clear_fence_reg - clear out fence register info
2692  * @obj: object to clear
2693  *
2694  * Zeroes out the fence register itself and clears out the associated
2695  * data structures in dev_priv and obj.
2696  */
2697 static void
2698 i915_gem_clear_fence_reg(struct drm_device *dev,
2699                          struct drm_i915_fence_reg *reg)
2700 {
2701         drm_i915_private_t *dev_priv = dev->dev_private;
2702         uint32_t fence_reg = reg - dev_priv->fence_regs;
2703
2704         switch (INTEL_INFO(dev)->gen) {
2705         case 7:
2706         case 6:
2707                 I915_WRITE64(FENCE_REG_SANDYBRIDGE_0 + fence_reg*8, 0);
2708                 break;
2709         case 5:
2710         case 4:
2711                 I915_WRITE64(FENCE_REG_965_0 + fence_reg*8, 0);
2712                 break;
2713         case 3:
2714                 if (fence_reg >= 8)
2715                         fence_reg = FENCE_REG_945_8 + (fence_reg - 8) * 4;
2716                 else
2717         case 2:
2718                         fence_reg = FENCE_REG_830_0 + fence_reg * 4;
2719
2720                 I915_WRITE(fence_reg, 0);
2721                 break;
2722         }
2723
2724         list_del_init(&reg->lru_list);
2725         reg->obj = NULL;
2726         reg->setup_seqno = 0;
2727 }
2728
2729 /**
2730  * Finds free space in the GTT aperture and binds the object there.
2731  */
2732 static int
2733 i915_gem_object_bind_to_gtt(struct drm_i915_gem_object *obj,
2734                             unsigned alignment,
2735                             bool map_and_fenceable)
2736 {
2737         struct drm_device *dev = obj->base.dev;
2738         drm_i915_private_t *dev_priv = dev->dev_private;
2739         struct drm_mm_node *free_space;
2740         gfp_t gfpmask = __GFP_NORETRY | __GFP_NOWARN;
2741         u32 size, fence_size, fence_alignment, unfenced_alignment;
2742         bool mappable, fenceable;
2743         int ret;
2744
2745         if (obj->madv != I915_MADV_WILLNEED) {
2746                 DRM_ERROR("Attempting to bind a purgeable object\n");
2747                 return -EINVAL;
2748         }
2749
2750         fence_size = i915_gem_get_gtt_size(obj);
2751         fence_alignment = i915_gem_get_gtt_alignment(obj);
2752         unfenced_alignment = i915_gem_get_unfenced_gtt_alignment(obj);
2753
2754         if (alignment == 0)
2755                 alignment = map_and_fenceable ? fence_alignment :
2756                                                 unfenced_alignment;
2757         if (map_and_fenceable && alignment & (fence_alignment - 1)) {
2758                 DRM_ERROR("Invalid object alignment requested %u\n", alignment);
2759                 return -EINVAL;
2760         }
2761
2762         size = map_and_fenceable ? fence_size : obj->base.size;
2763
2764         /* If the object is bigger than the entire aperture, reject it early
2765          * before evicting everything in a vain attempt to find space.
2766          */
2767         if (obj->base.size >
2768             (map_and_fenceable ? dev_priv->mm.gtt_mappable_end : dev_priv->mm.gtt_total)) {
2769                 DRM_ERROR("Attempting to bind an object larger than the aperture\n");
2770                 return -E2BIG;
2771         }
2772
2773  search_free:
2774         if (map_and_fenceable)
2775                 free_space =
2776                         drm_mm_search_free_in_range(&dev_priv->mm.gtt_space,
2777                                                     size, alignment, 0,
2778                                                     dev_priv->mm.gtt_mappable_end,
2779                                                     0);
2780         else
2781                 free_space = drm_mm_search_free(&dev_priv->mm.gtt_space,
2782                                                 size, alignment, 0);
2783
2784         if (free_space != NULL) {
2785                 if (map_and_fenceable)
2786                         obj->gtt_space =
2787                                 drm_mm_get_block_range_generic(free_space,
2788                                                                size, alignment, 0,
2789                                                                dev_priv->mm.gtt_mappable_end,
2790                                                                0);
2791                 else
2792                         obj->gtt_space =
2793                                 drm_mm_get_block(free_space, size, alignment);
2794         }
2795         if (obj->gtt_space == NULL) {
2796                 /* If the gtt is empty and we're still having trouble
2797                  * fitting our object in, we're out of memory.
2798                  */
2799                 ret = i915_gem_evict_something(dev, size, alignment,
2800                                                map_and_fenceable);
2801                 if (ret)
2802                         return ret;
2803
2804                 goto search_free;
2805         }
2806
2807         ret = i915_gem_object_get_pages_gtt(obj, gfpmask);
2808         if (ret) {
2809                 drm_mm_put_block(obj->gtt_space);
2810                 obj->gtt_space = NULL;
2811
2812                 if (ret == -ENOMEM) {
2813                         /* first try to reclaim some memory by clearing the GTT */
2814                         ret = i915_gem_evict_everything(dev, false);
2815                         if (ret) {
2816                                 /* now try to shrink everyone else */
2817                                 if (gfpmask) {
2818                                         gfpmask = 0;
2819                                         goto search_free;
2820                                 }
2821
2822                                 return -ENOMEM;
2823                         }
2824
2825                         goto search_free;
2826                 }
2827
2828                 return ret;
2829         }
2830
2831         ret = i915_gem_gtt_bind_object(obj);
2832         if (ret) {
2833                 i915_gem_object_put_pages_gtt(obj);
2834                 drm_mm_put_block(obj->gtt_space);
2835                 obj->gtt_space = NULL;
2836
2837                 if (i915_gem_evict_everything(dev, false))
2838                         return ret;
2839
2840                 goto search_free;
2841         }
2842
2843         list_add_tail(&obj->gtt_list, &dev_priv->mm.gtt_list);
2844         list_add_tail(&obj->mm_list, &dev_priv->mm.inactive_list);
2845
2846         /* Assert that the object is not currently in any GPU domain. As it
2847          * wasn't in the GTT, there shouldn't be any way it could have been in
2848          * a GPU cache
2849          */
2850         BUG_ON(obj->base.read_domains & I915_GEM_GPU_DOMAINS);
2851         BUG_ON(obj->base.write_domain & I915_GEM_GPU_DOMAINS);
2852
2853         obj->gtt_offset = obj->gtt_space->start;
2854
2855         fenceable =
2856                 obj->gtt_space->size == fence_size &&
2857                 (obj->gtt_space->start & (fence_alignment -1)) == 0;
2858
2859         mappable =
2860                 obj->gtt_offset + obj->base.size <= dev_priv->mm.gtt_mappable_end;
2861
2862         obj->map_and_fenceable = mappable && fenceable;
2863
2864         trace_i915_gem_object_bind(obj, map_and_fenceable);
2865         return 0;
2866 }
2867
2868 void
2869 i915_gem_clflush_object(struct drm_i915_gem_object *obj)
2870 {
2871         /* If we don't have a page list set up, then we're not pinned
2872          * to GPU, and we can ignore the cache flush because it'll happen
2873          * again at bind time.
2874          */
2875         if (obj->pages == NULL)
2876                 return;
2877
2878         /* If the GPU is snooping the contents of the CPU cache,
2879          * we do not need to manually clear the CPU cache lines.  However,
2880          * the caches are only snooped when the render cache is
2881          * flushed/invalidated.  As we always have to emit invalidations
2882          * and flushes when moving into and out of the RENDER domain, correct
2883          * snooping behaviour occurs naturally as the result of our domain
2884          * tracking.
2885          */
2886         if (obj->cache_level != I915_CACHE_NONE)
2887                 return;
2888
2889         trace_i915_gem_object_clflush(obj);
2890
2891         drm_clflush_pages(obj->pages, obj->base.size / PAGE_SIZE);
2892 }
2893
2894 /** Flushes any GPU write domain for the object if it's dirty. */
2895 static int
2896 i915_gem_object_flush_gpu_write_domain(struct drm_i915_gem_object *obj)
2897 {
2898         if ((obj->base.write_domain & I915_GEM_GPU_DOMAINS) == 0)
2899                 return 0;
2900
2901         /* Queue the GPU write cache flushing we need. */
2902         return i915_gem_flush_ring(obj->ring, 0, obj->base.write_domain);
2903 }
2904
2905 /** Flushes the GTT write domain for the object if it's dirty. */
2906 static void
2907 i915_gem_object_flush_gtt_write_domain(struct drm_i915_gem_object *obj)
2908 {
2909         uint32_t old_write_domain;
2910
2911         if (obj->base.write_domain != I915_GEM_DOMAIN_GTT)
2912                 return;
2913
2914         /* No actual flushing is required for the GTT write domain.  Writes
2915          * to it immediately go to main memory as far as we know, so there's
2916          * no chipset flush.  It also doesn't land in render cache.
2917          *
2918          * However, we do have to enforce the order so that all writes through
2919          * the GTT land before any writes to the device, such as updates to
2920          * the GATT itself.
2921          */
2922         wmb();
2923
2924         old_write_domain = obj->base.write_domain;
2925         obj->base.write_domain = 0;
2926
2927         trace_i915_gem_object_change_domain(obj,
2928                                             obj->base.read_domains,
2929                                             old_write_domain);
2930 }
2931
2932 /** Flushes the CPU write domain for the object if it's dirty. */
2933 static void
2934 i915_gem_object_flush_cpu_write_domain(struct drm_i915_gem_object *obj)
2935 {
2936         uint32_t old_write_domain;
2937
2938         if (obj->base.write_domain != I915_GEM_DOMAIN_CPU)
2939                 return;
2940
2941         i915_gem_clflush_object(obj);
2942         intel_gtt_chipset_flush();
2943         old_write_domain = obj->base.write_domain;
2944         obj->base.write_domain = 0;
2945
2946         trace_i915_gem_object_change_domain(obj,
2947                                             obj->base.read_domains,
2948                                             old_write_domain);
2949 }
2950
2951 /**
2952  * Moves a single object to the GTT read, and possibly write domain.
2953  *
2954  * This function returns when the move is complete, including waiting on
2955  * flushes to occur.
2956  */
2957 int
2958 i915_gem_object_set_to_gtt_domain(struct drm_i915_gem_object *obj, bool write)
2959 {
2960         uint32_t old_write_domain, old_read_domains;
2961         int ret;
2962
2963         /* Not valid to be called on unbound objects. */
2964         if (obj->gtt_space == NULL)
2965                 return -EINVAL;
2966
2967         if (obj->base.write_domain == I915_GEM_DOMAIN_GTT)
2968                 return 0;
2969
2970         ret = i915_gem_object_flush_gpu_write_domain(obj);
2971         if (ret)
2972                 return ret;
2973
2974         if (obj->pending_gpu_write || write) {
2975                 ret = i915_gem_object_wait_rendering(obj);
2976                 if (ret)
2977                         return ret;
2978         }
2979
2980         i915_gem_object_flush_cpu_write_domain(obj);
2981
2982         old_write_domain = obj->base.write_domain;
2983         old_read_domains = obj->base.read_domains;
2984
2985         /* It should now be out of any other write domains, and we can update
2986          * the domain values for our changes.
2987          */
2988         BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_GTT) != 0);
2989         obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
2990         if (write) {
2991                 obj->base.read_domains = I915_GEM_DOMAIN_GTT;
2992                 obj->base.write_domain = I915_GEM_DOMAIN_GTT;
2993                 obj->dirty = 1;
2994         }
2995
2996         trace_i915_gem_object_change_domain(obj,
2997                                             old_read_domains,
2998                                             old_write_domain);
2999
3000         return 0;
3001 }
3002
3003 /*
3004  * Prepare buffer for display plane. Use uninterruptible for possible flush
3005  * wait, as in modesetting process we're not supposed to be interrupted.
3006  */
3007 int
3008 i915_gem_object_set_to_display_plane(struct drm_i915_gem_object *obj,
3009                                      struct intel_ring_buffer *pipelined)
3010 {
3011         uint32_t old_read_domains;
3012         int ret;
3013
3014         /* Not valid to be called on unbound objects. */
3015         if (obj->gtt_space == NULL)
3016                 return -EINVAL;
3017
3018         ret = i915_gem_object_flush_gpu_write_domain(obj);
3019         if (ret)
3020                 return ret;
3021
3022
3023         /* Currently, we are always called from an non-interruptible context. */
3024         if (pipelined != obj->ring) {
3025                 ret = i915_gem_object_wait_rendering(obj);
3026                 if (ret)
3027                         return ret;
3028         }
3029
3030         i915_gem_object_flush_cpu_write_domain(obj);
3031
3032         old_read_domains = obj->base.read_domains;
3033         obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
3034
3035         trace_i915_gem_object_change_domain(obj,
3036                                             old_read_domains,
3037                                             obj->base.write_domain);
3038
3039         return 0;
3040 }
3041
3042 int
3043 i915_gem_object_flush_gpu(struct drm_i915_gem_object *obj)
3044 {
3045         int ret;
3046
3047         if (!obj->active)
3048                 return 0;
3049
3050         if (obj->base.write_domain & I915_GEM_GPU_DOMAINS) {
3051                 ret = i915_gem_flush_ring(obj->ring, 0, obj->base.write_domain);
3052                 if (ret)
3053                         return ret;
3054         }
3055
3056         return i915_gem_object_wait_rendering(obj);
3057 }
3058
3059 /**
3060  * Moves a single object to the CPU read, and possibly write domain.
3061  *
3062  * This function returns when the move is complete, including waiting on
3063  * flushes to occur.
3064  */
3065 static int
3066 i915_gem_object_set_to_cpu_domain(struct drm_i915_gem_object *obj, bool write)
3067 {
3068         uint32_t old_write_domain, old_read_domains;
3069         int ret;
3070
3071         if (obj->base.write_domain == I915_GEM_DOMAIN_CPU)
3072                 return 0;
3073
3074         ret = i915_gem_object_flush_gpu_write_domain(obj);
3075         if (ret)
3076                 return ret;
3077
3078         ret = i915_gem_object_wait_rendering(obj);
3079         if (ret)
3080                 return ret;
3081
3082         i915_gem_object_flush_gtt_write_domain(obj);
3083
3084         /* If we have a partially-valid cache of the object in the CPU,
3085          * finish invalidating it and free the per-page flags.
3086          */
3087         i915_gem_object_set_to_full_cpu_read_domain(obj);
3088
3089         old_write_domain = obj->base.write_domain;
3090         old_read_domains = obj->base.read_domains;
3091
3092         /* Flush the CPU cache if it's still invalid. */
3093         if ((obj->base.read_domains & I915_GEM_DOMAIN_CPU) == 0) {
3094                 i915_gem_clflush_object(obj);
3095
3096                 obj->base.read_domains |= I915_GEM_DOMAIN_CPU;
3097         }
3098
3099         /* It should now be out of any other write domains, and we can update
3100          * the domain values for our changes.
3101          */
3102         BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_CPU) != 0);
3103
3104         /* If we're writing through the CPU, then the GPU read domains will
3105          * need to be invalidated at next use.
3106          */
3107         if (write) {
3108                 obj->base.read_domains = I915_GEM_DOMAIN_CPU;
3109                 obj->base.write_domain = I915_GEM_DOMAIN_CPU;
3110         }
3111
3112         trace_i915_gem_object_change_domain(obj,
3113                                             old_read_domains,
3114                                             old_write_domain);
3115
3116         return 0;
3117 }
3118
3119 /**
3120  * Moves the object from a partially CPU read to a full one.
3121  *
3122  * Note that this only resolves i915_gem_object_set_cpu_read_domain_range(),
3123  * and doesn't handle transitioning from !(read_domains & I915_GEM_DOMAIN_CPU).
3124  */
3125 static void
3126 i915_gem_object_set_to_full_cpu_read_domain(struct drm_i915_gem_object *obj)
3127 {
3128         if (!obj->page_cpu_valid)
3129                 return;
3130
3131         /* If we're partially in the CPU read domain, finish moving it in.
3132          */
3133         if (obj->base.read_domains & I915_GEM_DOMAIN_CPU) {
3134                 int i;
3135
3136                 for (i = 0; i <= (obj->base.size - 1) / PAGE_SIZE; i++) {
3137                         if (obj->page_cpu_valid[i])
3138                                 continue;
3139                         drm_clflush_pages(obj->pages + i, 1);
3140                 }
3141         }
3142
3143         /* Free the page_cpu_valid mappings which are now stale, whether
3144          * or not we've got I915_GEM_DOMAIN_CPU.
3145          */
3146         kfree(obj->page_cpu_valid);
3147         obj->page_cpu_valid = NULL;
3148 }
3149
3150 /**
3151  * Set the CPU read domain on a range of the object.
3152  *
3153  * The object ends up with I915_GEM_DOMAIN_CPU in its read flags although it's
3154  * not entirely valid.  The page_cpu_valid member of the object flags which
3155  * pages have been flushed, and will be respected by
3156  * i915_gem_object_set_to_cpu_domain() if it's called on to get a valid mapping
3157  * of the whole object.
3158  *
3159  * This function returns when the move is complete, including waiting on
3160  * flushes to occur.
3161  */
3162 static int
3163 i915_gem_object_set_cpu_read_domain_range(struct drm_i915_gem_object *obj,
3164                                           uint64_t offset, uint64_t size)
3165 {
3166         uint32_t old_read_domains;
3167         int i, ret;
3168
3169         if (offset == 0 && size == obj->base.size)
3170                 return i915_gem_object_set_to_cpu_domain(obj, 0);
3171
3172         ret = i915_gem_object_flush_gpu_write_domain(obj);
3173         if (ret)
3174                 return ret;
3175
3176         ret = i915_gem_object_wait_rendering(obj);
3177         if (ret)
3178                 return ret;
3179
3180         i915_gem_object_flush_gtt_write_domain(obj);
3181
3182         /* If we're already fully in the CPU read domain, we're done. */
3183         if (obj->page_cpu_valid == NULL &&
3184             (obj->base.read_domains & I915_GEM_DOMAIN_CPU) != 0)
3185                 return 0;
3186
3187         /* Otherwise, create/clear the per-page CPU read domain flag if we're
3188          * newly adding I915_GEM_DOMAIN_CPU
3189          */
3190         if (obj->page_cpu_valid == NULL) {
3191                 obj->page_cpu_valid = kzalloc(obj->base.size / PAGE_SIZE,
3192                                               GFP_KERNEL);
3193                 if (obj->page_cpu_valid == NULL)
3194                         return -ENOMEM;
3195         } else if ((obj->base.read_domains & I915_GEM_DOMAIN_CPU) == 0)
3196                 memset(obj->page_cpu_valid, 0, obj->base.size / PAGE_SIZE);
3197
3198         /* Flush the cache on any pages that are still invalid from the CPU's
3199          * perspective.
3200          */
3201         for (i = offset / PAGE_SIZE; i <= (offset + size - 1) / PAGE_SIZE;
3202              i++) {
3203                 if (obj->page_cpu_valid[i])
3204                         continue;
3205
3206                 drm_clflush_pages(obj->pages + i, 1);
3207
3208                 obj->page_cpu_valid[i] = 1;
3209         }
3210
3211         /* It should now be out of any other write domains, and we can update
3212          * the domain values for our changes.
3213          */
3214         BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_CPU) != 0);
3215
3216         old_read_domains = obj->base.read_domains;
3217         obj->base.read_domains |= I915_GEM_DOMAIN_CPU;
3218
3219         trace_i915_gem_object_change_domain(obj,
3220                                             old_read_domains,
3221                                             obj->base.write_domain);
3222
3223         return 0;
3224 }
3225
3226 /* Throttle our rendering by waiting until the ring has completed our requests
3227  * emitted over 20 msec ago.
3228  *
3229  * Note that if we were to use the current jiffies each time around the loop,
3230  * we wouldn't escape the function with any frames outstanding if the time to
3231  * render a frame was over 20ms.
3232  *
3233  * This should get us reasonable parallelism between CPU and GPU but also
3234  * relatively low latency when blocking on a particular request to finish.
3235  */
3236 static int
3237 i915_gem_ring_throttle(struct drm_device *dev, struct drm_file *file)
3238 {
3239         struct drm_i915_private *dev_priv = dev->dev_private;
3240         struct drm_i915_file_private *file_priv = file->driver_priv;
3241         unsigned long recent_enough = jiffies - msecs_to_jiffies(20);
3242         struct drm_i915_gem_request *request;
3243         struct intel_ring_buffer *ring = NULL;
3244         u32 seqno = 0;
3245         int ret;
3246
3247         if (atomic_read(&dev_priv->mm.wedged))
3248                 return -EIO;
3249
3250         spin_lock(&file_priv->mm.lock);
3251         list_for_each_entry(request, &file_priv->mm.request_list, client_list) {
3252                 if (time_after_eq(request->emitted_jiffies, recent_enough))
3253                         break;
3254
3255                 ring = request->ring;
3256                 seqno = request->seqno;
3257         }
3258         spin_unlock(&file_priv->mm.lock);
3259
3260         if (seqno == 0)
3261                 return 0;
3262
3263         ret = 0;
3264         if (!i915_seqno_passed(ring->get_seqno(ring), seqno)) {
3265                 /* And wait for the seqno passing without holding any locks and
3266                  * causing extra latency for others. This is safe as the irq
3267                  * generation is designed to be run atomically and so is
3268                  * lockless.
3269                  */
3270                 if (ring->irq_get(ring)) {
3271                         ret = wait_event_interruptible(ring->irq_queue,
3272                                                        i915_seqno_passed(ring->get_seqno(ring), seqno)
3273                                                        || atomic_read(&dev_priv->mm.wedged));
3274                         ring->irq_put(ring);
3275
3276                         if (ret == 0 && atomic_read(&dev_priv->mm.wedged))
3277                                 ret = -EIO;
3278                 }
3279         }
3280
3281         if (ret == 0)
3282                 queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work, 0);
3283
3284         return ret;
3285 }
3286
3287 int
3288 i915_gem_object_pin(struct drm_i915_gem_object *obj,
3289                     uint32_t alignment,
3290                     bool map_and_fenceable)
3291 {
3292         struct drm_device *dev = obj->base.dev;
3293         struct drm_i915_private *dev_priv = dev->dev_private;
3294         int ret;
3295
3296         BUG_ON(obj->pin_count == DRM_I915_GEM_OBJECT_MAX_PIN_COUNT);
3297         WARN_ON(i915_verify_lists(dev));
3298
3299         if (obj->gtt_space != NULL) {
3300                 if ((alignment && obj->gtt_offset & (alignment - 1)) ||
3301                     (map_and_fenceable && !obj->map_and_fenceable)) {
3302                         WARN(obj->pin_count,
3303                              "bo is already pinned with incorrect alignment:"
3304                              " offset=%x, req.alignment=%x, req.map_and_fenceable=%d,"
3305                              " obj->map_and_fenceable=%d\n",
3306                              obj->gtt_offset, alignment,
3307                              map_and_fenceable,
3308                              obj->map_and_fenceable);
3309                         ret = i915_gem_object_unbind(obj);
3310                         if (ret)
3311                                 return ret;
3312                 }
3313         }
3314
3315         if (obj->gtt_space == NULL) {
3316                 ret = i915_gem_object_bind_to_gtt(obj, alignment,
3317                                                   map_and_fenceable);
3318                 if (ret)
3319                         return ret;
3320         }
3321
3322         if (obj->pin_count++ == 0) {
3323                 if (!obj->active)
3324                         list_move_tail(&obj->mm_list,
3325                                        &dev_priv->mm.pinned_list);
3326         }
3327         obj->pin_mappable |= map_and_fenceable;
3328
3329         WARN_ON(i915_verify_lists(dev));
3330         return 0;
3331 }
3332
3333 void
3334 i915_gem_object_unpin(struct drm_i915_gem_object *obj)
3335 {
3336         struct drm_device *dev = obj->base.dev;
3337         drm_i915_private_t *dev_priv = dev->dev_private;
3338
3339         WARN_ON(i915_verify_lists(dev));
3340         BUG_ON(obj->pin_count == 0);
3341         BUG_ON(obj->gtt_space == NULL);
3342
3343         if (--obj->pin_count == 0) {
3344                 if (!obj->active)
3345                         list_move_tail(&obj->mm_list,
3346                                        &dev_priv->mm.inactive_list);
3347                 obj->pin_mappable = false;
3348         }
3349         WARN_ON(i915_verify_lists(dev));
3350 }
3351
3352 int
3353 i915_gem_pin_ioctl(struct drm_device *dev, void *data,
3354                    struct drm_file *file)
3355 {
3356         struct drm_i915_gem_pin *args = data;
3357         struct drm_i915_gem_object *obj;
3358         int ret;
3359
3360         ret = i915_mutex_lock_interruptible(dev);
3361         if (ret)
3362                 return ret;
3363
3364         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
3365         if (&obj->base == NULL) {
3366                 ret = -ENOENT;
3367                 goto unlock;
3368         }
3369
3370         if (obj->madv != I915_MADV_WILLNEED) {
3371                 DRM_ERROR("Attempting to pin a purgeable buffer\n");
3372                 ret = -EINVAL;
3373                 goto out;
3374         }
3375
3376         if (obj->pin_filp != NULL && obj->pin_filp != file) {
3377                 DRM_ERROR("Already pinned in i915_gem_pin_ioctl(): %d\n",
3378                           args->handle);
3379                 ret = -EINVAL;
3380                 goto out;
3381         }
3382
3383         obj->user_pin_count++;
3384         obj->pin_filp = file;
3385         if (obj->user_pin_count == 1) {
3386                 ret = i915_gem_object_pin(obj, args->alignment, true);
3387                 if (ret)
3388                         goto out;
3389         }
3390
3391         /* XXX - flush the CPU caches for pinned objects
3392          * as the X server doesn't manage domains yet
3393          */
3394         i915_gem_object_flush_cpu_write_domain(obj);
3395         args->offset = obj->gtt_offset;
3396 out:
3397         drm_gem_object_unreference(&obj->base);
3398 unlock:
3399         mutex_unlock(&dev->struct_mutex);
3400         return ret;
3401 }
3402
3403 int
3404 i915_gem_unpin_ioctl(struct drm_device *dev, void *data,
3405                      struct drm_file *file)
3406 {
3407         struct drm_i915_gem_pin *args = data;
3408         struct drm_i915_gem_object *obj;
3409         int ret;
3410
3411         ret = i915_mutex_lock_interruptible(dev);
3412         if (ret)
3413                 return ret;
3414
3415         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
3416         if (&obj->base == NULL) {
3417                 ret = -ENOENT;
3418                 goto unlock;
3419         }
3420
3421         if (obj->pin_filp != file) {
3422                 DRM_ERROR("Not pinned by caller in i915_gem_pin_ioctl(): %d\n",
3423                           args->handle);
3424                 ret = -EINVAL;
3425                 goto out;
3426         }
3427         obj->user_pin_count--;
3428         if (obj->user_pin_count == 0) {
3429                 obj->pin_filp = NULL;
3430                 i915_gem_object_unpin(obj);
3431         }
3432
3433 out:
3434         drm_gem_object_unreference(&obj->base);
3435 unlock:
3436         mutex_unlock(&dev->struct_mutex);
3437         return ret;
3438 }
3439
3440 int
3441 i915_gem_busy_ioctl(struct drm_device *dev, void *data,
3442                     struct drm_file *file)
3443 {
3444         struct drm_i915_gem_busy *args = data;
3445         struct drm_i915_gem_object *obj;
3446         int ret;
3447
3448         ret = i915_mutex_lock_interruptible(dev);
3449         if (ret)
3450                 return ret;
3451
3452         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
3453         if (&obj->base == NULL) {
3454                 ret = -ENOENT;
3455                 goto unlock;
3456         }
3457
3458         /* Count all active objects as busy, even if they are currently not used
3459          * by the gpu. Users of this interface expect objects to eventually
3460          * become non-busy without any further actions, therefore emit any
3461          * necessary flushes here.
3462          */
3463         args->busy = obj->active;
3464         if (args->busy) {
3465                 /* Unconditionally flush objects, even when the gpu still uses this
3466                  * object. Userspace calling this function indicates that it wants to
3467                  * use this buffer rather sooner than later, so issuing the required
3468                  * flush earlier is beneficial.
3469                  */
3470                 if (obj->base.write_domain & I915_GEM_GPU_DOMAINS) {
3471                         ret = i915_gem_flush_ring(obj->ring,
3472                                                   0, obj->base.write_domain);
3473                 } else if (obj->ring->outstanding_lazy_request ==
3474                            obj->last_rendering_seqno) {
3475                         struct drm_i915_gem_request *request;
3476
3477                         /* This ring is not being cleared by active usage,
3478                          * so emit a request to do so.
3479                          */
3480                         request = kzalloc(sizeof(*request), GFP_KERNEL);
3481                         if (request)
3482                                 ret = i915_add_request(obj->ring, NULL,request);
3483                         else
3484                                 ret = -ENOMEM;
3485                 }
3486
3487                 /* Update the active list for the hardware's current position.
3488                  * Otherwise this only updates on a delayed timer or when irqs
3489                  * are actually unmasked, and our working set ends up being
3490                  * larger than required.
3491                  */
3492                 i915_gem_retire_requests_ring(obj->ring);
3493
3494                 args->busy = obj->active;
3495         }
3496
3497         drm_gem_object_unreference(&obj->base);
3498 unlock:
3499         mutex_unlock(&dev->struct_mutex);
3500         return ret;
3501 }
3502
3503 int
3504 i915_gem_throttle_ioctl(struct drm_device *dev, void *data,
3505                         struct drm_file *file_priv)
3506 {
3507     return i915_gem_ring_throttle(dev, file_priv);
3508 }
3509
3510 int
3511 i915_gem_madvise_ioctl(struct drm_device *dev, void *data,
3512                        struct drm_file *file_priv)
3513 {
3514         struct drm_i915_gem_madvise *args = data;
3515         struct drm_i915_gem_object *obj;
3516         int ret;
3517
3518         switch (args->madv) {
3519         case I915_MADV_DONTNEED:
3520         case I915_MADV_WILLNEED:
3521             break;
3522         default:
3523             return -EINVAL;
3524         }
3525
3526         ret = i915_mutex_lock_interruptible(dev);
3527         if (ret)
3528                 return ret;
3529
3530         obj = to_intel_bo(drm_gem_object_lookup(dev, file_priv, args->handle));
3531         if (&obj->base == NULL) {
3532                 ret = -ENOENT;
3533                 goto unlock;
3534         }
3535
3536         if (obj->pin_count) {
3537                 ret = -EINVAL;
3538                 goto out;
3539         }
3540
3541         if (obj->madv != __I915_MADV_PURGED)
3542                 obj->madv = args->madv;
3543
3544         /* if the object is no longer bound, discard its backing storage */
3545         if (i915_gem_object_is_purgeable(obj) &&
3546             obj->gtt_space == NULL)
3547                 i915_gem_object_truncate(obj);
3548
3549         args->retained = obj->madv != __I915_MADV_PURGED;
3550
3551 out:
3552         drm_gem_object_unreference(&obj->base);
3553 unlock:
3554         mutex_unlock(&dev->struct_mutex);
3555         return ret;
3556 }
3557
3558 struct drm_i915_gem_object *i915_gem_alloc_object(struct drm_device *dev,
3559                                                   size_t size)
3560 {
3561         struct drm_i915_private *dev_priv = dev->dev_private;
3562         struct drm_i915_gem_object *obj;
3563         struct address_space *mapping;
3564
3565         obj = kzalloc(sizeof(*obj), GFP_KERNEL);
3566         if (obj == NULL)
3567                 return NULL;
3568
3569         if (drm_gem_object_init(dev, &obj->base, size) != 0) {
3570                 kfree(obj);
3571                 return NULL;
3572         }
3573
3574         mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
3575         mapping_set_gfp_mask(mapping, GFP_HIGHUSER | __GFP_RECLAIMABLE);
3576
3577         i915_gem_info_add_obj(dev_priv, size);
3578
3579         obj->base.write_domain = I915_GEM_DOMAIN_CPU;
3580         obj->base.read_domains = I915_GEM_DOMAIN_CPU;
3581
3582         obj->cache_level = I915_CACHE_NONE;
3583         obj->base.driver_private = NULL;
3584         obj->fence_reg = I915_FENCE_REG_NONE;
3585         INIT_LIST_HEAD(&obj->mm_list);
3586         INIT_LIST_HEAD(&obj->gtt_list);
3587         INIT_LIST_HEAD(&obj->ring_list);
3588         INIT_LIST_HEAD(&obj->exec_list);
3589         INIT_LIST_HEAD(&obj->gpu_write_list);
3590         obj->madv = I915_MADV_WILLNEED;
3591         /* Avoid an unnecessary call to unbind on the first bind. */
3592         obj->map_and_fenceable = true;
3593
3594         return obj;
3595 }
3596
3597 int i915_gem_init_object(struct drm_gem_object *obj)
3598 {
3599         BUG();
3600
3601         return 0;
3602 }
3603
3604 static void i915_gem_free_object_tail(struct drm_i915_gem_object *obj)
3605 {
3606         struct drm_device *dev = obj->base.dev;
3607         drm_i915_private_t *dev_priv = dev->dev_private;
3608         int ret;
3609
3610         ret = i915_gem_object_unbind(obj);
3611         if (ret == -ERESTARTSYS) {
3612                 list_move(&obj->mm_list,
3613                           &dev_priv->mm.deferred_free_list);
3614                 return;
3615         }
3616
3617         trace_i915_gem_object_destroy(obj);
3618
3619         if (obj->base.map_list.map)
3620                 i915_gem_free_mmap_offset(obj);
3621
3622         drm_gem_object_release(&obj->base);
3623         i915_gem_info_remove_obj(dev_priv, obj->base.size);
3624
3625         kfree(obj->page_cpu_valid);
3626         kfree(obj->bit_17);
3627         kfree(obj);
3628 }
3629
3630 void i915_gem_free_object(struct drm_gem_object *gem_obj)
3631 {
3632         struct drm_i915_gem_object *obj = to_intel_bo(gem_obj);
3633         struct drm_device *dev = obj->base.dev;
3634
3635         while (obj->pin_count > 0)
3636                 i915_gem_object_unpin(obj);
3637
3638         if (obj->phys_obj)
3639                 i915_gem_detach_phys_object(dev, obj);
3640
3641         i915_gem_free_object_tail(obj);
3642 }
3643
3644 int
3645 i915_gem_idle(struct drm_device *dev)
3646 {
3647         drm_i915_private_t *dev_priv = dev->dev_private;
3648         int ret;
3649
3650         mutex_lock(&dev->struct_mutex);
3651
3652         if (dev_priv->mm.suspended) {
3653                 mutex_unlock(&dev->struct_mutex);
3654                 return 0;
3655         }
3656
3657         ret = i915_gpu_idle(dev);
3658         if (ret) {
3659                 mutex_unlock(&dev->struct_mutex);
3660                 return ret;
3661         }
3662
3663         /* Under UMS, be paranoid and evict. */
3664         if (!drm_core_check_feature(dev, DRIVER_MODESET)) {
3665                 ret = i915_gem_evict_inactive(dev, false);
3666                 if (ret) {
3667                         mutex_unlock(&dev->struct_mutex);
3668                         return ret;
3669                 }
3670         }
3671
3672         i915_gem_reset_fences(dev);
3673
3674         /* Hack!  Don't let anybody do execbuf while we don't control the chip.
3675          * We need to replace this with a semaphore, or something.
3676          * And not confound mm.suspended!
3677          */
3678         dev_priv->mm.suspended = 1;
3679         del_timer_sync(&dev_priv->hangcheck_timer);
3680
3681         i915_kernel_lost_context(dev);
3682         i915_gem_cleanup_ringbuffer(dev);
3683
3684         mutex_unlock(&dev->struct_mutex);
3685
3686         /* Cancel the retire work handler, which should be idle now. */
3687         cancel_delayed_work_sync(&dev_priv->mm.retire_work);
3688
3689         return 0;
3690 }
3691
3692 int
3693 i915_gem_init_ringbuffer(struct drm_device *dev)
3694 {
3695         drm_i915_private_t *dev_priv = dev->dev_private;
3696         int ret;
3697
3698         ret = intel_init_render_ring_buffer(dev);
3699         if (ret)
3700                 return ret;
3701
3702         if (HAS_BSD(dev)) {
3703                 ret = intel_init_bsd_ring_buffer(dev);
3704                 if (ret)
3705                         goto cleanup_render_ring;
3706         }
3707
3708         if (HAS_BLT(dev)) {
3709                 ret = intel_init_blt_ring_buffer(dev);
3710                 if (ret)
3711                         goto cleanup_bsd_ring;
3712         }
3713
3714         dev_priv->next_seqno = 1;
3715
3716         return 0;
3717
3718 cleanup_bsd_ring:
3719         intel_cleanup_ring_buffer(&dev_priv->ring[VCS]);
3720 cleanup_render_ring:
3721         intel_cleanup_ring_buffer(&dev_priv->ring[RCS]);
3722         return ret;
3723 }
3724
3725 void
3726 i915_gem_cleanup_ringbuffer(struct drm_device *dev)
3727 {
3728         drm_i915_private_t *dev_priv = dev->dev_private;
3729         int i;
3730
3731         for (i = 0; i < I915_NUM_RINGS; i++)
3732                 intel_cleanup_ring_buffer(&dev_priv->ring[i]);
3733 }
3734
3735 int
3736 i915_gem_entervt_ioctl(struct drm_device *dev, void *data,
3737                        struct drm_file *file_priv)
3738 {
3739         drm_i915_private_t *dev_priv = dev->dev_private;
3740         int ret, i;
3741
3742         if (drm_core_check_feature(dev, DRIVER_MODESET))
3743                 return 0;
3744
3745         if (atomic_read(&dev_priv->mm.wedged)) {
3746                 DRM_ERROR("Reenabling wedged hardware, good luck\n");
3747                 atomic_set(&dev_priv->mm.wedged, 0);
3748         }
3749
3750         mutex_lock(&dev->struct_mutex);
3751         dev_priv->mm.suspended = 0;
3752
3753         ret = i915_gem_init_ringbuffer(dev);
3754         if (ret != 0) {
3755                 mutex_unlock(&dev->struct_mutex);
3756                 return ret;
3757         }
3758
3759         BUG_ON(!list_empty(&dev_priv->mm.active_list));
3760         BUG_ON(!list_empty(&dev_priv->mm.flushing_list));
3761         BUG_ON(!list_empty(&dev_priv->mm.inactive_list));
3762         for (i = 0; i < I915_NUM_RINGS; i++) {
3763                 BUG_ON(!list_empty(&dev_priv->ring[i].active_list));
3764                 BUG_ON(!list_empty(&dev_priv->ring[i].request_list));
3765         }
3766         mutex_unlock(&dev->struct_mutex);
3767
3768         ret = drm_irq_install(dev);
3769         if (ret)
3770                 goto cleanup_ringbuffer;
3771
3772         return 0;
3773
3774 cleanup_ringbuffer:
3775         mutex_lock(&dev->struct_mutex);
3776         i915_gem_cleanup_ringbuffer(dev);
3777         dev_priv->mm.suspended = 1;
3778         mutex_unlock(&dev->struct_mutex);
3779
3780         return ret;
3781 }
3782
3783 int
3784 i915_gem_leavevt_ioctl(struct drm_device *dev, void *data,
3785                        struct drm_file *file_priv)
3786 {
3787         if (drm_core_check_feature(dev, DRIVER_MODESET))
3788                 return 0;
3789
3790         drm_irq_uninstall(dev);
3791         return i915_gem_idle(dev);
3792 }
3793
3794 void
3795 i915_gem_lastclose(struct drm_device *dev)
3796 {
3797         int ret;
3798
3799         if (drm_core_check_feature(dev, DRIVER_MODESET))
3800                 return;
3801
3802         ret = i915_gem_idle(dev);
3803         if (ret)
3804                 DRM_ERROR("failed to idle hardware: %d\n", ret);
3805 }
3806
3807 static void
3808 init_ring_lists(struct intel_ring_buffer *ring)
3809 {
3810         INIT_LIST_HEAD(&ring->active_list);
3811         INIT_LIST_HEAD(&ring->request_list);
3812         INIT_LIST_HEAD(&ring->gpu_write_list);
3813 }
3814
3815 void
3816 i915_gem_load(struct drm_device *dev)
3817 {
3818         int i;
3819         drm_i915_private_t *dev_priv = dev->dev_private;
3820
3821         INIT_LIST_HEAD(&dev_priv->mm.active_list);
3822         INIT_LIST_HEAD(&dev_priv->mm.flushing_list);
3823         INIT_LIST_HEAD(&dev_priv->mm.inactive_list);
3824         INIT_LIST_HEAD(&dev_priv->mm.pinned_list);
3825         INIT_LIST_HEAD(&dev_priv->mm.fence_list);
3826         INIT_LIST_HEAD(&dev_priv->mm.deferred_free_list);
3827         INIT_LIST_HEAD(&dev_priv->mm.gtt_list);
3828         for (i = 0; i < I915_NUM_RINGS; i++)
3829                 init_ring_lists(&dev_priv->ring[i]);
3830         for (i = 0; i < 16; i++)
3831                 INIT_LIST_HEAD(&dev_priv->fence_regs[i].lru_list);
3832         INIT_DELAYED_WORK(&dev_priv->mm.retire_work,
3833                           i915_gem_retire_work_handler);
3834         init_completion(&dev_priv->error_completion);
3835
3836         /* On GEN3 we really need to make sure the ARB C3 LP bit is set */
3837         if (IS_GEN3(dev)) {
3838                 u32 tmp = I915_READ(MI_ARB_STATE);
3839                 if (!(tmp & MI_ARB_C3_LP_WRITE_ENABLE)) {
3840                         /* arb state is a masked write, so set bit + bit in mask */
3841                         tmp = MI_ARB_C3_LP_WRITE_ENABLE | (MI_ARB_C3_LP_WRITE_ENABLE << MI_ARB_MASK_SHIFT);
3842                         I915_WRITE(MI_ARB_STATE, tmp);
3843                 }
3844         }
3845
3846         dev_priv->relative_constants_mode = I915_EXEC_CONSTANTS_REL_GENERAL;
3847
3848         /* Old X drivers will take 0-2 for front, back, depth buffers */
3849         if (!drm_core_check_feature(dev, DRIVER_MODESET))
3850                 dev_priv->fence_reg_start = 3;
3851
3852         if (INTEL_INFO(dev)->gen >= 4 || IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev))
3853                 dev_priv->num_fence_regs = 16;
3854         else
3855                 dev_priv->num_fence_regs = 8;
3856
3857         /* Initialize fence registers to zero */
3858         for (i = 0; i < dev_priv->num_fence_regs; i++) {
3859                 i915_gem_clear_fence_reg(dev, &dev_priv->fence_regs[i]);
3860         }
3861
3862         i915_gem_detect_bit_6_swizzle(dev);
3863         init_waitqueue_head(&dev_priv->pending_flip_queue);
3864
3865         dev_priv->mm.interruptible = true;
3866
3867         dev_priv->mm.inactive_shrinker.shrink = i915_gem_inactive_shrink;
3868         dev_priv->mm.inactive_shrinker.seeks = DEFAULT_SEEKS;
3869         register_shrinker(&dev_priv->mm.inactive_shrinker);
3870 }
3871
3872 /*
3873  * Create a physically contiguous memory object for this object
3874  * e.g. for cursor + overlay regs
3875  */
3876 static int i915_gem_init_phys_object(struct drm_device *dev,
3877                                      int id, int size, int align)
3878 {
3879         drm_i915_private_t *dev_priv = dev->dev_private;
3880         struct drm_i915_gem_phys_object *phys_obj;
3881         int ret;
3882
3883         if (dev_priv->mm.phys_objs[id - 1] || !size)
3884                 return 0;
3885
3886         phys_obj = kzalloc(sizeof(struct drm_i915_gem_phys_object), GFP_KERNEL);
3887         if (!phys_obj)
3888                 return -ENOMEM;
3889
3890         phys_obj->id = id;
3891
3892         phys_obj->handle = drm_pci_alloc(dev, size, align);
3893         if (!phys_obj->handle) {
3894                 ret = -ENOMEM;
3895                 goto kfree_obj;
3896         }
3897 #ifdef CONFIG_X86
3898         set_memory_wc((unsigned long)phys_obj->handle->vaddr, phys_obj->handle->size / PAGE_SIZE);
3899 #endif
3900
3901         dev_priv->mm.phys_objs[id - 1] = phys_obj;
3902
3903         return 0;
3904 kfree_obj:
3905         kfree(phys_obj);
3906         return ret;
3907 }
3908
3909 static void i915_gem_free_phys_object(struct drm_device *dev, int id)
3910 {
3911         drm_i915_private_t *dev_priv = dev->dev_private;
3912         struct drm_i915_gem_phys_object *phys_obj;
3913
3914         if (!dev_priv->mm.phys_objs[id - 1])
3915                 return;
3916
3917         phys_obj = dev_priv->mm.phys_objs[id - 1];
3918         if (phys_obj->cur_obj) {
3919                 i915_gem_detach_phys_object(dev, phys_obj->cur_obj);
3920         }
3921
3922 #ifdef CONFIG_X86
3923         set_memory_wb((unsigned long)phys_obj->handle->vaddr, phys_obj->handle->size / PAGE_SIZE);
3924 #endif
3925         drm_pci_free(dev, phys_obj->handle);
3926         kfree(phys_obj);
3927         dev_priv->mm.phys_objs[id - 1] = NULL;
3928 }
3929
3930 void i915_gem_free_all_phys_object(struct drm_device *dev)
3931 {
3932         int i;
3933
3934         for (i = I915_GEM_PHYS_CURSOR_0; i <= I915_MAX_PHYS_OBJECT; i++)
3935                 i915_gem_free_phys_object(dev, i);
3936 }
3937
3938 void i915_gem_detach_phys_object(struct drm_device *dev,
3939                                  struct drm_i915_gem_object *obj)
3940 {
3941         struct address_space *mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
3942         char *vaddr;
3943         int i;
3944         int page_count;
3945
3946         if (!obj->phys_obj)
3947                 return;
3948         vaddr = obj->phys_obj->handle->vaddr;
3949
3950         page_count = obj->base.size / PAGE_SIZE;
3951         for (i = 0; i < page_count; i++) {
3952                 struct page *page = shmem_read_mapping_page(mapping, i);
3953                 if (!IS_ERR(page)) {
3954                         char *dst = kmap_atomic(page);
3955                         memcpy(dst, vaddr + i*PAGE_SIZE, PAGE_SIZE);
3956                         kunmap_atomic(dst);
3957
3958                         drm_clflush_pages(&page, 1);
3959
3960                         set_page_dirty(page);
3961                         mark_page_accessed(page);
3962                         page_cache_release(page);
3963                 }
3964         }
3965         intel_gtt_chipset_flush();
3966
3967         obj->phys_obj->cur_obj = NULL;
3968         obj->phys_obj = NULL;
3969 }
3970
3971 int
3972 i915_gem_attach_phys_object(struct drm_device *dev,
3973                             struct drm_i915_gem_object *obj,
3974                             int id,
3975                             int align)
3976 {
3977         struct address_space *mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
3978         drm_i915_private_t *dev_priv = dev->dev_private;
3979         int ret = 0;
3980         int page_count;
3981         int i;
3982
3983         if (id > I915_MAX_PHYS_OBJECT)
3984                 return -EINVAL;
3985
3986         if (obj->phys_obj) {
3987                 if (obj->phys_obj->id == id)
3988                         return 0;
3989                 i915_gem_detach_phys_object(dev, obj);
3990         }
3991
3992         /* create a new object */
3993         if (!dev_priv->mm.phys_objs[id - 1]) {
3994                 ret = i915_gem_init_phys_object(dev, id,
3995                                                 obj->base.size, align);
3996                 if (ret) {
3997                         DRM_ERROR("failed to init phys object %d size: %zu\n",
3998                                   id, obj->base.size);
3999                         return ret;
4000                 }
4001         }
4002
4003         /* bind to the object */
4004         obj->phys_obj = dev_priv->mm.phys_objs[id - 1];
4005         obj->phys_obj->cur_obj = obj;
4006
4007         page_count = obj->base.size / PAGE_SIZE;
4008
4009         for (i = 0; i < page_count; i++) {
4010                 struct page *page;
4011                 char *dst, *src;
4012
4013                 page = shmem_read_mapping_page(mapping, i);
4014                 if (IS_ERR(page))
4015                         return PTR_ERR(page);
4016
4017                 src = kmap_atomic(page);
4018                 dst = obj->phys_obj->handle->vaddr + (i * PAGE_SIZE);
4019                 memcpy(dst, src, PAGE_SIZE);
4020                 kunmap_atomic(src);
4021
4022                 mark_page_accessed(page);
4023                 page_cache_release(page);
4024         }
4025
4026         return 0;
4027 }
4028
4029 static int
4030 i915_gem_phys_pwrite(struct drm_device *dev,
4031                      struct drm_i915_gem_object *obj,
4032                      struct drm_i915_gem_pwrite *args,
4033                      struct drm_file *file_priv)
4034 {
4035         void *vaddr = obj->phys_obj->handle->vaddr + args->offset;
4036         char __user *user_data = (char __user *) (uintptr_t) args->data_ptr;
4037
4038         if (__copy_from_user_inatomic_nocache(vaddr, user_data, args->size)) {
4039                 unsigned long unwritten;
4040
4041                 /* The physical object once assigned is fixed for the lifetime
4042                  * of the obj, so we can safely drop the lock and continue
4043                  * to access vaddr.
4044                  */
4045                 mutex_unlock(&dev->struct_mutex);
4046                 unwritten = copy_from_user(vaddr, user_data, args->size);
4047                 mutex_lock(&dev->struct_mutex);
4048                 if (unwritten)
4049                         return -EFAULT;
4050         }
4051
4052         intel_gtt_chipset_flush();
4053         return 0;
4054 }
4055
4056 void i915_gem_release(struct drm_device *dev, struct drm_file *file)
4057 {
4058         struct drm_i915_file_private *file_priv = file->driver_priv;
4059
4060         /* Clean up our request list when the client is going away, so that
4061          * later retire_requests won't dereference our soon-to-be-gone
4062          * file_priv.
4063          */
4064         spin_lock(&file_priv->mm.lock);
4065         while (!list_empty(&file_priv->mm.request_list)) {
4066                 struct drm_i915_gem_request *request;
4067
4068                 request = list_first_entry(&file_priv->mm.request_list,
4069                                            struct drm_i915_gem_request,
4070                                            client_list);
4071                 list_del(&request->client_list);
4072                 request->file_priv = NULL;
4073         }
4074         spin_unlock(&file_priv->mm.lock);
4075 }
4076
4077 static int
4078 i915_gpu_is_active(struct drm_device *dev)
4079 {
4080         drm_i915_private_t *dev_priv = dev->dev_private;
4081         int lists_empty;
4082
4083         lists_empty = list_empty(&dev_priv->mm.flushing_list) &&
4084                       list_empty(&dev_priv->mm.active_list);
4085
4086         return !lists_empty;
4087 }
4088
4089 static int
4090 i915_gem_inactive_shrink(struct shrinker *shrinker, struct shrink_control *sc)
4091 {
4092         struct drm_i915_private *dev_priv =
4093                 container_of(shrinker,
4094                              struct drm_i915_private,
4095                              mm.inactive_shrinker);
4096         struct drm_device *dev = dev_priv->dev;
4097         struct drm_i915_gem_object *obj, *next;
4098         int nr_to_scan = sc->nr_to_scan;
4099         int cnt;
4100
4101         if (!mutex_trylock(&dev->struct_mutex))
4102                 return 0;
4103
4104         /* "fast-path" to count number of available objects */
4105         if (nr_to_scan == 0) {
4106                 cnt = 0;
4107                 list_for_each_entry(obj,
4108                                     &dev_priv->mm.inactive_list,
4109                                     mm_list)
4110                         cnt++;
4111                 mutex_unlock(&dev->struct_mutex);
4112                 return cnt / 100 * sysctl_vfs_cache_pressure;
4113         }
4114
4115 rescan:
4116         /* first scan for clean buffers */
4117         i915_gem_retire_requests(dev);
4118
4119         list_for_each_entry_safe(obj, next,
4120                                  &dev_priv->mm.inactive_list,
4121                                  mm_list) {
4122                 if (i915_gem_object_is_purgeable(obj)) {
4123                         if (i915_gem_object_unbind(obj) == 0 &&
4124                             --nr_to_scan == 0)
4125                                 break;
4126                 }
4127         }
4128
4129         /* second pass, evict/count anything still on the inactive list */
4130         cnt = 0;
4131         list_for_each_entry_safe(obj, next,
4132                                  &dev_priv->mm.inactive_list,
4133                                  mm_list) {
4134                 if (nr_to_scan &&
4135                     i915_gem_object_unbind(obj) == 0)
4136                         nr_to_scan--;
4137                 else
4138                         cnt++;
4139         }
4140
4141         if (nr_to_scan && i915_gpu_is_active(dev)) {
4142                 /*
4143                  * We are desperate for pages, so as a last resort, wait
4144                  * for the GPU to finish and discard whatever we can.
4145                  * This has a dramatic impact to reduce the number of
4146                  * OOM-killer events whilst running the GPU aggressively.
4147                  */
4148                 if (i915_gpu_idle(dev) == 0)
4149                         goto rescan;
4150         }
4151         mutex_unlock(&dev->struct_mutex);
4152         return cnt / 100 * sysctl_vfs_cache_pressure;
4153 }