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