Home | History | Annotate | Line # | Download | only in i915
i915_gem.c revision 1.14.2.7
      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 (at) anholt.net>
     25  *
     26  */
     27 
     28 #ifdef __NetBSD__
     29 #if 0				/* XXX uvmhist option?  */
     30 #include "opt_uvmhist.h"
     31 #endif
     32 
     33 #include <sys/types.h>
     34 #include <sys/param.h>
     35 
     36 #include <uvm/uvm.h>
     37 #include <uvm/uvm_extern.h>
     38 #include <uvm/uvm_fault.h>
     39 #include <uvm/uvm_page.h>
     40 #include <uvm/uvm_pmap.h>
     41 #include <uvm/uvm_prot.h>
     42 
     43 #include <drm/bus_dma_hacks.h>
     44 #endif
     45 
     46 #include <drm/drmP.h>
     47 #include <drm/drm_vma_manager.h>
     48 #include <drm/i915_drm.h>
     49 #include "i915_drv.h"
     50 #include "i915_trace.h"
     51 #include "intel_drv.h"
     52 #include <linux/shmem_fs.h>
     53 #include <linux/slab.h>
     54 #include <linux/swap.h>
     55 #include <linux/pci.h>
     56 #include <linux/dma-buf.h>
     57 #include <linux/errno.h>
     58 #include <linux/time.h>
     59 #include <linux/err.h>
     60 #include <linux/bitops.h>
     61 #include <linux/printk.h>
     62 #include <asm/param.h>
     63 #include <asm/page.h>
     64 
     65 static void i915_gem_object_flush_gtt_write_domain(struct drm_i915_gem_object *obj);
     66 static void i915_gem_object_flush_cpu_write_domain(struct drm_i915_gem_object *obj,
     67 						   bool force);
     68 static __must_check int
     69 i915_gem_object_wait_rendering(struct drm_i915_gem_object *obj,
     70 			       bool readonly);
     71 
     72 static void i915_gem_write_fence(struct drm_device *dev, int reg,
     73 				 struct drm_i915_gem_object *obj);
     74 static void i915_gem_object_update_fence(struct drm_i915_gem_object *obj,
     75 					 struct drm_i915_fence_reg *fence,
     76 					 bool enable);
     77 
     78 static unsigned long i915_gem_inactive_count(struct shrinker *shrinker,
     79 					     struct shrink_control *sc);
     80 static unsigned long i915_gem_inactive_scan(struct shrinker *shrinker,
     81 					    struct shrink_control *sc);
     82 static unsigned long i915_gem_purge(struct drm_i915_private *dev_priv, long target);
     83 static unsigned long i915_gem_shrink_all(struct drm_i915_private *dev_priv);
     84 static void i915_gem_object_truncate(struct drm_i915_gem_object *obj);
     85 static void i915_gem_retire_requests_ring(struct intel_ring_buffer *ring);
     86 
     87 static bool cpu_cache_is_coherent(struct drm_device *dev,
     88 				  enum i915_cache_level level)
     89 {
     90 	return HAS_LLC(dev) || level != I915_CACHE_NONE;
     91 }
     92 
     93 static bool cpu_write_needs_clflush(struct drm_i915_gem_object *obj)
     94 {
     95 	if (!cpu_cache_is_coherent(obj->base.dev, obj->cache_level))
     96 		return true;
     97 
     98 	return obj->pin_display;
     99 }
    100 
    101 static inline void i915_gem_object_fence_lost(struct drm_i915_gem_object *obj)
    102 {
    103 	if (obj->tiling_mode)
    104 		i915_gem_release_mmap(obj);
    105 
    106 	/* As we do not have an associated fence register, we will force
    107 	 * a tiling change if we ever need to acquire one.
    108 	 */
    109 	obj->fence_dirty = false;
    110 	obj->fence_reg = I915_FENCE_REG_NONE;
    111 }
    112 
    113 /* some bookkeeping */
    114 static void i915_gem_info_add_obj(struct drm_i915_private *dev_priv,
    115 				  size_t size)
    116 {
    117 	spin_lock(&dev_priv->mm.object_stat_lock);
    118 	dev_priv->mm.object_count++;
    119 	dev_priv->mm.object_memory += size;
    120 	spin_unlock(&dev_priv->mm.object_stat_lock);
    121 }
    122 
    123 static void i915_gem_info_remove_obj(struct drm_i915_private *dev_priv,
    124 				     size_t size)
    125 {
    126 	spin_lock(&dev_priv->mm.object_stat_lock);
    127 	dev_priv->mm.object_count--;
    128 	dev_priv->mm.object_memory -= size;
    129 	spin_unlock(&dev_priv->mm.object_stat_lock);
    130 }
    131 
    132 static int
    133 i915_gem_wait_for_error(struct i915_gpu_error *error)
    134 {
    135 	int ret;
    136 
    137 #define EXIT_COND (!i915_reset_in_progress(error) || \
    138 		   i915_terminally_wedged(error))
    139 	if (EXIT_COND)
    140 		return 0;
    141 
    142 	/*
    143 	 * Only wait 10 seconds for the gpu reset to complete to avoid hanging
    144 	 * userspace. If it takes that long something really bad is going on and
    145 	 * we should simply try to bail out and fail as gracefully as possible.
    146 	 */
    147 #ifdef __NetBSD__
    148 	spin_lock(&error->reset_lock);
    149 	DRM_SPIN_TIMED_WAIT_UNTIL(ret, &error->reset_queue, &error->reset_lock,
    150 	    10*HZ, EXIT_COND);
    151 	spin_unlock(&error->reset_lock);
    152 #else
    153 	ret = wait_event_interruptible_timeout(error->reset_queue,
    154 					       EXIT_COND,
    155 					       10*HZ);
    156 #endif
    157 	if (ret == 0) {
    158 		DRM_ERROR("Timed out waiting for the gpu reset to complete\n");
    159 		return -EIO;
    160 	} else if (ret < 0) {
    161 		return ret;
    162 	}
    163 #undef EXIT_COND
    164 
    165 	return 0;
    166 }
    167 
    168 int i915_mutex_lock_interruptible(struct drm_device *dev)
    169 {
    170 	struct drm_i915_private *dev_priv = dev->dev_private;
    171 	int ret;
    172 
    173 	ret = i915_gem_wait_for_error(&dev_priv->gpu_error);
    174 	if (ret)
    175 		return ret;
    176 
    177 	ret = mutex_lock_interruptible(&dev->struct_mutex);
    178 	if (ret)
    179 		return ret;
    180 
    181 	WARN_ON(i915_verify_lists(dev));
    182 	return 0;
    183 }
    184 
    185 static inline bool
    186 i915_gem_object_is_inactive(struct drm_i915_gem_object *obj)
    187 {
    188 	return i915_gem_obj_bound_any(obj) && !obj->active;
    189 }
    190 
    191 int
    192 i915_gem_init_ioctl(struct drm_device *dev, void *data,
    193 		    struct drm_file *file)
    194 {
    195 	struct drm_i915_private *dev_priv = dev->dev_private;
    196 	struct drm_i915_gem_init *args = data;
    197 
    198 	if (drm_core_check_feature(dev, DRIVER_MODESET))
    199 		return -ENODEV;
    200 
    201 	if (args->gtt_start >= args->gtt_end ||
    202 	    (args->gtt_end | args->gtt_start) & (PAGE_SIZE - 1))
    203 		return -EINVAL;
    204 
    205 	/* GEM with user mode setting was never supported on ilk and later. */
    206 	if (INTEL_INFO(dev)->gen >= 5)
    207 		return -ENODEV;
    208 
    209 	mutex_lock(&dev->struct_mutex);
    210 	i915_gem_setup_global_gtt(dev, args->gtt_start, args->gtt_end,
    211 				  args->gtt_end);
    212 	dev_priv->gtt.mappable_end = args->gtt_end;
    213 	mutex_unlock(&dev->struct_mutex);
    214 
    215 	return 0;
    216 }
    217 
    218 int
    219 i915_gem_get_aperture_ioctl(struct drm_device *dev, void *data,
    220 			    struct drm_file *file)
    221 {
    222 	struct drm_i915_private *dev_priv = dev->dev_private;
    223 	struct drm_i915_gem_get_aperture *args = data;
    224 	struct drm_i915_gem_object *obj;
    225 	size_t pinned;
    226 
    227 	pinned = 0;
    228 	mutex_lock(&dev->struct_mutex);
    229 	list_for_each_entry(obj, &dev_priv->mm.bound_list, global_list)
    230 		if (i915_gem_obj_is_pinned(obj))
    231 			pinned += i915_gem_obj_ggtt_size(obj);
    232 	mutex_unlock(&dev->struct_mutex);
    233 
    234 	args->aper_size = dev_priv->gtt.base.total;
    235 	args->aper_available_size = args->aper_size - pinned;
    236 
    237 	return 0;
    238 }
    239 
    240 static void i915_gem_object_detach_phys(struct drm_i915_gem_object *obj)
    241 {
    242 	drm_dma_handle_t *phys = obj->phys_handle;
    243 
    244 	if (!phys)
    245 		return;
    246 
    247 	if (obj->madv == I915_MADV_WILLNEED) {
    248 #ifdef __NetBSD__
    249 		const char *vaddr = phys->vaddr;
    250 		unsigned i;
    251 
    252 		for (i = 0; i < obj->base.size / PAGE_SIZE; i++) {
    253 			struct pglist pages;
    254 			int error;
    255 
    256 			TAILQ_INIT(&pages);
    257 			error = uvm_obj_wirepages(obj->base.gemo_shm_uao,
    258 			    i*PAGE_SIZE, (i+1)*PAGE_SIZE, &pages);
    259 			if (error)
    260 				continue;
    261 
    262 			struct vm_page *const vm_page = TAILQ_FIRST(&pages);
    263 			struct page *const page = container_of(vm_page,
    264 			    struct page, p_vmp);
    265 			char *const dst = kmap_atomic(page);
    266 			(void)memcpy(dst, vaddr + (i*PAGE_SIZE), PAGE_SIZE);
    267 			drm_clflush_virt_range(dst, PAGE_SIZE);
    268 			kunmap_atomic(dst);
    269 
    270 			vm_page->flags &= ~PG_CLEAN;
    271 			/* XXX mark page accessed */
    272 			uvm_obj_unwirepages(obj->base.gemo_shm_uao,
    273 			    i*PAGE_SIZE, (i+1)*PAGE_SIZE);
    274 		}
    275 #else
    276 		struct address_space *mapping = file_inode(obj->base.filp)->i_mapping;
    277 		char *vaddr = phys->vaddr;
    278 		int i;
    279 
    280 		for (i = 0; i < obj->base.size / PAGE_SIZE; i++) {
    281 			struct page *page = shmem_read_mapping_page(mapping, i);
    282 			if (!IS_ERR(page)) {
    283 				char *dst = kmap_atomic(page);
    284 				memcpy(dst, vaddr, PAGE_SIZE);
    285 				drm_clflush_virt_range(dst, PAGE_SIZE);
    286 				kunmap_atomic(dst);
    287 
    288 				set_page_dirty(page);
    289 				mark_page_accessed(page);
    290 				page_cache_release(page);
    291 			}
    292 			vaddr += PAGE_SIZE;
    293 		}
    294 #endif
    295 		i915_gem_chipset_flush(obj->base.dev);
    296 	}
    297 
    298 #ifndef __NetBSD__
    299 #ifdef CONFIG_X86
    300 	set_memory_wb((unsigned long)phys->vaddr, phys->size / PAGE_SIZE);
    301 #endif
    302 #endif
    303 	drm_pci_free(obj->base.dev, phys);
    304 	obj->phys_handle = NULL;
    305 }
    306 
    307 int
    308 i915_gem_object_attach_phys(struct drm_i915_gem_object *obj,
    309 			    int align)
    310 {
    311 	drm_dma_handle_t *phys;
    312 #ifndef __NetBSD__
    313 	struct address_space *mapping;
    314 #endif
    315 	char *vaddr;
    316 	int i;
    317 
    318 	if (obj->phys_handle) {
    319 		if ((unsigned long)obj->phys_handle->vaddr & (align -1))
    320 			return -EBUSY;
    321 
    322 		return 0;
    323 	}
    324 
    325 	if (obj->madv != I915_MADV_WILLNEED)
    326 		return -EFAULT;
    327 
    328 #ifdef __NetBSD__
    329 	if (obj->base.gemo_shm_uao == NULL)
    330 		return -EINVAL;
    331 #else
    332 	if (obj->base.filp == NULL)
    333 		return -EINVAL;
    334 #endif
    335 
    336 	/* create a new object */
    337 	phys = drm_pci_alloc(obj->base.dev, obj->base.size, align);
    338 	if (!phys)
    339 		return -ENOMEM;
    340 
    341 	vaddr = phys->vaddr;
    342 #ifndef __NetBSD__
    343 #ifdef CONFIG_X86
    344 	set_memory_wc((unsigned long)vaddr, phys->size / PAGE_SIZE);
    345 #endif
    346 	mapping = file_inode(obj->base.filp)->i_mapping;
    347 #endif
    348 	for (i = 0; i < obj->base.size / PAGE_SIZE; i++) {
    349 		struct page *page;
    350 		char *src;
    351 
    352 #ifdef __NetBSD__
    353 		struct pglist pages;
    354 		int ret;
    355 
    356 		TAILQ_INIT(&pages);
    357 
    358 		/* XXX errno NetBSD->Linux */
    359 		ret = -uvm_obj_wirepages(obj->base.gemo_shm_uao, i*PAGE_SIZE,
    360 		    (i+1)*PAGE_SIZE, &pages);
    361 		if (ret) {
    362 			drm_pci_free(obj->base.dev, phys);
    363 			return ret;
    364 		}
    365 		KASSERT(!TAILQ_EMPTY(&pages));
    366 		page = container_of(TAILQ_FIRST(&pages), struct page, p_vmp);
    367 #else
    368 		page = shmem_read_mapping_page(mapping, i);
    369 		if (IS_ERR(page)) {
    370 #ifdef CONFIG_X86
    371 			set_memory_wb((unsigned long)phys->vaddr, phys->size / PAGE_SIZE);
    372 #endif
    373 			drm_pci_free(obj->base.dev, phys);
    374 			return PTR_ERR(page);
    375 		}
    376 #endif	/* defined(__NetBSD__) */
    377 
    378 		src = kmap_atomic(page);
    379 		memcpy(vaddr, src, PAGE_SIZE);
    380 		kunmap_atomic(src);
    381 
    382 #ifdef __NetBSD__
    383 		/* XXX mark page accessed */
    384 		uvm_obj_unwirepages(obj->base.gemo_shm_uao, i*PAGE_SIZE,
    385 		    (i + 1)*PAGE_SIZE);
    386 #else
    387 		mark_page_accessed(page);
    388 		page_cache_release(page);
    389 #endif
    390 
    391 		vaddr += PAGE_SIZE;
    392 	}
    393 
    394 	obj->phys_handle = phys;
    395 	return 0;
    396 }
    397 
    398 static int
    399 i915_gem_phys_pwrite(struct drm_i915_gem_object *obj,
    400 		     struct drm_i915_gem_pwrite *args,
    401 		     struct drm_file *file_priv)
    402 {
    403 	struct drm_device *dev = obj->base.dev;
    404 	void *vaddr = (char *)obj->phys_handle->vaddr + args->offset;
    405 	char __user *user_data = to_user_ptr(args->data_ptr);
    406 
    407 	if (__copy_from_user_inatomic_nocache(vaddr, user_data, args->size)) {
    408 		unsigned long unwritten;
    409 
    410 		/* The physical object once assigned is fixed for the lifetime
    411 		 * of the obj, so we can safely drop the lock and continue
    412 		 * to access vaddr.
    413 		 */
    414 		mutex_unlock(&dev->struct_mutex);
    415 		unwritten = copy_from_user(vaddr, user_data, args->size);
    416 		mutex_lock(&dev->struct_mutex);
    417 		if (unwritten)
    418 			return -EFAULT;
    419 	}
    420 
    421 	i915_gem_chipset_flush(dev);
    422 	return 0;
    423 }
    424 
    425 void *i915_gem_object_alloc(struct drm_device *dev)
    426 {
    427 	struct drm_i915_private *dev_priv = dev->dev_private;
    428 	return kmem_cache_zalloc(dev_priv->slab, GFP_KERNEL);
    429 }
    430 
    431 void i915_gem_object_free(struct drm_i915_gem_object *obj)
    432 {
    433 	struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
    434 	kmem_cache_free(dev_priv->slab, obj);
    435 }
    436 
    437 static int
    438 i915_gem_create(struct drm_file *file,
    439 		struct drm_device *dev,
    440 		uint64_t size,
    441 		uint32_t *handle_p)
    442 {
    443 	struct drm_i915_gem_object *obj;
    444 	int ret;
    445 	u32 handle;
    446 
    447 	size = roundup(size, PAGE_SIZE);
    448 	if (size == 0)
    449 		return -EINVAL;
    450 
    451 	/* Allocate the new object */
    452 	obj = i915_gem_alloc_object(dev, size);
    453 	if (obj == NULL)
    454 		return -ENOMEM;
    455 
    456 	ret = drm_gem_handle_create(file, &obj->base, &handle);
    457 	/* drop reference from allocate - handle holds it now */
    458 	drm_gem_object_unreference_unlocked(&obj->base);
    459 	if (ret)
    460 		return ret;
    461 
    462 	*handle_p = handle;
    463 	return 0;
    464 }
    465 
    466 int
    467 i915_gem_dumb_create(struct drm_file *file,
    468 		     struct drm_device *dev,
    469 		     struct drm_mode_create_dumb *args)
    470 {
    471 	/* have to work out size/pitch and return them */
    472 #ifdef __NetBSD__		/* ALIGN means something else.  */
    473 	args->pitch = round_up(args->width * DIV_ROUND_UP(args->bpp, 8), 64);
    474 #else
    475 	args->pitch = ALIGN(args->width * DIV_ROUND_UP(args->bpp, 8), 64);
    476 #endif
    477 	args->size = args->pitch * args->height;
    478 	return i915_gem_create(file, dev,
    479 			       args->size, &args->handle);
    480 }
    481 
    482 /**
    483  * Creates a new mm object and returns a handle to it.
    484  */
    485 int
    486 i915_gem_create_ioctl(struct drm_device *dev, void *data,
    487 		      struct drm_file *file)
    488 {
    489 	struct drm_i915_gem_create *args = data;
    490 
    491 	return i915_gem_create(file, dev,
    492 			       args->size, &args->handle);
    493 }
    494 
    495 static inline int
    496 __copy_to_user_swizzled(char __user *cpu_vaddr,
    497 			const char *gpu_vaddr, int gpu_offset,
    498 			int length)
    499 {
    500 	int ret, cpu_offset = 0;
    501 
    502 	while (length > 0) {
    503 #ifdef __NetBSD__		/* XXX ALIGN means something else.  */
    504 		int cacheline_end = round_up(gpu_offset + 1, 64);
    505 #else
    506 		int cacheline_end = ALIGN(gpu_offset + 1, 64);
    507 #endif
    508 		int this_length = min(cacheline_end - gpu_offset, length);
    509 		int swizzled_gpu_offset = gpu_offset ^ 64;
    510 
    511 		ret = __copy_to_user(cpu_vaddr + cpu_offset,
    512 				     gpu_vaddr + swizzled_gpu_offset,
    513 				     this_length);
    514 		if (ret)
    515 			return ret + length;
    516 
    517 		cpu_offset += this_length;
    518 		gpu_offset += this_length;
    519 		length -= this_length;
    520 	}
    521 
    522 	return 0;
    523 }
    524 
    525 static inline int
    526 __copy_from_user_swizzled(char *gpu_vaddr, int gpu_offset,
    527 			  const char __user *cpu_vaddr,
    528 			  int length)
    529 {
    530 	int ret, cpu_offset = 0;
    531 
    532 	while (length > 0) {
    533 #ifdef __NetBSD__		/* XXX ALIGN means something else.  */
    534 		int cacheline_end = round_up(gpu_offset + 1, 64);
    535 #else
    536 		int cacheline_end = ALIGN(gpu_offset + 1, 64);
    537 #endif
    538 		int this_length = min(cacheline_end - gpu_offset, length);
    539 		int swizzled_gpu_offset = gpu_offset ^ 64;
    540 
    541 		ret = __copy_from_user(gpu_vaddr + swizzled_gpu_offset,
    542 				       cpu_vaddr + cpu_offset,
    543 				       this_length);
    544 		if (ret)
    545 			return ret + length;
    546 
    547 		cpu_offset += this_length;
    548 		gpu_offset += this_length;
    549 		length -= this_length;
    550 	}
    551 
    552 	return 0;
    553 }
    554 
    555 /*
    556  * Pins the specified object's pages and synchronizes the object with
    557  * GPU accesses. Sets needs_clflush to non-zero if the caller should
    558  * flush the object from the CPU cache.
    559  */
    560 int i915_gem_obj_prepare_shmem_read(struct drm_i915_gem_object *obj,
    561 				    int *needs_clflush)
    562 {
    563 	int ret;
    564 
    565 	*needs_clflush = 0;
    566 
    567 #ifdef __NetBSD__
    568 	if (obj->base.gemo_shm_uao == NULL)
    569 		return -EINVAL;
    570 #else
    571 	if (!obj->base.filp)
    572 		return -EINVAL;
    573 #endif
    574 
    575 	if (!(obj->base.read_domains & I915_GEM_DOMAIN_CPU)) {
    576 		/* If we're not in the cpu read domain, set ourself into the gtt
    577 		 * read domain and manually flush cachelines (if required). This
    578 		 * optimizes for the case when the gpu will dirty the data
    579 		 * anyway again before the next pread happens. */
    580 		*needs_clflush = !cpu_cache_is_coherent(obj->base.dev,
    581 							obj->cache_level);
    582 		ret = i915_gem_object_wait_rendering(obj, true);
    583 		if (ret)
    584 			return ret;
    585 	}
    586 
    587 	ret = i915_gem_object_get_pages(obj);
    588 	if (ret)
    589 		return ret;
    590 
    591 	i915_gem_object_pin_pages(obj);
    592 
    593 	return ret;
    594 }
    595 
    596 /* Per-page copy function for the shmem pread fastpath.
    597  * Flushes invalid cachelines before reading the target if
    598  * needs_clflush is set. */
    599 static int
    600 shmem_pread_fast(struct page *page, int shmem_page_offset, int page_length,
    601 		 char __user *user_data,
    602 		 bool page_do_bit17_swizzling, bool needs_clflush)
    603 {
    604 #ifdef __NetBSD__		/* XXX atomic shmem fast path */
    605 	return -EFAULT;
    606 #else
    607 	char *vaddr;
    608 	int ret;
    609 
    610 	if (unlikely(page_do_bit17_swizzling))
    611 		return -EINVAL;
    612 
    613 	vaddr = kmap_atomic(page);
    614 	if (needs_clflush)
    615 		drm_clflush_virt_range(vaddr + shmem_page_offset,
    616 				       page_length);
    617 	ret = __copy_to_user_inatomic(user_data,
    618 				      vaddr + shmem_page_offset,
    619 				      page_length);
    620 	kunmap_atomic(vaddr);
    621 
    622 	return ret ? -EFAULT : 0;
    623 #endif
    624 }
    625 
    626 static void
    627 shmem_clflush_swizzled_range(char *addr, unsigned long length,
    628 			     bool swizzled)
    629 {
    630 	if (unlikely(swizzled)) {
    631 		unsigned long start = (unsigned long) addr;
    632 		unsigned long end = (unsigned long) addr + length;
    633 
    634 		/* For swizzling simply ensure that we always flush both
    635 		 * channels. Lame, but simple and it works. Swizzled
    636 		 * pwrite/pread is far from a hotpath - current userspace
    637 		 * doesn't use it at all. */
    638 		start = round_down(start, 128);
    639 		end = round_up(end, 128);
    640 
    641 		drm_clflush_virt_range((void *)start, end - start);
    642 	} else {
    643 		drm_clflush_virt_range(addr, length);
    644 	}
    645 
    646 }
    647 
    648 /* Only difference to the fast-path function is that this can handle bit17
    649  * and uses non-atomic copy and kmap functions. */
    650 static int
    651 shmem_pread_slow(struct page *page, int shmem_page_offset, int page_length,
    652 		 char __user *user_data,
    653 		 bool page_do_bit17_swizzling, bool needs_clflush)
    654 {
    655 	char *vaddr;
    656 	int ret;
    657 
    658 	vaddr = kmap(page);
    659 	if (needs_clflush)
    660 		shmem_clflush_swizzled_range(vaddr + shmem_page_offset,
    661 					     page_length,
    662 					     page_do_bit17_swizzling);
    663 
    664 	if (page_do_bit17_swizzling)
    665 		ret = __copy_to_user_swizzled(user_data,
    666 					      vaddr, shmem_page_offset,
    667 					      page_length);
    668 	else
    669 		ret = __copy_to_user(user_data,
    670 				     vaddr + shmem_page_offset,
    671 				     page_length);
    672 	kunmap(page);
    673 
    674 	return ret ? - EFAULT : 0;
    675 }
    676 
    677 static int
    678 i915_gem_shmem_pread(struct drm_device *dev,
    679 		     struct drm_i915_gem_object *obj,
    680 		     struct drm_i915_gem_pread *args,
    681 		     struct drm_file *file)
    682 {
    683 	char __user *user_data;
    684 	ssize_t remain;
    685 	loff_t offset;
    686 	int shmem_page_offset, page_length, ret = 0;
    687 	int obj_do_bit17_swizzling, page_do_bit17_swizzling;
    688 #ifndef __NetBSD__		/* XXX */
    689 	int prefaulted = 0;
    690 #endif
    691 	int needs_clflush = 0;
    692 #ifndef __NetBSD__
    693 	struct sg_page_iter sg_iter;
    694 #endif
    695 
    696 	user_data = to_user_ptr(args->data_ptr);
    697 	remain = args->size;
    698 
    699 	obj_do_bit17_swizzling = i915_gem_object_needs_bit17_swizzle(obj);
    700 
    701 	ret = i915_gem_obj_prepare_shmem_read(obj, &needs_clflush);
    702 	if (ret)
    703 		return ret;
    704 
    705 	offset = args->offset;
    706 
    707 #ifdef __NetBSD__
    708 	while (0 < remain)
    709 #else
    710 	for_each_sg_page(obj->pages->sgl, &sg_iter, obj->pages->nents,
    711 			 offset >> PAGE_SHIFT)
    712 #endif
    713 	{
    714 #ifdef __NetBSD__
    715 		struct page *const page = i915_gem_object_get_page(obj,
    716 		    atop(offset));
    717 #else
    718 		struct page *page = sg_page_iter_page(&sg_iter);
    719 
    720 		if (remain <= 0)
    721 			break;
    722 #endif
    723 
    724 		/* Operation in this page
    725 		 *
    726 		 * shmem_page_offset = offset within page in shmem file
    727 		 * page_length = bytes to copy for this page
    728 		 */
    729 		shmem_page_offset = offset_in_page(offset);
    730 		page_length = remain;
    731 		if ((shmem_page_offset + page_length) > PAGE_SIZE)
    732 			page_length = PAGE_SIZE - shmem_page_offset;
    733 
    734 		page_do_bit17_swizzling = obj_do_bit17_swizzling &&
    735 			(page_to_phys(page) & (1 << 17)) != 0;
    736 
    737 		ret = shmem_pread_fast(page, shmem_page_offset, page_length,
    738 				       user_data, page_do_bit17_swizzling,
    739 				       needs_clflush);
    740 		if (ret == 0)
    741 			goto next_page;
    742 
    743 		mutex_unlock(&dev->struct_mutex);
    744 #ifndef __NetBSD__
    745 		if (likely(!i915.prefault_disable) && !prefaulted) {
    746 			ret = fault_in_multipages_writeable(user_data, remain);
    747 			/* Userspace is tricking us, but we've already clobbered
    748 			 * its pages with the prefault and promised to write the
    749 			 * data up to the first fault. Hence ignore any errors
    750 			 * and just continue. */
    751 			(void)ret;
    752 			prefaulted = 1;
    753 		}
    754 #endif
    755 		ret = shmem_pread_slow(page, shmem_page_offset, page_length,
    756 				       user_data, page_do_bit17_swizzling,
    757 				       needs_clflush);
    758 
    759 		mutex_lock(&dev->struct_mutex);
    760 
    761 		if (ret)
    762 			goto out;
    763 
    764 next_page:
    765 		remain -= page_length;
    766 		user_data += page_length;
    767 		offset += page_length;
    768 	}
    769 
    770 out:
    771 	i915_gem_object_unpin_pages(obj);
    772 
    773 	return ret;
    774 }
    775 
    776 /**
    777  * Reads data from the object referenced by handle.
    778  *
    779  * On error, the contents of *data are undefined.
    780  */
    781 int
    782 i915_gem_pread_ioctl(struct drm_device *dev, void *data,
    783 		     struct drm_file *file)
    784 {
    785 	struct drm_i915_gem_pread *args = data;
    786 	struct drm_gem_object *gobj;
    787 	struct drm_i915_gem_object *obj;
    788 	int ret = 0;
    789 
    790 	if (args->size == 0)
    791 		return 0;
    792 
    793 	if (!access_ok(VERIFY_WRITE,
    794 		       to_user_ptr(args->data_ptr),
    795 		       args->size))
    796 		return -EFAULT;
    797 
    798 	ret = i915_mutex_lock_interruptible(dev);
    799 	if (ret)
    800 		return ret;
    801 
    802 	gobj = drm_gem_object_lookup(dev, file, args->handle);
    803 	if (gobj == NULL) {
    804 		ret = -ENOENT;
    805 		goto unlock;
    806 	}
    807 	obj = to_intel_bo(gobj);
    808 
    809 	/* Bounds check source.  */
    810 	if (args->offset > obj->base.size ||
    811 	    args->size > obj->base.size - args->offset) {
    812 		ret = -EINVAL;
    813 		goto out;
    814 	}
    815 
    816 	/* prime objects have no backing filp to GEM pread/pwrite
    817 	 * pages from.
    818 	 */
    819 #ifdef __NetBSD__
    820 	/* Also stolen objects.  */
    821 	if (obj->base.gemo_shm_uao == NULL) {
    822 		ret = -EINVAL;
    823 		goto out;
    824 	}
    825 #else
    826 	if (!obj->base.filp) {
    827 		ret = -EINVAL;
    828 		goto out;
    829 	}
    830 #endif
    831 
    832 	trace_i915_gem_object_pread(obj, args->offset, args->size);
    833 
    834 	ret = i915_gem_shmem_pread(dev, obj, args, file);
    835 
    836 out:
    837 	drm_gem_object_unreference(&obj->base);
    838 unlock:
    839 	mutex_unlock(&dev->struct_mutex);
    840 	return ret;
    841 }
    842 
    843 /* This is the fast write path which cannot handle
    844  * page faults in the source data
    845  */
    846 
    847 static inline int
    848 fast_user_write(struct io_mapping *mapping,
    849 		loff_t page_base, int page_offset,
    850 		char __user *user_data,
    851 		int length)
    852 {
    853 #ifdef __NetBSD__		/* XXX atomic shmem fast path */
    854 	return -EFAULT;
    855 #else
    856 	void __iomem *vaddr_atomic;
    857 	void *vaddr;
    858 	unsigned long unwritten;
    859 
    860 	vaddr_atomic = io_mapping_map_atomic_wc(mapping, page_base);
    861 	/* We can use the cpu mem copy function because this is X86. */
    862 	vaddr = (void __force*)vaddr_atomic + page_offset;
    863 	unwritten = __copy_from_user_inatomic_nocache(vaddr,
    864 						      user_data, length);
    865 	io_mapping_unmap_atomic(vaddr_atomic);
    866 	return unwritten;
    867 #endif
    868 }
    869 
    870 /**
    871  * This is the fast pwrite path, where we copy the data directly from the
    872  * user into the GTT, uncached.
    873  */
    874 static int
    875 i915_gem_gtt_pwrite_fast(struct drm_device *dev,
    876 			 struct drm_i915_gem_object *obj,
    877 			 struct drm_i915_gem_pwrite *args,
    878 			 struct drm_file *file)
    879 {
    880 	struct drm_i915_private *dev_priv = dev->dev_private;
    881 	ssize_t remain;
    882 	loff_t offset, page_base;
    883 	char __user *user_data;
    884 	int page_offset, page_length, ret;
    885 
    886 	ret = i915_gem_obj_ggtt_pin(obj, 0, PIN_MAPPABLE | PIN_NONBLOCK);
    887 	if (ret)
    888 		goto out;
    889 
    890 	ret = i915_gem_object_set_to_gtt_domain(obj, true);
    891 	if (ret)
    892 		goto out_unpin;
    893 
    894 	ret = i915_gem_object_put_fence(obj);
    895 	if (ret)
    896 		goto out_unpin;
    897 
    898 	user_data = to_user_ptr(args->data_ptr);
    899 	remain = args->size;
    900 
    901 	offset = i915_gem_obj_ggtt_offset(obj) + args->offset;
    902 
    903 	while (remain > 0) {
    904 		/* Operation in this page
    905 		 *
    906 		 * page_base = page offset within aperture
    907 		 * page_offset = offset within page
    908 		 * page_length = bytes to copy for this page
    909 		 */
    910 		page_base = offset & PAGE_MASK;
    911 		page_offset = offset_in_page(offset);
    912 		page_length = remain;
    913 		if ((page_offset + remain) > PAGE_SIZE)
    914 			page_length = PAGE_SIZE - page_offset;
    915 
    916 		/* If we get a fault while copying data, then (presumably) our
    917 		 * source page isn't available.  Return the error and we'll
    918 		 * retry in the slow path.
    919 		 */
    920 		if (fast_user_write(dev_priv->gtt.mappable, page_base,
    921 				    page_offset, user_data, page_length)) {
    922 			ret = -EFAULT;
    923 			goto out_unpin;
    924 		}
    925 
    926 		remain -= page_length;
    927 		user_data += page_length;
    928 		offset += page_length;
    929 	}
    930 
    931 out_unpin:
    932 	i915_gem_object_ggtt_unpin(obj);
    933 out:
    934 	return ret;
    935 }
    936 
    937 /* Per-page copy function for the shmem pwrite fastpath.
    938  * Flushes invalid cachelines before writing to the target if
    939  * needs_clflush_before is set and flushes out any written cachelines after
    940  * writing if needs_clflush is set. */
    941 static int
    942 shmem_pwrite_fast(struct page *page, int shmem_page_offset, int page_length,
    943 		  char __user *user_data,
    944 		  bool page_do_bit17_swizzling,
    945 		  bool needs_clflush_before,
    946 		  bool needs_clflush_after)
    947 {
    948 #ifdef __NetBSD__
    949 	return -EFAULT;
    950 #else
    951 	char *vaddr;
    952 	int ret;
    953 
    954 	if (unlikely(page_do_bit17_swizzling))
    955 		return -EINVAL;
    956 
    957 	vaddr = kmap_atomic(page);
    958 	if (needs_clflush_before)
    959 		drm_clflush_virt_range(vaddr + shmem_page_offset,
    960 				       page_length);
    961 	ret = __copy_from_user_inatomic(vaddr + shmem_page_offset,
    962 					user_data, page_length);
    963 	if (needs_clflush_after)
    964 		drm_clflush_virt_range(vaddr + shmem_page_offset,
    965 				       page_length);
    966 	kunmap_atomic(vaddr);
    967 
    968 	return ret ? -EFAULT : 0;
    969 #endif
    970 }
    971 
    972 /* Only difference to the fast-path function is that this can handle bit17
    973  * and uses non-atomic copy and kmap functions. */
    974 static int
    975 shmem_pwrite_slow(struct page *page, int shmem_page_offset, int page_length,
    976 		  char __user *user_data,
    977 		  bool page_do_bit17_swizzling,
    978 		  bool needs_clflush_before,
    979 		  bool needs_clflush_after)
    980 {
    981 	char *vaddr;
    982 	int ret;
    983 
    984 	vaddr = kmap(page);
    985 	if (unlikely(needs_clflush_before || page_do_bit17_swizzling))
    986 		shmem_clflush_swizzled_range(vaddr + shmem_page_offset,
    987 					     page_length,
    988 					     page_do_bit17_swizzling);
    989 	if (page_do_bit17_swizzling)
    990 		ret = __copy_from_user_swizzled(vaddr, shmem_page_offset,
    991 						user_data,
    992 						page_length);
    993 	else
    994 		ret = __copy_from_user(vaddr + shmem_page_offset,
    995 				       user_data,
    996 				       page_length);
    997 	if (needs_clflush_after)
    998 		shmem_clflush_swizzled_range(vaddr + shmem_page_offset,
    999 					     page_length,
   1000 					     page_do_bit17_swizzling);
   1001 	kunmap(page);
   1002 
   1003 	return ret ? -EFAULT : 0;
   1004 }
   1005 
   1006 static int
   1007 i915_gem_shmem_pwrite(struct drm_device *dev,
   1008 		      struct drm_i915_gem_object *obj,
   1009 		      struct drm_i915_gem_pwrite *args,
   1010 		      struct drm_file *file)
   1011 {
   1012 	ssize_t remain;
   1013 	loff_t offset;
   1014 	char __user *user_data;
   1015 	int shmem_page_offset, page_length, ret = 0;
   1016 	int obj_do_bit17_swizzling, page_do_bit17_swizzling;
   1017 	int hit_slowpath = 0;
   1018 	int needs_clflush_after = 0;
   1019 	int needs_clflush_before = 0;
   1020 #ifndef __NetBSD__
   1021 	struct sg_page_iter sg_iter;
   1022 	int flush_mask = boot_cpu_data.x86_clflush_size - 1;
   1023 #else
   1024 	int flush_mask = cpu_info_primary.ci_cflush_lsize - 1;
   1025 #endif
   1026 
   1027 	user_data = to_user_ptr(args->data_ptr);
   1028 	remain = args->size;
   1029 
   1030 	obj_do_bit17_swizzling = i915_gem_object_needs_bit17_swizzle(obj);
   1031 
   1032 	if (obj->base.write_domain != I915_GEM_DOMAIN_CPU) {
   1033 		/* If we're not in the cpu write domain, set ourself into the gtt
   1034 		 * write domain and manually flush cachelines (if required). This
   1035 		 * optimizes for the case when the gpu will use the data
   1036 		 * right away and we therefore have to clflush anyway. */
   1037 		needs_clflush_after = cpu_write_needs_clflush(obj);
   1038 		ret = i915_gem_object_wait_rendering(obj, false);
   1039 		if (ret)
   1040 			return ret;
   1041 	}
   1042 	/* Same trick applies to invalidate partially written cachelines read
   1043 	 * before writing. */
   1044 	if ((obj->base.read_domains & I915_GEM_DOMAIN_CPU) == 0)
   1045 		needs_clflush_before =
   1046 			!cpu_cache_is_coherent(dev, obj->cache_level);
   1047 
   1048 	ret = i915_gem_object_get_pages(obj);
   1049 	if (ret)
   1050 		return ret;
   1051 
   1052 	i915_gem_object_pin_pages(obj);
   1053 
   1054 	offset = args->offset;
   1055 	obj->dirty = 1;
   1056 
   1057 #ifdef __NetBSD__
   1058 	while (0 < remain)
   1059 #else
   1060 	for_each_sg_page(obj->pages->sgl, &sg_iter, obj->pages->nents,
   1061 			 offset >> PAGE_SHIFT)
   1062 #endif
   1063 	{
   1064 #ifdef __NetBSD__
   1065 		struct page *const page = i915_gem_object_get_page(obj,
   1066 		    atop(offset));
   1067 #else
   1068 		struct page *page = sg_page_iter_page(&sg_iter);
   1069 #endif
   1070 
   1071 		if (remain <= 0)
   1072 			break;
   1073 
   1074 		/* Operation in this page
   1075 		 *
   1076 		 * shmem_page_offset = offset within page in shmem file
   1077 		 * page_length = bytes to copy for this page
   1078 		 */
   1079 		shmem_page_offset = offset_in_page(offset);
   1080 
   1081 		page_length = remain;
   1082 		if ((shmem_page_offset + page_length) > PAGE_SIZE)
   1083 			page_length = PAGE_SIZE - shmem_page_offset;
   1084 
   1085 		/* If we don't overwrite a cacheline completely we need to be
   1086 		 * careful to have up-to-date data by first clflushing. Don't
   1087 		 * overcomplicate things and flush the entire patch. */
   1088 		const int partial_cacheline_write = needs_clflush_before &&
   1089 			((shmem_page_offset | page_length) & flush_mask);
   1090 
   1091 		page_do_bit17_swizzling = obj_do_bit17_swizzling &&
   1092 			(page_to_phys(page) & (1 << 17)) != 0;
   1093 
   1094 		ret = shmem_pwrite_fast(page, shmem_page_offset, page_length,
   1095 					user_data, page_do_bit17_swizzling,
   1096 					partial_cacheline_write,
   1097 					needs_clflush_after);
   1098 		if (ret == 0)
   1099 			goto next_page;
   1100 
   1101 		hit_slowpath = 1;
   1102 		mutex_unlock(&dev->struct_mutex);
   1103 		ret = shmem_pwrite_slow(page, shmem_page_offset, page_length,
   1104 					user_data, page_do_bit17_swizzling,
   1105 					partial_cacheline_write,
   1106 					needs_clflush_after);
   1107 
   1108 		mutex_lock(&dev->struct_mutex);
   1109 
   1110 		if (ret)
   1111 			goto out;
   1112 
   1113 next_page:
   1114 		remain -= page_length;
   1115 		user_data += page_length;
   1116 		offset += page_length;
   1117 	}
   1118 
   1119 out:
   1120 	i915_gem_object_unpin_pages(obj);
   1121 
   1122 	if (hit_slowpath) {
   1123 		/*
   1124 		 * Fixup: Flush cpu caches in case we didn't flush the dirty
   1125 		 * cachelines in-line while writing and the object moved
   1126 		 * out of the cpu write domain while we've dropped the lock.
   1127 		 */
   1128 		if (!needs_clflush_after &&
   1129 		    obj->base.write_domain != I915_GEM_DOMAIN_CPU) {
   1130 			if (i915_gem_clflush_object(obj, obj->pin_display))
   1131 				i915_gem_chipset_flush(dev);
   1132 		}
   1133 	}
   1134 
   1135 	if (needs_clflush_after)
   1136 		i915_gem_chipset_flush(dev);
   1137 
   1138 	return ret;
   1139 }
   1140 
   1141 /**
   1142  * Writes data to the object referenced by handle.
   1143  *
   1144  * On error, the contents of the buffer that were to be modified are undefined.
   1145  */
   1146 int
   1147 i915_gem_pwrite_ioctl(struct drm_device *dev, void *data,
   1148 		      struct drm_file *file)
   1149 {
   1150 	struct drm_i915_gem_pwrite *args = data;
   1151 	struct drm_gem_object *gobj;
   1152 	struct drm_i915_gem_object *obj;
   1153 	int ret;
   1154 
   1155 	if (args->size == 0)
   1156 		return 0;
   1157 
   1158 	if (!access_ok(VERIFY_READ,
   1159 		       to_user_ptr(args->data_ptr),
   1160 		       args->size))
   1161 		return -EFAULT;
   1162 
   1163 #ifndef __NetBSD__		/* XXX prefault */
   1164 	if (likely(!i915.prefault_disable)) {
   1165 		ret = fault_in_multipages_readable(to_user_ptr(args->data_ptr),
   1166 						   args->size);
   1167 		if (ret)
   1168 			return -EFAULT;
   1169 	}
   1170 #endif
   1171 
   1172 	ret = i915_mutex_lock_interruptible(dev);
   1173 	if (ret)
   1174 		return ret;
   1175 
   1176 	gobj = drm_gem_object_lookup(dev, file, args->handle);
   1177 	if (gobj == NULL) {
   1178 		ret = -ENOENT;
   1179 		goto unlock;
   1180 	}
   1181 	obj = to_intel_bo(gobj);
   1182 
   1183 	/* Bounds check destination. */
   1184 	if (args->offset > obj->base.size ||
   1185 	    args->size > obj->base.size - args->offset) {
   1186 		ret = -EINVAL;
   1187 		goto out;
   1188 	}
   1189 
   1190 	/* prime objects have no backing filp to GEM pread/pwrite
   1191 	 * pages from.
   1192 	 */
   1193 #ifdef __NetBSD__
   1194 	/* Also stolen objects.  */
   1195 	if (obj->base.gemo_shm_uao == NULL) {
   1196 		ret = -EINVAL;
   1197 		goto out;
   1198 	}
   1199 #else
   1200 	if (!obj->base.filp) {
   1201 		ret = -EINVAL;
   1202 		goto out;
   1203 	}
   1204 #endif
   1205 
   1206 	trace_i915_gem_object_pwrite(obj, args->offset, args->size);
   1207 
   1208 	ret = -EFAULT;
   1209 	/* We can only do the GTT pwrite on untiled buffers, as otherwise
   1210 	 * it would end up going through the fenced access, and we'll get
   1211 	 * different detiling behavior between reading and writing.
   1212 	 * pread/pwrite currently are reading and writing from the CPU
   1213 	 * perspective, requiring manual detiling by the client.
   1214 	 */
   1215 	if (obj->phys_handle) {
   1216 		ret = i915_gem_phys_pwrite(obj, args, file);
   1217 		goto out;
   1218 	}
   1219 
   1220 	if (obj->tiling_mode == I915_TILING_NONE &&
   1221 	    obj->base.write_domain != I915_GEM_DOMAIN_CPU &&
   1222 	    cpu_write_needs_clflush(obj)) {
   1223 		ret = i915_gem_gtt_pwrite_fast(dev, obj, args, file);
   1224 		/* Note that the gtt paths might fail with non-page-backed user
   1225 		 * pointers (e.g. gtt mappings when moving data between
   1226 		 * textures). Fallback to the shmem path in that case. */
   1227 	}
   1228 
   1229 	if (ret == -EFAULT || ret == -ENOSPC)
   1230 		ret = i915_gem_shmem_pwrite(dev, obj, args, file);
   1231 
   1232 out:
   1233 	drm_gem_object_unreference(&obj->base);
   1234 unlock:
   1235 	mutex_unlock(&dev->struct_mutex);
   1236 	return ret;
   1237 }
   1238 
   1239 int
   1240 i915_gem_check_wedge(struct i915_gpu_error *error,
   1241 		     bool interruptible)
   1242 {
   1243 	if (i915_reset_in_progress(error)) {
   1244 		/* Non-interruptible callers can't handle -EAGAIN, hence return
   1245 		 * -EIO unconditionally for these. */
   1246 		if (!interruptible)
   1247 			return -EIO;
   1248 
   1249 		/* Recovery complete, but the reset failed ... */
   1250 		if (i915_terminally_wedged(error))
   1251 			return -EIO;
   1252 
   1253 		return -EAGAIN;
   1254 	}
   1255 
   1256 	return 0;
   1257 }
   1258 
   1259 /*
   1260  * Compare seqno against outstanding lazy request. Emit a request if they are
   1261  * equal.
   1262  */
   1263 static int
   1264 i915_gem_check_olr(struct intel_ring_buffer *ring, u32 seqno)
   1265 {
   1266 	int ret;
   1267 
   1268 	BUG_ON(!mutex_is_locked(&ring->dev->struct_mutex));
   1269 
   1270 	ret = 0;
   1271 	if (seqno == ring->outstanding_lazy_seqno)
   1272 		ret = i915_add_request(ring, NULL);
   1273 
   1274 	return ret;
   1275 }
   1276 
   1277 #ifndef __NetBSD__
   1278 static void fake_irq(unsigned long data)
   1279 {
   1280 	wake_up_process((struct task_struct *)data);
   1281 }
   1282 #endif
   1283 
   1284 static bool missed_irq(struct drm_i915_private *dev_priv,
   1285 		       struct intel_ring_buffer *ring)
   1286 {
   1287 	return test_bit(ring->id, &dev_priv->gpu_error.missed_irq_rings);
   1288 }
   1289 
   1290 static bool can_wait_boost(struct drm_i915_file_private *file_priv)
   1291 {
   1292 	if (file_priv == NULL)
   1293 		return true;
   1294 
   1295 	return !atomic_xchg(&file_priv->rps_wait_boost, true);
   1296 }
   1297 
   1298 /**
   1299  * __wait_seqno - wait until execution of seqno has finished
   1300  * @ring: the ring expected to report seqno
   1301  * @seqno: duh!
   1302  * @reset_counter: reset sequence associated with the given seqno
   1303  * @interruptible: do an interruptible wait (normally yes)
   1304  * @timeout: in - how long to wait (NULL forever); out - how much time remaining
   1305  *
   1306  * Note: It is of utmost importance that the passed in seqno and reset_counter
   1307  * values have been read by the caller in an smp safe manner. Where read-side
   1308  * locks are involved, it is sufficient to read the reset_counter before
   1309  * unlocking the lock that protects the seqno. For lockless tricks, the
   1310  * reset_counter _must_ be read before, and an appropriate smp_rmb must be
   1311  * inserted.
   1312  *
   1313  * Returns 0 if the seqno was found within the alloted time. Else returns the
   1314  * errno with remaining time filled in timeout argument.
   1315  */
   1316 #ifdef __NetBSD__
   1317 static int
   1318 __wait_seqno(struct intel_ring_buffer *ring, u32 seqno, unsigned reset_counter,
   1319     bool interruptible, struct timespec *timeout,
   1320     struct drm_i915_file_private *file_priv)
   1321 {
   1322 	struct drm_device *dev = ring->dev;
   1323 	struct drm_i915_private *dev_priv = dev->dev_private;
   1324 	bool irq_test_in_progress;
   1325 	struct timespec before, after;
   1326 	int ticks;
   1327 	bool wedged;
   1328 	int ret;
   1329 
   1330 	irq_test_in_progress = (dev_priv->gpu_error.test_irq_rings &
   1331 	    intel_ring_flag(ring));
   1332 	__insn_barrier();
   1333 
   1334 	if (i915_seqno_passed(ring->get_seqno(ring, true), seqno))
   1335 		return 0;
   1336 
   1337 	if (timeout)
   1338 		ticks = mstohz(timespec_to_ns(timeout) / 1000000);
   1339 	else
   1340 		ticks = 1;
   1341 
   1342 	if (INTEL_INFO(dev)->gen >= 6 && can_wait_boost(file_priv)) {
   1343 		gen6_rps_boost(dev_priv);
   1344 		if (file_priv)
   1345 			mod_delayed_work(dev_priv->wq,
   1346 					 &file_priv->mm.idle_work,
   1347 					 msecs_to_jiffies(100));
   1348 	}
   1349 
   1350 	if (!irq_test_in_progress && WARN_ON(!ring->irq_get(ring)))
   1351 		return -ENODEV;
   1352 
   1353 	nanotime(&before);
   1354 	spin_lock(&dev_priv->irq_lock);
   1355 #define	EXIT_COND							      \
   1356 	((wedged = (reset_counter !=					      \
   1357 		atomic_read(&dev_priv->gpu_error.reset_counter))) ||	      \
   1358 	    i915_seqno_passed(ring->get_seqno(ring, false),		      \
   1359 		seqno))
   1360 
   1361 	if (timeout) {
   1362 		/*
   1363 		 * XXX This missed_irq business smells like unlocked
   1364 		 * Linux waitqueue nonsense.
   1365 		 */
   1366 		if (missed_irq(dev_priv, ring))
   1367 			ticks = 1;
   1368 		if (interruptible)
   1369 			DRM_SPIN_TIMED_WAIT_UNTIL(ret, &ring->irq_queue,
   1370 			    &dev_priv->irq_lock, ticks, EXIT_COND);
   1371 		else
   1372 			DRM_SPIN_TIMED_WAIT_NOINTR_UNTIL(ret, &ring->irq_queue,
   1373 			    &dev_priv->irq_lock, ticks, EXIT_COND);
   1374 		if (ret < 0)	/* Failure: return negative error as is.  */
   1375 			;
   1376 		else if (ret == 0) /* Timed out: return -ETIME.  */
   1377 			ret = -ETIME;
   1378 		else		/* Succeeded (ret > 0): return 0.  */
   1379 			ret = 0;
   1380 	} else {
   1381 		if (interruptible)
   1382 			DRM_SPIN_WAIT_UNTIL(ret, &ring->irq_queue,
   1383 			    &dev_priv->irq_lock, EXIT_COND);
   1384 		else
   1385 			DRM_SPIN_WAIT_NOINTR_UNTIL(ret, &ring->irq_queue,
   1386 			    &dev_priv->irq_lock, EXIT_COND);
   1387 		/* ret is negative on failure or zero on success.  */
   1388 	}
   1389 #undef	EXIT_COND
   1390 	spin_unlock(&dev_priv->irq_lock);
   1391 	nanotime(&after);
   1392 
   1393 	if (!irq_test_in_progress)
   1394 		ring->irq_put(ring);
   1395 	if (timeout) {
   1396 		struct timespec slept;
   1397 
   1398 		/* Compute slept = after - before.  */
   1399 		timespecsub(&after, &before, &slept);
   1400 
   1401 		/*
   1402 		 * Return the time remaining, timeout - slept, if we
   1403 		 * slept for less time than the timeout; or zero if we
   1404 		 * timed out.
   1405 		 */
   1406 		if (timespeccmp(&slept, timeout, <))
   1407 			timespecsub(timeout, &slept, timeout);
   1408 		else
   1409 			timespecclear(timeout);
   1410 	}
   1411 	if (wedged) {		/* GPU reset while we were waiting.  */
   1412 		ret = i915_gem_check_wedge(&dev_priv->gpu_error,
   1413 		    interruptible);
   1414 		if (ret == 0)
   1415 			ret = -EAGAIN;
   1416 	}
   1417 	return ret;
   1418 }
   1419 #else
   1420 static int __wait_seqno(struct intel_ring_buffer *ring, u32 seqno,
   1421 			unsigned reset_counter,
   1422 			bool interruptible,
   1423 			struct timespec *timeout,
   1424 			struct drm_i915_file_private *file_priv)
   1425 {
   1426 	struct drm_device *dev = ring->dev;
   1427 	struct drm_i915_private *dev_priv = dev->dev_private;
   1428 	const bool irq_test_in_progress =
   1429 		ACCESS_ONCE(dev_priv->gpu_error.test_irq_rings) & intel_ring_flag(ring);
   1430 	struct timespec before, now;
   1431 	DEFINE_WAIT(wait);
   1432 	unsigned long timeout_expire;
   1433 	int ret;
   1434 
   1435 	WARN(dev_priv->pm.irqs_disabled, "IRQs disabled\n");
   1436 
   1437 	if (i915_seqno_passed(ring->get_seqno(ring, true), seqno))
   1438 		return 0;
   1439 
   1440 	timeout_expire = timeout ? jiffies + timespec_to_jiffies_timeout(timeout) : 0;
   1441 
   1442 	if (INTEL_INFO(dev)->gen >= 6 && can_wait_boost(file_priv)) {
   1443 		gen6_rps_boost(dev_priv);
   1444 		if (file_priv)
   1445 			mod_delayed_work(dev_priv->wq,
   1446 					 &file_priv->mm.idle_work,
   1447 					 msecs_to_jiffies(100));
   1448 	}
   1449 
   1450 	if (!irq_test_in_progress && WARN_ON(!ring->irq_get(ring)))
   1451 		return -ENODEV;
   1452 
   1453 	/* Record current time in case interrupted by signal, or wedged */
   1454 	trace_i915_gem_request_wait_begin(ring, seqno);
   1455 	getrawmonotonic(&before);
   1456 	for (;;) {
   1457 		struct timer_list timer;
   1458 
   1459 		prepare_to_wait(&ring->irq_queue, &wait,
   1460 				interruptible ? TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE);
   1461 
   1462 		/* We need to check whether any gpu reset happened in between
   1463 		 * the caller grabbing the seqno and now ... */
   1464 		if (reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter)) {
   1465 			/* ... but upgrade the -EAGAIN to an -EIO if the gpu
   1466 			 * is truely gone. */
   1467 			ret = i915_gem_check_wedge(&dev_priv->gpu_error, interruptible);
   1468 			if (ret == 0)
   1469 				ret = -EAGAIN;
   1470 			break;
   1471 		}
   1472 
   1473 		if (i915_seqno_passed(ring->get_seqno(ring, false), seqno)) {
   1474 			ret = 0;
   1475 			break;
   1476 		}
   1477 
   1478 		if (interruptible && signal_pending(current)) {
   1479 			ret = -ERESTARTSYS;
   1480 			break;
   1481 		}
   1482 
   1483 		if (timeout && time_after_eq(jiffies, timeout_expire)) {
   1484 			ret = -ETIME;
   1485 			break;
   1486 		}
   1487 
   1488 		timer.function = NULL;
   1489 		if (timeout || missed_irq(dev_priv, ring)) {
   1490 			unsigned long expire;
   1491 
   1492 			setup_timer_on_stack(&timer, fake_irq, (unsigned long)current);
   1493 			expire = missed_irq(dev_priv, ring) ? jiffies + 1 : timeout_expire;
   1494 			mod_timer(&timer, expire);
   1495 		}
   1496 
   1497 		io_schedule();
   1498 
   1499 		if (timer.function) {
   1500 			del_singleshot_timer_sync(&timer);
   1501 			destroy_timer_on_stack(&timer);
   1502 		}
   1503 	}
   1504 	getrawmonotonic(&now);
   1505 	trace_i915_gem_request_wait_end(ring, seqno);
   1506 
   1507 	if (!irq_test_in_progress)
   1508 		ring->irq_put(ring);
   1509 
   1510 	finish_wait(&ring->irq_queue, &wait);
   1511 
   1512 	if (timeout) {
   1513 		struct timespec sleep_time = timespec_sub(now, before);
   1514 		*timeout = timespec_sub(*timeout, sleep_time);
   1515 		if (!timespec_valid(timeout)) /* i.e. negative time remains */
   1516 			set_normalized_timespec(timeout, 0, 0);
   1517 	}
   1518 
   1519 	return ret;
   1520 }
   1521 #endif
   1522 
   1523 /**
   1524  * Waits for a sequence number to be signaled, and cleans up the
   1525  * request and object lists appropriately for that event.
   1526  */
   1527 int
   1528 i915_wait_seqno(struct intel_ring_buffer *ring, uint32_t seqno)
   1529 {
   1530 	struct drm_device *dev = ring->dev;
   1531 	struct drm_i915_private *dev_priv = dev->dev_private;
   1532 	bool interruptible = dev_priv->mm.interruptible;
   1533 	int ret;
   1534 
   1535 	BUG_ON(!mutex_is_locked(&dev->struct_mutex));
   1536 	BUG_ON(seqno == 0);
   1537 
   1538 	ret = i915_gem_check_wedge(&dev_priv->gpu_error, interruptible);
   1539 	if (ret)
   1540 		return ret;
   1541 
   1542 	ret = i915_gem_check_olr(ring, seqno);
   1543 	if (ret)
   1544 		return ret;
   1545 
   1546 	return __wait_seqno(ring, seqno,
   1547 			    atomic_read(&dev_priv->gpu_error.reset_counter),
   1548 			    interruptible, NULL, NULL);
   1549 }
   1550 
   1551 static int
   1552 i915_gem_object_wait_rendering__tail(struct drm_i915_gem_object *obj,
   1553 				     struct intel_ring_buffer *ring)
   1554 {
   1555 	i915_gem_retire_requests_ring(ring);
   1556 
   1557 	/* Manually manage the write flush as we may have not yet
   1558 	 * retired the buffer.
   1559 	 *
   1560 	 * Note that the last_write_seqno is always the earlier of
   1561 	 * the two (read/write) seqno, so if we haved successfully waited,
   1562 	 * we know we have passed the last write.
   1563 	 */
   1564 	obj->last_write_seqno = 0;
   1565 	obj->base.write_domain &= ~I915_GEM_GPU_DOMAINS;
   1566 
   1567 	return 0;
   1568 }
   1569 
   1570 /**
   1571  * Ensures that all rendering to the object has completed and the object is
   1572  * safe to unbind from the GTT or access from the CPU.
   1573  */
   1574 static __must_check int
   1575 i915_gem_object_wait_rendering(struct drm_i915_gem_object *obj,
   1576 			       bool readonly)
   1577 {
   1578 	struct intel_ring_buffer *ring = obj->ring;
   1579 	u32 seqno;
   1580 	int ret;
   1581 
   1582 	seqno = readonly ? obj->last_write_seqno : obj->last_read_seqno;
   1583 	if (seqno == 0)
   1584 		return 0;
   1585 
   1586 	ret = i915_wait_seqno(ring, seqno);
   1587 	if (ret)
   1588 		return ret;
   1589 
   1590 	return i915_gem_object_wait_rendering__tail(obj, ring);
   1591 }
   1592 
   1593 /* A nonblocking variant of the above wait. This is a highly dangerous routine
   1594  * as the object state may change during this call.
   1595  */
   1596 static __must_check int
   1597 i915_gem_object_wait_rendering__nonblocking(struct drm_i915_gem_object *obj,
   1598 					    struct drm_i915_file_private *file_priv,
   1599 					    bool readonly)
   1600 {
   1601 	struct drm_device *dev = obj->base.dev;
   1602 	struct drm_i915_private *dev_priv = dev->dev_private;
   1603 	struct intel_ring_buffer *ring = obj->ring;
   1604 	unsigned reset_counter;
   1605 	u32 seqno;
   1606 	int ret;
   1607 
   1608 	BUG_ON(!mutex_is_locked(&dev->struct_mutex));
   1609 	BUG_ON(!dev_priv->mm.interruptible);
   1610 
   1611 	seqno = readonly ? obj->last_write_seqno : obj->last_read_seqno;
   1612 	if (seqno == 0)
   1613 		return 0;
   1614 
   1615 	ret = i915_gem_check_wedge(&dev_priv->gpu_error, true);
   1616 	if (ret)
   1617 		return ret;
   1618 
   1619 	ret = i915_gem_check_olr(ring, seqno);
   1620 	if (ret)
   1621 		return ret;
   1622 
   1623 	reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
   1624 	mutex_unlock(&dev->struct_mutex);
   1625 	ret = __wait_seqno(ring, seqno, reset_counter, true, NULL, file_priv);
   1626 	mutex_lock(&dev->struct_mutex);
   1627 	if (ret)
   1628 		return ret;
   1629 
   1630 	return i915_gem_object_wait_rendering__tail(obj, ring);
   1631 }
   1632 
   1633 /**
   1634  * Called when user space prepares to use an object with the CPU, either
   1635  * through the mmap ioctl's mapping or a GTT mapping.
   1636  */
   1637 int
   1638 i915_gem_set_domain_ioctl(struct drm_device *dev, void *data,
   1639 			  struct drm_file *file)
   1640 {
   1641 	struct drm_i915_gem_set_domain *args = data;
   1642 	struct drm_gem_object *gobj;
   1643 	struct drm_i915_gem_object *obj;
   1644 	uint32_t read_domains = args->read_domains;
   1645 	uint32_t write_domain = args->write_domain;
   1646 	int ret;
   1647 
   1648 	/* Only handle setting domains to types used by the CPU. */
   1649 	if (write_domain & I915_GEM_GPU_DOMAINS)
   1650 		return -EINVAL;
   1651 
   1652 	if (read_domains & I915_GEM_GPU_DOMAINS)
   1653 		return -EINVAL;
   1654 
   1655 	/* Having something in the write domain implies it's in the read
   1656 	 * domain, and only that read domain.  Enforce that in the request.
   1657 	 */
   1658 	if (write_domain != 0 && read_domains != write_domain)
   1659 		return -EINVAL;
   1660 
   1661 	ret = i915_mutex_lock_interruptible(dev);
   1662 	if (ret)
   1663 		return ret;
   1664 
   1665 	gobj = drm_gem_object_lookup(dev, file, args->handle);
   1666 	if (gobj == NULL) {
   1667 		ret = -ENOENT;
   1668 		goto unlock;
   1669 	}
   1670 	obj = to_intel_bo(gobj);
   1671 
   1672 	/* Try to flush the object off the GPU without holding the lock.
   1673 	 * We will repeat the flush holding the lock in the normal manner
   1674 	 * to catch cases where we are gazumped.
   1675 	 */
   1676 	ret = i915_gem_object_wait_rendering__nonblocking(obj,
   1677 							  file->driver_priv,
   1678 							  !write_domain);
   1679 	if (ret)
   1680 		goto unref;
   1681 
   1682 	if (read_domains & I915_GEM_DOMAIN_GTT) {
   1683 		ret = i915_gem_object_set_to_gtt_domain(obj, write_domain != 0);
   1684 
   1685 		/* Silently promote "you're not bound, there was nothing to do"
   1686 		 * to success, since the client was just asking us to
   1687 		 * make sure everything was done.
   1688 		 */
   1689 		if (ret == -EINVAL)
   1690 			ret = 0;
   1691 	} else {
   1692 		ret = i915_gem_object_set_to_cpu_domain(obj, write_domain != 0);
   1693 	}
   1694 
   1695 unref:
   1696 	drm_gem_object_unreference(&obj->base);
   1697 unlock:
   1698 	mutex_unlock(&dev->struct_mutex);
   1699 	return ret;
   1700 }
   1701 
   1702 /**
   1703  * Called when user space has done writes to this buffer
   1704  */
   1705 int
   1706 i915_gem_sw_finish_ioctl(struct drm_device *dev, void *data,
   1707 			 struct drm_file *file)
   1708 {
   1709 	struct drm_i915_gem_sw_finish *args = data;
   1710 	struct drm_gem_object *gobj;
   1711 	struct drm_i915_gem_object *obj;
   1712 	int ret = 0;
   1713 
   1714 	ret = i915_mutex_lock_interruptible(dev);
   1715 	if (ret)
   1716 		return ret;
   1717 
   1718 	gobj = drm_gem_object_lookup(dev, file, args->handle);
   1719 	if (gobj == NULL) {
   1720 		ret = -ENOENT;
   1721 		goto unlock;
   1722 	}
   1723 	obj = to_intel_bo(gobj);
   1724 
   1725 	/* Pinned buffers may be scanout, so flush the cache */
   1726 	if (obj->pin_display)
   1727 		i915_gem_object_flush_cpu_write_domain(obj, true);
   1728 
   1729 	drm_gem_object_unreference(&obj->base);
   1730 unlock:
   1731 	mutex_unlock(&dev->struct_mutex);
   1732 	return ret;
   1733 }
   1734 
   1735 /**
   1736  * Maps the contents of an object, returning the address it is mapped
   1737  * into.
   1738  *
   1739  * While the mapping holds a reference on the contents of the object, it doesn't
   1740  * imply a ref on the object itself.
   1741  */
   1742 int
   1743 i915_gem_mmap_ioctl(struct drm_device *dev, void *data,
   1744 		    struct drm_file *file)
   1745 {
   1746 	struct drm_i915_gem_mmap *args = data;
   1747 	struct drm_gem_object *obj;
   1748 	unsigned long addr;
   1749 #ifdef __NetBSD__
   1750 	int ret;
   1751 #endif
   1752 
   1753 	obj = drm_gem_object_lookup(dev, file, args->handle);
   1754 	if (obj == NULL)
   1755 		return -ENOENT;
   1756 
   1757 	/* prime objects have no backing filp to GEM mmap
   1758 	 * pages from.
   1759 	 */
   1760 #ifdef __NetBSD__
   1761 	/* Also stolen objects (XXX can we get them here?)  */
   1762 	if (obj->gemo_shm_uao == NULL) {
   1763 		drm_gem_object_unreference_unlocked(obj);
   1764 		return -EINVAL;
   1765 	}
   1766 #else
   1767 	if (!obj->filp) {
   1768 		drm_gem_object_unreference_unlocked(obj);
   1769 		return -EINVAL;
   1770 	}
   1771 #endif
   1772 
   1773 #ifdef __NetBSD__
   1774 	addr = (*curproc->p_emul->e_vm_default_addr)(curproc,
   1775 	    (vaddr_t)curproc->p_vmspace->vm_daddr, args->size);
   1776 	/* XXX errno NetBSD->Linux */
   1777 	ret = -uvm_map(&curproc->p_vmspace->vm_map, &addr, args->size,
   1778 	    obj->gemo_shm_uao, args->offset, 0,
   1779 	    UVM_MAPFLAG((VM_PROT_READ | VM_PROT_WRITE),
   1780 		(VM_PROT_READ | VM_PROT_WRITE), UVM_INH_COPY, UVM_ADV_NORMAL,
   1781 		0));
   1782 	if (ret) {
   1783 		drm_gem_object_unreference_unlocked(obj);
   1784 		return ret;
   1785 	}
   1786 	uao_reference(obj->gemo_shm_uao);
   1787 	drm_gem_object_unreference_unlocked(obj);
   1788 #else
   1789 	addr = vm_mmap(obj->filp, 0, args->size,
   1790 		       PROT_READ | PROT_WRITE, MAP_SHARED,
   1791 		       args->offset);
   1792 	drm_gem_object_unreference_unlocked(obj);
   1793 	if (IS_ERR((void *)addr))
   1794 		return addr;
   1795 #endif
   1796 
   1797 	args->addr_ptr = (uint64_t) addr;
   1798 
   1799 	return 0;
   1800 }
   1801 
   1802 #ifdef __NetBSD__		/* XXX gem gtt fault */
   1803 static int	i915_udv_fault(struct uvm_faultinfo *, vaddr_t,
   1804 		    struct vm_page **, int, int, vm_prot_t, int, paddr_t);
   1805 
   1806 int
   1807 i915_gem_fault(struct uvm_faultinfo *ufi, vaddr_t vaddr, struct vm_page **pps,
   1808     int npages, int centeridx, vm_prot_t access_type, int flags)
   1809 {
   1810 	struct uvm_object *uobj = ufi->entry->object.uvm_obj;
   1811 	struct drm_gem_object *gem_obj =
   1812 	    container_of(uobj, struct drm_gem_object, gemo_uvmobj);
   1813 	struct drm_i915_gem_object *obj = to_intel_bo(gem_obj);
   1814 	struct drm_device *dev = obj->base.dev;
   1815 	struct drm_i915_private *dev_priv = dev->dev_private;
   1816 	voff_t byte_offset;
   1817 	pgoff_t page_offset;
   1818 	int ret = 0;
   1819 	bool write = ISSET(access_type, VM_PROT_WRITE)? 1 : 0;
   1820 
   1821 	byte_offset = (ufi->entry->offset + (vaddr - ufi->entry->start));
   1822 	KASSERT(byte_offset <= obj->base.size);
   1823 	page_offset = (byte_offset >> PAGE_SHIFT);
   1824 
   1825 	intel_runtime_pm_get(dev_priv);
   1826 
   1827 	/* Thanks, uvm, but we don't need this lock.  */
   1828 	mutex_exit(uobj->vmobjlock);
   1829 
   1830 	ret = i915_mutex_lock_interruptible(dev);
   1831 	if (ret)
   1832 		goto out;
   1833 
   1834 	trace_i915_gem_object_fault(obj, page_offset, true, write);
   1835 
   1836 	ret = i915_gem_object_wait_rendering__nonblocking(obj, NULL, !write);
   1837 	if (ret)
   1838 		goto unlock;
   1839 
   1840 	if ((obj->cache_level != I915_CACHE_NONE) && !HAS_LLC(dev)) {
   1841 		ret = -EINVAL;
   1842 		goto unlock;
   1843 	}
   1844 
   1845 	ret = i915_gem_obj_ggtt_pin(obj, 0, PIN_MAPPABLE);
   1846 	if (ret)
   1847 		goto unlock;
   1848 
   1849 	ret = i915_gem_object_set_to_gtt_domain(obj, write);
   1850 	if (ret)
   1851 		goto unpin;
   1852 
   1853 	ret = i915_gem_object_get_fence(obj);
   1854 	if (ret)
   1855 		goto unpin;
   1856 
   1857 	obj->fault_mappable = true;
   1858 
   1859 	/* XXX errno NetBSD->Linux */
   1860 	ret = -i915_udv_fault(ufi, vaddr, pps, npages, centeridx, access_type,
   1861 	    flags,
   1862 	    (dev_priv->gtt.mappable_base + i915_gem_obj_ggtt_offset(obj)));
   1863 unpin:
   1864 	i915_gem_object_ggtt_unpin(obj);
   1865 unlock:
   1866 	mutex_unlock(&dev->struct_mutex);
   1867 out:
   1868 	mutex_enter(uobj->vmobjlock);
   1869 	uvmfault_unlockall(ufi, ufi->entry->aref.ar_amap, uobj);
   1870 	if (ret == -ERESTART)
   1871 		uvm_wait("i915flt");
   1872 	/* XXX Deal with GPU hangs here...  */
   1873 	intel_runtime_pm_put(dev_priv);
   1874 	/* XXX errno Linux->NetBSD */
   1875 	return -ret;
   1876 }
   1877 
   1878 /*
   1879  * XXX i915_udv_fault is copypasta of udv_fault from uvm_device.c.
   1880  *
   1881  * XXX pmap_enter_default instead of pmap_enter because of a problem
   1882  * with using weak aliases in kernel modules or something.
   1883  */
   1884 int	pmap_enter_default(pmap_t, vaddr_t, paddr_t, vm_prot_t, unsigned);
   1885 
   1886 static int
   1887 i915_udv_fault(struct uvm_faultinfo *ufi, vaddr_t vaddr, struct vm_page **pps,
   1888     int npages, int centeridx, vm_prot_t access_type, int flags,
   1889     paddr_t gtt_paddr)
   1890 {
   1891 	struct vm_map_entry *entry = ufi->entry;
   1892 	vaddr_t curr_va;
   1893 	off_t curr_offset;
   1894 	paddr_t paddr;
   1895 	u_int mmapflags;
   1896 	int lcv, retval;
   1897 	vm_prot_t mapprot;
   1898 	UVMHIST_FUNC("i915_udv_fault"); UVMHIST_CALLED(maphist);
   1899 	UVMHIST_LOG(maphist,"  flags=%d", flags,0,0,0);
   1900 
   1901 	/*
   1902 	 * we do not allow device mappings to be mapped copy-on-write
   1903 	 * so we kill any attempt to do so here.
   1904 	 */
   1905 
   1906 	if (UVM_ET_ISCOPYONWRITE(entry)) {
   1907 		UVMHIST_LOG(maphist, "<- failed -- COW entry (etype=0x%x)",
   1908 		entry->etype, 0,0,0);
   1909 		return(EIO);
   1910 	}
   1911 
   1912 	/*
   1913 	 * now we must determine the offset in udv to use and the VA to
   1914 	 * use for pmap_enter.  note that we always use orig_map's pmap
   1915 	 * for pmap_enter (even if we have a submap).   since virtual
   1916 	 * addresses in a submap must match the main map, this is ok.
   1917 	 */
   1918 
   1919 	/* udv offset = (offset from start of entry) + entry's offset */
   1920 	curr_offset = entry->offset + (vaddr - entry->start);
   1921 	/* pmap va = vaddr (virtual address of pps[0]) */
   1922 	curr_va = vaddr;
   1923 
   1924 	/*
   1925 	 * loop over the page range entering in as needed
   1926 	 */
   1927 
   1928 	retval = 0;
   1929 	for (lcv = 0 ; lcv < npages ; lcv++, curr_offset += PAGE_SIZE,
   1930 	    curr_va += PAGE_SIZE) {
   1931 		if ((flags & PGO_ALLPAGES) == 0 && lcv != centeridx)
   1932 			continue;
   1933 
   1934 		if (pps[lcv] == PGO_DONTCARE)
   1935 			continue;
   1936 
   1937 		paddr = (gtt_paddr + curr_offset);
   1938 		mmapflags = 0;
   1939 		mapprot = ufi->entry->protection;
   1940 		UVMHIST_LOG(maphist,
   1941 		    "  MAPPING: device: pm=0x%x, va=0x%x, pa=0x%lx, at=%d",
   1942 		    ufi->orig_map->pmap, curr_va, paddr, mapprot);
   1943 		if (pmap_enter_default(ufi->orig_map->pmap, curr_va, paddr, mapprot,
   1944 		    PMAP_CANFAIL | mapprot | mmapflags) != 0) {
   1945 			/*
   1946 			 * pmap_enter() didn't have the resource to
   1947 			 * enter this mapping.  Unlock everything,
   1948 			 * wait for the pagedaemon to free up some
   1949 			 * pages, and then tell uvm_fault() to start
   1950 			 * the fault again.
   1951 			 *
   1952 			 * XXX Needs some rethinking for the PGO_ALLPAGES
   1953 			 * XXX case.
   1954 			 */
   1955 			pmap_update(ufi->orig_map->pmap);	/* sync what we have so far */
   1956 			return (ERESTART);
   1957 		}
   1958 	}
   1959 
   1960 	pmap_update(ufi->orig_map->pmap);
   1961 	return (retval);
   1962 }
   1963 #else
   1964 /**
   1965  * i915_gem_fault - fault a page into the GTT
   1966  * vma: VMA in question
   1967  * vmf: fault info
   1968  *
   1969  * The fault handler is set up by drm_gem_mmap() when a object is GTT mapped
   1970  * from userspace.  The fault handler takes care of binding the object to
   1971  * the GTT (if needed), allocating and programming a fence register (again,
   1972  * only if needed based on whether the old reg is still valid or the object
   1973  * is tiled) and inserting a new PTE into the faulting process.
   1974  *
   1975  * Note that the faulting process may involve evicting existing objects
   1976  * from the GTT and/or fence registers to make room.  So performance may
   1977  * suffer if the GTT working set is large or there are few fence registers
   1978  * left.
   1979  */
   1980 int i915_gem_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
   1981 {
   1982 	struct drm_i915_gem_object *obj = to_intel_bo(vma->vm_private_data);
   1983 	struct drm_device *dev = obj->base.dev;
   1984 	struct drm_i915_private *dev_priv = dev->dev_private;
   1985 	pgoff_t page_offset;
   1986 	unsigned long pfn;
   1987 	int ret = 0;
   1988 	bool write = !!(vmf->flags & FAULT_FLAG_WRITE);
   1989 
   1990 	intel_runtime_pm_get(dev_priv);
   1991 
   1992 	/* We don't use vmf->pgoff since that has the fake offset */
   1993 	page_offset = ((unsigned long)vmf->virtual_address - vma->vm_start) >>
   1994 		PAGE_SHIFT;
   1995 
   1996 	ret = i915_mutex_lock_interruptible(dev);
   1997 	if (ret)
   1998 		goto out;
   1999 
   2000 	trace_i915_gem_object_fault(obj, page_offset, true, write);
   2001 
   2002 	/* Try to flush the object off the GPU first without holding the lock.
   2003 	 * Upon reacquiring the lock, we will perform our sanity checks and then
   2004 	 * repeat the flush holding the lock in the normal manner to catch cases
   2005 	 * where we are gazumped.
   2006 	 */
   2007 	ret = i915_gem_object_wait_rendering__nonblocking(obj, NULL, !write);
   2008 	if (ret)
   2009 		goto unlock;
   2010 
   2011 	/* Access to snoopable pages through the GTT is incoherent. */
   2012 	if (obj->cache_level != I915_CACHE_NONE && !HAS_LLC(dev)) {
   2013 		ret = -EINVAL;
   2014 		goto unlock;
   2015 	}
   2016 
   2017 	/* Now bind it into the GTT if needed */
   2018 	ret = i915_gem_obj_ggtt_pin(obj, 0, PIN_MAPPABLE);
   2019 	if (ret)
   2020 		goto unlock;
   2021 
   2022 	ret = i915_gem_object_set_to_gtt_domain(obj, write);
   2023 	if (ret)
   2024 		goto unpin;
   2025 
   2026 	ret = i915_gem_object_get_fence(obj);
   2027 	if (ret)
   2028 		goto unpin;
   2029 
   2030 	obj->fault_mappable = true;
   2031 
   2032 	pfn = dev_priv->gtt.mappable_base + i915_gem_obj_ggtt_offset(obj);
   2033 	pfn >>= PAGE_SHIFT;
   2034 	pfn += page_offset;
   2035 
   2036 	/* Finally, remap it using the new GTT offset */
   2037 	ret = vm_insert_pfn(vma, (unsigned long)vmf->virtual_address, pfn);
   2038 unpin:
   2039 	i915_gem_object_ggtt_unpin(obj);
   2040 unlock:
   2041 	mutex_unlock(&dev->struct_mutex);
   2042 out:
   2043 	switch (ret) {
   2044 	case -EIO:
   2045 		/* If this -EIO is due to a gpu hang, give the reset code a
   2046 		 * chance to clean up the mess. Otherwise return the proper
   2047 		 * SIGBUS. */
   2048 		if (i915_terminally_wedged(&dev_priv->gpu_error)) {
   2049 			ret = VM_FAULT_SIGBUS;
   2050 			break;
   2051 		}
   2052 	case -EAGAIN:
   2053 		/*
   2054 		 * EAGAIN means the gpu is hung and we'll wait for the error
   2055 		 * handler to reset everything when re-faulting in
   2056 		 * i915_mutex_lock_interruptible.
   2057 		 */
   2058 	case 0:
   2059 	case -ERESTARTSYS:
   2060 	case -EINTR:
   2061 	case -EBUSY:
   2062 		/*
   2063 		 * EBUSY is ok: this just means that another thread
   2064 		 * already did the job.
   2065 		 */
   2066 		ret = VM_FAULT_NOPAGE;
   2067 		break;
   2068 	case -ENOMEM:
   2069 		ret = VM_FAULT_OOM;
   2070 		break;
   2071 	case -ENOSPC:
   2072 	case -EFAULT:
   2073 		ret = VM_FAULT_SIGBUS;
   2074 		break;
   2075 	default:
   2076 		WARN_ONCE(ret, "unhandled error in i915_gem_fault: %i\n", ret);
   2077 		ret = VM_FAULT_SIGBUS;
   2078 		break;
   2079 	}
   2080 
   2081 	intel_runtime_pm_put(dev_priv);
   2082 	return ret;
   2083 }
   2084 
   2085 void i915_gem_release_all_mmaps(struct drm_i915_private *dev_priv)
   2086 {
   2087 	struct i915_vma *vma;
   2088 
   2089 	/*
   2090 	 * Only the global gtt is relevant for gtt memory mappings, so restrict
   2091 	 * list traversal to objects bound into the global address space. Note
   2092 	 * that the active list should be empty, but better safe than sorry.
   2093 	 */
   2094 	WARN_ON(!list_empty(&dev_priv->gtt.base.active_list));
   2095 	list_for_each_entry(vma, &dev_priv->gtt.base.active_list, mm_list)
   2096 		i915_gem_release_mmap(vma->obj);
   2097 	list_for_each_entry(vma, &dev_priv->gtt.base.inactive_list, mm_list)
   2098 		i915_gem_release_mmap(vma->obj);
   2099 }
   2100 #endif
   2101 
   2102 /**
   2103  * i915_gem_release_mmap - remove physical page mappings
   2104  * @obj: obj in question
   2105  *
   2106  * Preserve the reservation of the mmapping with the DRM core code, but
   2107  * relinquish ownership of the pages back to the system.
   2108  *
   2109  * It is vital that we remove the page mapping if we have mapped a tiled
   2110  * object through the GTT and then lose the fence register due to
   2111  * resource pressure. Similarly if the object has been moved out of the
   2112  * aperture, than pages mapped into userspace must be revoked. Removing the
   2113  * mapping will then trigger a page fault on the next user access, allowing
   2114  * fixup by i915_gem_fault().
   2115  */
   2116 void
   2117 i915_gem_release_mmap(struct drm_i915_gem_object *obj)
   2118 {
   2119 	if (!obj->fault_mappable)
   2120 		return;
   2121 
   2122 #ifdef __NetBSD__		/* XXX gem gtt fault */
   2123 	{
   2124 		struct vm_page *page;
   2125 
   2126 		mutex_enter(obj->base.gemo_shm_uao->vmobjlock);
   2127 		KASSERT(obj->pages != NULL);
   2128 		/* Force a fresh fault for each page.  */
   2129 		/*
   2130 		 * XXX OOPS!  This doesn't actually do what we want.
   2131 		 * This causes a fresh fault for access to the backing
   2132 		 * pages -- but nothing accesses the backing pages
   2133 		 * directly!  What is actually entered into CPU page
   2134 		 * table entries is aperture addresses which have been
   2135 		 * programmed by the GTT to refer to those backing
   2136 		 * pages.
   2137 		 *
   2138 		 * We need to clear those page table entries, but
   2139 		 * there's no good way to do that at the moment: nobody
   2140 		 * records for us a map from either uvm objects or
   2141 		 * physical device addresses to a list of all virtual
   2142 		 * pages where they have been mapped.  pmap(9) records
   2143 		 * a map only from physical RAM addresses to virtual
   2144 		 * pages; it does nothing for physical device
   2145 		 * addresses.
   2146 		 */
   2147 		TAILQ_FOREACH(page, &obj->igo_pageq, pageq.queue)
   2148 			pmap_page_protect(page, VM_PROT_NONE);
   2149 		mutex_exit(obj->base.gemo_shm_uao->vmobjlock);
   2150 	}
   2151 #else
   2152 	drm_vma_node_unmap(&obj->base.vma_node,
   2153 			   obj->base.dev->anon_inode->i_mapping);
   2154 #endif
   2155 	obj->fault_mappable = false;
   2156 }
   2157 
   2158 uint32_t
   2159 i915_gem_get_gtt_size(struct drm_device *dev, uint32_t size, int tiling_mode)
   2160 {
   2161 	uint32_t gtt_size;
   2162 
   2163 	if (INTEL_INFO(dev)->gen >= 4 ||
   2164 	    tiling_mode == I915_TILING_NONE)
   2165 		return size;
   2166 
   2167 	/* Previous chips need a power-of-two fence region when tiling */
   2168 	if (INTEL_INFO(dev)->gen == 3)
   2169 		gtt_size = 1024*1024;
   2170 	else
   2171 		gtt_size = 512*1024;
   2172 
   2173 	while (gtt_size < size)
   2174 		gtt_size <<= 1;
   2175 
   2176 	return gtt_size;
   2177 }
   2178 
   2179 /**
   2180  * i915_gem_get_gtt_alignment - return required GTT alignment for an object
   2181  * @obj: object to check
   2182  *
   2183  * Return the required GTT alignment for an object, taking into account
   2184  * potential fence register mapping.
   2185  */
   2186 uint32_t
   2187 i915_gem_get_gtt_alignment(struct drm_device *dev, uint32_t size,
   2188 			   int tiling_mode, bool fenced)
   2189 {
   2190 	/*
   2191 	 * Minimum alignment is 4k (GTT page size), but might be greater
   2192 	 * if a fence register is needed for the object.
   2193 	 */
   2194 	if (INTEL_INFO(dev)->gen >= 4 || (!fenced && IS_G33(dev)) ||
   2195 	    tiling_mode == I915_TILING_NONE)
   2196 		return 4096;
   2197 
   2198 	/*
   2199 	 * Previous chips need to be aligned to the size of the smallest
   2200 	 * fence register that can contain the object.
   2201 	 */
   2202 	return i915_gem_get_gtt_size(dev, size, tiling_mode);
   2203 }
   2204 
   2205 static int i915_gem_object_create_mmap_offset(struct drm_i915_gem_object *obj)
   2206 {
   2207 	struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
   2208 	int ret;
   2209 
   2210 	if (drm_vma_node_has_offset(&obj->base.vma_node))
   2211 		return 0;
   2212 
   2213 	dev_priv->mm.shrinker_no_lock_stealing = true;
   2214 
   2215 	ret = drm_gem_create_mmap_offset(&obj->base);
   2216 	if (ret != -ENOSPC)
   2217 		goto out;
   2218 
   2219 	/* Badly fragmented mmap space? The only way we can recover
   2220 	 * space is by destroying unwanted objects. We can't randomly release
   2221 	 * mmap_offsets as userspace expects them to be persistent for the
   2222 	 * lifetime of the objects. The closest we can is to release the
   2223 	 * offsets on purgeable objects by truncating it and marking it purged,
   2224 	 * which prevents userspace from ever using that object again.
   2225 	 */
   2226 	i915_gem_purge(dev_priv, obj->base.size >> PAGE_SHIFT);
   2227 	ret = drm_gem_create_mmap_offset(&obj->base);
   2228 	if (ret != -ENOSPC)
   2229 		goto out;
   2230 
   2231 	i915_gem_shrink_all(dev_priv);
   2232 	ret = drm_gem_create_mmap_offset(&obj->base);
   2233 out:
   2234 	dev_priv->mm.shrinker_no_lock_stealing = false;
   2235 
   2236 	return ret;
   2237 }
   2238 
   2239 static void i915_gem_object_free_mmap_offset(struct drm_i915_gem_object *obj)
   2240 {
   2241 	drm_gem_free_mmap_offset(&obj->base);
   2242 }
   2243 
   2244 int
   2245 i915_gem_mmap_gtt(struct drm_file *file,
   2246 		  struct drm_device *dev,
   2247 		  uint32_t handle,
   2248 		  uint64_t *offset)
   2249 {
   2250 	struct drm_i915_private *dev_priv = dev->dev_private;
   2251 	struct drm_gem_object *gobj;
   2252 	struct drm_i915_gem_object *obj;
   2253 	int ret;
   2254 
   2255 	ret = i915_mutex_lock_interruptible(dev);
   2256 	if (ret)
   2257 		return ret;
   2258 
   2259 	gobj = drm_gem_object_lookup(dev, file, handle);
   2260 	if (gobj == NULL) {
   2261 		ret = -ENOENT;
   2262 		goto unlock;
   2263 	}
   2264 	obj = to_intel_bo(gobj);
   2265 
   2266 	if (obj->base.size > dev_priv->gtt.mappable_end) {
   2267 		ret = -E2BIG;
   2268 		goto out;
   2269 	}
   2270 
   2271 	if (obj->madv != I915_MADV_WILLNEED) {
   2272 		DRM_DEBUG("Attempting to mmap a purgeable buffer\n");
   2273 		ret = -EFAULT;
   2274 		goto out;
   2275 	}
   2276 
   2277 	ret = i915_gem_object_create_mmap_offset(obj);
   2278 	if (ret)
   2279 		goto out;
   2280 
   2281 	*offset = drm_vma_node_offset_addr(&obj->base.vma_node);
   2282 
   2283 out:
   2284 	drm_gem_object_unreference(&obj->base);
   2285 unlock:
   2286 	mutex_unlock(&dev->struct_mutex);
   2287 	return ret;
   2288 }
   2289 
   2290 /**
   2291  * i915_gem_mmap_gtt_ioctl - prepare an object for GTT mmap'ing
   2292  * @dev: DRM device
   2293  * @data: GTT mapping ioctl data
   2294  * @file: GEM object info
   2295  *
   2296  * Simply returns the fake offset to userspace so it can mmap it.
   2297  * The mmap call will end up in drm_gem_mmap(), which will set things
   2298  * up so we can get faults in the handler above.
   2299  *
   2300  * The fault handler will take care of binding the object into the GTT
   2301  * (since it may have been evicted to make room for something), allocating
   2302  * a fence register, and mapping the appropriate aperture address into
   2303  * userspace.
   2304  */
   2305 int
   2306 i915_gem_mmap_gtt_ioctl(struct drm_device *dev, void *data,
   2307 			struct drm_file *file)
   2308 {
   2309 	struct drm_i915_gem_mmap_gtt *args = data;
   2310 
   2311 	return i915_gem_mmap_gtt(file, dev, args->handle, &args->offset);
   2312 }
   2313 
   2314 /* Immediately discard the backing storage */
   2315 static void
   2316 i915_gem_object_truncate(struct drm_i915_gem_object *obj)
   2317 {
   2318 #ifndef __NetBSD__
   2319 	struct inode *inode;
   2320 #endif
   2321 
   2322 	i915_gem_object_free_mmap_offset(obj);
   2323 
   2324 #ifdef __NetBSD__
   2325 	if (obj->base.gemo_shm_uao == NULL)
   2326 		return;
   2327 
   2328 	{
   2329 		struct uvm_object *const uobj = obj->base.gemo_shm_uao;
   2330 
   2331 		if (uobj != NULL) {
   2332 			/* XXX Calling pgo_put like this is bogus.  */
   2333 			mutex_enter(uobj->vmobjlock);
   2334 			(*uobj->pgops->pgo_put)(uobj, 0, obj->base.size,
   2335 			    (PGO_ALLPAGES | PGO_FREE));
   2336 		}
   2337 	}
   2338 #else
   2339 	if (obj->base.filp == NULL)
   2340 		return;
   2341 
   2342 	/* Our goal here is to return as much of the memory as
   2343 	 * is possible back to the system as we are called from OOM.
   2344 	 * To do this we must instruct the shmfs to drop all of its
   2345 	 * backing pages, *now*.
   2346 	 */
   2347 	inode = file_inode(obj->base.filp);
   2348 	shmem_truncate_range(inode, 0, (loff_t)-1);
   2349 #endif
   2350 
   2351 	obj->madv = __I915_MADV_PURGED;
   2352 }
   2353 
   2354 static inline int
   2355 i915_gem_object_is_purgeable(struct drm_i915_gem_object *obj)
   2356 {
   2357 	return obj->madv == I915_MADV_DONTNEED;
   2358 }
   2359 
   2360 #ifdef __NetBSD__
   2361 static void
   2362 i915_gem_object_put_pages_gtt(struct drm_i915_gem_object *obj)
   2363 {
   2364 	struct drm_device *const dev = obj->base.dev;
   2365 	struct vm_page *page;
   2366 	int ret;
   2367 
   2368 	/* XXX Cargo-culted from the Linux code.  */
   2369 	BUG_ON(obj->madv == __I915_MADV_PURGED);
   2370 
   2371 	ret = i915_gem_object_set_to_cpu_domain(obj, true);
   2372 	if (ret) {
   2373 		WARN_ON(ret != -EIO);
   2374 		i915_gem_clflush_object(obj, true);
   2375 		obj->base.read_domains = obj->base.write_domain =
   2376 		    I915_GEM_DOMAIN_CPU;
   2377 	}
   2378 
   2379 	if (i915_gem_object_needs_bit17_swizzle(obj))
   2380 		i915_gem_object_save_bit_17_swizzle(obj);
   2381 
   2382 	if (obj->madv == I915_MADV_DONTNEED)
   2383 		obj->dirty = 0;
   2384 
   2385 	if (obj->dirty) {
   2386 		TAILQ_FOREACH(page, &obj->igo_pageq, pageq.queue) {
   2387 			page->flags &= ~PG_CLEAN;
   2388 			/* XXX mark page accessed */
   2389 		}
   2390 	}
   2391 
   2392 	bus_dmamap_destroy(dev->dmat, obj->igo_dmamap);
   2393 	bus_dmamem_unwire_uvm_object(dev->dmat, obj->base.gemo_shm_uao, 0,
   2394 	    obj->base.size, obj->pages, obj->igo_nsegs);
   2395 
   2396 	kfree(obj->pages);
   2397 }
   2398 #else
   2399 static void
   2400 i915_gem_object_put_pages_gtt(struct drm_i915_gem_object *obj)
   2401 {
   2402 	struct sg_page_iter sg_iter;
   2403 	int ret;
   2404 
   2405 	BUG_ON(obj->madv == __I915_MADV_PURGED);
   2406 
   2407 	ret = i915_gem_object_set_to_cpu_domain(obj, true);
   2408 	if (ret) {
   2409 		/* In the event of a disaster, abandon all caches and
   2410 		 * hope for the best.
   2411 		 */
   2412 		WARN_ON(ret != -EIO);
   2413 		i915_gem_clflush_object(obj, true);
   2414 		obj->base.read_domains = obj->base.write_domain = I915_GEM_DOMAIN_CPU;
   2415 	}
   2416 
   2417 	if (i915_gem_object_needs_bit17_swizzle(obj))
   2418 		i915_gem_object_save_bit_17_swizzle(obj);
   2419 
   2420 	if (obj->madv == I915_MADV_DONTNEED)
   2421 		obj->dirty = 0;
   2422 
   2423 	for_each_sg_page(obj->pages->sgl, &sg_iter, obj->pages->nents, 0) {
   2424 		struct page *page = sg_page_iter_page(&sg_iter);
   2425 
   2426 		if (obj->dirty)
   2427 			set_page_dirty(page);
   2428 
   2429 		if (obj->madv == I915_MADV_WILLNEED)
   2430 			mark_page_accessed(page);
   2431 
   2432 		page_cache_release(page);
   2433 	}
   2434 	obj->dirty = 0;
   2435 
   2436 	sg_free_table(obj->pages);
   2437 	kfree(obj->pages);
   2438 }
   2439 #endif
   2440 
   2441 int
   2442 i915_gem_object_put_pages(struct drm_i915_gem_object *obj)
   2443 {
   2444 	const struct drm_i915_gem_object_ops *ops = obj->ops;
   2445 
   2446 	if (obj->pages == NULL)
   2447 		return 0;
   2448 
   2449 	if (obj->pages_pin_count)
   2450 		return -EBUSY;
   2451 
   2452 	BUG_ON(i915_gem_obj_bound_any(obj));
   2453 
   2454 	/* ->put_pages might need to allocate memory for the bit17 swizzle
   2455 	 * array, hence protect them from being reaped by removing them from gtt
   2456 	 * lists early. */
   2457 	list_del(&obj->global_list);
   2458 
   2459 	ops->put_pages(obj);
   2460 	obj->pages = NULL;
   2461 
   2462 	if (i915_gem_object_is_purgeable(obj))
   2463 		i915_gem_object_truncate(obj);
   2464 
   2465 	return 0;
   2466 }
   2467 
   2468 static unsigned long
   2469 __i915_gem_shrink(struct drm_i915_private *dev_priv, long target,
   2470 		  bool purgeable_only)
   2471 {
   2472 	struct list_head still_bound_list;
   2473 	struct drm_i915_gem_object *obj, *next;
   2474 	unsigned long count = 0;
   2475 
   2476 	list_for_each_entry_safe(obj, next,
   2477 				 &dev_priv->mm.unbound_list,
   2478 				 global_list) {
   2479 		if ((i915_gem_object_is_purgeable(obj) || !purgeable_only) &&
   2480 		    i915_gem_object_put_pages(obj) == 0) {
   2481 			count += obj->base.size >> PAGE_SHIFT;
   2482 			if (count >= target)
   2483 				return count;
   2484 		}
   2485 	}
   2486 
   2487 	/*
   2488 	 * As we may completely rewrite the bound list whilst unbinding
   2489 	 * (due to retiring requests) we have to strictly process only
   2490 	 * one element of the list at the time, and recheck the list
   2491 	 * on every iteration.
   2492 	 */
   2493 	INIT_LIST_HEAD(&still_bound_list);
   2494 	while (count < target && !list_empty(&dev_priv->mm.bound_list)) {
   2495 		struct i915_vma *vma, *v;
   2496 
   2497 		obj = list_first_entry(&dev_priv->mm.bound_list,
   2498 				       typeof(*obj), global_list);
   2499 		list_move_tail(&obj->global_list, &still_bound_list);
   2500 
   2501 		if (!i915_gem_object_is_purgeable(obj) && purgeable_only)
   2502 			continue;
   2503 
   2504 		/*
   2505 		 * Hold a reference whilst we unbind this object, as we may
   2506 		 * end up waiting for and retiring requests. This might
   2507 		 * release the final reference (held by the active list)
   2508 		 * and result in the object being freed from under us.
   2509 		 * in this object being freed.
   2510 		 *
   2511 		 * Note 1: Shrinking the bound list is special since only active
   2512 		 * (and hence bound objects) can contain such limbo objects, so
   2513 		 * we don't need special tricks for shrinking the unbound list.
   2514 		 * The only other place where we have to be careful with active
   2515 		 * objects suddenly disappearing due to retiring requests is the
   2516 		 * eviction code.
   2517 		 *
   2518 		 * Note 2: Even though the bound list doesn't hold a reference
   2519 		 * to the object we can safely grab one here: The final object
   2520 		 * unreferencing and the bound_list are both protected by the
   2521 		 * dev->struct_mutex and so we won't ever be able to observe an
   2522 		 * object on the bound_list with a reference count equals 0.
   2523 		 */
   2524 		drm_gem_object_reference(&obj->base);
   2525 
   2526 		list_for_each_entry_safe(vma, v, &obj->vma_list, vma_link)
   2527 			if (i915_vma_unbind(vma))
   2528 				break;
   2529 
   2530 		if (i915_gem_object_put_pages(obj) == 0)
   2531 			count += obj->base.size >> PAGE_SHIFT;
   2532 
   2533 		drm_gem_object_unreference(&obj->base);
   2534 	}
   2535 	list_splice(&still_bound_list, &dev_priv->mm.bound_list);
   2536 
   2537 	return count;
   2538 }
   2539 
   2540 static unsigned long
   2541 i915_gem_purge(struct drm_i915_private *dev_priv, long target)
   2542 {
   2543 	return __i915_gem_shrink(dev_priv, target, true);
   2544 }
   2545 
   2546 static unsigned long
   2547 i915_gem_shrink_all(struct drm_i915_private *dev_priv)
   2548 {
   2549 	struct drm_i915_gem_object *obj, *next;
   2550 	long freed = 0;
   2551 
   2552 	i915_gem_evict_everything(dev_priv->dev);
   2553 
   2554 	list_for_each_entry_safe(obj, next, &dev_priv->mm.unbound_list,
   2555 				 global_list) {
   2556 		if (i915_gem_object_put_pages(obj) == 0)
   2557 			freed += obj->base.size >> PAGE_SHIFT;
   2558 	}
   2559 	return freed;
   2560 }
   2561 
   2562 #ifdef __NetBSD__
   2563 static int
   2564 i915_gem_object_get_pages_gtt(struct drm_i915_gem_object *obj)
   2565 {
   2566 	struct drm_device *const dev = obj->base.dev;
   2567 	struct vm_page *page;
   2568 	int error;
   2569 
   2570 	/* XXX Cargo-culted from the Linux code.  */
   2571 	BUG_ON(obj->base.read_domains & I915_GEM_GPU_DOMAINS);
   2572 	BUG_ON(obj->base.write_domain & I915_GEM_GPU_DOMAINS);
   2573 
   2574 	KASSERT(obj->pages == NULL);
   2575 	TAILQ_INIT(&obj->igo_pageq);
   2576 	obj->pages = kcalloc((obj->base.size / PAGE_SIZE),
   2577 	    sizeof(obj->pages[0]), GFP_KERNEL);
   2578 	if (obj->pages == NULL) {
   2579 		error = -ENOMEM;
   2580 		goto fail0;
   2581 	}
   2582 
   2583 	/* XXX errno NetBSD->Linux */
   2584 	error = -bus_dmamem_wire_uvm_object(dev->dmat, obj->base.gemo_shm_uao,
   2585 	    0, obj->base.size, &obj->igo_pageq, PAGE_SIZE, 0, obj->pages,
   2586 	    (obj->base.size / PAGE_SIZE), &obj->igo_nsegs, BUS_DMA_NOWAIT);
   2587 	if (error)
   2588 		/* XXX Try i915_gem_purge, i915_gem_shrink_all.  */
   2589 		goto fail1;
   2590 	KASSERT(0 < obj->igo_nsegs);
   2591 	KASSERT(obj->igo_nsegs <= (obj->base.size / PAGE_SIZE));
   2592 
   2593 	/*
   2594 	 * Check that the paddrs will fit in 40 bits, or 32 bits on i965.
   2595 	 *
   2596 	 * XXX This is wrong; we ought to pass this constraint to
   2597 	 * bus_dmamem_wire_uvm_object instead.
   2598 	 */
   2599 	TAILQ_FOREACH(page, &obj->igo_pageq, pageq.queue) {
   2600 		const uint64_t mask =
   2601 		    (IS_BROADWATER(dev) || IS_CRESTLINE(dev)?
   2602 			0xffffffffULL : 0xffffffffffULL);
   2603 		if (VM_PAGE_TO_PHYS(page) & ~mask) {
   2604 			DRM_ERROR("GEM physical address exceeds %u bits"
   2605 			    ": %"PRIxMAX"\n",
   2606 			    popcount64(mask),
   2607 			    (uintmax_t)VM_PAGE_TO_PHYS(page));
   2608 			error = -EIO;
   2609 			goto fail2;
   2610 		}
   2611 	}
   2612 
   2613 	/* XXX Should create the DMA map when creating the object.  */
   2614 
   2615 	/* XXX errno NetBSD->Linux */
   2616 	error = -bus_dmamap_create(dev->dmat, obj->base.size, obj->igo_nsegs,
   2617 	    PAGE_SIZE, 0, BUS_DMA_NOWAIT, &obj->igo_dmamap);
   2618 	if (error)
   2619 		goto fail2;
   2620 
   2621 	/* XXX Cargo-culted from the Linux code.  */
   2622 	if (i915_gem_object_needs_bit17_swizzle(obj))
   2623 		i915_gem_object_do_bit_17_swizzle(obj);
   2624 
   2625 	/* Success!  */
   2626 	return 0;
   2627 
   2628 fail2:	bus_dmamem_unwire_uvm_object(dev->dmat, obj->base.gemo_shm_uao, 0,
   2629 	    obj->base.size, obj->pages, (obj->base.size / PAGE_SIZE));
   2630 fail1:	kfree(obj->pages);
   2631 	obj->pages = NULL;
   2632 fail0:	KASSERT(error);
   2633 	return error;
   2634 }
   2635 #else
   2636 static int
   2637 i915_gem_object_get_pages_gtt(struct drm_i915_gem_object *obj)
   2638 {
   2639 	struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
   2640 	int page_count, i;
   2641 	struct address_space *mapping;
   2642 	struct sg_table *st;
   2643 	struct scatterlist *sg;
   2644 	struct sg_page_iter sg_iter;
   2645 	struct page *page;
   2646 	unsigned long last_pfn = 0;	/* suppress gcc warning */
   2647 	gfp_t gfp;
   2648 
   2649 	/* Assert that the object is not currently in any GPU domain. As it
   2650 	 * wasn't in the GTT, there shouldn't be any way it could have been in
   2651 	 * a GPU cache
   2652 	 */
   2653 	BUG_ON(obj->base.read_domains & I915_GEM_GPU_DOMAINS);
   2654 	BUG_ON(obj->base.write_domain & I915_GEM_GPU_DOMAINS);
   2655 
   2656 	st = kmalloc(sizeof(*st), GFP_KERNEL);
   2657 	if (st == NULL)
   2658 		return -ENOMEM;
   2659 
   2660 	page_count = obj->base.size / PAGE_SIZE;
   2661 	if (sg_alloc_table(st, page_count, GFP_KERNEL)) {
   2662 		kfree(st);
   2663 		return -ENOMEM;
   2664 	}
   2665 
   2666 	/* Get the list of pages out of our struct file.  They'll be pinned
   2667 	 * at this point until we release them.
   2668 	 *
   2669 	 * Fail silently without starting the shrinker
   2670 	 */
   2671 	mapping = file_inode(obj->base.filp)->i_mapping;
   2672 	gfp = mapping_gfp_mask(mapping);
   2673 	gfp |= __GFP_NORETRY | __GFP_NOWARN | __GFP_NO_KSWAPD;
   2674 	gfp &= ~(__GFP_IO | __GFP_WAIT);
   2675 	sg = st->sgl;
   2676 	st->nents = 0;
   2677 	for (i = 0; i < page_count; i++) {
   2678 		page = shmem_read_mapping_page_gfp(mapping, i, gfp);
   2679 		if (IS_ERR(page)) {
   2680 			i915_gem_purge(dev_priv, page_count);
   2681 			page = shmem_read_mapping_page_gfp(mapping, i, gfp);
   2682 		}
   2683 		if (IS_ERR(page)) {
   2684 			/* We've tried hard to allocate the memory by reaping
   2685 			 * our own buffer, now let the real VM do its job and
   2686 			 * go down in flames if truly OOM.
   2687 			 */
   2688 			gfp &= ~(__GFP_NORETRY | __GFP_NOWARN | __GFP_NO_KSWAPD);
   2689 			gfp |= __GFP_IO | __GFP_WAIT;
   2690 
   2691 			i915_gem_shrink_all(dev_priv);
   2692 			page = shmem_read_mapping_page_gfp(mapping, i, gfp);
   2693 			if (IS_ERR(page))
   2694 				goto err_pages;
   2695 
   2696 			gfp |= __GFP_NORETRY | __GFP_NOWARN | __GFP_NO_KSWAPD;
   2697 			gfp &= ~(__GFP_IO | __GFP_WAIT);
   2698 		}
   2699 #ifdef CONFIG_SWIOTLB
   2700 		if (swiotlb_nr_tbl()) {
   2701 			st->nents++;
   2702 			sg_set_page(sg, page, PAGE_SIZE, 0);
   2703 			sg = sg_next(sg);
   2704 			continue;
   2705 		}
   2706 #endif
   2707 		if (!i || page_to_pfn(page) != last_pfn + 1) {
   2708 			if (i)
   2709 				sg = sg_next(sg);
   2710 			st->nents++;
   2711 			sg_set_page(sg, page, PAGE_SIZE, 0);
   2712 		} else {
   2713 			sg->length += PAGE_SIZE;
   2714 		}
   2715 		last_pfn = page_to_pfn(page);
   2716 
   2717 		/* Check that the i965g/gm workaround works. */
   2718 		WARN_ON((gfp & __GFP_DMA32) && (last_pfn >= 0x00100000UL));
   2719 	}
   2720 #ifdef CONFIG_SWIOTLB
   2721 	if (!swiotlb_nr_tbl())
   2722 #endif
   2723 		sg_mark_end(sg);
   2724 	obj->pages = st;
   2725 
   2726 	if (i915_gem_object_needs_bit17_swizzle(obj))
   2727 		i915_gem_object_do_bit_17_swizzle(obj);
   2728 
   2729 	return 0;
   2730 
   2731 err_pages:
   2732 	sg_mark_end(sg);
   2733 	for_each_sg_page(st->sgl, &sg_iter, st->nents, 0)
   2734 		page_cache_release(sg_page_iter_page(&sg_iter));
   2735 	sg_free_table(st);
   2736 	kfree(st);
   2737 	return PTR_ERR(page);
   2738 }
   2739 #endif
   2740 
   2741 /* Ensure that the associated pages are gathered from the backing storage
   2742  * and pinned into our object. i915_gem_object_get_pages() may be called
   2743  * multiple times before they are released by a single call to
   2744  * i915_gem_object_put_pages() - once the pages are no longer referenced
   2745  * either as a result of memory pressure (reaping pages under the shrinker)
   2746  * or as the object is itself released.
   2747  */
   2748 int
   2749 i915_gem_object_get_pages(struct drm_i915_gem_object *obj)
   2750 {
   2751 	struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
   2752 	const struct drm_i915_gem_object_ops *ops = obj->ops;
   2753 	int ret;
   2754 
   2755 	if (obj->pages)
   2756 		return 0;
   2757 
   2758 	if (obj->madv != I915_MADV_WILLNEED) {
   2759 		DRM_DEBUG("Attempting to obtain a purgeable object\n");
   2760 		return -EFAULT;
   2761 	}
   2762 
   2763 	BUG_ON(obj->pages_pin_count);
   2764 
   2765 	ret = ops->get_pages(obj);
   2766 	if (ret)
   2767 		return ret;
   2768 
   2769 	list_add_tail(&obj->global_list, &dev_priv->mm.unbound_list);
   2770 	return 0;
   2771 }
   2772 
   2773 static void
   2774 i915_gem_object_move_to_active(struct drm_i915_gem_object *obj,
   2775 			       struct intel_ring_buffer *ring)
   2776 {
   2777 	struct drm_device *dev = obj->base.dev;
   2778 	struct drm_i915_private *dev_priv = dev->dev_private;
   2779 	u32 seqno = intel_ring_get_seqno(ring);
   2780 
   2781 	BUG_ON(ring == NULL);
   2782 	if (obj->ring != ring && obj->last_write_seqno) {
   2783 		/* Keep the seqno relative to the current ring */
   2784 		obj->last_write_seqno = seqno;
   2785 	}
   2786 	obj->ring = ring;
   2787 
   2788 	/* Add a reference if we're newly entering the active list. */
   2789 	if (!obj->active) {
   2790 		drm_gem_object_reference(&obj->base);
   2791 		obj->active = 1;
   2792 	}
   2793 
   2794 	list_move_tail(&obj->ring_list, &ring->active_list);
   2795 
   2796 	obj->last_read_seqno = seqno;
   2797 
   2798 	if (obj->fenced_gpu_access) {
   2799 		obj->last_fenced_seqno = seqno;
   2800 
   2801 		/* Bump MRU to take account of the delayed flush */
   2802 		if (obj->fence_reg != I915_FENCE_REG_NONE) {
   2803 			struct drm_i915_fence_reg *reg;
   2804 
   2805 			reg = &dev_priv->fence_regs[obj->fence_reg];
   2806 			list_move_tail(&reg->lru_list,
   2807 				       &dev_priv->mm.fence_list);
   2808 		}
   2809 	}
   2810 }
   2811 
   2812 void i915_vma_move_to_active(struct i915_vma *vma,
   2813 			     struct intel_ring_buffer *ring)
   2814 {
   2815 	list_move_tail(&vma->mm_list, &vma->vm->active_list);
   2816 	return i915_gem_object_move_to_active(vma->obj, ring);
   2817 }
   2818 
   2819 static void
   2820 i915_gem_object_move_to_inactive(struct drm_i915_gem_object *obj)
   2821 {
   2822 	struct drm_device *dev = obj->base.dev;
   2823 	struct drm_i915_private *dev_priv = dev->dev_private;
   2824 	struct i915_address_space *vm;
   2825 	struct i915_vma *vma;
   2826 
   2827 	if ((obj->base.write_domain & I915_GEM_DOMAIN_GTT) != 0) {
   2828 		printk(KERN_ERR "%s: %p 0x%x flushing gtt\n", __func__, obj,
   2829 			obj->base.write_domain);
   2830 		i915_gem_object_flush_gtt_write_domain(obj);
   2831 	}
   2832 	if ((obj->base.write_domain & I915_GEM_DOMAIN_CPU) != 0) {
   2833 		printk(KERN_ERR "%s: %p 0x%x flushing cpu\n", __func__, obj,
   2834 			obj->base.write_domain);
   2835 		i915_gem_object_flush_cpu_write_domain(obj, false);
   2836 	}
   2837 	BUG_ON(obj->base.write_domain & ~I915_GEM_GPU_DOMAINS);
   2838 	BUG_ON(!obj->active);
   2839 
   2840 	list_for_each_entry(vm, &dev_priv->vm_list, global_link) {
   2841 		vma = i915_gem_obj_to_vma(obj, vm);
   2842 		if (vma && !list_empty(&vma->mm_list))
   2843 			list_move_tail(&vma->mm_list, &vm->inactive_list);
   2844 	}
   2845 
   2846 	list_del_init(&obj->ring_list);
   2847 	obj->ring = NULL;
   2848 
   2849 	obj->last_read_seqno = 0;
   2850 	obj->last_write_seqno = 0;
   2851 	obj->base.write_domain = 0;
   2852 
   2853 	obj->last_fenced_seqno = 0;
   2854 	obj->fenced_gpu_access = false;
   2855 
   2856 	obj->active = 0;
   2857 	drm_gem_object_unreference(&obj->base);
   2858 
   2859 	WARN_ON(i915_verify_lists(dev));
   2860 }
   2861 
   2862 static int
   2863 i915_gem_init_seqno(struct drm_device *dev, u32 seqno)
   2864 {
   2865 	struct drm_i915_private *dev_priv = dev->dev_private;
   2866 	struct intel_ring_buffer *ring;
   2867 	int ret, i, j;
   2868 
   2869 	/* Carefully retire all requests without writing to the rings */
   2870 	for_each_ring(ring, dev_priv, i) {
   2871 		ret = intel_ring_idle(ring);
   2872 		if (ret)
   2873 			return ret;
   2874 	}
   2875 	i915_gem_retire_requests(dev);
   2876 
   2877 	/* Finally reset hw state */
   2878 	for_each_ring(ring, dev_priv, i) {
   2879 		intel_ring_init_seqno(ring, seqno);
   2880 
   2881 		for (j = 0; j < ARRAY_SIZE(ring->sync_seqno); j++)
   2882 			ring->sync_seqno[j] = 0;
   2883 	}
   2884 
   2885 	return 0;
   2886 }
   2887 
   2888 int i915_gem_set_seqno(struct drm_device *dev, u32 seqno)
   2889 {
   2890 	struct drm_i915_private *dev_priv = dev->dev_private;
   2891 	int ret;
   2892 
   2893 	if (seqno == 0)
   2894 		return -EINVAL;
   2895 
   2896 	/* HWS page needs to be set less than what we
   2897 	 * will inject to ring
   2898 	 */
   2899 	ret = i915_gem_init_seqno(dev, seqno - 1);
   2900 	if (ret)
   2901 		return ret;
   2902 
   2903 	/* Carefully set the last_seqno value so that wrap
   2904 	 * detection still works
   2905 	 */
   2906 	dev_priv->next_seqno = seqno;
   2907 	dev_priv->last_seqno = seqno - 1;
   2908 	if (dev_priv->last_seqno == 0)
   2909 		dev_priv->last_seqno--;
   2910 
   2911 	return 0;
   2912 }
   2913 
   2914 int
   2915 i915_gem_get_seqno(struct drm_device *dev, u32 *seqno)
   2916 {
   2917 	struct drm_i915_private *dev_priv = dev->dev_private;
   2918 
   2919 	/* reserve 0 for non-seqno */
   2920 	if (dev_priv->next_seqno == 0) {
   2921 		int ret = i915_gem_init_seqno(dev, 0);
   2922 		if (ret)
   2923 			return ret;
   2924 
   2925 		dev_priv->next_seqno = 1;
   2926 	}
   2927 
   2928 	*seqno = dev_priv->last_seqno = dev_priv->next_seqno++;
   2929 	return 0;
   2930 }
   2931 
   2932 int __i915_add_request(struct intel_ring_buffer *ring,
   2933 		       struct drm_file *file,
   2934 		       struct drm_i915_gem_object *obj,
   2935 		       u32 *out_seqno)
   2936 {
   2937 	struct drm_i915_private *dev_priv = ring->dev->dev_private;
   2938 	struct drm_i915_gem_request *request;
   2939 	u32 request_ring_position, request_start;
   2940 	int ret;
   2941 
   2942 	request_start = intel_ring_get_tail(ring);
   2943 	/*
   2944 	 * Emit any outstanding flushes - execbuf can fail to emit the flush
   2945 	 * after having emitted the batchbuffer command. Hence we need to fix
   2946 	 * things up similar to emitting the lazy request. The difference here
   2947 	 * is that the flush _must_ happen before the next request, no matter
   2948 	 * what.
   2949 	 */
   2950 	ret = intel_ring_flush_all_caches(ring);
   2951 	if (ret)
   2952 		return ret;
   2953 
   2954 	request = ring->preallocated_lazy_request;
   2955 	if (WARN_ON(request == NULL))
   2956 		return -ENOMEM;
   2957 
   2958 	/* Record the position of the start of the request so that
   2959 	 * should we detect the updated seqno part-way through the
   2960 	 * GPU processing the request, we never over-estimate the
   2961 	 * position of the head.
   2962 	 */
   2963 	request_ring_position = intel_ring_get_tail(ring);
   2964 
   2965 	ret = ring->add_request(ring);
   2966 	if (ret)
   2967 		return ret;
   2968 
   2969 	request->seqno = intel_ring_get_seqno(ring);
   2970 	request->ring = ring;
   2971 	request->head = request_start;
   2972 	request->tail = request_ring_position;
   2973 
   2974 	/* Whilst this request exists, batch_obj will be on the
   2975 	 * active_list, and so will hold the active reference. Only when this
   2976 	 * request is retired will the the batch_obj be moved onto the
   2977 	 * inactive_list and lose its active reference. Hence we do not need
   2978 	 * to explicitly hold another reference here.
   2979 	 */
   2980 	request->batch_obj = obj;
   2981 
   2982 	/* Hold a reference to the current context so that we can inspect
   2983 	 * it later in case a hangcheck error event fires.
   2984 	 */
   2985 	request->ctx = ring->last_context;
   2986 	if (request->ctx)
   2987 		i915_gem_context_reference(request->ctx);
   2988 
   2989 	request->emitted_jiffies = jiffies;
   2990 	list_add_tail(&request->list, &ring->request_list);
   2991 	request->file_priv = NULL;
   2992 
   2993 	if (file) {
   2994 		struct drm_i915_file_private *file_priv = file->driver_priv;
   2995 
   2996 		spin_lock(&file_priv->mm.lock);
   2997 		request->file_priv = file_priv;
   2998 		list_add_tail(&request->client_list,
   2999 			      &file_priv->mm.request_list);
   3000 		spin_unlock(&file_priv->mm.lock);
   3001 	}
   3002 
   3003 	trace_i915_gem_request_add(ring, request->seqno);
   3004 	ring->outstanding_lazy_seqno = 0;
   3005 	ring->preallocated_lazy_request = NULL;
   3006 
   3007 	if (!dev_priv->ums.mm_suspended) {
   3008 		i915_queue_hangcheck(ring->dev);
   3009 
   3010 		cancel_delayed_work_sync(&dev_priv->mm.idle_work);
   3011 		queue_delayed_work(dev_priv->wq,
   3012 				   &dev_priv->mm.retire_work,
   3013 				   round_jiffies_up_relative(HZ));
   3014 		intel_mark_busy(dev_priv->dev);
   3015 	}
   3016 
   3017 	if (out_seqno)
   3018 		*out_seqno = request->seqno;
   3019 	return 0;
   3020 }
   3021 
   3022 static inline void
   3023 i915_gem_request_remove_from_client(struct drm_i915_gem_request *request)
   3024 {
   3025 	struct drm_i915_file_private *file_priv = request->file_priv;
   3026 
   3027 	if (!file_priv)
   3028 		return;
   3029 
   3030 	spin_lock(&file_priv->mm.lock);
   3031 	list_del(&request->client_list);
   3032 	request->file_priv = NULL;
   3033 	spin_unlock(&file_priv->mm.lock);
   3034 }
   3035 
   3036 static bool i915_context_is_banned(struct drm_i915_private *dev_priv,
   3037 				   const struct i915_hw_context *ctx)
   3038 {
   3039 	unsigned long elapsed;
   3040 
   3041 	elapsed = get_seconds() - ctx->hang_stats.guilty_ts;
   3042 
   3043 	if (ctx->hang_stats.banned)
   3044 		return true;
   3045 
   3046 	if (elapsed <= DRM_I915_CTX_BAN_PERIOD) {
   3047 		if (!i915_gem_context_is_default(ctx)) {
   3048 			DRM_DEBUG("context hanging too fast, banning!\n");
   3049 			return true;
   3050 		} else if (dev_priv->gpu_error.stop_rings == 0) {
   3051 			DRM_ERROR("gpu hanging too fast, banning!\n");
   3052 			return true;
   3053 		}
   3054 	}
   3055 
   3056 	return false;
   3057 }
   3058 
   3059 static void i915_set_reset_status(struct drm_i915_private *dev_priv,
   3060 				  struct i915_hw_context *ctx,
   3061 				  const bool guilty)
   3062 {
   3063 	struct i915_ctx_hang_stats *hs;
   3064 
   3065 	if (WARN_ON(!ctx))
   3066 		return;
   3067 
   3068 	hs = &ctx->hang_stats;
   3069 
   3070 	if (guilty) {
   3071 		hs->banned = i915_context_is_banned(dev_priv, ctx);
   3072 		hs->batch_active++;
   3073 		hs->guilty_ts = get_seconds();
   3074 	} else {
   3075 		hs->batch_pending++;
   3076 	}
   3077 }
   3078 
   3079 static void i915_gem_free_request(struct drm_i915_gem_request *request)
   3080 {
   3081 	list_del(&request->list);
   3082 	i915_gem_request_remove_from_client(request);
   3083 
   3084 	if (request->ctx)
   3085 		i915_gem_context_unreference(request->ctx);
   3086 
   3087 	kfree(request);
   3088 }
   3089 
   3090 struct drm_i915_gem_request *
   3091 i915_gem_find_active_request(struct intel_ring_buffer *ring)
   3092 {
   3093 	struct drm_i915_gem_request *request;
   3094 	u32 completed_seqno;
   3095 
   3096 	completed_seqno = ring->get_seqno(ring, false);
   3097 
   3098 	list_for_each_entry(request, &ring->request_list, list) {
   3099 		if (i915_seqno_passed(completed_seqno, request->seqno))
   3100 			continue;
   3101 
   3102 		return request;
   3103 	}
   3104 
   3105 	return NULL;
   3106 }
   3107 
   3108 static void i915_gem_reset_ring_status(struct drm_i915_private *dev_priv,
   3109 				       struct intel_ring_buffer *ring)
   3110 {
   3111 	struct drm_i915_gem_request *request;
   3112 	bool ring_hung;
   3113 
   3114 	request = i915_gem_find_active_request(ring);
   3115 
   3116 	if (request == NULL)
   3117 		return;
   3118 
   3119 	ring_hung = ring->hangcheck.score >= HANGCHECK_SCORE_RING_HUNG;
   3120 
   3121 	i915_set_reset_status(dev_priv, request->ctx, ring_hung);
   3122 
   3123 	list_for_each_entry_continue(request, &ring->request_list, list)
   3124 		i915_set_reset_status(dev_priv, request->ctx, false);
   3125 }
   3126 
   3127 static void i915_gem_reset_ring_cleanup(struct drm_i915_private *dev_priv,
   3128 					struct intel_ring_buffer *ring)
   3129 {
   3130 	while (!list_empty(&ring->active_list)) {
   3131 		struct drm_i915_gem_object *obj;
   3132 
   3133 		obj = list_first_entry(&ring->active_list,
   3134 				       struct drm_i915_gem_object,
   3135 				       ring_list);
   3136 
   3137 		i915_gem_object_move_to_inactive(obj);
   3138 	}
   3139 
   3140 	/*
   3141 	 * We must free the requests after all the corresponding objects have
   3142 	 * been moved off active lists. Which is the same order as the normal
   3143 	 * retire_requests function does. This is important if object hold
   3144 	 * implicit references on things like e.g. ppgtt address spaces through
   3145 	 * the request.
   3146 	 */
   3147 	while (!list_empty(&ring->request_list)) {
   3148 		struct drm_i915_gem_request *request;
   3149 
   3150 		request = list_first_entry(&ring->request_list,
   3151 					   struct drm_i915_gem_request,
   3152 					   list);
   3153 
   3154 		i915_gem_free_request(request);
   3155 	}
   3156 }
   3157 
   3158 void i915_gem_restore_fences(struct drm_device *dev)
   3159 {
   3160 	struct drm_i915_private *dev_priv = dev->dev_private;
   3161 	int i;
   3162 
   3163 	for (i = 0; i < dev_priv->num_fence_regs; i++) {
   3164 		struct drm_i915_fence_reg *reg = &dev_priv->fence_regs[i];
   3165 
   3166 		/*
   3167 		 * Commit delayed tiling changes if we have an object still
   3168 		 * attached to the fence, otherwise just clear the fence.
   3169 		 */
   3170 		if (reg->obj) {
   3171 			i915_gem_object_update_fence(reg->obj, reg,
   3172 						     reg->obj->tiling_mode);
   3173 		} else {
   3174 			i915_gem_write_fence(dev, i, NULL);
   3175 		}
   3176 	}
   3177 }
   3178 
   3179 void i915_gem_reset(struct drm_device *dev)
   3180 {
   3181 	struct drm_i915_private *dev_priv = dev->dev_private;
   3182 	struct intel_ring_buffer *ring;
   3183 	int i;
   3184 
   3185 	/*
   3186 	 * Before we free the objects from the requests, we need to inspect
   3187 	 * them for finding the guilty party. As the requests only borrow
   3188 	 * their reference to the objects, the inspection must be done first.
   3189 	 */
   3190 	for_each_ring(ring, dev_priv, i)
   3191 		i915_gem_reset_ring_status(dev_priv, ring);
   3192 
   3193 	for_each_ring(ring, dev_priv, i)
   3194 		i915_gem_reset_ring_cleanup(dev_priv, ring);
   3195 
   3196 	i915_gem_cleanup_ringbuffer(dev);
   3197 
   3198 	i915_gem_context_reset(dev);
   3199 
   3200 	i915_gem_restore_fences(dev);
   3201 }
   3202 
   3203 /**
   3204  * This function clears the request list as sequence numbers are passed.
   3205  */
   3206 static void
   3207 i915_gem_retire_requests_ring(struct intel_ring_buffer *ring)
   3208 {
   3209 	uint32_t seqno;
   3210 
   3211 	if (list_empty(&ring->request_list))
   3212 		return;
   3213 
   3214 	WARN_ON(i915_verify_lists(ring->dev));
   3215 
   3216 	seqno = ring->get_seqno(ring, true);
   3217 
   3218 	/* Move any buffers on the active list that are no longer referenced
   3219 	 * by the ringbuffer to the flushing/inactive lists as appropriate,
   3220 	 * before we free the context associated with the requests.
   3221 	 */
   3222 	while (!list_empty(&ring->active_list)) {
   3223 		struct drm_i915_gem_object *obj;
   3224 
   3225 		obj = list_first_entry(&ring->active_list,
   3226 				      struct drm_i915_gem_object,
   3227 				      ring_list);
   3228 
   3229 		if (!i915_seqno_passed(seqno, obj->last_read_seqno))
   3230 			break;
   3231 
   3232 		i915_gem_object_move_to_inactive(obj);
   3233 	}
   3234 
   3235 
   3236 	while (!list_empty(&ring->request_list)) {
   3237 		struct drm_i915_gem_request *request;
   3238 
   3239 		request = list_first_entry(&ring->request_list,
   3240 					   struct drm_i915_gem_request,
   3241 					   list);
   3242 
   3243 		if (!i915_seqno_passed(seqno, request->seqno))
   3244 			break;
   3245 
   3246 		trace_i915_gem_request_retire(ring, request->seqno);
   3247 		/* We know the GPU must have read the request to have
   3248 		 * sent us the seqno + interrupt, so use the position
   3249 		 * of tail of the request to update the last known position
   3250 		 * of the GPU head.
   3251 		 */
   3252 		ring->last_retired_head = request->tail;
   3253 
   3254 		i915_gem_free_request(request);
   3255 	}
   3256 
   3257 	if (unlikely(ring->trace_irq_seqno &&
   3258 		     i915_seqno_passed(seqno, ring->trace_irq_seqno))) {
   3259 		ring->irq_put(ring);
   3260 		ring->trace_irq_seqno = 0;
   3261 	}
   3262 
   3263 	WARN_ON(i915_verify_lists(ring->dev));
   3264 }
   3265 
   3266 bool
   3267 i915_gem_retire_requests(struct drm_device *dev)
   3268 {
   3269 	struct drm_i915_private *dev_priv = dev->dev_private;
   3270 	struct intel_ring_buffer *ring;
   3271 	bool idle = true;
   3272 	int i;
   3273 
   3274 	for_each_ring(ring, dev_priv, i) {
   3275 		i915_gem_retire_requests_ring(ring);
   3276 		idle &= list_empty(&ring->request_list);
   3277 	}
   3278 
   3279 	if (idle)
   3280 		mod_delayed_work(dev_priv->wq,
   3281 				   &dev_priv->mm.idle_work,
   3282 				   msecs_to_jiffies(100));
   3283 
   3284 	return idle;
   3285 }
   3286 
   3287 static void
   3288 i915_gem_retire_work_handler(struct work_struct *work)
   3289 {
   3290 	struct drm_i915_private *dev_priv =
   3291 		container_of(work, typeof(*dev_priv), mm.retire_work.work);
   3292 	struct drm_device *dev = dev_priv->dev;
   3293 	bool idle;
   3294 
   3295 	/* Come back later if the device is busy... */
   3296 	idle = false;
   3297 	if (mutex_trylock(&dev->struct_mutex)) {
   3298 		idle = i915_gem_retire_requests(dev);
   3299 		mutex_unlock(&dev->struct_mutex);
   3300 	}
   3301 	if (!idle)
   3302 		queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work,
   3303 				   round_jiffies_up_relative(HZ));
   3304 }
   3305 
   3306 static void
   3307 i915_gem_idle_work_handler(struct work_struct *work)
   3308 {
   3309 	struct drm_i915_private *dev_priv =
   3310 		container_of(work, typeof(*dev_priv), mm.idle_work.work);
   3311 
   3312 	intel_mark_idle(dev_priv->dev);
   3313 }
   3314 
   3315 /**
   3316  * Ensures that an object will eventually get non-busy by flushing any required
   3317  * write domains, emitting any outstanding lazy request and retiring and
   3318  * completed requests.
   3319  */
   3320 static int
   3321 i915_gem_object_flush_active(struct drm_i915_gem_object *obj)
   3322 {
   3323 	int ret;
   3324 
   3325 	if (obj->active) {
   3326 		ret = i915_gem_check_olr(obj->ring, obj->last_read_seqno);
   3327 		if (ret)
   3328 			return ret;
   3329 
   3330 		i915_gem_retire_requests_ring(obj->ring);
   3331 	}
   3332 
   3333 	return 0;
   3334 }
   3335 
   3336 /**
   3337  * i915_gem_wait_ioctl - implements DRM_IOCTL_I915_GEM_WAIT
   3338  * @DRM_IOCTL_ARGS: standard ioctl arguments
   3339  *
   3340  * Returns 0 if successful, else an error is returned with the remaining time in
   3341  * the timeout parameter.
   3342  *  -ETIME: object is still busy after timeout
   3343  *  -ERESTARTSYS: signal interrupted the wait
   3344  *  -ENONENT: object doesn't exist
   3345  * Also possible, but rare:
   3346  *  -EAGAIN: GPU wedged
   3347  *  -ENOMEM: damn
   3348  *  -ENODEV: Internal IRQ fail
   3349  *  -E?: The add request failed
   3350  *
   3351  * The wait ioctl with a timeout of 0 reimplements the busy ioctl. With any
   3352  * non-zero timeout parameter the wait ioctl will wait for the given number of
   3353  * nanoseconds on an object becoming unbusy. Since the wait itself does so
   3354  * without holding struct_mutex the object may become re-busied before this
   3355  * function completes. A similar but shorter * race condition exists in the busy
   3356  * ioctl
   3357  */
   3358 int
   3359 i915_gem_wait_ioctl(struct drm_device *dev, void *data, struct drm_file *file)
   3360 {
   3361 	struct drm_i915_private *dev_priv = dev->dev_private;
   3362 	struct drm_i915_gem_wait *args = data;
   3363 	struct drm_gem_object *gobj;
   3364 	struct drm_i915_gem_object *obj;
   3365 	struct intel_ring_buffer *ring = NULL;
   3366 	struct timespec timeout_stack, *timeout = NULL;
   3367 	unsigned reset_counter;
   3368 	u32 seqno = 0;
   3369 	int ret = 0;
   3370 
   3371 	if (args->timeout_ns >= 0) {
   3372 		timeout_stack = ns_to_timespec(args->timeout_ns);
   3373 		timeout = &timeout_stack;
   3374 	}
   3375 
   3376 	ret = i915_mutex_lock_interruptible(dev);
   3377 	if (ret)
   3378 		return ret;
   3379 
   3380 	gobj = drm_gem_object_lookup(dev, file, args->bo_handle);
   3381 	if (gobj == NULL) {
   3382 		mutex_unlock(&dev->struct_mutex);
   3383 		return -ENOENT;
   3384 	}
   3385 	obj = to_intel_bo(gobj);
   3386 
   3387 	/* Need to make sure the object gets inactive eventually. */
   3388 	ret = i915_gem_object_flush_active(obj);
   3389 	if (ret)
   3390 		goto out;
   3391 
   3392 	if (obj->active) {
   3393 		seqno = obj->last_read_seqno;
   3394 		ring = obj->ring;
   3395 	}
   3396 
   3397 	if (seqno == 0)
   3398 		 goto out;
   3399 
   3400 	/* Do this after OLR check to make sure we make forward progress polling
   3401 	 * on this IOCTL with a 0 timeout (like busy ioctl)
   3402 	 */
   3403 	if (!args->timeout_ns) {
   3404 		ret = -ETIME;
   3405 		goto out;
   3406 	}
   3407 
   3408 	drm_gem_object_unreference(&obj->base);
   3409 	reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
   3410 	mutex_unlock(&dev->struct_mutex);
   3411 
   3412 	ret = __wait_seqno(ring, seqno, reset_counter, true, timeout, file->driver_priv);
   3413 	if (timeout)
   3414 		args->timeout_ns = timespec_to_ns(timeout);
   3415 	return ret;
   3416 
   3417 out:
   3418 	drm_gem_object_unreference(&obj->base);
   3419 	mutex_unlock(&dev->struct_mutex);
   3420 	return ret;
   3421 }
   3422 
   3423 /**
   3424  * i915_gem_object_sync - sync an object to a ring.
   3425  *
   3426  * @obj: object which may be in use on another ring.
   3427  * @to: ring we wish to use the object on. May be NULL.
   3428  *
   3429  * This code is meant to abstract object synchronization with the GPU.
   3430  * Calling with NULL implies synchronizing the object with the CPU
   3431  * rather than a particular GPU ring.
   3432  *
   3433  * Returns 0 if successful, else propagates up the lower layer error.
   3434  */
   3435 int
   3436 i915_gem_object_sync(struct drm_i915_gem_object *obj,
   3437 		     struct intel_ring_buffer *to)
   3438 {
   3439 	struct intel_ring_buffer *from = obj->ring;
   3440 	u32 seqno;
   3441 	int ret, idx;
   3442 
   3443 	if (from == NULL || to == from)
   3444 		return 0;
   3445 
   3446 	if (to == NULL || !i915_semaphore_is_enabled(obj->base.dev))
   3447 		return i915_gem_object_wait_rendering(obj, false);
   3448 
   3449 	idx = intel_ring_sync_index(from, to);
   3450 
   3451 	seqno = obj->last_read_seqno;
   3452 	if (seqno <= from->sync_seqno[idx])
   3453 		return 0;
   3454 
   3455 	ret = i915_gem_check_olr(obj->ring, seqno);
   3456 	if (ret)
   3457 		return ret;
   3458 
   3459 	trace_i915_gem_ring_sync_to(from, to, seqno);
   3460 	ret = to->sync_to(to, from, seqno);
   3461 	if (!ret)
   3462 		/* We use last_read_seqno because sync_to()
   3463 		 * might have just caused seqno wrap under
   3464 		 * the radar.
   3465 		 */
   3466 		from->sync_seqno[idx] = obj->last_read_seqno;
   3467 
   3468 	return ret;
   3469 }
   3470 
   3471 static void i915_gem_object_finish_gtt(struct drm_i915_gem_object *obj)
   3472 {
   3473 	u32 old_write_domain, old_read_domains;
   3474 
   3475 	/* Force a pagefault for domain tracking on next user access */
   3476 	i915_gem_release_mmap(obj);
   3477 
   3478 	if ((obj->base.read_domains & I915_GEM_DOMAIN_GTT) == 0)
   3479 		return;
   3480 
   3481 	/* Wait for any direct GTT access to complete */
   3482 	mb();
   3483 
   3484 	old_read_domains = obj->base.read_domains;
   3485 	old_write_domain = obj->base.write_domain;
   3486 
   3487 	obj->base.read_domains &= ~I915_GEM_DOMAIN_GTT;
   3488 	obj->base.write_domain &= ~I915_GEM_DOMAIN_GTT;
   3489 
   3490 	trace_i915_gem_object_change_domain(obj,
   3491 					    old_read_domains,
   3492 					    old_write_domain);
   3493 }
   3494 
   3495 int i915_vma_unbind(struct i915_vma *vma)
   3496 {
   3497 	struct drm_i915_gem_object *obj = vma->obj;
   3498 	struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
   3499 	int ret;
   3500 
   3501 	if (list_empty(&vma->vma_link))
   3502 		return 0;
   3503 
   3504 	if (!drm_mm_node_allocated(&vma->node)) {
   3505 		i915_gem_vma_destroy(vma);
   3506 		return 0;
   3507 	}
   3508 
   3509 	if (vma->pin_count)
   3510 		return -EBUSY;
   3511 
   3512 	BUG_ON(obj->pages == NULL);
   3513 
   3514 	ret = i915_gem_object_finish_gpu(obj);
   3515 	if (ret)
   3516 		return ret;
   3517 	/* Continue on if we fail due to EIO, the GPU is hung so we
   3518 	 * should be safe and we need to cleanup or else we might
   3519 	 * cause memory corruption through use-after-free.
   3520 	 */
   3521 
   3522 	i915_gem_object_finish_gtt(obj);
   3523 
   3524 	/* release the fence reg _after_ flushing */
   3525 	ret = i915_gem_object_put_fence(obj);
   3526 	if (ret)
   3527 		return ret;
   3528 
   3529 	trace_i915_vma_unbind(vma);
   3530 
   3531 	vma->unbind_vma(vma);
   3532 
   3533 	i915_gem_gtt_finish_object(obj);
   3534 
   3535 	list_del_init(&vma->mm_list);
   3536 	/* Avoid an unnecessary call to unbind on rebind. */
   3537 	if (i915_is_ggtt(vma->vm))
   3538 		obj->map_and_fenceable = true;
   3539 
   3540 	drm_mm_remove_node(&vma->node);
   3541 	i915_gem_vma_destroy(vma);
   3542 
   3543 	/* Since the unbound list is global, only move to that list if
   3544 	 * no more VMAs exist. */
   3545 	if (list_empty(&obj->vma_list))
   3546 		list_move_tail(&obj->global_list, &dev_priv->mm.unbound_list);
   3547 
   3548 	/* And finally now the object is completely decoupled from this vma,
   3549 	 * we can drop its hold on the backing storage and allow it to be
   3550 	 * reaped by the shrinker.
   3551 	 */
   3552 	i915_gem_object_unpin_pages(obj);
   3553 
   3554 	return 0;
   3555 }
   3556 
   3557 int i915_gpu_idle(struct drm_device *dev)
   3558 {
   3559 	struct drm_i915_private *dev_priv = dev->dev_private;
   3560 	struct intel_ring_buffer *ring;
   3561 	int ret, i;
   3562 
   3563 	/* Flush everything onto the inactive list. */
   3564 	for_each_ring(ring, dev_priv, i) {
   3565 		ret = i915_switch_context(ring, ring->default_context);
   3566 		if (ret)
   3567 			return ret;
   3568 
   3569 		ret = intel_ring_idle(ring);
   3570 		if (ret)
   3571 			return ret;
   3572 	}
   3573 
   3574 	return 0;
   3575 }
   3576 
   3577 static void i965_write_fence_reg(struct drm_device *dev, int reg,
   3578 				 struct drm_i915_gem_object *obj)
   3579 {
   3580 	struct drm_i915_private *dev_priv = dev->dev_private;
   3581 	int fence_reg;
   3582 	int fence_pitch_shift;
   3583 
   3584 	if (INTEL_INFO(dev)->gen >= 6) {
   3585 		fence_reg = FENCE_REG_SANDYBRIDGE_0;
   3586 		fence_pitch_shift = SANDYBRIDGE_FENCE_PITCH_SHIFT;
   3587 	} else {
   3588 		fence_reg = FENCE_REG_965_0;
   3589 		fence_pitch_shift = I965_FENCE_PITCH_SHIFT;
   3590 	}
   3591 
   3592 	fence_reg += reg * 8;
   3593 
   3594 	/* To w/a incoherency with non-atomic 64-bit register updates,
   3595 	 * we split the 64-bit update into two 32-bit writes. In order
   3596 	 * for a partial fence not to be evaluated between writes, we
   3597 	 * precede the update with write to turn off the fence register,
   3598 	 * and only enable the fence as the last step.
   3599 	 *
   3600 	 * For extra levels of paranoia, we make sure each step lands
   3601 	 * before applying the next step.
   3602 	 */
   3603 	I915_WRITE(fence_reg, 0);
   3604 	POSTING_READ(fence_reg);
   3605 
   3606 	if (obj) {
   3607 		u32 size = i915_gem_obj_ggtt_size(obj);
   3608 		uint64_t val;
   3609 
   3610 		val = (uint64_t)((i915_gem_obj_ggtt_offset(obj) + size - 4096) &
   3611 				 0xfffff000) << 32;
   3612 		val |= i915_gem_obj_ggtt_offset(obj) & 0xfffff000;
   3613 		val |= (uint64_t)((obj->stride / 128) - 1) << fence_pitch_shift;
   3614 		if (obj->tiling_mode == I915_TILING_Y)
   3615 			val |= 1 << I965_FENCE_TILING_Y_SHIFT;
   3616 		val |= I965_FENCE_REG_VALID;
   3617 
   3618 		I915_WRITE(fence_reg + 4, val >> 32);
   3619 		POSTING_READ(fence_reg + 4);
   3620 
   3621 		I915_WRITE(fence_reg + 0, val);
   3622 		POSTING_READ(fence_reg);
   3623 	} else {
   3624 		I915_WRITE(fence_reg + 4, 0);
   3625 		POSTING_READ(fence_reg + 4);
   3626 	}
   3627 }
   3628 
   3629 static void i915_write_fence_reg(struct drm_device *dev, int reg,
   3630 				 struct drm_i915_gem_object *obj)
   3631 {
   3632 	struct drm_i915_private *dev_priv = dev->dev_private;
   3633 	u32 val;
   3634 
   3635 	if (obj) {
   3636 		u32 size = i915_gem_obj_ggtt_size(obj);
   3637 		int pitch_val;
   3638 		int tile_width;
   3639 
   3640 		WARN((i915_gem_obj_ggtt_offset(obj) & ~I915_FENCE_START_MASK) ||
   3641 		     (size & -size) != size ||
   3642 		     (i915_gem_obj_ggtt_offset(obj) & (size - 1)),
   3643 		     "object 0x%08lx [fenceable? %d] not 1M or pot-size (0x%08x) aligned\n",
   3644 		     i915_gem_obj_ggtt_offset(obj), obj->map_and_fenceable, size);
   3645 
   3646 		if (obj->tiling_mode == I915_TILING_Y && HAS_128_BYTE_Y_TILING(dev))
   3647 			tile_width = 128;
   3648 		else
   3649 			tile_width = 512;
   3650 
   3651 		/* Note: pitch better be a power of two tile widths */
   3652 		pitch_val = obj->stride / tile_width;
   3653 		pitch_val = ffs(pitch_val) - 1;
   3654 
   3655 		val = i915_gem_obj_ggtt_offset(obj);
   3656 		if (obj->tiling_mode == I915_TILING_Y)
   3657 			val |= 1 << I830_FENCE_TILING_Y_SHIFT;
   3658 		val |= I915_FENCE_SIZE_BITS(size);
   3659 		val |= pitch_val << I830_FENCE_PITCH_SHIFT;
   3660 		val |= I830_FENCE_REG_VALID;
   3661 	} else
   3662 		val = 0;
   3663 
   3664 	if (reg < 8)
   3665 		reg = FENCE_REG_830_0 + reg * 4;
   3666 	else
   3667 		reg = FENCE_REG_945_8 + (reg - 8) * 4;
   3668 
   3669 	I915_WRITE(reg, val);
   3670 	POSTING_READ(reg);
   3671 }
   3672 
   3673 static void i830_write_fence_reg(struct drm_device *dev, int reg,
   3674 				struct drm_i915_gem_object *obj)
   3675 {
   3676 	struct drm_i915_private *dev_priv = dev->dev_private;
   3677 	uint32_t val;
   3678 
   3679 	if (obj) {
   3680 		u32 size = i915_gem_obj_ggtt_size(obj);
   3681 		uint32_t pitch_val;
   3682 
   3683 		WARN((i915_gem_obj_ggtt_offset(obj) & ~I830_FENCE_START_MASK) ||
   3684 		     (size & -size) != size ||
   3685 		     (i915_gem_obj_ggtt_offset(obj) & (size - 1)),
   3686 		     "object 0x%08lx not 512K or pot-size 0x%08x aligned\n",
   3687 		     i915_gem_obj_ggtt_offset(obj), size);
   3688 
   3689 		pitch_val = obj->stride / 128;
   3690 		pitch_val = ffs(pitch_val) - 1;
   3691 
   3692 		val = i915_gem_obj_ggtt_offset(obj);
   3693 		if (obj->tiling_mode == I915_TILING_Y)
   3694 			val |= 1 << I830_FENCE_TILING_Y_SHIFT;
   3695 		val |= I830_FENCE_SIZE_BITS(size);
   3696 		val |= pitch_val << I830_FENCE_PITCH_SHIFT;
   3697 		val |= I830_FENCE_REG_VALID;
   3698 	} else
   3699 		val = 0;
   3700 
   3701 	I915_WRITE(FENCE_REG_830_0 + reg * 4, val);
   3702 	POSTING_READ(FENCE_REG_830_0 + reg * 4);
   3703 }
   3704 
   3705 inline static bool i915_gem_object_needs_mb(struct drm_i915_gem_object *obj)
   3706 {
   3707 	return obj && obj->base.read_domains & I915_GEM_DOMAIN_GTT;
   3708 }
   3709 
   3710 static void i915_gem_write_fence(struct drm_device *dev, int reg,
   3711 				 struct drm_i915_gem_object *obj)
   3712 {
   3713 	struct drm_i915_private *dev_priv = dev->dev_private;
   3714 
   3715 	/* Ensure that all CPU reads are completed before installing a fence
   3716 	 * and all writes before removing the fence.
   3717 	 */
   3718 	if (i915_gem_object_needs_mb(dev_priv->fence_regs[reg].obj))
   3719 		mb();
   3720 
   3721 	WARN(obj && (!obj->stride || !obj->tiling_mode),
   3722 	     "bogus fence setup with stride: 0x%x, tiling mode: %i\n",
   3723 	     obj->stride, obj->tiling_mode);
   3724 
   3725 	switch (INTEL_INFO(dev)->gen) {
   3726 	case 8:
   3727 	case 7:
   3728 	case 6:
   3729 	case 5:
   3730 	case 4: i965_write_fence_reg(dev, reg, obj); break;
   3731 	case 3: i915_write_fence_reg(dev, reg, obj); break;
   3732 	case 2: i830_write_fence_reg(dev, reg, obj); break;
   3733 	default: BUG();
   3734 	}
   3735 
   3736 	/* And similarly be paranoid that no direct access to this region
   3737 	 * is reordered to before the fence is installed.
   3738 	 */
   3739 	if (i915_gem_object_needs_mb(obj))
   3740 		mb();
   3741 }
   3742 
   3743 static inline int fence_number(struct drm_i915_private *dev_priv,
   3744 			       struct drm_i915_fence_reg *fence)
   3745 {
   3746 	return fence - dev_priv->fence_regs;
   3747 }
   3748 
   3749 static void i915_gem_object_update_fence(struct drm_i915_gem_object *obj,
   3750 					 struct drm_i915_fence_reg *fence,
   3751 					 bool enable)
   3752 {
   3753 	struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
   3754 	int reg = fence_number(dev_priv, fence);
   3755 
   3756 	i915_gem_write_fence(obj->base.dev, reg, enable ? obj : NULL);
   3757 
   3758 	if (enable) {
   3759 		obj->fence_reg = reg;
   3760 		fence->obj = obj;
   3761 		list_move_tail(&fence->lru_list, &dev_priv->mm.fence_list);
   3762 	} else {
   3763 		obj->fence_reg = I915_FENCE_REG_NONE;
   3764 		fence->obj = NULL;
   3765 		list_del_init(&fence->lru_list);
   3766 	}
   3767 	obj->fence_dirty = false;
   3768 }
   3769 
   3770 static int
   3771 i915_gem_object_wait_fence(struct drm_i915_gem_object *obj)
   3772 {
   3773 	if (obj->last_fenced_seqno) {
   3774 		int ret = i915_wait_seqno(obj->ring, obj->last_fenced_seqno);
   3775 		if (ret)
   3776 			return ret;
   3777 
   3778 		obj->last_fenced_seqno = 0;
   3779 	}
   3780 
   3781 	obj->fenced_gpu_access = false;
   3782 	return 0;
   3783 }
   3784 
   3785 int
   3786 i915_gem_object_put_fence(struct drm_i915_gem_object *obj)
   3787 {
   3788 	struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
   3789 	struct drm_i915_fence_reg *fence;
   3790 	int ret;
   3791 
   3792 	ret = i915_gem_object_wait_fence(obj);
   3793 	if (ret)
   3794 		return ret;
   3795 
   3796 	if (obj->fence_reg == I915_FENCE_REG_NONE)
   3797 		return 0;
   3798 
   3799 	fence = &dev_priv->fence_regs[obj->fence_reg];
   3800 
   3801 	i915_gem_object_fence_lost(obj);
   3802 	i915_gem_object_update_fence(obj, fence, false);
   3803 
   3804 	return 0;
   3805 }
   3806 
   3807 static struct drm_i915_fence_reg *
   3808 i915_find_fence_reg(struct drm_device *dev)
   3809 {
   3810 	struct drm_i915_private *dev_priv = dev->dev_private;
   3811 	struct drm_i915_fence_reg *reg, *avail;
   3812 	int i;
   3813 
   3814 	/* First try to find a free reg */
   3815 	avail = NULL;
   3816 	for (i = dev_priv->fence_reg_start; i < dev_priv->num_fence_regs; i++) {
   3817 		reg = &dev_priv->fence_regs[i];
   3818 		if (!reg->obj)
   3819 			return reg;
   3820 
   3821 		if (!reg->pin_count)
   3822 			avail = reg;
   3823 	}
   3824 
   3825 	if (avail == NULL)
   3826 		goto deadlock;
   3827 
   3828 	/* None available, try to steal one or wait for a user to finish */
   3829 	list_for_each_entry(reg, &dev_priv->mm.fence_list, lru_list) {
   3830 		if (reg->pin_count)
   3831 			continue;
   3832 
   3833 		return reg;
   3834 	}
   3835 
   3836 deadlock:
   3837 	/* Wait for completion of pending flips which consume fences */
   3838 	if (intel_has_pending_fb_unpin(dev))
   3839 		return ERR_PTR(-EAGAIN);
   3840 
   3841 	return ERR_PTR(-EDEADLK);
   3842 }
   3843 
   3844 /**
   3845  * i915_gem_object_get_fence - set up fencing for an object
   3846  * @obj: object to map through a fence reg
   3847  *
   3848  * When mapping objects through the GTT, userspace wants to be able to write
   3849  * to them without having to worry about swizzling if the object is tiled.
   3850  * This function walks the fence regs looking for a free one for @obj,
   3851  * stealing one if it can't find any.
   3852  *
   3853  * It then sets up the reg based on the object's properties: address, pitch
   3854  * and tiling format.
   3855  *
   3856  * For an untiled surface, this removes any existing fence.
   3857  */
   3858 int
   3859 i915_gem_object_get_fence(struct drm_i915_gem_object *obj)
   3860 {
   3861 	struct drm_device *dev = obj->base.dev;
   3862 	struct drm_i915_private *dev_priv = dev->dev_private;
   3863 	bool enable = obj->tiling_mode != I915_TILING_NONE;
   3864 	struct drm_i915_fence_reg *reg;
   3865 	int ret;
   3866 
   3867 	/* Have we updated the tiling parameters upon the object and so
   3868 	 * will need to serialise the write to the associated fence register?
   3869 	 */
   3870 	if (obj->fence_dirty) {
   3871 		ret = i915_gem_object_wait_fence(obj);
   3872 		if (ret)
   3873 			return ret;
   3874 	}
   3875 
   3876 	/* Just update our place in the LRU if our fence is getting reused. */
   3877 	if (obj->fence_reg != I915_FENCE_REG_NONE) {
   3878 		reg = &dev_priv->fence_regs[obj->fence_reg];
   3879 		if (!obj->fence_dirty) {
   3880 			list_move_tail(&reg->lru_list,
   3881 				       &dev_priv->mm.fence_list);
   3882 			return 0;
   3883 		}
   3884 	} else if (enable) {
   3885 		reg = i915_find_fence_reg(dev);
   3886 		if (IS_ERR(reg))
   3887 			return PTR_ERR(reg);
   3888 
   3889 		if (reg->obj) {
   3890 			struct drm_i915_gem_object *old = reg->obj;
   3891 
   3892 			ret = i915_gem_object_wait_fence(old);
   3893 			if (ret)
   3894 				return ret;
   3895 
   3896 			i915_gem_object_fence_lost(old);
   3897 		}
   3898 	} else
   3899 		return 0;
   3900 
   3901 	i915_gem_object_update_fence(obj, reg, enable);
   3902 
   3903 	return 0;
   3904 }
   3905 
   3906 static bool i915_gem_valid_gtt_space(struct drm_device *dev,
   3907 				     struct drm_mm_node *gtt_space,
   3908 				     unsigned long cache_level)
   3909 {
   3910 	struct drm_mm_node *other;
   3911 
   3912 	/* On non-LLC machines we have to be careful when putting differing
   3913 	 * types of snoopable memory together to avoid the prefetcher
   3914 	 * crossing memory domains and dying.
   3915 	 */
   3916 	if (HAS_LLC(dev))
   3917 		return true;
   3918 
   3919 	if (!drm_mm_node_allocated(gtt_space))
   3920 		return true;
   3921 
   3922 	if (list_empty(&gtt_space->node_list))
   3923 		return true;
   3924 
   3925 	other = list_entry(gtt_space->node_list.prev, struct drm_mm_node, node_list);
   3926 	if (other->allocated && !other->hole_follows && other->color != cache_level)
   3927 		return false;
   3928 
   3929 	other = list_entry(gtt_space->node_list.next, struct drm_mm_node, node_list);
   3930 	if (other->allocated && !gtt_space->hole_follows && other->color != cache_level)
   3931 		return false;
   3932 
   3933 	return true;
   3934 }
   3935 
   3936 static void i915_gem_verify_gtt(struct drm_device *dev)
   3937 {
   3938 #if WATCH_GTT
   3939 	struct drm_i915_private *dev_priv = dev->dev_private;
   3940 	struct drm_i915_gem_object *obj;
   3941 	int err = 0;
   3942 
   3943 	list_for_each_entry(obj, &dev_priv->mm.bound_list, global_list) {
   3944 		if (obj->gtt_space == NULL) {
   3945 			printk(KERN_ERR "object found on GTT list with no space reserved\n");
   3946 			err++;
   3947 			continue;
   3948 		}
   3949 
   3950 		if (obj->cache_level != obj->gtt_space->color) {
   3951 			printk(KERN_ERR "object reserved space [%08lx, %08lx] with wrong color, cache_level=%x, color=%lx\n",
   3952 			       i915_gem_obj_ggtt_offset(obj),
   3953 			       i915_gem_obj_ggtt_offset(obj) + i915_gem_obj_ggtt_size(obj),
   3954 			       obj->cache_level,
   3955 			       obj->gtt_space->color);
   3956 			err++;
   3957 			continue;
   3958 		}
   3959 
   3960 		if (!i915_gem_valid_gtt_space(dev,
   3961 					      obj->gtt_space,
   3962 					      obj->cache_level)) {
   3963 			printk(KERN_ERR "invalid GTT space found at [%08lx, %08lx] - color=%x\n",
   3964 			       i915_gem_obj_ggtt_offset(obj),
   3965 			       i915_gem_obj_ggtt_offset(obj) + i915_gem_obj_ggtt_size(obj),
   3966 			       obj->cache_level);
   3967 			err++;
   3968 			continue;
   3969 		}
   3970 	}
   3971 
   3972 	WARN_ON(err);
   3973 #endif
   3974 }
   3975 
   3976 /**
   3977  * Finds free space in the GTT aperture and binds the object there.
   3978  */
   3979 static struct i915_vma *
   3980 i915_gem_object_bind_to_vm(struct drm_i915_gem_object *obj,
   3981 			   struct i915_address_space *vm,
   3982 			   unsigned alignment,
   3983 			   uint64_t flags)
   3984 {
   3985 	struct drm_device *dev = obj->base.dev;
   3986 	struct drm_i915_private *dev_priv = dev->dev_private;
   3987 	u32 size, fence_size, fence_alignment, unfenced_alignment;
   3988 	unsigned long start =
   3989 		flags & PIN_OFFSET_BIAS ? flags & PIN_OFFSET_MASK : 0;
   3990 	unsigned long end =
   3991 		flags & PIN_MAPPABLE ? dev_priv->gtt.mappable_end : vm->total;
   3992 	struct i915_vma *vma;
   3993 	int ret;
   3994 
   3995 	fence_size = i915_gem_get_gtt_size(dev,
   3996 					   obj->base.size,
   3997 					   obj->tiling_mode);
   3998 	fence_alignment = i915_gem_get_gtt_alignment(dev,
   3999 						     obj->base.size,
   4000 						     obj->tiling_mode, true);
   4001 	unfenced_alignment =
   4002 		i915_gem_get_gtt_alignment(dev,
   4003 					   obj->base.size,
   4004 					   obj->tiling_mode, false);
   4005 
   4006 	if (alignment == 0)
   4007 		alignment = flags & PIN_MAPPABLE ? fence_alignment :
   4008 						unfenced_alignment;
   4009 	if (flags & PIN_MAPPABLE && alignment & (fence_alignment - 1)) {
   4010 		DRM_DEBUG("Invalid object alignment requested %u\n", alignment);
   4011 		return ERR_PTR(-EINVAL);
   4012 	}
   4013 
   4014 	size = flags & PIN_MAPPABLE ? fence_size : obj->base.size;
   4015 
   4016 	/* If the object is bigger than the entire aperture, reject it early
   4017 	 * before evicting everything in a vain attempt to find space.
   4018 	 */
   4019 	if (obj->base.size > end) {
   4020 		DRM_DEBUG("Attempting to bind an object larger than the aperture: object=%zd > %s aperture=%lu\n",
   4021 			  obj->base.size,
   4022 			  flags & PIN_MAPPABLE ? "mappable" : "total",
   4023 			  end);
   4024 		return ERR_PTR(-E2BIG);
   4025 	}
   4026 
   4027 	ret = i915_gem_object_get_pages(obj);
   4028 	if (ret)
   4029 		return ERR_PTR(ret);
   4030 
   4031 	i915_gem_object_pin_pages(obj);
   4032 
   4033 	vma = i915_gem_obj_lookup_or_create_vma(obj, vm);
   4034 	if (IS_ERR(vma))
   4035 		goto err_unpin;
   4036 
   4037 search_free:
   4038 	ret = drm_mm_insert_node_in_range_generic(&vm->mm, &vma->node,
   4039 						  size, alignment,
   4040 						  obj->cache_level,
   4041 						  start, end,
   4042 						  DRM_MM_SEARCH_DEFAULT,
   4043 						  DRM_MM_CREATE_DEFAULT);
   4044 	if (ret) {
   4045 		ret = i915_gem_evict_something(dev, vm, size, alignment,
   4046 					       obj->cache_level,
   4047 					       start, end,
   4048 					       flags);
   4049 		if (ret == 0)
   4050 			goto search_free;
   4051 
   4052 		goto err_free_vma;
   4053 	}
   4054 	if (WARN_ON(!i915_gem_valid_gtt_space(dev, &vma->node,
   4055 					      obj->cache_level))) {
   4056 		ret = -EINVAL;
   4057 		goto err_remove_node;
   4058 	}
   4059 
   4060 	ret = i915_gem_gtt_prepare_object(obj);
   4061 	if (ret)
   4062 		goto err_remove_node;
   4063 
   4064 	list_move_tail(&obj->global_list, &dev_priv->mm.bound_list);
   4065 	list_add_tail(&vma->mm_list, &vm->inactive_list);
   4066 
   4067 	if (i915_is_ggtt(vm)) {
   4068 		bool mappable, fenceable;
   4069 
   4070 		fenceable = (vma->node.size == fence_size &&
   4071 			     (vma->node.start & (fence_alignment - 1)) == 0);
   4072 
   4073 		mappable = (vma->node.start + obj->base.size <=
   4074 			    dev_priv->gtt.mappable_end);
   4075 
   4076 		obj->map_and_fenceable = mappable && fenceable;
   4077 	}
   4078 
   4079 	WARN_ON(flags & PIN_MAPPABLE && !obj->map_and_fenceable);
   4080 
   4081 	trace_i915_vma_bind(vma, flags);
   4082 	vma->bind_vma(vma, obj->cache_level,
   4083 		      flags & (PIN_MAPPABLE | PIN_GLOBAL) ? GLOBAL_BIND : 0);
   4084 
   4085 	i915_gem_verify_gtt(dev);
   4086 	return vma;
   4087 
   4088 err_remove_node:
   4089 	drm_mm_remove_node(&vma->node);
   4090 err_free_vma:
   4091 	i915_gem_vma_destroy(vma);
   4092 	vma = ERR_PTR(ret);
   4093 err_unpin:
   4094 	i915_gem_object_unpin_pages(obj);
   4095 	return vma;
   4096 }
   4097 
   4098 bool
   4099 i915_gem_clflush_object(struct drm_i915_gem_object *obj,
   4100 			bool force)
   4101 {
   4102 	/* If we don't have a page list set up, then we're not pinned
   4103 	 * to GPU, and we can ignore the cache flush because it'll happen
   4104 	 * again at bind time.
   4105 	 */
   4106 	if (obj->pages == NULL)
   4107 		return false;
   4108 
   4109 	/*
   4110 	 * Stolen memory is always coherent with the GPU as it is explicitly
   4111 	 * marked as wc by the system, or the system is cache-coherent.
   4112 	 */
   4113 	if (obj->stolen)
   4114 		return false;
   4115 
   4116 	/* If the GPU is snooping the contents of the CPU cache,
   4117 	 * we do not need to manually clear the CPU cache lines.  However,
   4118 	 * the caches are only snooped when the render cache is
   4119 	 * flushed/invalidated.  As we always have to emit invalidations
   4120 	 * and flushes when moving into and out of the RENDER domain, correct
   4121 	 * snooping behaviour occurs naturally as the result of our domain
   4122 	 * tracking.
   4123 	 */
   4124 	if (!force && cpu_cache_is_coherent(obj->base.dev, obj->cache_level))
   4125 		return false;
   4126 
   4127 	trace_i915_gem_object_clflush(obj);
   4128 #ifdef __NetBSD__
   4129 	drm_clflush_pglist(&obj->igo_pageq);
   4130 #else
   4131 	drm_clflush_sg(obj->pages);
   4132 #endif
   4133 
   4134 	return true;
   4135 }
   4136 
   4137 /** Flushes the GTT write domain for the object if it's dirty. */
   4138 static void
   4139 i915_gem_object_flush_gtt_write_domain(struct drm_i915_gem_object *obj)
   4140 {
   4141 	uint32_t old_write_domain;
   4142 
   4143 	if (obj->base.write_domain != I915_GEM_DOMAIN_GTT)
   4144 		return;
   4145 
   4146 	/* No actual flushing is required for the GTT write domain.  Writes
   4147 	 * to it immediately go to main memory as far as we know, so there's
   4148 	 * no chipset flush.  It also doesn't land in render cache.
   4149 	 *
   4150 	 * However, we do have to enforce the order so that all writes through
   4151 	 * the GTT land before any writes to the device, such as updates to
   4152 	 * the GATT itself.
   4153 	 */
   4154 	wmb();
   4155 
   4156 	old_write_domain = obj->base.write_domain;
   4157 	obj->base.write_domain = 0;
   4158 
   4159 	trace_i915_gem_object_change_domain(obj,
   4160 					    obj->base.read_domains,
   4161 					    old_write_domain);
   4162 }
   4163 
   4164 /** Flushes the CPU write domain for the object if it's dirty. */
   4165 static void
   4166 i915_gem_object_flush_cpu_write_domain(struct drm_i915_gem_object *obj,
   4167 				       bool force)
   4168 {
   4169 	uint32_t old_write_domain;
   4170 
   4171 	if (obj->base.write_domain != I915_GEM_DOMAIN_CPU)
   4172 		return;
   4173 
   4174 	if (i915_gem_clflush_object(obj, force))
   4175 		i915_gem_chipset_flush(obj->base.dev);
   4176 
   4177 	old_write_domain = obj->base.write_domain;
   4178 	obj->base.write_domain = 0;
   4179 
   4180 	trace_i915_gem_object_change_domain(obj,
   4181 					    obj->base.read_domains,
   4182 					    old_write_domain);
   4183 }
   4184 
   4185 /**
   4186  * Moves a single object to the GTT read, and possibly write domain.
   4187  *
   4188  * This function returns when the move is complete, including waiting on
   4189  * flushes to occur.
   4190  */
   4191 int
   4192 i915_gem_object_set_to_gtt_domain(struct drm_i915_gem_object *obj, bool write)
   4193 {
   4194 	struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
   4195 	uint32_t old_write_domain, old_read_domains;
   4196 	int ret;
   4197 
   4198 	/* Not valid to be called on unbound objects. */
   4199 	if (!i915_gem_obj_bound_any(obj))
   4200 		return -EINVAL;
   4201 
   4202 	if (obj->base.write_domain == I915_GEM_DOMAIN_GTT)
   4203 		return 0;
   4204 
   4205 	ret = i915_gem_object_wait_rendering(obj, !write);
   4206 	if (ret)
   4207 		return ret;
   4208 
   4209 	i915_gem_object_flush_cpu_write_domain(obj, false);
   4210 
   4211 	/* Serialise direct access to this object with the barriers for
   4212 	 * coherent writes from the GPU, by effectively invalidating the
   4213 	 * GTT domain upon first access.
   4214 	 */
   4215 	if ((obj->base.read_domains & I915_GEM_DOMAIN_GTT) == 0)
   4216 		mb();
   4217 
   4218 	old_write_domain = obj->base.write_domain;
   4219 	old_read_domains = obj->base.read_domains;
   4220 
   4221 	/* It should now be out of any other write domains, and we can update
   4222 	 * the domain values for our changes.
   4223 	 */
   4224 	BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_GTT) != 0);
   4225 	obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
   4226 	if (write) {
   4227 		obj->base.read_domains = I915_GEM_DOMAIN_GTT;
   4228 		obj->base.write_domain = I915_GEM_DOMAIN_GTT;
   4229 		obj->dirty = 1;
   4230 	}
   4231 
   4232 	trace_i915_gem_object_change_domain(obj,
   4233 					    old_read_domains,
   4234 					    old_write_domain);
   4235 
   4236 	/* And bump the LRU for this access */
   4237 	if (i915_gem_object_is_inactive(obj)) {
   4238 		struct i915_vma *vma = i915_gem_obj_to_ggtt(obj);
   4239 		if (vma)
   4240 			list_move_tail(&vma->mm_list,
   4241 				       &dev_priv->gtt.base.inactive_list);
   4242 
   4243 	}
   4244 
   4245 	return 0;
   4246 }
   4247 
   4248 int i915_gem_object_set_cache_level(struct drm_i915_gem_object *obj,
   4249 				    enum i915_cache_level cache_level)
   4250 {
   4251 	struct drm_device *dev = obj->base.dev;
   4252 	struct i915_vma *vma, *next;
   4253 	int ret;
   4254 
   4255 	if (obj->cache_level == cache_level)
   4256 		return 0;
   4257 
   4258 	if (i915_gem_obj_is_pinned(obj)) {
   4259 		DRM_DEBUG("can not change the cache level of pinned objects\n");
   4260 		return -EBUSY;
   4261 	}
   4262 
   4263 	list_for_each_entry_safe(vma, next, &obj->vma_list, vma_link) {
   4264 		if (!i915_gem_valid_gtt_space(dev, &vma->node, cache_level)) {
   4265 			ret = i915_vma_unbind(vma);
   4266 			if (ret)
   4267 				return ret;
   4268 		}
   4269 	}
   4270 
   4271 	if (i915_gem_obj_bound_any(obj)) {
   4272 		ret = i915_gem_object_finish_gpu(obj);
   4273 		if (ret)
   4274 			return ret;
   4275 
   4276 		i915_gem_object_finish_gtt(obj);
   4277 
   4278 		/* Before SandyBridge, you could not use tiling or fence
   4279 		 * registers with snooped memory, so relinquish any fences
   4280 		 * currently pointing to our region in the aperture.
   4281 		 */
   4282 		if (INTEL_INFO(dev)->gen < 6) {
   4283 			ret = i915_gem_object_put_fence(obj);
   4284 			if (ret)
   4285 				return ret;
   4286 		}
   4287 
   4288 		list_for_each_entry(vma, &obj->vma_list, vma_link)
   4289 			if (drm_mm_node_allocated(&vma->node))
   4290 				vma->bind_vma(vma, cache_level,
   4291 					      obj->has_global_gtt_mapping ? GLOBAL_BIND : 0);
   4292 	}
   4293 
   4294 	list_for_each_entry(vma, &obj->vma_list, vma_link)
   4295 		vma->node.color = cache_level;
   4296 	obj->cache_level = cache_level;
   4297 
   4298 	if (cpu_write_needs_clflush(obj)) {
   4299 		u32 old_read_domains, old_write_domain;
   4300 
   4301 		/* If we're coming from LLC cached, then we haven't
   4302 		 * actually been tracking whether the data is in the
   4303 		 * CPU cache or not, since we only allow one bit set
   4304 		 * in obj->write_domain and have been skipping the clflushes.
   4305 		 * Just set it to the CPU cache for now.
   4306 		 */
   4307 		WARN_ON(obj->base.write_domain & ~I915_GEM_DOMAIN_CPU);
   4308 
   4309 		old_read_domains = obj->base.read_domains;
   4310 		old_write_domain = obj->base.write_domain;
   4311 
   4312 		obj->base.read_domains = I915_GEM_DOMAIN_CPU;
   4313 		obj->base.write_domain = I915_GEM_DOMAIN_CPU;
   4314 
   4315 		trace_i915_gem_object_change_domain(obj,
   4316 						    old_read_domains,
   4317 						    old_write_domain);
   4318 	}
   4319 
   4320 	i915_gem_verify_gtt(dev);
   4321 	return 0;
   4322 }
   4323 
   4324 int i915_gem_get_caching_ioctl(struct drm_device *dev, void *data,
   4325 			       struct drm_file *file)
   4326 {
   4327 	struct drm_i915_gem_caching *args = data;
   4328 	struct drm_gem_object *gobj;
   4329 	struct drm_i915_gem_object *obj;
   4330 	int ret;
   4331 
   4332 	ret = i915_mutex_lock_interruptible(dev);
   4333 	if (ret)
   4334 		return ret;
   4335 
   4336 	gobj = drm_gem_object_lookup(dev, file, args->handle);
   4337 	if (gobj == NULL) {
   4338 		ret = -ENOENT;
   4339 		goto unlock;
   4340 	}
   4341 	obj = to_intel_bo(gobj);
   4342 
   4343 	switch (obj->cache_level) {
   4344 	case I915_CACHE_LLC:
   4345 	case I915_CACHE_L3_LLC:
   4346 		args->caching = I915_CACHING_CACHED;
   4347 		break;
   4348 
   4349 	case I915_CACHE_WT:
   4350 		args->caching = I915_CACHING_DISPLAY;
   4351 		break;
   4352 
   4353 	default:
   4354 		args->caching = I915_CACHING_NONE;
   4355 		break;
   4356 	}
   4357 
   4358 	drm_gem_object_unreference(&obj->base);
   4359 unlock:
   4360 	mutex_unlock(&dev->struct_mutex);
   4361 	return ret;
   4362 }
   4363 
   4364 int i915_gem_set_caching_ioctl(struct drm_device *dev, void *data,
   4365 			       struct drm_file *file)
   4366 {
   4367 	struct drm_i915_gem_caching *args = data;
   4368 	struct drm_gem_object *gobj;
   4369 	struct drm_i915_gem_object *obj;
   4370 	enum i915_cache_level level;
   4371 	int ret;
   4372 
   4373 	switch (args->caching) {
   4374 	case I915_CACHING_NONE:
   4375 		level = I915_CACHE_NONE;
   4376 		break;
   4377 	case I915_CACHING_CACHED:
   4378 		level = I915_CACHE_LLC;
   4379 		break;
   4380 	case I915_CACHING_DISPLAY:
   4381 		level = HAS_WT(dev) ? I915_CACHE_WT : I915_CACHE_NONE;
   4382 		break;
   4383 	default:
   4384 		return -EINVAL;
   4385 	}
   4386 
   4387 	ret = i915_mutex_lock_interruptible(dev);
   4388 	if (ret)
   4389 		return ret;
   4390 
   4391 	gobj = drm_gem_object_lookup(dev, file, args->handle);
   4392 	if (gobj == NULL) {
   4393 		ret = -ENOENT;
   4394 		goto unlock;
   4395 	}
   4396 	obj = to_intel_bo(gobj);
   4397 
   4398 	ret = i915_gem_object_set_cache_level(obj, level);
   4399 
   4400 	drm_gem_object_unreference(&obj->base);
   4401 unlock:
   4402 	mutex_unlock(&dev->struct_mutex);
   4403 	return ret;
   4404 }
   4405 
   4406 static bool is_pin_display(struct drm_i915_gem_object *obj)
   4407 {
   4408 	/* There are 3 sources that pin objects:
   4409 	 *   1. The display engine (scanouts, sprites, cursors);
   4410 	 *   2. Reservations for execbuffer;
   4411 	 *   3. The user.
   4412 	 *
   4413 	 * We can ignore reservations as we hold the struct_mutex and
   4414 	 * are only called outside of the reservation path.  The user
   4415 	 * can only increment pin_count once, and so if after
   4416 	 * subtracting the potential reference by the user, any pin_count
   4417 	 * remains, it must be due to another use by the display engine.
   4418 	 */
   4419 	return i915_gem_obj_to_ggtt(obj)->pin_count - !!obj->user_pin_count;
   4420 }
   4421 
   4422 /*
   4423  * Prepare buffer for display plane (scanout, cursors, etc).
   4424  * Can be called from an uninterruptible phase (modesetting) and allows
   4425  * any flushes to be pipelined (for pageflips).
   4426  */
   4427 int
   4428 i915_gem_object_pin_to_display_plane(struct drm_i915_gem_object *obj,
   4429 				     u32 alignment,
   4430 				     struct intel_ring_buffer *pipelined)
   4431 {
   4432 	u32 old_read_domains, old_write_domain;
   4433 	int ret;
   4434 
   4435 	if (pipelined != obj->ring) {
   4436 		ret = i915_gem_object_sync(obj, pipelined);
   4437 		if (ret)
   4438 			return ret;
   4439 	}
   4440 
   4441 	/* Mark the pin_display early so that we account for the
   4442 	 * display coherency whilst setting up the cache domains.
   4443 	 */
   4444 	obj->pin_display = true;
   4445 
   4446 	/* The display engine is not coherent with the LLC cache on gen6.  As
   4447 	 * a result, we make sure that the pinning that is about to occur is
   4448 	 * done with uncached PTEs. This is lowest common denominator for all
   4449 	 * chipsets.
   4450 	 *
   4451 	 * However for gen6+, we could do better by using the GFDT bit instead
   4452 	 * of uncaching, which would allow us to flush all the LLC-cached data
   4453 	 * with that bit in the PTE to main memory with just one PIPE_CONTROL.
   4454 	 */
   4455 	ret = i915_gem_object_set_cache_level(obj,
   4456 					      HAS_WT(obj->base.dev) ? I915_CACHE_WT : I915_CACHE_NONE);
   4457 	if (ret)
   4458 		goto err_unpin_display;
   4459 
   4460 	/* As the user may map the buffer once pinned in the display plane
   4461 	 * (e.g. libkms for the bootup splash), we have to ensure that we
   4462 	 * always use map_and_fenceable for all scanout buffers.
   4463 	 */
   4464 	ret = i915_gem_obj_ggtt_pin(obj, alignment, PIN_MAPPABLE);
   4465 	if (ret)
   4466 		goto err_unpin_display;
   4467 
   4468 	i915_gem_object_flush_cpu_write_domain(obj, true);
   4469 
   4470 	old_write_domain = obj->base.write_domain;
   4471 	old_read_domains = obj->base.read_domains;
   4472 
   4473 	/* It should now be out of any other write domains, and we can update
   4474 	 * the domain values for our changes.
   4475 	 */
   4476 	obj->base.write_domain = 0;
   4477 	obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
   4478 
   4479 	trace_i915_gem_object_change_domain(obj,
   4480 					    old_read_domains,
   4481 					    old_write_domain);
   4482 
   4483 	return 0;
   4484 
   4485 err_unpin_display:
   4486 	obj->pin_display = is_pin_display(obj);
   4487 	return ret;
   4488 }
   4489 
   4490 void
   4491 i915_gem_object_unpin_from_display_plane(struct drm_i915_gem_object *obj)
   4492 {
   4493 	i915_gem_object_ggtt_unpin(obj);
   4494 	obj->pin_display = is_pin_display(obj);
   4495 }
   4496 
   4497 int
   4498 i915_gem_object_finish_gpu(struct drm_i915_gem_object *obj)
   4499 {
   4500 	int ret;
   4501 
   4502 	if ((obj->base.read_domains & I915_GEM_GPU_DOMAINS) == 0)
   4503 		return 0;
   4504 
   4505 	ret = i915_gem_object_wait_rendering(obj, false);
   4506 	if (ret)
   4507 		return ret;
   4508 
   4509 	/* Ensure that we invalidate the GPU's caches and TLBs. */
   4510 	obj->base.read_domains &= ~I915_GEM_GPU_DOMAINS;
   4511 	return 0;
   4512 }
   4513 
   4514 /**
   4515  * Moves a single object to the CPU read, and possibly write domain.
   4516  *
   4517  * This function returns when the move is complete, including waiting on
   4518  * flushes to occur.
   4519  */
   4520 int
   4521 i915_gem_object_set_to_cpu_domain(struct drm_i915_gem_object *obj, bool write)
   4522 {
   4523 	uint32_t old_write_domain, old_read_domains;
   4524 	int ret;
   4525 
   4526 	if (obj->base.write_domain == I915_GEM_DOMAIN_CPU)
   4527 		return 0;
   4528 
   4529 	ret = i915_gem_object_wait_rendering(obj, !write);
   4530 	if (ret)
   4531 		return ret;
   4532 
   4533 	i915_gem_object_flush_gtt_write_domain(obj);
   4534 
   4535 	old_write_domain = obj->base.write_domain;
   4536 	old_read_domains = obj->base.read_domains;
   4537 
   4538 	/* Flush the CPU cache if it's still invalid. */
   4539 	if ((obj->base.read_domains & I915_GEM_DOMAIN_CPU) == 0) {
   4540 		i915_gem_clflush_object(obj, false);
   4541 
   4542 		obj->base.read_domains |= I915_GEM_DOMAIN_CPU;
   4543 	}
   4544 
   4545 	/* It should now be out of any other write domains, and we can update
   4546 	 * the domain values for our changes.
   4547 	 */
   4548 	BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_CPU) != 0);
   4549 
   4550 	/* If we're writing through the CPU, then the GPU read domains will
   4551 	 * need to be invalidated at next use.
   4552 	 */
   4553 	if (write) {
   4554 		obj->base.read_domains = I915_GEM_DOMAIN_CPU;
   4555 		obj->base.write_domain = I915_GEM_DOMAIN_CPU;
   4556 	}
   4557 
   4558 	trace_i915_gem_object_change_domain(obj,
   4559 					    old_read_domains,
   4560 					    old_write_domain);
   4561 
   4562 	return 0;
   4563 }
   4564 
   4565 /* Throttle our rendering by waiting until the ring has completed our requests
   4566  * emitted over 20 msec ago.
   4567  *
   4568  * Note that if we were to use the current jiffies each time around the loop,
   4569  * we wouldn't escape the function with any frames outstanding if the time to
   4570  * render a frame was over 20ms.
   4571  *
   4572  * This should get us reasonable parallelism between CPU and GPU but also
   4573  * relatively low latency when blocking on a particular request to finish.
   4574  */
   4575 static int
   4576 i915_gem_ring_throttle(struct drm_device *dev, struct drm_file *file)
   4577 {
   4578 	struct drm_i915_private *dev_priv = dev->dev_private;
   4579 	struct drm_i915_file_private *file_priv = file->driver_priv;
   4580 	unsigned long recent_enough = jiffies - msecs_to_jiffies(20);
   4581 	struct drm_i915_gem_request *request;
   4582 	struct intel_ring_buffer *ring = NULL;
   4583 	unsigned reset_counter;
   4584 	u32 seqno = 0;
   4585 	int ret;
   4586 
   4587 	ret = i915_gem_wait_for_error(&dev_priv->gpu_error);
   4588 	if (ret)
   4589 		return ret;
   4590 
   4591 	ret = i915_gem_check_wedge(&dev_priv->gpu_error, false);
   4592 	if (ret)
   4593 		return ret;
   4594 
   4595 	spin_lock(&file_priv->mm.lock);
   4596 	list_for_each_entry(request, &file_priv->mm.request_list, client_list) {
   4597 		if (time_after_eq(request->emitted_jiffies, recent_enough))
   4598 			break;
   4599 
   4600 		ring = request->ring;
   4601 		seqno = request->seqno;
   4602 	}
   4603 	reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
   4604 	spin_unlock(&file_priv->mm.lock);
   4605 
   4606 	if (seqno == 0)
   4607 		return 0;
   4608 
   4609 	ret = __wait_seqno(ring, seqno, reset_counter, true, NULL, NULL);
   4610 	if (ret == 0)
   4611 		queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work, 0);
   4612 
   4613 	return ret;
   4614 }
   4615 
   4616 static bool
   4617 i915_vma_misplaced(struct i915_vma *vma, uint32_t alignment, uint64_t flags)
   4618 {
   4619 	struct drm_i915_gem_object *obj = vma->obj;
   4620 
   4621 	if (alignment &&
   4622 	    vma->node.start & (alignment - 1))
   4623 		return true;
   4624 
   4625 	if (flags & PIN_MAPPABLE && !obj->map_and_fenceable)
   4626 		return true;
   4627 
   4628 	if (flags & PIN_OFFSET_BIAS &&
   4629 	    vma->node.start < (flags & PIN_OFFSET_MASK))
   4630 		return true;
   4631 
   4632 	return false;
   4633 }
   4634 
   4635 int
   4636 i915_gem_object_pin(struct drm_i915_gem_object *obj,
   4637 		    struct i915_address_space *vm,
   4638 		    uint32_t alignment,
   4639 		    uint64_t flags)
   4640 {
   4641 	struct i915_vma *vma;
   4642 	int ret;
   4643 
   4644 	if (WARN_ON(flags & (PIN_GLOBAL | PIN_MAPPABLE) && !i915_is_ggtt(vm)))
   4645 		return -EINVAL;
   4646 
   4647 	vma = i915_gem_obj_to_vma(obj, vm);
   4648 	if (vma) {
   4649 		if (WARN_ON(vma->pin_count == DRM_I915_GEM_OBJECT_MAX_PIN_COUNT))
   4650 			return -EBUSY;
   4651 
   4652 		if (i915_vma_misplaced(vma, alignment, flags)) {
   4653 			WARN(vma->pin_count,
   4654 			     "bo is already pinned with incorrect alignment:"
   4655 			     " offset=%lx, req.alignment=%x, req.map_and_fenceable=%d,"
   4656 			     " obj->map_and_fenceable=%d\n",
   4657 			     i915_gem_obj_offset(obj, vm), alignment,
   4658 			     !!(flags & PIN_MAPPABLE),
   4659 			     obj->map_and_fenceable);
   4660 			ret = i915_vma_unbind(vma);
   4661 			if (ret)
   4662 				return ret;
   4663 
   4664 			vma = NULL;
   4665 		}
   4666 	}
   4667 
   4668 	if (vma == NULL || !drm_mm_node_allocated(&vma->node)) {
   4669 		vma = i915_gem_object_bind_to_vm(obj, vm, alignment, flags);
   4670 		if (IS_ERR(vma))
   4671 			return PTR_ERR(vma);
   4672 	}
   4673 
   4674 	if (flags & PIN_GLOBAL && !obj->has_global_gtt_mapping)
   4675 		vma->bind_vma(vma, obj->cache_level, GLOBAL_BIND);
   4676 
   4677 	vma->pin_count++;
   4678 	if (flags & PIN_MAPPABLE)
   4679 		obj->pin_mappable |= true;
   4680 
   4681 	return 0;
   4682 }
   4683 
   4684 void
   4685 i915_gem_object_ggtt_unpin(struct drm_i915_gem_object *obj)
   4686 {
   4687 	struct i915_vma *vma = i915_gem_obj_to_ggtt(obj);
   4688 
   4689 	BUG_ON(!vma);
   4690 	BUG_ON(vma->pin_count == 0);
   4691 	BUG_ON(!i915_gem_obj_ggtt_bound(obj));
   4692 
   4693 	if (--vma->pin_count == 0)
   4694 		obj->pin_mappable = false;
   4695 }
   4696 
   4697 int
   4698 i915_gem_pin_ioctl(struct drm_device *dev, void *data,
   4699 		   struct drm_file *file)
   4700 {
   4701 	struct drm_i915_gem_pin *args = data;
   4702 	struct drm_gem_object *gobj;
   4703 	struct drm_i915_gem_object *obj;
   4704 	int ret;
   4705 
   4706 	if (INTEL_INFO(dev)->gen >= 6)
   4707 		return -ENODEV;
   4708 
   4709 	ret = i915_mutex_lock_interruptible(dev);
   4710 	if (ret)
   4711 		return ret;
   4712 
   4713 	gobj = drm_gem_object_lookup(dev, file, args->handle);
   4714 	if (gobj == NULL) {
   4715 		ret = -ENOENT;
   4716 		goto unlock;
   4717 	}
   4718 	obj = to_intel_bo(gobj);
   4719 
   4720 	if (obj->madv != I915_MADV_WILLNEED) {
   4721 		DRM_DEBUG("Attempting to pin a purgeable buffer\n");
   4722 		ret = -EFAULT;
   4723 		goto out;
   4724 	}
   4725 
   4726 	if (obj->pin_filp != NULL && obj->pin_filp != file) {
   4727 		DRM_DEBUG("Already pinned in i915_gem_pin_ioctl(): %d\n",
   4728 			  args->handle);
   4729 		ret = -EINVAL;
   4730 		goto out;
   4731 	}
   4732 
   4733 	if (obj->user_pin_count == ULONG_MAX) {
   4734 		ret = -EBUSY;
   4735 		goto out;
   4736 	}
   4737 
   4738 	if (obj->user_pin_count == 0) {
   4739 		ret = i915_gem_obj_ggtt_pin(obj, args->alignment, PIN_MAPPABLE);
   4740 		if (ret)
   4741 			goto out;
   4742 	}
   4743 
   4744 	obj->user_pin_count++;
   4745 	obj->pin_filp = file;
   4746 
   4747 	args->offset = i915_gem_obj_ggtt_offset(obj);
   4748 out:
   4749 	drm_gem_object_unreference(&obj->base);
   4750 unlock:
   4751 	mutex_unlock(&dev->struct_mutex);
   4752 	return ret;
   4753 }
   4754 
   4755 int
   4756 i915_gem_unpin_ioctl(struct drm_device *dev, void *data,
   4757 		     struct drm_file *file)
   4758 {
   4759 	struct drm_i915_gem_pin *args = data;
   4760 	struct drm_gem_object *gobj;
   4761 	struct drm_i915_gem_object *obj;
   4762 	int ret;
   4763 
   4764 	ret = i915_mutex_lock_interruptible(dev);
   4765 	if (ret)
   4766 		return ret;
   4767 
   4768 	gobj = drm_gem_object_lookup(dev, file, args->handle);
   4769 	if (gobj == NULL) {
   4770 		ret = -ENOENT;
   4771 		goto unlock;
   4772 	}
   4773 	obj = to_intel_bo(gobj);
   4774 
   4775 	if (obj->pin_filp != file) {
   4776 		DRM_DEBUG("Not pinned by caller in i915_gem_pin_ioctl(): %d\n",
   4777 			  args->handle);
   4778 		ret = -EINVAL;
   4779 		goto out;
   4780 	}
   4781 	obj->user_pin_count--;
   4782 	if (obj->user_pin_count == 0) {
   4783 		obj->pin_filp = NULL;
   4784 		i915_gem_object_ggtt_unpin(obj);
   4785 	}
   4786 
   4787 out:
   4788 	drm_gem_object_unreference(&obj->base);
   4789 unlock:
   4790 	mutex_unlock(&dev->struct_mutex);
   4791 	return ret;
   4792 }
   4793 
   4794 int
   4795 i915_gem_busy_ioctl(struct drm_device *dev, void *data,
   4796 		    struct drm_file *file)
   4797 {
   4798 	struct drm_i915_gem_busy *args = data;
   4799 	struct drm_gem_object *gobj;
   4800 	struct drm_i915_gem_object *obj;
   4801 	int ret;
   4802 
   4803 	ret = i915_mutex_lock_interruptible(dev);
   4804 	if (ret)
   4805 		return ret;
   4806 
   4807 	gobj = drm_gem_object_lookup(dev, file, args->handle);
   4808 	if (gobj == NULL) {
   4809 		ret = -ENOENT;
   4810 		goto unlock;
   4811 	}
   4812 	obj = to_intel_bo(gobj);
   4813 
   4814 	/* Count all active objects as busy, even if they are currently not used
   4815 	 * by the gpu. Users of this interface expect objects to eventually
   4816 	 * become non-busy without any further actions, therefore emit any
   4817 	 * necessary flushes here.
   4818 	 */
   4819 	ret = i915_gem_object_flush_active(obj);
   4820 
   4821 	args->busy = obj->active;
   4822 	if (obj->ring) {
   4823 		BUILD_BUG_ON(I915_NUM_RINGS > 16);
   4824 		args->busy |= intel_ring_flag(obj->ring) << 16;
   4825 	}
   4826 
   4827 	drm_gem_object_unreference(&obj->base);
   4828 unlock:
   4829 	mutex_unlock(&dev->struct_mutex);
   4830 	return ret;
   4831 }
   4832 
   4833 int
   4834 i915_gem_throttle_ioctl(struct drm_device *dev, void *data,
   4835 			struct drm_file *file_priv)
   4836 {
   4837 	return i915_gem_ring_throttle(dev, file_priv);
   4838 }
   4839 
   4840 int
   4841 i915_gem_madvise_ioctl(struct drm_device *dev, void *data,
   4842 		       struct drm_file *file_priv)
   4843 {
   4844 	struct drm_i915_gem_madvise *args = data;
   4845 	struct drm_gem_object *gobj;
   4846 	struct drm_i915_gem_object *obj;
   4847 	int ret;
   4848 
   4849 	switch (args->madv) {
   4850 	case I915_MADV_DONTNEED:
   4851 	case I915_MADV_WILLNEED:
   4852 	    break;
   4853 	default:
   4854 	    return -EINVAL;
   4855 	}
   4856 
   4857 	ret = i915_mutex_lock_interruptible(dev);
   4858 	if (ret)
   4859 		return ret;
   4860 
   4861 	gobj = drm_gem_object_lookup(dev, file_priv, args->handle);
   4862 	if (gobj == NULL) {
   4863 		ret = -ENOENT;
   4864 		goto unlock;
   4865 	}
   4866 	obj = to_intel_bo(gobj);
   4867 
   4868 	if (i915_gem_obj_is_pinned(obj)) {
   4869 		ret = -EINVAL;
   4870 		goto out;
   4871 	}
   4872 
   4873 	if (obj->madv != __I915_MADV_PURGED)
   4874 		obj->madv = args->madv;
   4875 
   4876 	/* if the object is no longer attached, discard its backing storage */
   4877 	if (i915_gem_object_is_purgeable(obj) && obj->pages == NULL)
   4878 		i915_gem_object_truncate(obj);
   4879 
   4880 	args->retained = obj->madv != __I915_MADV_PURGED;
   4881 
   4882 out:
   4883 	drm_gem_object_unreference(&obj->base);
   4884 unlock:
   4885 	mutex_unlock(&dev->struct_mutex);
   4886 	return ret;
   4887 }
   4888 
   4889 void i915_gem_object_init(struct drm_i915_gem_object *obj,
   4890 			  const struct drm_i915_gem_object_ops *ops)
   4891 {
   4892 	INIT_LIST_HEAD(&obj->global_list);
   4893 	INIT_LIST_HEAD(&obj->ring_list);
   4894 	INIT_LIST_HEAD(&obj->obj_exec_link);
   4895 	INIT_LIST_HEAD(&obj->vma_list);
   4896 
   4897 	obj->ops = ops;
   4898 
   4899 	obj->fence_reg = I915_FENCE_REG_NONE;
   4900 	obj->madv = I915_MADV_WILLNEED;
   4901 	/* Avoid an unnecessary call to unbind on the first bind. */
   4902 	obj->map_and_fenceable = true;
   4903 
   4904 	i915_gem_info_add_obj(obj->base.dev->dev_private, obj->base.size);
   4905 }
   4906 
   4907 static const struct drm_i915_gem_object_ops i915_gem_object_ops = {
   4908 	.get_pages = i915_gem_object_get_pages_gtt,
   4909 	.put_pages = i915_gem_object_put_pages_gtt,
   4910 };
   4911 
   4912 struct drm_i915_gem_object *i915_gem_alloc_object(struct drm_device *dev,
   4913 						  size_t size)
   4914 {
   4915 #ifdef __NetBSD__
   4916 	struct drm_i915_private *const dev_priv = dev->dev_private;
   4917 #endif
   4918 	struct drm_i915_gem_object *obj;
   4919 #ifndef __NetBSD__
   4920 	struct address_space *mapping;
   4921 	gfp_t mask;
   4922 #endif
   4923 
   4924 	obj = i915_gem_object_alloc(dev);
   4925 	if (obj == NULL)
   4926 		return NULL;
   4927 
   4928 	if (drm_gem_object_init(dev, &obj->base, size) != 0) {
   4929 		i915_gem_object_free(obj);
   4930 		return NULL;
   4931 	}
   4932 
   4933 #ifdef __NetBSD__
   4934 	uao_set_pgfl(obj->base.gemo_shm_uao, dev_priv->gtt.pgfl);
   4935 #else
   4936 	mask = GFP_HIGHUSER | __GFP_RECLAIMABLE;
   4937 	if (IS_CRESTLINE(dev) || IS_BROADWATER(dev)) {
   4938 		/* 965gm cannot relocate objects above 4GiB. */
   4939 		mask &= ~__GFP_HIGHMEM;
   4940 		mask |= __GFP_DMA32;
   4941 	}
   4942 
   4943 	mapping = file_inode(obj->base.filp)->i_mapping;
   4944 	mapping_set_gfp_mask(mapping, mask);
   4945 #endif
   4946 
   4947 	i915_gem_object_init(obj, &i915_gem_object_ops);
   4948 
   4949 	obj->base.write_domain = I915_GEM_DOMAIN_CPU;
   4950 	obj->base.read_domains = I915_GEM_DOMAIN_CPU;
   4951 
   4952 	if (HAS_LLC(dev)) {
   4953 		/* On some devices, we can have the GPU use the LLC (the CPU
   4954 		 * cache) for about a 10% performance improvement
   4955 		 * compared to uncached.  Graphics requests other than
   4956 		 * display scanout are coherent with the CPU in
   4957 		 * accessing this cache.  This means in this mode we
   4958 		 * don't need to clflush on the CPU side, and on the
   4959 		 * GPU side we only need to flush internal caches to
   4960 		 * get data visible to the CPU.
   4961 		 *
   4962 		 * However, we maintain the display planes as UC, and so
   4963 		 * need to rebind when first used as such.
   4964 		 */
   4965 		obj->cache_level = I915_CACHE_LLC;
   4966 	} else
   4967 		obj->cache_level = I915_CACHE_NONE;
   4968 
   4969 	trace_i915_gem_object_create(obj);
   4970 
   4971 	return obj;
   4972 }
   4973 
   4974 void i915_gem_free_object(struct drm_gem_object *gem_obj)
   4975 {
   4976 	struct drm_i915_gem_object *obj = to_intel_bo(gem_obj);
   4977 	struct drm_device *dev = obj->base.dev;
   4978 	struct drm_i915_private *dev_priv = dev->dev_private;
   4979 	struct i915_vma *vma, *next;
   4980 
   4981 	intel_runtime_pm_get(dev_priv);
   4982 
   4983 	trace_i915_gem_object_destroy(obj);
   4984 
   4985 	list_for_each_entry_safe(vma, next, &obj->vma_list, vma_link) {
   4986 		int ret;
   4987 
   4988 		vma->pin_count = 0;
   4989 		ret = i915_vma_unbind(vma);
   4990 		if (WARN_ON(ret == -ERESTARTSYS)) {
   4991 			bool was_interruptible;
   4992 
   4993 			was_interruptible = dev_priv->mm.interruptible;
   4994 			dev_priv->mm.interruptible = false;
   4995 
   4996 			WARN_ON(i915_vma_unbind(vma));
   4997 
   4998 			dev_priv->mm.interruptible = was_interruptible;
   4999 		}
   5000 	}
   5001 
   5002 	i915_gem_object_detach_phys(obj);
   5003 
   5004 	/* Stolen objects don't hold a ref, but do hold pin count. Fix that up
   5005 	 * before progressing. */
   5006 	if (obj->stolen)
   5007 		i915_gem_object_unpin_pages(obj);
   5008 
   5009 	if (WARN_ON(obj->pages_pin_count))
   5010 		obj->pages_pin_count = 0;
   5011 	i915_gem_object_put_pages(obj);
   5012 	i915_gem_object_free_mmap_offset(obj);
   5013 	i915_gem_object_release_stolen(obj);
   5014 
   5015 	BUG_ON(obj->pages);
   5016 
   5017 #ifndef __NetBSD__		/* XXX drm prime */
   5018 	if (obj->base.import_attach)
   5019 		drm_prime_gem_destroy(&obj->base, NULL);
   5020 #endif
   5021 
   5022 	drm_gem_object_release(&obj->base);
   5023 	i915_gem_info_remove_obj(dev_priv, obj->base.size);
   5024 
   5025 	kfree(obj->bit_17);
   5026 	i915_gem_object_free(obj);
   5027 
   5028 	intel_runtime_pm_put(dev_priv);
   5029 }
   5030 
   5031 struct i915_vma *i915_gem_obj_to_vma(struct drm_i915_gem_object *obj,
   5032 				     struct i915_address_space *vm)
   5033 {
   5034 	struct i915_vma *vma;
   5035 	list_for_each_entry(vma, &obj->vma_list, vma_link)
   5036 		if (vma->vm == vm)
   5037 			return vma;
   5038 
   5039 	return NULL;
   5040 }
   5041 
   5042 void i915_gem_vma_destroy(struct i915_vma *vma)
   5043 {
   5044 	WARN_ON(vma->node.allocated);
   5045 
   5046 	/* Keep the vma as a placeholder in the execbuffer reservation lists */
   5047 	if (!list_empty(&vma->exec_list))
   5048 		return;
   5049 
   5050 	list_del(&vma->vma_link);
   5051 
   5052 	kfree(vma);
   5053 }
   5054 
   5055 int
   5056 i915_gem_suspend(struct drm_device *dev)
   5057 {
   5058 	struct drm_i915_private *dev_priv = dev->dev_private;
   5059 	int ret = 0;
   5060 
   5061 	mutex_lock(&dev->struct_mutex);
   5062 	if (dev_priv->ums.mm_suspended)
   5063 		goto err;
   5064 
   5065 	ret = i915_gpu_idle(dev);
   5066 	if (ret)
   5067 		goto err;
   5068 
   5069 	i915_gem_retire_requests(dev);
   5070 
   5071 	/* Under UMS, be paranoid and evict. */
   5072 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
   5073 		i915_gem_evict_everything(dev);
   5074 
   5075 	i915_kernel_lost_context(dev);
   5076 	i915_gem_cleanup_ringbuffer(dev);
   5077 
   5078 	/* Hack!  Don't let anybody do execbuf while we don't control the chip.
   5079 	 * We need to replace this with a semaphore, or something.
   5080 	 * And not confound ums.mm_suspended!
   5081 	 */
   5082 	dev_priv->ums.mm_suspended = !drm_core_check_feature(dev,
   5083 							     DRIVER_MODESET);
   5084 	mutex_unlock(&dev->struct_mutex);
   5085 
   5086 	del_timer_sync(&dev_priv->gpu_error.hangcheck_timer);
   5087 	cancel_delayed_work_sync(&dev_priv->mm.retire_work);
   5088 	cancel_delayed_work_sync(&dev_priv->mm.idle_work);
   5089 
   5090 	return 0;
   5091 
   5092 err:
   5093 	mutex_unlock(&dev->struct_mutex);
   5094 	return ret;
   5095 }
   5096 
   5097 int i915_gem_l3_remap(struct intel_ring_buffer *ring, int slice)
   5098 {
   5099 	struct drm_device *dev = ring->dev;
   5100 	struct drm_i915_private *dev_priv = dev->dev_private;
   5101 	u32 reg_base = GEN7_L3LOG_BASE + (slice * 0x200);
   5102 	u32 *remap_info = dev_priv->l3_parity.remap_info[slice];
   5103 	int i, ret;
   5104 
   5105 	if (!HAS_L3_DPF(dev) || !remap_info)
   5106 		return 0;
   5107 
   5108 	ret = intel_ring_begin(ring, GEN7_L3LOG_SIZE / 4 * 3);
   5109 	if (ret)
   5110 		return ret;
   5111 
   5112 	/*
   5113 	 * Note: We do not worry about the concurrent register cacheline hang
   5114 	 * here because no other code should access these registers other than
   5115 	 * at initialization time.
   5116 	 */
   5117 	for (i = 0; i < GEN7_L3LOG_SIZE; i += 4) {
   5118 		intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
   5119 		intel_ring_emit(ring, reg_base + i);
   5120 		intel_ring_emit(ring, remap_info[i/4]);
   5121 	}
   5122 
   5123 	intel_ring_advance(ring);
   5124 
   5125 	return ret;
   5126 }
   5127 
   5128 void i915_gem_init_swizzling(struct drm_device *dev)
   5129 {
   5130 	struct drm_i915_private *dev_priv = dev->dev_private;
   5131 
   5132 	if (INTEL_INFO(dev)->gen < 5 ||
   5133 	    dev_priv->mm.bit_6_swizzle_x == I915_BIT_6_SWIZZLE_NONE)
   5134 		return;
   5135 
   5136 	I915_WRITE(DISP_ARB_CTL, I915_READ(DISP_ARB_CTL) |
   5137 				 DISP_TILE_SURFACE_SWIZZLING);
   5138 
   5139 	if (IS_GEN5(dev))
   5140 		return;
   5141 
   5142 	I915_WRITE(TILECTL, I915_READ(TILECTL) | TILECTL_SWZCTL);
   5143 	if (IS_GEN6(dev))
   5144 		I915_WRITE(ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_SNB));
   5145 	else if (IS_GEN7(dev))
   5146 		I915_WRITE(ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_IVB));
   5147 	else if (IS_GEN8(dev))
   5148 		I915_WRITE(GAMTARBMODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_BDW));
   5149 	else
   5150 		BUG();
   5151 }
   5152 
   5153 static bool
   5154 intel_enable_blt(struct drm_device *dev)
   5155 {
   5156 	if (!HAS_BLT(dev))
   5157 		return false;
   5158 
   5159 	/* The blitter was dysfunctional on early prototypes */
   5160 	if (IS_GEN6(dev) && dev->pdev->revision < 8) {
   5161 		DRM_INFO("BLT not supported on this pre-production hardware;"
   5162 			 " graphics performance will be degraded.\n");
   5163 		return false;
   5164 	}
   5165 
   5166 	return true;
   5167 }
   5168 
   5169 static int i915_gem_init_rings(struct drm_device *dev)
   5170 {
   5171 	struct drm_i915_private *dev_priv = dev->dev_private;
   5172 	int ret;
   5173 
   5174 	ret = intel_init_render_ring_buffer(dev);
   5175 	if (ret)
   5176 		return ret;
   5177 
   5178 	if (HAS_BSD(dev)) {
   5179 		ret = intel_init_bsd_ring_buffer(dev);
   5180 		if (ret)
   5181 			goto cleanup_render_ring;
   5182 	}
   5183 
   5184 	if (intel_enable_blt(dev)) {
   5185 		ret = intel_init_blt_ring_buffer(dev);
   5186 		if (ret)
   5187 			goto cleanup_bsd_ring;
   5188 	}
   5189 
   5190 	if (HAS_VEBOX(dev)) {
   5191 		ret = intel_init_vebox_ring_buffer(dev);
   5192 		if (ret)
   5193 			goto cleanup_blt_ring;
   5194 	}
   5195 
   5196 
   5197 	ret = i915_gem_set_seqno(dev, ((u32)~0 - 0x1000));
   5198 	if (ret)
   5199 		goto cleanup_vebox_ring;
   5200 
   5201 	return 0;
   5202 
   5203 cleanup_vebox_ring:
   5204 	intel_cleanup_ring_buffer(&dev_priv->ring[VECS]);
   5205 cleanup_blt_ring:
   5206 	intel_cleanup_ring_buffer(&dev_priv->ring[BCS]);
   5207 cleanup_bsd_ring:
   5208 	intel_cleanup_ring_buffer(&dev_priv->ring[VCS]);
   5209 cleanup_render_ring:
   5210 	intel_cleanup_ring_buffer(&dev_priv->ring[RCS]);
   5211 
   5212 	return ret;
   5213 }
   5214 
   5215 int
   5216 i915_gem_init_hw(struct drm_device *dev)
   5217 {
   5218 	struct drm_i915_private *dev_priv = dev->dev_private;
   5219 	int ret, i;
   5220 
   5221 	if (INTEL_INFO(dev)->gen < 6 && !intel_enable_gtt())
   5222 		return -EIO;
   5223 
   5224 	if (dev_priv->ellc_size)
   5225 		I915_WRITE(HSW_IDICR, I915_READ(HSW_IDICR) | IDIHASHMSK(0xf));
   5226 
   5227 	if (IS_HASWELL(dev))
   5228 		I915_WRITE(MI_PREDICATE_RESULT_2, IS_HSW_GT3(dev) ?
   5229 			   LOWER_SLICE_ENABLED : LOWER_SLICE_DISABLED);
   5230 
   5231 	if (HAS_PCH_NOP(dev)) {
   5232 		if (IS_IVYBRIDGE(dev)) {
   5233 			u32 temp = I915_READ(GEN7_MSG_CTL);
   5234 			temp &= ~(WAIT_FOR_PCH_FLR_ACK | WAIT_FOR_PCH_RESET_ACK);
   5235 			I915_WRITE(GEN7_MSG_CTL, temp);
   5236 		} else if (INTEL_INFO(dev)->gen >= 7) {
   5237 			u32 temp = I915_READ(HSW_NDE_RSTWRN_OPT);
   5238 			temp &= ~RESET_PCH_HANDSHAKE_ENABLE;
   5239 			I915_WRITE(HSW_NDE_RSTWRN_OPT, temp);
   5240 		}
   5241 	}
   5242 
   5243 	i915_gem_init_swizzling(dev);
   5244 
   5245 	ret = i915_gem_init_rings(dev);
   5246 	if (ret)
   5247 		return ret;
   5248 
   5249 	for (i = 0; i < NUM_L3_SLICES(dev); i++)
   5250 		i915_gem_l3_remap(&dev_priv->ring[RCS], i);
   5251 
   5252 	/*
   5253 	 * XXX: Contexts should only be initialized once. Doing a switch to the
   5254 	 * default context switch however is something we'd like to do after
   5255 	 * reset or thaw (the latter may not actually be necessary for HW, but
   5256 	 * goes with our code better). Context switching requires rings (for
   5257 	 * the do_switch), but before enabling PPGTT. So don't move this.
   5258 	 */
   5259 	ret = i915_gem_context_enable(dev_priv);
   5260 	if (ret) {
   5261 		DRM_ERROR("Context enable failed %d\n", ret);
   5262 		goto err_out;
   5263 	}
   5264 
   5265 	return 0;
   5266 
   5267 err_out:
   5268 	i915_gem_cleanup_ringbuffer(dev);
   5269 	return ret;
   5270 }
   5271 
   5272 int i915_gem_init(struct drm_device *dev)
   5273 {
   5274 	struct drm_i915_private *dev_priv = dev->dev_private;
   5275 	int ret;
   5276 
   5277 	mutex_lock(&dev->struct_mutex);
   5278 
   5279 	if (IS_VALLEYVIEW(dev)) {
   5280 		/* VLVA0 (potential hack), BIOS isn't actually waking us */
   5281 		I915_WRITE(VLV_GTLC_WAKE_CTRL, 1);
   5282 		if (wait_for((I915_READ(VLV_GTLC_PW_STATUS) & 1) == 1, 10))
   5283 			DRM_DEBUG_DRIVER("allow wake ack timed out\n");
   5284 	}
   5285 	i915_gem_init_global_gtt(dev);
   5286 
   5287 	ret = i915_gem_context_init(dev);
   5288 	if (ret) {
   5289 		mutex_unlock(&dev->struct_mutex);
   5290 		return ret;
   5291 	}
   5292 
   5293 	ret = i915_gem_init_hw(dev);
   5294 	mutex_unlock(&dev->struct_mutex);
   5295 	if (ret) {
   5296 		WARN_ON(dev_priv->mm.aliasing_ppgtt);
   5297 		i915_gem_context_fini(dev);
   5298 		drm_mm_takedown(&dev_priv->gtt.base.mm);
   5299 		return ret;
   5300 	}
   5301 
   5302 	/* Allow hardware batchbuffers unless told otherwise, but not for KMS. */
   5303 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
   5304 		dev_priv->dri1.allow_batchbuffer = 1;
   5305 	return 0;
   5306 }
   5307 
   5308 void
   5309 i915_gem_cleanup_ringbuffer(struct drm_device *dev)
   5310 {
   5311 	struct drm_i915_private *dev_priv = dev->dev_private;
   5312 	struct intel_ring_buffer *ring;
   5313 	int i;
   5314 
   5315 	for_each_ring(ring, dev_priv, i)
   5316 		intel_cleanup_ring_buffer(ring);
   5317 }
   5318 
   5319 int
   5320 i915_gem_entervt_ioctl(struct drm_device *dev, void *data,
   5321 		       struct drm_file *file_priv)
   5322 {
   5323 	struct drm_i915_private *dev_priv = dev->dev_private;
   5324 	int ret;
   5325 
   5326 	if (drm_core_check_feature(dev, DRIVER_MODESET))
   5327 		return 0;
   5328 
   5329 	if (i915_reset_in_progress(&dev_priv->gpu_error)) {
   5330 		DRM_ERROR("Reenabling wedged hardware, good luck\n");
   5331 		atomic_set(&dev_priv->gpu_error.reset_counter, 0);
   5332 	}
   5333 
   5334 	mutex_lock(&dev->struct_mutex);
   5335 	dev_priv->ums.mm_suspended = 0;
   5336 
   5337 	ret = i915_gem_init_hw(dev);
   5338 	if (ret != 0) {
   5339 		mutex_unlock(&dev->struct_mutex);
   5340 		return ret;
   5341 	}
   5342 
   5343 	BUG_ON(!list_empty(&dev_priv->gtt.base.active_list));
   5344 	mutex_unlock(&dev->struct_mutex);
   5345 
   5346 	ret = drm_irq_install(dev);
   5347 	if (ret)
   5348 		goto cleanup_ringbuffer;
   5349 
   5350 	return 0;
   5351 
   5352 cleanup_ringbuffer:
   5353 	mutex_lock(&dev->struct_mutex);
   5354 	i915_gem_cleanup_ringbuffer(dev);
   5355 	dev_priv->ums.mm_suspended = 1;
   5356 	mutex_unlock(&dev->struct_mutex);
   5357 
   5358 	return ret;
   5359 }
   5360 
   5361 int
   5362 i915_gem_leavevt_ioctl(struct drm_device *dev, void *data,
   5363 		       struct drm_file *file_priv)
   5364 {
   5365 	if (drm_core_check_feature(dev, DRIVER_MODESET))
   5366 		return 0;
   5367 
   5368 	drm_irq_uninstall(dev);
   5369 
   5370 	return i915_gem_suspend(dev);
   5371 }
   5372 
   5373 void
   5374 i915_gem_lastclose(struct drm_device *dev)
   5375 {
   5376 	int ret;
   5377 
   5378 	if (drm_core_check_feature(dev, DRIVER_MODESET))
   5379 		return;
   5380 
   5381 	ret = i915_gem_suspend(dev);
   5382 	if (ret)
   5383 		DRM_ERROR("failed to idle hardware: %d\n", ret);
   5384 }
   5385 
   5386 static void
   5387 init_ring_lists(struct intel_ring_buffer *ring)
   5388 {
   5389 	INIT_LIST_HEAD(&ring->active_list);
   5390 	INIT_LIST_HEAD(&ring->request_list);
   5391 }
   5392 
   5393 void i915_init_vm(struct drm_i915_private *dev_priv,
   5394 		  struct i915_address_space *vm)
   5395 {
   5396 	if (!i915_is_ggtt(vm))
   5397 		drm_mm_init(&vm->mm, vm->start, vm->total);
   5398 	vm->dev = dev_priv->dev;
   5399 	INIT_LIST_HEAD(&vm->active_list);
   5400 	INIT_LIST_HEAD(&vm->inactive_list);
   5401 	INIT_LIST_HEAD(&vm->global_link);
   5402 	list_add_tail(&vm->global_link, &dev_priv->vm_list);
   5403 }
   5404 
   5405 void
   5406 i915_gem_load(struct drm_device *dev)
   5407 {
   5408 	struct drm_i915_private *dev_priv = dev->dev_private;
   5409 	int i;
   5410 
   5411 	dev_priv->slab =
   5412 		kmem_cache_create("i915_gem_object",
   5413 				  sizeof(struct drm_i915_gem_object), 0,
   5414 				  SLAB_HWCACHE_ALIGN,
   5415 				  NULL);
   5416 
   5417 	INIT_LIST_HEAD(&dev_priv->vm_list);
   5418 	i915_init_vm(dev_priv, &dev_priv->gtt.base);
   5419 
   5420 	INIT_LIST_HEAD(&dev_priv->context_list);
   5421 	INIT_LIST_HEAD(&dev_priv->mm.unbound_list);
   5422 	INIT_LIST_HEAD(&dev_priv->mm.bound_list);
   5423 	INIT_LIST_HEAD(&dev_priv->mm.fence_list);
   5424 	for (i = 0; i < I915_NUM_RINGS; i++)
   5425 		init_ring_lists(&dev_priv->ring[i]);
   5426 	for (i = 0; i < I915_MAX_NUM_FENCES; i++)
   5427 		INIT_LIST_HEAD(&dev_priv->fence_regs[i].lru_list);
   5428 	INIT_DELAYED_WORK(&dev_priv->mm.retire_work,
   5429 			  i915_gem_retire_work_handler);
   5430 	INIT_DELAYED_WORK(&dev_priv->mm.idle_work,
   5431 			  i915_gem_idle_work_handler);
   5432 #ifdef __NetBSD__
   5433 	spin_lock_init(&dev_priv->gpu_error.reset_lock);
   5434 	DRM_INIT_WAITQUEUE(&dev_priv->gpu_error.reset_queue, "i915errst");
   5435 #else
   5436 	init_waitqueue_head(&dev_priv->gpu_error.reset_queue);
   5437 #endif
   5438 
   5439 	/* On GEN3 we really need to make sure the ARB C3 LP bit is set */
   5440 	if (IS_GEN3(dev)) {
   5441 		I915_WRITE(MI_ARB_STATE,
   5442 			   _MASKED_BIT_ENABLE(MI_ARB_C3_LP_WRITE_ENABLE));
   5443 	}
   5444 
   5445 	dev_priv->relative_constants_mode = I915_EXEC_CONSTANTS_REL_GENERAL;
   5446 
   5447 	/* Old X drivers will take 0-2 for front, back, depth buffers */
   5448 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
   5449 		dev_priv->fence_reg_start = 3;
   5450 
   5451 	if (INTEL_INFO(dev)->gen >= 7 && !IS_VALLEYVIEW(dev))
   5452 		dev_priv->num_fence_regs = 32;
   5453 	else if (INTEL_INFO(dev)->gen >= 4 || IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev))
   5454 		dev_priv->num_fence_regs = 16;
   5455 	else
   5456 		dev_priv->num_fence_regs = 8;
   5457 
   5458 	/* Initialize fence registers to zero */
   5459 	INIT_LIST_HEAD(&dev_priv->mm.fence_list);
   5460 	i915_gem_restore_fences(dev);
   5461 
   5462 	i915_gem_detect_bit_6_swizzle(dev);
   5463 #ifdef __NetBSD__
   5464 	DRM_INIT_WAITQUEUE(&dev_priv->pending_flip_queue, "i915flip");
   5465 	spin_lock_init(&dev_priv->pending_flip_lock);
   5466 #else
   5467 	init_waitqueue_head(&dev_priv->pending_flip_queue);
   5468 #endif
   5469 
   5470 	dev_priv->mm.interruptible = true;
   5471 
   5472 	dev_priv->mm.inactive_shrinker.scan_objects = i915_gem_inactive_scan;
   5473 	dev_priv->mm.inactive_shrinker.count_objects = i915_gem_inactive_count;
   5474 	dev_priv->mm.inactive_shrinker.seeks = DEFAULT_SEEKS;
   5475 	register_shrinker(&dev_priv->mm.inactive_shrinker);
   5476 }
   5477 
   5478 void i915_gem_release(struct drm_device *dev, struct drm_file *file)
   5479 {
   5480 	struct drm_i915_file_private *file_priv = file->driver_priv;
   5481 
   5482 	cancel_delayed_work_sync(&file_priv->mm.idle_work);
   5483 
   5484 	/* Clean up our request list when the client is going away, so that
   5485 	 * later retire_requests won't dereference our soon-to-be-gone
   5486 	 * file_priv.
   5487 	 */
   5488 	spin_lock(&file_priv->mm.lock);
   5489 	while (!list_empty(&file_priv->mm.request_list)) {
   5490 		struct drm_i915_gem_request *request;
   5491 
   5492 		request = list_first_entry(&file_priv->mm.request_list,
   5493 					   struct drm_i915_gem_request,
   5494 					   client_list);
   5495 		list_del(&request->client_list);
   5496 		request->file_priv = NULL;
   5497 	}
   5498 	spin_unlock(&file_priv->mm.lock);
   5499 }
   5500 
   5501 static void
   5502 i915_gem_file_idle_work_handler(struct work_struct *work)
   5503 {
   5504 	struct drm_i915_file_private *file_priv =
   5505 		container_of(work, typeof(*file_priv), mm.idle_work.work);
   5506 
   5507 	atomic_set(&file_priv->rps_wait_boost, false);
   5508 }
   5509 
   5510 int i915_gem_open(struct drm_device *dev, struct drm_file *file)
   5511 {
   5512 	struct drm_i915_file_private *file_priv;
   5513 	int ret;
   5514 
   5515 	DRM_DEBUG_DRIVER("\n");
   5516 
   5517 	file_priv = kzalloc(sizeof(*file_priv), GFP_KERNEL);
   5518 	if (!file_priv)
   5519 		return -ENOMEM;
   5520 
   5521 	file->driver_priv = file_priv;
   5522 	file_priv->dev_priv = dev->dev_private;
   5523 	file_priv->file = file;
   5524 
   5525 	spin_lock_init(&file_priv->mm.lock);
   5526 	INIT_LIST_HEAD(&file_priv->mm.request_list);
   5527 	INIT_DELAYED_WORK(&file_priv->mm.idle_work,
   5528 			  i915_gem_file_idle_work_handler);
   5529 
   5530 	ret = i915_gem_context_open(dev, file);
   5531 	if (ret)
   5532 		kfree(file_priv);
   5533 
   5534 	return ret;
   5535 }
   5536 
   5537 #ifndef __NetBSD__
   5538 static bool mutex_is_locked_by(struct mutex *mutex, struct task_struct *task)
   5539 {
   5540 	if (!mutex_is_locked(mutex))
   5541 		return false;
   5542 
   5543 #if defined(CONFIG_SMP) || defined(CONFIG_DEBUG_MUTEXES)
   5544 	return mutex->owner == task;
   5545 #else
   5546 	/* Since UP may be pre-empted, we cannot assume that we own the lock */
   5547 	return false;
   5548 #endif
   5549 }
   5550 #endif
   5551 
   5552 static unsigned long
   5553 i915_gem_inactive_count(struct shrinker *shrinker, struct shrink_control *sc)
   5554 {
   5555 #ifdef __NetBSD__		/* XXX shrinkers */
   5556 	return 0;
   5557 #else
   5558 	struct drm_i915_private *dev_priv =
   5559 		container_of(shrinker,
   5560 			     struct drm_i915_private,
   5561 			     mm.inactive_shrinker);
   5562 	struct drm_device *dev = dev_priv->dev;
   5563 	struct drm_i915_gem_object *obj;
   5564 	bool unlock = true;
   5565 	unsigned long count;
   5566 
   5567 	if (!mutex_trylock(&dev->struct_mutex)) {
   5568 		if (!mutex_is_locked_by(&dev->struct_mutex, current))
   5569 			return 0;
   5570 
   5571 		if (dev_priv->mm.shrinker_no_lock_stealing)
   5572 			return 0;
   5573 
   5574 		unlock = false;
   5575 	}
   5576 
   5577 	count = 0;
   5578 	list_for_each_entry(obj, &dev_priv->mm.unbound_list, global_list)
   5579 		if (obj->pages_pin_count == 0)
   5580 			count += obj->base.size >> PAGE_SHIFT;
   5581 
   5582 	list_for_each_entry(obj, &dev_priv->mm.bound_list, global_list) {
   5583 		if (obj->active)
   5584 			continue;
   5585 
   5586 		if (!i915_gem_obj_is_pinned(obj) && obj->pages_pin_count == 0)
   5587 			count += obj->base.size >> PAGE_SHIFT;
   5588 	}
   5589 
   5590 	if (unlock)
   5591 		mutex_unlock(&dev->struct_mutex);
   5592 
   5593 	return count;
   5594 #endif
   5595 }
   5596 
   5597 /* All the new VM stuff */
   5598 unsigned long i915_gem_obj_offset(struct drm_i915_gem_object *o,
   5599 				  struct i915_address_space *vm)
   5600 {
   5601 	struct drm_i915_private *dev_priv = o->base.dev->dev_private;
   5602 	struct i915_vma *vma;
   5603 
   5604 	if (!dev_priv->mm.aliasing_ppgtt ||
   5605 	    vm == &dev_priv->mm.aliasing_ppgtt->base)
   5606 		vm = &dev_priv->gtt.base;
   5607 
   5608 	BUG_ON(list_empty(&o->vma_list));
   5609 	list_for_each_entry(vma, &o->vma_list, vma_link) {
   5610 		if (vma->vm == vm)
   5611 			return vma->node.start;
   5612 
   5613 	}
   5614 	return -1;
   5615 }
   5616 
   5617 bool i915_gem_obj_bound(struct drm_i915_gem_object *o,
   5618 			struct i915_address_space *vm)
   5619 {
   5620 	struct i915_vma *vma;
   5621 
   5622 	list_for_each_entry(vma, &o->vma_list, vma_link)
   5623 		if (vma->vm == vm && drm_mm_node_allocated(&vma->node))
   5624 			return true;
   5625 
   5626 	return false;
   5627 }
   5628 
   5629 bool i915_gem_obj_bound_any(struct drm_i915_gem_object *o)
   5630 {
   5631 	struct i915_vma *vma;
   5632 
   5633 	list_for_each_entry(vma, &o->vma_list, vma_link)
   5634 		if (drm_mm_node_allocated(&vma->node))
   5635 			return true;
   5636 
   5637 	return false;
   5638 }
   5639 
   5640 unsigned long i915_gem_obj_size(struct drm_i915_gem_object *o,
   5641 				struct i915_address_space *vm)
   5642 {
   5643 	struct drm_i915_private *dev_priv = o->base.dev->dev_private;
   5644 	struct i915_vma *vma;
   5645 
   5646 	if (!dev_priv->mm.aliasing_ppgtt ||
   5647 	    vm == &dev_priv->mm.aliasing_ppgtt->base)
   5648 		vm = &dev_priv->gtt.base;
   5649 
   5650 	BUG_ON(list_empty(&o->vma_list));
   5651 
   5652 	list_for_each_entry(vma, &o->vma_list, vma_link)
   5653 		if (vma->vm == vm)
   5654 			return vma->node.size;
   5655 
   5656 	return 0;
   5657 }
   5658 
   5659 static unsigned long
   5660 i915_gem_inactive_scan(struct shrinker *shrinker, struct shrink_control *sc)
   5661 {
   5662 #ifdef __NetBSD__		/* XXX shrinkers */
   5663 	return 0;
   5664 #else
   5665 	struct drm_i915_private *dev_priv =
   5666 		container_of(shrinker,
   5667 			     struct drm_i915_private,
   5668 			     mm.inactive_shrinker);
   5669 	struct drm_device *dev = dev_priv->dev;
   5670 	unsigned long freed;
   5671 	bool unlock = true;
   5672 
   5673 	if (!mutex_trylock(&dev->struct_mutex)) {
   5674 		if (!mutex_is_locked_by(&dev->struct_mutex, current))
   5675 			return SHRINK_STOP;
   5676 
   5677 		if (dev_priv->mm.shrinker_no_lock_stealing)
   5678 			return SHRINK_STOP;
   5679 
   5680 		unlock = false;
   5681 	}
   5682 
   5683 	freed = i915_gem_purge(dev_priv, sc->nr_to_scan);
   5684 	if (freed < sc->nr_to_scan)
   5685 		freed += __i915_gem_shrink(dev_priv,
   5686 					   sc->nr_to_scan - freed,
   5687 					   false);
   5688 	if (freed < sc->nr_to_scan)
   5689 		freed += i915_gem_shrink_all(dev_priv);
   5690 
   5691 	if (unlock)
   5692 		mutex_unlock(&dev->struct_mutex);
   5693 
   5694 	return freed;
   5695 #endif
   5696 }
   5697 
   5698 struct i915_vma *i915_gem_obj_to_ggtt(struct drm_i915_gem_object *obj)
   5699 {
   5700 	struct i915_vma *vma;
   5701 
   5702 	if (WARN_ON(list_empty(&obj->vma_list)))
   5703 		return NULL;
   5704 
   5705 	vma = list_first_entry(&obj->vma_list, typeof(*vma), vma_link);
   5706 	if (vma->vm != obj_to_ggtt(obj))
   5707 		return NULL;
   5708 
   5709 	return vma;
   5710 }
   5711