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