drm/i915: Sync i915_gem_shmem_pread() with Linux 3.11
[dragonfly.git] / sys / dev / 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  * Copyright (c) 2011 The FreeBSD Foundation
27  * All rights reserved.
28  *
29  * This software was developed by Konstantin Belousov under sponsorship from
30  * the FreeBSD Foundation.
31  *
32  * Redistribution and use in source and binary forms, with or without
33  * modification, are permitted provided that the following conditions
34  * are met:
35  * 1. Redistributions of source code must retain the above copyright
36  *    notice, this list of conditions and the following disclaimer.
37  * 2. Redistributions in binary form must reproduce the above copyright
38  *    notice, this list of conditions and the following disclaimer in the
39  *    documentation and/or other materials provided with the distribution.
40  *
41  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  *
53  */
54
55 #include <sys/resourcevar.h>
56 #include <sys/sfbuf.h>
57 #include <machine/md_var.h>
58
59 #include <drm/drmP.h>
60 #include <drm/i915_drm.h>
61 #include "i915_drv.h"
62 #include "i915_trace.h"
63 #include "intel_drv.h"
64 #include <linux/shmem_fs.h>
65 #include <linux/slab.h>
66 #include <linux/swap.h>
67 #include <linux/pci.h>
68
69 static void i915_gem_object_flush_gtt_write_domain(struct drm_i915_gem_object *obj);
70 static void i915_gem_object_flush_cpu_write_domain(struct drm_i915_gem_object *obj);
71 static __must_check int i915_gem_object_bind_to_gtt(struct drm_i915_gem_object *obj,
72                                                     unsigned alignment,
73                                                     bool map_and_fenceable,
74                                                     bool nonblocking);
75 static int i915_gem_phys_pwrite(struct drm_device *dev,
76                                 struct drm_i915_gem_object *obj,
77                                 struct drm_i915_gem_pwrite *args,
78                                 struct drm_file *file);
79
80 static void i915_gem_write_fence(struct drm_device *dev, int reg,
81                                  struct drm_i915_gem_object *obj);
82 static void i915_gem_object_update_fence(struct drm_i915_gem_object *obj,
83                                          struct drm_i915_fence_reg *fence,
84                                          bool enable);
85
86 static long i915_gem_purge(struct drm_i915_private *dev_priv, long target);
87 static void i915_gem_object_truncate(struct drm_i915_gem_object *obj);
88
89 static inline void i915_gem_object_fence_lost(struct drm_i915_gem_object *obj)
90 {
91         if (obj->tiling_mode)
92                 i915_gem_release_mmap(obj);
93
94         /* As we do not have an associated fence register, we will force
95          * a tiling change if we ever need to acquire one.
96          */
97         obj->fence_dirty = false;
98         obj->fence_reg = I915_FENCE_REG_NONE;
99 }
100
101 static bool i915_gem_object_is_inactive(struct drm_i915_gem_object *obj);
102 static void i915_gem_lowmem(void *arg);
103
104 /* some bookkeeping */
105 static void i915_gem_info_add_obj(struct drm_i915_private *dev_priv,
106                                   size_t size)
107 {
108         dev_priv->mm.object_count++;
109         dev_priv->mm.object_memory += size;
110 }
111
112 static void i915_gem_info_remove_obj(struct drm_i915_private *dev_priv,
113                                      size_t size)
114 {
115         dev_priv->mm.object_count--;
116         dev_priv->mm.object_memory -= size;
117 }
118
119 static int
120 i915_gem_wait_for_error(struct i915_gpu_error *error)
121 {
122         int ret;
123
124 #define EXIT_COND (!i915_reset_in_progress(error) || \
125                    i915_terminally_wedged(error))
126         if (EXIT_COND)
127                 return 0;
128
129         /*
130          * Only wait 10 seconds for the gpu reset to complete to avoid hanging
131          * userspace. If it takes that long something really bad is going on and
132          * we should simply try to bail out and fail as gracefully as possible.
133          */
134         ret = wait_event_interruptible_timeout(error->reset_queue,
135                                                EXIT_COND,
136                                                10*HZ);
137         if (ret == 0) {
138                 DRM_ERROR("Timed out waiting for the gpu reset to complete\n");
139                 return -EIO;
140         } else if (ret < 0) {
141                 return ret;
142         }
143 #undef EXIT_COND
144
145         return 0;
146 }
147
148 int i915_mutex_lock_interruptible(struct drm_device *dev)
149 {
150         struct drm_i915_private *dev_priv = dev->dev_private;
151         int ret;
152
153         ret = i915_gem_wait_for_error(&dev_priv->gpu_error);
154         if (ret)
155                 return ret;
156
157         ret = lockmgr(&dev->struct_mutex, LK_EXCLUSIVE|LK_SLEEPFAIL);
158         if (ret)
159                 return -EINTR;
160
161         WARN_ON(i915_verify_lists(dev));
162         return 0;
163 }
164
165 static inline bool
166 i915_gem_object_is_inactive(struct drm_i915_gem_object *obj)
167 {
168         return !obj->active;
169 }
170
171 int
172 i915_gem_init_ioctl(struct drm_device *dev, void *data,
173                     struct drm_file *file)
174 {
175         struct drm_i915_private *dev_priv = dev->dev_private;
176         struct drm_i915_gem_init *args = data;
177
178         if (drm_core_check_feature(dev, DRIVER_MODESET))
179                 return -ENODEV;
180
181         if (args->gtt_start >= args->gtt_end ||
182             (args->gtt_end | args->gtt_start) & (PAGE_SIZE - 1))
183                 return -EINVAL;
184
185         /* GEM with user mode setting was never supported on ilk and later. */
186         if (INTEL_INFO(dev)->gen >= 5)
187                 return -ENODEV;
188
189         mutex_lock(&dev->struct_mutex);
190         i915_gem_setup_global_gtt(dev, args->gtt_start, args->gtt_end,
191                                   args->gtt_end);
192         dev_priv->gtt.mappable_end = args->gtt_end;
193         mutex_unlock(&dev->struct_mutex);
194
195         return 0;
196 }
197
198 int
199 i915_gem_get_aperture_ioctl(struct drm_device *dev, void *data,
200                             struct drm_file *file)
201 {
202         struct drm_i915_private *dev_priv = dev->dev_private;
203         struct drm_i915_gem_get_aperture *args = data;
204         struct drm_i915_gem_object *obj;
205         size_t pinned;
206
207         pinned = 0;
208         mutex_lock(&dev->struct_mutex);
209         list_for_each_entry(obj, &dev_priv->mm.bound_list, global_list)
210                 if (obj->pin_count)
211                         pinned += obj->gtt_space->size;
212         mutex_unlock(&dev->struct_mutex);
213
214         args->aper_size = dev_priv->gtt.total;
215         args->aper_available_size = args->aper_size - pinned;
216
217         return 0;
218 }
219
220 void i915_gem_object_free(struct drm_i915_gem_object *obj)
221 {
222         kfree(obj);
223 }
224
225 static int
226 i915_gem_create(struct drm_file *file,
227                 struct drm_device *dev,
228                 uint64_t size,
229                 uint32_t *handle_p)
230 {
231         struct drm_i915_gem_object *obj;
232         int ret;
233         u32 handle;
234
235         size = roundup(size, PAGE_SIZE);
236         if (size == 0)
237                 return -EINVAL;
238
239         /* Allocate the new object */
240         obj = i915_gem_alloc_object(dev, size);
241         if (obj == NULL)
242                 return -ENOMEM;
243
244         ret = drm_gem_handle_create(file, &obj->base, &handle);
245         if (ret) {
246                 drm_gem_object_release(&obj->base);
247                 i915_gem_info_remove_obj(dev->dev_private, obj->base.size);
248                 i915_gem_object_free(obj);
249                 return ret;
250         }
251
252         /* drop reference from allocate - handle holds it now */
253         drm_gem_object_unreference(&obj->base);
254         trace_i915_gem_object_create(obj);
255
256         *handle_p = handle;
257         return 0;
258 }
259
260 int
261 i915_gem_dumb_create(struct drm_file *file,
262                      struct drm_device *dev,
263                      struct drm_mode_create_dumb *args)
264 {
265
266         /* have to work out size/pitch and return them */
267         args->pitch = ALIGN(args->width * ((args->bpp + 7) / 8), 64);
268         args->size = args->pitch * args->height;
269         return i915_gem_create(file, dev,
270                                args->size, &args->handle);
271 }
272
273 int i915_gem_dumb_destroy(struct drm_file *file,
274                           struct drm_device *dev,
275                           uint32_t handle)
276 {
277
278         return drm_gem_handle_delete(file, handle);
279 }
280
281 /**
282  * Creates a new mm object and returns a handle to it.
283  */
284 int
285 i915_gem_create_ioctl(struct drm_device *dev, void *data,
286                       struct drm_file *file)
287 {
288         struct drm_i915_gem_create *args = data;
289
290         return i915_gem_create(file, dev,
291                                args->size, &args->handle);
292 }
293
294 static inline int
295 __copy_to_user_swizzled(char __user *cpu_vaddr,
296                         const char *gpu_vaddr, int gpu_offset,
297                         int length)
298 {
299         int ret, cpu_offset = 0;
300
301         while (length > 0) {
302                 int cacheline_end = ALIGN(gpu_offset + 1, 64);
303                 int this_length = min(cacheline_end - gpu_offset, length);
304                 int swizzled_gpu_offset = gpu_offset ^ 64;
305
306                 ret = __copy_to_user(cpu_vaddr + cpu_offset,
307                                      gpu_vaddr + swizzled_gpu_offset,
308                                      this_length);
309                 if (ret)
310                         return ret + length;
311
312                 cpu_offset += this_length;
313                 gpu_offset += this_length;
314                 length -= this_length;
315         }
316
317         return 0;
318 }
319
320 static inline int
321 __copy_from_user_swizzled(char *gpu_vaddr, int gpu_offset,
322                           const char __user *cpu_vaddr,
323                           int length)
324 {
325         int ret, cpu_offset = 0;
326
327         while (length > 0) {
328                 int cacheline_end = ALIGN(gpu_offset + 1, 64);
329                 int this_length = min(cacheline_end - gpu_offset, length);
330                 int swizzled_gpu_offset = gpu_offset ^ 64;
331
332                 ret = __copy_from_user(gpu_vaddr + swizzled_gpu_offset,
333                                        cpu_vaddr + cpu_offset,
334                                        this_length);
335                 if (ret)
336                         return ret + length;
337
338                 cpu_offset += this_length;
339                 gpu_offset += this_length;
340                 length -= this_length;
341         }
342
343         return 0;
344 }
345
346 /* Per-page copy function for the shmem pread fastpath.
347  * Flushes invalid cachelines before reading the target if
348  * needs_clflush is set. */
349 static int
350 shmem_pread_fast(struct vm_page *page, int shmem_page_offset, int page_length,
351                  char __user *user_data,
352                  bool page_do_bit17_swizzling, bool needs_clflush)
353 {
354         char *vaddr;
355         int ret;
356
357         if (unlikely(page_do_bit17_swizzling))
358                 return -EINVAL;
359
360         vaddr = kmap_atomic(page);
361         if (needs_clflush)
362                 drm_clflush_virt_range(vaddr + shmem_page_offset,
363                                        page_length);
364         ret = __copy_to_user_inatomic(user_data,
365                                       vaddr + shmem_page_offset,
366                                       page_length);
367         kunmap_atomic(vaddr);
368
369         return ret ? -EFAULT : 0;
370 }
371
372 static void
373 shmem_clflush_swizzled_range(char *addr, unsigned long length,
374                              bool swizzled)
375 {
376         if (unlikely(swizzled)) {
377                 unsigned long start = (unsigned long) addr;
378                 unsigned long end = (unsigned long) addr + length;
379
380                 /* For swizzling simply ensure that we always flush both
381                  * channels. Lame, but simple and it works. Swizzled
382                  * pwrite/pread is far from a hotpath - current userspace
383                  * doesn't use it at all. */
384                 start = round_down(start, 128);
385                 end = round_up(end, 128);
386
387                 drm_clflush_virt_range((void *)start, end - start);
388         } else {
389                 drm_clflush_virt_range(addr, length);
390         }
391
392 }
393
394 /* Only difference to the fast-path function is that this can handle bit17
395  * and uses non-atomic copy and kmap functions. */
396 static int
397 shmem_pread_slow(struct vm_page *page, int shmem_page_offset, int page_length,
398                  char __user *user_data,
399                  bool page_do_bit17_swizzling, bool needs_clflush)
400 {
401         char *vaddr;
402         int ret;
403
404         vaddr = kmap(page);
405         if (needs_clflush)
406                 shmem_clflush_swizzled_range(vaddr + shmem_page_offset,
407                                              page_length,
408                                              page_do_bit17_swizzling);
409
410         if (page_do_bit17_swizzling)
411                 ret = __copy_to_user_swizzled(user_data,
412                                               vaddr, shmem_page_offset,
413                                               page_length);
414         else
415                 ret = __copy_to_user(user_data,
416                                      vaddr + shmem_page_offset,
417                                      page_length);
418         kunmap(page);
419
420         return ret ? - EFAULT : 0;
421 }
422
423 static inline void vm_page_reference(vm_page_t m)
424 {
425         vm_page_flag_set(m, PG_REFERENCED);
426 }
427
428 static int
429 i915_gem_shmem_pread(struct drm_device *dev,
430                      struct drm_i915_gem_object *obj,
431                      struct drm_i915_gem_pread *args,
432                      struct drm_file *file)
433 {
434         char __user *user_data;
435         ssize_t remain;
436         loff_t offset;
437         int shmem_page_offset, page_length, ret = 0;
438         int obj_do_bit17_swizzling, page_do_bit17_swizzling;
439         int needs_clflush = 0;
440         int i;
441
442         user_data = (char __user *) (uintptr_t) args->data_ptr;
443         remain = args->size;
444
445         obj_do_bit17_swizzling = i915_gem_object_needs_bit17_swizzle(obj);
446
447         if (!(obj->base.read_domains & I915_GEM_DOMAIN_CPU)) {
448                 /* If we're not in the cpu read domain, set ourself into the gtt
449                  * read domain and manually flush cachelines (if required). This
450                  * optimizes for the case when the gpu will dirty the data
451                  * anyway again before the next pread happens. */
452                 if (obj->cache_level == I915_CACHE_NONE)
453                         needs_clflush = 1;
454                 if (obj->gtt_space) {
455                         ret = i915_gem_object_set_to_gtt_domain(obj, false);
456                         if (ret)
457                                 return ret;
458                 }
459         }
460
461         ret = i915_gem_object_get_pages(obj);
462         if (ret)
463                 return ret;
464
465         i915_gem_object_pin_pages(obj);
466
467         offset = args->offset;
468
469         for (i = 0; i < (obj->base.size >> PAGE_SHIFT); i++) {
470                 struct vm_page *page = obj->pages[i];
471
472                 if (i < offset >> PAGE_SHIFT)
473                         continue;
474
475                 if (remain <= 0)
476                         break;
477
478                 /* Operation in this page
479                  *
480                  * shmem_page_offset = offset within page in shmem file
481                  * page_length = bytes to copy for this page
482                  */
483                 shmem_page_offset = offset_in_page(offset);
484                 page_length = remain;
485                 if ((shmem_page_offset + page_length) > PAGE_SIZE)
486                         page_length = PAGE_SIZE - shmem_page_offset;
487
488                 page_do_bit17_swizzling = obj_do_bit17_swizzling &&
489                         (VM_PAGE_TO_PHYS(page) & (1 << 17)) != 0;
490
491                 ret = shmem_pread_fast(page, shmem_page_offset, page_length,
492                                        user_data, page_do_bit17_swizzling,
493                                        needs_clflush);
494                 if (ret == 0)
495                         goto next_page;
496
497                 mutex_unlock(&dev->struct_mutex);
498
499 #ifdef __linux__
500                 if (!prefaulted) {
501                         ret = fault_in_multipages_writeable(user_data, remain);
502                         /* Userspace is tricking us, but we've already clobbered
503                          * its pages with the prefault and promised to write the
504                          * data up to the first fault. Hence ignore any errors
505                          * and just continue. */
506                         (void)ret;
507                         prefaulted = 1;
508                 }
509 #endif
510
511                 ret = shmem_pread_slow(page, shmem_page_offset, page_length,
512                                        user_data, page_do_bit17_swizzling,
513                                        needs_clflush);
514
515                 mutex_lock(&dev->struct_mutex);
516
517 next_page:
518                 mark_page_accessed(page);
519
520                 if (ret)
521                         goto out;
522
523                 remain -= page_length;
524                 user_data += page_length;
525                 offset += page_length;
526         }
527
528 out:
529         i915_gem_object_unpin_pages(obj);
530
531         return ret;
532 }
533
534 /**
535  * Reads data from the object referenced by handle.
536  *
537  * On error, the contents of *data are undefined.
538  */
539 int
540 i915_gem_pread_ioctl(struct drm_device *dev, void *data,
541                      struct drm_file *file)
542 {
543         struct drm_i915_gem_pread *args = data;
544         struct drm_i915_gem_object *obj;
545         int ret = 0;
546
547         if (args->size == 0)
548                 return 0;
549
550         ret = i915_mutex_lock_interruptible(dev);
551         if (ret)
552                 return ret;
553
554         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
555         if (&obj->base == NULL) {
556                 ret = -ENOENT;
557                 goto unlock;
558         }
559
560         /* Bounds check source.  */
561         if (args->offset > obj->base.size ||
562             args->size > obj->base.size - args->offset) {
563                 ret = -EINVAL;
564                 goto out;
565         }
566
567         trace_i915_gem_object_pread(obj, args->offset, args->size);
568
569         ret = i915_gem_shmem_pread(dev, obj, args, file);
570
571 out:
572         drm_gem_object_unreference(&obj->base);
573 unlock:
574         mutex_unlock(&dev->struct_mutex);
575         return ret;
576 }
577
578 #if 0
579 /* This is the fast write path which cannot handle
580  * page faults in the source data
581  */
582
583 static inline int
584 fast_user_write(struct io_mapping *mapping,
585                 loff_t page_base, int page_offset,
586                 char __user *user_data,
587                 int length)
588 {
589         void __iomem *vaddr_atomic;
590         void *vaddr;
591         unsigned long unwritten;
592
593         vaddr_atomic = io_mapping_map_atomic_wc(mapping, page_base);
594         /* We can use the cpu mem copy function because this is X86. */
595         vaddr = (void __force*)vaddr_atomic + page_offset;
596         unwritten = __copy_from_user_inatomic_nocache(vaddr,
597                                                       user_data, length);
598         io_mapping_unmap_atomic(vaddr_atomic);
599         return unwritten;
600 }
601
602 /**
603  * This is the fast pwrite path, where we copy the data directly from the
604  * user into the GTT, uncached.
605  */
606 static int
607 i915_gem_gtt_pwrite_fast(struct drm_device *dev,
608                          struct drm_i915_gem_object *obj,
609                          struct drm_i915_gem_pwrite *args,
610                          struct drm_file *file)
611 {
612         drm_i915_private_t *dev_priv = dev->dev_private;
613         ssize_t remain;
614         loff_t offset, page_base;
615         char __user *user_data;
616         int page_offset, page_length, ret;
617
618         ret = i915_gem_object_pin(obj, 0, true, true);
619         if (ret)
620                 goto out;
621
622         ret = i915_gem_object_set_to_gtt_domain(obj, true);
623         if (ret)
624                 goto out_unpin;
625
626         ret = i915_gem_object_put_fence(obj);
627         if (ret)
628                 goto out_unpin;
629
630         user_data = to_user_ptr(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->gtt.mappable, page_base,
653                                     page_offset, user_data, page_length)) {
654                         ret = -EFAULT;
655                         goto out_unpin;
656                 }
657
658                 remain -= page_length;
659                 user_data += page_length;
660                 offset += page_length;
661         }
662
663 out_unpin:
664         i915_gem_object_unpin(obj);
665 out:
666         return ret;
667 }
668 #endif
669
670 static int
671 i915_gem_gtt_write(struct drm_device *dev, struct drm_i915_gem_object *obj,
672     uint64_t data_ptr, uint64_t size, uint64_t offset, struct drm_file *file)
673 {
674         vm_offset_t mkva;
675         int ret;
676
677         /*
678          * Pass the unaligned physical address and size to pmap_mapdev_attr()
679          * so it can properly calculate whether an extra page needs to be
680          * mapped or not to cover the requested range.  The function will
681          * add the page offset into the returned mkva for us.
682          */
683         mkva = (vm_offset_t)pmap_mapdev_attr(dev->agp->base + obj->gtt_offset +
684             offset, size, PAT_WRITE_COMBINING);
685         ret = -copyin_nofault((void *)(uintptr_t)data_ptr, (char *)mkva, size);
686         pmap_unmapdev(mkva, size);
687         return ret;
688 }
689
690 #if 0
691 /* Per-page copy function for the shmem pwrite fastpath.
692  * Flushes invalid cachelines before writing to the target if
693  * needs_clflush_before is set and flushes out any written cachelines after
694  * writing if needs_clflush is set. */
695 static int
696 shmem_pwrite_fast(struct vm_page *page, int shmem_page_offset, int page_length,
697                   char __user *user_data,
698                   bool page_do_bit17_swizzling,
699                   bool needs_clflush_before,
700                   bool needs_clflush_after)
701 {
702         char *vaddr;
703         int ret;
704
705         if (unlikely(page_do_bit17_swizzling))
706                 return -EINVAL;
707
708         vaddr = kmap_atomic(page);
709         if (needs_clflush_before)
710                 drm_clflush_virt_range(vaddr + shmem_page_offset,
711                                        page_length);
712         ret = __copy_from_user_inatomic_nocache(vaddr + shmem_page_offset,
713                                                 user_data,
714                                                 page_length);
715         if (needs_clflush_after)
716                 drm_clflush_virt_range(vaddr + shmem_page_offset,
717                                        page_length);
718         kunmap_atomic(vaddr);
719
720         return ret ? -EFAULT : 0;
721 }
722
723 /* Only difference to the fast-path function is that this can handle bit17
724  * and uses non-atomic copy and kmap functions. */
725 static int
726 shmem_pwrite_slow(struct vm_page *page, int shmem_page_offset, int page_length,
727                   char __user *user_data,
728                   bool page_do_bit17_swizzling,
729                   bool needs_clflush_before,
730                   bool needs_clflush_after)
731 {
732         char *vaddr;
733         int ret;
734
735         vaddr = kmap(page);
736         if (unlikely(needs_clflush_before || page_do_bit17_swizzling))
737                 shmem_clflush_swizzled_range(vaddr + shmem_page_offset,
738                                              page_length,
739                                              page_do_bit17_swizzling);
740         if (page_do_bit17_swizzling)
741                 ret = __copy_from_user_swizzled(vaddr, shmem_page_offset,
742                                                 user_data,
743                                                 page_length);
744         else
745                 ret = __copy_from_user(vaddr + shmem_page_offset,
746                                        user_data,
747                                        page_length);
748         if (needs_clflush_after)
749                 shmem_clflush_swizzled_range(vaddr + shmem_page_offset,
750                                              page_length,
751                                              page_do_bit17_swizzling);
752         kunmap(page);
753
754         return ret ? -EFAULT : 0;
755 }
756 #endif
757
758 static int
759 i915_gem_shmem_pwrite(struct drm_device *dev,
760                       struct drm_i915_gem_object *obj,
761                       struct drm_i915_gem_pwrite *args,
762                       struct drm_file *file)
763 {
764         vm_object_t vm_obj;
765         vm_page_t m;
766         struct sf_buf *sf;
767         vm_offset_t mkva;
768         vm_pindex_t obj_pi;
769         int cnt, do_bit17_swizzling, length, obj_po, ret, swizzled_po;
770
771         do_bit17_swizzling = 0;
772
773         obj->dirty = 1;
774         vm_obj = obj->base.vm_obj;
775         ret = 0;
776
777         VM_OBJECT_LOCK(vm_obj);
778         vm_object_pip_add(vm_obj, 1);
779         while (args->size > 0) {
780                 obj_pi = OFF_TO_IDX(args->offset);
781                 obj_po = args->offset & PAGE_MASK;
782
783                 m = shmem_read_mapping_page(vm_obj, obj_pi);
784                 VM_OBJECT_UNLOCK(vm_obj);
785
786                 sf = sf_buf_alloc(m);
787                 mkva = sf_buf_kva(sf);
788                 length = min(args->size, PAGE_SIZE - obj_po);
789                 while (length > 0) {
790                         if (do_bit17_swizzling &&
791                             (VM_PAGE_TO_PHYS(m) & (1 << 17)) != 0) {
792                                 cnt = roundup2(obj_po + 1, 64);
793                                 cnt = min(cnt - obj_po, length);
794                                 swizzled_po = obj_po ^ 64;
795                         } else {
796                                 cnt = length;
797                                 swizzled_po = obj_po;
798                         }
799                         ret = -copyin_nofault(
800                             (void *)(uintptr_t)args->data_ptr,
801                             (char *)mkva + swizzled_po, cnt);
802                         if (ret != 0)
803                                 break;
804                         args->data_ptr += cnt;
805                         args->size -= cnt;
806                         length -= cnt;
807                         args->offset += cnt;
808                         obj_po += cnt;
809                 }
810                 sf_buf_free(sf);
811                 VM_OBJECT_LOCK(vm_obj);
812                 vm_page_dirty(m);
813                 vm_page_reference(m);
814                 vm_page_busy_wait(m, FALSE, "i915gem");
815                 vm_page_unwire(m, 1);
816                 vm_page_wakeup(m);
817
818                 if (ret != 0)
819                         break;
820         }
821         vm_object_pip_wakeup(vm_obj);
822         VM_OBJECT_UNLOCK(vm_obj);
823
824         return (ret);
825 }
826
827 /**
828  * Writes data to the object referenced by handle.
829  *
830  * On error, the contents of the buffer that were to be modified are undefined.
831  */
832 int
833 i915_gem_pwrite_ioctl(struct drm_device *dev, void *data,
834                       struct drm_file *file)
835 {
836         struct drm_i915_gem_pwrite *args = data;
837         struct drm_i915_gem_object *obj;
838         vm_page_t *ma;
839         vm_offset_t start, end;
840         int npages, ret;
841
842         if (args->size == 0)
843                 return 0;
844
845         start = trunc_page(args->data_ptr);
846         end = round_page(args->data_ptr + args->size);
847         npages = howmany(end - start, PAGE_SIZE);
848         ma = kmalloc(npages * sizeof(vm_page_t), M_DRM, M_WAITOK |
849             M_ZERO);
850         npages = vm_fault_quick_hold_pages(&curproc->p_vmspace->vm_map,
851             (vm_offset_t)args->data_ptr, args->size,
852             VM_PROT_READ, ma, npages);
853         if (npages == -1) {
854                 ret = -EFAULT;
855                 goto free_ma;
856         }
857
858         ret = i915_mutex_lock_interruptible(dev);
859         if (ret != 0)
860                 goto unlocked;
861
862         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
863         if (&obj->base == NULL) {
864                 ret = -ENOENT;
865                 goto unlock;
866         }
867
868         /* Bounds check destination. */
869         if (args->offset > obj->base.size ||
870             args->size > obj->base.size - args->offset) {
871                 ret = -EINVAL;
872                 goto out;
873         }
874
875         trace_i915_gem_object_pwrite(obj, args->offset, args->size);
876
877         if (obj->phys_obj) {
878                 ret = i915_gem_phys_pwrite(dev, obj, args, file);
879         } else if (obj->gtt_space &&
880                     obj->base.write_domain != I915_GEM_DOMAIN_CPU) {
881                 ret = i915_gem_object_pin(obj, 0, true, false);
882                 if (ret != 0)
883                         goto out;
884                 ret = i915_gem_object_set_to_gtt_domain(obj, true);
885                 if (ret != 0)
886                         goto out_unpin;
887                 ret = i915_gem_object_put_fence(obj);
888                 if (ret != 0)
889                         goto out_unpin;
890                 ret = i915_gem_gtt_write(dev, obj, args->data_ptr, args->size,
891                     args->offset, file);
892 out_unpin:
893                 i915_gem_object_unpin(obj);
894         } else {
895                 ret = i915_gem_object_set_to_cpu_domain(obj, true);
896                 if (ret != 0)
897                         goto out;
898                 ret = i915_gem_shmem_pwrite(dev, obj, args, file);
899         }
900 out:
901         drm_gem_object_unreference(&obj->base);
902 unlock:
903         mutex_unlock(&dev->struct_mutex);
904 unlocked:
905         vm_page_unhold_pages(ma, npages);
906 free_ma:
907         drm_free(ma, M_DRM);
908         return ret;
909 }
910
911 int
912 i915_gem_check_wedge(struct i915_gpu_error *error,
913                      bool interruptible)
914 {
915         if (i915_reset_in_progress(error)) {
916                 /* Non-interruptible callers can't handle -EAGAIN, hence return
917                  * -EIO unconditionally for these. */
918                 if (!interruptible)
919                         return -EIO;
920
921                 /* Recovery complete, but the reset failed ... */
922                 if (i915_terminally_wedged(error))
923                         return -EIO;
924
925                 return -EAGAIN;
926         }
927
928         return 0;
929 }
930
931 /*
932  * Compare seqno against outstanding lazy request. Emit a request if they are
933  * equal.
934  */
935 static int
936 i915_gem_check_olr(struct intel_ring_buffer *ring, u32 seqno)
937 {
938         int ret;
939
940         DRM_LOCK_ASSERT(ring->dev);
941
942         ret = 0;
943         if (seqno == ring->outstanding_lazy_request)
944                 ret = i915_add_request(ring, NULL);
945
946         return ret;
947 }
948
949 /**
950  * __wait_seqno - wait until execution of seqno has finished
951  * @ring: the ring expected to report seqno
952  * @seqno: duh!
953  * @reset_counter: reset sequence associated with the given seqno
954  * @interruptible: do an interruptible wait (normally yes)
955  * @timeout: in - how long to wait (NULL forever); out - how much time remaining
956  *
957  * Note: It is of utmost importance that the passed in seqno and reset_counter
958  * values have been read by the caller in an smp safe manner. Where read-side
959  * locks are involved, it is sufficient to read the reset_counter before
960  * unlocking the lock that protects the seqno. For lockless tricks, the
961  * reset_counter _must_ be read before, and an appropriate smp_rmb must be
962  * inserted.
963  *
964  * Returns 0 if the seqno was found within the alloted time. Else returns the
965  * errno with remaining time filled in timeout argument.
966  */
967 static int __wait_seqno(struct intel_ring_buffer *ring, u32 seqno,
968                         unsigned reset_counter,
969                         bool interruptible, struct timespec *timeout)
970 {
971         drm_i915_private_t *dev_priv = ring->dev->dev_private;
972         struct timespec before, now, wait_time={1,0};
973         unsigned long timeout_jiffies;
974         long end;
975         bool wait_forever = true;
976         int ret;
977
978         if (i915_seqno_passed(ring->get_seqno(ring, true), seqno))
979                 return 0;
980
981         trace_i915_gem_request_wait_begin(ring, seqno);
982
983         if (timeout != NULL) {
984                 wait_time = *timeout;
985                 wait_forever = false;
986         }
987
988         timeout_jiffies = timespec_to_jiffies_timeout(&wait_time);
989
990         if (WARN_ON(!ring->irq_get(ring)))
991                 return -ENODEV;
992
993         /* Record current time in case interrupted by signal, or wedged * */
994         getrawmonotonic(&before);
995
996 #define EXIT_COND \
997         (i915_seqno_passed(ring->get_seqno(ring, false), seqno) || \
998          i915_reset_in_progress(&dev_priv->gpu_error) || \
999          reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
1000         do {
1001                 if (interruptible)
1002                         end = wait_event_interruptible_timeout(ring->irq_queue,
1003                                                                EXIT_COND,
1004                                                                timeout_jiffies);
1005                 else
1006                         end = wait_event_timeout(ring->irq_queue, EXIT_COND,
1007                                                  timeout_jiffies);
1008
1009                 /* We need to check whether any gpu reset happened in between
1010                  * the caller grabbing the seqno and now ... */
1011                 if (reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
1012                         end = -EAGAIN;
1013
1014                 /* ... but upgrade the -EGAIN to an -EIO if the gpu is truely
1015                  * gone. */
1016                 ret = i915_gem_check_wedge(&dev_priv->gpu_error, interruptible);
1017                 if (ret)
1018                         end = ret;
1019         } while (end == 0 && wait_forever);
1020
1021         getrawmonotonic(&now);
1022
1023         ring->irq_put(ring);
1024         trace_i915_gem_request_wait_end(ring, seqno);
1025 #undef EXIT_COND
1026
1027         if (timeout) {
1028                 struct timespec sleep_time = timespec_sub(now, before);
1029                 *timeout = timespec_sub(*timeout, sleep_time);
1030                 if (!timespec_valid(timeout)) /* i.e. negative time remains */
1031                         set_normalized_timespec(timeout, 0, 0);
1032         }
1033
1034         switch (end) {
1035         case -EIO:
1036         case -EAGAIN: /* Wedged */
1037         case -ERESTARTSYS: /* Signal */
1038                 return (int)end;
1039         case 0: /* Timeout */
1040                 return -ETIMEDOUT;      /* -ETIME on Linux */
1041         default: /* Completed */
1042                 WARN_ON(end < 0); /* We're not aware of other errors */
1043                 return 0;
1044         }
1045 }
1046
1047 /**
1048  * Waits for a sequence number to be signaled, and cleans up the
1049  * request and object lists appropriately for that event.
1050  */
1051 int
1052 i915_wait_seqno(struct intel_ring_buffer *ring, uint32_t seqno)
1053 {
1054         struct drm_device *dev = ring->dev;
1055         struct drm_i915_private *dev_priv = dev->dev_private;
1056         bool interruptible = dev_priv->mm.interruptible;
1057         int ret;
1058
1059         DRM_LOCK_ASSERT(dev);
1060         BUG_ON(seqno == 0);
1061
1062         ret = i915_gem_check_wedge(&dev_priv->gpu_error, interruptible);
1063         if (ret)
1064                 return ret;
1065
1066         ret = i915_gem_check_olr(ring, seqno);
1067         if (ret)
1068                 return ret;
1069
1070         return __wait_seqno(ring, seqno,
1071                             atomic_read(&dev_priv->gpu_error.reset_counter),
1072                             interruptible, NULL);
1073 }
1074
1075 static int
1076 i915_gem_object_wait_rendering__tail(struct drm_i915_gem_object *obj,
1077                                      struct intel_ring_buffer *ring)
1078 {
1079         i915_gem_retire_requests_ring(ring);
1080
1081         /* Manually manage the write flush as we may have not yet
1082          * retired the buffer.
1083          *
1084          * Note that the last_write_seqno is always the earlier of
1085          * the two (read/write) seqno, so if we haved successfully waited,
1086          * we know we have passed the last write.
1087          */
1088         obj->last_write_seqno = 0;
1089         obj->base.write_domain &= ~I915_GEM_GPU_DOMAINS;
1090
1091         return 0;
1092 }
1093
1094 /**
1095  * Ensures that all rendering to the object has completed and the object is
1096  * safe to unbind from the GTT or access from the CPU.
1097  */
1098 static __must_check int
1099 i915_gem_object_wait_rendering(struct drm_i915_gem_object *obj,
1100                                bool readonly)
1101 {
1102         struct intel_ring_buffer *ring = obj->ring;
1103         u32 seqno;
1104         int ret;
1105
1106         seqno = readonly ? obj->last_write_seqno : obj->last_read_seqno;
1107         if (seqno == 0)
1108                 return 0;
1109
1110         ret = i915_wait_seqno(ring, seqno);
1111         if (ret)
1112                 return ret;
1113
1114         return i915_gem_object_wait_rendering__tail(obj, ring);
1115 }
1116
1117 /* A nonblocking variant of the above wait. This is a highly dangerous routine
1118  * as the object state may change during this call.
1119  */
1120 static __must_check int
1121 i915_gem_object_wait_rendering__nonblocking(struct drm_i915_gem_object *obj,
1122                                             bool readonly)
1123 {
1124         struct drm_device *dev = obj->base.dev;
1125         struct drm_i915_private *dev_priv = dev->dev_private;
1126         struct intel_ring_buffer *ring = obj->ring;
1127         unsigned reset_counter;
1128         u32 seqno;
1129         int ret;
1130
1131         DRM_LOCK_ASSERT(dev);
1132         BUG_ON(!dev_priv->mm.interruptible);
1133
1134         seqno = readonly ? obj->last_write_seqno : obj->last_read_seqno;
1135         if (seqno == 0)
1136                 return 0;
1137
1138         ret = i915_gem_check_wedge(&dev_priv->gpu_error, true);
1139         if (ret)
1140                 return ret;
1141
1142         ret = i915_gem_check_olr(ring, seqno);
1143         if (ret)
1144                 return ret;
1145
1146         reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
1147         mutex_unlock(&dev->struct_mutex);
1148         ret = __wait_seqno(ring, seqno, reset_counter, true, NULL);
1149         mutex_lock(&dev->struct_mutex);
1150         if (ret)
1151                 return ret;
1152
1153         return i915_gem_object_wait_rendering__tail(obj, ring);
1154 }
1155
1156 /**
1157  * Called when user space prepares to use an object with the CPU, either
1158  * through the mmap ioctl's mapping or a GTT mapping.
1159  */
1160 int
1161 i915_gem_set_domain_ioctl(struct drm_device *dev, void *data,
1162                           struct drm_file *file)
1163 {
1164         struct drm_i915_gem_set_domain *args = data;
1165         struct drm_i915_gem_object *obj;
1166         uint32_t read_domains = args->read_domains;
1167         uint32_t write_domain = args->write_domain;
1168         int ret;
1169
1170         /* Only handle setting domains to types used by the CPU. */
1171         if (write_domain & I915_GEM_GPU_DOMAINS)
1172                 return -EINVAL;
1173
1174         if (read_domains & I915_GEM_GPU_DOMAINS)
1175                 return -EINVAL;
1176
1177         /* Having something in the write domain implies it's in the read
1178          * domain, and only that read domain.  Enforce that in the request.
1179          */
1180         if (write_domain != 0 && read_domains != write_domain)
1181                 return -EINVAL;
1182
1183         ret = i915_mutex_lock_interruptible(dev);
1184         if (ret)
1185                 return ret;
1186
1187         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
1188         if (&obj->base == NULL) {
1189                 ret = -ENOENT;
1190                 goto unlock;
1191         }
1192
1193         /* Try to flush the object off the GPU without holding the lock.
1194          * We will repeat the flush holding the lock in the normal manner
1195          * to catch cases where we are gazumped.
1196          */
1197         ret = i915_gem_object_wait_rendering__nonblocking(obj, !write_domain);
1198         if (ret)
1199                 goto unref;
1200
1201         if (read_domains & I915_GEM_DOMAIN_GTT) {
1202                 ret = i915_gem_object_set_to_gtt_domain(obj, write_domain != 0);
1203
1204                 /* Silently promote "you're not bound, there was nothing to do"
1205                  * to success, since the client was just asking us to
1206                  * make sure everything was done.
1207                  */
1208                 if (ret == -EINVAL)
1209                         ret = 0;
1210         } else {
1211                 ret = i915_gem_object_set_to_cpu_domain(obj, write_domain != 0);
1212         }
1213
1214 unref:
1215         drm_gem_object_unreference(&obj->base);
1216 unlock:
1217         mutex_unlock(&dev->struct_mutex);
1218         return ret;
1219 }
1220
1221 /**
1222  * Called when user space has done writes to this buffer
1223  */
1224 int
1225 i915_gem_sw_finish_ioctl(struct drm_device *dev, void *data,
1226                          struct drm_file *file)
1227 {
1228         struct drm_i915_gem_sw_finish *args = data;
1229         struct drm_i915_gem_object *obj;
1230         int ret = 0;
1231
1232         ret = i915_mutex_lock_interruptible(dev);
1233         if (ret)
1234                 return ret;
1235         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
1236         if (&obj->base == NULL) {
1237                 ret = -ENOENT;
1238                 goto unlock;
1239         }
1240
1241         /* Pinned buffers may be scanout, so flush the cache */
1242         if (obj->pin_count)
1243                 i915_gem_object_flush_cpu_write_domain(obj);
1244
1245         drm_gem_object_unreference(&obj->base);
1246 unlock:
1247         mutex_unlock(&dev->struct_mutex);
1248         return ret;
1249 }
1250
1251 /**
1252  * Maps the contents of an object, returning the address it is mapped
1253  * into.
1254  *
1255  * While the mapping holds a reference on the contents of the object, it doesn't
1256  * imply a ref on the object itself.
1257  */
1258 int
1259 i915_gem_mmap_ioctl(struct drm_device *dev, void *data,
1260                     struct drm_file *file)
1261 {
1262         struct drm_i915_gem_mmap *args = data;
1263         struct drm_gem_object *obj;
1264         struct proc *p = curproc;
1265         vm_map_t map = &p->p_vmspace->vm_map;
1266         vm_offset_t addr;
1267         vm_size_t size;
1268         int error = 0, rv;
1269
1270         obj = drm_gem_object_lookup(dev, file, args->handle);
1271         if (obj == NULL)
1272                 return -ENOENT;
1273
1274         if (args->size == 0)
1275                 goto out;
1276
1277         size = round_page(args->size);
1278         if (map->size + size > p->p_rlimit[RLIMIT_VMEM].rlim_cur) {
1279                 error = ENOMEM;
1280                 goto out;
1281         }
1282
1283         addr = 0;
1284         vm_object_hold(obj->vm_obj);
1285         vm_object_reference_locked(obj->vm_obj);
1286         vm_object_drop(obj->vm_obj);
1287         rv = vm_map_find(map, obj->vm_obj, NULL,
1288                          args->offset, &addr, args->size,
1289                          PAGE_SIZE, /* align */
1290                          TRUE, /* fitit */
1291                          VM_MAPTYPE_NORMAL, /* maptype */
1292                          VM_PROT_READ | VM_PROT_WRITE, /* prot */
1293                          VM_PROT_READ | VM_PROT_WRITE, /* max */
1294                          MAP_SHARED /* cow */);
1295         if (rv != KERN_SUCCESS) {
1296                 vm_object_deallocate(obj->vm_obj);
1297                 error = -vm_mmap_to_errno(rv);
1298         } else {
1299                 args->addr_ptr = (uint64_t)addr;
1300         }
1301 out:
1302         drm_gem_object_unreference(obj);
1303         return (error);
1304 }
1305
1306 int i915_intr_pf;
1307
1308 /**
1309  * i915_gem_fault - fault a page into the GTT
1310  * vma: VMA in question
1311  * vmf: fault info
1312  *
1313  * The fault handler is set up by drm_gem_mmap() when a object is GTT mapped
1314  * from userspace.  The fault handler takes care of binding the object to
1315  * the GTT (if needed), allocating and programming a fence register (again,
1316  * only if needed based on whether the old reg is still valid or the object
1317  * is tiled) and inserting a new PTE into the faulting process.
1318  *
1319  * Note that the faulting process may involve evicting existing objects
1320  * from the GTT and/or fence registers to make room.  So performance may
1321  * suffer if the GTT working set is large or there are few fence registers
1322  * left.
1323  */
1324 int
1325 i915_gem_fault(vm_object_t vm_obj, vm_ooffset_t offset, int prot,
1326     vm_page_t *mres)
1327 {
1328         struct drm_gem_object *gem_obj;
1329         struct drm_i915_gem_object *obj;
1330         struct drm_device *dev;
1331         drm_i915_private_t *dev_priv;
1332         vm_page_t m, oldm;
1333         int cause, ret;
1334         bool write;
1335
1336         gem_obj = vm_obj->handle;
1337         obj = to_intel_bo(gem_obj);
1338         dev = obj->base.dev;
1339         dev_priv = dev->dev_private;
1340 #if 0
1341         write = (prot & VM_PROT_WRITE) != 0;
1342 #else
1343         write = true;
1344 #endif
1345         vm_object_pip_add(vm_obj, 1);
1346
1347         /*
1348          * Remove the placeholder page inserted by vm_fault() from the
1349          * object before dropping the object lock. If
1350          * i915_gem_release_mmap() is active in parallel on this gem
1351          * object, then it owns the drm device sx and might find the
1352          * placeholder already. Then, since the page is busy,
1353          * i915_gem_release_mmap() sleeps waiting for the busy state
1354          * of the page cleared. We will be not able to acquire drm
1355          * device lock until i915_gem_release_mmap() is able to make a
1356          * progress.
1357          */
1358         if (*mres != NULL) {
1359                 oldm = *mres;
1360                 vm_page_remove(oldm);
1361                 *mres = NULL;
1362         } else
1363                 oldm = NULL;
1364 retry:
1365         VM_OBJECT_UNLOCK(vm_obj);
1366 unlocked_vmobj:
1367         cause = ret = 0;
1368         m = NULL;
1369
1370         if (i915_intr_pf) {
1371                 ret = i915_mutex_lock_interruptible(dev);
1372                 if (ret != 0) {
1373                         cause = 10;
1374                         goto out;
1375                 }
1376         } else
1377                 mutex_lock(&dev->struct_mutex);
1378
1379         /*
1380          * Since the object lock was dropped, other thread might have
1381          * faulted on the same GTT address and instantiated the
1382          * mapping for the page.  Recheck.
1383          */
1384         VM_OBJECT_LOCK(vm_obj);
1385         m = vm_page_lookup(vm_obj, OFF_TO_IDX(offset));
1386         if (m != NULL) {
1387                 if ((m->flags & PG_BUSY) != 0) {
1388                         mutex_unlock(&dev->struct_mutex);
1389 #if 0 /* XXX */
1390                         vm_page_sleep(m, "915pee");
1391 #endif
1392                         goto retry;
1393                 }
1394                 goto have_page;
1395         } else
1396                 VM_OBJECT_UNLOCK(vm_obj);
1397
1398         trace_i915_gem_object_fault(obj, page_offset, true, write);
1399
1400         /* Access to snoopable pages through the GTT is incoherent. */
1401         if (obj->cache_level != I915_CACHE_NONE && !HAS_LLC(dev)) {
1402                 ret = -EINVAL;
1403                 goto unlock;
1404         }
1405
1406         /* Now bind it into the GTT if needed */
1407         if (!obj->map_and_fenceable) {
1408                 ret = i915_gem_object_unbind(obj);
1409                 if (ret != 0) {
1410                         cause = 20;
1411                         goto unlock;
1412                 }
1413         }
1414         if (!obj->gtt_space) {
1415                 ret = i915_gem_object_bind_to_gtt(obj, 0, true, false);
1416                 if (ret != 0) {
1417                         cause = 30;
1418                         goto unlock;
1419                 }
1420
1421                 ret = i915_gem_object_set_to_gtt_domain(obj, write);
1422                 if (ret != 0) {
1423                         cause = 40;
1424                         goto unlock;
1425                 }
1426         }
1427
1428         if (obj->tiling_mode == I915_TILING_NONE)
1429                 ret = i915_gem_object_put_fence(obj);
1430         else
1431                 ret = i915_gem_object_get_fence(obj);
1432         if (ret != 0) {
1433                 cause = 50;
1434                 goto unlock;
1435         }
1436
1437         if (i915_gem_object_is_inactive(obj))
1438                 list_move_tail(&obj->mm_list, &dev_priv->mm.inactive_list);
1439
1440         obj->fault_mappable = true;
1441         VM_OBJECT_LOCK(vm_obj);
1442         m = vm_phys_fictitious_to_vm_page(dev->agp->base + obj->gtt_offset +
1443             offset);
1444         if (m == NULL) {
1445                 cause = 60;
1446                 ret = -EFAULT;
1447                 goto unlock;
1448         }
1449         KASSERT((m->flags & PG_FICTITIOUS) != 0,
1450             ("not fictitious %p", m));
1451         KASSERT(m->wire_count == 1, ("wire_count not 1 %p", m));
1452
1453         if ((m->flags & PG_BUSY) != 0) {
1454                 mutex_unlock(&dev->struct_mutex);
1455 #if 0 /* XXX */
1456                 vm_page_sleep(m, "915pbs");
1457 #endif
1458                 goto retry;
1459         }
1460         m->valid = VM_PAGE_BITS_ALL;
1461         vm_page_insert(m, vm_obj, OFF_TO_IDX(offset));
1462 have_page:
1463         *mres = m;
1464         vm_page_busy_try(m, false);
1465
1466         mutex_unlock(&dev->struct_mutex);
1467         if (oldm != NULL) {
1468                 vm_page_free(oldm);
1469         }
1470         vm_object_pip_wakeup(vm_obj);
1471         return (VM_PAGER_OK);
1472
1473 unlock:
1474         mutex_unlock(&dev->struct_mutex);
1475 out:
1476         KASSERT(ret != 0, ("i915_gem_pager_fault: wrong return"));
1477         if (ret == -EAGAIN || ret == -EIO || ret == -EINTR) {
1478                 goto unlocked_vmobj;
1479         }
1480         VM_OBJECT_LOCK(vm_obj);
1481         vm_object_pip_wakeup(vm_obj);
1482         return (VM_PAGER_ERROR);
1483 }
1484
1485 /**
1486  * i915_gem_release_mmap - remove physical page mappings
1487  * @obj: obj in question
1488  *
1489  * Preserve the reservation of the mmapping with the DRM core code, but
1490  * relinquish ownership of the pages back to the system.
1491  *
1492  * It is vital that we remove the page mapping if we have mapped a tiled
1493  * object through the GTT and then lose the fence register due to
1494  * resource pressure. Similarly if the object has been moved out of the
1495  * aperture, than pages mapped into userspace must be revoked. Removing the
1496  * mapping will then trigger a page fault on the next user access, allowing
1497  * fixup by i915_gem_fault().
1498  */
1499 void
1500 i915_gem_release_mmap(struct drm_i915_gem_object *obj)
1501 {
1502         vm_object_t devobj;
1503         vm_page_t m;
1504         int i, page_count;
1505
1506         if (!obj->fault_mappable)
1507                 return;
1508
1509         devobj = cdev_pager_lookup(obj);
1510         if (devobj != NULL) {
1511                 page_count = OFF_TO_IDX(obj->base.size);
1512
1513                 VM_OBJECT_LOCK(devobj);
1514                 for (i = 0; i < page_count; i++) {
1515                         m = vm_page_lookup_busy_wait(devobj, i, TRUE, "915unm");
1516                         if (m == NULL)
1517                                 continue;
1518                         cdev_pager_free_page(devobj, m);
1519                 }
1520                 VM_OBJECT_UNLOCK(devobj);
1521                 vm_object_deallocate(devobj);
1522         }
1523
1524         obj->fault_mappable = false;
1525 }
1526
1527 uint32_t
1528 i915_gem_get_gtt_size(struct drm_device *dev, uint32_t size, int tiling_mode)
1529 {
1530         uint32_t gtt_size;
1531
1532         if (INTEL_INFO(dev)->gen >= 4 ||
1533             tiling_mode == I915_TILING_NONE)
1534                 return size;
1535
1536         /* Previous chips need a power-of-two fence region when tiling */
1537         if (INTEL_INFO(dev)->gen == 3)
1538                 gtt_size = 1024*1024;
1539         else
1540                 gtt_size = 512*1024;
1541
1542         while (gtt_size < size)
1543                 gtt_size <<= 1;
1544
1545         return gtt_size;
1546 }
1547
1548 /**
1549  * i915_gem_get_gtt_alignment - return required GTT alignment for an object
1550  * @obj: object to check
1551  *
1552  * Return the required GTT alignment for an object, taking into account
1553  * potential fence register mapping.
1554  */
1555 uint32_t
1556 i915_gem_get_gtt_alignment(struct drm_device *dev, uint32_t size,
1557                            int tiling_mode, bool fenced)
1558 {
1559
1560         /*
1561          * Minimum alignment is 4k (GTT page size), but might be greater
1562          * if a fence register is needed for the object.
1563          */
1564         if (INTEL_INFO(dev)->gen >= 4 || (!fenced && IS_G33(dev)) ||
1565             tiling_mode == I915_TILING_NONE)
1566                 return 4096;
1567
1568         /*
1569          * Previous chips need to be aligned to the size of the smallest
1570          * fence register that can contain the object.
1571          */
1572         return i915_gem_get_gtt_size(dev, size, tiling_mode);
1573 }
1574
1575 int
1576 i915_gem_mmap_gtt(struct drm_file *file,
1577                   struct drm_device *dev,
1578                   uint32_t handle,
1579                   uint64_t *offset)
1580 {
1581         struct drm_i915_private *dev_priv = dev->dev_private;
1582         struct drm_i915_gem_object *obj;
1583         int ret;
1584
1585         ret = i915_mutex_lock_interruptible(dev);
1586         if (ret)
1587                 return ret;
1588
1589         obj = to_intel_bo(drm_gem_object_lookup(dev, file, handle));
1590         if (&obj->base == NULL) {
1591                 ret = -ENOENT;
1592                 goto unlock;
1593         }
1594
1595         if (obj->base.size > dev_priv->gtt.mappable_end) {
1596                 ret = -E2BIG;
1597                 goto out;
1598         }
1599
1600         if (obj->madv != I915_MADV_WILLNEED) {
1601                 DRM_ERROR("Attempting to mmap a purgeable buffer\n");
1602                 ret = -EINVAL;
1603                 goto out;
1604         }
1605
1606         ret = drm_gem_create_mmap_offset(&obj->base);
1607         if (ret)
1608                 goto out;
1609
1610         *offset = DRM_GEM_MAPPING_OFF(obj->base.map_list.key) |
1611             DRM_GEM_MAPPING_KEY;
1612 out:
1613         drm_gem_object_unreference(&obj->base);
1614 unlock:
1615         mutex_unlock(&dev->struct_mutex);
1616         return ret;
1617 }
1618
1619 /**
1620  * i915_gem_mmap_gtt_ioctl - prepare an object for GTT mmap'ing
1621  * @dev: DRM device
1622  * @data: GTT mapping ioctl data
1623  * @file: GEM object info
1624  *
1625  * Simply returns the fake offset to userspace so it can mmap it.
1626  * The mmap call will end up in drm_gem_mmap(), which will set things
1627  * up so we can get faults in the handler above.
1628  *
1629  * The fault handler will take care of binding the object into the GTT
1630  * (since it may have been evicted to make room for something), allocating
1631  * a fence register, and mapping the appropriate aperture address into
1632  * userspace.
1633  */
1634 int
1635 i915_gem_mmap_gtt_ioctl(struct drm_device *dev, void *data,
1636                         struct drm_file *file)
1637 {
1638         struct drm_i915_gem_mmap_gtt *args = data;
1639
1640         return i915_gem_mmap_gtt(file, dev, args->handle, &args->offset);
1641 }
1642
1643 /* Immediately discard the backing storage */
1644 static void
1645 i915_gem_object_truncate(struct drm_i915_gem_object *obj)
1646 {
1647         vm_object_t vm_obj;
1648
1649         vm_obj = obj->base.vm_obj;
1650         VM_OBJECT_LOCK(vm_obj);
1651         vm_object_page_remove(vm_obj, 0, 0, false);
1652         VM_OBJECT_UNLOCK(vm_obj);
1653
1654         obj->madv = __I915_MADV_PURGED;
1655 }
1656
1657 static inline int
1658 i915_gem_object_is_purgeable(struct drm_i915_gem_object *obj)
1659 {
1660         return obj->madv == I915_MADV_DONTNEED;
1661 }
1662
1663 static void
1664 i915_gem_object_put_pages_gtt(struct drm_i915_gem_object *obj)
1665 {
1666         vm_page_t m;
1667         int page_count, i;
1668
1669         BUG_ON(obj->madv == __I915_MADV_PURGED);
1670
1671         if (obj->tiling_mode != I915_TILING_NONE)
1672                 i915_gem_object_save_bit_17_swizzle(obj);
1673         if (obj->madv == I915_MADV_DONTNEED)
1674                 obj->dirty = 0;
1675         page_count = obj->base.size / PAGE_SIZE;
1676         VM_OBJECT_LOCK(obj->base.vm_obj);
1677 #if GEM_PARANOID_CHECK_GTT
1678         i915_gem_assert_pages_not_mapped(obj->base.dev, obj->pages, page_count);
1679 #endif
1680         for (i = 0; i < page_count; i++) {
1681                 m = obj->pages[i];
1682                 if (obj->dirty)
1683                         vm_page_dirty(m);
1684                 if (obj->madv == I915_MADV_WILLNEED)
1685                         vm_page_reference(m);
1686                 vm_page_busy_wait(obj->pages[i], FALSE, "i915gem");
1687                 vm_page_unwire(obj->pages[i], 1);
1688                 vm_page_wakeup(obj->pages[i]);
1689         }
1690         VM_OBJECT_UNLOCK(obj->base.vm_obj);
1691         obj->dirty = 0;
1692         drm_free(obj->pages, M_DRM);
1693         obj->pages = NULL;
1694 }
1695
1696 int
1697 i915_gem_object_put_pages(struct drm_i915_gem_object *obj)
1698 {
1699         const struct drm_i915_gem_object_ops *ops = obj->ops;
1700
1701         if (obj->pages == NULL)
1702                 return 0;
1703
1704         BUG_ON(obj->gtt_space);
1705
1706         if (obj->pages_pin_count)
1707                 return -EBUSY;
1708
1709         /* ->put_pages might need to allocate memory for the bit17 swizzle
1710          * array, hence protect them from being reaped by removing them from gtt
1711          * lists early. */
1712         list_del(&obj->global_list);
1713
1714         ops->put_pages(obj);
1715         obj->pages = NULL;
1716
1717         if (i915_gem_object_is_purgeable(obj))
1718                 i915_gem_object_truncate(obj);
1719
1720         return 0;
1721 }
1722
1723 static long
1724 __i915_gem_shrink(struct drm_i915_private *dev_priv, long target,
1725                   bool purgeable_only)
1726 {
1727         struct drm_i915_gem_object *obj, *next;
1728         long count = 0;
1729
1730         list_for_each_entry_safe(obj, next,
1731                                  &dev_priv->mm.unbound_list,
1732                                  global_list) {
1733 #if 0
1734                 if ((i915_gem_object_is_purgeable(obj) || !purgeable_only) &&
1735                     i915_gem_object_put_pages(obj) == 0) {
1736                         count += obj->base.size >> PAGE_SHIFT;
1737                         if (count >= target)
1738                                 return count;
1739                 }
1740 #endif
1741         }
1742
1743         list_for_each_entry_safe(obj, next,
1744                                  &dev_priv->mm.inactive_list,
1745                                  mm_list) {
1746 #if 0
1747                 if ((i915_gem_object_is_purgeable(obj) || !purgeable_only) &&
1748                     i915_gem_object_unbind(obj) == 0 &&
1749                     i915_gem_object_put_pages(obj) == 0) {
1750                         count += obj->base.size >> PAGE_SHIFT;
1751                         if (count >= target)
1752                                 return count;
1753                 }
1754 #endif
1755         }
1756
1757         return count;
1758 }
1759
1760 static long
1761 i915_gem_purge(struct drm_i915_private *dev_priv, long target)
1762 {
1763         return __i915_gem_shrink(dev_priv, target, true);
1764 }
1765
1766 static int
1767 i915_gem_object_get_pages_gtt(struct drm_i915_gem_object *obj)
1768 {
1769         struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
1770         struct drm_device *dev;
1771         vm_object_t vm_obj;
1772         int page_count, i, j;
1773         struct vm_page *page;
1774
1775         dev = obj->base.dev;
1776         KASSERT(obj->pages == NULL, ("Obj already has pages"));
1777         page_count = obj->base.size / PAGE_SIZE;
1778         obj->pages = kmalloc(page_count * sizeof(vm_page_t), M_DRM,
1779             M_WAITOK);
1780
1781         vm_obj = obj->base.vm_obj;
1782         VM_OBJECT_LOCK(vm_obj);
1783
1784         for (i = 0; i < page_count; i++) {
1785                 page = shmem_read_mapping_page(vm_obj, i);
1786                 if (IS_ERR(page)) {
1787                         i915_gem_purge(dev_priv, page_count);
1788                         goto err_pages;
1789                 }
1790
1791                 obj->pages[i] = page;
1792         }
1793
1794         VM_OBJECT_UNLOCK(vm_obj);
1795         if (i915_gem_object_needs_bit17_swizzle(obj))
1796                 i915_gem_object_do_bit_17_swizzle(obj);
1797
1798         return 0;
1799
1800 err_pages:
1801         for (j = 0; j < i; j++) {
1802                 page = obj->pages[j];
1803                 vm_page_busy_wait(page, FALSE, "i915gem");
1804                 vm_page_unwire(page, 0);
1805                 vm_page_wakeup(page);
1806         }
1807         VM_OBJECT_UNLOCK(vm_obj);
1808         drm_free(obj->pages, M_DRM);
1809         obj->pages = NULL;
1810         return (-EIO);
1811 }
1812
1813 /* Ensure that the associated pages are gathered from the backing storage
1814  * and pinned into our object. i915_gem_object_get_pages() may be called
1815  * multiple times before they are released by a single call to
1816  * i915_gem_object_put_pages() - once the pages are no longer referenced
1817  * either as a result of memory pressure (reaping pages under the shrinker)
1818  * or as the object is itself released.
1819  */
1820 int
1821 i915_gem_object_get_pages(struct drm_i915_gem_object *obj)
1822 {
1823         struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
1824         const struct drm_i915_gem_object_ops *ops = obj->ops;
1825         int ret;
1826
1827         if (obj->pages)
1828                 return 0;
1829
1830         if (obj->madv != I915_MADV_WILLNEED) {
1831                 DRM_ERROR("Attempting to obtain a purgeable object\n");
1832                 return -EINVAL;
1833         }
1834
1835         BUG_ON(obj->pages_pin_count);
1836
1837         ret = ops->get_pages(obj);
1838         if (ret)
1839                 return ret;
1840
1841         list_add_tail(&obj->global_list, &dev_priv->mm.unbound_list);
1842         return 0;
1843 }
1844
1845 void
1846 i915_gem_object_move_to_active(struct drm_i915_gem_object *obj,
1847                                struct intel_ring_buffer *ring)
1848 {
1849         struct drm_device *dev = obj->base.dev;
1850         struct drm_i915_private *dev_priv = dev->dev_private;
1851         u32 seqno = intel_ring_get_seqno(ring);
1852
1853         BUG_ON(ring == NULL);
1854         if (obj->ring != ring && obj->last_write_seqno) {
1855                 /* Keep the seqno relative to the current ring */
1856                 obj->last_write_seqno = seqno;
1857         }
1858         obj->ring = ring;
1859
1860         /* Add a reference if we're newly entering the active list. */
1861         if (!obj->active) {
1862                 drm_gem_object_reference(&obj->base);
1863                 obj->active = 1;
1864         }
1865
1866         /* Move from whatever list we were on to the tail of execution. */
1867         list_move_tail(&obj->mm_list, &dev_priv->mm.active_list);
1868         list_move_tail(&obj->ring_list, &ring->active_list);
1869
1870         obj->last_read_seqno = seqno;
1871
1872         if (obj->fenced_gpu_access) {
1873                 obj->last_fenced_seqno = seqno;
1874
1875                 /* Bump MRU to take account of the delayed flush */
1876                 if (obj->fence_reg != I915_FENCE_REG_NONE) {
1877                         struct drm_i915_fence_reg *reg;
1878
1879                         reg = &dev_priv->fence_regs[obj->fence_reg];
1880                         list_move_tail(&reg->lru_list,
1881                                        &dev_priv->mm.fence_list);
1882                 }
1883         }
1884 }
1885
1886 static void
1887 i915_gem_object_move_to_inactive(struct drm_i915_gem_object *obj)
1888 {
1889         struct drm_device *dev = obj->base.dev;
1890         struct drm_i915_private *dev_priv = dev->dev_private;
1891
1892         BUG_ON(obj->base.write_domain & ~I915_GEM_GPU_DOMAINS);
1893         BUG_ON(!obj->active);
1894
1895         list_move_tail(&obj->mm_list, &dev_priv->mm.inactive_list);
1896
1897         list_del_init(&obj->ring_list);
1898         obj->ring = NULL;
1899
1900         obj->last_read_seqno = 0;
1901         obj->last_write_seqno = 0;
1902         obj->base.write_domain = 0;
1903
1904         obj->last_fenced_seqno = 0;
1905         obj->fenced_gpu_access = false;
1906
1907         obj->active = 0;
1908         drm_gem_object_unreference(&obj->base);
1909
1910         WARN_ON(i915_verify_lists(dev));
1911 }
1912
1913 static int
1914 i915_gem_init_seqno(struct drm_device *dev, u32 seqno)
1915 {
1916         struct drm_i915_private *dev_priv = dev->dev_private;
1917         struct intel_ring_buffer *ring;
1918         int ret, i, j;
1919
1920         /* Carefully retire all requests without writing to the rings */
1921         for_each_ring(ring, dev_priv, i) {
1922                 ret = intel_ring_idle(ring);
1923                 if (ret)
1924                         return ret;
1925         }
1926         i915_gem_retire_requests(dev);
1927
1928         /* Finally reset hw state */
1929         for_each_ring(ring, dev_priv, i) {
1930                 intel_ring_init_seqno(ring, seqno);
1931
1932                 for (j = 0; j < ARRAY_SIZE(ring->sync_seqno); j++)
1933                         ring->sync_seqno[j] = 0;
1934         }
1935
1936         return 0;
1937 }
1938
1939 int i915_gem_set_seqno(struct drm_device *dev, u32 seqno)
1940 {
1941         struct drm_i915_private *dev_priv = dev->dev_private;
1942         int ret;
1943
1944         if (seqno == 0)
1945                 return -EINVAL;
1946
1947         /* HWS page needs to be set less than what we
1948          * will inject to ring
1949          */
1950         ret = i915_gem_init_seqno(dev, seqno - 1);
1951         if (ret)
1952                 return ret;
1953
1954         /* Carefully set the last_seqno value so that wrap
1955          * detection still works
1956          */
1957         dev_priv->next_seqno = seqno;
1958         dev_priv->last_seqno = seqno - 1;
1959         if (dev_priv->last_seqno == 0)
1960                 dev_priv->last_seqno--;
1961
1962         return 0;
1963 }
1964
1965 int
1966 i915_gem_get_seqno(struct drm_device *dev, u32 *seqno)
1967 {
1968         struct drm_i915_private *dev_priv = dev->dev_private;
1969
1970         /* reserve 0 for non-seqno */
1971         if (dev_priv->next_seqno == 0) {
1972                 int ret = i915_gem_init_seqno(dev, 0);
1973                 if (ret)
1974                         return ret;
1975
1976                 dev_priv->next_seqno = 1;
1977         }
1978
1979         *seqno = dev_priv->last_seqno = dev_priv->next_seqno++;
1980         return 0;
1981 }
1982
1983 int __i915_add_request(struct intel_ring_buffer *ring,
1984                        struct drm_file *file,
1985                        struct drm_i915_gem_object *obj,
1986                        u32 *out_seqno)
1987 {
1988         drm_i915_private_t *dev_priv = ring->dev->dev_private;
1989         struct drm_i915_gem_request *request;
1990         u32 request_ring_position, request_start;
1991         int was_empty;
1992         int ret;
1993
1994         request_start = intel_ring_get_tail(ring);
1995         /*
1996          * Emit any outstanding flushes - execbuf can fail to emit the flush
1997          * after having emitted the batchbuffer command. Hence we need to fix
1998          * things up similar to emitting the lazy request. The difference here
1999          * is that the flush _must_ happen before the next request, no matter
2000          * what.
2001          */
2002         ret = intel_ring_flush_all_caches(ring);
2003         if (ret)
2004                 return ret;
2005
2006         request = kmalloc(sizeof(*request), M_DRM, M_WAITOK);
2007         if (request == NULL)
2008                 return -ENOMEM;
2009
2010
2011         /* Record the position of the start of the request so that
2012          * should we detect the updated seqno part-way through the
2013          * GPU processing the request, we never over-estimate the
2014          * position of the head.
2015          */
2016         request_ring_position = intel_ring_get_tail(ring);
2017
2018         ret = ring->add_request(ring);
2019         if (ret) {
2020                 kfree(request);
2021                 return ret;
2022         }
2023
2024         request->seqno = intel_ring_get_seqno(ring);
2025         request->ring = ring;
2026         request->head = request_start;
2027         request->tail = request_ring_position;
2028         request->ctx = ring->last_context;
2029         request->batch_obj = obj;
2030
2031         /* Whilst this request exists, batch_obj will be on the
2032          * active_list, and so will hold the active reference. Only when this
2033          * request is retired will the the batch_obj be moved onto the
2034          * inactive_list and lose its active reference. Hence we do not need
2035          * to explicitly hold another reference here.
2036          */
2037
2038         if (request->ctx)
2039                 i915_gem_context_reference(request->ctx);
2040
2041         request->emitted_jiffies = jiffies;
2042         was_empty = list_empty(&ring->request_list);
2043         list_add_tail(&request->list, &ring->request_list);
2044         request->file_priv = NULL;
2045
2046         if (file) {
2047                 struct drm_i915_file_private *file_priv = file->driver_priv;
2048
2049                 spin_lock(&file_priv->mm.lock);
2050                 request->file_priv = file_priv;
2051                 list_add_tail(&request->client_list,
2052                               &file_priv->mm.request_list);
2053                 spin_unlock(&file_priv->mm.lock);
2054         }
2055
2056         trace_i915_gem_request_add(ring, request->seqno);
2057         ring->outstanding_lazy_request = 0;
2058
2059         if (!dev_priv->mm.suspended) {
2060                 if (i915_enable_hangcheck) {
2061                         mod_timer(&dev_priv->gpu_error.hangcheck_timer,
2062                                   round_jiffies_up(jiffies + DRM_I915_HANGCHECK_JIFFIES));
2063                 }
2064                 if (was_empty) {
2065                         queue_delayed_work(dev_priv->wq,
2066                                            &dev_priv->mm.retire_work,
2067                                            round_jiffies_up_relative(hz));
2068                         intel_mark_busy(dev_priv->dev);
2069                 }
2070         }
2071
2072         if (out_seqno)
2073                 *out_seqno = request->seqno;
2074         return 0;
2075 }
2076
2077 static inline void
2078 i915_gem_request_remove_from_client(struct drm_i915_gem_request *request)
2079 {
2080         struct drm_i915_file_private *file_priv = request->file_priv;
2081
2082         if (!file_priv)
2083                 return;
2084
2085         spin_lock(&file_priv->mm.lock);
2086         if (request->file_priv) {
2087                 list_del(&request->client_list);
2088                 request->file_priv = NULL;
2089         }
2090         spin_unlock(&file_priv->mm.lock);
2091 }
2092
2093 static bool i915_head_inside_object(u32 acthd, struct drm_i915_gem_object *obj)
2094 {
2095         if (acthd >= obj->gtt_offset &&
2096             acthd < obj->gtt_offset + obj->base.size)
2097                 return true;
2098
2099         return false;
2100 }
2101
2102 static bool i915_head_inside_request(const u32 acthd_unmasked,
2103                                      const u32 request_start,
2104                                      const u32 request_end)
2105 {
2106         const u32 acthd = acthd_unmasked & HEAD_ADDR;
2107
2108         if (request_start < request_end) {
2109                 if (acthd >= request_start && acthd < request_end)
2110                         return true;
2111         } else if (request_start > request_end) {
2112                 if (acthd >= request_start || acthd < request_end)
2113                         return true;
2114         }
2115
2116         return false;
2117 }
2118
2119 static bool i915_request_guilty(struct drm_i915_gem_request *request,
2120                                 const u32 acthd, bool *inside)
2121 {
2122         /* There is a possibility that unmasked head address
2123          * pointing inside the ring, matches the batch_obj address range.
2124          * However this is extremely unlikely.
2125          */
2126
2127         if (request->batch_obj) {
2128                 if (i915_head_inside_object(acthd, request->batch_obj)) {
2129                         *inside = true;
2130                         return true;
2131                 }
2132         }
2133
2134         if (i915_head_inside_request(acthd, request->head, request->tail)) {
2135                 *inside = false;
2136                 return true;
2137         }
2138
2139         return false;
2140 }
2141
2142 static void i915_set_reset_status(struct intel_ring_buffer *ring,
2143                                   struct drm_i915_gem_request *request,
2144                                   u32 acthd)
2145 {
2146         struct i915_ctx_hang_stats *hs = NULL;
2147         bool inside, guilty;
2148
2149         /* Innocent until proven guilty */
2150         guilty = false;
2151
2152         if (ring->hangcheck.action != wait &&
2153             i915_request_guilty(request, acthd, &inside)) {
2154                 DRM_ERROR("%s hung %s bo (0x%x ctx %d) at 0x%x\n",
2155                           ring->name,
2156                           inside ? "inside" : "flushing",
2157                           request->batch_obj ?
2158                           request->batch_obj->gtt_offset : 0,
2159                           request->ctx ? request->ctx->id : 0,
2160                           acthd);
2161
2162                 guilty = true;
2163         }
2164
2165         /* If contexts are disabled or this is the default context, use
2166          * file_priv->reset_state
2167          */
2168         if (request->ctx && request->ctx->id != DEFAULT_CONTEXT_ID)
2169                 hs = &request->ctx->hang_stats;
2170         else if (request->file_priv)
2171                 hs = &request->file_priv->hang_stats;
2172
2173         if (hs) {
2174                 if (guilty)
2175                         hs->batch_active++;
2176                 else
2177                         hs->batch_pending++;
2178         }
2179 }
2180
2181 static void i915_gem_free_request(struct drm_i915_gem_request *request)
2182 {
2183         list_del(&request->list);
2184         i915_gem_request_remove_from_client(request);
2185
2186         if (request->ctx)
2187                 i915_gem_context_unreference(request->ctx);
2188
2189         kfree(request);
2190 }
2191
2192 static void i915_gem_reset_ring_lists(struct drm_i915_private *dev_priv,
2193                                       struct intel_ring_buffer *ring)
2194 {
2195         u32 completed_seqno;
2196         u32 acthd;
2197
2198         acthd = intel_ring_get_active_head(ring);
2199         completed_seqno = ring->get_seqno(ring, false);
2200
2201         while (!list_empty(&ring->request_list)) {
2202                 struct drm_i915_gem_request *request;
2203
2204                 request = list_first_entry(&ring->request_list,
2205                                            struct drm_i915_gem_request,
2206                                            list);
2207
2208                 if (request->seqno > completed_seqno)
2209                         i915_set_reset_status(ring, request, acthd);
2210
2211                 i915_gem_free_request(request);
2212         }
2213
2214         while (!list_empty(&ring->active_list)) {
2215                 struct drm_i915_gem_object *obj;
2216
2217                 obj = list_first_entry(&ring->active_list,
2218                                        struct drm_i915_gem_object,
2219                                        ring_list);
2220
2221                 i915_gem_object_move_to_inactive(obj);
2222         }
2223 }
2224
2225 void i915_gem_restore_fences(struct drm_device *dev)
2226 {
2227         struct drm_i915_private *dev_priv = dev->dev_private;
2228         int i;
2229
2230         for (i = 0; i < dev_priv->num_fence_regs; i++) {
2231                 struct drm_i915_fence_reg *reg = &dev_priv->fence_regs[i];
2232
2233                 /*
2234                  * Commit delayed tiling changes if we have an object still
2235                  * attached to the fence, otherwise just clear the fence.
2236                  */
2237                 if (reg->obj) {
2238                         i915_gem_object_update_fence(reg->obj, reg,
2239                                                      reg->obj->tiling_mode);
2240                 } else {
2241                         i915_gem_write_fence(dev, i, NULL);
2242                 }
2243         }
2244 }
2245
2246 void i915_gem_reset(struct drm_device *dev)
2247 {
2248         struct drm_i915_private *dev_priv = dev->dev_private;
2249         struct drm_i915_gem_object *obj;
2250         struct intel_ring_buffer *ring;
2251         int i;
2252
2253         for_each_ring(ring, dev_priv, i)
2254                 i915_gem_reset_ring_lists(dev_priv, ring);
2255
2256         /* Move everything out of the GPU domains to ensure we do any
2257          * necessary invalidation upon reuse.
2258          */
2259         list_for_each_entry(obj,
2260                             &dev_priv->mm.inactive_list,
2261                             mm_list)
2262         {
2263                 obj->base.read_domains &= ~I915_GEM_GPU_DOMAINS;
2264         }
2265
2266         i915_gem_restore_fences(dev);
2267 }
2268
2269 /**
2270  * This function clears the request list as sequence numbers are passed.
2271  */
2272 void
2273 i915_gem_retire_requests_ring(struct intel_ring_buffer *ring)
2274 {
2275         uint32_t seqno;
2276
2277         if (list_empty(&ring->request_list))
2278                 return;
2279
2280         WARN_ON(i915_verify_lists(ring->dev));
2281
2282         seqno = ring->get_seqno(ring, true);
2283
2284         while (!list_empty(&ring->request_list)) {
2285                 struct drm_i915_gem_request *request;
2286
2287                 request = list_first_entry(&ring->request_list,
2288                                            struct drm_i915_gem_request,
2289                                            list);
2290
2291                 if (!i915_seqno_passed(seqno, request->seqno))
2292                         break;
2293
2294                 trace_i915_gem_request_retire(ring, request->seqno);
2295                 /* We know the GPU must have read the request to have
2296                  * sent us the seqno + interrupt, so use the position
2297                  * of tail of the request to update the last known position
2298                  * of the GPU head.
2299                  */
2300                 ring->last_retired_head = request->tail;
2301
2302                 i915_gem_free_request(request);
2303         }
2304
2305         /* Move any buffers on the active list that are no longer referenced
2306          * by the ringbuffer to the flushing/inactive lists as appropriate.
2307          */
2308         while (!list_empty(&ring->active_list)) {
2309                 struct drm_i915_gem_object *obj;
2310
2311                 obj = list_first_entry(&ring->active_list,
2312                                       struct drm_i915_gem_object,
2313                                       ring_list);
2314
2315                 if (!i915_seqno_passed(seqno, obj->last_read_seqno))
2316                         break;
2317
2318                 i915_gem_object_move_to_inactive(obj);
2319         }
2320
2321         if (unlikely(ring->trace_irq_seqno &&
2322                      i915_seqno_passed(seqno, ring->trace_irq_seqno))) {
2323                 ring->irq_put(ring);
2324                 ring->trace_irq_seqno = 0;
2325         }
2326
2327 }
2328
2329 void
2330 i915_gem_retire_requests(struct drm_device *dev)
2331 {
2332         drm_i915_private_t *dev_priv = dev->dev_private;
2333         struct intel_ring_buffer *ring;
2334         int i;
2335
2336         for_each_ring(ring, dev_priv, i)
2337                 i915_gem_retire_requests_ring(ring);
2338 }
2339
2340 static void
2341 i915_gem_retire_work_handler(struct work_struct *work)
2342 {
2343         drm_i915_private_t *dev_priv;
2344         struct drm_device *dev;
2345         struct intel_ring_buffer *ring;
2346         bool idle;
2347         int i;
2348
2349         dev_priv = container_of(work, drm_i915_private_t,
2350                                 mm.retire_work.work);
2351         dev = dev_priv->dev;
2352
2353         /* Come back later if the device is busy... */
2354         if (lockmgr(&dev->struct_mutex, LK_EXCLUSIVE|LK_NOWAIT)) {
2355                 queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work,
2356                                    round_jiffies_up_relative(hz));
2357                 return;
2358         }
2359
2360         i915_gem_retire_requests(dev);
2361
2362         /* Send a periodic flush down the ring so we don't hold onto GEM
2363          * objects indefinitely.
2364          */
2365         idle = true;
2366         for_each_ring(ring, dev_priv, i) {
2367                 if (ring->gpu_caches_dirty)
2368                         i915_add_request(ring, NULL);
2369
2370                 idle &= list_empty(&ring->request_list);
2371         }
2372
2373         if (!dev_priv->mm.suspended && !idle)
2374                 queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work,
2375                                    round_jiffies_up_relative(hz));
2376         if (idle)
2377                 intel_mark_idle(dev);
2378
2379         mutex_unlock(&dev->struct_mutex);
2380 }
2381 /**
2382  * Ensures that an object will eventually get non-busy by flushing any required
2383  * write domains, emitting any outstanding lazy request and retiring and
2384  * completed requests.
2385  */
2386 static int
2387 i915_gem_object_flush_active(struct drm_i915_gem_object *obj)
2388 {
2389         int ret;
2390
2391         if (obj->active) {
2392                 ret = i915_gem_check_olr(obj->ring, obj->last_read_seqno);
2393                 if (ret)
2394                         return ret;
2395
2396                 i915_gem_retire_requests_ring(obj->ring);
2397         }
2398
2399         return 0;
2400 }
2401
2402 /**
2403  * i915_gem_wait_ioctl - implements DRM_IOCTL_I915_GEM_WAIT
2404  * @DRM_IOCTL_ARGS: standard ioctl arguments
2405  *
2406  * Returns 0 if successful, else an error is returned with the remaining time in
2407  * the timeout parameter.
2408  *  -ETIME: object is still busy after timeout
2409  *  -ERESTARTSYS: signal interrupted the wait
2410  *  -ENONENT: object doesn't exist
2411  * Also possible, but rare:
2412  *  -EAGAIN: GPU wedged
2413  *  -ENOMEM: damn
2414  *  -ENODEV: Internal IRQ fail
2415  *  -E?: The add request failed
2416  *
2417  * The wait ioctl with a timeout of 0 reimplements the busy ioctl. With any
2418  * non-zero timeout parameter the wait ioctl will wait for the given number of
2419  * nanoseconds on an object becoming unbusy. Since the wait itself does so
2420  * without holding struct_mutex the object may become re-busied before this
2421  * function completes. A similar but shorter * race condition exists in the busy
2422  * ioctl
2423  */
2424 int
2425 i915_gem_wait_ioctl(struct drm_device *dev, void *data, struct drm_file *file)
2426 {
2427         drm_i915_private_t *dev_priv = dev->dev_private;
2428         struct drm_i915_gem_wait *args = data;
2429         struct drm_i915_gem_object *obj;
2430         struct intel_ring_buffer *ring = NULL;
2431         struct timespec timeout_stack, *timeout = NULL;
2432         unsigned reset_counter;
2433         u32 seqno = 0;
2434         int ret = 0;
2435
2436         if (args->timeout_ns >= 0) {
2437                 timeout_stack = ns_to_timespec(args->timeout_ns);
2438                 timeout = &timeout_stack;
2439         }
2440
2441         ret = i915_mutex_lock_interruptible(dev);
2442         if (ret)
2443                 return ret;
2444
2445         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->bo_handle));
2446         if (&obj->base == NULL) {
2447                 mutex_unlock(&dev->struct_mutex);
2448                 return -ENOENT;
2449         }
2450
2451         /* Need to make sure the object gets inactive eventually. */
2452         ret = i915_gem_object_flush_active(obj);
2453         if (ret)
2454                 goto out;
2455
2456         if (obj->active) {
2457                 seqno = obj->last_read_seqno;
2458                 ring = obj->ring;
2459         }
2460
2461         if (seqno == 0)
2462                  goto out;
2463
2464         /* Do this after OLR check to make sure we make forward progress polling
2465          * on this IOCTL with a 0 timeout (like busy ioctl)
2466          */
2467         if (!args->timeout_ns) {
2468                 ret = -ETIMEDOUT;
2469                 goto out;
2470         }
2471
2472         drm_gem_object_unreference(&obj->base);
2473         reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
2474         mutex_unlock(&dev->struct_mutex);
2475
2476         ret = __wait_seqno(ring, seqno, reset_counter, true, timeout);
2477         if (timeout)
2478                 args->timeout_ns = timespec_to_ns(timeout);
2479         return ret;
2480
2481 out:
2482         drm_gem_object_unreference(&obj->base);
2483         mutex_unlock(&dev->struct_mutex);
2484         return ret;
2485 }
2486
2487 /**
2488  * i915_gem_object_sync - sync an object to a ring.
2489  *
2490  * @obj: object which may be in use on another ring.
2491  * @to: ring we wish to use the object on. May be NULL.
2492  *
2493  * This code is meant to abstract object synchronization with the GPU.
2494  * Calling with NULL implies synchronizing the object with the CPU
2495  * rather than a particular GPU ring.
2496  *
2497  * Returns 0 if successful, else propagates up the lower layer error.
2498  */
2499 int
2500 i915_gem_object_sync(struct drm_i915_gem_object *obj,
2501                      struct intel_ring_buffer *to)
2502 {
2503         struct intel_ring_buffer *from = obj->ring;
2504         u32 seqno;
2505         int ret, idx;
2506
2507         if (from == NULL || to == from)
2508                 return 0;
2509
2510         if (to == NULL || !i915_semaphore_is_enabled(obj->base.dev))
2511                 return i915_gem_object_wait_rendering(obj, false);
2512
2513         idx = intel_ring_sync_index(from, to);
2514
2515         seqno = obj->last_read_seqno;
2516         if (seqno <= from->sync_seqno[idx])
2517                 return 0;
2518
2519         ret = i915_gem_check_olr(obj->ring, seqno);
2520         if (ret)
2521                 return ret;
2522
2523         ret = to->sync_to(to, from, seqno);
2524         if (!ret)
2525                 /* We use last_read_seqno because sync_to()
2526                  * might have just caused seqno wrap under
2527                  * the radar.
2528                  */
2529                 from->sync_seqno[idx] = obj->last_read_seqno;
2530
2531         return ret;
2532 }
2533
2534 static void i915_gem_object_finish_gtt(struct drm_i915_gem_object *obj)
2535 {
2536         u32 old_write_domain, old_read_domains;
2537
2538         /* Force a pagefault for domain tracking on next user access */
2539         i915_gem_release_mmap(obj);
2540
2541         if ((obj->base.read_domains & I915_GEM_DOMAIN_GTT) == 0)
2542                 return;
2543
2544         /* Wait for any direct GTT access to complete */
2545         cpu_mfence();
2546
2547         old_read_domains = obj->base.read_domains;
2548         old_write_domain = obj->base.write_domain;
2549
2550         obj->base.read_domains &= ~I915_GEM_DOMAIN_GTT;
2551         obj->base.write_domain &= ~I915_GEM_DOMAIN_GTT;
2552
2553         trace_i915_gem_object_change_domain(obj,
2554                                             old_read_domains,
2555                                             old_write_domain);
2556 }
2557
2558 /**
2559  * Unbinds an object from the GTT aperture.
2560  */
2561 int
2562 i915_gem_object_unbind(struct drm_i915_gem_object *obj)
2563 {
2564         drm_i915_private_t *dev_priv = obj->base.dev->dev_private;
2565         int ret;
2566
2567         if (obj->gtt_space == NULL)
2568                 return 0;
2569
2570         if (obj->pin_count)
2571                 return -EBUSY;
2572
2573         BUG_ON(obj->pages == NULL);
2574
2575         ret = i915_gem_object_finish_gpu(obj);
2576         if (ret)
2577                 return ret;
2578         /* Continue on if we fail due to EIO, the GPU is hung so we
2579          * should be safe and we need to cleanup or else we might
2580          * cause memory corruption through use-after-free.
2581          */
2582
2583         i915_gem_object_finish_gtt(obj);
2584
2585         /* Move the object to the CPU domain to ensure that
2586          * any possible CPU writes while it's not in the GTT
2587          * are flushed when we go to remap it.
2588          */
2589         if (ret == 0)
2590                 ret = i915_gem_object_set_to_cpu_domain(obj, 1);
2591         if (ret == -ERESTARTSYS)
2592                 return ret;
2593         if (ret) {
2594                 /* In the event of a disaster, abandon all caches and
2595                  * hope for the best.
2596                  */
2597                 i915_gem_clflush_object(obj);
2598                 obj->base.read_domains = obj->base.write_domain = I915_GEM_DOMAIN_CPU;
2599         }
2600
2601         /* release the fence reg _after_ flushing */
2602         ret = i915_gem_object_put_fence(obj);
2603         if (ret)
2604                 return ret;
2605
2606         trace_i915_gem_object_unbind(obj);
2607
2608         if (obj->has_global_gtt_mapping)
2609                 i915_gem_gtt_unbind_object(obj);
2610         if (obj->has_aliasing_ppgtt_mapping) {
2611                 i915_ppgtt_unbind_object(dev_priv->mm.aliasing_ppgtt, obj);
2612                 obj->has_aliasing_ppgtt_mapping = 0;
2613         }
2614         i915_gem_gtt_finish_object(obj);
2615
2616         i915_gem_object_put_pages_gtt(obj);
2617
2618         list_del_init(&obj->global_list);
2619         list_del_init(&obj->mm_list);
2620         /* Avoid an unnecessary call to unbind on rebind. */
2621         obj->map_and_fenceable = true;
2622
2623         drm_mm_put_block(obj->gtt_space);
2624         obj->gtt_space = NULL;
2625         obj->gtt_offset = 0;
2626
2627         if (i915_gem_object_is_purgeable(obj))
2628                 i915_gem_object_truncate(obj);
2629
2630         return ret;
2631 }
2632
2633 int i915_gpu_idle(struct drm_device *dev)
2634 {
2635         drm_i915_private_t *dev_priv = dev->dev_private;
2636         struct intel_ring_buffer *ring;
2637         int ret, i;
2638
2639         /* Flush everything onto the inactive list. */
2640         for_each_ring(ring, dev_priv, i) {
2641                 ret = i915_switch_context(ring, NULL, DEFAULT_CONTEXT_ID);
2642                 if (ret)
2643                         return ret;
2644
2645                 ret = intel_ring_idle(ring);
2646                 if (ret)
2647                         return ret;
2648         }
2649
2650         return 0;
2651 }
2652
2653 static void i965_write_fence_reg(struct drm_device *dev, int reg,
2654                                  struct drm_i915_gem_object *obj)
2655 {
2656         drm_i915_private_t *dev_priv = dev->dev_private;
2657         int fence_reg;
2658         int fence_pitch_shift;
2659
2660         if (INTEL_INFO(dev)->gen >= 6) {
2661                 fence_reg = FENCE_REG_SANDYBRIDGE_0;
2662                 fence_pitch_shift = SANDYBRIDGE_FENCE_PITCH_SHIFT;
2663         } else {
2664                 fence_reg = FENCE_REG_965_0;
2665                 fence_pitch_shift = I965_FENCE_PITCH_SHIFT;
2666         }
2667
2668         fence_reg += reg * 8;
2669
2670         /* To w/a incoherency with non-atomic 64-bit register updates,
2671          * we split the 64-bit update into two 32-bit writes. In order
2672          * for a partial fence not to be evaluated between writes, we
2673          * precede the update with write to turn off the fence register,
2674          * and only enable the fence as the last step.
2675          *
2676          * For extra levels of paranoia, we make sure each step lands
2677          * before applying the next step.
2678          */
2679         I915_WRITE(fence_reg, 0);
2680         POSTING_READ(fence_reg);
2681
2682         if (obj) {
2683                 u32 size = obj->gtt_space->size;
2684                 uint64_t val;
2685
2686                 val = (uint64_t)((obj->gtt_offset + size - 4096) &
2687                                  0xfffff000) << 32;
2688                 val |= obj->gtt_offset & 0xfffff000;
2689                 val |= (uint64_t)((obj->stride / 128) - 1) << fence_pitch_shift;
2690                 if (obj->tiling_mode == I915_TILING_Y)
2691                         val |= 1 << I965_FENCE_TILING_Y_SHIFT;
2692                 val |= I965_FENCE_REG_VALID;
2693
2694                 I915_WRITE(fence_reg + 4, val >> 32);
2695                 POSTING_READ(fence_reg + 4);
2696
2697                 I915_WRITE(fence_reg + 0, val);
2698                 POSTING_READ(fence_reg);
2699         } else {
2700                 I915_WRITE(fence_reg + 4, 0);
2701                 POSTING_READ(fence_reg + 4);
2702         }
2703 }
2704
2705 static void i915_write_fence_reg(struct drm_device *dev, int reg,
2706                                  struct drm_i915_gem_object *obj)
2707 {
2708         drm_i915_private_t *dev_priv = dev->dev_private;
2709         u32 val;
2710
2711         if (obj) {
2712                 u32 size = obj->gtt_space->size;
2713                 int pitch_val;
2714                 int tile_width;
2715
2716                 WARN((obj->gtt_offset & ~I915_FENCE_START_MASK) ||
2717                      (size & -size) != size ||
2718                      (obj->gtt_offset & (size - 1)),
2719                      "object 0x%08x [fenceable? %d] not 1M or pot-size (0x%08x) aligned\n",
2720                      obj->gtt_offset, obj->map_and_fenceable, size);
2721
2722                 if (obj->tiling_mode == I915_TILING_Y && HAS_128_BYTE_Y_TILING(dev))
2723                         tile_width = 128;
2724                 else
2725                         tile_width = 512;
2726
2727                 /* Note: pitch better be a power of two tile widths */
2728                 pitch_val = obj->stride / tile_width;
2729                 pitch_val = ffs(pitch_val) - 1;
2730
2731                 val = obj->gtt_offset;
2732                 if (obj->tiling_mode == I915_TILING_Y)
2733                         val |= 1 << I830_FENCE_TILING_Y_SHIFT;
2734                 val |= I915_FENCE_SIZE_BITS(size);
2735                 val |= pitch_val << I830_FENCE_PITCH_SHIFT;
2736                 val |= I830_FENCE_REG_VALID;
2737         } else
2738                 val = 0;
2739
2740         if (reg < 8)
2741                 reg = FENCE_REG_830_0 + reg * 4;
2742         else
2743                 reg = FENCE_REG_945_8 + (reg - 8) * 4;
2744
2745         I915_WRITE(reg, val);
2746         POSTING_READ(reg);
2747 }
2748
2749 static void i830_write_fence_reg(struct drm_device *dev, int reg,
2750                                 struct drm_i915_gem_object *obj)
2751 {
2752         drm_i915_private_t *dev_priv = dev->dev_private;
2753         uint32_t val;
2754
2755         if (obj) {
2756                 u32 size = obj->gtt_space->size;
2757                 uint32_t pitch_val;
2758
2759                 WARN((obj->gtt_offset & ~I830_FENCE_START_MASK) ||
2760                      (size & -size) != size ||
2761                      (obj->gtt_offset & (size - 1)),
2762                      "object 0x%08x not 512K or pot-size 0x%08x aligned\n",
2763                      obj->gtt_offset, size);
2764
2765                 pitch_val = obj->stride / 128;
2766                 pitch_val = ffs(pitch_val) - 1;
2767
2768                 val = obj->gtt_offset;
2769                 if (obj->tiling_mode == I915_TILING_Y)
2770                         val |= 1 << I830_FENCE_TILING_Y_SHIFT;
2771                 val |= I830_FENCE_SIZE_BITS(size);
2772                 val |= pitch_val << I830_FENCE_PITCH_SHIFT;
2773                 val |= I830_FENCE_REG_VALID;
2774         } else
2775                 val = 0;
2776
2777         I915_WRITE(FENCE_REG_830_0 + reg * 4, val);
2778         POSTING_READ(FENCE_REG_830_0 + reg * 4);
2779 }
2780
2781 inline static bool i915_gem_object_needs_mb(struct drm_i915_gem_object *obj)
2782 {
2783         return obj && obj->base.read_domains & I915_GEM_DOMAIN_GTT;
2784 }
2785
2786 static void i915_gem_write_fence(struct drm_device *dev, int reg,
2787                                  struct drm_i915_gem_object *obj)
2788 {
2789         struct drm_i915_private *dev_priv = dev->dev_private;
2790
2791         /* Ensure that all CPU reads are completed before installing a fence
2792          * and all writes before removing the fence.
2793          */
2794         if (i915_gem_object_needs_mb(dev_priv->fence_regs[reg].obj))
2795                 cpu_mfence();
2796
2797         WARN(obj && (!obj->stride || !obj->tiling_mode),
2798              "bogus fence setup with stride: 0x%x, tiling mode: %i\n",
2799              obj->stride, obj->tiling_mode);
2800
2801         switch (INTEL_INFO(dev)->gen) {
2802         case 7:
2803         case 6:
2804         case 5:
2805         case 4: i965_write_fence_reg(dev, reg, obj); break;
2806         case 3: i915_write_fence_reg(dev, reg, obj); break;
2807         case 2: i830_write_fence_reg(dev, reg, obj); break;
2808         default: BUG();
2809         }
2810
2811         /* And similarly be paranoid that no direct access to this region
2812          * is reordered to before the fence is installed.
2813          */
2814         if (i915_gem_object_needs_mb(obj))
2815                 cpu_mfence();
2816 }
2817
2818 static inline int fence_number(struct drm_i915_private *dev_priv,
2819                                struct drm_i915_fence_reg *fence)
2820 {
2821         return fence - dev_priv->fence_regs;
2822 }
2823
2824 static void i915_gem_object_update_fence(struct drm_i915_gem_object *obj,
2825                                          struct drm_i915_fence_reg *fence,
2826                                          bool enable)
2827 {
2828         struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
2829         int reg = fence_number(dev_priv, fence);
2830
2831         i915_gem_write_fence(obj->base.dev, reg, enable ? obj : NULL);
2832
2833         if (enable) {
2834                 obj->fence_reg = reg;
2835                 fence->obj = obj;
2836                 list_move_tail(&fence->lru_list, &dev_priv->mm.fence_list);
2837         } else {
2838                 obj->fence_reg = I915_FENCE_REG_NONE;
2839                 fence->obj = NULL;
2840                 list_del_init(&fence->lru_list);
2841         }
2842         obj->fence_dirty = false;
2843 }
2844
2845 static int
2846 i915_gem_object_wait_fence(struct drm_i915_gem_object *obj)
2847 {
2848         if (obj->last_fenced_seqno) {
2849                 int ret = i915_wait_seqno(obj->ring, obj->last_fenced_seqno);
2850                 if (ret)
2851                         return ret;
2852
2853                 obj->last_fenced_seqno = 0;
2854         }
2855
2856         obj->fenced_gpu_access = false;
2857         return 0;
2858 }
2859
2860 int
2861 i915_gem_object_put_fence(struct drm_i915_gem_object *obj)
2862 {
2863         struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
2864         struct drm_i915_fence_reg *fence;
2865         int ret;
2866
2867         ret = i915_gem_object_wait_fence(obj);
2868         if (ret)
2869                 return ret;
2870
2871         if (obj->fence_reg == I915_FENCE_REG_NONE)
2872                 return 0;
2873
2874         fence = &dev_priv->fence_regs[obj->fence_reg];
2875
2876         i915_gem_object_fence_lost(obj);
2877         i915_gem_object_update_fence(obj, fence, false);
2878
2879         return 0;
2880 }
2881
2882 static struct drm_i915_fence_reg *
2883 i915_find_fence_reg(struct drm_device *dev)
2884 {
2885         struct drm_i915_private *dev_priv = dev->dev_private;
2886         struct drm_i915_fence_reg *reg, *avail;
2887         int i;
2888
2889         /* First try to find a free reg */
2890         avail = NULL;
2891         for (i = dev_priv->fence_reg_start; i < dev_priv->num_fence_regs; i++) {
2892                 reg = &dev_priv->fence_regs[i];
2893                 if (!reg->obj)
2894                         return reg;
2895
2896                 if (!reg->pin_count)
2897                         avail = reg;
2898         }
2899
2900         if (avail == NULL)
2901                 return NULL;
2902
2903         /* None available, try to steal one or wait for a user to finish */
2904         list_for_each_entry(reg, &dev_priv->mm.fence_list, lru_list) {
2905                 if (reg->pin_count)
2906                         continue;
2907
2908                 return reg;
2909         }
2910
2911         return NULL;
2912 }
2913
2914 /**
2915  * i915_gem_object_get_fence - set up fencing for an object
2916  * @obj: object to map through a fence reg
2917  *
2918  * When mapping objects through the GTT, userspace wants to be able to write
2919  * to them without having to worry about swizzling if the object is tiled.
2920  * This function walks the fence regs looking for a free one for @obj,
2921  * stealing one if it can't find any.
2922  *
2923  * It then sets up the reg based on the object's properties: address, pitch
2924  * and tiling format.
2925  *
2926  * For an untiled surface, this removes any existing fence.
2927  */
2928 int
2929 i915_gem_object_get_fence(struct drm_i915_gem_object *obj)
2930 {
2931         struct drm_device *dev = obj->base.dev;
2932         struct drm_i915_private *dev_priv = dev->dev_private;
2933         bool enable = obj->tiling_mode != I915_TILING_NONE;
2934         struct drm_i915_fence_reg *reg;
2935         int ret;
2936
2937         /* Have we updated the tiling parameters upon the object and so
2938          * will need to serialise the write to the associated fence register?
2939          */
2940         if (obj->fence_dirty) {
2941                 ret = i915_gem_object_wait_fence(obj);
2942                 if (ret)
2943                         return ret;
2944         }
2945
2946         /* Just update our place in the LRU if our fence is getting reused. */
2947         if (obj->fence_reg != I915_FENCE_REG_NONE) {
2948                 reg = &dev_priv->fence_regs[obj->fence_reg];
2949                 if (!obj->fence_dirty) {
2950                         list_move_tail(&reg->lru_list,
2951                                        &dev_priv->mm.fence_list);
2952                         return 0;
2953                 }
2954         } else if (enable) {
2955                 reg = i915_find_fence_reg(dev);
2956                 if (reg == NULL)
2957                         return -EDEADLK;
2958
2959                 if (reg->obj) {
2960                         struct drm_i915_gem_object *old = reg->obj;
2961
2962                         ret = i915_gem_object_wait_fence(old);
2963                         if (ret)
2964                                 return ret;
2965
2966                         i915_gem_object_fence_lost(old);
2967                 }
2968         } else
2969                 return 0;
2970
2971         i915_gem_object_update_fence(obj, reg, enable);
2972
2973         return 0;
2974 }
2975
2976 static bool i915_gem_valid_gtt_space(struct drm_device *dev,
2977                                      struct drm_mm_node *gtt_space,
2978                                      unsigned long cache_level)
2979 {
2980         struct drm_mm_node *other;
2981
2982         /* On non-LLC machines we have to be careful when putting differing
2983          * types of snoopable memory together to avoid the prefetcher
2984          * crossing memory domains and dying.
2985          */
2986         if (HAS_LLC(dev))
2987                 return true;
2988
2989         if (gtt_space == NULL)
2990                 return true;
2991
2992         if (list_empty(&gtt_space->node_list))
2993                 return true;
2994
2995         other = list_entry(gtt_space->node_list.prev, struct drm_mm_node, node_list);
2996         if (other->allocated && !other->hole_follows && other->color != cache_level)
2997                 return false;
2998
2999         other = list_entry(gtt_space->node_list.next, struct drm_mm_node, node_list);
3000         if (other->allocated && !gtt_space->hole_follows && other->color != cache_level)
3001                 return false;
3002
3003         return true;
3004 }
3005
3006 static void i915_gem_verify_gtt(struct drm_device *dev)
3007 {
3008 #if WATCH_GTT
3009         struct drm_i915_private *dev_priv = dev->dev_private;
3010         struct drm_i915_gem_object *obj;
3011         int err = 0;
3012
3013         list_for_each_entry(obj, &dev_priv->mm.global_list, global_list) {
3014                 if (obj->gtt_space == NULL) {
3015                         printk(KERN_ERR "object found on GTT list with no space reserved\n");
3016                         err++;
3017                         continue;
3018                 }
3019
3020                 if (obj->cache_level != obj->gtt_space->color) {
3021                         printk(KERN_ERR "object reserved space [%08lx, %08lx] with wrong color, cache_level=%x, color=%lx\n",
3022                                obj->gtt_space->start,
3023                                obj->gtt_space->start + obj->gtt_space->size,
3024                                obj->cache_level,
3025                                obj->gtt_space->color);
3026                         err++;
3027                         continue;
3028                 }
3029
3030                 if (!i915_gem_valid_gtt_space(dev,
3031                                               obj->gtt_space,
3032                                               obj->cache_level)) {
3033                         printk(KERN_ERR "invalid GTT space found at [%08lx, %08lx] - color=%x\n",
3034                                obj->gtt_space->start,
3035                                obj->gtt_space->start + obj->gtt_space->size,
3036                                obj->cache_level);
3037                         err++;
3038                         continue;
3039                 }
3040         }
3041
3042         WARN_ON(err);
3043 #endif
3044 }
3045
3046 /**
3047  * Finds free space in the GTT aperture and binds the object there.
3048  */
3049 static int
3050 i915_gem_object_bind_to_gtt(struct drm_i915_gem_object *obj,
3051                             unsigned alignment,
3052                             bool map_and_fenceable,
3053                             bool nonblocking)
3054 {
3055         struct drm_device *dev = obj->base.dev;
3056         drm_i915_private_t *dev_priv = dev->dev_private;
3057         struct drm_mm_node *node;
3058         u32 size, fence_size, fence_alignment, unfenced_alignment;
3059         bool mappable, fenceable;
3060         size_t gtt_max = map_and_fenceable ?
3061                 dev_priv->gtt.mappable_end : dev_priv->gtt.total;
3062         int ret;
3063
3064         fence_size = i915_gem_get_gtt_size(dev,
3065                                            obj->base.size,
3066                                            obj->tiling_mode);
3067         fence_alignment = i915_gem_get_gtt_alignment(dev,
3068                                                      obj->base.size,
3069                                                      obj->tiling_mode, true);
3070         unfenced_alignment =
3071                 i915_gem_get_gtt_alignment(dev,
3072                                                     obj->base.size,
3073                                                     obj->tiling_mode, false);
3074
3075         if (alignment == 0)
3076                 alignment = map_and_fenceable ? fence_alignment :
3077                                                 unfenced_alignment;
3078         if (map_and_fenceable && alignment & (fence_alignment - 1)) {
3079                 DRM_ERROR("Invalid object alignment requested %u\n", alignment);
3080                 return -EINVAL;
3081         }
3082
3083         size = map_and_fenceable ? fence_size : obj->base.size;
3084
3085         /* If the object is bigger than the entire aperture, reject it early
3086          * before evicting everything in a vain attempt to find space.
3087          */
3088         if (obj->base.size > gtt_max) {
3089                 DRM_ERROR("Attempting to bind an object larger than the aperture: object=%zd > %s aperture=%zu\n",
3090                           obj->base.size,
3091                           map_and_fenceable ? "mappable" : "total",
3092                           gtt_max);
3093                 return -E2BIG;
3094         }
3095
3096  search_free:
3097         if (map_and_fenceable)
3098                 node = drm_mm_search_free_in_range_color(&dev_priv->mm.gtt_space,
3099                                                           size, alignment, obj->cache_level,
3100                                                           0, dev_priv->gtt.mappable_end,
3101                                                           false);
3102         else
3103                 node = drm_mm_search_free_color(&dev_priv->mm.gtt_space,
3104                                                       size, alignment, obj->cache_level,
3105                                                       false);
3106         if (node != NULL) {
3107                 if (map_and_fenceable)
3108                         obj->gtt_space =
3109                                 drm_mm_get_block_range_generic(node,
3110                                                                size, alignment, obj->cache_level,
3111                                                                0, dev_priv->gtt.mappable_end,
3112                                                                false);
3113                 else
3114                         obj->gtt_space =
3115                                 drm_mm_get_block_generic(node,
3116                                                          size, alignment, obj->cache_level,
3117                                                          false);
3118         }
3119         if (obj->gtt_space == NULL) {
3120                 ret = i915_gem_evict_something(dev, size, alignment,
3121                                                obj->cache_level,
3122                                                map_and_fenceable,
3123                                                nonblocking);
3124                 if (ret)
3125                         return ret;
3126
3127                 goto search_free;
3128         }
3129
3130         /*
3131          * NOTE: i915_gem_object_get_pages_gtt() cannot
3132          *       return ENOMEM, since we used VM_ALLOC_RETRY.
3133          */
3134         ret = i915_gem_object_get_pages_gtt(obj);
3135         if (ret != 0) {
3136                 drm_mm_put_block(obj->gtt_space);
3137                 obj->gtt_space = NULL;
3138                 return ret;
3139         }
3140
3141         i915_gem_gtt_bind_object(obj, obj->cache_level);
3142         if (ret != 0) {
3143                 i915_gem_object_put_pages_gtt(obj);
3144                 drm_mm_put_block(obj->gtt_space);
3145                 obj->gtt_space = NULL;
3146                 if (i915_gem_evict_everything(dev))
3147                         return (ret);
3148                 goto search_free;
3149         }
3150
3151         list_add_tail(&obj->global_list, &dev_priv->mm.bound_list);
3152         list_add_tail(&obj->mm_list, &dev_priv->mm.inactive_list);
3153
3154         obj->gtt_offset = obj->gtt_space->start;
3155
3156         fenceable =
3157                 obj->gtt_space->size == fence_size &&
3158                 (obj->gtt_space->start & (fence_alignment - 1)) == 0;
3159
3160         mappable =
3161                 obj->gtt_offset + obj->base.size <= dev_priv->gtt.mappable_end;
3162
3163         obj->map_and_fenceable = mappable && fenceable;
3164
3165         trace_i915_gem_object_bind(obj, map_and_fenceable);
3166         i915_gem_verify_gtt(dev);
3167         return 0;
3168 }
3169
3170 void
3171 i915_gem_clflush_object(struct drm_i915_gem_object *obj)
3172 {
3173
3174         /* If we don't have a page list set up, then we're not pinned
3175          * to GPU, and we can ignore the cache flush because it'll happen
3176          * again at bind time.
3177          */
3178         if (obj->pages == NULL)
3179                 return;
3180
3181         /*
3182          * Stolen memory is always coherent with the GPU as it is explicitly
3183          * marked as wc by the system, or the system is cache-coherent.
3184          */
3185         if (obj->stolen)
3186                 return;
3187
3188         /* If the GPU is snooping the contents of the CPU cache,
3189          * we do not need to manually clear the CPU cache lines.  However,
3190          * the caches are only snooped when the render cache is
3191          * flushed/invalidated.  As we always have to emit invalidations
3192          * and flushes when moving into and out of the RENDER domain, correct
3193          * snooping behaviour occurs naturally as the result of our domain
3194          * tracking.
3195          */
3196         if (obj->cache_level != I915_CACHE_NONE)
3197                 return;
3198
3199         trace_i915_gem_object_clflush(obj);
3200
3201         drm_clflush_pages(obj->pages, obj->base.size / PAGE_SIZE);
3202 }
3203
3204 /** Flushes the GTT write domain for the object if it's dirty. */
3205 static void
3206 i915_gem_object_flush_gtt_write_domain(struct drm_i915_gem_object *obj)
3207 {
3208         uint32_t old_write_domain;
3209
3210         if (obj->base.write_domain != I915_GEM_DOMAIN_GTT)
3211                 return;
3212
3213         /* No actual flushing is required for the GTT write domain.  Writes
3214          * to it immediately go to main memory as far as we know, so there's
3215          * no chipset flush.  It also doesn't land in render cache.
3216          *
3217          * However, we do have to enforce the order so that all writes through
3218          * the GTT land before any writes to the device, such as updates to
3219          * the GATT itself.
3220          */
3221         cpu_sfence();
3222
3223         old_write_domain = obj->base.write_domain;
3224         obj->base.write_domain = 0;
3225
3226         trace_i915_gem_object_change_domain(obj,
3227                                             obj->base.read_domains,
3228                                             old_write_domain);
3229 }
3230
3231 /** Flushes the CPU write domain for the object if it's dirty. */
3232 static void
3233 i915_gem_object_flush_cpu_write_domain(struct drm_i915_gem_object *obj)
3234 {
3235         uint32_t old_write_domain;
3236
3237         if (obj->base.write_domain != I915_GEM_DOMAIN_CPU)
3238                 return;
3239
3240         i915_gem_clflush_object(obj);
3241         i915_gem_chipset_flush(obj->base.dev);
3242         old_write_domain = obj->base.write_domain;
3243         obj->base.write_domain = 0;
3244
3245         trace_i915_gem_object_change_domain(obj,
3246                                             obj->base.read_domains,
3247                                             old_write_domain);
3248 }
3249
3250 /**
3251  * Moves a single object to the GTT read, and possibly write domain.
3252  *
3253  * This function returns when the move is complete, including waiting on
3254  * flushes to occur.
3255  */
3256 int
3257 i915_gem_object_set_to_gtt_domain(struct drm_i915_gem_object *obj, bool write)
3258 {
3259         drm_i915_private_t *dev_priv = obj->base.dev->dev_private;
3260         uint32_t old_write_domain, old_read_domains;
3261         int ret;
3262
3263         /* Not valid to be called on unbound objects. */
3264         if (obj->gtt_space == NULL)
3265                 return -EINVAL;
3266
3267         if (obj->base.write_domain == I915_GEM_DOMAIN_GTT)
3268                 return 0;
3269
3270         ret = i915_gem_object_wait_rendering(obj, !write);
3271         if (ret)
3272                 return ret;
3273
3274         i915_gem_object_flush_cpu_write_domain(obj);
3275
3276         /* Serialise direct access to this object with the barriers for
3277          * coherent writes from the GPU, by effectively invalidating the
3278          * GTT domain upon first access.
3279          */
3280         if ((obj->base.read_domains & I915_GEM_DOMAIN_GTT) == 0)
3281                 cpu_mfence();
3282
3283         old_write_domain = obj->base.write_domain;
3284         old_read_domains = obj->base.read_domains;
3285
3286         /* It should now be out of any other write domains, and we can update
3287          * the domain values for our changes.
3288          */
3289         BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_GTT) != 0);
3290         obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
3291         if (write) {
3292                 obj->base.read_domains = I915_GEM_DOMAIN_GTT;
3293                 obj->base.write_domain = I915_GEM_DOMAIN_GTT;
3294                 obj->dirty = 1;
3295         }
3296
3297         trace_i915_gem_object_change_domain(obj,
3298                                             old_read_domains,
3299                                             old_write_domain);
3300
3301         /* And bump the LRU for this access */
3302         if (i915_gem_object_is_inactive(obj))
3303                 list_move_tail(&obj->mm_list, &dev_priv->mm.inactive_list);
3304
3305         return 0;
3306 }
3307
3308 int i915_gem_object_set_cache_level(struct drm_i915_gem_object *obj,
3309                                     enum i915_cache_level cache_level)
3310 {
3311         struct drm_device *dev = obj->base.dev;
3312         drm_i915_private_t *dev_priv = dev->dev_private;
3313         int ret;
3314
3315         if (obj->cache_level == cache_level)
3316                 return 0;
3317
3318         if (obj->pin_count) {
3319                 DRM_DEBUG("can not change the cache level of pinned objects\n");
3320                 return -EBUSY;
3321         }
3322
3323         if (!i915_gem_valid_gtt_space(dev, obj->gtt_space, cache_level)) {
3324                 ret = i915_gem_object_unbind(obj);
3325                 if (ret)
3326                         return ret;
3327         }
3328
3329         if (obj->gtt_space) {
3330                 ret = i915_gem_object_finish_gpu(obj);
3331                 if (ret)
3332                         return ret;
3333
3334                 i915_gem_object_finish_gtt(obj);
3335
3336                 /* Before SandyBridge, you could not use tiling or fence
3337                  * registers with snooped memory, so relinquish any fences
3338                  * currently pointing to our region in the aperture.
3339                  */
3340                 if (INTEL_INFO(dev)->gen < 6) {
3341                         ret = i915_gem_object_put_fence(obj);
3342                         if (ret)
3343                                 return ret;
3344                 }
3345
3346                 if (obj->has_global_gtt_mapping)
3347                         i915_gem_gtt_bind_object(obj, cache_level);
3348                 if (obj->has_aliasing_ppgtt_mapping)
3349                         i915_ppgtt_bind_object(dev_priv->mm.aliasing_ppgtt,
3350                                                obj, cache_level);
3351
3352                 obj->gtt_space->color = cache_level;
3353         }
3354
3355         if (cache_level == I915_CACHE_NONE) {
3356                 u32 old_read_domains, old_write_domain;
3357
3358                 /* If we're coming from LLC cached, then we haven't
3359                  * actually been tracking whether the data is in the
3360                  * CPU cache or not, since we only allow one bit set
3361                  * in obj->write_domain and have been skipping the clflushes.
3362                  * Just set it to the CPU cache for now.
3363                  */
3364                 WARN_ON(obj->base.write_domain & ~I915_GEM_DOMAIN_CPU);
3365                 WARN_ON(obj->base.read_domains & ~I915_GEM_DOMAIN_CPU);
3366
3367                 old_read_domains = obj->base.read_domains;
3368                 old_write_domain = obj->base.write_domain;
3369
3370                 obj->base.read_domains = I915_GEM_DOMAIN_CPU;
3371                 obj->base.write_domain = I915_GEM_DOMAIN_CPU;
3372
3373                 trace_i915_gem_object_change_domain(obj,
3374                                                     old_read_domains,
3375                                                     old_write_domain);
3376         }
3377
3378         obj->cache_level = cache_level;
3379         i915_gem_verify_gtt(dev);
3380         return 0;
3381 }
3382
3383 int i915_gem_get_caching_ioctl(struct drm_device *dev, void *data,
3384                                struct drm_file *file)
3385 {
3386         struct drm_i915_gem_caching *args = data;
3387         struct drm_i915_gem_object *obj;
3388         int ret;
3389
3390         ret = i915_mutex_lock_interruptible(dev);
3391         if (ret)
3392                 return ret;
3393
3394         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
3395         if (&obj->base == NULL) {
3396                 ret = -ENOENT;
3397                 goto unlock;
3398         }
3399
3400         args->caching = obj->cache_level != I915_CACHE_NONE;
3401
3402         drm_gem_object_unreference(&obj->base);
3403 unlock:
3404         mutex_unlock(&dev->struct_mutex);
3405         return ret;
3406 }
3407
3408 int i915_gem_set_caching_ioctl(struct drm_device *dev, void *data,
3409                                struct drm_file *file)
3410 {
3411         struct drm_i915_gem_caching *args = data;
3412         struct drm_i915_gem_object *obj;
3413         enum i915_cache_level level;
3414         int ret;
3415
3416         switch (args->caching) {
3417         case I915_CACHING_NONE:
3418                 level = I915_CACHE_NONE;
3419                 break;
3420         case I915_CACHING_CACHED:
3421                 level = I915_CACHE_LLC;
3422                 break;
3423         default:
3424                 return -EINVAL;
3425         }
3426
3427         ret = i915_mutex_lock_interruptible(dev);
3428         if (ret)
3429                 return ret;
3430
3431         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
3432         if (&obj->base == NULL) {
3433                 ret = -ENOENT;
3434                 goto unlock;
3435         }
3436
3437         ret = i915_gem_object_set_cache_level(obj, level);
3438
3439         drm_gem_object_unreference(&obj->base);
3440 unlock:
3441         mutex_unlock(&dev->struct_mutex);
3442         return ret;
3443 }
3444
3445 /*
3446  * Prepare buffer for display plane (scanout, cursors, etc).
3447  * Can be called from an uninterruptible phase (modesetting) and allows
3448  * any flushes to be pipelined (for pageflips).
3449  */
3450 int
3451 i915_gem_object_pin_to_display_plane(struct drm_i915_gem_object *obj,
3452                                      u32 alignment,
3453                                      struct intel_ring_buffer *pipelined)
3454 {
3455         u32 old_read_domains, old_write_domain;
3456         int ret;
3457
3458         if (pipelined != obj->ring) {
3459                 ret = i915_gem_object_sync(obj, pipelined);
3460                 if (ret)
3461                         return ret;
3462         }
3463
3464         /* The display engine is not coherent with the LLC cache on gen6.  As
3465          * a result, we make sure that the pinning that is about to occur is
3466          * done with uncached PTEs. This is lowest common denominator for all
3467          * chipsets.
3468          *
3469          * However for gen6+, we could do better by using the GFDT bit instead
3470          * of uncaching, which would allow us to flush all the LLC-cached data
3471          * with that bit in the PTE to main memory with just one PIPE_CONTROL.
3472          */
3473         ret = i915_gem_object_set_cache_level(obj, I915_CACHE_NONE);
3474         if (ret)
3475                 return ret;
3476
3477         /* As the user may map the buffer once pinned in the display plane
3478          * (e.g. libkms for the bootup splash), we have to ensure that we
3479          * always use map_and_fenceable for all scanout buffers.
3480          */
3481         ret = i915_gem_object_pin(obj, alignment, true, false);
3482         if (ret)
3483                 return ret;
3484
3485         i915_gem_object_flush_cpu_write_domain(obj);
3486
3487         old_write_domain = obj->base.write_domain;
3488         old_read_domains = obj->base.read_domains;
3489
3490         /* It should now be out of any other write domains, and we can update
3491          * the domain values for our changes.
3492          */
3493         obj->base.write_domain = 0;
3494         obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
3495
3496         trace_i915_gem_object_change_domain(obj,
3497                                             old_read_domains,
3498                                             old_write_domain);
3499
3500         return 0;
3501 }
3502
3503 int
3504 i915_gem_object_finish_gpu(struct drm_i915_gem_object *obj)
3505 {
3506         int ret;
3507
3508         if ((obj->base.read_domains & I915_GEM_GPU_DOMAINS) == 0)
3509                 return 0;
3510
3511         ret = i915_gem_object_wait_rendering(obj, false);
3512         if (ret)
3513                 return ret;
3514
3515         /* Ensure that we invalidate the GPU's caches and TLBs. */
3516         obj->base.read_domains &= ~I915_GEM_GPU_DOMAINS;
3517         return 0;
3518 }
3519
3520 /**
3521  * Moves a single object to the CPU read, and possibly write domain.
3522  *
3523  * This function returns when the move is complete, including waiting on
3524  * flushes to occur.
3525  */
3526 int
3527 i915_gem_object_set_to_cpu_domain(struct drm_i915_gem_object *obj, bool write)
3528 {
3529         uint32_t old_write_domain, old_read_domains;
3530         int ret;
3531
3532         if (obj->base.write_domain == I915_GEM_DOMAIN_CPU)
3533                 return 0;
3534
3535         ret = i915_gem_object_wait_rendering(obj, !write);
3536         if (ret)
3537                 return ret;
3538
3539         i915_gem_object_flush_gtt_write_domain(obj);
3540
3541         old_write_domain = obj->base.write_domain;
3542         old_read_domains = obj->base.read_domains;
3543
3544         /* Flush the CPU cache if it's still invalid. */
3545         if ((obj->base.read_domains & I915_GEM_DOMAIN_CPU) == 0) {
3546                 i915_gem_clflush_object(obj);
3547
3548                 obj->base.read_domains |= I915_GEM_DOMAIN_CPU;
3549         }
3550
3551         /* It should now be out of any other write domains, and we can update
3552          * the domain values for our changes.
3553          */
3554         BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_CPU) != 0);
3555
3556         /* If we're writing through the CPU, then the GPU read domains will
3557          * need to be invalidated at next use.
3558          */
3559         if (write) {
3560                 obj->base.read_domains = I915_GEM_DOMAIN_CPU;
3561                 obj->base.write_domain = I915_GEM_DOMAIN_CPU;
3562         }
3563
3564         trace_i915_gem_object_change_domain(obj,
3565                                             old_read_domains,
3566                                             old_write_domain);
3567
3568         return 0;
3569 }
3570
3571 /* Throttle our rendering by waiting until the ring has completed our requests
3572  * emitted over 20 msec ago.
3573  *
3574  * Note that if we were to use the current jiffies each time around the loop,
3575  * we wouldn't escape the function with any frames outstanding if the time to
3576  * render a frame was over 20ms.
3577  *
3578  * This should get us reasonable parallelism between CPU and GPU but also
3579  * relatively low latency when blocking on a particular request to finish.
3580  */
3581 static int
3582 i915_gem_ring_throttle(struct drm_device *dev, struct drm_file *file)
3583 {
3584         struct drm_i915_private *dev_priv = dev->dev_private;
3585         struct drm_i915_file_private *file_priv = file->driver_priv;
3586         unsigned long recent_enough = jiffies - msecs_to_jiffies(20);
3587         struct drm_i915_gem_request *request;
3588         struct intel_ring_buffer *ring = NULL;
3589         unsigned reset_counter;
3590         u32 seqno = 0;
3591         int ret;
3592
3593         ret = i915_gem_wait_for_error(&dev_priv->gpu_error);
3594         if (ret)
3595                 return ret;
3596
3597         ret = i915_gem_check_wedge(&dev_priv->gpu_error, false);
3598         if (ret)
3599                 return ret;
3600
3601         spin_lock(&file_priv->mm.lock);
3602         list_for_each_entry(request, &file_priv->mm.request_list, client_list) {
3603                 if (time_after_eq(request->emitted_jiffies, recent_enough))
3604                         break;
3605
3606                 ring = request->ring;
3607                 seqno = request->seqno;
3608         }
3609         reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
3610         spin_unlock(&file_priv->mm.lock);
3611
3612         if (seqno == 0)
3613                 return 0;
3614
3615         ret = __wait_seqno(ring, seqno, reset_counter, true, NULL);
3616         if (ret == 0)
3617                 queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work, 0);
3618
3619         return ret;
3620 }
3621
3622 int
3623 i915_gem_object_pin(struct drm_i915_gem_object *obj,
3624                     uint32_t alignment,
3625                     bool map_and_fenceable,
3626                     bool nonblocking)
3627 {
3628         int ret;
3629
3630         if (WARN_ON(obj->pin_count == DRM_I915_GEM_OBJECT_MAX_PIN_COUNT))
3631                 return -EBUSY;
3632
3633         if (obj->gtt_space != NULL) {
3634                 if ((alignment && obj->gtt_offset & (alignment - 1)) ||
3635                     (map_and_fenceable && !obj->map_and_fenceable)) {
3636                         WARN(obj->pin_count,
3637                              "bo is already pinned with incorrect alignment:"
3638                              " offset=%x, req.alignment=%x, req.map_and_fenceable=%d,"
3639                              " obj->map_and_fenceable=%d\n",
3640                              obj->gtt_offset, alignment,
3641                              map_and_fenceable,
3642                              obj->map_and_fenceable);
3643                         ret = i915_gem_object_unbind(obj);
3644                         if (ret)
3645                                 return ret;
3646                 }
3647         }
3648
3649         if (obj->gtt_space == NULL) {
3650                 struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
3651
3652                 ret = i915_gem_object_bind_to_gtt(obj, alignment,
3653                                                   map_and_fenceable,
3654                                                   nonblocking);
3655                 if (ret)
3656                         return ret;
3657
3658                 if (!dev_priv->mm.aliasing_ppgtt)
3659                         i915_gem_gtt_bind_object(obj, obj->cache_level);
3660         }
3661
3662         if (!obj->has_global_gtt_mapping && map_and_fenceable)
3663                 i915_gem_gtt_bind_object(obj, obj->cache_level);
3664
3665         obj->pin_count++;
3666         obj->pin_mappable |= map_and_fenceable;
3667
3668         return 0;
3669 }
3670
3671 void
3672 i915_gem_object_unpin(struct drm_i915_gem_object *obj)
3673 {
3674         BUG_ON(obj->pin_count == 0);
3675         BUG_ON(obj->gtt_space == NULL);
3676
3677         if (--obj->pin_count == 0)
3678                 obj->pin_mappable = false;
3679 }
3680
3681 int
3682 i915_gem_pin_ioctl(struct drm_device *dev, void *data,
3683                    struct drm_file *file)
3684 {
3685         struct drm_i915_gem_pin *args = data;
3686         struct drm_i915_gem_object *obj;
3687         int ret;
3688
3689         ret = i915_mutex_lock_interruptible(dev);
3690         if (ret)
3691                 return ret;
3692
3693         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
3694         if (&obj->base == NULL) {
3695                 ret = -ENOENT;
3696                 goto unlock;
3697         }
3698
3699         if (obj->madv != I915_MADV_WILLNEED) {
3700                 DRM_ERROR("Attempting to pin a purgeable buffer\n");
3701                 ret = -EINVAL;
3702                 goto out;
3703         }
3704
3705         if (obj->pin_filp != NULL && obj->pin_filp != file) {
3706                 DRM_ERROR("Already pinned in i915_gem_pin_ioctl(): %d\n",
3707                           args->handle);
3708                 ret = -EINVAL;
3709                 goto out;
3710         }
3711
3712         if (obj->user_pin_count == 0) {
3713                 ret = i915_gem_object_pin(obj, args->alignment, true, false);
3714                 if (ret)
3715                         goto out;
3716         }
3717
3718         obj->user_pin_count++;
3719         obj->pin_filp = file;
3720
3721         /* XXX - flush the CPU caches for pinned objects
3722          * as the X server doesn't manage domains yet
3723          */
3724         i915_gem_object_flush_cpu_write_domain(obj);
3725         args->offset = obj->gtt_offset;
3726 out:
3727         drm_gem_object_unreference(&obj->base);
3728 unlock:
3729         mutex_unlock(&dev->struct_mutex);
3730         return ret;
3731 }
3732
3733 int
3734 i915_gem_unpin_ioctl(struct drm_device *dev, void *data,
3735                      struct drm_file *file)
3736 {
3737         struct drm_i915_gem_pin *args = data;
3738         struct drm_i915_gem_object *obj;
3739         int ret;
3740
3741         ret = i915_mutex_lock_interruptible(dev);
3742         if (ret)
3743                 return ret;
3744
3745         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
3746         if (&obj->base == NULL) {
3747                 ret = -ENOENT;
3748                 goto unlock;
3749         }
3750
3751         if (obj->pin_filp != file) {
3752                 DRM_ERROR("Not pinned by caller in i915_gem_pin_ioctl(): %d\n",
3753                           args->handle);
3754                 ret = -EINVAL;
3755                 goto out;
3756         }
3757         obj->user_pin_count--;
3758         if (obj->user_pin_count == 0) {
3759                 obj->pin_filp = NULL;
3760                 i915_gem_object_unpin(obj);
3761         }
3762
3763 out:
3764         drm_gem_object_unreference(&obj->base);
3765 unlock:
3766         mutex_unlock(&dev->struct_mutex);
3767         return ret;
3768 }
3769
3770 int
3771 i915_gem_busy_ioctl(struct drm_device *dev, void *data,
3772                     struct drm_file *file)
3773 {
3774         struct drm_i915_gem_busy *args = data;
3775         struct drm_i915_gem_object *obj;
3776         int ret;
3777
3778         ret = i915_mutex_lock_interruptible(dev);
3779         if (ret)
3780                 return ret;
3781
3782         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
3783         if (&obj->base == NULL) {
3784                 ret = -ENOENT;
3785                 goto unlock;
3786         }
3787
3788         /* Count all active objects as busy, even if they are currently not used
3789          * by the gpu. Users of this interface expect objects to eventually
3790          * become non-busy without any further actions, therefore emit any
3791          * necessary flushes here.
3792          */
3793         ret = i915_gem_object_flush_active(obj);
3794
3795         args->busy = obj->active;
3796         if (obj->ring) {
3797                 args->busy |= intel_ring_flag(obj->ring) << 16;
3798         }
3799
3800         drm_gem_object_unreference(&obj->base);
3801 unlock:
3802         mutex_unlock(&dev->struct_mutex);
3803         return ret;
3804 }
3805
3806 int
3807 i915_gem_throttle_ioctl(struct drm_device *dev, void *data,
3808                         struct drm_file *file_priv)
3809 {
3810         return i915_gem_ring_throttle(dev, file_priv);
3811 }
3812
3813 int
3814 i915_gem_madvise_ioctl(struct drm_device *dev, void *data,
3815                        struct drm_file *file_priv)
3816 {
3817         struct drm_i915_gem_madvise *args = data;
3818         struct drm_i915_gem_object *obj;
3819         int ret;
3820
3821         switch (args->madv) {
3822         case I915_MADV_DONTNEED:
3823         case I915_MADV_WILLNEED:
3824             break;
3825         default:
3826             return -EINVAL;
3827         }
3828
3829         ret = i915_mutex_lock_interruptible(dev);
3830         if (ret)
3831                 return ret;
3832
3833         obj = to_intel_bo(drm_gem_object_lookup(dev, file_priv, args->handle));
3834         if (&obj->base == NULL) {
3835                 ret = -ENOENT;
3836                 goto unlock;
3837         }
3838
3839         if (obj->pin_count) {
3840                 ret = -EINVAL;
3841                 goto out;
3842         }
3843
3844         if (obj->madv != __I915_MADV_PURGED)
3845                 obj->madv = args->madv;
3846
3847         /* if the object is no longer attached, discard its backing storage */
3848         if (i915_gem_object_is_purgeable(obj) && obj->pages == NULL)
3849                 i915_gem_object_truncate(obj);
3850
3851         args->retained = obj->madv != __I915_MADV_PURGED;
3852
3853 out:
3854         drm_gem_object_unreference(&obj->base);
3855 unlock:
3856         mutex_unlock(&dev->struct_mutex);
3857         return ret;
3858 }
3859
3860 void i915_gem_object_init(struct drm_i915_gem_object *obj,
3861                           const struct drm_i915_gem_object_ops *ops)
3862 {
3863         INIT_LIST_HEAD(&obj->mm_list);
3864         INIT_LIST_HEAD(&obj->global_list);
3865         INIT_LIST_HEAD(&obj->ring_list);
3866         INIT_LIST_HEAD(&obj->exec_list);
3867
3868         obj->ops = ops;
3869
3870         obj->fence_reg = I915_FENCE_REG_NONE;
3871         obj->madv = I915_MADV_WILLNEED;
3872         /* Avoid an unnecessary call to unbind on the first bind. */
3873         obj->map_and_fenceable = true;
3874
3875         i915_gem_info_add_obj(obj->base.dev->dev_private, obj->base.size);
3876 }
3877
3878 static const struct drm_i915_gem_object_ops i915_gem_object_ops = {
3879         .get_pages = i915_gem_object_get_pages_gtt,
3880         .put_pages = i915_gem_object_put_pages_gtt,
3881 };
3882
3883 struct drm_i915_gem_object *i915_gem_alloc_object(struct drm_device *dev,
3884                                                   size_t size)
3885 {
3886         struct drm_i915_gem_object *obj;
3887 #if 0
3888         struct address_space *mapping;
3889         u32 mask;
3890 #endif
3891
3892         obj = kmalloc(sizeof(*obj), M_DRM, M_WAITOK | M_ZERO);
3893         if (obj == NULL)
3894                 return NULL;
3895
3896         if (drm_gem_object_init(dev, &obj->base, size) != 0) {
3897                 kfree(obj);
3898                 return NULL;
3899         }
3900
3901 #if 0
3902         mask = GFP_HIGHUSER | __GFP_RECLAIMABLE;
3903         if (IS_CRESTLINE(dev) || IS_BROADWATER(dev)) {
3904                 /* 965gm cannot relocate objects above 4GiB. */
3905                 mask &= ~__GFP_HIGHMEM;
3906                 mask |= __GFP_DMA32;
3907         }
3908
3909         mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
3910         mapping_set_gfp_mask(mapping, mask);
3911 #endif
3912
3913         i915_gem_object_init(obj, &i915_gem_object_ops);
3914
3915         obj->base.write_domain = I915_GEM_DOMAIN_CPU;
3916         obj->base.read_domains = I915_GEM_DOMAIN_CPU;
3917
3918         if (HAS_LLC(dev)) {
3919                 /* On some devices, we can have the GPU use the LLC (the CPU
3920                  * cache) for about a 10% performance improvement
3921                  * compared to uncached.  Graphics requests other than
3922                  * display scanout are coherent with the CPU in
3923                  * accessing this cache.  This means in this mode we
3924                  * don't need to clflush on the CPU side, and on the
3925                  * GPU side we only need to flush internal caches to
3926                  * get data visible to the CPU.
3927                  *
3928                  * However, we maintain the display planes as UC, and so
3929                  * need to rebind when first used as such.
3930                  */
3931                 obj->cache_level = I915_CACHE_LLC;
3932         } else
3933                 obj->cache_level = I915_CACHE_NONE;
3934
3935         return obj;
3936 }
3937
3938 int i915_gem_init_object(struct drm_gem_object *obj)
3939 {
3940         BUG();
3941
3942         return 0;
3943 }
3944
3945 void i915_gem_free_object(struct drm_gem_object *gem_obj)
3946 {
3947         struct drm_i915_gem_object *obj = to_intel_bo(gem_obj);
3948         struct drm_device *dev = obj->base.dev;
3949         drm_i915_private_t *dev_priv = dev->dev_private;
3950
3951         trace_i915_gem_object_destroy(obj);
3952
3953         if (obj->phys_obj)
3954                 i915_gem_detach_phys_object(dev, obj);
3955
3956         obj->pin_count = 0;
3957         if (WARN_ON(i915_gem_object_unbind(obj) == -ERESTARTSYS)) {
3958                 bool was_interruptible;
3959
3960                 was_interruptible = dev_priv->mm.interruptible;
3961                 dev_priv->mm.interruptible = false;
3962
3963                 WARN_ON(i915_gem_object_unbind(obj));
3964
3965                 dev_priv->mm.interruptible = was_interruptible;
3966         }
3967
3968         /* Stolen objects don't hold a ref, but do hold pin count. Fix that up
3969          * before progressing. */
3970         if (obj->stolen)
3971                 i915_gem_object_unpin_pages(obj);
3972
3973         if (WARN_ON(obj->pages_pin_count))
3974                 obj->pages_pin_count = 0;
3975         i915_gem_object_put_pages(obj);
3976         drm_gem_free_mmap_offset(&obj->base);
3977
3978         BUG_ON(obj->pages);
3979
3980         drm_gem_object_release(&obj->base);
3981         i915_gem_info_remove_obj(dev_priv, obj->base.size);
3982
3983         kfree(obj->bit_17);
3984         i915_gem_object_free(obj);
3985 }
3986
3987 int
3988 i915_gem_idle(struct drm_device *dev)
3989 {
3990         drm_i915_private_t *dev_priv = dev->dev_private;
3991         int ret;
3992
3993         mutex_lock(&dev->struct_mutex);
3994
3995         if (dev_priv->mm.suspended) {
3996                 mutex_unlock(&dev->struct_mutex);
3997                 return 0;
3998         }
3999
4000         ret = i915_gpu_idle(dev);
4001         if (ret) {
4002                 mutex_unlock(&dev->struct_mutex);
4003                 return ret;
4004         }
4005         i915_gem_retire_requests(dev);
4006
4007         /* Under UMS, be paranoid and evict. */
4008         if (!drm_core_check_feature(dev, DRIVER_MODESET))
4009                 i915_gem_evict_everything(dev);
4010
4011         /* Hack!  Don't let anybody do execbuf while we don't control the chip.
4012          * We need to replace this with a semaphore, or something.
4013          * And not confound mm.suspended!
4014          */
4015         dev_priv->mm.suspended = 1;
4016         del_timer_sync(&dev_priv->gpu_error.hangcheck_timer);
4017
4018         i915_kernel_lost_context(dev);
4019         i915_gem_cleanup_ringbuffer(dev);
4020
4021         mutex_unlock(&dev->struct_mutex);
4022
4023         /* Cancel the retire work handler, which should be idle now. */
4024         cancel_delayed_work_sync(&dev_priv->mm.retire_work);
4025
4026         return 0;
4027 }
4028
4029 void i915_gem_l3_remap(struct drm_device *dev)
4030 {
4031         drm_i915_private_t *dev_priv = dev->dev_private;
4032         u32 misccpctl;
4033         int i;
4034
4035         if (!HAS_L3_GPU_CACHE(dev))
4036                 return;
4037
4038         if (!dev_priv->l3_parity.remap_info)
4039                 return;
4040
4041         misccpctl = I915_READ(GEN7_MISCCPCTL);
4042         I915_WRITE(GEN7_MISCCPCTL, misccpctl & ~GEN7_DOP_CLOCK_GATE_ENABLE);
4043         POSTING_READ(GEN7_MISCCPCTL);
4044
4045         for (i = 0; i < GEN7_L3LOG_SIZE; i += 4) {
4046                 u32 remap = I915_READ(GEN7_L3LOG_BASE + i);
4047                 if (remap && remap != dev_priv->l3_parity.remap_info[i/4])
4048                         DRM_DEBUG("0x%x was already programmed to %x\n",
4049                                   GEN7_L3LOG_BASE + i, remap);
4050                 if (remap && !dev_priv->l3_parity.remap_info[i/4])
4051                         DRM_DEBUG_DRIVER("Clearing remapped register\n");
4052                 I915_WRITE(GEN7_L3LOG_BASE + i, dev_priv->l3_parity.remap_info[i/4]);
4053         }
4054
4055         /* Make sure all the writes land before disabling dop clock gating */
4056         POSTING_READ(GEN7_L3LOG_BASE);
4057
4058         I915_WRITE(GEN7_MISCCPCTL, misccpctl);
4059 }
4060
4061 void i915_gem_init_swizzling(struct drm_device *dev)
4062 {
4063         drm_i915_private_t *dev_priv = dev->dev_private;
4064
4065         if (INTEL_INFO(dev)->gen < 5 ||
4066             dev_priv->mm.bit_6_swizzle_x == I915_BIT_6_SWIZZLE_NONE)
4067                 return;
4068
4069         I915_WRITE(DISP_ARB_CTL, I915_READ(DISP_ARB_CTL) |
4070                                  DISP_TILE_SURFACE_SWIZZLING);
4071
4072         if (IS_GEN5(dev))
4073                 return;
4074
4075         I915_WRITE(TILECTL, I915_READ(TILECTL) | TILECTL_SWZCTL);
4076         if (IS_GEN6(dev))
4077                 I915_WRITE(ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_SNB));
4078         else if (IS_GEN7(dev))
4079                 I915_WRITE(ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_IVB));
4080         else
4081                 BUG();
4082 }
4083
4084 static bool
4085 intel_enable_blt(struct drm_device *dev)
4086 {
4087         int revision;
4088
4089         if (!HAS_BLT(dev))
4090                 return false;
4091
4092         /* The blitter was dysfunctional on early prototypes */
4093         revision = pci_read_config(dev->dev, PCIR_REVID, 1);
4094         if (IS_GEN6(dev) && revision < 8) {
4095                 DRM_INFO("BLT not supported on this pre-production hardware;"
4096                          " graphics performance will be degraded.\n");
4097                 return false;
4098         }
4099
4100         return true;
4101 }
4102
4103 static int i915_gem_init_rings(struct drm_device *dev)
4104 {
4105         struct drm_i915_private *dev_priv = dev->dev_private;
4106         int ret;
4107
4108         ret = intel_init_render_ring_buffer(dev);
4109         if (ret)
4110                 return ret;
4111
4112         if (HAS_BSD(dev)) {
4113                 ret = intel_init_bsd_ring_buffer(dev);
4114                 if (ret)
4115                         goto cleanup_render_ring;
4116         }
4117
4118         if (intel_enable_blt(dev)) {
4119                 ret = intel_init_blt_ring_buffer(dev);
4120                 if (ret)
4121                         goto cleanup_bsd_ring;
4122         }
4123
4124         if (HAS_VEBOX(dev)) {
4125                 ret = intel_init_vebox_ring_buffer(dev);
4126                 if (ret)
4127                         goto cleanup_blt_ring;
4128         }
4129
4130
4131         ret = i915_gem_set_seqno(dev, ((u32)~0 - 0x1000));
4132         if (ret)
4133                 goto cleanup_vebox_ring;
4134
4135         return 0;
4136
4137 cleanup_vebox_ring:
4138         intel_cleanup_ring_buffer(&dev_priv->ring[VECS]);
4139 cleanup_blt_ring:
4140         intel_cleanup_ring_buffer(&dev_priv->ring[BCS]);
4141 cleanup_bsd_ring:
4142         intel_cleanup_ring_buffer(&dev_priv->ring[VCS]);
4143 cleanup_render_ring:
4144         intel_cleanup_ring_buffer(&dev_priv->ring[RCS]);
4145
4146         return ret;
4147 }
4148
4149 int
4150 i915_gem_init_hw(struct drm_device *dev)
4151 {
4152         drm_i915_private_t *dev_priv = dev->dev_private;
4153         int ret;
4154
4155 #if 0
4156         if (INTEL_INFO(dev)->gen < 6 && !intel_enable_gtt())
4157                 return -EIO;
4158 #endif
4159
4160         if (IS_HASWELL(dev) && (I915_READ(0x120010) == 1))
4161                 I915_WRITE(0x9008, I915_READ(0x9008) | 0xf0000);
4162
4163         if (HAS_PCH_NOP(dev)) {
4164                 u32 temp = I915_READ(GEN7_MSG_CTL);
4165                 temp &= ~(WAIT_FOR_PCH_FLR_ACK | WAIT_FOR_PCH_RESET_ACK);
4166                 I915_WRITE(GEN7_MSG_CTL, temp);
4167         }
4168
4169         i915_gem_l3_remap(dev);
4170
4171         i915_gem_init_swizzling(dev);
4172
4173         ret = i915_gem_init_rings(dev);
4174         if (ret)
4175                 return ret;
4176
4177         /*
4178          * XXX: There was some w/a described somewhere suggesting loading
4179          * contexts before PPGTT.
4180          */
4181         i915_gem_context_init(dev);
4182         if (dev_priv->mm.aliasing_ppgtt) {
4183                 ret = dev_priv->mm.aliasing_ppgtt->enable(dev);
4184                 if (ret) {
4185                         i915_gem_cleanup_aliasing_ppgtt(dev);
4186                         DRM_INFO("PPGTT enable failed. This is not fatal, but unexpected\n");
4187                 }
4188         }
4189
4190         return 0;
4191 }
4192
4193 int i915_gem_init(struct drm_device *dev)
4194 {
4195         struct drm_i915_private *dev_priv = dev->dev_private;
4196         int ret;
4197
4198         mutex_lock(&dev->struct_mutex);
4199
4200         if (IS_VALLEYVIEW(dev)) {
4201                 /* VLVA0 (potential hack), BIOS isn't actually waking us */
4202                 I915_WRITE(VLV_GTLC_WAKE_CTRL, 1);
4203                 if (wait_for((I915_READ(VLV_GTLC_PW_STATUS) & 1) == 1, 10))
4204                         DRM_DEBUG_DRIVER("allow wake ack timed out\n");
4205         }
4206
4207         i915_gem_init_global_gtt(dev);
4208
4209         ret = i915_gem_init_hw(dev);
4210         mutex_unlock(&dev->struct_mutex);
4211         if (ret) {
4212                 i915_gem_cleanup_aliasing_ppgtt(dev);
4213                 return ret;
4214         }
4215
4216         /* Allow hardware batchbuffers unless told otherwise, but not for KMS. */
4217         if (!drm_core_check_feature(dev, DRIVER_MODESET))
4218                 dev_priv->dri1.allow_batchbuffer = 1;
4219         return 0;
4220 }
4221
4222 void
4223 i915_gem_cleanup_ringbuffer(struct drm_device *dev)
4224 {
4225         drm_i915_private_t *dev_priv = dev->dev_private;
4226         struct intel_ring_buffer *ring;
4227         int i;
4228
4229         for_each_ring(ring, dev_priv, i)
4230                 intel_cleanup_ring_buffer(ring);
4231 }
4232
4233 int
4234 i915_gem_entervt_ioctl(struct drm_device *dev, void *data,
4235                        struct drm_file *file_priv)
4236 {
4237         drm_i915_private_t *dev_priv = dev->dev_private;
4238         int ret;
4239
4240         if (drm_core_check_feature(dev, DRIVER_MODESET))
4241                 return 0;
4242
4243         if (i915_reset_in_progress(&dev_priv->gpu_error)) {
4244                 DRM_ERROR("Reenabling wedged hardware, good luck\n");
4245                 atomic_set(&dev_priv->gpu_error.reset_counter, 0);
4246         }
4247
4248         mutex_lock(&dev->struct_mutex);
4249         dev_priv->mm.suspended = 0;
4250
4251         ret = i915_gem_init_hw(dev);
4252         if (ret != 0) {
4253                 mutex_unlock(&dev->struct_mutex);
4254                 return ret;
4255         }
4256
4257         KASSERT(list_empty(&dev_priv->mm.active_list), ("active list"));
4258         mutex_unlock(&dev->struct_mutex);
4259
4260         ret = drm_irq_install(dev);
4261         if (ret)
4262                 goto cleanup_ringbuffer;
4263
4264         return 0;
4265
4266 cleanup_ringbuffer:
4267         mutex_lock(&dev->struct_mutex);
4268         i915_gem_cleanup_ringbuffer(dev);
4269         dev_priv->mm.suspended = 1;
4270         mutex_unlock(&dev->struct_mutex);
4271
4272         return ret;
4273 }
4274
4275 int
4276 i915_gem_leavevt_ioctl(struct drm_device *dev, void *data,
4277                        struct drm_file *file_priv)
4278 {
4279         if (drm_core_check_feature(dev, DRIVER_MODESET))
4280                 return 0;
4281
4282         drm_irq_uninstall(dev);
4283         return i915_gem_idle(dev);
4284 }
4285
4286 void
4287 i915_gem_lastclose(struct drm_device *dev)
4288 {
4289         int ret;
4290
4291         if (drm_core_check_feature(dev, DRIVER_MODESET))
4292                 return;
4293
4294         ret = i915_gem_idle(dev);
4295         if (ret)
4296                 DRM_ERROR("failed to idle hardware: %d\n", ret);
4297 }
4298
4299 static void
4300 init_ring_lists(struct intel_ring_buffer *ring)
4301 {
4302         INIT_LIST_HEAD(&ring->active_list);
4303         INIT_LIST_HEAD(&ring->request_list);
4304 }
4305
4306 void
4307 i915_gem_load(struct drm_device *dev)
4308 {
4309         int i;
4310         drm_i915_private_t *dev_priv = dev->dev_private;
4311
4312         INIT_LIST_HEAD(&dev_priv->mm.active_list);
4313         INIT_LIST_HEAD(&dev_priv->mm.inactive_list);
4314         INIT_LIST_HEAD(&dev_priv->mm.unbound_list);
4315         INIT_LIST_HEAD(&dev_priv->mm.bound_list);
4316         INIT_LIST_HEAD(&dev_priv->mm.fence_list);
4317         for (i = 0; i < I915_NUM_RINGS; i++)
4318                 init_ring_lists(&dev_priv->ring[i]);
4319         for (i = 0; i < I915_MAX_NUM_FENCES; i++)
4320                 INIT_LIST_HEAD(&dev_priv->fence_regs[i].lru_list);
4321         INIT_DELAYED_WORK(&dev_priv->mm.retire_work,
4322                           i915_gem_retire_work_handler);
4323         init_waitqueue_head(&dev_priv->gpu_error.reset_queue);
4324
4325         /* On GEN3 we really need to make sure the ARB C3 LP bit is set */
4326         if (IS_GEN3(dev)) {
4327                 I915_WRITE(MI_ARB_STATE,
4328                            _MASKED_BIT_ENABLE(MI_ARB_C3_LP_WRITE_ENABLE));
4329         }
4330
4331         dev_priv->relative_constants_mode = I915_EXEC_CONSTANTS_REL_GENERAL;
4332
4333         /* Old X drivers will take 0-2 for front, back, depth buffers */
4334         if (!drm_core_check_feature(dev, DRIVER_MODESET))
4335                 dev_priv->fence_reg_start = 3;
4336
4337         if (INTEL_INFO(dev)->gen >= 7 && !IS_VALLEYVIEW(dev))
4338                 dev_priv->num_fence_regs = 32;
4339         else if (INTEL_INFO(dev)->gen >= 4 || IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev))
4340                 dev_priv->num_fence_regs = 16;
4341         else
4342                 dev_priv->num_fence_regs = 8;
4343
4344         /* Initialize fence registers to zero */
4345         INIT_LIST_HEAD(&dev_priv->mm.fence_list);
4346         i915_gem_restore_fences(dev);
4347
4348         i915_gem_detect_bit_6_swizzle(dev);
4349         init_waitqueue_head(&dev_priv->pending_flip_queue);
4350
4351         dev_priv->mm.interruptible = true;
4352
4353 #if 0
4354         dev_priv->mm.inactive_shrinker.shrink = i915_gem_inactive_shrink;
4355         dev_priv->mm.inactive_shrinker.seeks = DEFAULT_SEEKS;
4356         register_shrinker(&dev_priv->mm.inactive_shrinker);
4357 #else
4358         dev_priv->mm.inactive_shrinker = EVENTHANDLER_REGISTER(vm_lowmem,
4359             i915_gem_lowmem, dev, EVENTHANDLER_PRI_ANY);
4360 #endif
4361 }
4362
4363 /*
4364  * Create a physically contiguous memory object for this object
4365  * e.g. for cursor + overlay regs
4366  */
4367 static int i915_gem_init_phys_object(struct drm_device *dev,
4368                                      int id, int size, int align)
4369 {
4370         drm_i915_private_t *dev_priv = dev->dev_private;
4371         struct drm_i915_gem_phys_object *phys_obj;
4372         int ret;
4373
4374         if (dev_priv->mm.phys_objs[id - 1] || !size)
4375                 return 0;
4376
4377         phys_obj = kzalloc(sizeof(struct drm_i915_gem_phys_object), GFP_KERNEL);
4378         if (!phys_obj)
4379                 return -ENOMEM;
4380
4381         phys_obj->id = id;
4382
4383         phys_obj->handle = drm_pci_alloc(dev, size, align);
4384         if (!phys_obj->handle) {
4385                 ret = -ENOMEM;
4386                 goto kfree_obj;
4387         }
4388         pmap_change_attr((vm_offset_t)phys_obj->handle->vaddr,
4389             size / PAGE_SIZE, PAT_WRITE_COMBINING);
4390
4391         dev_priv->mm.phys_objs[id - 1] = phys_obj;
4392
4393         return 0;
4394
4395 kfree_obj:
4396         kfree(phys_obj);
4397         return ret;
4398 }
4399
4400 static void i915_gem_free_phys_object(struct drm_device *dev, int id)
4401 {
4402         drm_i915_private_t *dev_priv = dev->dev_private;
4403         struct drm_i915_gem_phys_object *phys_obj;
4404
4405         if (!dev_priv->mm.phys_objs[id - 1])
4406                 return;
4407
4408         phys_obj = dev_priv->mm.phys_objs[id - 1];
4409         if (phys_obj->cur_obj) {
4410                 i915_gem_detach_phys_object(dev, phys_obj->cur_obj);
4411         }
4412
4413         drm_pci_free(dev, phys_obj->handle);
4414         kfree(phys_obj);
4415         dev_priv->mm.phys_objs[id - 1] = NULL;
4416 }
4417
4418 void i915_gem_free_all_phys_object(struct drm_device *dev)
4419 {
4420         int i;
4421
4422         for (i = I915_GEM_PHYS_CURSOR_0; i <= I915_MAX_PHYS_OBJECT; i++)
4423                 i915_gem_free_phys_object(dev, i);
4424 }
4425
4426 void i915_gem_detach_phys_object(struct drm_device *dev,
4427                                  struct drm_i915_gem_object *obj)
4428 {
4429         struct vm_object *mapping = obj->base.vm_obj;
4430         char *vaddr;
4431         int i;
4432         int page_count;
4433
4434         if (!obj->phys_obj)
4435                 return;
4436         vaddr = obj->phys_obj->handle->vaddr;
4437
4438         page_count = obj->base.size / PAGE_SIZE;
4439         VM_OBJECT_LOCK(obj->base.vm_obj);
4440         for (i = 0; i < page_count; i++) {
4441                 struct vm_page *page = shmem_read_mapping_page(mapping, i);
4442                 if (!IS_ERR(page)) {
4443                         VM_OBJECT_UNLOCK(obj->base.vm_obj);
4444                         char *dst = kmap_atomic(page);
4445                         memcpy(dst, vaddr + i*PAGE_SIZE, PAGE_SIZE);
4446                         kunmap_atomic(dst);
4447
4448                         drm_clflush_pages(&page, 1);
4449
4450 #if 0
4451                         set_page_dirty(page);
4452                         mark_page_accessed(page);
4453                         page_cache_release(page);
4454 #endif
4455                         VM_OBJECT_LOCK(obj->base.vm_obj);
4456                         vm_page_reference(page);
4457                         vm_page_dirty(page);
4458                         vm_page_busy_wait(page, FALSE, "i915gem");
4459                         vm_page_unwire(page, 0);
4460                         vm_page_wakeup(page);
4461                 }
4462         }
4463         VM_OBJECT_UNLOCK(obj->base.vm_obj);
4464         intel_gtt_chipset_flush();
4465
4466         obj->phys_obj->cur_obj = NULL;
4467         obj->phys_obj = NULL;
4468 }
4469
4470 int
4471 i915_gem_attach_phys_object(struct drm_device *dev,
4472                             struct drm_i915_gem_object *obj,
4473                             int id,
4474                             int align)
4475 {
4476         struct vm_object *mapping = obj->base.vm_obj;
4477         drm_i915_private_t *dev_priv = dev->dev_private;
4478         int ret = 0;
4479         int page_count;
4480         int i;
4481
4482         if (id > I915_MAX_PHYS_OBJECT)
4483                 return -EINVAL;
4484
4485         if (obj->phys_obj) {
4486                 if (obj->phys_obj->id == id)
4487                         return 0;
4488                 i915_gem_detach_phys_object(dev, obj);
4489         }
4490
4491         /* create a new object */
4492         if (!dev_priv->mm.phys_objs[id - 1]) {
4493                 ret = i915_gem_init_phys_object(dev, id,
4494                                                 obj->base.size, align);
4495                 if (ret) {
4496                         DRM_ERROR("failed to init phys object %d size: %zu\n",
4497                                   id, obj->base.size);
4498                         return ret;
4499                 }
4500         }
4501
4502         /* bind to the object */
4503         obj->phys_obj = dev_priv->mm.phys_objs[id - 1];
4504         obj->phys_obj->cur_obj = obj;
4505
4506         page_count = obj->base.size / PAGE_SIZE;
4507
4508         VM_OBJECT_LOCK(obj->base.vm_obj);
4509         for (i = 0; i < page_count; i++) {
4510                 struct vm_page *page;
4511                 char *dst, *src;
4512
4513                 page = shmem_read_mapping_page(mapping, i);
4514                 VM_OBJECT_UNLOCK(obj->base.vm_obj);
4515                 if (IS_ERR(page))
4516                         return PTR_ERR(page);
4517
4518                 src = kmap_atomic(page);
4519                 dst = (char*)obj->phys_obj->handle->vaddr + (i * PAGE_SIZE);
4520                 memcpy(dst, src, PAGE_SIZE);
4521                 kunmap_atomic(src);
4522
4523 #if 0
4524                 mark_page_accessed(page);
4525                 page_cache_release(page);
4526 #endif
4527                 VM_OBJECT_LOCK(obj->base.vm_obj);
4528                 vm_page_reference(page);
4529                 vm_page_busy_wait(page, FALSE, "i915gem");
4530                 vm_page_unwire(page, 0);
4531                 vm_page_wakeup(page);
4532         }
4533         VM_OBJECT_UNLOCK(obj->base.vm_obj);
4534
4535         return 0;
4536 }
4537
4538 static int
4539 i915_gem_phys_pwrite(struct drm_device *dev,
4540                      struct drm_i915_gem_object *obj,
4541                      struct drm_i915_gem_pwrite *args,
4542                      struct drm_file *file_priv)
4543 {
4544         void *vaddr = (char *)obj->phys_obj->handle->vaddr + args->offset;
4545         char __user *user_data = (char __user *) (uintptr_t) args->data_ptr;
4546
4547         if (copyin_nofault(user_data, vaddr, args->size) != 0) {
4548                 unsigned long unwritten;
4549
4550                 /* The physical object once assigned is fixed for the lifetime
4551                  * of the obj, so we can safely drop the lock and continue
4552                  * to access vaddr.
4553                  */
4554                 mutex_unlock(&dev->struct_mutex);
4555                 unwritten = copy_from_user(vaddr, user_data, args->size);
4556                 mutex_lock(&dev->struct_mutex);
4557                 if (unwritten)
4558                         return -EFAULT;
4559         }
4560
4561         i915_gem_chipset_flush(dev);
4562         return 0;
4563 }
4564
4565 void i915_gem_release(struct drm_device *dev, struct drm_file *file)
4566 {
4567         struct drm_i915_file_private *file_priv = file->driver_priv;
4568
4569         /* Clean up our request list when the client is going away, so that
4570          * later retire_requests won't dereference our soon-to-be-gone
4571          * file_priv.
4572          */
4573         spin_lock(&file_priv->mm.lock);
4574         while (!list_empty(&file_priv->mm.request_list)) {
4575                 struct drm_i915_gem_request *request;
4576
4577                 request = list_first_entry(&file_priv->mm.request_list,
4578                                            struct drm_i915_gem_request,
4579                                            client_list);
4580                 list_del(&request->client_list);
4581                 request->file_priv = NULL;
4582         }
4583         spin_unlock(&file_priv->mm.lock);
4584 }
4585
4586 int
4587 i915_gem_pager_ctor(void *handle, vm_ooffset_t size, vm_prot_t prot,
4588     vm_ooffset_t foff, struct ucred *cred, u_short *color)
4589 {
4590
4591         *color = 0; /* XXXKIB */
4592         return (0);
4593 }
4594
4595 void
4596 i915_gem_pager_dtor(void *handle)
4597 {
4598         struct drm_gem_object *obj;
4599         struct drm_device *dev;
4600
4601         obj = handle;
4602         dev = obj->dev;
4603
4604         mutex_lock(&dev->struct_mutex);
4605         drm_gem_free_mmap_offset(obj);
4606         i915_gem_release_mmap(to_intel_bo(obj));
4607         drm_gem_object_unreference(obj);
4608         mutex_unlock(&dev->struct_mutex);
4609 }
4610
4611 #define GEM_PARANOID_CHECK_GTT 0
4612 #if GEM_PARANOID_CHECK_GTT
4613 static void
4614 i915_gem_assert_pages_not_mapped(struct drm_device *dev, vm_page_t *ma,
4615     int page_count)
4616 {
4617         struct drm_i915_private *dev_priv;
4618         vm_paddr_t pa;
4619         unsigned long start, end;
4620         u_int i;
4621         int j;
4622
4623         dev_priv = dev->dev_private;
4624         start = OFF_TO_IDX(dev_priv->mm.gtt_start);
4625         end = OFF_TO_IDX(dev_priv->mm.gtt_end);
4626         for (i = start; i < end; i++) {
4627                 pa = intel_gtt_read_pte_paddr(i);
4628                 for (j = 0; j < page_count; j++) {
4629                         if (pa == VM_PAGE_TO_PHYS(ma[j])) {
4630                                 panic("Page %p in GTT pte index %d pte %x",
4631                                     ma[i], i, intel_gtt_read_pte(i));
4632                         }
4633                 }
4634         }
4635         obj->fence_dirty = false;
4636 }
4637 #endif
4638
4639 static int
4640 i915_gpu_is_active(struct drm_device *dev)
4641 {
4642         drm_i915_private_t *dev_priv = dev->dev_private;
4643
4644         return !list_empty(&dev_priv->mm.active_list);
4645 }
4646
4647 static void
4648 i915_gem_lowmem(void *arg)
4649 {
4650         struct drm_device *dev;
4651         struct drm_i915_private *dev_priv;
4652         struct drm_i915_gem_object *obj, *next;
4653         int cnt, cnt_fail, cnt_total;
4654
4655         dev = arg;
4656         dev_priv = dev->dev_private;
4657
4658         if (lockmgr(&dev->struct_mutex, LK_EXCLUSIVE|LK_NOWAIT))
4659                 return;
4660
4661 rescan:
4662         /* first scan for clean buffers */
4663         i915_gem_retire_requests(dev);
4664
4665         cnt_total = cnt_fail = cnt = 0;
4666
4667         list_for_each_entry_safe(obj, next, &dev_priv->mm.inactive_list,
4668             mm_list) {
4669                 if (i915_gem_object_is_purgeable(obj)) {
4670                         if (i915_gem_object_unbind(obj) != 0)
4671                                 cnt_total++;
4672                 } else
4673                         cnt_total++;
4674         }
4675
4676         /* second pass, evict/count anything still on the inactive list */
4677         list_for_each_entry_safe(obj, next, &dev_priv->mm.inactive_list,
4678             mm_list) {
4679                 if (i915_gem_object_unbind(obj) == 0)
4680                         cnt++;
4681                 else
4682                         cnt_fail++;
4683         }
4684
4685         if (cnt_fail > cnt_total / 100 && i915_gpu_is_active(dev)) {
4686                 /*
4687                  * We are desperate for pages, so as a last resort, wait
4688                  * for the GPU to finish and discard whatever we can.
4689                  * This has a dramatic impact to reduce the number of
4690                  * OOM-killer events whilst running the GPU aggressively.
4691                  */
4692                 if (i915_gpu_idle(dev) == 0)
4693                         goto rescan;
4694         }
4695         mutex_unlock(&dev->struct_mutex);
4696 }