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