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