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