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