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