drm/i915: Sync i915_gem_phys_pwrite() 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 = to_user_ptr(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
1236         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
1237         if (&obj->base == NULL) {
1238                 ret = -ENOENT;
1239                 goto unlock;
1240         }
1241
1242         /* Pinned buffers may be scanout, so flush the cache */
1243         if (obj->pin_count)
1244                 i915_gem_object_flush_cpu_write_domain(obj);
1245
1246         drm_gem_object_unreference(&obj->base);
1247 unlock:
1248         mutex_unlock(&dev->struct_mutex);
1249         return ret;
1250 }
1251
1252 /**
1253  * Maps the contents of an object, returning the address it is mapped
1254  * into.
1255  *
1256  * While the mapping holds a reference on the contents of the object, it doesn't
1257  * imply a ref on the object itself.
1258  */
1259 int
1260 i915_gem_mmap_ioctl(struct drm_device *dev, void *data,
1261                     struct drm_file *file)
1262 {
1263         struct drm_i915_gem_mmap *args = data;
1264         struct drm_gem_object *obj;
1265         struct proc *p = curproc;
1266         vm_map_t map = &p->p_vmspace->vm_map;
1267         vm_offset_t addr;
1268         vm_size_t size;
1269         int error = 0, rv;
1270
1271         obj = drm_gem_object_lookup(dev, file, args->handle);
1272         if (obj == NULL)
1273                 return -ENOENT;
1274
1275         if (args->size == 0)
1276                 goto out;
1277
1278         size = round_page(args->size);
1279         if (map->size + size > p->p_rlimit[RLIMIT_VMEM].rlim_cur) {
1280                 error = ENOMEM;
1281                 goto out;
1282         }
1283
1284         addr = 0;
1285         vm_object_hold(obj->vm_obj);
1286         vm_object_reference_locked(obj->vm_obj);
1287         vm_object_drop(obj->vm_obj);
1288         rv = vm_map_find(map, obj->vm_obj, NULL,
1289                          args->offset, &addr, args->size,
1290                          PAGE_SIZE, /* align */
1291                          TRUE, /* fitit */
1292                          VM_MAPTYPE_NORMAL, /* maptype */
1293                          VM_PROT_READ | VM_PROT_WRITE, /* prot */
1294                          VM_PROT_READ | VM_PROT_WRITE, /* max */
1295                          MAP_SHARED /* cow */);
1296         if (rv != KERN_SUCCESS) {
1297                 vm_object_deallocate(obj->vm_obj);
1298                 error = -vm_mmap_to_errno(rv);
1299         } else {
1300                 args->addr_ptr = (uint64_t)addr;
1301         }
1302 out:
1303         drm_gem_object_unreference(obj);
1304         return (error);
1305 }
1306
1307 int i915_intr_pf;
1308
1309 /**
1310  * i915_gem_fault - fault a page into the GTT
1311  * vma: VMA in question
1312  * vmf: fault info
1313  *
1314  * The fault handler is set up by drm_gem_mmap() when a object is GTT mapped
1315  * from userspace.  The fault handler takes care of binding the object to
1316  * the GTT (if needed), allocating and programming a fence register (again,
1317  * only if needed based on whether the old reg is still valid or the object
1318  * is tiled) and inserting a new PTE into the faulting process.
1319  *
1320  * Note that the faulting process may involve evicting existing objects
1321  * from the GTT and/or fence registers to make room.  So performance may
1322  * suffer if the GTT working set is large or there are few fence registers
1323  * left.
1324  */
1325 int
1326 i915_gem_fault(vm_object_t vm_obj, vm_ooffset_t offset, int prot,
1327     vm_page_t *mres)
1328 {
1329         struct drm_gem_object *gem_obj;
1330         struct drm_i915_gem_object *obj;
1331         struct drm_device *dev;
1332         drm_i915_private_t *dev_priv;
1333         vm_page_t m, oldm;
1334         int cause, ret;
1335         bool write;
1336
1337         gem_obj = vm_obj->handle;
1338         obj = to_intel_bo(gem_obj);
1339         dev = obj->base.dev;
1340         dev_priv = dev->dev_private;
1341 #if 0
1342         write = (prot & VM_PROT_WRITE) != 0;
1343 #else
1344         write = true;
1345 #endif
1346         vm_object_pip_add(vm_obj, 1);
1347
1348         /*
1349          * Remove the placeholder page inserted by vm_fault() from the
1350          * object before dropping the object lock. If
1351          * i915_gem_release_mmap() is active in parallel on this gem
1352          * object, then it owns the drm device sx and might find the
1353          * placeholder already. Then, since the page is busy,
1354          * i915_gem_release_mmap() sleeps waiting for the busy state
1355          * of the page cleared. We will be not able to acquire drm
1356          * device lock until i915_gem_release_mmap() is able to make a
1357          * progress.
1358          */
1359         if (*mres != NULL) {
1360                 oldm = *mres;
1361                 vm_page_remove(oldm);
1362                 *mres = NULL;
1363         } else
1364                 oldm = NULL;
1365 retry:
1366         VM_OBJECT_UNLOCK(vm_obj);
1367 unlocked_vmobj:
1368         cause = ret = 0;
1369         m = NULL;
1370
1371         if (i915_intr_pf) {
1372                 ret = i915_mutex_lock_interruptible(dev);
1373                 if (ret != 0) {
1374                         cause = 10;
1375                         goto out;
1376                 }
1377         } else
1378                 mutex_lock(&dev->struct_mutex);
1379
1380         /*
1381          * Since the object lock was dropped, other thread might have
1382          * faulted on the same GTT address and instantiated the
1383          * mapping for the page.  Recheck.
1384          */
1385         VM_OBJECT_LOCK(vm_obj);
1386         m = vm_page_lookup(vm_obj, OFF_TO_IDX(offset));
1387         if (m != NULL) {
1388                 if ((m->flags & PG_BUSY) != 0) {
1389                         mutex_unlock(&dev->struct_mutex);
1390 #if 0 /* XXX */
1391                         vm_page_sleep(m, "915pee");
1392 #endif
1393                         goto retry;
1394                 }
1395                 goto have_page;
1396         } else
1397                 VM_OBJECT_UNLOCK(vm_obj);
1398
1399         trace_i915_gem_object_fault(obj, page_offset, true, write);
1400
1401         /* Access to snoopable pages through the GTT is incoherent. */
1402         if (obj->cache_level != I915_CACHE_NONE && !HAS_LLC(dev)) {
1403                 ret = -EINVAL;
1404                 goto unlock;
1405         }
1406
1407         /* Now bind it into the GTT if needed */
1408         if (!obj->map_and_fenceable) {
1409                 ret = i915_gem_object_unbind(obj);
1410                 if (ret != 0) {
1411                         cause = 20;
1412                         goto unlock;
1413                 }
1414         }
1415         if (!obj->gtt_space) {
1416                 ret = i915_gem_object_bind_to_gtt(obj, 0, true, false);
1417                 if (ret != 0) {
1418                         cause = 30;
1419                         goto unlock;
1420                 }
1421
1422                 ret = i915_gem_object_set_to_gtt_domain(obj, write);
1423                 if (ret != 0) {
1424                         cause = 40;
1425                         goto unlock;
1426                 }
1427         }
1428
1429         if (obj->tiling_mode == I915_TILING_NONE)
1430                 ret = i915_gem_object_put_fence(obj);
1431         else
1432                 ret = i915_gem_object_get_fence(obj);
1433         if (ret != 0) {
1434                 cause = 50;
1435                 goto unlock;
1436         }
1437
1438         if (i915_gem_object_is_inactive(obj))
1439                 list_move_tail(&obj->mm_list, &dev_priv->mm.inactive_list);
1440
1441         obj->fault_mappable = true;
1442         VM_OBJECT_LOCK(vm_obj);
1443         m = vm_phys_fictitious_to_vm_page(dev->agp->base + obj->gtt_offset +
1444             offset);
1445         if (m == NULL) {
1446                 cause = 60;
1447                 ret = -EFAULT;
1448                 goto unlock;
1449         }
1450         KASSERT((m->flags & PG_FICTITIOUS) != 0,
1451             ("not fictitious %p", m));
1452         KASSERT(m->wire_count == 1, ("wire_count not 1 %p", m));
1453
1454         if ((m->flags & PG_BUSY) != 0) {
1455                 mutex_unlock(&dev->struct_mutex);
1456 #if 0 /* XXX */
1457                 vm_page_sleep(m, "915pbs");
1458 #endif
1459                 goto retry;
1460         }
1461         m->valid = VM_PAGE_BITS_ALL;
1462         vm_page_insert(m, vm_obj, OFF_TO_IDX(offset));
1463 have_page:
1464         *mres = m;
1465         vm_page_busy_try(m, false);
1466
1467         mutex_unlock(&dev->struct_mutex);
1468         if (oldm != NULL) {
1469                 vm_page_free(oldm);
1470         }
1471         vm_object_pip_wakeup(vm_obj);
1472         return (VM_PAGER_OK);
1473
1474 unlock:
1475         mutex_unlock(&dev->struct_mutex);
1476 out:
1477         KASSERT(ret != 0, ("i915_gem_pager_fault: wrong return"));
1478         if (ret == -EAGAIN || ret == -EIO || ret == -EINTR) {
1479                 goto unlocked_vmobj;
1480         }
1481         VM_OBJECT_LOCK(vm_obj);
1482         vm_object_pip_wakeup(vm_obj);
1483         return (VM_PAGER_ERROR);
1484 }
1485
1486 /**
1487  * i915_gem_release_mmap - remove physical page mappings
1488  * @obj: obj in question
1489  *
1490  * Preserve the reservation of the mmapping with the DRM core code, but
1491  * relinquish ownership of the pages back to the system.
1492  *
1493  * It is vital that we remove the page mapping if we have mapped a tiled
1494  * object through the GTT and then lose the fence register due to
1495  * resource pressure. Similarly if the object has been moved out of the
1496  * aperture, than pages mapped into userspace must be revoked. Removing the
1497  * mapping will then trigger a page fault on the next user access, allowing
1498  * fixup by i915_gem_fault().
1499  */
1500 void
1501 i915_gem_release_mmap(struct drm_i915_gem_object *obj)
1502 {
1503         vm_object_t devobj;
1504         vm_page_t m;
1505         int i, page_count;
1506
1507         if (!obj->fault_mappable)
1508                 return;
1509
1510         devobj = cdev_pager_lookup(obj);
1511         if (devobj != NULL) {
1512                 page_count = OFF_TO_IDX(obj->base.size);
1513
1514                 VM_OBJECT_LOCK(devobj);
1515                 for (i = 0; i < page_count; i++) {
1516                         m = vm_page_lookup_busy_wait(devobj, i, TRUE, "915unm");
1517                         if (m == NULL)
1518                                 continue;
1519                         cdev_pager_free_page(devobj, m);
1520                 }
1521                 VM_OBJECT_UNLOCK(devobj);
1522                 vm_object_deallocate(devobj);
1523         }
1524
1525         obj->fault_mappable = false;
1526 }
1527
1528 uint32_t
1529 i915_gem_get_gtt_size(struct drm_device *dev, uint32_t size, int tiling_mode)
1530 {
1531         uint32_t gtt_size;
1532
1533         if (INTEL_INFO(dev)->gen >= 4 ||
1534             tiling_mode == I915_TILING_NONE)
1535                 return size;
1536
1537         /* Previous chips need a power-of-two fence region when tiling */
1538         if (INTEL_INFO(dev)->gen == 3)
1539                 gtt_size = 1024*1024;
1540         else
1541                 gtt_size = 512*1024;
1542
1543         while (gtt_size < size)
1544                 gtt_size <<= 1;
1545
1546         return gtt_size;
1547 }
1548
1549 /**
1550  * i915_gem_get_gtt_alignment - return required GTT alignment for an object
1551  * @obj: object to check
1552  *
1553  * Return the required GTT alignment for an object, taking into account
1554  * potential fence register mapping.
1555  */
1556 uint32_t
1557 i915_gem_get_gtt_alignment(struct drm_device *dev, uint32_t size,
1558                            int tiling_mode, bool fenced)
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         int page_count = obj->base.size / PAGE_SIZE;
1667         int i, ret;
1668
1669         if (!obj->pages)
1670                 return;
1671
1672         BUG_ON(obj->madv == __I915_MADV_PURGED);
1673
1674         ret = i915_gem_object_set_to_cpu_domain(obj, true);
1675         if (ret) {
1676                 /* In the event of a disaster, abandon all caches and
1677                  * hope for the best.
1678                  */
1679                 WARN_ON(ret != -EIO);
1680                 i915_gem_clflush_object(obj);
1681                 obj->base.read_domains = obj->base.write_domain = I915_GEM_DOMAIN_CPU;
1682         }
1683
1684         if (i915_gem_object_needs_bit17_swizzle(obj))
1685                 i915_gem_object_save_bit_17_swizzle(obj);
1686
1687         if (obj->madv == I915_MADV_DONTNEED)
1688                 obj->dirty = 0;
1689
1690         for (i = 0; i < page_count; i++) {
1691                 if (obj->dirty)
1692                         set_page_dirty(obj->pages[i]);
1693
1694                 if (obj->madv == I915_MADV_WILLNEED)
1695                         mark_page_accessed(obj->pages[i]);
1696
1697                 vm_page_busy_wait(obj->pages[i], FALSE, "i915gem");
1698                 vm_page_unwire(obj->pages[i], 1);
1699                 vm_page_wakeup(obj->pages[i]);
1700         }
1701         obj->dirty = 0;
1702
1703         kfree(obj->pages);
1704         obj->pages = NULL;
1705 }
1706
1707 int
1708 i915_gem_object_put_pages(struct drm_i915_gem_object *obj)
1709 {
1710         const struct drm_i915_gem_object_ops *ops = obj->ops;
1711
1712         if (obj->pages == NULL)
1713                 return 0;
1714
1715         BUG_ON(obj->gtt_space);
1716
1717         if (obj->pages_pin_count)
1718                 return -EBUSY;
1719
1720         /* ->put_pages might need to allocate memory for the bit17 swizzle
1721          * array, hence protect them from being reaped by removing them from gtt
1722          * lists early. */
1723         list_del(&obj->global_list);
1724
1725         ops->put_pages(obj);
1726         obj->pages = NULL;
1727
1728         if (i915_gem_object_is_purgeable(obj))
1729                 i915_gem_object_truncate(obj);
1730
1731         return 0;
1732 }
1733
1734 static long
1735 __i915_gem_shrink(struct drm_i915_private *dev_priv, long target,
1736                   bool purgeable_only)
1737 {
1738         struct drm_i915_gem_object *obj, *next;
1739         long count = 0;
1740
1741         list_for_each_entry_safe(obj, next,
1742                                  &dev_priv->mm.unbound_list,
1743                                  global_list) {
1744 #if 0
1745                 if ((i915_gem_object_is_purgeable(obj) || !purgeable_only) &&
1746                     i915_gem_object_put_pages(obj) == 0) {
1747                         count += obj->base.size >> PAGE_SHIFT;
1748                         if (count >= target)
1749                                 return count;
1750                 }
1751 #endif
1752         }
1753
1754         list_for_each_entry_safe(obj, next,
1755                                  &dev_priv->mm.inactive_list,
1756                                  mm_list) {
1757 #if 0
1758                 if ((i915_gem_object_is_purgeable(obj) || !purgeable_only) &&
1759                     i915_gem_object_unbind(obj) == 0 &&
1760                     i915_gem_object_put_pages(obj) == 0) {
1761                         count += obj->base.size >> PAGE_SHIFT;
1762                         if (count >= target)
1763                                 return count;
1764                 }
1765 #endif
1766         }
1767
1768         return count;
1769 }
1770
1771 static long
1772 i915_gem_purge(struct drm_i915_private *dev_priv, long target)
1773 {
1774         return __i915_gem_shrink(dev_priv, target, true);
1775 }
1776
1777 static int
1778 i915_gem_object_get_pages_gtt(struct drm_i915_gem_object *obj)
1779 {
1780         struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
1781         struct drm_device *dev;
1782         vm_object_t vm_obj;
1783         int page_count, i, j;
1784         struct vm_page *page;
1785
1786         dev = obj->base.dev;
1787         KASSERT(obj->pages == NULL, ("Obj already has pages"));
1788         page_count = obj->base.size / PAGE_SIZE;
1789         obj->pages = kmalloc(page_count * sizeof(vm_page_t), M_DRM,
1790             M_WAITOK);
1791
1792         vm_obj = obj->base.vm_obj;
1793         VM_OBJECT_LOCK(vm_obj);
1794
1795         for (i = 0; i < page_count; i++) {
1796                 page = shmem_read_mapping_page(vm_obj, i);
1797                 if (IS_ERR(page)) {
1798                         i915_gem_purge(dev_priv, page_count);
1799                         goto err_pages;
1800                 }
1801
1802                 obj->pages[i] = page;
1803         }
1804
1805         VM_OBJECT_UNLOCK(vm_obj);
1806         if (i915_gem_object_needs_bit17_swizzle(obj))
1807                 i915_gem_object_do_bit_17_swizzle(obj);
1808
1809         return 0;
1810
1811 err_pages:
1812         for (j = 0; j < i; j++) {
1813                 page = obj->pages[j];
1814                 vm_page_busy_wait(page, FALSE, "i915gem");
1815                 vm_page_unwire(page, 0);
1816                 vm_page_wakeup(page);
1817         }
1818         VM_OBJECT_UNLOCK(vm_obj);
1819         drm_free(obj->pages, M_DRM);
1820         obj->pages = NULL;
1821         return (-EIO);
1822 }
1823
1824 /* Ensure that the associated pages are gathered from the backing storage
1825  * and pinned into our object. i915_gem_object_get_pages() may be called
1826  * multiple times before they are released by a single call to
1827  * i915_gem_object_put_pages() - once the pages are no longer referenced
1828  * either as a result of memory pressure (reaping pages under the shrinker)
1829  * or as the object is itself released.
1830  */
1831 int
1832 i915_gem_object_get_pages(struct drm_i915_gem_object *obj)
1833 {
1834         struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
1835         const struct drm_i915_gem_object_ops *ops = obj->ops;
1836         int ret;
1837
1838         if (obj->pages)
1839                 return 0;
1840
1841         if (obj->madv != I915_MADV_WILLNEED) {
1842                 DRM_ERROR("Attempting to obtain a purgeable object\n");
1843                 return -EINVAL;
1844         }
1845
1846         BUG_ON(obj->pages_pin_count);
1847
1848         ret = ops->get_pages(obj);
1849         if (ret)
1850                 return ret;
1851
1852         list_add_tail(&obj->global_list, &dev_priv->mm.unbound_list);
1853         return 0;
1854 }
1855
1856 void
1857 i915_gem_object_move_to_active(struct drm_i915_gem_object *obj,
1858                                struct intel_ring_buffer *ring)
1859 {
1860         struct drm_device *dev = obj->base.dev;
1861         struct drm_i915_private *dev_priv = dev->dev_private;
1862         u32 seqno = intel_ring_get_seqno(ring);
1863
1864         BUG_ON(ring == NULL);
1865         if (obj->ring != ring && obj->last_write_seqno) {
1866                 /* Keep the seqno relative to the current ring */
1867                 obj->last_write_seqno = seqno;
1868         }
1869         obj->ring = ring;
1870
1871         /* Add a reference if we're newly entering the active list. */
1872         if (!obj->active) {
1873                 drm_gem_object_reference(&obj->base);
1874                 obj->active = 1;
1875         }
1876
1877         /* Move from whatever list we were on to the tail of execution. */
1878         list_move_tail(&obj->mm_list, &dev_priv->mm.active_list);
1879         list_move_tail(&obj->ring_list, &ring->active_list);
1880
1881         obj->last_read_seqno = seqno;
1882
1883         if (obj->fenced_gpu_access) {
1884                 obj->last_fenced_seqno = seqno;
1885
1886                 /* Bump MRU to take account of the delayed flush */
1887                 if (obj->fence_reg != I915_FENCE_REG_NONE) {
1888                         struct drm_i915_fence_reg *reg;
1889
1890                         reg = &dev_priv->fence_regs[obj->fence_reg];
1891                         list_move_tail(&reg->lru_list,
1892                                        &dev_priv->mm.fence_list);
1893                 }
1894         }
1895 }
1896
1897 static void
1898 i915_gem_object_move_to_inactive(struct drm_i915_gem_object *obj)
1899 {
1900         struct drm_device *dev = obj->base.dev;
1901         struct drm_i915_private *dev_priv = dev->dev_private;
1902
1903         BUG_ON(obj->base.write_domain & ~I915_GEM_GPU_DOMAINS);
1904         BUG_ON(!obj->active);
1905
1906         list_move_tail(&obj->mm_list, &dev_priv->mm.inactive_list);
1907
1908         list_del_init(&obj->ring_list);
1909         obj->ring = NULL;
1910
1911         obj->last_read_seqno = 0;
1912         obj->last_write_seqno = 0;
1913         obj->base.write_domain = 0;
1914
1915         obj->last_fenced_seqno = 0;
1916         obj->fenced_gpu_access = false;
1917
1918         obj->active = 0;
1919         drm_gem_object_unreference(&obj->base);
1920
1921         WARN_ON(i915_verify_lists(dev));
1922 }
1923
1924 static int
1925 i915_gem_init_seqno(struct drm_device *dev, u32 seqno)
1926 {
1927         struct drm_i915_private *dev_priv = dev->dev_private;
1928         struct intel_ring_buffer *ring;
1929         int ret, i, j;
1930
1931         /* Carefully retire all requests without writing to the rings */
1932         for_each_ring(ring, dev_priv, i) {
1933                 ret = intel_ring_idle(ring);
1934                 if (ret)
1935                         return ret;
1936         }
1937         i915_gem_retire_requests(dev);
1938
1939         /* Finally reset hw state */
1940         for_each_ring(ring, dev_priv, i) {
1941                 intel_ring_init_seqno(ring, seqno);
1942
1943                 for (j = 0; j < ARRAY_SIZE(ring->sync_seqno); j++)
1944                         ring->sync_seqno[j] = 0;
1945         }
1946
1947         return 0;
1948 }
1949
1950 int i915_gem_set_seqno(struct drm_device *dev, u32 seqno)
1951 {
1952         struct drm_i915_private *dev_priv = dev->dev_private;
1953         int ret;
1954
1955         if (seqno == 0)
1956                 return -EINVAL;
1957
1958         /* HWS page needs to be set less than what we
1959          * will inject to ring
1960          */
1961         ret = i915_gem_init_seqno(dev, seqno - 1);
1962         if (ret)
1963                 return ret;
1964
1965         /* Carefully set the last_seqno value so that wrap
1966          * detection still works
1967          */
1968         dev_priv->next_seqno = seqno;
1969         dev_priv->last_seqno = seqno - 1;
1970         if (dev_priv->last_seqno == 0)
1971                 dev_priv->last_seqno--;
1972
1973         return 0;
1974 }
1975
1976 int
1977 i915_gem_get_seqno(struct drm_device *dev, u32 *seqno)
1978 {
1979         struct drm_i915_private *dev_priv = dev->dev_private;
1980
1981         /* reserve 0 for non-seqno */
1982         if (dev_priv->next_seqno == 0) {
1983                 int ret = i915_gem_init_seqno(dev, 0);
1984                 if (ret)
1985                         return ret;
1986
1987                 dev_priv->next_seqno = 1;
1988         }
1989
1990         *seqno = dev_priv->last_seqno = dev_priv->next_seqno++;
1991         return 0;
1992 }
1993
1994 int __i915_add_request(struct intel_ring_buffer *ring,
1995                        struct drm_file *file,
1996                        struct drm_i915_gem_object *obj,
1997                        u32 *out_seqno)
1998 {
1999         drm_i915_private_t *dev_priv = ring->dev->dev_private;
2000         struct drm_i915_gem_request *request;
2001         u32 request_ring_position, request_start;
2002         int was_empty;
2003         int ret;
2004
2005         request_start = intel_ring_get_tail(ring);
2006         /*
2007          * Emit any outstanding flushes - execbuf can fail to emit the flush
2008          * after having emitted the batchbuffer command. Hence we need to fix
2009          * things up similar to emitting the lazy request. The difference here
2010          * is that the flush _must_ happen before the next request, no matter
2011          * what.
2012          */
2013         ret = intel_ring_flush_all_caches(ring);
2014         if (ret)
2015                 return ret;
2016
2017         request = kmalloc(sizeof(*request), M_DRM, M_WAITOK);
2018         if (request == NULL)
2019                 return -ENOMEM;
2020
2021
2022         /* Record the position of the start of the request so that
2023          * should we detect the updated seqno part-way through the
2024          * GPU processing the request, we never over-estimate the
2025          * position of the head.
2026          */
2027         request_ring_position = intel_ring_get_tail(ring);
2028
2029         ret = ring->add_request(ring);
2030         if (ret) {
2031                 kfree(request);
2032                 return ret;
2033         }
2034
2035         request->seqno = intel_ring_get_seqno(ring);
2036         request->ring = ring;
2037         request->head = request_start;
2038         request->tail = request_ring_position;
2039         request->ctx = ring->last_context;
2040         request->batch_obj = obj;
2041
2042         /* Whilst this request exists, batch_obj will be on the
2043          * active_list, and so will hold the active reference. Only when this
2044          * request is retired will the the batch_obj be moved onto the
2045          * inactive_list and lose its active reference. Hence we do not need
2046          * to explicitly hold another reference here.
2047          */
2048
2049         if (request->ctx)
2050                 i915_gem_context_reference(request->ctx);
2051
2052         request->emitted_jiffies = jiffies;
2053         was_empty = list_empty(&ring->request_list);
2054         list_add_tail(&request->list, &ring->request_list);
2055         request->file_priv = NULL;
2056
2057         if (file) {
2058                 struct drm_i915_file_private *file_priv = file->driver_priv;
2059
2060                 spin_lock(&file_priv->mm.lock);
2061                 request->file_priv = file_priv;
2062                 list_add_tail(&request->client_list,
2063                               &file_priv->mm.request_list);
2064                 spin_unlock(&file_priv->mm.lock);
2065         }
2066
2067         trace_i915_gem_request_add(ring, request->seqno);
2068         ring->outstanding_lazy_request = 0;
2069
2070         if (!dev_priv->mm.suspended) {
2071                 if (i915_enable_hangcheck) {
2072                         mod_timer(&dev_priv->gpu_error.hangcheck_timer,
2073                                   round_jiffies_up(jiffies + DRM_I915_HANGCHECK_JIFFIES));
2074                 }
2075                 if (was_empty) {
2076                         queue_delayed_work(dev_priv->wq,
2077                                            &dev_priv->mm.retire_work,
2078                                            round_jiffies_up_relative(hz));
2079                         intel_mark_busy(dev_priv->dev);
2080                 }
2081         }
2082
2083         if (out_seqno)
2084                 *out_seqno = request->seqno;
2085         return 0;
2086 }
2087
2088 static inline void
2089 i915_gem_request_remove_from_client(struct drm_i915_gem_request *request)
2090 {
2091         struct drm_i915_file_private *file_priv = request->file_priv;
2092
2093         if (!file_priv)
2094                 return;
2095
2096         spin_lock(&file_priv->mm.lock);
2097         if (request->file_priv) {
2098                 list_del(&request->client_list);
2099                 request->file_priv = NULL;
2100         }
2101         spin_unlock(&file_priv->mm.lock);
2102 }
2103
2104 static bool i915_head_inside_object(u32 acthd, struct drm_i915_gem_object *obj)
2105 {
2106         if (acthd >= obj->gtt_offset &&
2107             acthd < obj->gtt_offset + obj->base.size)
2108                 return true;
2109
2110         return false;
2111 }
2112
2113 static bool i915_head_inside_request(const u32 acthd_unmasked,
2114                                      const u32 request_start,
2115                                      const u32 request_end)
2116 {
2117         const u32 acthd = acthd_unmasked & HEAD_ADDR;
2118
2119         if (request_start < request_end) {
2120                 if (acthd >= request_start && acthd < request_end)
2121                         return true;
2122         } else if (request_start > request_end) {
2123                 if (acthd >= request_start || acthd < request_end)
2124                         return true;
2125         }
2126
2127         return false;
2128 }
2129
2130 static bool i915_request_guilty(struct drm_i915_gem_request *request,
2131                                 const u32 acthd, bool *inside)
2132 {
2133         /* There is a possibility that unmasked head address
2134          * pointing inside the ring, matches the batch_obj address range.
2135          * However this is extremely unlikely.
2136          */
2137
2138         if (request->batch_obj) {
2139                 if (i915_head_inside_object(acthd, request->batch_obj)) {
2140                         *inside = true;
2141                         return true;
2142                 }
2143         }
2144
2145         if (i915_head_inside_request(acthd, request->head, request->tail)) {
2146                 *inside = false;
2147                 return true;
2148         }
2149
2150         return false;
2151 }
2152
2153 static void i915_set_reset_status(struct intel_ring_buffer *ring,
2154                                   struct drm_i915_gem_request *request,
2155                                   u32 acthd)
2156 {
2157         struct i915_ctx_hang_stats *hs = NULL;
2158         bool inside, guilty;
2159
2160         /* Innocent until proven guilty */
2161         guilty = false;
2162
2163         if (ring->hangcheck.action != wait &&
2164             i915_request_guilty(request, acthd, &inside)) {
2165                 DRM_ERROR("%s hung %s bo (0x%x ctx %d) at 0x%x\n",
2166                           ring->name,
2167                           inside ? "inside" : "flushing",
2168                           request->batch_obj ?
2169                           request->batch_obj->gtt_offset : 0,
2170                           request->ctx ? request->ctx->id : 0,
2171                           acthd);
2172
2173                 guilty = true;
2174         }
2175
2176         /* If contexts are disabled or this is the default context, use
2177          * file_priv->reset_state
2178          */
2179         if (request->ctx && request->ctx->id != DEFAULT_CONTEXT_ID)
2180                 hs = &request->ctx->hang_stats;
2181         else if (request->file_priv)
2182                 hs = &request->file_priv->hang_stats;
2183
2184         if (hs) {
2185                 if (guilty)
2186                         hs->batch_active++;
2187                 else
2188                         hs->batch_pending++;
2189         }
2190 }
2191
2192 static void i915_gem_free_request(struct drm_i915_gem_request *request)
2193 {
2194         list_del(&request->list);
2195         i915_gem_request_remove_from_client(request);
2196
2197         if (request->ctx)
2198                 i915_gem_context_unreference(request->ctx);
2199
2200         kfree(request);
2201 }
2202
2203 static void i915_gem_reset_ring_lists(struct drm_i915_private *dev_priv,
2204                                       struct intel_ring_buffer *ring)
2205 {
2206         u32 completed_seqno;
2207         u32 acthd;
2208
2209         acthd = intel_ring_get_active_head(ring);
2210         completed_seqno = ring->get_seqno(ring, false);
2211
2212         while (!list_empty(&ring->request_list)) {
2213                 struct drm_i915_gem_request *request;
2214
2215                 request = list_first_entry(&ring->request_list,
2216                                            struct drm_i915_gem_request,
2217                                            list);
2218
2219                 if (request->seqno > completed_seqno)
2220                         i915_set_reset_status(ring, request, acthd);
2221
2222                 i915_gem_free_request(request);
2223         }
2224
2225         while (!list_empty(&ring->active_list)) {
2226                 struct drm_i915_gem_object *obj;
2227
2228                 obj = list_first_entry(&ring->active_list,
2229                                        struct drm_i915_gem_object,
2230                                        ring_list);
2231
2232                 i915_gem_object_move_to_inactive(obj);
2233         }
2234 }
2235
2236 void i915_gem_restore_fences(struct drm_device *dev)
2237 {
2238         struct drm_i915_private *dev_priv = dev->dev_private;
2239         int i;
2240
2241         for (i = 0; i < dev_priv->num_fence_regs; i++) {
2242                 struct drm_i915_fence_reg *reg = &dev_priv->fence_regs[i];
2243
2244                 /*
2245                  * Commit delayed tiling changes if we have an object still
2246                  * attached to the fence, otherwise just clear the fence.
2247                  */
2248                 if (reg->obj) {
2249                         i915_gem_object_update_fence(reg->obj, reg,
2250                                                      reg->obj->tiling_mode);
2251                 } else {
2252                         i915_gem_write_fence(dev, i, NULL);
2253                 }
2254         }
2255 }
2256
2257 void i915_gem_reset(struct drm_device *dev)
2258 {
2259         struct drm_i915_private *dev_priv = dev->dev_private;
2260         struct drm_i915_gem_object *obj;
2261         struct intel_ring_buffer *ring;
2262         int i;
2263
2264         for_each_ring(ring, dev_priv, i)
2265                 i915_gem_reset_ring_lists(dev_priv, ring);
2266
2267         /* Move everything out of the GPU domains to ensure we do any
2268          * necessary invalidation upon reuse.
2269          */
2270         list_for_each_entry(obj,
2271                             &dev_priv->mm.inactive_list,
2272                             mm_list)
2273         {
2274                 obj->base.read_domains &= ~I915_GEM_GPU_DOMAINS;
2275         }
2276
2277         i915_gem_restore_fences(dev);
2278 }
2279
2280 /**
2281  * This function clears the request list as sequence numbers are passed.
2282  */
2283 void
2284 i915_gem_retire_requests_ring(struct intel_ring_buffer *ring)
2285 {
2286         uint32_t seqno;
2287
2288         if (list_empty(&ring->request_list))
2289                 return;
2290
2291         WARN_ON(i915_verify_lists(ring->dev));
2292
2293         seqno = ring->get_seqno(ring, true);
2294
2295         while (!list_empty(&ring->request_list)) {
2296                 struct drm_i915_gem_request *request;
2297
2298                 request = list_first_entry(&ring->request_list,
2299                                            struct drm_i915_gem_request,
2300                                            list);
2301
2302                 if (!i915_seqno_passed(seqno, request->seqno))
2303                         break;
2304
2305                 trace_i915_gem_request_retire(ring, request->seqno);
2306                 /* We know the GPU must have read the request to have
2307                  * sent us the seqno + interrupt, so use the position
2308                  * of tail of the request to update the last known position
2309                  * of the GPU head.
2310                  */
2311                 ring->last_retired_head = request->tail;
2312
2313                 i915_gem_free_request(request);
2314         }
2315
2316         /* Move any buffers on the active list that are no longer referenced
2317          * by the ringbuffer to the flushing/inactive lists as appropriate.
2318          */
2319         while (!list_empty(&ring->active_list)) {
2320                 struct drm_i915_gem_object *obj;
2321
2322                 obj = list_first_entry(&ring->active_list,
2323                                       struct drm_i915_gem_object,
2324                                       ring_list);
2325
2326                 if (!i915_seqno_passed(seqno, obj->last_read_seqno))
2327                         break;
2328
2329                 i915_gem_object_move_to_inactive(obj);
2330         }
2331
2332         if (unlikely(ring->trace_irq_seqno &&
2333                      i915_seqno_passed(seqno, ring->trace_irq_seqno))) {
2334                 ring->irq_put(ring);
2335                 ring->trace_irq_seqno = 0;
2336         }
2337
2338 }
2339
2340 void
2341 i915_gem_retire_requests(struct drm_device *dev)
2342 {
2343         drm_i915_private_t *dev_priv = dev->dev_private;
2344         struct intel_ring_buffer *ring;
2345         int i;
2346
2347         for_each_ring(ring, dev_priv, i)
2348                 i915_gem_retire_requests_ring(ring);
2349 }
2350
2351 static void
2352 i915_gem_retire_work_handler(struct work_struct *work)
2353 {
2354         drm_i915_private_t *dev_priv;
2355         struct drm_device *dev;
2356         struct intel_ring_buffer *ring;
2357         bool idle;
2358         int i;
2359
2360         dev_priv = container_of(work, drm_i915_private_t,
2361                                 mm.retire_work.work);
2362         dev = dev_priv->dev;
2363
2364         /* Come back later if the device is busy... */
2365         if (lockmgr(&dev->struct_mutex, LK_EXCLUSIVE|LK_NOWAIT)) {
2366                 queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work,
2367                                    round_jiffies_up_relative(hz));
2368                 return;
2369         }
2370
2371         i915_gem_retire_requests(dev);
2372
2373         /* Send a periodic flush down the ring so we don't hold onto GEM
2374          * objects indefinitely.
2375          */
2376         idle = true;
2377         for_each_ring(ring, dev_priv, i) {
2378                 if (ring->gpu_caches_dirty)
2379                         i915_add_request(ring, NULL);
2380
2381                 idle &= list_empty(&ring->request_list);
2382         }
2383
2384         if (!dev_priv->mm.suspended && !idle)
2385                 queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work,
2386                                    round_jiffies_up_relative(hz));
2387         if (idle)
2388                 intel_mark_idle(dev);
2389
2390         mutex_unlock(&dev->struct_mutex);
2391 }
2392 /**
2393  * Ensures that an object will eventually get non-busy by flushing any required
2394  * write domains, emitting any outstanding lazy request and retiring and
2395  * completed requests.
2396  */
2397 static int
2398 i915_gem_object_flush_active(struct drm_i915_gem_object *obj)
2399 {
2400         int ret;
2401
2402         if (obj->active) {
2403                 ret = i915_gem_check_olr(obj->ring, obj->last_read_seqno);
2404                 if (ret)
2405                         return ret;
2406
2407                 i915_gem_retire_requests_ring(obj->ring);
2408         }
2409
2410         return 0;
2411 }
2412
2413 /**
2414  * i915_gem_wait_ioctl - implements DRM_IOCTL_I915_GEM_WAIT
2415  * @DRM_IOCTL_ARGS: standard ioctl arguments
2416  *
2417  * Returns 0 if successful, else an error is returned with the remaining time in
2418  * the timeout parameter.
2419  *  -ETIME: object is still busy after timeout
2420  *  -ERESTARTSYS: signal interrupted the wait
2421  *  -ENONENT: object doesn't exist
2422  * Also possible, but rare:
2423  *  -EAGAIN: GPU wedged
2424  *  -ENOMEM: damn
2425  *  -ENODEV: Internal IRQ fail
2426  *  -E?: The add request failed
2427  *
2428  * The wait ioctl with a timeout of 0 reimplements the busy ioctl. With any
2429  * non-zero timeout parameter the wait ioctl will wait for the given number of
2430  * nanoseconds on an object becoming unbusy. Since the wait itself does so
2431  * without holding struct_mutex the object may become re-busied before this
2432  * function completes. A similar but shorter * race condition exists in the busy
2433  * ioctl
2434  */
2435 int
2436 i915_gem_wait_ioctl(struct drm_device *dev, void *data, struct drm_file *file)
2437 {
2438         drm_i915_private_t *dev_priv = dev->dev_private;
2439         struct drm_i915_gem_wait *args = data;
2440         struct drm_i915_gem_object *obj;
2441         struct intel_ring_buffer *ring = NULL;
2442         struct timespec timeout_stack, *timeout = NULL;
2443         unsigned reset_counter;
2444         u32 seqno = 0;
2445         int ret = 0;
2446
2447         if (args->timeout_ns >= 0) {
2448                 timeout_stack = ns_to_timespec(args->timeout_ns);
2449                 timeout = &timeout_stack;
2450         }
2451
2452         ret = i915_mutex_lock_interruptible(dev);
2453         if (ret)
2454                 return ret;
2455
2456         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->bo_handle));
2457         if (&obj->base == NULL) {
2458                 mutex_unlock(&dev->struct_mutex);
2459                 return -ENOENT;
2460         }
2461
2462         /* Need to make sure the object gets inactive eventually. */
2463         ret = i915_gem_object_flush_active(obj);
2464         if (ret)
2465                 goto out;
2466
2467         if (obj->active) {
2468                 seqno = obj->last_read_seqno;
2469                 ring = obj->ring;
2470         }
2471
2472         if (seqno == 0)
2473                  goto out;
2474
2475         /* Do this after OLR check to make sure we make forward progress polling
2476          * on this IOCTL with a 0 timeout (like busy ioctl)
2477          */
2478         if (!args->timeout_ns) {
2479                 ret = -ETIMEDOUT;
2480                 goto out;
2481         }
2482
2483         drm_gem_object_unreference(&obj->base);
2484         reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
2485         mutex_unlock(&dev->struct_mutex);
2486
2487         ret = __wait_seqno(ring, seqno, reset_counter, true, timeout);
2488         if (timeout)
2489                 args->timeout_ns = timespec_to_ns(timeout);
2490         return ret;
2491
2492 out:
2493         drm_gem_object_unreference(&obj->base);
2494         mutex_unlock(&dev->struct_mutex);
2495         return ret;
2496 }
2497
2498 /**
2499  * i915_gem_object_sync - sync an object to a ring.
2500  *
2501  * @obj: object which may be in use on another ring.
2502  * @to: ring we wish to use the object on. May be NULL.
2503  *
2504  * This code is meant to abstract object synchronization with the GPU.
2505  * Calling with NULL implies synchronizing the object with the CPU
2506  * rather than a particular GPU ring.
2507  *
2508  * Returns 0 if successful, else propagates up the lower layer error.
2509  */
2510 int
2511 i915_gem_object_sync(struct drm_i915_gem_object *obj,
2512                      struct intel_ring_buffer *to)
2513 {
2514         struct intel_ring_buffer *from = obj->ring;
2515         u32 seqno;
2516         int ret, idx;
2517
2518         if (from == NULL || to == from)
2519                 return 0;
2520
2521         if (to == NULL || !i915_semaphore_is_enabled(obj->base.dev))
2522                 return i915_gem_object_wait_rendering(obj, false);
2523
2524         idx = intel_ring_sync_index(from, to);
2525
2526         seqno = obj->last_read_seqno;
2527         if (seqno <= from->sync_seqno[idx])
2528                 return 0;
2529
2530         ret = i915_gem_check_olr(obj->ring, seqno);
2531         if (ret)
2532                 return ret;
2533
2534         ret = to->sync_to(to, from, seqno);
2535         if (!ret)
2536                 /* We use last_read_seqno because sync_to()
2537                  * might have just caused seqno wrap under
2538                  * the radar.
2539                  */
2540                 from->sync_seqno[idx] = obj->last_read_seqno;
2541
2542         return ret;
2543 }
2544
2545 static void i915_gem_object_finish_gtt(struct drm_i915_gem_object *obj)
2546 {
2547         u32 old_write_domain, old_read_domains;
2548
2549         /* Force a pagefault for domain tracking on next user access */
2550         i915_gem_release_mmap(obj);
2551
2552         if ((obj->base.read_domains & I915_GEM_DOMAIN_GTT) == 0)
2553                 return;
2554
2555         /* Wait for any direct GTT access to complete */
2556         cpu_mfence();
2557
2558         old_read_domains = obj->base.read_domains;
2559         old_write_domain = obj->base.write_domain;
2560
2561         obj->base.read_domains &= ~I915_GEM_DOMAIN_GTT;
2562         obj->base.write_domain &= ~I915_GEM_DOMAIN_GTT;
2563
2564         trace_i915_gem_object_change_domain(obj,
2565                                             old_read_domains,
2566                                             old_write_domain);
2567 }
2568
2569 /**
2570  * Unbinds an object from the GTT aperture.
2571  */
2572 int
2573 i915_gem_object_unbind(struct drm_i915_gem_object *obj)
2574 {
2575         drm_i915_private_t *dev_priv = obj->base.dev->dev_private;
2576         int ret;
2577
2578         if (obj->gtt_space == NULL)
2579                 return 0;
2580
2581         if (obj->pin_count)
2582                 return -EBUSY;
2583
2584         BUG_ON(obj->pages == NULL);
2585
2586         ret = i915_gem_object_finish_gpu(obj);
2587         if (ret)
2588                 return ret;
2589         /* Continue on if we fail due to EIO, the GPU is hung so we
2590          * should be safe and we need to cleanup or else we might
2591          * cause memory corruption through use-after-free.
2592          */
2593
2594         i915_gem_object_finish_gtt(obj);
2595
2596         /* Move the object to the CPU domain to ensure that
2597          * any possible CPU writes while it's not in the GTT
2598          * are flushed when we go to remap it.
2599          */
2600         if (ret == 0)
2601                 ret = i915_gem_object_set_to_cpu_domain(obj, 1);
2602         if (ret == -ERESTARTSYS)
2603                 return ret;
2604         if (ret) {
2605                 /* In the event of a disaster, abandon all caches and
2606                  * hope for the best.
2607                  */
2608                 i915_gem_clflush_object(obj);
2609                 obj->base.read_domains = obj->base.write_domain = I915_GEM_DOMAIN_CPU;
2610         }
2611
2612         /* release the fence reg _after_ flushing */
2613         ret = i915_gem_object_put_fence(obj);
2614         if (ret)
2615                 return ret;
2616
2617         trace_i915_gem_object_unbind(obj);
2618
2619         if (obj->has_global_gtt_mapping)
2620                 i915_gem_gtt_unbind_object(obj);
2621         if (obj->has_aliasing_ppgtt_mapping) {
2622                 i915_ppgtt_unbind_object(dev_priv->mm.aliasing_ppgtt, obj);
2623                 obj->has_aliasing_ppgtt_mapping = 0;
2624         }
2625         i915_gem_gtt_finish_object(obj);
2626
2627         i915_gem_object_put_pages_gtt(obj);
2628
2629         list_del_init(&obj->global_list);
2630         list_del_init(&obj->mm_list);
2631         /* Avoid an unnecessary call to unbind on rebind. */
2632         obj->map_and_fenceable = true;
2633
2634         drm_mm_put_block(obj->gtt_space);
2635         obj->gtt_space = NULL;
2636         obj->gtt_offset = 0;
2637
2638         if (i915_gem_object_is_purgeable(obj))
2639                 i915_gem_object_truncate(obj);
2640
2641         return ret;
2642 }
2643
2644 int i915_gpu_idle(struct drm_device *dev)
2645 {
2646         drm_i915_private_t *dev_priv = dev->dev_private;
2647         struct intel_ring_buffer *ring;
2648         int ret, i;
2649
2650         /* Flush everything onto the inactive list. */
2651         for_each_ring(ring, dev_priv, i) {
2652                 ret = i915_switch_context(ring, NULL, DEFAULT_CONTEXT_ID);
2653                 if (ret)
2654                         return ret;
2655
2656                 ret = intel_ring_idle(ring);
2657                 if (ret)
2658                         return ret;
2659         }
2660
2661         return 0;
2662 }
2663
2664 static void i965_write_fence_reg(struct drm_device *dev, int reg,
2665                                  struct drm_i915_gem_object *obj)
2666 {
2667         drm_i915_private_t *dev_priv = dev->dev_private;
2668         int fence_reg;
2669         int fence_pitch_shift;
2670
2671         if (INTEL_INFO(dev)->gen >= 6) {
2672                 fence_reg = FENCE_REG_SANDYBRIDGE_0;
2673                 fence_pitch_shift = SANDYBRIDGE_FENCE_PITCH_SHIFT;
2674         } else {
2675                 fence_reg = FENCE_REG_965_0;
2676                 fence_pitch_shift = I965_FENCE_PITCH_SHIFT;
2677         }
2678
2679         fence_reg += reg * 8;
2680
2681         /* To w/a incoherency with non-atomic 64-bit register updates,
2682          * we split the 64-bit update into two 32-bit writes. In order
2683          * for a partial fence not to be evaluated between writes, we
2684          * precede the update with write to turn off the fence register,
2685          * and only enable the fence as the last step.
2686          *
2687          * For extra levels of paranoia, we make sure each step lands
2688          * before applying the next step.
2689          */
2690         I915_WRITE(fence_reg, 0);
2691         POSTING_READ(fence_reg);
2692
2693         if (obj) {
2694                 u32 size = obj->gtt_space->size;
2695                 uint64_t val;
2696
2697                 val = (uint64_t)((obj->gtt_offset + size - 4096) &
2698                                  0xfffff000) << 32;
2699                 val |= obj->gtt_offset & 0xfffff000;
2700                 val |= (uint64_t)((obj->stride / 128) - 1) << fence_pitch_shift;
2701                 if (obj->tiling_mode == I915_TILING_Y)
2702                         val |= 1 << I965_FENCE_TILING_Y_SHIFT;
2703                 val |= I965_FENCE_REG_VALID;
2704
2705                 I915_WRITE(fence_reg + 4, val >> 32);
2706                 POSTING_READ(fence_reg + 4);
2707
2708                 I915_WRITE(fence_reg + 0, val);
2709                 POSTING_READ(fence_reg);
2710         } else {
2711                 I915_WRITE(fence_reg + 4, 0);
2712                 POSTING_READ(fence_reg + 4);
2713         }
2714 }
2715
2716 static void i915_write_fence_reg(struct drm_device *dev, int reg,
2717                                  struct drm_i915_gem_object *obj)
2718 {
2719         drm_i915_private_t *dev_priv = dev->dev_private;
2720         u32 val;
2721
2722         if (obj) {
2723                 u32 size = obj->gtt_space->size;
2724                 int pitch_val;
2725                 int tile_width;
2726
2727                 WARN((obj->gtt_offset & ~I915_FENCE_START_MASK) ||
2728                      (size & -size) != size ||
2729                      (obj->gtt_offset & (size - 1)),
2730                      "object 0x%08x [fenceable? %d] not 1M or pot-size (0x%08x) aligned\n",
2731                      obj->gtt_offset, obj->map_and_fenceable, size);
2732
2733                 if (obj->tiling_mode == I915_TILING_Y && HAS_128_BYTE_Y_TILING(dev))
2734                         tile_width = 128;
2735                 else
2736                         tile_width = 512;
2737
2738                 /* Note: pitch better be a power of two tile widths */
2739                 pitch_val = obj->stride / tile_width;
2740                 pitch_val = ffs(pitch_val) - 1;
2741
2742                 val = obj->gtt_offset;
2743                 if (obj->tiling_mode == I915_TILING_Y)
2744                         val |= 1 << I830_FENCE_TILING_Y_SHIFT;
2745                 val |= I915_FENCE_SIZE_BITS(size);
2746                 val |= pitch_val << I830_FENCE_PITCH_SHIFT;
2747                 val |= I830_FENCE_REG_VALID;
2748         } else
2749                 val = 0;
2750
2751         if (reg < 8)
2752                 reg = FENCE_REG_830_0 + reg * 4;
2753         else
2754                 reg = FENCE_REG_945_8 + (reg - 8) * 4;
2755
2756         I915_WRITE(reg, val);
2757         POSTING_READ(reg);
2758 }
2759
2760 static void i830_write_fence_reg(struct drm_device *dev, int reg,
2761                                 struct drm_i915_gem_object *obj)
2762 {
2763         drm_i915_private_t *dev_priv = dev->dev_private;
2764         uint32_t val;
2765
2766         if (obj) {
2767                 u32 size = obj->gtt_space->size;
2768                 uint32_t pitch_val;
2769
2770                 WARN((obj->gtt_offset & ~I830_FENCE_START_MASK) ||
2771                      (size & -size) != size ||
2772                      (obj->gtt_offset & (size - 1)),
2773                      "object 0x%08x not 512K or pot-size 0x%08x aligned\n",
2774                      obj->gtt_offset, size);
2775
2776                 pitch_val = obj->stride / 128;
2777                 pitch_val = ffs(pitch_val) - 1;
2778
2779                 val = obj->gtt_offset;
2780                 if (obj->tiling_mode == I915_TILING_Y)
2781                         val |= 1 << I830_FENCE_TILING_Y_SHIFT;
2782                 val |= I830_FENCE_SIZE_BITS(size);
2783                 val |= pitch_val << I830_FENCE_PITCH_SHIFT;
2784                 val |= I830_FENCE_REG_VALID;
2785         } else
2786                 val = 0;
2787
2788         I915_WRITE(FENCE_REG_830_0 + reg * 4, val);
2789         POSTING_READ(FENCE_REG_830_0 + reg * 4);
2790 }
2791
2792 inline static bool i915_gem_object_needs_mb(struct drm_i915_gem_object *obj)
2793 {
2794         return obj && obj->base.read_domains & I915_GEM_DOMAIN_GTT;
2795 }
2796
2797 static void i915_gem_write_fence(struct drm_device *dev, int reg,
2798                                  struct drm_i915_gem_object *obj)
2799 {
2800         struct drm_i915_private *dev_priv = dev->dev_private;
2801
2802         /* Ensure that all CPU reads are completed before installing a fence
2803          * and all writes before removing the fence.
2804          */
2805         if (i915_gem_object_needs_mb(dev_priv->fence_regs[reg].obj))
2806                 cpu_mfence();
2807
2808         WARN(obj && (!obj->stride || !obj->tiling_mode),
2809              "bogus fence setup with stride: 0x%x, tiling mode: %i\n",
2810              obj->stride, obj->tiling_mode);
2811
2812         switch (INTEL_INFO(dev)->gen) {
2813         case 7:
2814         case 6:
2815         case 5:
2816         case 4: i965_write_fence_reg(dev, reg, obj); break;
2817         case 3: i915_write_fence_reg(dev, reg, obj); break;
2818         case 2: i830_write_fence_reg(dev, reg, obj); break;
2819         default: BUG();
2820         }
2821
2822         /* And similarly be paranoid that no direct access to this region
2823          * is reordered to before the fence is installed.
2824          */
2825         if (i915_gem_object_needs_mb(obj))
2826                 cpu_mfence();
2827 }
2828
2829 static inline int fence_number(struct drm_i915_private *dev_priv,
2830                                struct drm_i915_fence_reg *fence)
2831 {
2832         return fence - dev_priv->fence_regs;
2833 }
2834
2835 static void i915_gem_object_update_fence(struct drm_i915_gem_object *obj,
2836                                          struct drm_i915_fence_reg *fence,
2837                                          bool enable)
2838 {
2839         struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
2840         int reg = fence_number(dev_priv, fence);
2841
2842         i915_gem_write_fence(obj->base.dev, reg, enable ? obj : NULL);
2843
2844         if (enable) {
2845                 obj->fence_reg = reg;
2846                 fence->obj = obj;
2847                 list_move_tail(&fence->lru_list, &dev_priv->mm.fence_list);
2848         } else {
2849                 obj->fence_reg = I915_FENCE_REG_NONE;
2850                 fence->obj = NULL;
2851                 list_del_init(&fence->lru_list);
2852         }
2853         obj->fence_dirty = false;
2854 }
2855
2856 static int
2857 i915_gem_object_wait_fence(struct drm_i915_gem_object *obj)
2858 {
2859         if (obj->last_fenced_seqno) {
2860                 int ret = i915_wait_seqno(obj->ring, obj->last_fenced_seqno);
2861                 if (ret)
2862                         return ret;
2863
2864                 obj->last_fenced_seqno = 0;
2865         }
2866
2867         obj->fenced_gpu_access = false;
2868         return 0;
2869 }
2870
2871 int
2872 i915_gem_object_put_fence(struct drm_i915_gem_object *obj)
2873 {
2874         struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
2875         struct drm_i915_fence_reg *fence;
2876         int ret;
2877
2878         ret = i915_gem_object_wait_fence(obj);
2879         if (ret)
2880                 return ret;
2881
2882         if (obj->fence_reg == I915_FENCE_REG_NONE)
2883                 return 0;
2884
2885         fence = &dev_priv->fence_regs[obj->fence_reg];
2886
2887         i915_gem_object_fence_lost(obj);
2888         i915_gem_object_update_fence(obj, fence, false);
2889
2890         return 0;
2891 }
2892
2893 static struct drm_i915_fence_reg *
2894 i915_find_fence_reg(struct drm_device *dev)
2895 {
2896         struct drm_i915_private *dev_priv = dev->dev_private;
2897         struct drm_i915_fence_reg *reg, *avail;
2898         int i;
2899
2900         /* First try to find a free reg */
2901         avail = NULL;
2902         for (i = dev_priv->fence_reg_start; i < dev_priv->num_fence_regs; i++) {
2903                 reg = &dev_priv->fence_regs[i];
2904                 if (!reg->obj)
2905                         return reg;
2906
2907                 if (!reg->pin_count)
2908                         avail = reg;
2909         }
2910
2911         if (avail == NULL)
2912                 return NULL;
2913
2914         /* None available, try to steal one or wait for a user to finish */
2915         list_for_each_entry(reg, &dev_priv->mm.fence_list, lru_list) {
2916                 if (reg->pin_count)
2917                         continue;
2918
2919                 return reg;
2920         }
2921
2922         return NULL;
2923 }
2924
2925 /**
2926  * i915_gem_object_get_fence - set up fencing for an object
2927  * @obj: object to map through a fence reg
2928  *
2929  * When mapping objects through the GTT, userspace wants to be able to write
2930  * to them without having to worry about swizzling if the object is tiled.
2931  * This function walks the fence regs looking for a free one for @obj,
2932  * stealing one if it can't find any.
2933  *
2934  * It then sets up the reg based on the object's properties: address, pitch
2935  * and tiling format.
2936  *
2937  * For an untiled surface, this removes any existing fence.
2938  */
2939 int
2940 i915_gem_object_get_fence(struct drm_i915_gem_object *obj)
2941 {
2942         struct drm_device *dev = obj->base.dev;
2943         struct drm_i915_private *dev_priv = dev->dev_private;
2944         bool enable = obj->tiling_mode != I915_TILING_NONE;
2945         struct drm_i915_fence_reg *reg;
2946         int ret;
2947
2948         /* Have we updated the tiling parameters upon the object and so
2949          * will need to serialise the write to the associated fence register?
2950          */
2951         if (obj->fence_dirty) {
2952                 ret = i915_gem_object_wait_fence(obj);
2953                 if (ret)
2954                         return ret;
2955         }
2956
2957         /* Just update our place in the LRU if our fence is getting reused. */
2958         if (obj->fence_reg != I915_FENCE_REG_NONE) {
2959                 reg = &dev_priv->fence_regs[obj->fence_reg];
2960                 if (!obj->fence_dirty) {
2961                         list_move_tail(&reg->lru_list,
2962                                        &dev_priv->mm.fence_list);
2963                         return 0;
2964                 }
2965         } else if (enable) {
2966                 reg = i915_find_fence_reg(dev);
2967                 if (reg == NULL)
2968                         return -EDEADLK;
2969
2970                 if (reg->obj) {
2971                         struct drm_i915_gem_object *old = reg->obj;
2972
2973                         ret = i915_gem_object_wait_fence(old);
2974                         if (ret)
2975                                 return ret;
2976
2977                         i915_gem_object_fence_lost(old);
2978                 }
2979         } else
2980                 return 0;
2981
2982         i915_gem_object_update_fence(obj, reg, enable);
2983
2984         return 0;
2985 }
2986
2987 static bool i915_gem_valid_gtt_space(struct drm_device *dev,
2988                                      struct drm_mm_node *gtt_space,
2989                                      unsigned long cache_level)
2990 {
2991         struct drm_mm_node *other;
2992
2993         /* On non-LLC machines we have to be careful when putting differing
2994          * types of snoopable memory together to avoid the prefetcher
2995          * crossing memory domains and dying.
2996          */
2997         if (HAS_LLC(dev))
2998                 return true;
2999
3000         if (gtt_space == NULL)
3001                 return true;
3002
3003         if (list_empty(&gtt_space->node_list))
3004                 return true;
3005
3006         other = list_entry(gtt_space->node_list.prev, struct drm_mm_node, node_list);
3007         if (other->allocated && !other->hole_follows && other->color != cache_level)
3008                 return false;
3009
3010         other = list_entry(gtt_space->node_list.next, struct drm_mm_node, node_list);
3011         if (other->allocated && !gtt_space->hole_follows && other->color != cache_level)
3012                 return false;
3013
3014         return true;
3015 }
3016
3017 static void i915_gem_verify_gtt(struct drm_device *dev)
3018 {
3019 #if WATCH_GTT
3020         struct drm_i915_private *dev_priv = dev->dev_private;
3021         struct drm_i915_gem_object *obj;
3022         int err = 0;
3023
3024         list_for_each_entry(obj, &dev_priv->mm.global_list, global_list) {
3025                 if (obj->gtt_space == NULL) {
3026                         printk(KERN_ERR "object found on GTT list with no space reserved\n");
3027                         err++;
3028                         continue;
3029                 }
3030
3031                 if (obj->cache_level != obj->gtt_space->color) {
3032                         printk(KERN_ERR "object reserved space [%08lx, %08lx] with wrong color, cache_level=%x, color=%lx\n",
3033                                obj->gtt_space->start,
3034                                obj->gtt_space->start + obj->gtt_space->size,
3035                                obj->cache_level,
3036                                obj->gtt_space->color);
3037                         err++;
3038                         continue;
3039                 }
3040
3041                 if (!i915_gem_valid_gtt_space(dev,
3042                                               obj->gtt_space,
3043                                               obj->cache_level)) {
3044                         printk(KERN_ERR "invalid GTT space found at [%08lx, %08lx] - color=%x\n",
3045                                obj->gtt_space->start,
3046                                obj->gtt_space->start + obj->gtt_space->size,
3047                                obj->cache_level);
3048                         err++;
3049                         continue;
3050                 }
3051         }
3052
3053         WARN_ON(err);
3054 #endif
3055 }
3056
3057 /**
3058  * Finds free space in the GTT aperture and binds the object there.
3059  */
3060 static int
3061 i915_gem_object_bind_to_gtt(struct drm_i915_gem_object *obj,
3062                             unsigned alignment,
3063                             bool map_and_fenceable,
3064                             bool nonblocking)
3065 {
3066         struct drm_device *dev = obj->base.dev;
3067         drm_i915_private_t *dev_priv = dev->dev_private;
3068         struct drm_mm_node *node;
3069         u32 size, fence_size, fence_alignment, unfenced_alignment;
3070         bool mappable, fenceable;
3071         size_t gtt_max = map_and_fenceable ?
3072                 dev_priv->gtt.mappable_end : dev_priv->gtt.total;
3073         int ret;
3074
3075         fence_size = i915_gem_get_gtt_size(dev,
3076                                            obj->base.size,
3077                                            obj->tiling_mode);
3078         fence_alignment = i915_gem_get_gtt_alignment(dev,
3079                                                      obj->base.size,
3080                                                      obj->tiling_mode, true);
3081         unfenced_alignment =
3082                 i915_gem_get_gtt_alignment(dev,
3083                                                     obj->base.size,
3084                                                     obj->tiling_mode, false);
3085
3086         if (alignment == 0)
3087                 alignment = map_and_fenceable ? fence_alignment :
3088                                                 unfenced_alignment;
3089         if (map_and_fenceable && alignment & (fence_alignment - 1)) {
3090                 DRM_ERROR("Invalid object alignment requested %u\n", alignment);
3091                 return -EINVAL;
3092         }
3093
3094         size = map_and_fenceable ? fence_size : obj->base.size;
3095
3096         /* If the object is bigger than the entire aperture, reject it early
3097          * before evicting everything in a vain attempt to find space.
3098          */
3099         if (obj->base.size > gtt_max) {
3100                 DRM_ERROR("Attempting to bind an object larger than the aperture: object=%zd > %s aperture=%zu\n",
3101                           obj->base.size,
3102                           map_and_fenceable ? "mappable" : "total",
3103                           gtt_max);
3104                 return -E2BIG;
3105         }
3106
3107  search_free:
3108         if (map_and_fenceable)
3109                 node = drm_mm_search_free_in_range_color(&dev_priv->mm.gtt_space,
3110                                                           size, alignment, obj->cache_level,
3111                                                           0, dev_priv->gtt.mappable_end,
3112                                                           false);
3113         else
3114                 node = drm_mm_search_free_color(&dev_priv->mm.gtt_space,
3115                                                       size, alignment, obj->cache_level,
3116                                                       false);
3117         if (node != NULL) {
3118                 if (map_and_fenceable)
3119                         obj->gtt_space =
3120                                 drm_mm_get_block_range_generic(node,
3121                                                                size, alignment, obj->cache_level,
3122                                                                0, dev_priv->gtt.mappable_end,
3123                                                                false);
3124                 else
3125                         obj->gtt_space =
3126                                 drm_mm_get_block_generic(node,
3127                                                          size, alignment, obj->cache_level,
3128                                                          false);
3129         }
3130         if (obj->gtt_space == NULL) {
3131                 ret = i915_gem_evict_something(dev, size, alignment,
3132                                                obj->cache_level,
3133                                                map_and_fenceable,
3134                                                nonblocking);
3135                 if (ret)
3136                         return ret;
3137
3138                 goto search_free;
3139         }
3140
3141         /*
3142          * NOTE: i915_gem_object_get_pages_gtt() cannot
3143          *       return ENOMEM, since we used VM_ALLOC_RETRY.
3144          */
3145         ret = i915_gem_object_get_pages_gtt(obj);
3146         if (ret != 0) {
3147                 drm_mm_put_block(obj->gtt_space);
3148                 obj->gtt_space = NULL;
3149                 return ret;
3150         }
3151
3152         i915_gem_gtt_bind_object(obj, obj->cache_level);
3153         if (ret != 0) {
3154                 i915_gem_object_put_pages_gtt(obj);
3155                 drm_mm_put_block(obj->gtt_space);
3156                 obj->gtt_space = NULL;
3157                 if (i915_gem_evict_everything(dev))
3158                         return (ret);
3159                 goto search_free;
3160         }
3161
3162         list_add_tail(&obj->global_list, &dev_priv->mm.bound_list);
3163         list_add_tail(&obj->mm_list, &dev_priv->mm.inactive_list);
3164
3165         obj->gtt_offset = obj->gtt_space->start;
3166
3167         fenceable =
3168                 obj->gtt_space->size == fence_size &&
3169                 (obj->gtt_space->start & (fence_alignment - 1)) == 0;
3170
3171         mappable =
3172                 obj->gtt_offset + obj->base.size <= dev_priv->gtt.mappable_end;
3173
3174         obj->map_and_fenceable = mappable && fenceable;
3175
3176         trace_i915_gem_object_bind(obj, map_and_fenceable);
3177         i915_gem_verify_gtt(dev);
3178         return 0;
3179 }
3180
3181 void
3182 i915_gem_clflush_object(struct drm_i915_gem_object *obj)
3183 {
3184
3185         /* If we don't have a page list set up, then we're not pinned
3186          * to GPU, and we can ignore the cache flush because it'll happen
3187          * again at bind time.
3188          */
3189         if (obj->pages == NULL)
3190                 return;
3191
3192         /*
3193          * Stolen memory is always coherent with the GPU as it is explicitly
3194          * marked as wc by the system, or the system is cache-coherent.
3195          */
3196         if (obj->stolen)
3197                 return;
3198
3199         /* If the GPU is snooping the contents of the CPU cache,
3200          * we do not need to manually clear the CPU cache lines.  However,
3201          * the caches are only snooped when the render cache is
3202          * flushed/invalidated.  As we always have to emit invalidations
3203          * and flushes when moving into and out of the RENDER domain, correct
3204          * snooping behaviour occurs naturally as the result of our domain
3205          * tracking.
3206          */
3207         if (obj->cache_level != I915_CACHE_NONE)
3208                 return;
3209
3210         trace_i915_gem_object_clflush(obj);
3211
3212         drm_clflush_pages(obj->pages, obj->base.size / PAGE_SIZE);
3213 }
3214
3215 /** Flushes the GTT write domain for the object if it's dirty. */
3216 static void
3217 i915_gem_object_flush_gtt_write_domain(struct drm_i915_gem_object *obj)
3218 {
3219         uint32_t old_write_domain;
3220
3221         if (obj->base.write_domain != I915_GEM_DOMAIN_GTT)
3222                 return;
3223
3224         /* No actual flushing is required for the GTT write domain.  Writes
3225          * to it immediately go to main memory as far as we know, so there's
3226          * no chipset flush.  It also doesn't land in render cache.
3227          *
3228          * However, we do have to enforce the order so that all writes through
3229          * the GTT land before any writes to the device, such as updates to
3230          * the GATT itself.
3231          */
3232         cpu_sfence();
3233
3234         old_write_domain = obj->base.write_domain;
3235         obj->base.write_domain = 0;
3236
3237         trace_i915_gem_object_change_domain(obj,
3238                                             obj->base.read_domains,
3239                                             old_write_domain);
3240 }
3241
3242 /** Flushes the CPU write domain for the object if it's dirty. */
3243 static void
3244 i915_gem_object_flush_cpu_write_domain(struct drm_i915_gem_object *obj)
3245 {
3246         uint32_t old_write_domain;
3247
3248         if (obj->base.write_domain != I915_GEM_DOMAIN_CPU)
3249                 return;
3250
3251         i915_gem_clflush_object(obj);
3252         i915_gem_chipset_flush(obj->base.dev);
3253         old_write_domain = obj->base.write_domain;
3254         obj->base.write_domain = 0;
3255
3256         trace_i915_gem_object_change_domain(obj,
3257                                             obj->base.read_domains,
3258                                             old_write_domain);
3259 }
3260
3261 /**
3262  * Moves a single object to the GTT read, and possibly write domain.
3263  *
3264  * This function returns when the move is complete, including waiting on
3265  * flushes to occur.
3266  */
3267 int
3268 i915_gem_object_set_to_gtt_domain(struct drm_i915_gem_object *obj, bool write)
3269 {
3270         drm_i915_private_t *dev_priv = obj->base.dev->dev_private;
3271         uint32_t old_write_domain, old_read_domains;
3272         int ret;
3273
3274         /* Not valid to be called on unbound objects. */
3275         if (obj->gtt_space == NULL)
3276                 return -EINVAL;
3277
3278         if (obj->base.write_domain == I915_GEM_DOMAIN_GTT)
3279                 return 0;
3280
3281         ret = i915_gem_object_wait_rendering(obj, !write);
3282         if (ret)
3283                 return ret;
3284
3285         i915_gem_object_flush_cpu_write_domain(obj);
3286
3287         /* Serialise direct access to this object with the barriers for
3288          * coherent writes from the GPU, by effectively invalidating the
3289          * GTT domain upon first access.
3290          */
3291         if ((obj->base.read_domains & I915_GEM_DOMAIN_GTT) == 0)
3292                 cpu_mfence();
3293
3294         old_write_domain = obj->base.write_domain;
3295         old_read_domains = obj->base.read_domains;
3296
3297         /* It should now be out of any other write domains, and we can update
3298          * the domain values for our changes.
3299          */
3300         BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_GTT) != 0);
3301         obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
3302         if (write) {
3303                 obj->base.read_domains = I915_GEM_DOMAIN_GTT;
3304                 obj->base.write_domain = I915_GEM_DOMAIN_GTT;
3305                 obj->dirty = 1;
3306         }
3307
3308         trace_i915_gem_object_change_domain(obj,
3309                                             old_read_domains,
3310                                             old_write_domain);
3311
3312         /* And bump the LRU for this access */
3313         if (i915_gem_object_is_inactive(obj))
3314                 list_move_tail(&obj->mm_list, &dev_priv->mm.inactive_list);
3315
3316         return 0;
3317 }
3318
3319 int i915_gem_object_set_cache_level(struct drm_i915_gem_object *obj,
3320                                     enum i915_cache_level cache_level)
3321 {
3322         struct drm_device *dev = obj->base.dev;
3323         drm_i915_private_t *dev_priv = dev->dev_private;
3324         int ret;
3325
3326         if (obj->cache_level == cache_level)
3327                 return 0;
3328
3329         if (obj->pin_count) {
3330                 DRM_DEBUG("can not change the cache level of pinned objects\n");
3331                 return -EBUSY;
3332         }
3333
3334         if (!i915_gem_valid_gtt_space(dev, obj->gtt_space, cache_level)) {
3335                 ret = i915_gem_object_unbind(obj);
3336                 if (ret)
3337                         return ret;
3338         }
3339
3340         if (obj->gtt_space) {
3341                 ret = i915_gem_object_finish_gpu(obj);
3342                 if (ret)
3343                         return ret;
3344
3345                 i915_gem_object_finish_gtt(obj);
3346
3347                 /* Before SandyBridge, you could not use tiling or fence
3348                  * registers with snooped memory, so relinquish any fences
3349                  * currently pointing to our region in the aperture.
3350                  */
3351                 if (INTEL_INFO(dev)->gen < 6) {
3352                         ret = i915_gem_object_put_fence(obj);
3353                         if (ret)
3354                                 return ret;
3355                 }
3356
3357                 if (obj->has_global_gtt_mapping)
3358                         i915_gem_gtt_bind_object(obj, cache_level);
3359                 if (obj->has_aliasing_ppgtt_mapping)
3360                         i915_ppgtt_bind_object(dev_priv->mm.aliasing_ppgtt,
3361                                                obj, cache_level);
3362
3363                 obj->gtt_space->color = cache_level;
3364         }
3365
3366         if (cache_level == I915_CACHE_NONE) {
3367                 u32 old_read_domains, old_write_domain;
3368
3369                 /* If we're coming from LLC cached, then we haven't
3370                  * actually been tracking whether the data is in the
3371                  * CPU cache or not, since we only allow one bit set
3372                  * in obj->write_domain and have been skipping the clflushes.
3373                  * Just set it to the CPU cache for now.
3374                  */
3375                 WARN_ON(obj->base.write_domain & ~I915_GEM_DOMAIN_CPU);
3376                 WARN_ON(obj->base.read_domains & ~I915_GEM_DOMAIN_CPU);
3377
3378                 old_read_domains = obj->base.read_domains;
3379                 old_write_domain = obj->base.write_domain;
3380
3381                 obj->base.read_domains = I915_GEM_DOMAIN_CPU;
3382                 obj->base.write_domain = I915_GEM_DOMAIN_CPU;
3383
3384                 trace_i915_gem_object_change_domain(obj,
3385                                                     old_read_domains,
3386                                                     old_write_domain);
3387         }
3388
3389         obj->cache_level = cache_level;
3390         i915_gem_verify_gtt(dev);
3391         return 0;
3392 }
3393
3394 int i915_gem_get_caching_ioctl(struct drm_device *dev, void *data,
3395                                struct drm_file *file)
3396 {
3397         struct drm_i915_gem_caching *args = data;
3398         struct drm_i915_gem_object *obj;
3399         int ret;
3400
3401         ret = i915_mutex_lock_interruptible(dev);
3402         if (ret)
3403                 return ret;
3404
3405         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
3406         if (&obj->base == NULL) {
3407                 ret = -ENOENT;
3408                 goto unlock;
3409         }
3410
3411         args->caching = obj->cache_level != I915_CACHE_NONE;
3412
3413         drm_gem_object_unreference(&obj->base);
3414 unlock:
3415         mutex_unlock(&dev->struct_mutex);
3416         return ret;
3417 }
3418
3419 int i915_gem_set_caching_ioctl(struct drm_device *dev, void *data,
3420                                struct drm_file *file)
3421 {
3422         struct drm_i915_gem_caching *args = data;
3423         struct drm_i915_gem_object *obj;
3424         enum i915_cache_level level;
3425         int ret;
3426
3427         switch (args->caching) {
3428         case I915_CACHING_NONE:
3429                 level = I915_CACHE_NONE;
3430                 break;
3431         case I915_CACHING_CACHED:
3432                 level = I915_CACHE_LLC;
3433                 break;
3434         default:
3435                 return -EINVAL;
3436         }
3437
3438         ret = i915_mutex_lock_interruptible(dev);
3439         if (ret)
3440                 return ret;
3441
3442         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
3443         if (&obj->base == NULL) {
3444                 ret = -ENOENT;
3445                 goto unlock;
3446         }
3447
3448         ret = i915_gem_object_set_cache_level(obj, level);
3449
3450         drm_gem_object_unreference(&obj->base);
3451 unlock:
3452         mutex_unlock(&dev->struct_mutex);
3453         return ret;
3454 }
3455
3456 /*
3457  * Prepare buffer for display plane (scanout, cursors, etc).
3458  * Can be called from an uninterruptible phase (modesetting) and allows
3459  * any flushes to be pipelined (for pageflips).
3460  */
3461 int
3462 i915_gem_object_pin_to_display_plane(struct drm_i915_gem_object *obj,
3463                                      u32 alignment,
3464                                      struct intel_ring_buffer *pipelined)
3465 {
3466         u32 old_read_domains, old_write_domain;
3467         int ret;
3468
3469         if (pipelined != obj->ring) {
3470                 ret = i915_gem_object_sync(obj, pipelined);
3471                 if (ret)
3472                         return ret;
3473         }
3474
3475         /* The display engine is not coherent with the LLC cache on gen6.  As
3476          * a result, we make sure that the pinning that is about to occur is
3477          * done with uncached PTEs. This is lowest common denominator for all
3478          * chipsets.
3479          *
3480          * However for gen6+, we could do better by using the GFDT bit instead
3481          * of uncaching, which would allow us to flush all the LLC-cached data
3482          * with that bit in the PTE to main memory with just one PIPE_CONTROL.
3483          */
3484         ret = i915_gem_object_set_cache_level(obj, I915_CACHE_NONE);
3485         if (ret)
3486                 return ret;
3487
3488         /* As the user may map the buffer once pinned in the display plane
3489          * (e.g. libkms for the bootup splash), we have to ensure that we
3490          * always use map_and_fenceable for all scanout buffers.
3491          */
3492         ret = i915_gem_object_pin(obj, alignment, true, false);
3493         if (ret)
3494                 return ret;
3495
3496         i915_gem_object_flush_cpu_write_domain(obj);
3497
3498         old_write_domain = obj->base.write_domain;
3499         old_read_domains = obj->base.read_domains;
3500
3501         /* It should now be out of any other write domains, and we can update
3502          * the domain values for our changes.
3503          */
3504         obj->base.write_domain = 0;
3505         obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
3506
3507         trace_i915_gem_object_change_domain(obj,
3508                                             old_read_domains,
3509                                             old_write_domain);
3510
3511         return 0;
3512 }
3513
3514 int
3515 i915_gem_object_finish_gpu(struct drm_i915_gem_object *obj)
3516 {
3517         int ret;
3518
3519         if ((obj->base.read_domains & I915_GEM_GPU_DOMAINS) == 0)
3520                 return 0;
3521
3522         ret = i915_gem_object_wait_rendering(obj, false);
3523         if (ret)
3524                 return ret;
3525
3526         /* Ensure that we invalidate the GPU's caches and TLBs. */
3527         obj->base.read_domains &= ~I915_GEM_GPU_DOMAINS;
3528         return 0;
3529 }
3530
3531 /**
3532  * Moves a single object to the CPU read, and possibly write domain.
3533  *
3534  * This function returns when the move is complete, including waiting on
3535  * flushes to occur.
3536  */
3537 int
3538 i915_gem_object_set_to_cpu_domain(struct drm_i915_gem_object *obj, bool write)
3539 {
3540         uint32_t old_write_domain, old_read_domains;
3541         int ret;
3542
3543         if (obj->base.write_domain == I915_GEM_DOMAIN_CPU)
3544                 return 0;
3545
3546         ret = i915_gem_object_wait_rendering(obj, !write);
3547         if (ret)
3548                 return ret;
3549
3550         i915_gem_object_flush_gtt_write_domain(obj);
3551
3552         old_write_domain = obj->base.write_domain;
3553         old_read_domains = obj->base.read_domains;
3554
3555         /* Flush the CPU cache if it's still invalid. */
3556         if ((obj->base.read_domains & I915_GEM_DOMAIN_CPU) == 0) {
3557                 i915_gem_clflush_object(obj);
3558
3559                 obj->base.read_domains |= I915_GEM_DOMAIN_CPU;
3560         }
3561
3562         /* It should now be out of any other write domains, and we can update
3563          * the domain values for our changes.
3564          */
3565         BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_CPU) != 0);
3566
3567         /* If we're writing through the CPU, then the GPU read domains will
3568          * need to be invalidated at next use.
3569          */
3570         if (write) {
3571                 obj->base.read_domains = I915_GEM_DOMAIN_CPU;
3572                 obj->base.write_domain = I915_GEM_DOMAIN_CPU;
3573         }
3574
3575         trace_i915_gem_object_change_domain(obj,
3576                                             old_read_domains,
3577                                             old_write_domain);
3578
3579         return 0;
3580 }
3581
3582 /* Throttle our rendering by waiting until the ring has completed our requests
3583  * emitted over 20 msec ago.
3584  *
3585  * Note that if we were to use the current jiffies each time around the loop,
3586  * we wouldn't escape the function with any frames outstanding if the time to
3587  * render a frame was over 20ms.
3588  *
3589  * This should get us reasonable parallelism between CPU and GPU but also
3590  * relatively low latency when blocking on a particular request to finish.
3591  */
3592 static int
3593 i915_gem_ring_throttle(struct drm_device *dev, struct drm_file *file)
3594 {
3595         struct drm_i915_private *dev_priv = dev->dev_private;
3596         struct drm_i915_file_private *file_priv = file->driver_priv;
3597         unsigned long recent_enough = jiffies - msecs_to_jiffies(20);
3598         struct drm_i915_gem_request *request;
3599         struct intel_ring_buffer *ring = NULL;
3600         unsigned reset_counter;
3601         u32 seqno = 0;
3602         int ret;
3603
3604         ret = i915_gem_wait_for_error(&dev_priv->gpu_error);
3605         if (ret)
3606                 return ret;
3607
3608         ret = i915_gem_check_wedge(&dev_priv->gpu_error, false);
3609         if (ret)
3610                 return ret;
3611
3612         spin_lock(&file_priv->mm.lock);
3613         list_for_each_entry(request, &file_priv->mm.request_list, client_list) {
3614                 if (time_after_eq(request->emitted_jiffies, recent_enough))
3615                         break;
3616
3617                 ring = request->ring;
3618                 seqno = request->seqno;
3619         }
3620         reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
3621         spin_unlock(&file_priv->mm.lock);
3622
3623         if (seqno == 0)
3624                 return 0;
3625
3626         ret = __wait_seqno(ring, seqno, reset_counter, true, NULL);
3627         if (ret == 0)
3628                 queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work, 0);
3629
3630         return ret;
3631 }
3632
3633 int
3634 i915_gem_object_pin(struct drm_i915_gem_object *obj,
3635                     uint32_t alignment,
3636                     bool map_and_fenceable,
3637                     bool nonblocking)
3638 {
3639         int ret;
3640
3641         if (WARN_ON(obj->pin_count == DRM_I915_GEM_OBJECT_MAX_PIN_COUNT))
3642                 return -EBUSY;
3643
3644         if (obj->gtt_space != NULL) {
3645                 if ((alignment && obj->gtt_offset & (alignment - 1)) ||
3646                     (map_and_fenceable && !obj->map_and_fenceable)) {
3647                         WARN(obj->pin_count,
3648                              "bo is already pinned with incorrect alignment:"
3649                              " offset=%x, req.alignment=%x, req.map_and_fenceable=%d,"
3650                              " obj->map_and_fenceable=%d\n",
3651                              obj->gtt_offset, alignment,
3652                              map_and_fenceable,
3653                              obj->map_and_fenceable);
3654                         ret = i915_gem_object_unbind(obj);
3655                         if (ret)
3656                                 return ret;
3657                 }
3658         }
3659
3660         if (obj->gtt_space == NULL) {
3661                 struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
3662
3663                 ret = i915_gem_object_bind_to_gtt(obj, alignment,
3664                                                   map_and_fenceable,
3665                                                   nonblocking);
3666                 if (ret)
3667                         return ret;
3668
3669                 if (!dev_priv->mm.aliasing_ppgtt)
3670                         i915_gem_gtt_bind_object(obj, obj->cache_level);
3671         }
3672
3673         if (!obj->has_global_gtt_mapping && map_and_fenceable)
3674                 i915_gem_gtt_bind_object(obj, obj->cache_level);
3675
3676         obj->pin_count++;
3677         obj->pin_mappable |= map_and_fenceable;
3678
3679         return 0;
3680 }
3681
3682 void
3683 i915_gem_object_unpin(struct drm_i915_gem_object *obj)
3684 {
3685         BUG_ON(obj->pin_count == 0);
3686         BUG_ON(obj->gtt_space == NULL);
3687
3688         if (--obj->pin_count == 0)
3689                 obj->pin_mappable = false;
3690 }
3691
3692 int
3693 i915_gem_pin_ioctl(struct drm_device *dev, void *data,
3694                    struct drm_file *file)
3695 {
3696         struct drm_i915_gem_pin *args = data;
3697         struct drm_i915_gem_object *obj;
3698         int ret;
3699
3700         ret = i915_mutex_lock_interruptible(dev);
3701         if (ret)
3702                 return ret;
3703
3704         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
3705         if (&obj->base == NULL) {
3706                 ret = -ENOENT;
3707                 goto unlock;
3708         }
3709
3710         if (obj->madv != I915_MADV_WILLNEED) {
3711                 DRM_ERROR("Attempting to pin a purgeable buffer\n");
3712                 ret = -EINVAL;
3713                 goto out;
3714         }
3715
3716         if (obj->pin_filp != NULL && obj->pin_filp != file) {
3717                 DRM_ERROR("Already pinned in i915_gem_pin_ioctl(): %d\n",
3718                           args->handle);
3719                 ret = -EINVAL;
3720                 goto out;
3721         }
3722
3723         if (obj->user_pin_count == 0) {
3724                 ret = i915_gem_object_pin(obj, args->alignment, true, false);
3725                 if (ret)
3726                         goto out;
3727         }
3728
3729         obj->user_pin_count++;
3730         obj->pin_filp = file;
3731
3732         /* XXX - flush the CPU caches for pinned objects
3733          * as the X server doesn't manage domains yet
3734          */
3735         i915_gem_object_flush_cpu_write_domain(obj);
3736         args->offset = obj->gtt_offset;
3737 out:
3738         drm_gem_object_unreference(&obj->base);
3739 unlock:
3740         mutex_unlock(&dev->struct_mutex);
3741         return ret;
3742 }
3743
3744 int
3745 i915_gem_unpin_ioctl(struct drm_device *dev, void *data,
3746                      struct drm_file *file)
3747 {
3748         struct drm_i915_gem_pin *args = data;
3749         struct drm_i915_gem_object *obj;
3750         int ret;
3751
3752         ret = i915_mutex_lock_interruptible(dev);
3753         if (ret)
3754                 return ret;
3755
3756         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
3757         if (&obj->base == NULL) {
3758                 ret = -ENOENT;
3759                 goto unlock;
3760         }
3761
3762         if (obj->pin_filp != file) {
3763                 DRM_ERROR("Not pinned by caller in i915_gem_pin_ioctl(): %d\n",
3764                           args->handle);
3765                 ret = -EINVAL;
3766                 goto out;
3767         }
3768         obj->user_pin_count--;
3769         if (obj->user_pin_count == 0) {
3770                 obj->pin_filp = NULL;
3771                 i915_gem_object_unpin(obj);
3772         }
3773
3774 out:
3775         drm_gem_object_unreference(&obj->base);
3776 unlock:
3777         mutex_unlock(&dev->struct_mutex);
3778         return ret;
3779 }
3780
3781 int
3782 i915_gem_busy_ioctl(struct drm_device *dev, void *data,
3783                     struct drm_file *file)
3784 {
3785         struct drm_i915_gem_busy *args = data;
3786         struct drm_i915_gem_object *obj;
3787         int ret;
3788
3789         ret = i915_mutex_lock_interruptible(dev);
3790         if (ret)
3791                 return ret;
3792
3793         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
3794         if (&obj->base == NULL) {
3795                 ret = -ENOENT;
3796                 goto unlock;
3797         }
3798
3799         /* Count all active objects as busy, even if they are currently not used
3800          * by the gpu. Users of this interface expect objects to eventually
3801          * become non-busy without any further actions, therefore emit any
3802          * necessary flushes here.
3803          */
3804         ret = i915_gem_object_flush_active(obj);
3805
3806         args->busy = obj->active;
3807         if (obj->ring) {
3808                 args->busy |= intel_ring_flag(obj->ring) << 16;
3809         }
3810
3811         drm_gem_object_unreference(&obj->base);
3812 unlock:
3813         mutex_unlock(&dev->struct_mutex);
3814         return ret;
3815 }
3816
3817 int
3818 i915_gem_throttle_ioctl(struct drm_device *dev, void *data,
3819                         struct drm_file *file_priv)
3820 {
3821         return i915_gem_ring_throttle(dev, file_priv);
3822 }
3823
3824 int
3825 i915_gem_madvise_ioctl(struct drm_device *dev, void *data,
3826                        struct drm_file *file_priv)
3827 {
3828         struct drm_i915_gem_madvise *args = data;
3829         struct drm_i915_gem_object *obj;
3830         int ret;
3831
3832         switch (args->madv) {
3833         case I915_MADV_DONTNEED:
3834         case I915_MADV_WILLNEED:
3835             break;
3836         default:
3837             return -EINVAL;
3838         }
3839
3840         ret = i915_mutex_lock_interruptible(dev);
3841         if (ret)
3842                 return ret;
3843
3844         obj = to_intel_bo(drm_gem_object_lookup(dev, file_priv, args->handle));
3845         if (&obj->base == NULL) {
3846                 ret = -ENOENT;
3847                 goto unlock;
3848         }
3849
3850         if (obj->pin_count) {
3851                 ret = -EINVAL;
3852                 goto out;
3853         }
3854
3855         if (obj->madv != __I915_MADV_PURGED)
3856                 obj->madv = args->madv;
3857
3858         /* if the object is no longer attached, discard its backing storage */
3859         if (i915_gem_object_is_purgeable(obj) && obj->pages == NULL)
3860                 i915_gem_object_truncate(obj);
3861
3862         args->retained = obj->madv != __I915_MADV_PURGED;
3863
3864 out:
3865         drm_gem_object_unreference(&obj->base);
3866 unlock:
3867         mutex_unlock(&dev->struct_mutex);
3868         return ret;
3869 }
3870
3871 void i915_gem_object_init(struct drm_i915_gem_object *obj,
3872                           const struct drm_i915_gem_object_ops *ops)
3873 {
3874         INIT_LIST_HEAD(&obj->mm_list);
3875         INIT_LIST_HEAD(&obj->global_list);
3876         INIT_LIST_HEAD(&obj->ring_list);
3877         INIT_LIST_HEAD(&obj->exec_list);
3878
3879         obj->ops = ops;
3880
3881         obj->fence_reg = I915_FENCE_REG_NONE;
3882         obj->madv = I915_MADV_WILLNEED;
3883         /* Avoid an unnecessary call to unbind on the first bind. */
3884         obj->map_and_fenceable = true;
3885
3886         i915_gem_info_add_obj(obj->base.dev->dev_private, obj->base.size);
3887 }
3888
3889 static const struct drm_i915_gem_object_ops i915_gem_object_ops = {
3890         .get_pages = i915_gem_object_get_pages_gtt,
3891         .put_pages = i915_gem_object_put_pages_gtt,
3892 };
3893
3894 struct drm_i915_gem_object *i915_gem_alloc_object(struct drm_device *dev,
3895                                                   size_t size)
3896 {
3897         struct drm_i915_gem_object *obj;
3898 #if 0
3899         struct address_space *mapping;
3900         u32 mask;
3901 #endif
3902
3903         obj = kmalloc(sizeof(*obj), M_DRM, M_WAITOK | M_ZERO);
3904         if (obj == NULL)
3905                 return NULL;
3906
3907         if (drm_gem_object_init(dev, &obj->base, size) != 0) {
3908                 kfree(obj);
3909                 return NULL;
3910         }
3911
3912 #if 0
3913         mask = GFP_HIGHUSER | __GFP_RECLAIMABLE;
3914         if (IS_CRESTLINE(dev) || IS_BROADWATER(dev)) {
3915                 /* 965gm cannot relocate objects above 4GiB. */
3916                 mask &= ~__GFP_HIGHMEM;
3917                 mask |= __GFP_DMA32;
3918         }
3919
3920         mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
3921         mapping_set_gfp_mask(mapping, mask);
3922 #endif
3923
3924         i915_gem_object_init(obj, &i915_gem_object_ops);
3925
3926         obj->base.write_domain = I915_GEM_DOMAIN_CPU;
3927         obj->base.read_domains = I915_GEM_DOMAIN_CPU;
3928
3929         if (HAS_LLC(dev)) {
3930                 /* On some devices, we can have the GPU use the LLC (the CPU
3931                  * cache) for about a 10% performance improvement
3932                  * compared to uncached.  Graphics requests other than
3933                  * display scanout are coherent with the CPU in
3934                  * accessing this cache.  This means in this mode we
3935                  * don't need to clflush on the CPU side, and on the
3936                  * GPU side we only need to flush internal caches to
3937                  * get data visible to the CPU.
3938                  *
3939                  * However, we maintain the display planes as UC, and so
3940                  * need to rebind when first used as such.
3941                  */
3942                 obj->cache_level = I915_CACHE_LLC;
3943         } else
3944                 obj->cache_level = I915_CACHE_NONE;
3945
3946         return obj;
3947 }
3948
3949 int i915_gem_init_object(struct drm_gem_object *obj)
3950 {
3951         BUG();
3952
3953         return 0;
3954 }
3955
3956 void i915_gem_free_object(struct drm_gem_object *gem_obj)
3957 {
3958         struct drm_i915_gem_object *obj = to_intel_bo(gem_obj);
3959         struct drm_device *dev = obj->base.dev;
3960         drm_i915_private_t *dev_priv = dev->dev_private;
3961
3962         trace_i915_gem_object_destroy(obj);
3963
3964         if (obj->phys_obj)
3965                 i915_gem_detach_phys_object(dev, obj);
3966
3967         obj->pin_count = 0;
3968         if (WARN_ON(i915_gem_object_unbind(obj) == -ERESTARTSYS)) {
3969                 bool was_interruptible;
3970
3971                 was_interruptible = dev_priv->mm.interruptible;
3972                 dev_priv->mm.interruptible = false;
3973
3974                 WARN_ON(i915_gem_object_unbind(obj));
3975
3976                 dev_priv->mm.interruptible = was_interruptible;
3977         }
3978
3979         /* Stolen objects don't hold a ref, but do hold pin count. Fix that up
3980          * before progressing. */
3981         if (obj->stolen)
3982                 i915_gem_object_unpin_pages(obj);
3983
3984         if (WARN_ON(obj->pages_pin_count))
3985                 obj->pages_pin_count = 0;
3986         i915_gem_object_put_pages(obj);
3987         drm_gem_free_mmap_offset(&obj->base);
3988
3989         BUG_ON(obj->pages);
3990
3991         drm_gem_object_release(&obj->base);
3992         i915_gem_info_remove_obj(dev_priv, obj->base.size);
3993
3994         kfree(obj->bit_17);
3995         i915_gem_object_free(obj);
3996 }
3997
3998 int
3999 i915_gem_idle(struct drm_device *dev)
4000 {
4001         drm_i915_private_t *dev_priv = dev->dev_private;
4002         int ret;
4003
4004         mutex_lock(&dev->struct_mutex);
4005
4006         if (dev_priv->mm.suspended) {
4007                 mutex_unlock(&dev->struct_mutex);
4008                 return 0;
4009         }
4010
4011         ret = i915_gpu_idle(dev);
4012         if (ret) {
4013                 mutex_unlock(&dev->struct_mutex);
4014                 return ret;
4015         }
4016         i915_gem_retire_requests(dev);
4017
4018         /* Under UMS, be paranoid and evict. */
4019         if (!drm_core_check_feature(dev, DRIVER_MODESET))
4020                 i915_gem_evict_everything(dev);
4021
4022         /* Hack!  Don't let anybody do execbuf while we don't control the chip.
4023          * We need to replace this with a semaphore, or something.
4024          * And not confound mm.suspended!
4025          */
4026         dev_priv->mm.suspended = 1;
4027         del_timer_sync(&dev_priv->gpu_error.hangcheck_timer);
4028
4029         i915_kernel_lost_context(dev);
4030         i915_gem_cleanup_ringbuffer(dev);
4031
4032         mutex_unlock(&dev->struct_mutex);
4033
4034         /* Cancel the retire work handler, which should be idle now. */
4035         cancel_delayed_work_sync(&dev_priv->mm.retire_work);
4036
4037         return 0;
4038 }
4039
4040 void i915_gem_l3_remap(struct drm_device *dev)
4041 {
4042         drm_i915_private_t *dev_priv = dev->dev_private;
4043         u32 misccpctl;
4044         int i;
4045
4046         if (!HAS_L3_GPU_CACHE(dev))
4047                 return;
4048
4049         if (!dev_priv->l3_parity.remap_info)
4050                 return;
4051
4052         misccpctl = I915_READ(GEN7_MISCCPCTL);
4053         I915_WRITE(GEN7_MISCCPCTL, misccpctl & ~GEN7_DOP_CLOCK_GATE_ENABLE);
4054         POSTING_READ(GEN7_MISCCPCTL);
4055
4056         for (i = 0; i < GEN7_L3LOG_SIZE; i += 4) {
4057                 u32 remap = I915_READ(GEN7_L3LOG_BASE + i);
4058                 if (remap && remap != dev_priv->l3_parity.remap_info[i/4])
4059                         DRM_DEBUG("0x%x was already programmed to %x\n",
4060                                   GEN7_L3LOG_BASE + i, remap);
4061                 if (remap && !dev_priv->l3_parity.remap_info[i/4])
4062                         DRM_DEBUG_DRIVER("Clearing remapped register\n");
4063                 I915_WRITE(GEN7_L3LOG_BASE + i, dev_priv->l3_parity.remap_info[i/4]);
4064         }
4065
4066         /* Make sure all the writes land before disabling dop clock gating */
4067         POSTING_READ(GEN7_L3LOG_BASE);
4068
4069         I915_WRITE(GEN7_MISCCPCTL, misccpctl);
4070 }
4071
4072 void i915_gem_init_swizzling(struct drm_device *dev)
4073 {
4074         drm_i915_private_t *dev_priv = dev->dev_private;
4075
4076         if (INTEL_INFO(dev)->gen < 5 ||
4077             dev_priv->mm.bit_6_swizzle_x == I915_BIT_6_SWIZZLE_NONE)
4078                 return;
4079
4080         I915_WRITE(DISP_ARB_CTL, I915_READ(DISP_ARB_CTL) |
4081                                  DISP_TILE_SURFACE_SWIZZLING);
4082
4083         if (IS_GEN5(dev))
4084                 return;
4085
4086         I915_WRITE(TILECTL, I915_READ(TILECTL) | TILECTL_SWZCTL);
4087         if (IS_GEN6(dev))
4088                 I915_WRITE(ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_SNB));
4089         else if (IS_GEN7(dev))
4090                 I915_WRITE(ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_IVB));
4091         else
4092                 BUG();
4093 }
4094
4095 static bool
4096 intel_enable_blt(struct drm_device *dev)
4097 {
4098         int revision;
4099
4100         if (!HAS_BLT(dev))
4101                 return false;
4102
4103         /* The blitter was dysfunctional on early prototypes */
4104         revision = pci_read_config(dev->dev, PCIR_REVID, 1);
4105         if (IS_GEN6(dev) && revision < 8) {
4106                 DRM_INFO("BLT not supported on this pre-production hardware;"
4107                          " graphics performance will be degraded.\n");
4108                 return false;
4109         }
4110
4111         return true;
4112 }
4113
4114 static int i915_gem_init_rings(struct drm_device *dev)
4115 {
4116         struct drm_i915_private *dev_priv = dev->dev_private;
4117         int ret;
4118
4119         ret = intel_init_render_ring_buffer(dev);
4120         if (ret)
4121                 return ret;
4122
4123         if (HAS_BSD(dev)) {
4124                 ret = intel_init_bsd_ring_buffer(dev);
4125                 if (ret)
4126                         goto cleanup_render_ring;
4127         }
4128
4129         if (intel_enable_blt(dev)) {
4130                 ret = intel_init_blt_ring_buffer(dev);
4131                 if (ret)
4132                         goto cleanup_bsd_ring;
4133         }
4134
4135         if (HAS_VEBOX(dev)) {
4136                 ret = intel_init_vebox_ring_buffer(dev);
4137                 if (ret)
4138                         goto cleanup_blt_ring;
4139         }
4140
4141
4142         ret = i915_gem_set_seqno(dev, ((u32)~0 - 0x1000));
4143         if (ret)
4144                 goto cleanup_vebox_ring;
4145
4146         return 0;
4147
4148 cleanup_vebox_ring:
4149         intel_cleanup_ring_buffer(&dev_priv->ring[VECS]);
4150 cleanup_blt_ring:
4151         intel_cleanup_ring_buffer(&dev_priv->ring[BCS]);
4152 cleanup_bsd_ring:
4153         intel_cleanup_ring_buffer(&dev_priv->ring[VCS]);
4154 cleanup_render_ring:
4155         intel_cleanup_ring_buffer(&dev_priv->ring[RCS]);
4156
4157         return ret;
4158 }
4159
4160 int
4161 i915_gem_init_hw(struct drm_device *dev)
4162 {
4163         drm_i915_private_t *dev_priv = dev->dev_private;
4164         int ret;
4165
4166 #if 0
4167         if (INTEL_INFO(dev)->gen < 6 && !intel_enable_gtt())
4168                 return -EIO;
4169 #endif
4170
4171         if (IS_HASWELL(dev) && (I915_READ(0x120010) == 1))
4172                 I915_WRITE(0x9008, I915_READ(0x9008) | 0xf0000);
4173
4174         if (HAS_PCH_NOP(dev)) {
4175                 u32 temp = I915_READ(GEN7_MSG_CTL);
4176                 temp &= ~(WAIT_FOR_PCH_FLR_ACK | WAIT_FOR_PCH_RESET_ACK);
4177                 I915_WRITE(GEN7_MSG_CTL, temp);
4178         }
4179
4180         i915_gem_l3_remap(dev);
4181
4182         i915_gem_init_swizzling(dev);
4183
4184         ret = i915_gem_init_rings(dev);
4185         if (ret)
4186                 return ret;
4187
4188         /*
4189          * XXX: There was some w/a described somewhere suggesting loading
4190          * contexts before PPGTT.
4191          */
4192         i915_gem_context_init(dev);
4193         if (dev_priv->mm.aliasing_ppgtt) {
4194                 ret = dev_priv->mm.aliasing_ppgtt->enable(dev);
4195                 if (ret) {
4196                         i915_gem_cleanup_aliasing_ppgtt(dev);
4197                         DRM_INFO("PPGTT enable failed. This is not fatal, but unexpected\n");
4198                 }
4199         }
4200
4201         return 0;
4202 }
4203
4204 int i915_gem_init(struct drm_device *dev)
4205 {
4206         struct drm_i915_private *dev_priv = dev->dev_private;
4207         int ret;
4208
4209         mutex_lock(&dev->struct_mutex);
4210
4211         if (IS_VALLEYVIEW(dev)) {
4212                 /* VLVA0 (potential hack), BIOS isn't actually waking us */
4213                 I915_WRITE(VLV_GTLC_WAKE_CTRL, 1);
4214                 if (wait_for((I915_READ(VLV_GTLC_PW_STATUS) & 1) == 1, 10))
4215                         DRM_DEBUG_DRIVER("allow wake ack timed out\n");
4216         }
4217
4218         i915_gem_init_global_gtt(dev);
4219
4220         ret = i915_gem_init_hw(dev);
4221         mutex_unlock(&dev->struct_mutex);
4222         if (ret) {
4223                 i915_gem_cleanup_aliasing_ppgtt(dev);
4224                 return ret;
4225         }
4226
4227         /* Allow hardware batchbuffers unless told otherwise, but not for KMS. */
4228         if (!drm_core_check_feature(dev, DRIVER_MODESET))
4229                 dev_priv->dri1.allow_batchbuffer = 1;
4230         return 0;
4231 }
4232
4233 void
4234 i915_gem_cleanup_ringbuffer(struct drm_device *dev)
4235 {
4236         drm_i915_private_t *dev_priv = dev->dev_private;
4237         struct intel_ring_buffer *ring;
4238         int i;
4239
4240         for_each_ring(ring, dev_priv, i)
4241                 intel_cleanup_ring_buffer(ring);
4242 }
4243
4244 int
4245 i915_gem_entervt_ioctl(struct drm_device *dev, void *data,
4246                        struct drm_file *file_priv)
4247 {
4248         drm_i915_private_t *dev_priv = dev->dev_private;
4249         int ret;
4250
4251         if (drm_core_check_feature(dev, DRIVER_MODESET))
4252                 return 0;
4253
4254         if (i915_reset_in_progress(&dev_priv->gpu_error)) {
4255                 DRM_ERROR("Reenabling wedged hardware, good luck\n");
4256                 atomic_set(&dev_priv->gpu_error.reset_counter, 0);
4257         }
4258
4259         mutex_lock(&dev->struct_mutex);
4260         dev_priv->mm.suspended = 0;
4261
4262         ret = i915_gem_init_hw(dev);
4263         if (ret != 0) {
4264                 mutex_unlock(&dev->struct_mutex);
4265                 return ret;
4266         }
4267
4268         KASSERT(list_empty(&dev_priv->mm.active_list), ("active list"));
4269         mutex_unlock(&dev->struct_mutex);
4270
4271         ret = drm_irq_install(dev);
4272         if (ret)
4273                 goto cleanup_ringbuffer;
4274
4275         return 0;
4276
4277 cleanup_ringbuffer:
4278         mutex_lock(&dev->struct_mutex);
4279         i915_gem_cleanup_ringbuffer(dev);
4280         dev_priv->mm.suspended = 1;
4281         mutex_unlock(&dev->struct_mutex);
4282
4283         return ret;
4284 }
4285
4286 int
4287 i915_gem_leavevt_ioctl(struct drm_device *dev, void *data,
4288                        struct drm_file *file_priv)
4289 {
4290         if (drm_core_check_feature(dev, DRIVER_MODESET))
4291                 return 0;
4292
4293         drm_irq_uninstall(dev);
4294         return i915_gem_idle(dev);
4295 }
4296
4297 void
4298 i915_gem_lastclose(struct drm_device *dev)
4299 {
4300         int ret;
4301
4302         if (drm_core_check_feature(dev, DRIVER_MODESET))
4303                 return;
4304
4305         ret = i915_gem_idle(dev);
4306         if (ret)
4307                 DRM_ERROR("failed to idle hardware: %d\n", ret);
4308 }
4309
4310 static void
4311 init_ring_lists(struct intel_ring_buffer *ring)
4312 {
4313         INIT_LIST_HEAD(&ring->active_list);
4314         INIT_LIST_HEAD(&ring->request_list);
4315 }
4316
4317 void
4318 i915_gem_load(struct drm_device *dev)
4319 {
4320         int i;
4321         drm_i915_private_t *dev_priv = dev->dev_private;
4322
4323         INIT_LIST_HEAD(&dev_priv->mm.active_list);
4324         INIT_LIST_HEAD(&dev_priv->mm.inactive_list);
4325         INIT_LIST_HEAD(&dev_priv->mm.unbound_list);
4326         INIT_LIST_HEAD(&dev_priv->mm.bound_list);
4327         INIT_LIST_HEAD(&dev_priv->mm.fence_list);
4328         for (i = 0; i < I915_NUM_RINGS; i++)
4329                 init_ring_lists(&dev_priv->ring[i]);
4330         for (i = 0; i < I915_MAX_NUM_FENCES; i++)
4331                 INIT_LIST_HEAD(&dev_priv->fence_regs[i].lru_list);
4332         INIT_DELAYED_WORK(&dev_priv->mm.retire_work,
4333                           i915_gem_retire_work_handler);
4334         init_waitqueue_head(&dev_priv->gpu_error.reset_queue);
4335
4336         /* On GEN3 we really need to make sure the ARB C3 LP bit is set */
4337         if (IS_GEN3(dev)) {
4338                 I915_WRITE(MI_ARB_STATE,
4339                            _MASKED_BIT_ENABLE(MI_ARB_C3_LP_WRITE_ENABLE));
4340         }
4341
4342         dev_priv->relative_constants_mode = I915_EXEC_CONSTANTS_REL_GENERAL;
4343
4344         /* Old X drivers will take 0-2 for front, back, depth buffers */
4345         if (!drm_core_check_feature(dev, DRIVER_MODESET))
4346                 dev_priv->fence_reg_start = 3;
4347
4348         if (INTEL_INFO(dev)->gen >= 7 && !IS_VALLEYVIEW(dev))
4349                 dev_priv->num_fence_regs = 32;
4350         else if (INTEL_INFO(dev)->gen >= 4 || IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev))
4351                 dev_priv->num_fence_regs = 16;
4352         else
4353                 dev_priv->num_fence_regs = 8;
4354
4355         /* Initialize fence registers to zero */
4356         INIT_LIST_HEAD(&dev_priv->mm.fence_list);
4357         i915_gem_restore_fences(dev);
4358
4359         i915_gem_detect_bit_6_swizzle(dev);
4360         init_waitqueue_head(&dev_priv->pending_flip_queue);
4361
4362         dev_priv->mm.interruptible = true;
4363
4364 #if 0
4365         dev_priv->mm.inactive_shrinker.shrink = i915_gem_inactive_shrink;
4366         dev_priv->mm.inactive_shrinker.seeks = DEFAULT_SEEKS;
4367         register_shrinker(&dev_priv->mm.inactive_shrinker);
4368 #else
4369         dev_priv->mm.inactive_shrinker = EVENTHANDLER_REGISTER(vm_lowmem,
4370             i915_gem_lowmem, dev, EVENTHANDLER_PRI_ANY);
4371 #endif
4372 }
4373
4374 /*
4375  * Create a physically contiguous memory object for this object
4376  * e.g. for cursor + overlay regs
4377  */
4378 static int i915_gem_init_phys_object(struct drm_device *dev,
4379                                      int id, int size, int align)
4380 {
4381         drm_i915_private_t *dev_priv = dev->dev_private;
4382         struct drm_i915_gem_phys_object *phys_obj;
4383         int ret;
4384
4385         if (dev_priv->mm.phys_objs[id - 1] || !size)
4386                 return 0;
4387
4388         phys_obj = kzalloc(sizeof(struct drm_i915_gem_phys_object), GFP_KERNEL);
4389         if (!phys_obj)
4390                 return -ENOMEM;
4391
4392         phys_obj->id = id;
4393
4394         phys_obj->handle = drm_pci_alloc(dev, size, align);
4395         if (!phys_obj->handle) {
4396                 ret = -ENOMEM;
4397                 goto kfree_obj;
4398         }
4399         pmap_change_attr((vm_offset_t)phys_obj->handle->vaddr,
4400             size / PAGE_SIZE, PAT_WRITE_COMBINING);
4401
4402         dev_priv->mm.phys_objs[id - 1] = phys_obj;
4403
4404         return 0;
4405
4406 kfree_obj:
4407         kfree(phys_obj);
4408         return ret;
4409 }
4410
4411 static void i915_gem_free_phys_object(struct drm_device *dev, int id)
4412 {
4413         drm_i915_private_t *dev_priv = dev->dev_private;
4414         struct drm_i915_gem_phys_object *phys_obj;
4415
4416         if (!dev_priv->mm.phys_objs[id - 1])
4417                 return;
4418
4419         phys_obj = dev_priv->mm.phys_objs[id - 1];
4420         if (phys_obj->cur_obj) {
4421                 i915_gem_detach_phys_object(dev, phys_obj->cur_obj);
4422         }
4423
4424         drm_pci_free(dev, phys_obj->handle);
4425         kfree(phys_obj);
4426         dev_priv->mm.phys_objs[id - 1] = NULL;
4427 }
4428
4429 void i915_gem_free_all_phys_object(struct drm_device *dev)
4430 {
4431         int i;
4432
4433         for (i = I915_GEM_PHYS_CURSOR_0; i <= I915_MAX_PHYS_OBJECT; i++)
4434                 i915_gem_free_phys_object(dev, i);
4435 }
4436
4437 void i915_gem_detach_phys_object(struct drm_device *dev,
4438                                  struct drm_i915_gem_object *obj)
4439 {
4440         struct vm_object *mapping = obj->base.vm_obj;
4441         char *vaddr;
4442         int i;
4443         int page_count;
4444
4445         if (!obj->phys_obj)
4446                 return;
4447         vaddr = obj->phys_obj->handle->vaddr;
4448
4449         page_count = obj->base.size / PAGE_SIZE;
4450         VM_OBJECT_LOCK(obj->base.vm_obj);
4451         for (i = 0; i < page_count; i++) {
4452                 struct vm_page *page = shmem_read_mapping_page(mapping, i);
4453                 if (!IS_ERR(page)) {
4454                         VM_OBJECT_UNLOCK(obj->base.vm_obj);
4455                         char *dst = kmap_atomic(page);
4456                         memcpy(dst, vaddr + i*PAGE_SIZE, PAGE_SIZE);
4457                         kunmap_atomic(dst);
4458
4459                         drm_clflush_pages(&page, 1);
4460
4461 #if 0
4462                         set_page_dirty(page);
4463                         mark_page_accessed(page);
4464                         page_cache_release(page);
4465 #endif
4466                         VM_OBJECT_LOCK(obj->base.vm_obj);
4467                         vm_page_reference(page);
4468                         vm_page_dirty(page);
4469                         vm_page_busy_wait(page, FALSE, "i915gem");
4470                         vm_page_unwire(page, 0);
4471                         vm_page_wakeup(page);
4472                 }
4473         }
4474         VM_OBJECT_UNLOCK(obj->base.vm_obj);
4475         intel_gtt_chipset_flush();
4476
4477         obj->phys_obj->cur_obj = NULL;
4478         obj->phys_obj = NULL;
4479 }
4480
4481 int
4482 i915_gem_attach_phys_object(struct drm_device *dev,
4483                             struct drm_i915_gem_object *obj,
4484                             int id,
4485                             int align)
4486 {
4487         struct vm_object *mapping = obj->base.vm_obj;
4488         drm_i915_private_t *dev_priv = dev->dev_private;
4489         int ret = 0;
4490         int page_count;
4491         int i;
4492
4493         if (id > I915_MAX_PHYS_OBJECT)
4494                 return -EINVAL;
4495
4496         if (obj->phys_obj) {
4497                 if (obj->phys_obj->id == id)
4498                         return 0;
4499                 i915_gem_detach_phys_object(dev, obj);
4500         }
4501
4502         /* create a new object */
4503         if (!dev_priv->mm.phys_objs[id - 1]) {
4504                 ret = i915_gem_init_phys_object(dev, id,
4505                                                 obj->base.size, align);
4506                 if (ret) {
4507                         DRM_ERROR("failed to init phys object %d size: %zu\n",
4508                                   id, obj->base.size);
4509                         return ret;
4510                 }
4511         }
4512
4513         /* bind to the object */
4514         obj->phys_obj = dev_priv->mm.phys_objs[id - 1];
4515         obj->phys_obj->cur_obj = obj;
4516
4517         page_count = obj->base.size / PAGE_SIZE;
4518
4519         VM_OBJECT_LOCK(obj->base.vm_obj);
4520         for (i = 0; i < page_count; i++) {
4521                 struct vm_page *page;
4522                 char *dst, *src;
4523
4524                 page = shmem_read_mapping_page(mapping, i);
4525                 VM_OBJECT_UNLOCK(obj->base.vm_obj);
4526                 if (IS_ERR(page))
4527                         return PTR_ERR(page);
4528
4529                 src = kmap_atomic(page);
4530                 dst = (char*)obj->phys_obj->handle->vaddr + (i * PAGE_SIZE);
4531                 memcpy(dst, src, PAGE_SIZE);
4532                 kunmap_atomic(src);
4533
4534 #if 0
4535                 mark_page_accessed(page);
4536                 page_cache_release(page);
4537 #endif
4538                 VM_OBJECT_LOCK(obj->base.vm_obj);
4539                 vm_page_reference(page);
4540                 vm_page_busy_wait(page, FALSE, "i915gem");
4541                 vm_page_unwire(page, 0);
4542                 vm_page_wakeup(page);
4543         }
4544         VM_OBJECT_UNLOCK(obj->base.vm_obj);
4545
4546         return 0;
4547 }
4548
4549 static int
4550 i915_gem_phys_pwrite(struct drm_device *dev,
4551                      struct drm_i915_gem_object *obj,
4552                      struct drm_i915_gem_pwrite *args,
4553                      struct drm_file *file_priv)
4554 {
4555         void *vaddr = (char *)obj->phys_obj->handle->vaddr + args->offset;
4556         char __user *user_data = to_user_ptr(args->data_ptr);
4557
4558         if (__copy_from_user_inatomic_nocache(vaddr, user_data, args->size)) {
4559                 unsigned long unwritten;
4560
4561                 /* The physical object once assigned is fixed for the lifetime
4562                  * of the obj, so we can safely drop the lock and continue
4563                  * to access vaddr.
4564                  */
4565                 mutex_unlock(&dev->struct_mutex);
4566                 unwritten = copy_from_user(vaddr, user_data, args->size);
4567                 mutex_lock(&dev->struct_mutex);
4568                 if (unwritten)
4569                         return -EFAULT;
4570         }
4571
4572         i915_gem_chipset_flush(dev);
4573         return 0;
4574 }
4575
4576 void i915_gem_release(struct drm_device *dev, struct drm_file *file)
4577 {
4578         struct drm_i915_file_private *file_priv = file->driver_priv;
4579
4580         /* Clean up our request list when the client is going away, so that
4581          * later retire_requests won't dereference our soon-to-be-gone
4582          * file_priv.
4583          */
4584         spin_lock(&file_priv->mm.lock);
4585         while (!list_empty(&file_priv->mm.request_list)) {
4586                 struct drm_i915_gem_request *request;
4587
4588                 request = list_first_entry(&file_priv->mm.request_list,
4589                                            struct drm_i915_gem_request,
4590                                            client_list);
4591                 list_del(&request->client_list);
4592                 request->file_priv = NULL;
4593         }
4594         spin_unlock(&file_priv->mm.lock);
4595 }
4596
4597 int
4598 i915_gem_pager_ctor(void *handle, vm_ooffset_t size, vm_prot_t prot,
4599     vm_ooffset_t foff, struct ucred *cred, u_short *color)
4600 {
4601
4602         *color = 0; /* XXXKIB */
4603         return (0);
4604 }
4605
4606 void
4607 i915_gem_pager_dtor(void *handle)
4608 {
4609         struct drm_gem_object *obj;
4610         struct drm_device *dev;
4611
4612         obj = handle;
4613         dev = obj->dev;
4614
4615         mutex_lock(&dev->struct_mutex);
4616         drm_gem_free_mmap_offset(obj);
4617         i915_gem_release_mmap(to_intel_bo(obj));
4618         drm_gem_object_unreference(obj);
4619         mutex_unlock(&dev->struct_mutex);
4620 }
4621
4622 #define GEM_PARANOID_CHECK_GTT 0
4623 #if GEM_PARANOID_CHECK_GTT
4624 static void
4625 i915_gem_assert_pages_not_mapped(struct drm_device *dev, vm_page_t *ma,
4626     int page_count)
4627 {
4628         struct drm_i915_private *dev_priv;
4629         vm_paddr_t pa;
4630         unsigned long start, end;
4631         u_int i;
4632         int j;
4633
4634         dev_priv = dev->dev_private;
4635         start = OFF_TO_IDX(dev_priv->mm.gtt_start);
4636         end = OFF_TO_IDX(dev_priv->mm.gtt_end);
4637         for (i = start; i < end; i++) {
4638                 pa = intel_gtt_read_pte_paddr(i);
4639                 for (j = 0; j < page_count; j++) {
4640                         if (pa == VM_PAGE_TO_PHYS(ma[j])) {
4641                                 panic("Page %p in GTT pte index %d pte %x",
4642                                     ma[i], i, intel_gtt_read_pte(i));
4643                         }
4644                 }
4645         }
4646         obj->fence_dirty = false;
4647 }
4648 #endif
4649
4650 static int
4651 i915_gpu_is_active(struct drm_device *dev)
4652 {
4653         drm_i915_private_t *dev_priv = dev->dev_private;
4654
4655         return !list_empty(&dev_priv->mm.active_list);
4656 }
4657
4658 static void
4659 i915_gem_lowmem(void *arg)
4660 {
4661         struct drm_device *dev;
4662         struct drm_i915_private *dev_priv;
4663         struct drm_i915_gem_object *obj, *next;
4664         int cnt, cnt_fail, cnt_total;
4665
4666         dev = arg;
4667         dev_priv = dev->dev_private;
4668
4669         if (lockmgr(&dev->struct_mutex, LK_EXCLUSIVE|LK_NOWAIT))
4670                 return;
4671
4672 rescan:
4673         /* first scan for clean buffers */
4674         i915_gem_retire_requests(dev);
4675
4676         cnt_total = cnt_fail = cnt = 0;
4677
4678         list_for_each_entry_safe(obj, next, &dev_priv->mm.inactive_list,
4679             mm_list) {
4680                 if (i915_gem_object_is_purgeable(obj)) {
4681                         if (i915_gem_object_unbind(obj) != 0)
4682                                 cnt_total++;
4683                 } else
4684                         cnt_total++;
4685         }
4686
4687         /* second pass, evict/count anything still on the inactive list */
4688         list_for_each_entry_safe(obj, next, &dev_priv->mm.inactive_list,
4689             mm_list) {
4690                 if (i915_gem_object_unbind(obj) == 0)
4691                         cnt++;
4692                 else
4693                         cnt_fail++;
4694         }
4695
4696         if (cnt_fail > cnt_total / 100 && i915_gpu_is_active(dev)) {
4697                 /*
4698                  * We are desperate for pages, so as a last resort, wait
4699                  * for the GPU to finish and discard whatever we can.
4700                  * This has a dramatic impact to reduce the number of
4701                  * OOM-killer events whilst running the GPU aggressively.
4702                  */
4703                 if (i915_gpu_idle(dev) == 0)
4704                         goto rescan;
4705         }
4706         mutex_unlock(&dev->struct_mutex);
4707 }