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