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