]> git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blame - drivers/gpu/drm/i915/i915_gem.c
drm/i915: Remove engine->execlist_lock
[mirror_ubuntu-bionic-kernel.git] / drivers / gpu / drm / i915 / i915_gem.c
CommitLineData
673a394b 1/*
be6a0376 2 * Copyright © 2008-2015 Intel Corporation
673a394b
EA
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 *
23 * Authors:
24 * Eric Anholt <eric@anholt.net>
25 *
26 */
27
760285e7 28#include <drm/drmP.h>
0de23977 29#include <drm/drm_vma_manager.h>
760285e7 30#include <drm/i915_drm.h>
673a394b 31#include "i915_drv.h"
eb82289a 32#include "i915_vgpu.h"
1c5d22f7 33#include "i915_trace.h"
652c393a 34#include "intel_drv.h"
5d723d7a 35#include "intel_frontbuffer.h"
0ccdacf6 36#include "intel_mocs.h"
c13d87ea 37#include <linux/reservation.h>
5949eac4 38#include <linux/shmem_fs.h>
5a0e3ad6 39#include <linux/slab.h>
673a394b 40#include <linux/swap.h>
79e53945 41#include <linux/pci.h>
1286ff73 42#include <linux/dma-buf.h>
673a394b 43
fbbd37b3 44static void i915_gem_flush_free_objects(struct drm_i915_private *i915);
05394f39 45static void i915_gem_object_flush_gtt_write_domain(struct drm_i915_gem_object *obj);
e62b59e4 46static void i915_gem_object_flush_cpu_write_domain(struct drm_i915_gem_object *obj);
61050808 47
c76ce038
CW
48static bool cpu_cache_is_coherent(struct drm_device *dev,
49 enum i915_cache_level level)
50{
0031fb96 51 return HAS_LLC(to_i915(dev)) || level != I915_CACHE_NONE;
c76ce038
CW
52}
53
2c22569b
CW
54static bool cpu_write_needs_clflush(struct drm_i915_gem_object *obj)
55{
b50a5371
AS
56 if (obj->base.write_domain == I915_GEM_DOMAIN_CPU)
57 return false;
58
2c22569b
CW
59 if (!cpu_cache_is_coherent(obj->base.dev, obj->cache_level))
60 return true;
61
62 return obj->pin_display;
63}
64
4f1959ee 65static int
bb6dc8d9 66insert_mappable_node(struct i915_ggtt *ggtt,
4f1959ee
AS
67 struct drm_mm_node *node, u32 size)
68{
69 memset(node, 0, sizeof(*node));
bb6dc8d9
CW
70 return drm_mm_insert_node_in_range_generic(&ggtt->base.mm, node,
71 size, 0, -1,
72 0, ggtt->mappable_end,
4f1959ee
AS
73 DRM_MM_SEARCH_DEFAULT,
74 DRM_MM_CREATE_DEFAULT);
75}
76
77static void
78remove_mappable_node(struct drm_mm_node *node)
79{
80 drm_mm_remove_node(node);
81}
82
73aa808f
CW
83/* some bookkeeping */
84static void i915_gem_info_add_obj(struct drm_i915_private *dev_priv,
3ef7f228 85 u64 size)
73aa808f 86{
c20e8355 87 spin_lock(&dev_priv->mm.object_stat_lock);
73aa808f
CW
88 dev_priv->mm.object_count++;
89 dev_priv->mm.object_memory += size;
c20e8355 90 spin_unlock(&dev_priv->mm.object_stat_lock);
73aa808f
CW
91}
92
93static void i915_gem_info_remove_obj(struct drm_i915_private *dev_priv,
3ef7f228 94 u64 size)
73aa808f 95{
c20e8355 96 spin_lock(&dev_priv->mm.object_stat_lock);
73aa808f
CW
97 dev_priv->mm.object_count--;
98 dev_priv->mm.object_memory -= size;
c20e8355 99 spin_unlock(&dev_priv->mm.object_stat_lock);
73aa808f
CW
100}
101
21dd3734 102static int
33196ded 103i915_gem_wait_for_error(struct i915_gpu_error *error)
30dbf0c0 104{
30dbf0c0
CW
105 int ret;
106
4c7d62c6
CW
107 might_sleep();
108
d98c52cf 109 if (!i915_reset_in_progress(error))
30dbf0c0
CW
110 return 0;
111
0a6759c6
DV
112 /*
113 * Only wait 10 seconds for the gpu reset to complete to avoid hanging
114 * userspace. If it takes that long something really bad is going on and
115 * we should simply try to bail out and fail as gracefully as possible.
116 */
1f83fee0 117 ret = wait_event_interruptible_timeout(error->reset_queue,
d98c52cf 118 !i915_reset_in_progress(error),
b52992c0 119 I915_RESET_TIMEOUT);
0a6759c6
DV
120 if (ret == 0) {
121 DRM_ERROR("Timed out waiting for the gpu reset to complete\n");
122 return -EIO;
123 } else if (ret < 0) {
30dbf0c0 124 return ret;
d98c52cf
CW
125 } else {
126 return 0;
0a6759c6 127 }
30dbf0c0
CW
128}
129
54cf91dc 130int i915_mutex_lock_interruptible(struct drm_device *dev)
76c1dec1 131{
fac5e23e 132 struct drm_i915_private *dev_priv = to_i915(dev);
76c1dec1
CW
133 int ret;
134
33196ded 135 ret = i915_gem_wait_for_error(&dev_priv->gpu_error);
76c1dec1
CW
136 if (ret)
137 return ret;
138
139 ret = mutex_lock_interruptible(&dev->struct_mutex);
140 if (ret)
141 return ret;
142
76c1dec1
CW
143 return 0;
144}
30dbf0c0 145
5a125c3c
EA
146int
147i915_gem_get_aperture_ioctl(struct drm_device *dev, void *data,
05394f39 148 struct drm_file *file)
5a125c3c 149{
72e96d64 150 struct drm_i915_private *dev_priv = to_i915(dev);
62106b4f 151 struct i915_ggtt *ggtt = &dev_priv->ggtt;
72e96d64 152 struct drm_i915_gem_get_aperture *args = data;
ca1543be 153 struct i915_vma *vma;
6299f992 154 size_t pinned;
5a125c3c 155
6299f992 156 pinned = 0;
73aa808f 157 mutex_lock(&dev->struct_mutex);
1c7f4bca 158 list_for_each_entry(vma, &ggtt->base.active_list, vm_link)
20dfbde4 159 if (i915_vma_is_pinned(vma))
ca1543be 160 pinned += vma->node.size;
1c7f4bca 161 list_for_each_entry(vma, &ggtt->base.inactive_list, vm_link)
20dfbde4 162 if (i915_vma_is_pinned(vma))
ca1543be 163 pinned += vma->node.size;
73aa808f 164 mutex_unlock(&dev->struct_mutex);
5a125c3c 165
72e96d64 166 args->aper_size = ggtt->base.total;
0206e353 167 args->aper_available_size = args->aper_size - pinned;
6299f992 168
5a125c3c
EA
169 return 0;
170}
171
03ac84f1 172static struct sg_table *
6a2c4232 173i915_gem_object_get_pages_phys(struct drm_i915_gem_object *obj)
00731155 174{
93c76a3d 175 struct address_space *mapping = obj->base.filp->f_mapping;
6a2c4232
CW
176 char *vaddr = obj->phys_handle->vaddr;
177 struct sg_table *st;
178 struct scatterlist *sg;
179 int i;
00731155 180
6a2c4232 181 if (WARN_ON(i915_gem_object_needs_bit17_swizzle(obj)))
03ac84f1 182 return ERR_PTR(-EINVAL);
6a2c4232
CW
183
184 for (i = 0; i < obj->base.size / PAGE_SIZE; i++) {
185 struct page *page;
186 char *src;
187
188 page = shmem_read_mapping_page(mapping, i);
189 if (IS_ERR(page))
03ac84f1 190 return ERR_CAST(page);
6a2c4232
CW
191
192 src = kmap_atomic(page);
193 memcpy(vaddr, src, PAGE_SIZE);
194 drm_clflush_virt_range(vaddr, PAGE_SIZE);
195 kunmap_atomic(src);
196
09cbfeaf 197 put_page(page);
6a2c4232
CW
198 vaddr += PAGE_SIZE;
199 }
200
c033666a 201 i915_gem_chipset_flush(to_i915(obj->base.dev));
6a2c4232
CW
202
203 st = kmalloc(sizeof(*st), GFP_KERNEL);
204 if (st == NULL)
03ac84f1 205 return ERR_PTR(-ENOMEM);
6a2c4232
CW
206
207 if (sg_alloc_table(st, 1, GFP_KERNEL)) {
208 kfree(st);
03ac84f1 209 return ERR_PTR(-ENOMEM);
6a2c4232
CW
210 }
211
212 sg = st->sgl;
213 sg->offset = 0;
214 sg->length = obj->base.size;
00731155 215
6a2c4232
CW
216 sg_dma_address(sg) = obj->phys_handle->busaddr;
217 sg_dma_len(sg) = obj->base.size;
218
03ac84f1 219 return st;
6a2c4232
CW
220}
221
222static void
2b3c8317
CW
223__i915_gem_object_release_shmem(struct drm_i915_gem_object *obj,
224 struct sg_table *pages)
6a2c4232 225{
a4f5ea64 226 GEM_BUG_ON(obj->mm.madv == __I915_MADV_PURGED);
00731155 227
a4f5ea64
CW
228 if (obj->mm.madv == I915_MADV_DONTNEED)
229 obj->mm.dirty = false;
6a2c4232 230
03ac84f1 231 if ((obj->base.read_domains & I915_GEM_DOMAIN_CPU) == 0)
2b3c8317 232 drm_clflush_sg(pages);
03ac84f1
CW
233
234 obj->base.read_domains = I915_GEM_DOMAIN_CPU;
235 obj->base.write_domain = I915_GEM_DOMAIN_CPU;
236}
237
238static void
239i915_gem_object_put_pages_phys(struct drm_i915_gem_object *obj,
240 struct sg_table *pages)
241{
2b3c8317 242 __i915_gem_object_release_shmem(obj, pages);
03ac84f1 243
a4f5ea64 244 if (obj->mm.dirty) {
93c76a3d 245 struct address_space *mapping = obj->base.filp->f_mapping;
6a2c4232 246 char *vaddr = obj->phys_handle->vaddr;
00731155
CW
247 int i;
248
249 for (i = 0; i < obj->base.size / PAGE_SIZE; i++) {
6a2c4232
CW
250 struct page *page;
251 char *dst;
252
253 page = shmem_read_mapping_page(mapping, i);
254 if (IS_ERR(page))
255 continue;
256
257 dst = kmap_atomic(page);
258 drm_clflush_virt_range(vaddr, PAGE_SIZE);
259 memcpy(dst, vaddr, PAGE_SIZE);
260 kunmap_atomic(dst);
261
262 set_page_dirty(page);
a4f5ea64 263 if (obj->mm.madv == I915_MADV_WILLNEED)
00731155 264 mark_page_accessed(page);
09cbfeaf 265 put_page(page);
00731155
CW
266 vaddr += PAGE_SIZE;
267 }
a4f5ea64 268 obj->mm.dirty = false;
00731155
CW
269 }
270
03ac84f1
CW
271 sg_free_table(pages);
272 kfree(pages);
6a2c4232
CW
273}
274
275static void
276i915_gem_object_release_phys(struct drm_i915_gem_object *obj)
277{
278 drm_pci_free(obj->base.dev, obj->phys_handle);
a4f5ea64 279 i915_gem_object_unpin_pages(obj);
6a2c4232
CW
280}
281
282static const struct drm_i915_gem_object_ops i915_gem_phys_ops = {
283 .get_pages = i915_gem_object_get_pages_phys,
284 .put_pages = i915_gem_object_put_pages_phys,
285 .release = i915_gem_object_release_phys,
286};
287
35a9611c 288int i915_gem_object_unbind(struct drm_i915_gem_object *obj)
aa653a68
CW
289{
290 struct i915_vma *vma;
291 LIST_HEAD(still_in_list);
02bef8f9
CW
292 int ret;
293
294 lockdep_assert_held(&obj->base.dev->struct_mutex);
aa653a68 295
02bef8f9
CW
296 /* Closed vma are removed from the obj->vma_list - but they may
297 * still have an active binding on the object. To remove those we
298 * must wait for all rendering to complete to the object (as unbinding
299 * must anyway), and retire the requests.
aa653a68 300 */
e95433c7
CW
301 ret = i915_gem_object_wait(obj,
302 I915_WAIT_INTERRUPTIBLE |
303 I915_WAIT_LOCKED |
304 I915_WAIT_ALL,
305 MAX_SCHEDULE_TIMEOUT,
306 NULL);
02bef8f9
CW
307 if (ret)
308 return ret;
309
310 i915_gem_retire_requests(to_i915(obj->base.dev));
311
aa653a68
CW
312 while ((vma = list_first_entry_or_null(&obj->vma_list,
313 struct i915_vma,
314 obj_link))) {
315 list_move_tail(&vma->obj_link, &still_in_list);
316 ret = i915_vma_unbind(vma);
317 if (ret)
318 break;
319 }
320 list_splice(&still_in_list, &obj->vma_list);
321
322 return ret;
323}
324
e95433c7
CW
325static long
326i915_gem_object_wait_fence(struct dma_fence *fence,
327 unsigned int flags,
328 long timeout,
329 struct intel_rps_client *rps)
00e60f26 330{
e95433c7 331 struct drm_i915_gem_request *rq;
00e60f26 332
e95433c7 333 BUILD_BUG_ON(I915_WAIT_INTERRUPTIBLE != 0x1);
00e60f26 334
e95433c7
CW
335 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
336 return timeout;
337
338 if (!dma_fence_is_i915(fence))
339 return dma_fence_wait_timeout(fence,
340 flags & I915_WAIT_INTERRUPTIBLE,
341 timeout);
342
343 rq = to_request(fence);
344 if (i915_gem_request_completed(rq))
345 goto out;
346
347 /* This client is about to stall waiting for the GPU. In many cases
348 * this is undesirable and limits the throughput of the system, as
349 * many clients cannot continue processing user input/output whilst
350 * blocked. RPS autotuning may take tens of milliseconds to respond
351 * to the GPU load and thus incurs additional latency for the client.
352 * We can circumvent that by promoting the GPU frequency to maximum
353 * before we wait. This makes the GPU throttle up much more quickly
354 * (good for benchmarks and user experience, e.g. window animations),
355 * but at a cost of spending more power processing the workload
356 * (bad for battery). Not all clients even want their results
357 * immediately and for them we should just let the GPU select its own
358 * frequency to maximise efficiency. To prevent a single client from
359 * forcing the clocks too high for the whole system, we only allow
360 * each client to waitboost once in a busy period.
361 */
362 if (rps) {
363 if (INTEL_GEN(rq->i915) >= 6)
364 gen6_rps_boost(rq->i915, rps, rq->emitted_jiffies);
365 else
366 rps = NULL;
00e60f26
CW
367 }
368
e95433c7
CW
369 timeout = i915_wait_request(rq, flags, timeout);
370
371out:
372 if (flags & I915_WAIT_LOCKED && i915_gem_request_completed(rq))
373 i915_gem_request_retire_upto(rq);
374
cb399eab 375 if (rps && rq->global_seqno == intel_engine_last_submit(rq->engine)) {
e95433c7
CW
376 /* The GPU is now idle and this client has stalled.
377 * Since no other client has submitted a request in the
378 * meantime, assume that this client is the only one
379 * supplying work to the GPU but is unable to keep that
380 * work supplied because it is waiting. Since the GPU is
381 * then never kept fully busy, RPS autoclocking will
382 * keep the clocks relatively low, causing further delays.
383 * Compensate by giving the synchronous client credit for
384 * a waitboost next time.
385 */
386 spin_lock(&rq->i915->rps.client_lock);
387 list_del_init(&rps->link);
388 spin_unlock(&rq->i915->rps.client_lock);
389 }
390
391 return timeout;
392}
393
394static long
395i915_gem_object_wait_reservation(struct reservation_object *resv,
396 unsigned int flags,
397 long timeout,
398 struct intel_rps_client *rps)
399{
400 struct dma_fence *excl;
401
402 if (flags & I915_WAIT_ALL) {
403 struct dma_fence **shared;
404 unsigned int count, i;
00e60f26
CW
405 int ret;
406
e95433c7
CW
407 ret = reservation_object_get_fences_rcu(resv,
408 &excl, &count, &shared);
00e60f26
CW
409 if (ret)
410 return ret;
00e60f26 411
e95433c7
CW
412 for (i = 0; i < count; i++) {
413 timeout = i915_gem_object_wait_fence(shared[i],
414 flags, timeout,
415 rps);
416 if (timeout <= 0)
417 break;
00e60f26 418
e95433c7
CW
419 dma_fence_put(shared[i]);
420 }
421
422 for (; i < count; i++)
423 dma_fence_put(shared[i]);
424 kfree(shared);
425 } else {
426 excl = reservation_object_get_excl_rcu(resv);
00e60f26
CW
427 }
428
e95433c7
CW
429 if (excl && timeout > 0)
430 timeout = i915_gem_object_wait_fence(excl, flags, timeout, rps);
431
432 dma_fence_put(excl);
433
434 return timeout;
00e60f26
CW
435}
436
e95433c7
CW
437/**
438 * Waits for rendering to the object to be completed
439 * @obj: i915 gem object
440 * @flags: how to wait (under a lock, for all rendering or just for writes etc)
441 * @timeout: how long to wait
442 * @rps: client (user process) to charge for any waitboosting
00e60f26 443 */
e95433c7
CW
444int
445i915_gem_object_wait(struct drm_i915_gem_object *obj,
446 unsigned int flags,
447 long timeout,
448 struct intel_rps_client *rps)
00e60f26 449{
e95433c7
CW
450 might_sleep();
451#if IS_ENABLED(CONFIG_LOCKDEP)
452 GEM_BUG_ON(debug_locks &&
453 !!lockdep_is_held(&obj->base.dev->struct_mutex) !=
454 !!(flags & I915_WAIT_LOCKED));
455#endif
456 GEM_BUG_ON(timeout < 0);
00e60f26 457
d07f0e59
CW
458 timeout = i915_gem_object_wait_reservation(obj->resv,
459 flags, timeout,
460 rps);
e95433c7 461 return timeout < 0 ? timeout : 0;
00e60f26
CW
462}
463
464static struct intel_rps_client *to_rps_client(struct drm_file *file)
465{
466 struct drm_i915_file_private *fpriv = file->driver_priv;
467
468 return &fpriv->rps;
469}
470
00731155
CW
471int
472i915_gem_object_attach_phys(struct drm_i915_gem_object *obj,
473 int align)
474{
475 drm_dma_handle_t *phys;
6a2c4232 476 int ret;
00731155
CW
477
478 if (obj->phys_handle) {
479 if ((unsigned long)obj->phys_handle->vaddr & (align -1))
480 return -EBUSY;
481
482 return 0;
483 }
484
a4f5ea64 485 if (obj->mm.madv != I915_MADV_WILLNEED)
00731155
CW
486 return -EFAULT;
487
488 if (obj->base.filp == NULL)
489 return -EINVAL;
490
4717ca9e
CW
491 ret = i915_gem_object_unbind(obj);
492 if (ret)
493 return ret;
494
548625ee 495 __i915_gem_object_put_pages(obj, I915_MM_NORMAL);
03ac84f1
CW
496 if (obj->mm.pages)
497 return -EBUSY;
6a2c4232 498
00731155
CW
499 /* create a new object */
500 phys = drm_pci_alloc(obj->base.dev, obj->base.size, align);
501 if (!phys)
502 return -ENOMEM;
503
00731155 504 obj->phys_handle = phys;
6a2c4232
CW
505 obj->ops = &i915_gem_phys_ops;
506
a4f5ea64 507 return i915_gem_object_pin_pages(obj);
00731155
CW
508}
509
510static int
511i915_gem_phys_pwrite(struct drm_i915_gem_object *obj,
512 struct drm_i915_gem_pwrite *args,
03ac84f1 513 struct drm_file *file)
00731155
CW
514{
515 struct drm_device *dev = obj->base.dev;
516 void *vaddr = obj->phys_handle->vaddr + args->offset;
3ed605bc 517 char __user *user_data = u64_to_user_ptr(args->data_ptr);
e95433c7 518 int ret;
6a2c4232
CW
519
520 /* We manually control the domain here and pretend that it
521 * remains coherent i.e. in the GTT domain, like shmem_pwrite.
522 */
e95433c7
CW
523 lockdep_assert_held(&obj->base.dev->struct_mutex);
524 ret = i915_gem_object_wait(obj,
525 I915_WAIT_INTERRUPTIBLE |
526 I915_WAIT_LOCKED |
527 I915_WAIT_ALL,
528 MAX_SCHEDULE_TIMEOUT,
03ac84f1 529 to_rps_client(file));
6a2c4232
CW
530 if (ret)
531 return ret;
00731155 532
77a0d1ca 533 intel_fb_obj_invalidate(obj, ORIGIN_CPU);
00731155
CW
534 if (__copy_from_user_inatomic_nocache(vaddr, user_data, args->size)) {
535 unsigned long unwritten;
536
537 /* The physical object once assigned is fixed for the lifetime
538 * of the obj, so we can safely drop the lock and continue
539 * to access vaddr.
540 */
541 mutex_unlock(&dev->struct_mutex);
542 unwritten = copy_from_user(vaddr, user_data, args->size);
543 mutex_lock(&dev->struct_mutex);
063e4e6b
PZ
544 if (unwritten) {
545 ret = -EFAULT;
546 goto out;
547 }
00731155
CW
548 }
549
6a2c4232 550 drm_clflush_virt_range(vaddr, args->size);
c033666a 551 i915_gem_chipset_flush(to_i915(dev));
063e4e6b
PZ
552
553out:
de152b62 554 intel_fb_obj_flush(obj, false, ORIGIN_CPU);
063e4e6b 555 return ret;
00731155
CW
556}
557
42dcedd4
CW
558void *i915_gem_object_alloc(struct drm_device *dev)
559{
fac5e23e 560 struct drm_i915_private *dev_priv = to_i915(dev);
efab6d8d 561 return kmem_cache_zalloc(dev_priv->objects, GFP_KERNEL);
42dcedd4
CW
562}
563
564void i915_gem_object_free(struct drm_i915_gem_object *obj)
565{
fac5e23e 566 struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
efab6d8d 567 kmem_cache_free(dev_priv->objects, obj);
42dcedd4
CW
568}
569
ff72145b
DA
570static int
571i915_gem_create(struct drm_file *file,
572 struct drm_device *dev,
573 uint64_t size,
574 uint32_t *handle_p)
673a394b 575{
05394f39 576 struct drm_i915_gem_object *obj;
a1a2d1d3
PP
577 int ret;
578 u32 handle;
673a394b 579
ff72145b 580 size = roundup(size, PAGE_SIZE);
8ffc0246
CW
581 if (size == 0)
582 return -EINVAL;
673a394b
EA
583
584 /* Allocate the new object */
d37cd8a8 585 obj = i915_gem_object_create(dev, size);
fe3db79b
CW
586 if (IS_ERR(obj))
587 return PTR_ERR(obj);
673a394b 588
05394f39 589 ret = drm_gem_handle_create(file, &obj->base, &handle);
202f2fef 590 /* drop reference from allocate - handle holds it now */
f0cd5182 591 i915_gem_object_put(obj);
d861e338
DV
592 if (ret)
593 return ret;
202f2fef 594
ff72145b 595 *handle_p = handle;
673a394b
EA
596 return 0;
597}
598
ff72145b
DA
599int
600i915_gem_dumb_create(struct drm_file *file,
601 struct drm_device *dev,
602 struct drm_mode_create_dumb *args)
603{
604 /* have to work out size/pitch and return them */
de45eaf7 605 args->pitch = ALIGN(args->width * DIV_ROUND_UP(args->bpp, 8), 64);
ff72145b
DA
606 args->size = args->pitch * args->height;
607 return i915_gem_create(file, dev,
da6b51d0 608 args->size, &args->handle);
ff72145b
DA
609}
610
ff72145b
DA
611/**
612 * Creates a new mm object and returns a handle to it.
14bb2c11
TU
613 * @dev: drm device pointer
614 * @data: ioctl data blob
615 * @file: drm file pointer
ff72145b
DA
616 */
617int
618i915_gem_create_ioctl(struct drm_device *dev, void *data,
619 struct drm_file *file)
620{
621 struct drm_i915_gem_create *args = data;
63ed2cb2 622
fbbd37b3
CW
623 i915_gem_flush_free_objects(to_i915(dev));
624
ff72145b 625 return i915_gem_create(file, dev,
da6b51d0 626 args->size, &args->handle);
ff72145b
DA
627}
628
8461d226
DV
629static inline int
630__copy_to_user_swizzled(char __user *cpu_vaddr,
631 const char *gpu_vaddr, int gpu_offset,
632 int length)
633{
634 int ret, cpu_offset = 0;
635
636 while (length > 0) {
637 int cacheline_end = ALIGN(gpu_offset + 1, 64);
638 int this_length = min(cacheline_end - gpu_offset, length);
639 int swizzled_gpu_offset = gpu_offset ^ 64;
640
641 ret = __copy_to_user(cpu_vaddr + cpu_offset,
642 gpu_vaddr + swizzled_gpu_offset,
643 this_length);
644 if (ret)
645 return ret + length;
646
647 cpu_offset += this_length;
648 gpu_offset += this_length;
649 length -= this_length;
650 }
651
652 return 0;
653}
654
8c59967c 655static inline int
4f0c7cfb
BW
656__copy_from_user_swizzled(char *gpu_vaddr, int gpu_offset,
657 const char __user *cpu_vaddr,
8c59967c
DV
658 int length)
659{
660 int ret, cpu_offset = 0;
661
662 while (length > 0) {
663 int cacheline_end = ALIGN(gpu_offset + 1, 64);
664 int this_length = min(cacheline_end - gpu_offset, length);
665 int swizzled_gpu_offset = gpu_offset ^ 64;
666
667 ret = __copy_from_user(gpu_vaddr + swizzled_gpu_offset,
668 cpu_vaddr + cpu_offset,
669 this_length);
670 if (ret)
671 return ret + length;
672
673 cpu_offset += this_length;
674 gpu_offset += this_length;
675 length -= this_length;
676 }
677
678 return 0;
679}
680
4c914c0c
BV
681/*
682 * Pins the specified object's pages and synchronizes the object with
683 * GPU accesses. Sets needs_clflush to non-zero if the caller should
684 * flush the object from the CPU cache.
685 */
686int i915_gem_obj_prepare_shmem_read(struct drm_i915_gem_object *obj,
43394c7d 687 unsigned int *needs_clflush)
4c914c0c
BV
688{
689 int ret;
690
e95433c7 691 lockdep_assert_held(&obj->base.dev->struct_mutex);
4c914c0c 692
e95433c7 693 *needs_clflush = 0;
43394c7d
CW
694 if (!i915_gem_object_has_struct_page(obj))
695 return -ENODEV;
4c914c0c 696
e95433c7
CW
697 ret = i915_gem_object_wait(obj,
698 I915_WAIT_INTERRUPTIBLE |
699 I915_WAIT_LOCKED,
700 MAX_SCHEDULE_TIMEOUT,
701 NULL);
c13d87ea
CW
702 if (ret)
703 return ret;
704
a4f5ea64 705 ret = i915_gem_object_pin_pages(obj);
9764951e
CW
706 if (ret)
707 return ret;
708
a314d5cb
CW
709 i915_gem_object_flush_gtt_write_domain(obj);
710
43394c7d
CW
711 /* If we're not in the cpu read domain, set ourself into the gtt
712 * read domain and manually flush cachelines (if required). This
713 * optimizes for the case when the gpu will dirty the data
714 * anyway again before the next pread happens.
715 */
716 if (!(obj->base.read_domains & I915_GEM_DOMAIN_CPU))
4c914c0c
BV
717 *needs_clflush = !cpu_cache_is_coherent(obj->base.dev,
718 obj->cache_level);
43394c7d 719
43394c7d
CW
720 if (*needs_clflush && !static_cpu_has(X86_FEATURE_CLFLUSH)) {
721 ret = i915_gem_object_set_to_cpu_domain(obj, false);
9764951e
CW
722 if (ret)
723 goto err_unpin;
724
43394c7d 725 *needs_clflush = 0;
4c914c0c
BV
726 }
727
9764951e 728 /* return with the pages pinned */
43394c7d 729 return 0;
9764951e
CW
730
731err_unpin:
732 i915_gem_object_unpin_pages(obj);
733 return ret;
43394c7d
CW
734}
735
736int i915_gem_obj_prepare_shmem_write(struct drm_i915_gem_object *obj,
737 unsigned int *needs_clflush)
738{
739 int ret;
740
e95433c7
CW
741 lockdep_assert_held(&obj->base.dev->struct_mutex);
742
43394c7d
CW
743 *needs_clflush = 0;
744 if (!i915_gem_object_has_struct_page(obj))
745 return -ENODEV;
746
e95433c7
CW
747 ret = i915_gem_object_wait(obj,
748 I915_WAIT_INTERRUPTIBLE |
749 I915_WAIT_LOCKED |
750 I915_WAIT_ALL,
751 MAX_SCHEDULE_TIMEOUT,
752 NULL);
43394c7d
CW
753 if (ret)
754 return ret;
755
a4f5ea64 756 ret = i915_gem_object_pin_pages(obj);
9764951e
CW
757 if (ret)
758 return ret;
759
a314d5cb
CW
760 i915_gem_object_flush_gtt_write_domain(obj);
761
43394c7d
CW
762 /* If we're not in the cpu write domain, set ourself into the
763 * gtt write domain and manually flush cachelines (as required).
764 * This optimizes for the case when the gpu will use the data
765 * right away and we therefore have to clflush anyway.
766 */
767 if (obj->base.write_domain != I915_GEM_DOMAIN_CPU)
768 *needs_clflush |= cpu_write_needs_clflush(obj) << 1;
769
770 /* Same trick applies to invalidate partially written cachelines read
771 * before writing.
772 */
773 if (!(obj->base.read_domains & I915_GEM_DOMAIN_CPU))
774 *needs_clflush |= !cpu_cache_is_coherent(obj->base.dev,
775 obj->cache_level);
776
43394c7d
CW
777 if (*needs_clflush && !static_cpu_has(X86_FEATURE_CLFLUSH)) {
778 ret = i915_gem_object_set_to_cpu_domain(obj, true);
9764951e
CW
779 if (ret)
780 goto err_unpin;
781
43394c7d
CW
782 *needs_clflush = 0;
783 }
784
785 if ((*needs_clflush & CLFLUSH_AFTER) == 0)
786 obj->cache_dirty = true;
787
788 intel_fb_obj_invalidate(obj, ORIGIN_CPU);
a4f5ea64 789 obj->mm.dirty = true;
9764951e 790 /* return with the pages pinned */
43394c7d 791 return 0;
9764951e
CW
792
793err_unpin:
794 i915_gem_object_unpin_pages(obj);
795 return ret;
4c914c0c
BV
796}
797
23c18c71
DV
798static void
799shmem_clflush_swizzled_range(char *addr, unsigned long length,
800 bool swizzled)
801{
e7e58eb5 802 if (unlikely(swizzled)) {
23c18c71
DV
803 unsigned long start = (unsigned long) addr;
804 unsigned long end = (unsigned long) addr + length;
805
806 /* For swizzling simply ensure that we always flush both
807 * channels. Lame, but simple and it works. Swizzled
808 * pwrite/pread is far from a hotpath - current userspace
809 * doesn't use it at all. */
810 start = round_down(start, 128);
811 end = round_up(end, 128);
812
813 drm_clflush_virt_range((void *)start, end - start);
814 } else {
815 drm_clflush_virt_range(addr, length);
816 }
817
818}
819
d174bd64
DV
820/* Only difference to the fast-path function is that this can handle bit17
821 * and uses non-atomic copy and kmap functions. */
822static int
bb6dc8d9 823shmem_pread_slow(struct page *page, int offset, int length,
d174bd64
DV
824 char __user *user_data,
825 bool page_do_bit17_swizzling, bool needs_clflush)
826{
827 char *vaddr;
828 int ret;
829
830 vaddr = kmap(page);
831 if (needs_clflush)
bb6dc8d9 832 shmem_clflush_swizzled_range(vaddr + offset, length,
23c18c71 833 page_do_bit17_swizzling);
d174bd64
DV
834
835 if (page_do_bit17_swizzling)
bb6dc8d9 836 ret = __copy_to_user_swizzled(user_data, vaddr, offset, length);
d174bd64 837 else
bb6dc8d9 838 ret = __copy_to_user(user_data, vaddr + offset, length);
d174bd64
DV
839 kunmap(page);
840
f60d7f0c 841 return ret ? - EFAULT : 0;
d174bd64
DV
842}
843
bb6dc8d9
CW
844static int
845shmem_pread(struct page *page, int offset, int length, char __user *user_data,
846 bool page_do_bit17_swizzling, bool needs_clflush)
847{
848 int ret;
849
850 ret = -ENODEV;
851 if (!page_do_bit17_swizzling) {
852 char *vaddr = kmap_atomic(page);
853
854 if (needs_clflush)
855 drm_clflush_virt_range(vaddr + offset, length);
856 ret = __copy_to_user_inatomic(user_data, vaddr + offset, length);
857 kunmap_atomic(vaddr);
858 }
859 if (ret == 0)
860 return 0;
861
862 return shmem_pread_slow(page, offset, length, user_data,
863 page_do_bit17_swizzling, needs_clflush);
864}
865
866static int
867i915_gem_shmem_pread(struct drm_i915_gem_object *obj,
868 struct drm_i915_gem_pread *args)
869{
870 char __user *user_data;
871 u64 remain;
872 unsigned int obj_do_bit17_swizzling;
873 unsigned int needs_clflush;
874 unsigned int idx, offset;
875 int ret;
876
877 obj_do_bit17_swizzling = 0;
878 if (i915_gem_object_needs_bit17_swizzle(obj))
879 obj_do_bit17_swizzling = BIT(17);
880
881 ret = mutex_lock_interruptible(&obj->base.dev->struct_mutex);
882 if (ret)
883 return ret;
884
885 ret = i915_gem_obj_prepare_shmem_read(obj, &needs_clflush);
886 mutex_unlock(&obj->base.dev->struct_mutex);
887 if (ret)
888 return ret;
889
890 remain = args->size;
891 user_data = u64_to_user_ptr(args->data_ptr);
892 offset = offset_in_page(args->offset);
893 for (idx = args->offset >> PAGE_SHIFT; remain; idx++) {
894 struct page *page = i915_gem_object_get_page(obj, idx);
895 int length;
896
897 length = remain;
898 if (offset + length > PAGE_SIZE)
899 length = PAGE_SIZE - offset;
900
901 ret = shmem_pread(page, offset, length, user_data,
902 page_to_phys(page) & obj_do_bit17_swizzling,
903 needs_clflush);
904 if (ret)
905 break;
906
907 remain -= length;
908 user_data += length;
909 offset = 0;
910 }
911
912 i915_gem_obj_finish_shmem_access(obj);
913 return ret;
914}
915
916static inline bool
917gtt_user_read(struct io_mapping *mapping,
918 loff_t base, int offset,
919 char __user *user_data, int length)
b50a5371 920{
b50a5371 921 void *vaddr;
bb6dc8d9 922 unsigned long unwritten;
b50a5371 923
b50a5371 924 /* We can use the cpu mem copy function because this is X86. */
bb6dc8d9
CW
925 vaddr = (void __force *)io_mapping_map_atomic_wc(mapping, base);
926 unwritten = __copy_to_user_inatomic(user_data, vaddr + offset, length);
927 io_mapping_unmap_atomic(vaddr);
928 if (unwritten) {
929 vaddr = (void __force *)
930 io_mapping_map_wc(mapping, base, PAGE_SIZE);
931 unwritten = copy_to_user(user_data, vaddr + offset, length);
932 io_mapping_unmap(vaddr);
933 }
b50a5371
AS
934 return unwritten;
935}
936
937static int
bb6dc8d9
CW
938i915_gem_gtt_pread(struct drm_i915_gem_object *obj,
939 const struct drm_i915_gem_pread *args)
b50a5371 940{
bb6dc8d9
CW
941 struct drm_i915_private *i915 = to_i915(obj->base.dev);
942 struct i915_ggtt *ggtt = &i915->ggtt;
b50a5371 943 struct drm_mm_node node;
bb6dc8d9
CW
944 struct i915_vma *vma;
945 void __user *user_data;
946 u64 remain, offset;
b50a5371
AS
947 int ret;
948
bb6dc8d9
CW
949 ret = mutex_lock_interruptible(&i915->drm.struct_mutex);
950 if (ret)
951 return ret;
952
953 intel_runtime_pm_get(i915);
954 vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0,
955 PIN_MAPPABLE | PIN_NONBLOCK);
18034584
CW
956 if (!IS_ERR(vma)) {
957 node.start = i915_ggtt_offset(vma);
958 node.allocated = false;
49ef5294 959 ret = i915_vma_put_fence(vma);
18034584
CW
960 if (ret) {
961 i915_vma_unpin(vma);
962 vma = ERR_PTR(ret);
963 }
964 }
058d88c4 965 if (IS_ERR(vma)) {
bb6dc8d9 966 ret = insert_mappable_node(ggtt, &node, PAGE_SIZE);
b50a5371 967 if (ret)
bb6dc8d9
CW
968 goto out_unlock;
969 GEM_BUG_ON(!node.allocated);
b50a5371
AS
970 }
971
972 ret = i915_gem_object_set_to_gtt_domain(obj, false);
973 if (ret)
974 goto out_unpin;
975
bb6dc8d9 976 mutex_unlock(&i915->drm.struct_mutex);
b50a5371 977
bb6dc8d9
CW
978 user_data = u64_to_user_ptr(args->data_ptr);
979 remain = args->size;
980 offset = args->offset;
b50a5371
AS
981
982 while (remain > 0) {
983 /* Operation in this page
984 *
985 * page_base = page offset within aperture
986 * page_offset = offset within page
987 * page_length = bytes to copy for this page
988 */
989 u32 page_base = node.start;
990 unsigned page_offset = offset_in_page(offset);
991 unsigned page_length = PAGE_SIZE - page_offset;
992 page_length = remain < page_length ? remain : page_length;
993 if (node.allocated) {
994 wmb();
995 ggtt->base.insert_page(&ggtt->base,
996 i915_gem_object_get_dma_address(obj, offset >> PAGE_SHIFT),
bb6dc8d9 997 node.start, I915_CACHE_NONE, 0);
b50a5371
AS
998 wmb();
999 } else {
1000 page_base += offset & PAGE_MASK;
1001 }
bb6dc8d9
CW
1002
1003 if (gtt_user_read(&ggtt->mappable, page_base, page_offset,
1004 user_data, page_length)) {
b50a5371
AS
1005 ret = -EFAULT;
1006 break;
1007 }
1008
1009 remain -= page_length;
1010 user_data += page_length;
1011 offset += page_length;
1012 }
1013
bb6dc8d9 1014 mutex_lock(&i915->drm.struct_mutex);
b50a5371
AS
1015out_unpin:
1016 if (node.allocated) {
1017 wmb();
1018 ggtt->base.clear_range(&ggtt->base,
4fb84d99 1019 node.start, node.size);
b50a5371
AS
1020 remove_mappable_node(&node);
1021 } else {
058d88c4 1022 i915_vma_unpin(vma);
b50a5371 1023 }
bb6dc8d9
CW
1024out_unlock:
1025 intel_runtime_pm_put(i915);
1026 mutex_unlock(&i915->drm.struct_mutex);
f60d7f0c 1027
eb01459f
EA
1028 return ret;
1029}
1030
673a394b
EA
1031/**
1032 * Reads data from the object referenced by handle.
14bb2c11
TU
1033 * @dev: drm device pointer
1034 * @data: ioctl data blob
1035 * @file: drm file pointer
673a394b
EA
1036 *
1037 * On error, the contents of *data are undefined.
1038 */
1039int
1040i915_gem_pread_ioctl(struct drm_device *dev, void *data,
05394f39 1041 struct drm_file *file)
673a394b
EA
1042{
1043 struct drm_i915_gem_pread *args = data;
05394f39 1044 struct drm_i915_gem_object *obj;
bb6dc8d9 1045 int ret;
673a394b 1046
51311d0a
CW
1047 if (args->size == 0)
1048 return 0;
1049
1050 if (!access_ok(VERIFY_WRITE,
3ed605bc 1051 u64_to_user_ptr(args->data_ptr),
51311d0a
CW
1052 args->size))
1053 return -EFAULT;
1054
03ac0642 1055 obj = i915_gem_object_lookup(file, args->handle);
258a5ede
CW
1056 if (!obj)
1057 return -ENOENT;
673a394b 1058
7dcd2499 1059 /* Bounds check source. */
05394f39
CW
1060 if (args->offset > obj->base.size ||
1061 args->size > obj->base.size - args->offset) {
ce9d419d 1062 ret = -EINVAL;
bb6dc8d9 1063 goto out;
ce9d419d
CW
1064 }
1065
db53a302
CW
1066 trace_i915_gem_object_pread(obj, args->offset, args->size);
1067
e95433c7
CW
1068 ret = i915_gem_object_wait(obj,
1069 I915_WAIT_INTERRUPTIBLE,
1070 MAX_SCHEDULE_TIMEOUT,
1071 to_rps_client(file));
258a5ede 1072 if (ret)
bb6dc8d9 1073 goto out;
258a5ede 1074
bb6dc8d9 1075 ret = i915_gem_object_pin_pages(obj);
258a5ede 1076 if (ret)
bb6dc8d9 1077 goto out;
673a394b 1078
bb6dc8d9 1079 ret = i915_gem_shmem_pread(obj, args);
9c870d03 1080 if (ret == -EFAULT || ret == -ENODEV)
bb6dc8d9 1081 ret = i915_gem_gtt_pread(obj, args);
b50a5371 1082
bb6dc8d9
CW
1083 i915_gem_object_unpin_pages(obj);
1084out:
f0cd5182 1085 i915_gem_object_put(obj);
eb01459f 1086 return ret;
673a394b
EA
1087}
1088
0839ccb8
KP
1089/* This is the fast write path which cannot handle
1090 * page faults in the source data
9b7530cc 1091 */
0839ccb8 1092
fe115628
CW
1093static inline bool
1094ggtt_write(struct io_mapping *mapping,
1095 loff_t base, int offset,
1096 char __user *user_data, int length)
9b7530cc 1097{
4f0c7cfb 1098 void *vaddr;
0839ccb8 1099 unsigned long unwritten;
9b7530cc 1100
4f0c7cfb 1101 /* We can use the cpu mem copy function because this is X86. */
fe115628
CW
1102 vaddr = (void __force *)io_mapping_map_atomic_wc(mapping, base);
1103 unwritten = __copy_from_user_inatomic_nocache(vaddr + offset,
0839ccb8 1104 user_data, length);
fe115628
CW
1105 io_mapping_unmap_atomic(vaddr);
1106 if (unwritten) {
1107 vaddr = (void __force *)
1108 io_mapping_map_wc(mapping, base, PAGE_SIZE);
1109 unwritten = copy_from_user(vaddr + offset, user_data, length);
1110 io_mapping_unmap(vaddr);
1111 }
bb6dc8d9 1112
bb6dc8d9
CW
1113 return unwritten;
1114}
1115
3de09aa3
EA
1116/**
1117 * This is the fast pwrite path, where we copy the data directly from the
1118 * user into the GTT, uncached.
fe115628 1119 * @obj: i915 GEM object
14bb2c11 1120 * @args: pwrite arguments structure
3de09aa3 1121 */
673a394b 1122static int
fe115628
CW
1123i915_gem_gtt_pwrite_fast(struct drm_i915_gem_object *obj,
1124 const struct drm_i915_gem_pwrite *args)
673a394b 1125{
fe115628 1126 struct drm_i915_private *i915 = to_i915(obj->base.dev);
4f1959ee
AS
1127 struct i915_ggtt *ggtt = &i915->ggtt;
1128 struct drm_mm_node node;
fe115628
CW
1129 struct i915_vma *vma;
1130 u64 remain, offset;
1131 void __user *user_data;
4f1959ee 1132 int ret;
b50a5371 1133
fe115628
CW
1134 ret = mutex_lock_interruptible(&i915->drm.struct_mutex);
1135 if (ret)
1136 return ret;
935aaa69 1137
9c870d03 1138 intel_runtime_pm_get(i915);
058d88c4 1139 vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0,
de895082 1140 PIN_MAPPABLE | PIN_NONBLOCK);
18034584
CW
1141 if (!IS_ERR(vma)) {
1142 node.start = i915_ggtt_offset(vma);
1143 node.allocated = false;
49ef5294 1144 ret = i915_vma_put_fence(vma);
18034584
CW
1145 if (ret) {
1146 i915_vma_unpin(vma);
1147 vma = ERR_PTR(ret);
1148 }
1149 }
058d88c4 1150 if (IS_ERR(vma)) {
bb6dc8d9 1151 ret = insert_mappable_node(ggtt, &node, PAGE_SIZE);
4f1959ee 1152 if (ret)
fe115628
CW
1153 goto out_unlock;
1154 GEM_BUG_ON(!node.allocated);
4f1959ee 1155 }
935aaa69
DV
1156
1157 ret = i915_gem_object_set_to_gtt_domain(obj, true);
1158 if (ret)
1159 goto out_unpin;
1160
fe115628
CW
1161 mutex_unlock(&i915->drm.struct_mutex);
1162
b19482d7 1163 intel_fb_obj_invalidate(obj, ORIGIN_CPU);
063e4e6b 1164
4f1959ee
AS
1165 user_data = u64_to_user_ptr(args->data_ptr);
1166 offset = args->offset;
1167 remain = args->size;
1168 while (remain) {
673a394b
EA
1169 /* Operation in this page
1170 *
0839ccb8
KP
1171 * page_base = page offset within aperture
1172 * page_offset = offset within page
1173 * page_length = bytes to copy for this page
673a394b 1174 */
4f1959ee 1175 u32 page_base = node.start;
bb6dc8d9
CW
1176 unsigned int page_offset = offset_in_page(offset);
1177 unsigned int page_length = PAGE_SIZE - page_offset;
4f1959ee
AS
1178 page_length = remain < page_length ? remain : page_length;
1179 if (node.allocated) {
1180 wmb(); /* flush the write before we modify the GGTT */
1181 ggtt->base.insert_page(&ggtt->base,
1182 i915_gem_object_get_dma_address(obj, offset >> PAGE_SHIFT),
1183 node.start, I915_CACHE_NONE, 0);
1184 wmb(); /* flush modifications to the GGTT (insert_page) */
1185 } else {
1186 page_base += offset & PAGE_MASK;
1187 }
0839ccb8 1188 /* If we get a fault while copying data, then (presumably) our
3de09aa3
EA
1189 * source page isn't available. Return the error and we'll
1190 * retry in the slow path.
b50a5371
AS
1191 * If the object is non-shmem backed, we retry again with the
1192 * path that handles page fault.
0839ccb8 1193 */
fe115628
CW
1194 if (ggtt_write(&ggtt->mappable, page_base, page_offset,
1195 user_data, page_length)) {
1196 ret = -EFAULT;
1197 break;
935aaa69 1198 }
673a394b 1199
0839ccb8
KP
1200 remain -= page_length;
1201 user_data += page_length;
1202 offset += page_length;
673a394b 1203 }
b19482d7 1204 intel_fb_obj_flush(obj, false, ORIGIN_CPU);
fe115628
CW
1205
1206 mutex_lock(&i915->drm.struct_mutex);
935aaa69 1207out_unpin:
4f1959ee
AS
1208 if (node.allocated) {
1209 wmb();
1210 ggtt->base.clear_range(&ggtt->base,
4fb84d99 1211 node.start, node.size);
4f1959ee
AS
1212 remove_mappable_node(&node);
1213 } else {
058d88c4 1214 i915_vma_unpin(vma);
4f1959ee 1215 }
fe115628 1216out_unlock:
9c870d03 1217 intel_runtime_pm_put(i915);
fe115628 1218 mutex_unlock(&i915->drm.struct_mutex);
3de09aa3 1219 return ret;
673a394b
EA
1220}
1221
3043c60c 1222static int
fe115628 1223shmem_pwrite_slow(struct page *page, int offset, int length,
d174bd64
DV
1224 char __user *user_data,
1225 bool page_do_bit17_swizzling,
1226 bool needs_clflush_before,
1227 bool needs_clflush_after)
673a394b 1228{
d174bd64
DV
1229 char *vaddr;
1230 int ret;
e5281ccd 1231
d174bd64 1232 vaddr = kmap(page);
e7e58eb5 1233 if (unlikely(needs_clflush_before || page_do_bit17_swizzling))
fe115628 1234 shmem_clflush_swizzled_range(vaddr + offset, length,
23c18c71 1235 page_do_bit17_swizzling);
d174bd64 1236 if (page_do_bit17_swizzling)
fe115628
CW
1237 ret = __copy_from_user_swizzled(vaddr, offset, user_data,
1238 length);
d174bd64 1239 else
fe115628 1240 ret = __copy_from_user(vaddr + offset, user_data, length);
d174bd64 1241 if (needs_clflush_after)
fe115628 1242 shmem_clflush_swizzled_range(vaddr + offset, length,
23c18c71 1243 page_do_bit17_swizzling);
d174bd64 1244 kunmap(page);
40123c1f 1245
755d2218 1246 return ret ? -EFAULT : 0;
40123c1f
EA
1247}
1248
fe115628
CW
1249/* Per-page copy function for the shmem pwrite fastpath.
1250 * Flushes invalid cachelines before writing to the target if
1251 * needs_clflush_before is set and flushes out any written cachelines after
1252 * writing if needs_clflush is set.
1253 */
40123c1f 1254static int
fe115628
CW
1255shmem_pwrite(struct page *page, int offset, int len, char __user *user_data,
1256 bool page_do_bit17_swizzling,
1257 bool needs_clflush_before,
1258 bool needs_clflush_after)
40123c1f 1259{
fe115628
CW
1260 int ret;
1261
1262 ret = -ENODEV;
1263 if (!page_do_bit17_swizzling) {
1264 char *vaddr = kmap_atomic(page);
1265
1266 if (needs_clflush_before)
1267 drm_clflush_virt_range(vaddr + offset, len);
1268 ret = __copy_from_user_inatomic(vaddr + offset, user_data, len);
1269 if (needs_clflush_after)
1270 drm_clflush_virt_range(vaddr + offset, len);
1271
1272 kunmap_atomic(vaddr);
1273 }
1274 if (ret == 0)
1275 return ret;
1276
1277 return shmem_pwrite_slow(page, offset, len, user_data,
1278 page_do_bit17_swizzling,
1279 needs_clflush_before,
1280 needs_clflush_after);
1281}
1282
1283static int
1284i915_gem_shmem_pwrite(struct drm_i915_gem_object *obj,
1285 const struct drm_i915_gem_pwrite *args)
1286{
1287 struct drm_i915_private *i915 = to_i915(obj->base.dev);
1288 void __user *user_data;
1289 u64 remain;
1290 unsigned int obj_do_bit17_swizzling;
1291 unsigned int partial_cacheline_write;
43394c7d 1292 unsigned int needs_clflush;
fe115628
CW
1293 unsigned int offset, idx;
1294 int ret;
40123c1f 1295
fe115628 1296 ret = mutex_lock_interruptible(&i915->drm.struct_mutex);
755d2218
CW
1297 if (ret)
1298 return ret;
1299
fe115628
CW
1300 ret = i915_gem_obj_prepare_shmem_write(obj, &needs_clflush);
1301 mutex_unlock(&i915->drm.struct_mutex);
1302 if (ret)
1303 return ret;
673a394b 1304
fe115628
CW
1305 obj_do_bit17_swizzling = 0;
1306 if (i915_gem_object_needs_bit17_swizzle(obj))
1307 obj_do_bit17_swizzling = BIT(17);
e5281ccd 1308
fe115628
CW
1309 /* If we don't overwrite a cacheline completely we need to be
1310 * careful to have up-to-date data by first clflushing. Don't
1311 * overcomplicate things and flush the entire patch.
1312 */
1313 partial_cacheline_write = 0;
1314 if (needs_clflush & CLFLUSH_BEFORE)
1315 partial_cacheline_write = boot_cpu_data.x86_clflush_size - 1;
9da3da66 1316
fe115628
CW
1317 user_data = u64_to_user_ptr(args->data_ptr);
1318 remain = args->size;
1319 offset = offset_in_page(args->offset);
1320 for (idx = args->offset >> PAGE_SHIFT; remain; idx++) {
1321 struct page *page = i915_gem_object_get_page(obj, idx);
1322 int length;
40123c1f 1323
fe115628
CW
1324 length = remain;
1325 if (offset + length > PAGE_SIZE)
1326 length = PAGE_SIZE - offset;
755d2218 1327
fe115628
CW
1328 ret = shmem_pwrite(page, offset, length, user_data,
1329 page_to_phys(page) & obj_do_bit17_swizzling,
1330 (offset | length) & partial_cacheline_write,
1331 needs_clflush & CLFLUSH_AFTER);
755d2218 1332 if (ret)
fe115628 1333 break;
755d2218 1334
fe115628
CW
1335 remain -= length;
1336 user_data += length;
1337 offset = 0;
8c59967c 1338 }
673a394b 1339
de152b62 1340 intel_fb_obj_flush(obj, false, ORIGIN_CPU);
fe115628 1341 i915_gem_obj_finish_shmem_access(obj);
40123c1f 1342 return ret;
673a394b
EA
1343}
1344
1345/**
1346 * Writes data to the object referenced by handle.
14bb2c11
TU
1347 * @dev: drm device
1348 * @data: ioctl data blob
1349 * @file: drm file
673a394b
EA
1350 *
1351 * On error, the contents of the buffer that were to be modified are undefined.
1352 */
1353int
1354i915_gem_pwrite_ioctl(struct drm_device *dev, void *data,
fbd5a26d 1355 struct drm_file *file)
673a394b
EA
1356{
1357 struct drm_i915_gem_pwrite *args = data;
05394f39 1358 struct drm_i915_gem_object *obj;
51311d0a
CW
1359 int ret;
1360
1361 if (args->size == 0)
1362 return 0;
1363
1364 if (!access_ok(VERIFY_READ,
3ed605bc 1365 u64_to_user_ptr(args->data_ptr),
51311d0a
CW
1366 args->size))
1367 return -EFAULT;
1368
03ac0642 1369 obj = i915_gem_object_lookup(file, args->handle);
258a5ede
CW
1370 if (!obj)
1371 return -ENOENT;
673a394b 1372
7dcd2499 1373 /* Bounds check destination. */
05394f39
CW
1374 if (args->offset > obj->base.size ||
1375 args->size > obj->base.size - args->offset) {
ce9d419d 1376 ret = -EINVAL;
258a5ede 1377 goto err;
ce9d419d
CW
1378 }
1379
db53a302
CW
1380 trace_i915_gem_object_pwrite(obj, args->offset, args->size);
1381
e95433c7
CW
1382 ret = i915_gem_object_wait(obj,
1383 I915_WAIT_INTERRUPTIBLE |
1384 I915_WAIT_ALL,
1385 MAX_SCHEDULE_TIMEOUT,
1386 to_rps_client(file));
258a5ede
CW
1387 if (ret)
1388 goto err;
1389
fe115628 1390 ret = i915_gem_object_pin_pages(obj);
258a5ede 1391 if (ret)
fe115628 1392 goto err;
258a5ede 1393
935aaa69 1394 ret = -EFAULT;
673a394b
EA
1395 /* We can only do the GTT pwrite on untiled buffers, as otherwise
1396 * it would end up going through the fenced access, and we'll get
1397 * different detiling behavior between reading and writing.
1398 * pread/pwrite currently are reading and writing from the CPU
1399 * perspective, requiring manual detiling by the client.
1400 */
6eae0059 1401 if (!i915_gem_object_has_struct_page(obj) ||
9c870d03 1402 cpu_write_needs_clflush(obj))
935aaa69
DV
1403 /* Note that the gtt paths might fail with non-page-backed user
1404 * pointers (e.g. gtt mappings when moving data between
9c870d03
CW
1405 * textures). Fallback to the shmem path in that case.
1406 */
fe115628 1407 ret = i915_gem_gtt_pwrite_fast(obj, args);
673a394b 1408
d1054ee4 1409 if (ret == -EFAULT || ret == -ENOSPC) {
6a2c4232
CW
1410 if (obj->phys_handle)
1411 ret = i915_gem_phys_pwrite(obj, args, file);
b50a5371 1412 else
fe115628 1413 ret = i915_gem_shmem_pwrite(obj, args);
6a2c4232 1414 }
5c0480f2 1415
fe115628 1416 i915_gem_object_unpin_pages(obj);
258a5ede 1417err:
f0cd5182 1418 i915_gem_object_put(obj);
258a5ede 1419 return ret;
673a394b
EA
1420}
1421
d243ad82 1422static inline enum fb_op_origin
aeecc969
CW
1423write_origin(struct drm_i915_gem_object *obj, unsigned domain)
1424{
50349247
CW
1425 return (domain == I915_GEM_DOMAIN_GTT ?
1426 obj->frontbuffer_ggtt_origin : ORIGIN_CPU);
aeecc969
CW
1427}
1428
40e62d5d
CW
1429static void i915_gem_object_bump_inactive_ggtt(struct drm_i915_gem_object *obj)
1430{
1431 struct drm_i915_private *i915;
1432 struct list_head *list;
1433 struct i915_vma *vma;
1434
1435 list_for_each_entry(vma, &obj->vma_list, obj_link) {
1436 if (!i915_vma_is_ggtt(vma))
1437 continue;
1438
1439 if (i915_vma_is_active(vma))
1440 continue;
1441
1442 if (!drm_mm_node_allocated(&vma->node))
1443 continue;
1444
1445 list_move_tail(&vma->vm_link, &vma->vm->inactive_list);
1446 }
1447
1448 i915 = to_i915(obj->base.dev);
1449 list = obj->bind_count ? &i915->mm.bound_list : &i915->mm.unbound_list;
56cea323 1450 list_move_tail(&obj->global_link, list);
40e62d5d
CW
1451}
1452
673a394b 1453/**
2ef7eeaa
EA
1454 * Called when user space prepares to use an object with the CPU, either
1455 * through the mmap ioctl's mapping or a GTT mapping.
14bb2c11
TU
1456 * @dev: drm device
1457 * @data: ioctl data blob
1458 * @file: drm file
673a394b
EA
1459 */
1460int
1461i915_gem_set_domain_ioctl(struct drm_device *dev, void *data,
05394f39 1462 struct drm_file *file)
673a394b
EA
1463{
1464 struct drm_i915_gem_set_domain *args = data;
05394f39 1465 struct drm_i915_gem_object *obj;
2ef7eeaa
EA
1466 uint32_t read_domains = args->read_domains;
1467 uint32_t write_domain = args->write_domain;
40e62d5d 1468 int err;
673a394b 1469
2ef7eeaa 1470 /* Only handle setting domains to types used by the CPU. */
b8f9096d 1471 if ((write_domain | read_domains) & I915_GEM_GPU_DOMAINS)
2ef7eeaa
EA
1472 return -EINVAL;
1473
1474 /* Having something in the write domain implies it's in the read
1475 * domain, and only that read domain. Enforce that in the request.
1476 */
1477 if (write_domain != 0 && read_domains != write_domain)
1478 return -EINVAL;
1479
03ac0642 1480 obj = i915_gem_object_lookup(file, args->handle);
b8f9096d
CW
1481 if (!obj)
1482 return -ENOENT;
673a394b 1483
3236f57a
CW
1484 /* Try to flush the object off the GPU without holding the lock.
1485 * We will repeat the flush holding the lock in the normal manner
1486 * to catch cases where we are gazumped.
1487 */
40e62d5d 1488 err = i915_gem_object_wait(obj,
e95433c7
CW
1489 I915_WAIT_INTERRUPTIBLE |
1490 (write_domain ? I915_WAIT_ALL : 0),
1491 MAX_SCHEDULE_TIMEOUT,
1492 to_rps_client(file));
40e62d5d 1493 if (err)
f0cd5182 1494 goto out;
b8f9096d 1495
40e62d5d
CW
1496 /* Flush and acquire obj->pages so that we are coherent through
1497 * direct access in memory with previous cached writes through
1498 * shmemfs and that our cache domain tracking remains valid.
1499 * For example, if the obj->filp was moved to swap without us
1500 * being notified and releasing the pages, we would mistakenly
1501 * continue to assume that the obj remained out of the CPU cached
1502 * domain.
1503 */
1504 err = i915_gem_object_pin_pages(obj);
1505 if (err)
f0cd5182 1506 goto out;
40e62d5d
CW
1507
1508 err = i915_mutex_lock_interruptible(dev);
1509 if (err)
f0cd5182 1510 goto out_unpin;
3236f57a 1511
43566ded 1512 if (read_domains & I915_GEM_DOMAIN_GTT)
40e62d5d 1513 err = i915_gem_object_set_to_gtt_domain(obj, write_domain != 0);
43566ded 1514 else
40e62d5d 1515 err = i915_gem_object_set_to_cpu_domain(obj, write_domain != 0);
2ef7eeaa 1516
40e62d5d
CW
1517 /* And bump the LRU for this access */
1518 i915_gem_object_bump_inactive_ggtt(obj);
031b698a 1519
673a394b 1520 mutex_unlock(&dev->struct_mutex);
b8f9096d 1521
40e62d5d
CW
1522 if (write_domain != 0)
1523 intel_fb_obj_invalidate(obj, write_origin(obj, write_domain));
1524
f0cd5182 1525out_unpin:
40e62d5d 1526 i915_gem_object_unpin_pages(obj);
f0cd5182
CW
1527out:
1528 i915_gem_object_put(obj);
40e62d5d 1529 return err;
673a394b
EA
1530}
1531
1532/**
1533 * Called when user space has done writes to this buffer
14bb2c11
TU
1534 * @dev: drm device
1535 * @data: ioctl data blob
1536 * @file: drm file
673a394b
EA
1537 */
1538int
1539i915_gem_sw_finish_ioctl(struct drm_device *dev, void *data,
05394f39 1540 struct drm_file *file)
673a394b
EA
1541{
1542 struct drm_i915_gem_sw_finish *args = data;
05394f39 1543 struct drm_i915_gem_object *obj;
c21724cc 1544 int err = 0;
1d7cfea1 1545
03ac0642 1546 obj = i915_gem_object_lookup(file, args->handle);
c21724cc
CW
1547 if (!obj)
1548 return -ENOENT;
673a394b 1549
673a394b 1550 /* Pinned buffers may be scanout, so flush the cache */
c21724cc
CW
1551 if (READ_ONCE(obj->pin_display)) {
1552 err = i915_mutex_lock_interruptible(dev);
1553 if (!err) {
1554 i915_gem_object_flush_cpu_write_domain(obj);
1555 mutex_unlock(&dev->struct_mutex);
1556 }
1557 }
e47c68e9 1558
f0cd5182 1559 i915_gem_object_put(obj);
c21724cc 1560 return err;
673a394b
EA
1561}
1562
1563/**
14bb2c11
TU
1564 * i915_gem_mmap_ioctl - Maps the contents of an object, returning the address
1565 * it is mapped to.
1566 * @dev: drm device
1567 * @data: ioctl data blob
1568 * @file: drm file
673a394b
EA
1569 *
1570 * While the mapping holds a reference on the contents of the object, it doesn't
1571 * imply a ref on the object itself.
34367381
DV
1572 *
1573 * IMPORTANT:
1574 *
1575 * DRM driver writers who look a this function as an example for how to do GEM
1576 * mmap support, please don't implement mmap support like here. The modern way
1577 * to implement DRM mmap support is with an mmap offset ioctl (like
1578 * i915_gem_mmap_gtt) and then using the mmap syscall on the DRM fd directly.
1579 * That way debug tooling like valgrind will understand what's going on, hiding
1580 * the mmap call in a driver private ioctl will break that. The i915 driver only
1581 * does cpu mmaps this way because we didn't know better.
673a394b
EA
1582 */
1583int
1584i915_gem_mmap_ioctl(struct drm_device *dev, void *data,
05394f39 1585 struct drm_file *file)
673a394b
EA
1586{
1587 struct drm_i915_gem_mmap *args = data;
03ac0642 1588 struct drm_i915_gem_object *obj;
673a394b
EA
1589 unsigned long addr;
1590
1816f923
AG
1591 if (args->flags & ~(I915_MMAP_WC))
1592 return -EINVAL;
1593
568a58e5 1594 if (args->flags & I915_MMAP_WC && !boot_cpu_has(X86_FEATURE_PAT))
1816f923
AG
1595 return -ENODEV;
1596
03ac0642
CW
1597 obj = i915_gem_object_lookup(file, args->handle);
1598 if (!obj)
bf79cb91 1599 return -ENOENT;
673a394b 1600
1286ff73
DV
1601 /* prime objects have no backing filp to GEM mmap
1602 * pages from.
1603 */
03ac0642 1604 if (!obj->base.filp) {
f0cd5182 1605 i915_gem_object_put(obj);
1286ff73
DV
1606 return -EINVAL;
1607 }
1608
03ac0642 1609 addr = vm_mmap(obj->base.filp, 0, args->size,
673a394b
EA
1610 PROT_READ | PROT_WRITE, MAP_SHARED,
1611 args->offset);
1816f923
AG
1612 if (args->flags & I915_MMAP_WC) {
1613 struct mm_struct *mm = current->mm;
1614 struct vm_area_struct *vma;
1615
80a89a5e 1616 if (down_write_killable(&mm->mmap_sem)) {
f0cd5182 1617 i915_gem_object_put(obj);
80a89a5e
MH
1618 return -EINTR;
1619 }
1816f923
AG
1620 vma = find_vma(mm, addr);
1621 if (vma)
1622 vma->vm_page_prot =
1623 pgprot_writecombine(vm_get_page_prot(vma->vm_flags));
1624 else
1625 addr = -ENOMEM;
1626 up_write(&mm->mmap_sem);
aeecc969
CW
1627
1628 /* This may race, but that's ok, it only gets set */
50349247 1629 WRITE_ONCE(obj->frontbuffer_ggtt_origin, ORIGIN_CPU);
1816f923 1630 }
f0cd5182 1631 i915_gem_object_put(obj);
673a394b
EA
1632 if (IS_ERR((void *)addr))
1633 return addr;
1634
1635 args->addr_ptr = (uint64_t) addr;
1636
1637 return 0;
1638}
1639
03af84fe
CW
1640static unsigned int tile_row_pages(struct drm_i915_gem_object *obj)
1641{
1642 u64 size;
1643
1644 size = i915_gem_object_get_stride(obj);
1645 size *= i915_gem_object_get_tiling(obj) == I915_TILING_Y ? 32 : 8;
1646
1647 return size >> PAGE_SHIFT;
1648}
1649
4cc69075
CW
1650/**
1651 * i915_gem_mmap_gtt_version - report the current feature set for GTT mmaps
1652 *
1653 * A history of the GTT mmap interface:
1654 *
1655 * 0 - Everything had to fit into the GTT. Both parties of a memcpy had to
1656 * aligned and suitable for fencing, and still fit into the available
1657 * mappable space left by the pinned display objects. A classic problem
1658 * we called the page-fault-of-doom where we would ping-pong between
1659 * two objects that could not fit inside the GTT and so the memcpy
1660 * would page one object in at the expense of the other between every
1661 * single byte.
1662 *
1663 * 1 - Objects can be any size, and have any compatible fencing (X Y, or none
1664 * as set via i915_gem_set_tiling() [DRM_I915_GEM_SET_TILING]). If the
1665 * object is too large for the available space (or simply too large
1666 * for the mappable aperture!), a view is created instead and faulted
1667 * into userspace. (This view is aligned and sized appropriately for
1668 * fenced access.)
1669 *
1670 * Restrictions:
1671 *
1672 * * snoopable objects cannot be accessed via the GTT. It can cause machine
1673 * hangs on some architectures, corruption on others. An attempt to service
1674 * a GTT page fault from a snoopable object will generate a SIGBUS.
1675 *
1676 * * the object must be able to fit into RAM (physical memory, though no
1677 * limited to the mappable aperture).
1678 *
1679 *
1680 * Caveats:
1681 *
1682 * * a new GTT page fault will synchronize rendering from the GPU and flush
1683 * all data to system memory. Subsequent access will not be synchronized.
1684 *
1685 * * all mappings are revoked on runtime device suspend.
1686 *
1687 * * there are only 8, 16 or 32 fence registers to share between all users
1688 * (older machines require fence register for display and blitter access
1689 * as well). Contention of the fence registers will cause the previous users
1690 * to be unmapped and any new access will generate new page faults.
1691 *
1692 * * running out of memory while servicing a fault may generate a SIGBUS,
1693 * rather than the expected SIGSEGV.
1694 */
1695int i915_gem_mmap_gtt_version(void)
1696{
1697 return 1;
1698}
1699
de151cf6
JB
1700/**
1701 * i915_gem_fault - fault a page into the GTT
058d88c4 1702 * @area: CPU VMA in question
d9072a3e 1703 * @vmf: fault info
de151cf6
JB
1704 *
1705 * The fault handler is set up by drm_gem_mmap() when a object is GTT mapped
1706 * from userspace. The fault handler takes care of binding the object to
1707 * the GTT (if needed), allocating and programming a fence register (again,
1708 * only if needed based on whether the old reg is still valid or the object
1709 * is tiled) and inserting a new PTE into the faulting process.
1710 *
1711 * Note that the faulting process may involve evicting existing objects
1712 * from the GTT and/or fence registers to make room. So performance may
1713 * suffer if the GTT working set is large or there are few fence registers
1714 * left.
4cc69075
CW
1715 *
1716 * The current feature set supported by i915_gem_fault() and thus GTT mmaps
1717 * is exposed via I915_PARAM_MMAP_GTT_VERSION (see i915_gem_mmap_gtt_version).
de151cf6 1718 */
058d88c4 1719int i915_gem_fault(struct vm_area_struct *area, struct vm_fault *vmf)
de151cf6 1720{
03af84fe 1721#define MIN_CHUNK_PAGES ((1 << 20) >> PAGE_SHIFT) /* 1 MiB */
058d88c4 1722 struct drm_i915_gem_object *obj = to_intel_bo(area->vm_private_data);
05394f39 1723 struct drm_device *dev = obj->base.dev;
72e96d64
JL
1724 struct drm_i915_private *dev_priv = to_i915(dev);
1725 struct i915_ggtt *ggtt = &dev_priv->ggtt;
b8f9096d 1726 bool write = !!(vmf->flags & FAULT_FLAG_WRITE);
058d88c4 1727 struct i915_vma *vma;
de151cf6 1728 pgoff_t page_offset;
82118877 1729 unsigned int flags;
b8f9096d 1730 int ret;
f65c9168 1731
de151cf6 1732 /* We don't use vmf->pgoff since that has the fake offset */
058d88c4 1733 page_offset = ((unsigned long)vmf->virtual_address - area->vm_start) >>
de151cf6
JB
1734 PAGE_SHIFT;
1735
db53a302
CW
1736 trace_i915_gem_object_fault(obj, page_offset, true, write);
1737
6e4930f6 1738 /* Try to flush the object off the GPU first without holding the lock.
b8f9096d 1739 * Upon acquiring the lock, we will perform our sanity checks and then
6e4930f6
CW
1740 * repeat the flush holding the lock in the normal manner to catch cases
1741 * where we are gazumped.
1742 */
e95433c7
CW
1743 ret = i915_gem_object_wait(obj,
1744 I915_WAIT_INTERRUPTIBLE,
1745 MAX_SCHEDULE_TIMEOUT,
1746 NULL);
6e4930f6 1747 if (ret)
b8f9096d
CW
1748 goto err;
1749
40e62d5d
CW
1750 ret = i915_gem_object_pin_pages(obj);
1751 if (ret)
1752 goto err;
1753
b8f9096d
CW
1754 intel_runtime_pm_get(dev_priv);
1755
1756 ret = i915_mutex_lock_interruptible(dev);
1757 if (ret)
1758 goto err_rpm;
6e4930f6 1759
eb119bd6 1760 /* Access to snoopable pages through the GTT is incoherent. */
0031fb96 1761 if (obj->cache_level != I915_CACHE_NONE && !HAS_LLC(dev_priv)) {
ddeff6ee 1762 ret = -EFAULT;
b8f9096d 1763 goto err_unlock;
eb119bd6
CW
1764 }
1765
82118877
CW
1766 /* If the object is smaller than a couple of partial vma, it is
1767 * not worth only creating a single partial vma - we may as well
1768 * clear enough space for the full object.
1769 */
1770 flags = PIN_MAPPABLE;
1771 if (obj->base.size > 2 * MIN_CHUNK_PAGES << PAGE_SHIFT)
1772 flags |= PIN_NONBLOCK | PIN_NONFAULT;
1773
a61007a8 1774 /* Now pin it into the GTT as needed */
82118877 1775 vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0, flags);
a61007a8
CW
1776 if (IS_ERR(vma)) {
1777 struct i915_ggtt_view view;
03af84fe
CW
1778 unsigned int chunk_size;
1779
a61007a8 1780 /* Use a partial view if it is bigger than available space */
03af84fe
CW
1781 chunk_size = MIN_CHUNK_PAGES;
1782 if (i915_gem_object_is_tiled(obj))
0ef723cb 1783 chunk_size = roundup(chunk_size, tile_row_pages(obj));
e7ded2d7 1784
c5ad54cf
JL
1785 memset(&view, 0, sizeof(view));
1786 view.type = I915_GGTT_VIEW_PARTIAL;
1787 view.params.partial.offset = rounddown(page_offset, chunk_size);
1788 view.params.partial.size =
a61007a8 1789 min_t(unsigned int, chunk_size,
908b1232 1790 vma_pages(area) - view.params.partial.offset);
c5ad54cf 1791
aa136d9d
CW
1792 /* If the partial covers the entire object, just create a
1793 * normal VMA.
1794 */
1795 if (chunk_size >= obj->base.size >> PAGE_SHIFT)
1796 view.type = I915_GGTT_VIEW_NORMAL;
1797
50349247
CW
1798 /* Userspace is now writing through an untracked VMA, abandon
1799 * all hope that the hardware is able to track future writes.
1800 */
1801 obj->frontbuffer_ggtt_origin = ORIGIN_CPU;
1802
a61007a8
CW
1803 vma = i915_gem_object_ggtt_pin(obj, &view, 0, 0, PIN_MAPPABLE);
1804 }
058d88c4
CW
1805 if (IS_ERR(vma)) {
1806 ret = PTR_ERR(vma);
b8f9096d 1807 goto err_unlock;
058d88c4 1808 }
4a684a41 1809
c9839303
CW
1810 ret = i915_gem_object_set_to_gtt_domain(obj, write);
1811 if (ret)
b8f9096d 1812 goto err_unpin;
74898d7e 1813
49ef5294 1814 ret = i915_vma_get_fence(vma);
d9e86c0e 1815 if (ret)
b8f9096d 1816 goto err_unpin;
7d1c4804 1817
275f039d 1818 /* Mark as being mmapped into userspace for later revocation */
9c870d03 1819 assert_rpm_wakelock_held(dev_priv);
275f039d
CW
1820 if (list_empty(&obj->userfault_link))
1821 list_add(&obj->userfault_link, &dev_priv->mm.userfault_list);
275f039d 1822
b90b91d8 1823 /* Finally, remap it using the new GTT offset */
c58305af
CW
1824 ret = remap_io_mapping(area,
1825 area->vm_start + (vma->ggtt_view.params.partial.offset << PAGE_SHIFT),
1826 (ggtt->mappable_base + vma->node.start) >> PAGE_SHIFT,
1827 min_t(u64, vma->size, area->vm_end - area->vm_start),
1828 &ggtt->mappable);
a61007a8 1829
b8f9096d 1830err_unpin:
058d88c4 1831 __i915_vma_unpin(vma);
b8f9096d 1832err_unlock:
de151cf6 1833 mutex_unlock(&dev->struct_mutex);
b8f9096d
CW
1834err_rpm:
1835 intel_runtime_pm_put(dev_priv);
40e62d5d 1836 i915_gem_object_unpin_pages(obj);
b8f9096d 1837err:
de151cf6 1838 switch (ret) {
d9bc7e9f 1839 case -EIO:
2232f031
DV
1840 /*
1841 * We eat errors when the gpu is terminally wedged to avoid
1842 * userspace unduly crashing (gl has no provisions for mmaps to
1843 * fail). But any other -EIO isn't ours (e.g. swap in failure)
1844 * and so needs to be reported.
1845 */
1846 if (!i915_terminally_wedged(&dev_priv->gpu_error)) {
f65c9168
PZ
1847 ret = VM_FAULT_SIGBUS;
1848 break;
1849 }
045e769a 1850 case -EAGAIN:
571c608d
DV
1851 /*
1852 * EAGAIN means the gpu is hung and we'll wait for the error
1853 * handler to reset everything when re-faulting in
1854 * i915_mutex_lock_interruptible.
d9bc7e9f 1855 */
c715089f
CW
1856 case 0:
1857 case -ERESTARTSYS:
bed636ab 1858 case -EINTR:
e79e0fe3
DR
1859 case -EBUSY:
1860 /*
1861 * EBUSY is ok: this just means that another thread
1862 * already did the job.
1863 */
f65c9168
PZ
1864 ret = VM_FAULT_NOPAGE;
1865 break;
de151cf6 1866 case -ENOMEM:
f65c9168
PZ
1867 ret = VM_FAULT_OOM;
1868 break;
a7c2e1aa 1869 case -ENOSPC:
45d67817 1870 case -EFAULT:
f65c9168
PZ
1871 ret = VM_FAULT_SIGBUS;
1872 break;
de151cf6 1873 default:
a7c2e1aa 1874 WARN_ONCE(ret, "unhandled error in i915_gem_fault: %i\n", ret);
f65c9168
PZ
1875 ret = VM_FAULT_SIGBUS;
1876 break;
de151cf6 1877 }
f65c9168 1878 return ret;
de151cf6
JB
1879}
1880
901782b2
CW
1881/**
1882 * i915_gem_release_mmap - remove physical page mappings
1883 * @obj: obj in question
1884 *
af901ca1 1885 * Preserve the reservation of the mmapping with the DRM core code, but
901782b2
CW
1886 * relinquish ownership of the pages back to the system.
1887 *
1888 * It is vital that we remove the page mapping if we have mapped a tiled
1889 * object through the GTT and then lose the fence register due to
1890 * resource pressure. Similarly if the object has been moved out of the
1891 * aperture, than pages mapped into userspace must be revoked. Removing the
1892 * mapping will then trigger a page fault on the next user access, allowing
1893 * fixup by i915_gem_fault().
1894 */
d05ca301 1895void
05394f39 1896i915_gem_release_mmap(struct drm_i915_gem_object *obj)
901782b2 1897{
275f039d 1898 struct drm_i915_private *i915 = to_i915(obj->base.dev);
275f039d 1899
349f2ccf
CW
1900 /* Serialisation between user GTT access and our code depends upon
1901 * revoking the CPU's PTE whilst the mutex is held. The next user
1902 * pagefault then has to wait until we release the mutex.
9c870d03
CW
1903 *
1904 * Note that RPM complicates somewhat by adding an additional
1905 * requirement that operations to the GGTT be made holding the RPM
1906 * wakeref.
349f2ccf 1907 */
275f039d 1908 lockdep_assert_held(&i915->drm.struct_mutex);
9c870d03 1909 intel_runtime_pm_get(i915);
349f2ccf 1910
3594a3e2 1911 if (list_empty(&obj->userfault_link))
9c870d03 1912 goto out;
901782b2 1913
3594a3e2 1914 list_del_init(&obj->userfault_link);
6796cb16
DH
1915 drm_vma_node_unmap(&obj->base.vma_node,
1916 obj->base.dev->anon_inode->i_mapping);
349f2ccf
CW
1917
1918 /* Ensure that the CPU's PTE are revoked and there are not outstanding
1919 * memory transactions from userspace before we return. The TLB
1920 * flushing implied above by changing the PTE above *should* be
1921 * sufficient, an extra barrier here just provides us with a bit
1922 * of paranoid documentation about our requirement to serialise
1923 * memory writes before touching registers / GSM.
1924 */
1925 wmb();
9c870d03
CW
1926
1927out:
1928 intel_runtime_pm_put(i915);
901782b2
CW
1929}
1930
7c108fd8 1931void i915_gem_runtime_suspend(struct drm_i915_private *dev_priv)
eedd10f4 1932{
3594a3e2 1933 struct drm_i915_gem_object *obj, *on;
7c108fd8 1934 int i;
eedd10f4 1935
3594a3e2
CW
1936 /*
1937 * Only called during RPM suspend. All users of the userfault_list
1938 * must be holding an RPM wakeref to ensure that this can not
1939 * run concurrently with themselves (and use the struct_mutex for
1940 * protection between themselves).
1941 */
275f039d 1942
3594a3e2
CW
1943 list_for_each_entry_safe(obj, on,
1944 &dev_priv->mm.userfault_list, userfault_link) {
1945 list_del_init(&obj->userfault_link);
275f039d
CW
1946 drm_vma_node_unmap(&obj->base.vma_node,
1947 obj->base.dev->anon_inode->i_mapping);
275f039d 1948 }
7c108fd8
CW
1949
1950 /* The fence will be lost when the device powers down. If any were
1951 * in use by hardware (i.e. they are pinned), we should not be powering
1952 * down! All other fences will be reacquired by the user upon waking.
1953 */
1954 for (i = 0; i < dev_priv->num_fence_regs; i++) {
1955 struct drm_i915_fence_reg *reg = &dev_priv->fence_regs[i];
1956
1957 if (WARN_ON(reg->pin_count))
1958 continue;
1959
1960 if (!reg->vma)
1961 continue;
1962
1963 GEM_BUG_ON(!list_empty(&reg->vma->obj->userfault_link));
1964 reg->dirty = true;
1965 }
eedd10f4
CW
1966}
1967
ad1a7d20
CW
1968/**
1969 * i915_gem_get_ggtt_size - return required global GTT size for an object
a9f1481f 1970 * @dev_priv: i915 device
ad1a7d20
CW
1971 * @size: object size
1972 * @tiling_mode: tiling mode
1973 *
1974 * Return the required global GTT size for an object, taking into account
1975 * potential fence register mapping.
1976 */
a9f1481f
CW
1977u64 i915_gem_get_ggtt_size(struct drm_i915_private *dev_priv,
1978 u64 size, int tiling_mode)
92b88aeb 1979{
ad1a7d20 1980 u64 ggtt_size;
92b88aeb 1981
ad1a7d20
CW
1982 GEM_BUG_ON(size == 0);
1983
a9f1481f 1984 if (INTEL_GEN(dev_priv) >= 4 ||
e28f8711
CW
1985 tiling_mode == I915_TILING_NONE)
1986 return size;
92b88aeb
CW
1987
1988 /* Previous chips need a power-of-two fence region when tiling */
a9f1481f 1989 if (IS_GEN3(dev_priv))
ad1a7d20 1990 ggtt_size = 1024*1024;
92b88aeb 1991 else
ad1a7d20 1992 ggtt_size = 512*1024;
92b88aeb 1993
ad1a7d20
CW
1994 while (ggtt_size < size)
1995 ggtt_size <<= 1;
92b88aeb 1996
ad1a7d20 1997 return ggtt_size;
92b88aeb
CW
1998}
1999
de151cf6 2000/**
ad1a7d20 2001 * i915_gem_get_ggtt_alignment - return required global GTT alignment
a9f1481f 2002 * @dev_priv: i915 device
14bb2c11
TU
2003 * @size: object size
2004 * @tiling_mode: tiling mode
ad1a7d20 2005 * @fenced: is fenced alignment required or not
de151cf6 2006 *
ad1a7d20 2007 * Return the required global GTT alignment for an object, taking into account
5e783301 2008 * potential fence register mapping.
de151cf6 2009 */
a9f1481f 2010u64 i915_gem_get_ggtt_alignment(struct drm_i915_private *dev_priv, u64 size,
ad1a7d20 2011 int tiling_mode, bool fenced)
de151cf6 2012{
ad1a7d20
CW
2013 GEM_BUG_ON(size == 0);
2014
de151cf6
JB
2015 /*
2016 * Minimum alignment is 4k (GTT page size), but might be greater
2017 * if a fence register is needed for the object.
2018 */
a9f1481f 2019 if (INTEL_GEN(dev_priv) >= 4 || (!fenced && IS_G33(dev_priv)) ||
e28f8711 2020 tiling_mode == I915_TILING_NONE)
de151cf6
JB
2021 return 4096;
2022
a00b10c3
CW
2023 /*
2024 * Previous chips need to be aligned to the size of the smallest
2025 * fence register that can contain the object.
2026 */
a9f1481f 2027 return i915_gem_get_ggtt_size(dev_priv, size, tiling_mode);
a00b10c3
CW
2028}
2029
d8cb5086
CW
2030static int i915_gem_object_create_mmap_offset(struct drm_i915_gem_object *obj)
2031{
fac5e23e 2032 struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
f3f6184c 2033 int err;
da494d7c 2034
f3f6184c
CW
2035 err = drm_gem_create_mmap_offset(&obj->base);
2036 if (!err)
2037 return 0;
d8cb5086 2038
f3f6184c
CW
2039 /* We can idle the GPU locklessly to flush stale objects, but in order
2040 * to claim that space for ourselves, we need to take the big
2041 * struct_mutex to free the requests+objects and allocate our slot.
d8cb5086 2042 */
ea746f36 2043 err = i915_gem_wait_for_idle(dev_priv, I915_WAIT_INTERRUPTIBLE);
f3f6184c
CW
2044 if (err)
2045 return err;
2046
2047 err = i915_mutex_lock_interruptible(&dev_priv->drm);
2048 if (!err) {
2049 i915_gem_retire_requests(dev_priv);
2050 err = drm_gem_create_mmap_offset(&obj->base);
2051 mutex_unlock(&dev_priv->drm.struct_mutex);
2052 }
da494d7c 2053
f3f6184c 2054 return err;
d8cb5086
CW
2055}
2056
2057static void i915_gem_object_free_mmap_offset(struct drm_i915_gem_object *obj)
2058{
d8cb5086
CW
2059 drm_gem_free_mmap_offset(&obj->base);
2060}
2061
da6b51d0 2062int
ff72145b
DA
2063i915_gem_mmap_gtt(struct drm_file *file,
2064 struct drm_device *dev,
da6b51d0 2065 uint32_t handle,
ff72145b 2066 uint64_t *offset)
de151cf6 2067{
05394f39 2068 struct drm_i915_gem_object *obj;
de151cf6
JB
2069 int ret;
2070
03ac0642 2071 obj = i915_gem_object_lookup(file, handle);
f3f6184c
CW
2072 if (!obj)
2073 return -ENOENT;
ab18282d 2074
d8cb5086 2075 ret = i915_gem_object_create_mmap_offset(obj);
f3f6184c
CW
2076 if (ret == 0)
2077 *offset = drm_vma_node_offset_addr(&obj->base.vma_node);
de151cf6 2078
f0cd5182 2079 i915_gem_object_put(obj);
1d7cfea1 2080 return ret;
de151cf6
JB
2081}
2082
ff72145b
DA
2083/**
2084 * i915_gem_mmap_gtt_ioctl - prepare an object for GTT mmap'ing
2085 * @dev: DRM device
2086 * @data: GTT mapping ioctl data
2087 * @file: GEM object info
2088 *
2089 * Simply returns the fake offset to userspace so it can mmap it.
2090 * The mmap call will end up in drm_gem_mmap(), which will set things
2091 * up so we can get faults in the handler above.
2092 *
2093 * The fault handler will take care of binding the object into the GTT
2094 * (since it may have been evicted to make room for something), allocating
2095 * a fence register, and mapping the appropriate aperture address into
2096 * userspace.
2097 */
2098int
2099i915_gem_mmap_gtt_ioctl(struct drm_device *dev, void *data,
2100 struct drm_file *file)
2101{
2102 struct drm_i915_gem_mmap_gtt *args = data;
2103
da6b51d0 2104 return i915_gem_mmap_gtt(file, dev, args->handle, &args->offset);
ff72145b
DA
2105}
2106
225067ee
DV
2107/* Immediately discard the backing storage */
2108static void
2109i915_gem_object_truncate(struct drm_i915_gem_object *obj)
e5281ccd 2110{
4d6294bf 2111 i915_gem_object_free_mmap_offset(obj);
1286ff73 2112
4d6294bf
CW
2113 if (obj->base.filp == NULL)
2114 return;
e5281ccd 2115
225067ee
DV
2116 /* Our goal here is to return as much of the memory as
2117 * is possible back to the system as we are called from OOM.
2118 * To do this we must instruct the shmfs to drop all of its
2119 * backing pages, *now*.
2120 */
5537252b 2121 shmem_truncate_range(file_inode(obj->base.filp), 0, (loff_t)-1);
a4f5ea64 2122 obj->mm.madv = __I915_MADV_PURGED;
225067ee 2123}
e5281ccd 2124
5537252b 2125/* Try to discard unwanted pages */
03ac84f1 2126void __i915_gem_object_invalidate(struct drm_i915_gem_object *obj)
225067ee 2127{
5537252b
CW
2128 struct address_space *mapping;
2129
1233e2db
CW
2130 lockdep_assert_held(&obj->mm.lock);
2131 GEM_BUG_ON(obj->mm.pages);
2132
a4f5ea64 2133 switch (obj->mm.madv) {
5537252b
CW
2134 case I915_MADV_DONTNEED:
2135 i915_gem_object_truncate(obj);
2136 case __I915_MADV_PURGED:
2137 return;
2138 }
2139
2140 if (obj->base.filp == NULL)
2141 return;
2142
93c76a3d 2143 mapping = obj->base.filp->f_mapping,
5537252b 2144 invalidate_mapping_pages(mapping, 0, (loff_t)-1);
e5281ccd
CW
2145}
2146
5cdf5881 2147static void
03ac84f1
CW
2148i915_gem_object_put_pages_gtt(struct drm_i915_gem_object *obj,
2149 struct sg_table *pages)
673a394b 2150{
85d1225e
DG
2151 struct sgt_iter sgt_iter;
2152 struct page *page;
1286ff73 2153
2b3c8317 2154 __i915_gem_object_release_shmem(obj, pages);
673a394b 2155
03ac84f1 2156 i915_gem_gtt_finish_pages(obj, pages);
e2273302 2157
6dacfd2f 2158 if (i915_gem_object_needs_bit17_swizzle(obj))
03ac84f1 2159 i915_gem_object_save_bit_17_swizzle(obj, pages);
280b713b 2160
03ac84f1 2161 for_each_sgt_page(page, sgt_iter, pages) {
a4f5ea64 2162 if (obj->mm.dirty)
9da3da66 2163 set_page_dirty(page);
3ef94daa 2164
a4f5ea64 2165 if (obj->mm.madv == I915_MADV_WILLNEED)
9da3da66 2166 mark_page_accessed(page);
3ef94daa 2167
09cbfeaf 2168 put_page(page);
3ef94daa 2169 }
a4f5ea64 2170 obj->mm.dirty = false;
673a394b 2171
03ac84f1
CW
2172 sg_free_table(pages);
2173 kfree(pages);
37e680a1 2174}
6c085a72 2175
96d77634
CW
2176static void __i915_gem_object_reset_page_iter(struct drm_i915_gem_object *obj)
2177{
2178 struct radix_tree_iter iter;
2179 void **slot;
2180
a4f5ea64
CW
2181 radix_tree_for_each_slot(slot, &obj->mm.get_page.radix, &iter, 0)
2182 radix_tree_delete(&obj->mm.get_page.radix, iter.index);
96d77634
CW
2183}
2184
548625ee
CW
2185void __i915_gem_object_put_pages(struct drm_i915_gem_object *obj,
2186 enum i915_mm_subclass subclass)
37e680a1 2187{
03ac84f1 2188 struct sg_table *pages;
37e680a1 2189
a4f5ea64 2190 if (i915_gem_object_has_pinned_pages(obj))
03ac84f1 2191 return;
a5570178 2192
15717de2 2193 GEM_BUG_ON(obj->bind_count);
1233e2db
CW
2194 if (!READ_ONCE(obj->mm.pages))
2195 return;
2196
2197 /* May be called by shrinker from within get_pages() (on another bo) */
548625ee 2198 mutex_lock_nested(&obj->mm.lock, subclass);
1233e2db
CW
2199 if (unlikely(atomic_read(&obj->mm.pages_pin_count)))
2200 goto unlock;
3e123027 2201
a2165e31
CW
2202 /* ->put_pages might need to allocate memory for the bit17 swizzle
2203 * array, hence protect them from being reaped by removing them from gtt
2204 * lists early. */
03ac84f1
CW
2205 pages = fetch_and_zero(&obj->mm.pages);
2206 GEM_BUG_ON(!pages);
a2165e31 2207
a4f5ea64 2208 if (obj->mm.mapping) {
4b30cb23
CW
2209 void *ptr;
2210
a4f5ea64 2211 ptr = ptr_mask_bits(obj->mm.mapping);
4b30cb23
CW
2212 if (is_vmalloc_addr(ptr))
2213 vunmap(ptr);
fb8621d3 2214 else
4b30cb23
CW
2215 kunmap(kmap_to_page(ptr));
2216
a4f5ea64 2217 obj->mm.mapping = NULL;
0a798eb9
CW
2218 }
2219
96d77634
CW
2220 __i915_gem_object_reset_page_iter(obj);
2221
03ac84f1 2222 obj->ops->put_pages(obj, pages);
1233e2db
CW
2223unlock:
2224 mutex_unlock(&obj->mm.lock);
6c085a72
CW
2225}
2226
4ff340f0 2227static unsigned int swiotlb_max_size(void)
871dfbd6
CW
2228{
2229#if IS_ENABLED(CONFIG_SWIOTLB)
2230 return rounddown(swiotlb_nr_tbl() << IO_TLB_SHIFT, PAGE_SIZE);
2231#else
2232 return 0;
2233#endif
2234}
2235
0c40ce13
TU
2236static void i915_sg_trim(struct sg_table *orig_st)
2237{
2238 struct sg_table new_st;
2239 struct scatterlist *sg, *new_sg;
2240 unsigned int i;
2241
2242 if (orig_st->nents == orig_st->orig_nents)
2243 return;
2244
2245 if (sg_alloc_table(&new_st, orig_st->nents, GFP_KERNEL))
2246 return;
2247
2248 new_sg = new_st.sgl;
2249 for_each_sg(orig_st->sgl, sg, orig_st->nents, i) {
2250 sg_set_page(new_sg, sg_page(sg), sg->length, 0);
2251 /* called before being DMA mapped, no need to copy sg->dma_* */
2252 new_sg = sg_next(new_sg);
2253 }
2254
2255 sg_free_table(orig_st);
2256
2257 *orig_st = new_st;
2258}
2259
03ac84f1 2260static struct sg_table *
6c085a72 2261i915_gem_object_get_pages_gtt(struct drm_i915_gem_object *obj)
e5281ccd 2262{
fac5e23e 2263 struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
e5281ccd
CW
2264 int page_count, i;
2265 struct address_space *mapping;
9da3da66
CW
2266 struct sg_table *st;
2267 struct scatterlist *sg;
85d1225e 2268 struct sgt_iter sgt_iter;
e5281ccd 2269 struct page *page;
90797e6d 2270 unsigned long last_pfn = 0; /* suppress gcc warning */
4ff340f0 2271 unsigned int max_segment;
e2273302 2272 int ret;
6c085a72 2273 gfp_t gfp;
e5281ccd 2274
6c085a72
CW
2275 /* Assert that the object is not currently in any GPU domain. As it
2276 * wasn't in the GTT, there shouldn't be any way it could have been in
2277 * a GPU cache
2278 */
03ac84f1
CW
2279 GEM_BUG_ON(obj->base.read_domains & I915_GEM_GPU_DOMAINS);
2280 GEM_BUG_ON(obj->base.write_domain & I915_GEM_GPU_DOMAINS);
6c085a72 2281
871dfbd6
CW
2282 max_segment = swiotlb_max_size();
2283 if (!max_segment)
4ff340f0 2284 max_segment = rounddown(UINT_MAX, PAGE_SIZE);
871dfbd6 2285
9da3da66
CW
2286 st = kmalloc(sizeof(*st), GFP_KERNEL);
2287 if (st == NULL)
03ac84f1 2288 return ERR_PTR(-ENOMEM);
9da3da66 2289
05394f39 2290 page_count = obj->base.size / PAGE_SIZE;
9da3da66 2291 if (sg_alloc_table(st, page_count, GFP_KERNEL)) {
9da3da66 2292 kfree(st);
03ac84f1 2293 return ERR_PTR(-ENOMEM);
9da3da66 2294 }
e5281ccd 2295
9da3da66
CW
2296 /* Get the list of pages out of our struct file. They'll be pinned
2297 * at this point until we release them.
2298 *
2299 * Fail silently without starting the shrinker
2300 */
93c76a3d 2301 mapping = obj->base.filp->f_mapping;
c62d2555 2302 gfp = mapping_gfp_constraint(mapping, ~(__GFP_IO | __GFP_RECLAIM));
d0164adc 2303 gfp |= __GFP_NORETRY | __GFP_NOWARN;
90797e6d
ID
2304 sg = st->sgl;
2305 st->nents = 0;
2306 for (i = 0; i < page_count; i++) {
6c085a72
CW
2307 page = shmem_read_mapping_page_gfp(mapping, i, gfp);
2308 if (IS_ERR(page)) {
21ab4e74
CW
2309 i915_gem_shrink(dev_priv,
2310 page_count,
2311 I915_SHRINK_BOUND |
2312 I915_SHRINK_UNBOUND |
2313 I915_SHRINK_PURGEABLE);
6c085a72
CW
2314 page = shmem_read_mapping_page_gfp(mapping, i, gfp);
2315 }
2316 if (IS_ERR(page)) {
2317 /* We've tried hard to allocate the memory by reaping
2318 * our own buffer, now let the real VM do its job and
2319 * go down in flames if truly OOM.
2320 */
f461d1be 2321 page = shmem_read_mapping_page(mapping, i);
e2273302
ID
2322 if (IS_ERR(page)) {
2323 ret = PTR_ERR(page);
6c085a72 2324 goto err_pages;
e2273302 2325 }
6c085a72 2326 }
871dfbd6
CW
2327 if (!i ||
2328 sg->length >= max_segment ||
2329 page_to_pfn(page) != last_pfn + 1) {
90797e6d
ID
2330 if (i)
2331 sg = sg_next(sg);
2332 st->nents++;
2333 sg_set_page(sg, page, PAGE_SIZE, 0);
2334 } else {
2335 sg->length += PAGE_SIZE;
2336 }
2337 last_pfn = page_to_pfn(page);
3bbbe706
DV
2338
2339 /* Check that the i965g/gm workaround works. */
2340 WARN_ON((gfp & __GFP_DMA32) && (last_pfn >= 0x00100000UL));
e5281ccd 2341 }
871dfbd6 2342 if (sg) /* loop terminated early; short sg table */
426729dc 2343 sg_mark_end(sg);
74ce6b6c 2344
0c40ce13
TU
2345 /* Trim unused sg entries to avoid wasting memory. */
2346 i915_sg_trim(st);
2347
03ac84f1 2348 ret = i915_gem_gtt_prepare_pages(obj, st);
e2273302
ID
2349 if (ret)
2350 goto err_pages;
2351
6dacfd2f 2352 if (i915_gem_object_needs_bit17_swizzle(obj))
03ac84f1 2353 i915_gem_object_do_bit_17_swizzle(obj, st);
e5281ccd 2354
03ac84f1 2355 return st;
e5281ccd
CW
2356
2357err_pages:
90797e6d 2358 sg_mark_end(sg);
85d1225e
DG
2359 for_each_sgt_page(page, sgt_iter, st)
2360 put_page(page);
9da3da66
CW
2361 sg_free_table(st);
2362 kfree(st);
0820baf3
CW
2363
2364 /* shmemfs first checks if there is enough memory to allocate the page
2365 * and reports ENOSPC should there be insufficient, along with the usual
2366 * ENOMEM for a genuine allocation failure.
2367 *
2368 * We use ENOSPC in our driver to mean that we have run out of aperture
2369 * space and so want to translate the error from shmemfs back to our
2370 * usual understanding of ENOMEM.
2371 */
e2273302
ID
2372 if (ret == -ENOSPC)
2373 ret = -ENOMEM;
2374
03ac84f1
CW
2375 return ERR_PTR(ret);
2376}
2377
2378void __i915_gem_object_set_pages(struct drm_i915_gem_object *obj,
2379 struct sg_table *pages)
2380{
1233e2db 2381 lockdep_assert_held(&obj->mm.lock);
03ac84f1
CW
2382
2383 obj->mm.get_page.sg_pos = pages->sgl;
2384 obj->mm.get_page.sg_idx = 0;
2385
2386 obj->mm.pages = pages;
2c3a3f44
CW
2387
2388 if (i915_gem_object_is_tiled(obj) &&
2389 to_i915(obj->base.dev)->quirks & QUIRK_PIN_SWIZZLED_PAGES) {
2390 GEM_BUG_ON(obj->mm.quirked);
2391 __i915_gem_object_pin_pages(obj);
2392 obj->mm.quirked = true;
2393 }
03ac84f1
CW
2394}
2395
2396static int ____i915_gem_object_get_pages(struct drm_i915_gem_object *obj)
2397{
2398 struct sg_table *pages;
2399
2c3a3f44
CW
2400 GEM_BUG_ON(i915_gem_object_has_pinned_pages(obj));
2401
03ac84f1
CW
2402 if (unlikely(obj->mm.madv != I915_MADV_WILLNEED)) {
2403 DRM_DEBUG("Attempting to obtain a purgeable object\n");
2404 return -EFAULT;
2405 }
2406
2407 pages = obj->ops->get_pages(obj);
2408 if (unlikely(IS_ERR(pages)))
2409 return PTR_ERR(pages);
2410
2411 __i915_gem_object_set_pages(obj, pages);
2412 return 0;
673a394b
EA
2413}
2414
37e680a1 2415/* Ensure that the associated pages are gathered from the backing storage
1233e2db 2416 * and pinned into our object. i915_gem_object_pin_pages() may be called
37e680a1 2417 * multiple times before they are released by a single call to
1233e2db 2418 * i915_gem_object_unpin_pages() - once the pages are no longer referenced
37e680a1
CW
2419 * either as a result of memory pressure (reaping pages under the shrinker)
2420 * or as the object is itself released.
2421 */
a4f5ea64 2422int __i915_gem_object_get_pages(struct drm_i915_gem_object *obj)
37e680a1 2423{
03ac84f1 2424 int err;
37e680a1 2425
1233e2db
CW
2426 err = mutex_lock_interruptible(&obj->mm.lock);
2427 if (err)
2428 return err;
4c7d62c6 2429
2c3a3f44
CW
2430 if (unlikely(!obj->mm.pages)) {
2431 err = ____i915_gem_object_get_pages(obj);
2432 if (err)
2433 goto unlock;
37e680a1 2434
2c3a3f44
CW
2435 smp_mb__before_atomic();
2436 }
2437 atomic_inc(&obj->mm.pages_pin_count);
ee286370 2438
1233e2db
CW
2439unlock:
2440 mutex_unlock(&obj->mm.lock);
03ac84f1 2441 return err;
673a394b
EA
2442}
2443
dd6034c6 2444/* The 'mapping' part of i915_gem_object_pin_map() below */
d31d7cb1
CW
2445static void *i915_gem_object_map(const struct drm_i915_gem_object *obj,
2446 enum i915_map_type type)
dd6034c6
DG
2447{
2448 unsigned long n_pages = obj->base.size >> PAGE_SHIFT;
a4f5ea64 2449 struct sg_table *sgt = obj->mm.pages;
85d1225e
DG
2450 struct sgt_iter sgt_iter;
2451 struct page *page;
b338fa47
DG
2452 struct page *stack_pages[32];
2453 struct page **pages = stack_pages;
dd6034c6 2454 unsigned long i = 0;
d31d7cb1 2455 pgprot_t pgprot;
dd6034c6
DG
2456 void *addr;
2457
2458 /* A single page can always be kmapped */
d31d7cb1 2459 if (n_pages == 1 && type == I915_MAP_WB)
dd6034c6
DG
2460 return kmap(sg_page(sgt->sgl));
2461
b338fa47
DG
2462 if (n_pages > ARRAY_SIZE(stack_pages)) {
2463 /* Too big for stack -- allocate temporary array instead */
2464 pages = drm_malloc_gfp(n_pages, sizeof(*pages), GFP_TEMPORARY);
2465 if (!pages)
2466 return NULL;
2467 }
dd6034c6 2468
85d1225e
DG
2469 for_each_sgt_page(page, sgt_iter, sgt)
2470 pages[i++] = page;
dd6034c6
DG
2471
2472 /* Check that we have the expected number of pages */
2473 GEM_BUG_ON(i != n_pages);
2474
d31d7cb1
CW
2475 switch (type) {
2476 case I915_MAP_WB:
2477 pgprot = PAGE_KERNEL;
2478 break;
2479 case I915_MAP_WC:
2480 pgprot = pgprot_writecombine(PAGE_KERNEL_IO);
2481 break;
2482 }
2483 addr = vmap(pages, n_pages, 0, pgprot);
dd6034c6 2484
b338fa47
DG
2485 if (pages != stack_pages)
2486 drm_free_large(pages);
dd6034c6
DG
2487
2488 return addr;
2489}
2490
2491/* get, pin, and map the pages of the object into kernel space */
d31d7cb1
CW
2492void *i915_gem_object_pin_map(struct drm_i915_gem_object *obj,
2493 enum i915_map_type type)
0a798eb9 2494{
d31d7cb1
CW
2495 enum i915_map_type has_type;
2496 bool pinned;
2497 void *ptr;
0a798eb9
CW
2498 int ret;
2499
d31d7cb1 2500 GEM_BUG_ON(!i915_gem_object_has_struct_page(obj));
0a798eb9 2501
1233e2db 2502 ret = mutex_lock_interruptible(&obj->mm.lock);
0a798eb9
CW
2503 if (ret)
2504 return ERR_PTR(ret);
2505
1233e2db
CW
2506 pinned = true;
2507 if (!atomic_inc_not_zero(&obj->mm.pages_pin_count)) {
2c3a3f44
CW
2508 if (unlikely(!obj->mm.pages)) {
2509 ret = ____i915_gem_object_get_pages(obj);
2510 if (ret)
2511 goto err_unlock;
1233e2db 2512
2c3a3f44
CW
2513 smp_mb__before_atomic();
2514 }
2515 atomic_inc(&obj->mm.pages_pin_count);
1233e2db
CW
2516 pinned = false;
2517 }
2518 GEM_BUG_ON(!obj->mm.pages);
0a798eb9 2519
a4f5ea64 2520 ptr = ptr_unpack_bits(obj->mm.mapping, has_type);
d31d7cb1
CW
2521 if (ptr && has_type != type) {
2522 if (pinned) {
2523 ret = -EBUSY;
1233e2db 2524 goto err_unpin;
0a798eb9 2525 }
d31d7cb1
CW
2526
2527 if (is_vmalloc_addr(ptr))
2528 vunmap(ptr);
2529 else
2530 kunmap(kmap_to_page(ptr));
2531
a4f5ea64 2532 ptr = obj->mm.mapping = NULL;
0a798eb9
CW
2533 }
2534
d31d7cb1
CW
2535 if (!ptr) {
2536 ptr = i915_gem_object_map(obj, type);
2537 if (!ptr) {
2538 ret = -ENOMEM;
1233e2db 2539 goto err_unpin;
d31d7cb1
CW
2540 }
2541
a4f5ea64 2542 obj->mm.mapping = ptr_pack_bits(ptr, type);
d31d7cb1
CW
2543 }
2544
1233e2db
CW
2545out_unlock:
2546 mutex_unlock(&obj->mm.lock);
d31d7cb1
CW
2547 return ptr;
2548
1233e2db
CW
2549err_unpin:
2550 atomic_dec(&obj->mm.pages_pin_count);
2551err_unlock:
2552 ptr = ERR_PTR(ret);
2553 goto out_unlock;
0a798eb9
CW
2554}
2555
7b4d3a16 2556static bool i915_context_is_banned(const struct i915_gem_context *ctx)
be62acb4 2557{
44e2c070 2558 unsigned long elapsed;
be62acb4 2559
44e2c070 2560 if (ctx->hang_stats.banned)
be62acb4
MK
2561 return true;
2562
7b4d3a16 2563 elapsed = get_seconds() - ctx->hang_stats.guilty_ts;
676fa572
CW
2564 if (ctx->hang_stats.ban_period_seconds &&
2565 elapsed <= ctx->hang_stats.ban_period_seconds) {
7b4d3a16
CW
2566 DRM_DEBUG("context hanging too fast, banning!\n");
2567 return true;
be62acb4
MK
2568 }
2569
2570 return false;
2571}
2572
7b4d3a16 2573static void i915_set_reset_status(struct i915_gem_context *ctx,
b6b0fac0 2574 const bool guilty)
aa60c664 2575{
7b4d3a16 2576 struct i915_ctx_hang_stats *hs = &ctx->hang_stats;
44e2c070
MK
2577
2578 if (guilty) {
7b4d3a16 2579 hs->banned = i915_context_is_banned(ctx);
44e2c070
MK
2580 hs->batch_active++;
2581 hs->guilty_ts = get_seconds();
2582 } else {
2583 hs->batch_pending++;
aa60c664
MK
2584 }
2585}
2586
8d9fc7fd 2587struct drm_i915_gem_request *
0bc40be8 2588i915_gem_find_active_request(struct intel_engine_cs *engine)
9375e446 2589{
4db080f9
CW
2590 struct drm_i915_gem_request *request;
2591
f69a02c9
CW
2592 /* We are called by the error capture and reset at a random
2593 * point in time. In particular, note that neither is crucially
2594 * ordered with an interrupt. After a hang, the GPU is dead and we
2595 * assume that no more writes can happen (we waited long enough for
2596 * all writes that were in transaction to be flushed) - adding an
2597 * extra delay for a recent interrupt is pointless. Hence, we do
2598 * not need an engine->irq_seqno_barrier() before the seqno reads.
2599 */
73cb9701 2600 list_for_each_entry(request, &engine->timeline->requests, link) {
80b204bc 2601 if (__i915_gem_request_completed(request))
4db080f9 2602 continue;
aa60c664 2603
b6b0fac0 2604 return request;
4db080f9 2605 }
b6b0fac0
MK
2606
2607 return NULL;
2608}
2609
821ed7df
CW
2610static void reset_request(struct drm_i915_gem_request *request)
2611{
2612 void *vaddr = request->ring->vaddr;
2613 u32 head;
2614
2615 /* As this request likely depends on state from the lost
2616 * context, clear out all the user operations leaving the
2617 * breadcrumb at the end (so we get the fence notifications).
2618 */
2619 head = request->head;
2620 if (request->postfix < head) {
2621 memset(vaddr + head, 0, request->ring->size - head);
2622 head = 0;
2623 }
2624 memset(vaddr + head, 0, request->postfix - head);
2625}
2626
2627static void i915_gem_reset_engine(struct intel_engine_cs *engine)
b6b0fac0
MK
2628{
2629 struct drm_i915_gem_request *request;
821ed7df 2630 struct i915_gem_context *incomplete_ctx;
80b204bc 2631 struct intel_timeline *timeline;
b6b0fac0
MK
2632 bool ring_hung;
2633
821ed7df
CW
2634 if (engine->irq_seqno_barrier)
2635 engine->irq_seqno_barrier(engine);
2636
0bc40be8 2637 request = i915_gem_find_active_request(engine);
821ed7df 2638 if (!request)
b6b0fac0
MK
2639 return;
2640
0bc40be8 2641 ring_hung = engine->hangcheck.score >= HANGCHECK_SCORE_RING_HUNG;
77c60701
CW
2642 if (engine->hangcheck.seqno != intel_engine_get_seqno(engine))
2643 ring_hung = false;
2644
7b4d3a16 2645 i915_set_reset_status(request->ctx, ring_hung);
821ed7df
CW
2646 if (!ring_hung)
2647 return;
2648
2649 DRM_DEBUG_DRIVER("resetting %s to restart from tail of request 0x%x\n",
65e4760e 2650 engine->name, request->global_seqno);
821ed7df
CW
2651
2652 /* Setup the CS to resume from the breadcrumb of the hung request */
2653 engine->reset_hw(engine, request);
2654
2655 /* Users of the default context do not rely on logical state
2656 * preserved between batches. They have to emit full state on
2657 * every batch and so it is safe to execute queued requests following
2658 * the hang.
2659 *
2660 * Other contexts preserve state, now corrupt. We want to skip all
2661 * queued requests that reference the corrupt context.
2662 */
2663 incomplete_ctx = request->ctx;
2664 if (i915_gem_context_is_default(incomplete_ctx))
2665 return;
2666
73cb9701 2667 list_for_each_entry_continue(request, &engine->timeline->requests, link)
821ed7df
CW
2668 if (request->ctx == incomplete_ctx)
2669 reset_request(request);
80b204bc
CW
2670
2671 timeline = i915_gem_context_lookup_timeline(incomplete_ctx, engine);
2672 list_for_each_entry(request, &timeline->requests, link)
2673 reset_request(request);
4db080f9 2674}
aa60c664 2675
821ed7df 2676void i915_gem_reset(struct drm_i915_private *dev_priv)
4db080f9 2677{
821ed7df 2678 struct intel_engine_cs *engine;
3b3f1650 2679 enum intel_engine_id id;
608c1a52 2680
4c7d62c6
CW
2681 lockdep_assert_held(&dev_priv->drm.struct_mutex);
2682
821ed7df
CW
2683 i915_gem_retire_requests(dev_priv);
2684
3b3f1650 2685 for_each_engine(engine, dev_priv, id)
821ed7df
CW
2686 i915_gem_reset_engine(engine);
2687
2688 i915_gem_restore_fences(&dev_priv->drm);
f2a91d1a
CW
2689
2690 if (dev_priv->gt.awake) {
2691 intel_sanitize_gt_powersave(dev_priv);
2692 intel_enable_gt_powersave(dev_priv);
2693 if (INTEL_GEN(dev_priv) >= 6)
2694 gen6_rps_busy(dev_priv);
2695 }
821ed7df
CW
2696}
2697
2698static void nop_submit_request(struct drm_i915_gem_request *request)
2699{
2700}
2701
2702static void i915_gem_cleanup_engine(struct intel_engine_cs *engine)
2703{
2704 engine->submit_request = nop_submit_request;
70c2a24d 2705
c4b0930b
CW
2706 /* Mark all pending requests as complete so that any concurrent
2707 * (lockless) lookup doesn't try and wait upon the request as we
2708 * reset it.
2709 */
73cb9701 2710 intel_engine_init_global_seqno(engine,
cb399eab 2711 intel_engine_last_submit(engine));
c4b0930b 2712
dcb4c12a
OM
2713 /*
2714 * Clear the execlists queue up before freeing the requests, as those
2715 * are the ones that keep the context and ringbuffer backing objects
2716 * pinned in place.
2717 */
dcb4c12a 2718
7de1691a 2719 if (i915.enable_execlists) {
663f71e7
CW
2720 unsigned long flags;
2721
2722 spin_lock_irqsave(&engine->timeline->lock, flags);
2723
70c2a24d
CW
2724 INIT_LIST_HEAD(&engine->execlist_queue);
2725 i915_gem_request_put(engine->execlist_port[0].request);
2726 i915_gem_request_put(engine->execlist_port[1].request);
2727 memset(engine->execlist_port, 0, sizeof(engine->execlist_port));
663f71e7
CW
2728
2729 spin_unlock_irqrestore(&engine->timeline->lock, flags);
dcb4c12a 2730 }
673a394b
EA
2731}
2732
821ed7df 2733void i915_gem_set_wedged(struct drm_i915_private *dev_priv)
673a394b 2734{
e2f80391 2735 struct intel_engine_cs *engine;
3b3f1650 2736 enum intel_engine_id id;
673a394b 2737
821ed7df
CW
2738 lockdep_assert_held(&dev_priv->drm.struct_mutex);
2739 set_bit(I915_WEDGED, &dev_priv->gpu_error.flags);
4db080f9 2740
821ed7df 2741 i915_gem_context_lost(dev_priv);
3b3f1650 2742 for_each_engine(engine, dev_priv, id)
821ed7df 2743 i915_gem_cleanup_engine(engine);
b913b33c 2744 mod_delayed_work(dev_priv->wq, &dev_priv->gt.idle_work, 0);
dfaae392 2745
821ed7df 2746 i915_gem_retire_requests(dev_priv);
673a394b
EA
2747}
2748
75ef9da2 2749static void
673a394b
EA
2750i915_gem_retire_work_handler(struct work_struct *work)
2751{
b29c19b6 2752 struct drm_i915_private *dev_priv =
67d97da3 2753 container_of(work, typeof(*dev_priv), gt.retire_work.work);
91c8a326 2754 struct drm_device *dev = &dev_priv->drm;
673a394b 2755
891b48cf 2756 /* Come back later if the device is busy... */
b29c19b6 2757 if (mutex_trylock(&dev->struct_mutex)) {
67d97da3 2758 i915_gem_retire_requests(dev_priv);
b29c19b6 2759 mutex_unlock(&dev->struct_mutex);
673a394b 2760 }
67d97da3
CW
2761
2762 /* Keep the retire handler running until we are finally idle.
2763 * We do not need to do this test under locking as in the worst-case
2764 * we queue the retire worker once too often.
2765 */
c9615613
CW
2766 if (READ_ONCE(dev_priv->gt.awake)) {
2767 i915_queue_hangcheck(dev_priv);
67d97da3
CW
2768 queue_delayed_work(dev_priv->wq,
2769 &dev_priv->gt.retire_work,
bcb45086 2770 round_jiffies_up_relative(HZ));
c9615613 2771 }
b29c19b6 2772}
0a58705b 2773
b29c19b6
CW
2774static void
2775i915_gem_idle_work_handler(struct work_struct *work)
2776{
2777 struct drm_i915_private *dev_priv =
67d97da3 2778 container_of(work, typeof(*dev_priv), gt.idle_work.work);
91c8a326 2779 struct drm_device *dev = &dev_priv->drm;
b4ac5afc 2780 struct intel_engine_cs *engine;
3b3f1650 2781 enum intel_engine_id id;
67d97da3
CW
2782 bool rearm_hangcheck;
2783
2784 if (!READ_ONCE(dev_priv->gt.awake))
2785 return;
2786
0cb5670b
ID
2787 /*
2788 * Wait for last execlists context complete, but bail out in case a
2789 * new request is submitted.
2790 */
2791 wait_for(READ_ONCE(dev_priv->gt.active_requests) ||
2792 intel_execlists_idle(dev_priv), 10);
2793
28176ef4 2794 if (READ_ONCE(dev_priv->gt.active_requests))
67d97da3
CW
2795 return;
2796
2797 rearm_hangcheck =
2798 cancel_delayed_work_sync(&dev_priv->gpu_error.hangcheck_work);
2799
2800 if (!mutex_trylock(&dev->struct_mutex)) {
2801 /* Currently busy, come back later */
2802 mod_delayed_work(dev_priv->wq,
2803 &dev_priv->gt.idle_work,
2804 msecs_to_jiffies(50));
2805 goto out_rearm;
2806 }
2807
93c97dc1
ID
2808 /*
2809 * New request retired after this work handler started, extend active
2810 * period until next instance of the work.
2811 */
2812 if (work_pending(work))
2813 goto out_unlock;
2814
28176ef4 2815 if (dev_priv->gt.active_requests)
67d97da3 2816 goto out_unlock;
b29c19b6 2817
0cb5670b
ID
2818 if (wait_for(intel_execlists_idle(dev_priv), 10))
2819 DRM_ERROR("Timeout waiting for engines to idle\n");
2820
3b3f1650 2821 for_each_engine(engine, dev_priv, id)
67d97da3 2822 i915_gem_batch_pool_fini(&engine->batch_pool);
35c94185 2823
67d97da3
CW
2824 GEM_BUG_ON(!dev_priv->gt.awake);
2825 dev_priv->gt.awake = false;
2826 rearm_hangcheck = false;
30ecad77 2827
67d97da3
CW
2828 if (INTEL_GEN(dev_priv) >= 6)
2829 gen6_rps_idle(dev_priv);
2830 intel_runtime_pm_put(dev_priv);
2831out_unlock:
2832 mutex_unlock(&dev->struct_mutex);
b29c19b6 2833
67d97da3
CW
2834out_rearm:
2835 if (rearm_hangcheck) {
2836 GEM_BUG_ON(!dev_priv->gt.awake);
2837 i915_queue_hangcheck(dev_priv);
35c94185 2838 }
673a394b
EA
2839}
2840
b1f788c6
CW
2841void i915_gem_close_object(struct drm_gem_object *gem, struct drm_file *file)
2842{
2843 struct drm_i915_gem_object *obj = to_intel_bo(gem);
2844 struct drm_i915_file_private *fpriv = file->driver_priv;
2845 struct i915_vma *vma, *vn;
2846
2847 mutex_lock(&obj->base.dev->struct_mutex);
2848 list_for_each_entry_safe(vma, vn, &obj->vma_list, obj_link)
2849 if (vma->vm->file == fpriv)
2850 i915_vma_close(vma);
f8a7fde4
CW
2851
2852 if (i915_gem_object_is_active(obj) &&
2853 !i915_gem_object_has_active_reference(obj)) {
2854 i915_gem_object_set_active_reference(obj);
2855 i915_gem_object_get(obj);
2856 }
b1f788c6
CW
2857 mutex_unlock(&obj->base.dev->struct_mutex);
2858}
2859
e95433c7
CW
2860static unsigned long to_wait_timeout(s64 timeout_ns)
2861{
2862 if (timeout_ns < 0)
2863 return MAX_SCHEDULE_TIMEOUT;
2864
2865 if (timeout_ns == 0)
2866 return 0;
2867
2868 return nsecs_to_jiffies_timeout(timeout_ns);
2869}
2870
23ba4fd0
BW
2871/**
2872 * i915_gem_wait_ioctl - implements DRM_IOCTL_I915_GEM_WAIT
14bb2c11
TU
2873 * @dev: drm device pointer
2874 * @data: ioctl data blob
2875 * @file: drm file pointer
23ba4fd0
BW
2876 *
2877 * Returns 0 if successful, else an error is returned with the remaining time in
2878 * the timeout parameter.
2879 * -ETIME: object is still busy after timeout
2880 * -ERESTARTSYS: signal interrupted the wait
2881 * -ENONENT: object doesn't exist
2882 * Also possible, but rare:
2883 * -EAGAIN: GPU wedged
2884 * -ENOMEM: damn
2885 * -ENODEV: Internal IRQ fail
2886 * -E?: The add request failed
2887 *
2888 * The wait ioctl with a timeout of 0 reimplements the busy ioctl. With any
2889 * non-zero timeout parameter the wait ioctl will wait for the given number of
2890 * nanoseconds on an object becoming unbusy. Since the wait itself does so
2891 * without holding struct_mutex the object may become re-busied before this
2892 * function completes. A similar but shorter * race condition exists in the busy
2893 * ioctl
2894 */
2895int
2896i915_gem_wait_ioctl(struct drm_device *dev, void *data, struct drm_file *file)
2897{
2898 struct drm_i915_gem_wait *args = data;
2899 struct drm_i915_gem_object *obj;
e95433c7
CW
2900 ktime_t start;
2901 long ret;
23ba4fd0 2902
11b5d511
DV
2903 if (args->flags != 0)
2904 return -EINVAL;
2905
03ac0642 2906 obj = i915_gem_object_lookup(file, args->bo_handle);
033d549b 2907 if (!obj)
23ba4fd0 2908 return -ENOENT;
23ba4fd0 2909
e95433c7
CW
2910 start = ktime_get();
2911
2912 ret = i915_gem_object_wait(obj,
2913 I915_WAIT_INTERRUPTIBLE | I915_WAIT_ALL,
2914 to_wait_timeout(args->timeout_ns),
2915 to_rps_client(file));
2916
2917 if (args->timeout_ns > 0) {
2918 args->timeout_ns -= ktime_to_ns(ktime_sub(ktime_get(), start));
2919 if (args->timeout_ns < 0)
2920 args->timeout_ns = 0;
b4716185
CW
2921 }
2922
f0cd5182 2923 i915_gem_object_put(obj);
ff865885 2924 return ret;
23ba4fd0
BW
2925}
2926
73cb9701 2927static int wait_for_timeline(struct i915_gem_timeline *tl, unsigned int flags)
4df2faf4 2928{
73cb9701 2929 int ret, i;
4df2faf4 2930
73cb9701
CW
2931 for (i = 0; i < ARRAY_SIZE(tl->engine); i++) {
2932 ret = i915_gem_active_wait(&tl->engine[i].last_request, flags);
2933 if (ret)
2934 return ret;
2935 }
62e63007 2936
73cb9701
CW
2937 return 0;
2938}
2939
2940int i915_gem_wait_for_idle(struct drm_i915_private *i915, unsigned int flags)
2941{
73cb9701
CW
2942 int ret;
2943
9caa34aa
CW
2944 if (flags & I915_WAIT_LOCKED) {
2945 struct i915_gem_timeline *tl;
2946
2947 lockdep_assert_held(&i915->drm.struct_mutex);
2948
2949 list_for_each_entry(tl, &i915->gt.timelines, link) {
2950 ret = wait_for_timeline(tl, flags);
2951 if (ret)
2952 return ret;
2953 }
2954 } else {
2955 ret = wait_for_timeline(&i915->gt.global_timeline, flags);
1ec14ad3
CW
2956 if (ret)
2957 return ret;
2958 }
4df2faf4 2959
8a1a49f9 2960 return 0;
4df2faf4
DV
2961}
2962
d0da48cf
CW
2963void i915_gem_clflush_object(struct drm_i915_gem_object *obj,
2964 bool force)
673a394b 2965{
673a394b
EA
2966 /* If we don't have a page list set up, then we're not pinned
2967 * to GPU, and we can ignore the cache flush because it'll happen
2968 * again at bind time.
2969 */
a4f5ea64 2970 if (!obj->mm.pages)
d0da48cf 2971 return;
673a394b 2972
769ce464
ID
2973 /*
2974 * Stolen memory is always coherent with the GPU as it is explicitly
2975 * marked as wc by the system, or the system is cache-coherent.
2976 */
6a2c4232 2977 if (obj->stolen || obj->phys_handle)
d0da48cf 2978 return;
769ce464 2979
9c23f7fc
CW
2980 /* If the GPU is snooping the contents of the CPU cache,
2981 * we do not need to manually clear the CPU cache lines. However,
2982 * the caches are only snooped when the render cache is
2983 * flushed/invalidated. As we always have to emit invalidations
2984 * and flushes when moving into and out of the RENDER domain, correct
2985 * snooping behaviour occurs naturally as the result of our domain
2986 * tracking.
2987 */
0f71979a
CW
2988 if (!force && cpu_cache_is_coherent(obj->base.dev, obj->cache_level)) {
2989 obj->cache_dirty = true;
d0da48cf 2990 return;
0f71979a 2991 }
9c23f7fc 2992
1c5d22f7 2993 trace_i915_gem_object_clflush(obj);
a4f5ea64 2994 drm_clflush_sg(obj->mm.pages);
0f71979a 2995 obj->cache_dirty = false;
e47c68e9
EA
2996}
2997
2998/** Flushes the GTT write domain for the object if it's dirty. */
2999static void
05394f39 3000i915_gem_object_flush_gtt_write_domain(struct drm_i915_gem_object *obj)
e47c68e9 3001{
3b5724d7 3002 struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
1c5d22f7 3003
05394f39 3004 if (obj->base.write_domain != I915_GEM_DOMAIN_GTT)
e47c68e9
EA
3005 return;
3006
63256ec5 3007 /* No actual flushing is required for the GTT write domain. Writes
3b5724d7 3008 * to it "immediately" go to main memory as far as we know, so there's
e47c68e9 3009 * no chipset flush. It also doesn't land in render cache.
63256ec5
CW
3010 *
3011 * However, we do have to enforce the order so that all writes through
3012 * the GTT land before any writes to the device, such as updates to
3013 * the GATT itself.
3b5724d7
CW
3014 *
3015 * We also have to wait a bit for the writes to land from the GTT.
3016 * An uncached read (i.e. mmio) seems to be ideal for the round-trip
3017 * timing. This issue has only been observed when switching quickly
3018 * between GTT writes and CPU reads from inside the kernel on recent hw,
3019 * and it appears to only affect discrete GTT blocks (i.e. on LLC
3020 * system agents we cannot reproduce this behaviour).
e47c68e9 3021 */
63256ec5 3022 wmb();
3b5724d7 3023 if (INTEL_GEN(dev_priv) >= 6 && !HAS_LLC(dev_priv))
3b3f1650 3024 POSTING_READ(RING_ACTHD(dev_priv->engine[RCS]->mmio_base));
63256ec5 3025
d243ad82 3026 intel_fb_obj_flush(obj, false, write_origin(obj, I915_GEM_DOMAIN_GTT));
f99d7069 3027
b0dc465f 3028 obj->base.write_domain = 0;
1c5d22f7 3029 trace_i915_gem_object_change_domain(obj,
05394f39 3030 obj->base.read_domains,
b0dc465f 3031 I915_GEM_DOMAIN_GTT);
e47c68e9
EA
3032}
3033
3034/** Flushes the CPU write domain for the object if it's dirty. */
3035static void
e62b59e4 3036i915_gem_object_flush_cpu_write_domain(struct drm_i915_gem_object *obj)
e47c68e9 3037{
05394f39 3038 if (obj->base.write_domain != I915_GEM_DOMAIN_CPU)
e47c68e9
EA
3039 return;
3040
d0da48cf 3041 i915_gem_clflush_object(obj, obj->pin_display);
de152b62 3042 intel_fb_obj_flush(obj, false, ORIGIN_CPU);
f99d7069 3043
b0dc465f 3044 obj->base.write_domain = 0;
1c5d22f7 3045 trace_i915_gem_object_change_domain(obj,
05394f39 3046 obj->base.read_domains,
b0dc465f 3047 I915_GEM_DOMAIN_CPU);
e47c68e9
EA
3048}
3049
2ef7eeaa
EA
3050/**
3051 * Moves a single object to the GTT read, and possibly write domain.
14bb2c11
TU
3052 * @obj: object to act on
3053 * @write: ask for write access or read only
2ef7eeaa
EA
3054 *
3055 * This function returns when the move is complete, including waiting on
3056 * flushes to occur.
3057 */
79e53945 3058int
2021746e 3059i915_gem_object_set_to_gtt_domain(struct drm_i915_gem_object *obj, bool write)
2ef7eeaa 3060{
1c5d22f7 3061 uint32_t old_write_domain, old_read_domains;
e47c68e9 3062 int ret;
2ef7eeaa 3063
e95433c7 3064 lockdep_assert_held(&obj->base.dev->struct_mutex);
4c7d62c6 3065
e95433c7
CW
3066 ret = i915_gem_object_wait(obj,
3067 I915_WAIT_INTERRUPTIBLE |
3068 I915_WAIT_LOCKED |
3069 (write ? I915_WAIT_ALL : 0),
3070 MAX_SCHEDULE_TIMEOUT,
3071 NULL);
88241785
CW
3072 if (ret)
3073 return ret;
3074
c13d87ea
CW
3075 if (obj->base.write_domain == I915_GEM_DOMAIN_GTT)
3076 return 0;
3077
43566ded
CW
3078 /* Flush and acquire obj->pages so that we are coherent through
3079 * direct access in memory with previous cached writes through
3080 * shmemfs and that our cache domain tracking remains valid.
3081 * For example, if the obj->filp was moved to swap without us
3082 * being notified and releasing the pages, we would mistakenly
3083 * continue to assume that the obj remained out of the CPU cached
3084 * domain.
3085 */
a4f5ea64 3086 ret = i915_gem_object_pin_pages(obj);
43566ded
CW
3087 if (ret)
3088 return ret;
3089
e62b59e4 3090 i915_gem_object_flush_cpu_write_domain(obj);
1c5d22f7 3091
d0a57789
CW
3092 /* Serialise direct access to this object with the barriers for
3093 * coherent writes from the GPU, by effectively invalidating the
3094 * GTT domain upon first access.
3095 */
3096 if ((obj->base.read_domains & I915_GEM_DOMAIN_GTT) == 0)
3097 mb();
3098
05394f39
CW
3099 old_write_domain = obj->base.write_domain;
3100 old_read_domains = obj->base.read_domains;
1c5d22f7 3101
e47c68e9
EA
3102 /* It should now be out of any other write domains, and we can update
3103 * the domain values for our changes.
3104 */
40e62d5d 3105 GEM_BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_GTT) != 0);
05394f39 3106 obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
e47c68e9 3107 if (write) {
05394f39
CW
3108 obj->base.read_domains = I915_GEM_DOMAIN_GTT;
3109 obj->base.write_domain = I915_GEM_DOMAIN_GTT;
a4f5ea64 3110 obj->mm.dirty = true;
2ef7eeaa
EA
3111 }
3112
1c5d22f7
CW
3113 trace_i915_gem_object_change_domain(obj,
3114 old_read_domains,
3115 old_write_domain);
3116
a4f5ea64 3117 i915_gem_object_unpin_pages(obj);
e47c68e9
EA
3118 return 0;
3119}
3120
ef55f92a
CW
3121/**
3122 * Changes the cache-level of an object across all VMA.
14bb2c11
TU
3123 * @obj: object to act on
3124 * @cache_level: new cache level to set for the object
ef55f92a
CW
3125 *
3126 * After this function returns, the object will be in the new cache-level
3127 * across all GTT and the contents of the backing storage will be coherent,
3128 * with respect to the new cache-level. In order to keep the backing storage
3129 * coherent for all users, we only allow a single cache level to be set
3130 * globally on the object and prevent it from being changed whilst the
3131 * hardware is reading from the object. That is if the object is currently
3132 * on the scanout it will be set to uncached (or equivalent display
3133 * cache coherency) and all non-MOCS GPU access will also be uncached so
3134 * that all direct access to the scanout remains coherent.
3135 */
e4ffd173
CW
3136int i915_gem_object_set_cache_level(struct drm_i915_gem_object *obj,
3137 enum i915_cache_level cache_level)
3138{
aa653a68 3139 struct i915_vma *vma;
ed75a55b 3140 int ret = 0;
e4ffd173 3141
4c7d62c6
CW
3142 lockdep_assert_held(&obj->base.dev->struct_mutex);
3143
e4ffd173 3144 if (obj->cache_level == cache_level)
ed75a55b 3145 goto out;
e4ffd173 3146
ef55f92a
CW
3147 /* Inspect the list of currently bound VMA and unbind any that would
3148 * be invalid given the new cache-level. This is principally to
3149 * catch the issue of the CS prefetch crossing page boundaries and
3150 * reading an invalid PTE on older architectures.
3151 */
aa653a68
CW
3152restart:
3153 list_for_each_entry(vma, &obj->vma_list, obj_link) {
ef55f92a
CW
3154 if (!drm_mm_node_allocated(&vma->node))
3155 continue;
3156
20dfbde4 3157 if (i915_vma_is_pinned(vma)) {
ef55f92a
CW
3158 DRM_DEBUG("can not change the cache level of pinned objects\n");
3159 return -EBUSY;
3160 }
3161
aa653a68
CW
3162 if (i915_gem_valid_gtt_space(vma, cache_level))
3163 continue;
3164
3165 ret = i915_vma_unbind(vma);
3166 if (ret)
3167 return ret;
3168
3169 /* As unbinding may affect other elements in the
3170 * obj->vma_list (due to side-effects from retiring
3171 * an active vma), play safe and restart the iterator.
3172 */
3173 goto restart;
42d6ab48
CW
3174 }
3175
ef55f92a
CW
3176 /* We can reuse the existing drm_mm nodes but need to change the
3177 * cache-level on the PTE. We could simply unbind them all and
3178 * rebind with the correct cache-level on next use. However since
3179 * we already have a valid slot, dma mapping, pages etc, we may as
3180 * rewrite the PTE in the belief that doing so tramples upon less
3181 * state and so involves less work.
3182 */
15717de2 3183 if (obj->bind_count) {
ef55f92a
CW
3184 /* Before we change the PTE, the GPU must not be accessing it.
3185 * If we wait upon the object, we know that all the bound
3186 * VMA are no longer active.
3187 */
e95433c7
CW
3188 ret = i915_gem_object_wait(obj,
3189 I915_WAIT_INTERRUPTIBLE |
3190 I915_WAIT_LOCKED |
3191 I915_WAIT_ALL,
3192 MAX_SCHEDULE_TIMEOUT,
3193 NULL);
e4ffd173
CW
3194 if (ret)
3195 return ret;
3196
0031fb96
TU
3197 if (!HAS_LLC(to_i915(obj->base.dev)) &&
3198 cache_level != I915_CACHE_NONE) {
ef55f92a
CW
3199 /* Access to snoopable pages through the GTT is
3200 * incoherent and on some machines causes a hard
3201 * lockup. Relinquish the CPU mmaping to force
3202 * userspace to refault in the pages and we can
3203 * then double check if the GTT mapping is still
3204 * valid for that pointer access.
3205 */
3206 i915_gem_release_mmap(obj);
3207
3208 /* As we no longer need a fence for GTT access,
3209 * we can relinquish it now (and so prevent having
3210 * to steal a fence from someone else on the next
3211 * fence request). Note GPU activity would have
3212 * dropped the fence as all snoopable access is
3213 * supposed to be linear.
3214 */
49ef5294
CW
3215 list_for_each_entry(vma, &obj->vma_list, obj_link) {
3216 ret = i915_vma_put_fence(vma);
3217 if (ret)
3218 return ret;
3219 }
ef55f92a
CW
3220 } else {
3221 /* We either have incoherent backing store and
3222 * so no GTT access or the architecture is fully
3223 * coherent. In such cases, existing GTT mmaps
3224 * ignore the cache bit in the PTE and we can
3225 * rewrite it without confusing the GPU or having
3226 * to force userspace to fault back in its mmaps.
3227 */
e4ffd173
CW
3228 }
3229
1c7f4bca 3230 list_for_each_entry(vma, &obj->vma_list, obj_link) {
ef55f92a
CW
3231 if (!drm_mm_node_allocated(&vma->node))
3232 continue;
3233
3234 ret = i915_vma_bind(vma, cache_level, PIN_UPDATE);
3235 if (ret)
3236 return ret;
3237 }
e4ffd173
CW
3238 }
3239
1c7f4bca 3240 list_for_each_entry(vma, &obj->vma_list, obj_link)
2c22569b
CW
3241 vma->node.color = cache_level;
3242 obj->cache_level = cache_level;
3243
ed75a55b 3244out:
ef55f92a
CW
3245 /* Flush the dirty CPU caches to the backing storage so that the
3246 * object is now coherent at its new cache level (with respect
3247 * to the access domain).
3248 */
d0da48cf
CW
3249 if (obj->cache_dirty && cpu_write_needs_clflush(obj))
3250 i915_gem_clflush_object(obj, true);
e4ffd173 3251
e4ffd173
CW
3252 return 0;
3253}
3254
199adf40
BW
3255int i915_gem_get_caching_ioctl(struct drm_device *dev, void *data,
3256 struct drm_file *file)
e6994aee 3257{
199adf40 3258 struct drm_i915_gem_caching *args = data;
e6994aee 3259 struct drm_i915_gem_object *obj;
fbbd37b3 3260 int err = 0;
e6994aee 3261
fbbd37b3
CW
3262 rcu_read_lock();
3263 obj = i915_gem_object_lookup_rcu(file, args->handle);
3264 if (!obj) {
3265 err = -ENOENT;
3266 goto out;
3267 }
e6994aee 3268
651d794f
CW
3269 switch (obj->cache_level) {
3270 case I915_CACHE_LLC:
3271 case I915_CACHE_L3_LLC:
3272 args->caching = I915_CACHING_CACHED;
3273 break;
3274
4257d3ba
CW
3275 case I915_CACHE_WT:
3276 args->caching = I915_CACHING_DISPLAY;
3277 break;
3278
651d794f
CW
3279 default:
3280 args->caching = I915_CACHING_NONE;
3281 break;
3282 }
fbbd37b3
CW
3283out:
3284 rcu_read_unlock();
3285 return err;
e6994aee
CW
3286}
3287
199adf40
BW
3288int i915_gem_set_caching_ioctl(struct drm_device *dev, void *data,
3289 struct drm_file *file)
e6994aee 3290{
9c870d03 3291 struct drm_i915_private *i915 = to_i915(dev);
199adf40 3292 struct drm_i915_gem_caching *args = data;
e6994aee
CW
3293 struct drm_i915_gem_object *obj;
3294 enum i915_cache_level level;
3295 int ret;
3296
199adf40
BW
3297 switch (args->caching) {
3298 case I915_CACHING_NONE:
e6994aee
CW
3299 level = I915_CACHE_NONE;
3300 break;
199adf40 3301 case I915_CACHING_CACHED:
e5756c10
ID
3302 /*
3303 * Due to a HW issue on BXT A stepping, GPU stores via a
3304 * snooped mapping may leave stale data in a corresponding CPU
3305 * cacheline, whereas normally such cachelines would get
3306 * invalidated.
3307 */
9c870d03 3308 if (!HAS_LLC(i915) && !HAS_SNOOP(i915))
e5756c10
ID
3309 return -ENODEV;
3310
e6994aee
CW
3311 level = I915_CACHE_LLC;
3312 break;
4257d3ba 3313 case I915_CACHING_DISPLAY:
9c870d03 3314 level = HAS_WT(i915) ? I915_CACHE_WT : I915_CACHE_NONE;
4257d3ba 3315 break;
e6994aee
CW
3316 default:
3317 return -EINVAL;
3318 }
3319
3bc2913e
BW
3320 ret = i915_mutex_lock_interruptible(dev);
3321 if (ret)
9c870d03 3322 return ret;
3bc2913e 3323
03ac0642
CW
3324 obj = i915_gem_object_lookup(file, args->handle);
3325 if (!obj) {
e6994aee
CW
3326 ret = -ENOENT;
3327 goto unlock;
3328 }
3329
3330 ret = i915_gem_object_set_cache_level(obj, level);
f8c417cd 3331 i915_gem_object_put(obj);
e6994aee
CW
3332unlock:
3333 mutex_unlock(&dev->struct_mutex);
3334 return ret;
3335}
3336
b9241ea3 3337/*
2da3b9b9
CW
3338 * Prepare buffer for display plane (scanout, cursors, etc).
3339 * Can be called from an uninterruptible phase (modesetting) and allows
3340 * any flushes to be pipelined (for pageflips).
b9241ea3 3341 */
058d88c4 3342struct i915_vma *
2da3b9b9
CW
3343i915_gem_object_pin_to_display_plane(struct drm_i915_gem_object *obj,
3344 u32 alignment,
e6617330 3345 const struct i915_ggtt_view *view)
b9241ea3 3346{
058d88c4 3347 struct i915_vma *vma;
2da3b9b9 3348 u32 old_read_domains, old_write_domain;
b9241ea3
ZW
3349 int ret;
3350
4c7d62c6
CW
3351 lockdep_assert_held(&obj->base.dev->struct_mutex);
3352
cc98b413
CW
3353 /* Mark the pin_display early so that we account for the
3354 * display coherency whilst setting up the cache domains.
3355 */
8a0c39b1 3356 obj->pin_display++;
cc98b413 3357
a7ef0640
EA
3358 /* The display engine is not coherent with the LLC cache on gen6. As
3359 * a result, we make sure that the pinning that is about to occur is
3360 * done with uncached PTEs. This is lowest common denominator for all
3361 * chipsets.
3362 *
3363 * However for gen6+, we could do better by using the GFDT bit instead
3364 * of uncaching, which would allow us to flush all the LLC-cached data
3365 * with that bit in the PTE to main memory with just one PIPE_CONTROL.
3366 */
651d794f 3367 ret = i915_gem_object_set_cache_level(obj,
8652744b
TU
3368 HAS_WT(to_i915(obj->base.dev)) ?
3369 I915_CACHE_WT : I915_CACHE_NONE);
058d88c4
CW
3370 if (ret) {
3371 vma = ERR_PTR(ret);
cc98b413 3372 goto err_unpin_display;
058d88c4 3373 }
a7ef0640 3374
2da3b9b9
CW
3375 /* As the user may map the buffer once pinned in the display plane
3376 * (e.g. libkms for the bootup splash), we have to ensure that we
2efb813d
CW
3377 * always use map_and_fenceable for all scanout buffers. However,
3378 * it may simply be too big to fit into mappable, in which case
3379 * put it anyway and hope that userspace can cope (but always first
3380 * try to preserve the existing ABI).
2da3b9b9 3381 */
2efb813d
CW
3382 vma = ERR_PTR(-ENOSPC);
3383 if (view->type == I915_GGTT_VIEW_NORMAL)
3384 vma = i915_gem_object_ggtt_pin(obj, view, 0, alignment,
3385 PIN_MAPPABLE | PIN_NONBLOCK);
767a222e
CW
3386 if (IS_ERR(vma)) {
3387 struct drm_i915_private *i915 = to_i915(obj->base.dev);
3388 unsigned int flags;
3389
3390 /* Valleyview is definitely limited to scanning out the first
3391 * 512MiB. Lets presume this behaviour was inherited from the
3392 * g4x display engine and that all earlier gen are similarly
3393 * limited. Testing suggests that it is a little more
3394 * complicated than this. For example, Cherryview appears quite
3395 * happy to scanout from anywhere within its global aperture.
3396 */
3397 flags = 0;
3398 if (HAS_GMCH_DISPLAY(i915))
3399 flags = PIN_MAPPABLE;
3400 vma = i915_gem_object_ggtt_pin(obj, view, 0, alignment, flags);
3401 }
058d88c4 3402 if (IS_ERR(vma))
cc98b413 3403 goto err_unpin_display;
2da3b9b9 3404
d8923dcf
CW
3405 vma->display_alignment = max_t(u64, vma->display_alignment, alignment);
3406
e62b59e4 3407 i915_gem_object_flush_cpu_write_domain(obj);
b118c1e3 3408
2da3b9b9 3409 old_write_domain = obj->base.write_domain;
05394f39 3410 old_read_domains = obj->base.read_domains;
2da3b9b9
CW
3411
3412 /* It should now be out of any other write domains, and we can update
3413 * the domain values for our changes.
3414 */
e5f1d962 3415 obj->base.write_domain = 0;
05394f39 3416 obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
b9241ea3
ZW
3417
3418 trace_i915_gem_object_change_domain(obj,
3419 old_read_domains,
2da3b9b9 3420 old_write_domain);
b9241ea3 3421
058d88c4 3422 return vma;
cc98b413
CW
3423
3424err_unpin_display:
8a0c39b1 3425 obj->pin_display--;
058d88c4 3426 return vma;
cc98b413
CW
3427}
3428
3429void
058d88c4 3430i915_gem_object_unpin_from_display_plane(struct i915_vma *vma)
cc98b413 3431{
4c7d62c6
CW
3432 lockdep_assert_held(&vma->vm->dev->struct_mutex);
3433
058d88c4 3434 if (WARN_ON(vma->obj->pin_display == 0))
8a0c39b1
TU
3435 return;
3436
d8923dcf
CW
3437 if (--vma->obj->pin_display == 0)
3438 vma->display_alignment = 0;
e6617330 3439
383d5823
CW
3440 /* Bump the LRU to try and avoid premature eviction whilst flipping */
3441 if (!i915_vma_is_active(vma))
3442 list_move_tail(&vma->vm_link, &vma->vm->inactive_list);
3443
058d88c4 3444 i915_vma_unpin(vma);
b9241ea3
ZW
3445}
3446
e47c68e9
EA
3447/**
3448 * Moves a single object to the CPU read, and possibly write domain.
14bb2c11
TU
3449 * @obj: object to act on
3450 * @write: requesting write or read-only access
e47c68e9
EA
3451 *
3452 * This function returns when the move is complete, including waiting on
3453 * flushes to occur.
3454 */
dabdfe02 3455int
919926ae 3456i915_gem_object_set_to_cpu_domain(struct drm_i915_gem_object *obj, bool write)
e47c68e9 3457{
1c5d22f7 3458 uint32_t old_write_domain, old_read_domains;
e47c68e9
EA
3459 int ret;
3460
e95433c7 3461 lockdep_assert_held(&obj->base.dev->struct_mutex);
4c7d62c6 3462
e95433c7
CW
3463 ret = i915_gem_object_wait(obj,
3464 I915_WAIT_INTERRUPTIBLE |
3465 I915_WAIT_LOCKED |
3466 (write ? I915_WAIT_ALL : 0),
3467 MAX_SCHEDULE_TIMEOUT,
3468 NULL);
88241785
CW
3469 if (ret)
3470 return ret;
3471
c13d87ea
CW
3472 if (obj->base.write_domain == I915_GEM_DOMAIN_CPU)
3473 return 0;
3474
e47c68e9 3475 i915_gem_object_flush_gtt_write_domain(obj);
2ef7eeaa 3476
05394f39
CW
3477 old_write_domain = obj->base.write_domain;
3478 old_read_domains = obj->base.read_domains;
1c5d22f7 3479
e47c68e9 3480 /* Flush the CPU cache if it's still invalid. */
05394f39 3481 if ((obj->base.read_domains & I915_GEM_DOMAIN_CPU) == 0) {
2c22569b 3482 i915_gem_clflush_object(obj, false);
2ef7eeaa 3483
05394f39 3484 obj->base.read_domains |= I915_GEM_DOMAIN_CPU;
2ef7eeaa
EA
3485 }
3486
3487 /* It should now be out of any other write domains, and we can update
3488 * the domain values for our changes.
3489 */
40e62d5d 3490 GEM_BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_CPU) != 0);
e47c68e9
EA
3491
3492 /* If we're writing through the CPU, then the GPU read domains will
3493 * need to be invalidated at next use.
3494 */
3495 if (write) {
05394f39
CW
3496 obj->base.read_domains = I915_GEM_DOMAIN_CPU;
3497 obj->base.write_domain = I915_GEM_DOMAIN_CPU;
e47c68e9 3498 }
2ef7eeaa 3499
1c5d22f7
CW
3500 trace_i915_gem_object_change_domain(obj,
3501 old_read_domains,
3502 old_write_domain);
3503
2ef7eeaa
EA
3504 return 0;
3505}
3506
673a394b
EA
3507/* Throttle our rendering by waiting until the ring has completed our requests
3508 * emitted over 20 msec ago.
3509 *
b962442e
EA
3510 * Note that if we were to use the current jiffies each time around the loop,
3511 * we wouldn't escape the function with any frames outstanding if the time to
3512 * render a frame was over 20ms.
3513 *
673a394b
EA
3514 * This should get us reasonable parallelism between CPU and GPU but also
3515 * relatively low latency when blocking on a particular request to finish.
3516 */
40a5f0de 3517static int
f787a5f5 3518i915_gem_ring_throttle(struct drm_device *dev, struct drm_file *file)
40a5f0de 3519{
fac5e23e 3520 struct drm_i915_private *dev_priv = to_i915(dev);
f787a5f5 3521 struct drm_i915_file_private *file_priv = file->driver_priv;
d0bc54f2 3522 unsigned long recent_enough = jiffies - DRM_I915_THROTTLE_JIFFIES;
54fb2411 3523 struct drm_i915_gem_request *request, *target = NULL;
e95433c7 3524 long ret;
93533c29 3525
f4457ae7
CW
3526 /* ABI: return -EIO if already wedged */
3527 if (i915_terminally_wedged(&dev_priv->gpu_error))
3528 return -EIO;
e110e8d6 3529
1c25595f 3530 spin_lock(&file_priv->mm.lock);
f787a5f5 3531 list_for_each_entry(request, &file_priv->mm.request_list, client_list) {
b962442e
EA
3532 if (time_after_eq(request->emitted_jiffies, recent_enough))
3533 break;
40a5f0de 3534
fcfa423c
JH
3535 /*
3536 * Note that the request might not have been submitted yet.
3537 * In which case emitted_jiffies will be zero.
3538 */
3539 if (!request->emitted_jiffies)
3540 continue;
3541
54fb2411 3542 target = request;
b962442e 3543 }
ff865885 3544 if (target)
e8a261ea 3545 i915_gem_request_get(target);
1c25595f 3546 spin_unlock(&file_priv->mm.lock);
40a5f0de 3547
54fb2411 3548 if (target == NULL)
f787a5f5 3549 return 0;
2bc43b5c 3550
e95433c7
CW
3551 ret = i915_wait_request(target,
3552 I915_WAIT_INTERRUPTIBLE,
3553 MAX_SCHEDULE_TIMEOUT);
e8a261ea 3554 i915_gem_request_put(target);
ff865885 3555
e95433c7 3556 return ret < 0 ? ret : 0;
40a5f0de
EA
3557}
3558
058d88c4 3559struct i915_vma *
ec7adb6e
JL
3560i915_gem_object_ggtt_pin(struct drm_i915_gem_object *obj,
3561 const struct i915_ggtt_view *view,
91b2db6f 3562 u64 size,
2ffffd0f
CW
3563 u64 alignment,
3564 u64 flags)
ec7adb6e 3565{
ad16d2ed
CW
3566 struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
3567 struct i915_address_space *vm = &dev_priv->ggtt.base;
59bfa124
CW
3568 struct i915_vma *vma;
3569 int ret;
72e96d64 3570
4c7d62c6
CW
3571 lockdep_assert_held(&obj->base.dev->struct_mutex);
3572
058d88c4 3573 vma = i915_gem_obj_lookup_or_create_vma(obj, vm, view);
59bfa124 3574 if (IS_ERR(vma))
058d88c4 3575 return vma;
59bfa124
CW
3576
3577 if (i915_vma_misplaced(vma, size, alignment, flags)) {
3578 if (flags & PIN_NONBLOCK &&
3579 (i915_vma_is_pinned(vma) || i915_vma_is_active(vma)))
058d88c4 3580 return ERR_PTR(-ENOSPC);
59bfa124 3581
ad16d2ed
CW
3582 if (flags & PIN_MAPPABLE) {
3583 u32 fence_size;
3584
3585 fence_size = i915_gem_get_ggtt_size(dev_priv, vma->size,
3586 i915_gem_object_get_tiling(obj));
3587 /* If the required space is larger than the available
3588 * aperture, we will not able to find a slot for the
3589 * object and unbinding the object now will be in
3590 * vain. Worse, doing so may cause us to ping-pong
3591 * the object in and out of the Global GTT and
3592 * waste a lot of cycles under the mutex.
3593 */
3594 if (fence_size > dev_priv->ggtt.mappable_end)
3595 return ERR_PTR(-E2BIG);
3596
3597 /* If NONBLOCK is set the caller is optimistically
3598 * trying to cache the full object within the mappable
3599 * aperture, and *must* have a fallback in place for
3600 * situations where we cannot bind the object. We
3601 * can be a little more lax here and use the fallback
3602 * more often to avoid costly migrations of ourselves
3603 * and other objects within the aperture.
3604 *
3605 * Half-the-aperture is used as a simple heuristic.
3606 * More interesting would to do search for a free
3607 * block prior to making the commitment to unbind.
3608 * That caters for the self-harm case, and with a
3609 * little more heuristics (e.g. NOFAULT, NOEVICT)
3610 * we could try to minimise harm to others.
3611 */
3612 if (flags & PIN_NONBLOCK &&
3613 fence_size > dev_priv->ggtt.mappable_end / 2)
3614 return ERR_PTR(-ENOSPC);
3615 }
3616
59bfa124
CW
3617 WARN(i915_vma_is_pinned(vma),
3618 "bo is already pinned in ggtt with incorrect alignment:"
05a20d09
CW
3619 " offset=%08x, req.alignment=%llx,"
3620 " req.map_and_fenceable=%d, vma->map_and_fenceable=%d\n",
3621 i915_ggtt_offset(vma), alignment,
59bfa124 3622 !!(flags & PIN_MAPPABLE),
05a20d09 3623 i915_vma_is_map_and_fenceable(vma));
59bfa124
CW
3624 ret = i915_vma_unbind(vma);
3625 if (ret)
058d88c4 3626 return ERR_PTR(ret);
59bfa124
CW
3627 }
3628
058d88c4
CW
3629 ret = i915_vma_pin(vma, size, alignment, flags | PIN_GLOBAL);
3630 if (ret)
3631 return ERR_PTR(ret);
ec7adb6e 3632
058d88c4 3633 return vma;
673a394b
EA
3634}
3635
edf6b76f 3636static __always_inline unsigned int __busy_read_flag(unsigned int id)
3fdc13c7
CW
3637{
3638 /* Note that we could alias engines in the execbuf API, but
3639 * that would be very unwise as it prevents userspace from
3640 * fine control over engine selection. Ahem.
3641 *
3642 * This should be something like EXEC_MAX_ENGINE instead of
3643 * I915_NUM_ENGINES.
3644 */
3645 BUILD_BUG_ON(I915_NUM_ENGINES > 16);
3646 return 0x10000 << id;
3647}
3648
3649static __always_inline unsigned int __busy_write_id(unsigned int id)
3650{
70cb472c
CW
3651 /* The uABI guarantees an active writer is also amongst the read
3652 * engines. This would be true if we accessed the activity tracking
3653 * under the lock, but as we perform the lookup of the object and
3654 * its activity locklessly we can not guarantee that the last_write
3655 * being active implies that we have set the same engine flag from
3656 * last_read - hence we always set both read and write busy for
3657 * last_write.
3658 */
3659 return id | __busy_read_flag(id);
3fdc13c7
CW
3660}
3661
edf6b76f 3662static __always_inline unsigned int
d07f0e59 3663__busy_set_if_active(const struct dma_fence *fence,
3fdc13c7
CW
3664 unsigned int (*flag)(unsigned int id))
3665{
d07f0e59 3666 struct drm_i915_gem_request *rq;
3fdc13c7 3667
d07f0e59
CW
3668 /* We have to check the current hw status of the fence as the uABI
3669 * guarantees forward progress. We could rely on the idle worker
3670 * to eventually flush us, but to minimise latency just ask the
3671 * hardware.
1255501d 3672 *
d07f0e59 3673 * Note we only report on the status of native fences.
1255501d 3674 */
d07f0e59
CW
3675 if (!dma_fence_is_i915(fence))
3676 return 0;
3677
3678 /* opencode to_request() in order to avoid const warnings */
3679 rq = container_of(fence, struct drm_i915_gem_request, fence);
3680 if (i915_gem_request_completed(rq))
3681 return 0;
3682
3683 return flag(rq->engine->exec_id);
3fdc13c7
CW
3684}
3685
edf6b76f 3686static __always_inline unsigned int
d07f0e59 3687busy_check_reader(const struct dma_fence *fence)
3fdc13c7 3688{
d07f0e59 3689 return __busy_set_if_active(fence, __busy_read_flag);
3fdc13c7
CW
3690}
3691
edf6b76f 3692static __always_inline unsigned int
d07f0e59 3693busy_check_writer(const struct dma_fence *fence)
3fdc13c7 3694{
d07f0e59
CW
3695 if (!fence)
3696 return 0;
3697
3698 return __busy_set_if_active(fence, __busy_write_id);
3fdc13c7
CW
3699}
3700
673a394b
EA
3701int
3702i915_gem_busy_ioctl(struct drm_device *dev, void *data,
05394f39 3703 struct drm_file *file)
673a394b
EA
3704{
3705 struct drm_i915_gem_busy *args = data;
05394f39 3706 struct drm_i915_gem_object *obj;
d07f0e59
CW
3707 struct reservation_object_list *list;
3708 unsigned int seq;
fbbd37b3 3709 int err;
673a394b 3710
d07f0e59 3711 err = -ENOENT;
fbbd37b3
CW
3712 rcu_read_lock();
3713 obj = i915_gem_object_lookup_rcu(file, args->handle);
d07f0e59 3714 if (!obj)
fbbd37b3 3715 goto out;
d1b851fc 3716
d07f0e59
CW
3717 /* A discrepancy here is that we do not report the status of
3718 * non-i915 fences, i.e. even though we may report the object as idle,
3719 * a call to set-domain may still stall waiting for foreign rendering.
3720 * This also means that wait-ioctl may report an object as busy,
3721 * where busy-ioctl considers it idle.
3722 *
3723 * We trade the ability to warn of foreign fences to report on which
3724 * i915 engines are active for the object.
3725 *
3726 * Alternatively, we can trade that extra information on read/write
3727 * activity with
3728 * args->busy =
3729 * !reservation_object_test_signaled_rcu(obj->resv, true);
3730 * to report the overall busyness. This is what the wait-ioctl does.
3731 *
3732 */
3733retry:
3734 seq = raw_read_seqcount(&obj->resv->seq);
426960be 3735
d07f0e59
CW
3736 /* Translate the exclusive fence to the READ *and* WRITE engine */
3737 args->busy = busy_check_writer(rcu_dereference(obj->resv->fence_excl));
3fdc13c7 3738
d07f0e59
CW
3739 /* Translate shared fences to READ set of engines */
3740 list = rcu_dereference(obj->resv->fence);
3741 if (list) {
3742 unsigned int shared_count = list->shared_count, i;
3fdc13c7 3743
d07f0e59
CW
3744 for (i = 0; i < shared_count; ++i) {
3745 struct dma_fence *fence =
3746 rcu_dereference(list->shared[i]);
3747
3748 args->busy |= busy_check_reader(fence);
3749 }
426960be 3750 }
673a394b 3751
d07f0e59
CW
3752 if (args->busy && read_seqcount_retry(&obj->resv->seq, seq))
3753 goto retry;
3754
3755 err = 0;
fbbd37b3
CW
3756out:
3757 rcu_read_unlock();
3758 return err;
673a394b
EA
3759}
3760
3761int
3762i915_gem_throttle_ioctl(struct drm_device *dev, void *data,
3763 struct drm_file *file_priv)
3764{
0206e353 3765 return i915_gem_ring_throttle(dev, file_priv);
673a394b
EA
3766}
3767
3ef94daa
CW
3768int
3769i915_gem_madvise_ioctl(struct drm_device *dev, void *data,
3770 struct drm_file *file_priv)
3771{
fac5e23e 3772 struct drm_i915_private *dev_priv = to_i915(dev);
3ef94daa 3773 struct drm_i915_gem_madvise *args = data;
05394f39 3774 struct drm_i915_gem_object *obj;
1233e2db 3775 int err;
3ef94daa
CW
3776
3777 switch (args->madv) {
3778 case I915_MADV_DONTNEED:
3779 case I915_MADV_WILLNEED:
3780 break;
3781 default:
3782 return -EINVAL;
3783 }
3784
03ac0642 3785 obj = i915_gem_object_lookup(file_priv, args->handle);
1233e2db
CW
3786 if (!obj)
3787 return -ENOENT;
3788
3789 err = mutex_lock_interruptible(&obj->mm.lock);
3790 if (err)
3791 goto out;
3ef94daa 3792
a4f5ea64 3793 if (obj->mm.pages &&
3e510a8e 3794 i915_gem_object_is_tiled(obj) &&
656bfa3a 3795 dev_priv->quirks & QUIRK_PIN_SWIZZLED_PAGES) {
bc0629a7
CW
3796 if (obj->mm.madv == I915_MADV_WILLNEED) {
3797 GEM_BUG_ON(!obj->mm.quirked);
a4f5ea64 3798 __i915_gem_object_unpin_pages(obj);
bc0629a7
CW
3799 obj->mm.quirked = false;
3800 }
3801 if (args->madv == I915_MADV_WILLNEED) {
2c3a3f44 3802 GEM_BUG_ON(obj->mm.quirked);
a4f5ea64 3803 __i915_gem_object_pin_pages(obj);
bc0629a7
CW
3804 obj->mm.quirked = true;
3805 }
656bfa3a
DV
3806 }
3807
a4f5ea64
CW
3808 if (obj->mm.madv != __I915_MADV_PURGED)
3809 obj->mm.madv = args->madv;
3ef94daa 3810
6c085a72 3811 /* if the object is no longer attached, discard its backing storage */
a4f5ea64 3812 if (obj->mm.madv == I915_MADV_DONTNEED && !obj->mm.pages)
2d7ef395
CW
3813 i915_gem_object_truncate(obj);
3814
a4f5ea64 3815 args->retained = obj->mm.madv != __I915_MADV_PURGED;
1233e2db 3816 mutex_unlock(&obj->mm.lock);
bb6baf76 3817
1233e2db 3818out:
f8c417cd 3819 i915_gem_object_put(obj);
1233e2db 3820 return err;
3ef94daa
CW
3821}
3822
37e680a1
CW
3823void i915_gem_object_init(struct drm_i915_gem_object *obj,
3824 const struct drm_i915_gem_object_ops *ops)
0327d6ba 3825{
1233e2db
CW
3826 mutex_init(&obj->mm.lock);
3827
56cea323 3828 INIT_LIST_HEAD(&obj->global_link);
275f039d 3829 INIT_LIST_HEAD(&obj->userfault_link);
b25cb2f8 3830 INIT_LIST_HEAD(&obj->obj_exec_link);
2f633156 3831 INIT_LIST_HEAD(&obj->vma_list);
8d9d5744 3832 INIT_LIST_HEAD(&obj->batch_pool_link);
0327d6ba 3833
37e680a1
CW
3834 obj->ops = ops;
3835
d07f0e59
CW
3836 reservation_object_init(&obj->__builtin_resv);
3837 obj->resv = &obj->__builtin_resv;
3838
50349247 3839 obj->frontbuffer_ggtt_origin = ORIGIN_GTT;
a4f5ea64
CW
3840
3841 obj->mm.madv = I915_MADV_WILLNEED;
3842 INIT_RADIX_TREE(&obj->mm.get_page.radix, GFP_KERNEL | __GFP_NOWARN);
3843 mutex_init(&obj->mm.get_page.lock);
0327d6ba 3844
f19ec8cb 3845 i915_gem_info_add_obj(to_i915(obj->base.dev), obj->base.size);
0327d6ba
CW
3846}
3847
37e680a1 3848static const struct drm_i915_gem_object_ops i915_gem_object_ops = {
3599a91c
TU
3849 .flags = I915_GEM_OBJECT_HAS_STRUCT_PAGE |
3850 I915_GEM_OBJECT_IS_SHRINKABLE,
37e680a1
CW
3851 .get_pages = i915_gem_object_get_pages_gtt,
3852 .put_pages = i915_gem_object_put_pages_gtt,
3853};
3854
b4bcbe2a
CW
3855/* Note we don't consider signbits :| */
3856#define overflows_type(x, T) \
3857 (sizeof(x) > sizeof(T) && (x) >> (sizeof(T) * BITS_PER_BYTE))
3858
3859struct drm_i915_gem_object *
3860i915_gem_object_create(struct drm_device *dev, u64 size)
ac52bc56 3861{
a26e5239 3862 struct drm_i915_private *dev_priv = to_i915(dev);
c397b908 3863 struct drm_i915_gem_object *obj;
5949eac4 3864 struct address_space *mapping;
1a240d4d 3865 gfp_t mask;
fe3db79b 3866 int ret;
ac52bc56 3867
b4bcbe2a
CW
3868 /* There is a prevalence of the assumption that we fit the object's
3869 * page count inside a 32bit _signed_ variable. Let's document this and
3870 * catch if we ever need to fix it. In the meantime, if you do spot
3871 * such a local variable, please consider fixing!
3872 */
3873 if (WARN_ON(size >> PAGE_SHIFT > INT_MAX))
3874 return ERR_PTR(-E2BIG);
3875
3876 if (overflows_type(size, obj->base.size))
3877 return ERR_PTR(-E2BIG);
3878
42dcedd4 3879 obj = i915_gem_object_alloc(dev);
c397b908 3880 if (obj == NULL)
fe3db79b 3881 return ERR_PTR(-ENOMEM);
673a394b 3882
fe3db79b
CW
3883 ret = drm_gem_object_init(dev, &obj->base, size);
3884 if (ret)
3885 goto fail;
673a394b 3886
bed1ea95 3887 mask = GFP_HIGHUSER | __GFP_RECLAIMABLE;
a26e5239 3888 if (IS_CRESTLINE(dev_priv) || IS_BROADWATER(dev_priv)) {
bed1ea95
CW
3889 /* 965gm cannot relocate objects above 4GiB. */
3890 mask &= ~__GFP_HIGHMEM;
3891 mask |= __GFP_DMA32;
3892 }
3893
93c76a3d 3894 mapping = obj->base.filp->f_mapping;
bed1ea95 3895 mapping_set_gfp_mask(mapping, mask);
5949eac4 3896
37e680a1 3897 i915_gem_object_init(obj, &i915_gem_object_ops);
73aa808f 3898
c397b908
DV
3899 obj->base.write_domain = I915_GEM_DOMAIN_CPU;
3900 obj->base.read_domains = I915_GEM_DOMAIN_CPU;
673a394b 3901
0031fb96 3902 if (HAS_LLC(dev_priv)) {
3d29b842 3903 /* On some devices, we can have the GPU use the LLC (the CPU
a1871112
EA
3904 * cache) for about a 10% performance improvement
3905 * compared to uncached. Graphics requests other than
3906 * display scanout are coherent with the CPU in
3907 * accessing this cache. This means in this mode we
3908 * don't need to clflush on the CPU side, and on the
3909 * GPU side we only need to flush internal caches to
3910 * get data visible to the CPU.
3911 *
3912 * However, we maintain the display planes as UC, and so
3913 * need to rebind when first used as such.
3914 */
3915 obj->cache_level = I915_CACHE_LLC;
3916 } else
3917 obj->cache_level = I915_CACHE_NONE;
3918
d861e338
DV
3919 trace_i915_gem_object_create(obj);
3920
05394f39 3921 return obj;
fe3db79b
CW
3922
3923fail:
3924 i915_gem_object_free(obj);
fe3db79b 3925 return ERR_PTR(ret);
c397b908
DV
3926}
3927
340fbd8c
CW
3928static bool discard_backing_storage(struct drm_i915_gem_object *obj)
3929{
3930 /* If we are the last user of the backing storage (be it shmemfs
3931 * pages or stolen etc), we know that the pages are going to be
3932 * immediately released. In this case, we can then skip copying
3933 * back the contents from the GPU.
3934 */
3935
a4f5ea64 3936 if (obj->mm.madv != I915_MADV_WILLNEED)
340fbd8c
CW
3937 return false;
3938
3939 if (obj->base.filp == NULL)
3940 return true;
3941
3942 /* At first glance, this looks racy, but then again so would be
3943 * userspace racing mmap against close. However, the first external
3944 * reference to the filp can only be obtained through the
3945 * i915_gem_mmap_ioctl() which safeguards us against the user
3946 * acquiring such a reference whilst we are in the middle of
3947 * freeing the object.
3948 */
3949 return atomic_long_read(&obj->base.filp->f_count) == 1;
3950}
3951
fbbd37b3
CW
3952static void __i915_gem_free_objects(struct drm_i915_private *i915,
3953 struct llist_node *freed)
673a394b 3954{
fbbd37b3 3955 struct drm_i915_gem_object *obj, *on;
673a394b 3956
fbbd37b3
CW
3957 mutex_lock(&i915->drm.struct_mutex);
3958 intel_runtime_pm_get(i915);
3959 llist_for_each_entry(obj, freed, freed) {
3960 struct i915_vma *vma, *vn;
3961
3962 trace_i915_gem_object_destroy(obj);
3963
3964 GEM_BUG_ON(i915_gem_object_is_active(obj));
3965 list_for_each_entry_safe(vma, vn,
3966 &obj->vma_list, obj_link) {
3967 GEM_BUG_ON(!i915_vma_is_ggtt(vma));
3968 GEM_BUG_ON(i915_vma_is_active(vma));
3969 vma->flags &= ~I915_VMA_PIN_MASK;
3970 i915_vma_close(vma);
3971 }
db6c2b41
CW
3972 GEM_BUG_ON(!list_empty(&obj->vma_list));
3973 GEM_BUG_ON(!RB_EMPTY_ROOT(&obj->vma_tree));
fbbd37b3 3974
56cea323 3975 list_del(&obj->global_link);
fbbd37b3
CW
3976 }
3977 intel_runtime_pm_put(i915);
3978 mutex_unlock(&i915->drm.struct_mutex);
3979
3980 llist_for_each_entry_safe(obj, on, freed, freed) {
3981 GEM_BUG_ON(obj->bind_count);
3982 GEM_BUG_ON(atomic_read(&obj->frontbuffer_bits));
3983
3984 if (obj->ops->release)
3985 obj->ops->release(obj);
f65c9168 3986
fbbd37b3
CW
3987 if (WARN_ON(i915_gem_object_has_pinned_pages(obj)))
3988 atomic_set(&obj->mm.pages_pin_count, 0);
548625ee 3989 __i915_gem_object_put_pages(obj, I915_MM_NORMAL);
fbbd37b3
CW
3990 GEM_BUG_ON(obj->mm.pages);
3991
3992 if (obj->base.import_attach)
3993 drm_prime_gem_destroy(&obj->base, NULL);
3994
d07f0e59 3995 reservation_object_fini(&obj->__builtin_resv);
fbbd37b3
CW
3996 drm_gem_object_release(&obj->base);
3997 i915_gem_info_remove_obj(i915, obj->base.size);
3998
3999 kfree(obj->bit_17);
4000 i915_gem_object_free(obj);
4001 }
4002}
4003
4004static void i915_gem_flush_free_objects(struct drm_i915_private *i915)
4005{
4006 struct llist_node *freed;
4007
4008 freed = llist_del_all(&i915->mm.free_list);
4009 if (unlikely(freed))
4010 __i915_gem_free_objects(i915, freed);
4011}
4012
4013static void __i915_gem_free_work(struct work_struct *work)
4014{
4015 struct drm_i915_private *i915 =
4016 container_of(work, struct drm_i915_private, mm.free_work);
4017 struct llist_node *freed;
26e12f89 4018
b1f788c6
CW
4019 /* All file-owned VMA should have been released by this point through
4020 * i915_gem_close_object(), or earlier by i915_gem_context_close().
4021 * However, the object may also be bound into the global GTT (e.g.
4022 * older GPUs without per-process support, or for direct access through
4023 * the GTT either for the user or for scanout). Those VMA still need to
4024 * unbound now.
4025 */
1488fc08 4026
fbbd37b3
CW
4027 while ((freed = llist_del_all(&i915->mm.free_list)))
4028 __i915_gem_free_objects(i915, freed);
4029}
a071fa00 4030
fbbd37b3
CW
4031static void __i915_gem_free_object_rcu(struct rcu_head *head)
4032{
4033 struct drm_i915_gem_object *obj =
4034 container_of(head, typeof(*obj), rcu);
4035 struct drm_i915_private *i915 = to_i915(obj->base.dev);
4036
4037 /* We can't simply use call_rcu() from i915_gem_free_object()
4038 * as we need to block whilst unbinding, and the call_rcu
4039 * task may be called from softirq context. So we take a
4040 * detour through a worker.
4041 */
4042 if (llist_add(&obj->freed, &i915->mm.free_list))
4043 schedule_work(&i915->mm.free_work);
4044}
656bfa3a 4045
fbbd37b3
CW
4046void i915_gem_free_object(struct drm_gem_object *gem_obj)
4047{
4048 struct drm_i915_gem_object *obj = to_intel_bo(gem_obj);
a4f5ea64 4049
bc0629a7
CW
4050 if (obj->mm.quirked)
4051 __i915_gem_object_unpin_pages(obj);
4052
340fbd8c 4053 if (discard_backing_storage(obj))
a4f5ea64 4054 obj->mm.madv = I915_MADV_DONTNEED;
de151cf6 4055
fbbd37b3
CW
4056 /* Before we free the object, make sure any pure RCU-only
4057 * read-side critical sections are complete, e.g.
4058 * i915_gem_busy_ioctl(). For the corresponding synchronized
4059 * lookup see i915_gem_object_lookup_rcu().
4060 */
4061 call_rcu(&obj->rcu, __i915_gem_free_object_rcu);
673a394b
EA
4062}
4063
f8a7fde4
CW
4064void __i915_gem_object_release_unless_active(struct drm_i915_gem_object *obj)
4065{
4066 lockdep_assert_held(&obj->base.dev->struct_mutex);
4067
4068 GEM_BUG_ON(i915_gem_object_has_active_reference(obj));
4069 if (i915_gem_object_is_active(obj))
4070 i915_gem_object_set_active_reference(obj);
4071 else
4072 i915_gem_object_put(obj);
4073}
4074
3033acab
CW
4075static void assert_kernel_context_is_current(struct drm_i915_private *dev_priv)
4076{
4077 struct intel_engine_cs *engine;
4078 enum intel_engine_id id;
4079
4080 for_each_engine(engine, dev_priv, id)
4081 GEM_BUG_ON(engine->last_context != dev_priv->kernel_context);
4082}
4083
dcff85c8 4084int i915_gem_suspend(struct drm_device *dev)
29105ccc 4085{
fac5e23e 4086 struct drm_i915_private *dev_priv = to_i915(dev);
dcff85c8 4087 int ret;
28dfe52a 4088
54b4f68f
CW
4089 intel_suspend_gt_powersave(dev_priv);
4090
45c5f202 4091 mutex_lock(&dev->struct_mutex);
5ab57c70
CW
4092
4093 /* We have to flush all the executing contexts to main memory so
4094 * that they can saved in the hibernation image. To ensure the last
4095 * context image is coherent, we have to switch away from it. That
4096 * leaves the dev_priv->kernel_context still active when
4097 * we actually suspend, and its image in memory may not match the GPU
4098 * state. Fortunately, the kernel_context is disposable and we do
4099 * not rely on its state.
4100 */
4101 ret = i915_gem_switch_to_kernel_context(dev_priv);
4102 if (ret)
4103 goto err;
4104
22dd3bb9
CW
4105 ret = i915_gem_wait_for_idle(dev_priv,
4106 I915_WAIT_INTERRUPTIBLE |
4107 I915_WAIT_LOCKED);
f7403347 4108 if (ret)
45c5f202 4109 goto err;
f7403347 4110
c033666a 4111 i915_gem_retire_requests(dev_priv);
28176ef4 4112 GEM_BUG_ON(dev_priv->gt.active_requests);
673a394b 4113
3033acab 4114 assert_kernel_context_is_current(dev_priv);
b2e862d0 4115 i915_gem_context_lost(dev_priv);
45c5f202
CW
4116 mutex_unlock(&dev->struct_mutex);
4117
737b1506 4118 cancel_delayed_work_sync(&dev_priv->gpu_error.hangcheck_work);
67d97da3
CW
4119 cancel_delayed_work_sync(&dev_priv->gt.retire_work);
4120 flush_delayed_work(&dev_priv->gt.idle_work);
fbbd37b3 4121 flush_work(&dev_priv->mm.free_work);
29105ccc 4122
bdcf120b
CW
4123 /* Assert that we sucessfully flushed all the work and
4124 * reset the GPU back to its idle, low power state.
4125 */
67d97da3 4126 WARN_ON(dev_priv->gt.awake);
31ab49ab 4127 WARN_ON(!intel_execlists_idle(dev_priv));
bdcf120b 4128
1c777c5d
ID
4129 /*
4130 * Neither the BIOS, ourselves or any other kernel
4131 * expects the system to be in execlists mode on startup,
4132 * so we need to reset the GPU back to legacy mode. And the only
4133 * known way to disable logical contexts is through a GPU reset.
4134 *
4135 * So in order to leave the system in a known default configuration,
4136 * always reset the GPU upon unload and suspend. Afterwards we then
4137 * clean up the GEM state tracking, flushing off the requests and
4138 * leaving the system in a known idle state.
4139 *
4140 * Note that is of the upmost importance that the GPU is idle and
4141 * all stray writes are flushed *before* we dismantle the backing
4142 * storage for the pinned objects.
4143 *
4144 * However, since we are uncertain that resetting the GPU on older
4145 * machines is a good idea, we don't - just in case it leaves the
4146 * machine in an unusable condition.
4147 */
0031fb96 4148 if (HAS_HW_CONTEXTS(dev_priv)) {
1c777c5d
ID
4149 int reset = intel_gpu_reset(dev_priv, ALL_ENGINES);
4150 WARN_ON(reset && reset != -ENODEV);
4151 }
4152
673a394b 4153 return 0;
45c5f202
CW
4154
4155err:
4156 mutex_unlock(&dev->struct_mutex);
4157 return ret;
673a394b
EA
4158}
4159
5ab57c70
CW
4160void i915_gem_resume(struct drm_device *dev)
4161{
4162 struct drm_i915_private *dev_priv = to_i915(dev);
4163
31ab49ab
ID
4164 WARN_ON(dev_priv->gt.awake);
4165
5ab57c70
CW
4166 mutex_lock(&dev->struct_mutex);
4167 i915_gem_restore_gtt_mappings(dev);
4168
4169 /* As we didn't flush the kernel context before suspend, we cannot
4170 * guarantee that the context image is complete. So let's just reset
4171 * it and start again.
4172 */
821ed7df 4173 dev_priv->gt.resume(dev_priv);
5ab57c70
CW
4174
4175 mutex_unlock(&dev->struct_mutex);
4176}
4177
f691e2f4
DV
4178void i915_gem_init_swizzling(struct drm_device *dev)
4179{
fac5e23e 4180 struct drm_i915_private *dev_priv = to_i915(dev);
f691e2f4 4181
11782b02 4182 if (INTEL_INFO(dev)->gen < 5 ||
f691e2f4
DV
4183 dev_priv->mm.bit_6_swizzle_x == I915_BIT_6_SWIZZLE_NONE)
4184 return;
4185
4186 I915_WRITE(DISP_ARB_CTL, I915_READ(DISP_ARB_CTL) |
4187 DISP_TILE_SURFACE_SWIZZLING);
4188
5db94019 4189 if (IS_GEN5(dev_priv))
11782b02
DV
4190 return;
4191
f691e2f4 4192 I915_WRITE(TILECTL, I915_READ(TILECTL) | TILECTL_SWZCTL);
5db94019 4193 if (IS_GEN6(dev_priv))
6b26c86d 4194 I915_WRITE(ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_SNB));
5db94019 4195 else if (IS_GEN7(dev_priv))
6b26c86d 4196 I915_WRITE(ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_IVB));
5db94019 4197 else if (IS_GEN8(dev_priv))
31a5336e 4198 I915_WRITE(GAMTARBMODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_BDW));
8782e26c
BW
4199 else
4200 BUG();
f691e2f4 4201}
e21af88d 4202
50a0bc90 4203static void init_unused_ring(struct drm_i915_private *dev_priv, u32 base)
81e7f200 4204{
81e7f200
VS
4205 I915_WRITE(RING_CTL(base), 0);
4206 I915_WRITE(RING_HEAD(base), 0);
4207 I915_WRITE(RING_TAIL(base), 0);
4208 I915_WRITE(RING_START(base), 0);
4209}
4210
50a0bc90 4211static void init_unused_rings(struct drm_i915_private *dev_priv)
81e7f200 4212{
50a0bc90
TU
4213 if (IS_I830(dev_priv)) {
4214 init_unused_ring(dev_priv, PRB1_BASE);
4215 init_unused_ring(dev_priv, SRB0_BASE);
4216 init_unused_ring(dev_priv, SRB1_BASE);
4217 init_unused_ring(dev_priv, SRB2_BASE);
4218 init_unused_ring(dev_priv, SRB3_BASE);
4219 } else if (IS_GEN2(dev_priv)) {
4220 init_unused_ring(dev_priv, SRB0_BASE);
4221 init_unused_ring(dev_priv, SRB1_BASE);
4222 } else if (IS_GEN3(dev_priv)) {
4223 init_unused_ring(dev_priv, PRB1_BASE);
4224 init_unused_ring(dev_priv, PRB2_BASE);
81e7f200
VS
4225 }
4226}
4227
4fc7c971
BW
4228int
4229i915_gem_init_hw(struct drm_device *dev)
4230{
fac5e23e 4231 struct drm_i915_private *dev_priv = to_i915(dev);
e2f80391 4232 struct intel_engine_cs *engine;
3b3f1650 4233 enum intel_engine_id id;
d200cda6 4234 int ret;
4fc7c971 4235
de867c20
CW
4236 dev_priv->gt.last_init_time = ktime_get();
4237
5e4f5189
CW
4238 /* Double layer security blanket, see i915_gem_init() */
4239 intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
4240
0031fb96 4241 if (HAS_EDRAM(dev_priv) && INTEL_GEN(dev_priv) < 9)
05e21cc4 4242 I915_WRITE(HSW_IDICR, I915_READ(HSW_IDICR) | IDIHASHMSK(0xf));
4fc7c971 4243
772c2a51 4244 if (IS_HASWELL(dev_priv))
50a0bc90 4245 I915_WRITE(MI_PREDICATE_RESULT_2, IS_HSW_GT3(dev_priv) ?
0bf21347 4246 LOWER_SLICE_ENABLED : LOWER_SLICE_DISABLED);
9435373e 4247
6e266956 4248 if (HAS_PCH_NOP(dev_priv)) {
fd6b8f43 4249 if (IS_IVYBRIDGE(dev_priv)) {
6ba844b0
DV
4250 u32 temp = I915_READ(GEN7_MSG_CTL);
4251 temp &= ~(WAIT_FOR_PCH_FLR_ACK | WAIT_FOR_PCH_RESET_ACK);
4252 I915_WRITE(GEN7_MSG_CTL, temp);
4253 } else if (INTEL_INFO(dev)->gen >= 7) {
4254 u32 temp = I915_READ(HSW_NDE_RSTWRN_OPT);
4255 temp &= ~RESET_PCH_HANDSHAKE_ENABLE;
4256 I915_WRITE(HSW_NDE_RSTWRN_OPT, temp);
4257 }
88a2b2a3
BW
4258 }
4259
4fc7c971
BW
4260 i915_gem_init_swizzling(dev);
4261
d5abdfda
DV
4262 /*
4263 * At least 830 can leave some of the unused rings
4264 * "active" (ie. head != tail) after resume which
4265 * will prevent c3 entry. Makes sure all unused rings
4266 * are totally idle.
4267 */
50a0bc90 4268 init_unused_rings(dev_priv);
d5abdfda 4269
ed54c1a1 4270 BUG_ON(!dev_priv->kernel_context);
90638cc1 4271
4ad2fd88
JH
4272 ret = i915_ppgtt_init_hw(dev);
4273 if (ret) {
4274 DRM_ERROR("PPGTT enable HW failed %d\n", ret);
4275 goto out;
4276 }
4277
4278 /* Need to do basic initialisation of all rings first: */
3b3f1650 4279 for_each_engine(engine, dev_priv, id) {
e2f80391 4280 ret = engine->init_hw(engine);
35a57ffb 4281 if (ret)
5e4f5189 4282 goto out;
35a57ffb 4283 }
99433931 4284
0ccdacf6
PA
4285 intel_mocs_init_l3cc_table(dev);
4286
33a732f4 4287 /* We can't enable contexts until all firmware is loaded */
e556f7c1
DG
4288 ret = intel_guc_setup(dev);
4289 if (ret)
4290 goto out;
33a732f4 4291
5e4f5189
CW
4292out:
4293 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
2fa48d8d 4294 return ret;
8187a2b7
ZN
4295}
4296
39df9190
CW
4297bool intel_sanitize_semaphores(struct drm_i915_private *dev_priv, int value)
4298{
4299 if (INTEL_INFO(dev_priv)->gen < 6)
4300 return false;
4301
4302 /* TODO: make semaphores and Execlists play nicely together */
4303 if (i915.enable_execlists)
4304 return false;
4305
4306 if (value >= 0)
4307 return value;
4308
4309#ifdef CONFIG_INTEL_IOMMU
4310 /* Enable semaphores on SNB when IO remapping is off */
4311 if (INTEL_INFO(dev_priv)->gen == 6 && intel_iommu_gfx_mapped)
4312 return false;
4313#endif
4314
4315 return true;
4316}
4317
1070a42b
CW
4318int i915_gem_init(struct drm_device *dev)
4319{
fac5e23e 4320 struct drm_i915_private *dev_priv = to_i915(dev);
1070a42b
CW
4321 int ret;
4322
1070a42b 4323 mutex_lock(&dev->struct_mutex);
d62b4892 4324
a83014d3 4325 if (!i915.enable_execlists) {
821ed7df 4326 dev_priv->gt.resume = intel_legacy_submission_resume;
7e37f889 4327 dev_priv->gt.cleanup_engine = intel_engine_cleanup;
454afebd 4328 } else {
821ed7df 4329 dev_priv->gt.resume = intel_lr_context_resume;
117897f4 4330 dev_priv->gt.cleanup_engine = intel_logical_ring_cleanup;
a83014d3
OM
4331 }
4332
5e4f5189
CW
4333 /* This is just a security blanket to placate dragons.
4334 * On some systems, we very sporadically observe that the first TLBs
4335 * used by the CS may be stale, despite us poking the TLB reset. If
4336 * we hold the forcewake during initialisation these problems
4337 * just magically go away.
4338 */
4339 intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
4340
72778cb2 4341 i915_gem_init_userptr(dev_priv);
f6b9d5ca
CW
4342
4343 ret = i915_gem_init_ggtt(dev_priv);
4344 if (ret)
4345 goto out_unlock;
d62b4892 4346
2fa48d8d 4347 ret = i915_gem_context_init(dev);
7bcc3777
JN
4348 if (ret)
4349 goto out_unlock;
2fa48d8d 4350
8b3e2d36 4351 ret = intel_engines_init(dev);
35a57ffb 4352 if (ret)
7bcc3777 4353 goto out_unlock;
2fa48d8d 4354
1070a42b 4355 ret = i915_gem_init_hw(dev);
60990320 4356 if (ret == -EIO) {
7e21d648 4357 /* Allow engine initialisation to fail by marking the GPU as
60990320
CW
4358 * wedged. But we only want to do this where the GPU is angry,
4359 * for all other failure, such as an allocation failure, bail.
4360 */
4361 DRM_ERROR("Failed to initialize GPU, declaring it wedged\n");
821ed7df 4362 i915_gem_set_wedged(dev_priv);
60990320 4363 ret = 0;
1070a42b 4364 }
7bcc3777
JN
4365
4366out_unlock:
5e4f5189 4367 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
60990320 4368 mutex_unlock(&dev->struct_mutex);
1070a42b 4369
60990320 4370 return ret;
1070a42b
CW
4371}
4372
8187a2b7 4373void
117897f4 4374i915_gem_cleanup_engines(struct drm_device *dev)
8187a2b7 4375{
fac5e23e 4376 struct drm_i915_private *dev_priv = to_i915(dev);
e2f80391 4377 struct intel_engine_cs *engine;
3b3f1650 4378 enum intel_engine_id id;
8187a2b7 4379
3b3f1650 4380 for_each_engine(engine, dev_priv, id)
117897f4 4381 dev_priv->gt.cleanup_engine(engine);
8187a2b7
ZN
4382}
4383
40ae4e16
ID
4384void
4385i915_gem_load_init_fences(struct drm_i915_private *dev_priv)
4386{
91c8a326 4387 struct drm_device *dev = &dev_priv->drm;
49ef5294 4388 int i;
40ae4e16
ID
4389
4390 if (INTEL_INFO(dev_priv)->gen >= 7 && !IS_VALLEYVIEW(dev_priv) &&
4391 !IS_CHERRYVIEW(dev_priv))
4392 dev_priv->num_fence_regs = 32;
4393 else if (INTEL_INFO(dev_priv)->gen >= 4 || IS_I945G(dev_priv) ||
4394 IS_I945GM(dev_priv) || IS_G33(dev_priv))
4395 dev_priv->num_fence_regs = 16;
4396 else
4397 dev_priv->num_fence_regs = 8;
4398
c033666a 4399 if (intel_vgpu_active(dev_priv))
40ae4e16
ID
4400 dev_priv->num_fence_regs =
4401 I915_READ(vgtif_reg(avail_rs.fence_num));
4402
4403 /* Initialize fence registers to zero */
49ef5294
CW
4404 for (i = 0; i < dev_priv->num_fence_regs; i++) {
4405 struct drm_i915_fence_reg *fence = &dev_priv->fence_regs[i];
4406
4407 fence->i915 = dev_priv;
4408 fence->id = i;
4409 list_add_tail(&fence->link, &dev_priv->mm.fence_list);
4410 }
40ae4e16
ID
4411 i915_gem_restore_fences(dev);
4412
4413 i915_gem_detect_bit_6_swizzle(dev);
4414}
4415
73cb9701 4416int
d64aa096 4417i915_gem_load_init(struct drm_device *dev)
673a394b 4418{
fac5e23e 4419 struct drm_i915_private *dev_priv = to_i915(dev);
a933568e 4420 int err = -ENOMEM;
42dcedd4 4421
a933568e
TU
4422 dev_priv->objects = KMEM_CACHE(drm_i915_gem_object, SLAB_HWCACHE_ALIGN);
4423 if (!dev_priv->objects)
73cb9701 4424 goto err_out;
73cb9701 4425
a933568e
TU
4426 dev_priv->vmas = KMEM_CACHE(i915_vma, SLAB_HWCACHE_ALIGN);
4427 if (!dev_priv->vmas)
73cb9701 4428 goto err_objects;
73cb9701 4429
a933568e
TU
4430 dev_priv->requests = KMEM_CACHE(drm_i915_gem_request,
4431 SLAB_HWCACHE_ALIGN |
4432 SLAB_RECLAIM_ACCOUNT |
4433 SLAB_DESTROY_BY_RCU);
4434 if (!dev_priv->requests)
73cb9701 4435 goto err_vmas;
73cb9701
CW
4436
4437 mutex_lock(&dev_priv->drm.struct_mutex);
4438 INIT_LIST_HEAD(&dev_priv->gt.timelines);
bb89485e 4439 err = i915_gem_timeline_init__global(dev_priv);
73cb9701
CW
4440 mutex_unlock(&dev_priv->drm.struct_mutex);
4441 if (err)
4442 goto err_requests;
673a394b 4443
a33afea5 4444 INIT_LIST_HEAD(&dev_priv->context_list);
fbbd37b3
CW
4445 INIT_WORK(&dev_priv->mm.free_work, __i915_gem_free_work);
4446 init_llist_head(&dev_priv->mm.free_list);
6c085a72
CW
4447 INIT_LIST_HEAD(&dev_priv->mm.unbound_list);
4448 INIT_LIST_HEAD(&dev_priv->mm.bound_list);
a09ba7fa 4449 INIT_LIST_HEAD(&dev_priv->mm.fence_list);
275f039d 4450 INIT_LIST_HEAD(&dev_priv->mm.userfault_list);
67d97da3 4451 INIT_DELAYED_WORK(&dev_priv->gt.retire_work,
673a394b 4452 i915_gem_retire_work_handler);
67d97da3 4453 INIT_DELAYED_WORK(&dev_priv->gt.idle_work,
b29c19b6 4454 i915_gem_idle_work_handler);
1f15b76f 4455 init_waitqueue_head(&dev_priv->gpu_error.wait_queue);
1f83fee0 4456 init_waitqueue_head(&dev_priv->gpu_error.reset_queue);
31169714 4457
72bfa19c
CW
4458 dev_priv->relative_constants_mode = I915_EXEC_CONSTANTS_REL_GENERAL;
4459
6b95a207 4460 init_waitqueue_head(&dev_priv->pending_flip_queue);
17250b71 4461
ce453d81
CW
4462 dev_priv->mm.interruptible = true;
4463
6f633402
JL
4464 atomic_set(&dev_priv->mm.bsd_engine_dispatch_index, 0);
4465
b5add959 4466 spin_lock_init(&dev_priv->fb_tracking.lock);
73cb9701
CW
4467
4468 return 0;
4469
4470err_requests:
4471 kmem_cache_destroy(dev_priv->requests);
4472err_vmas:
4473 kmem_cache_destroy(dev_priv->vmas);
4474err_objects:
4475 kmem_cache_destroy(dev_priv->objects);
4476err_out:
4477 return err;
673a394b 4478}
71acb5eb 4479
d64aa096
ID
4480void i915_gem_load_cleanup(struct drm_device *dev)
4481{
4482 struct drm_i915_private *dev_priv = to_i915(dev);
4483
7d5d59e5
CW
4484 WARN_ON(!llist_empty(&dev_priv->mm.free_list));
4485
d64aa096
ID
4486 kmem_cache_destroy(dev_priv->requests);
4487 kmem_cache_destroy(dev_priv->vmas);
4488 kmem_cache_destroy(dev_priv->objects);
0eafec6d
CW
4489
4490 /* And ensure that our DESTROY_BY_RCU slabs are truly destroyed */
4491 rcu_barrier();
d64aa096
ID
4492}
4493
6a800eab
CW
4494int i915_gem_freeze(struct drm_i915_private *dev_priv)
4495{
4496 intel_runtime_pm_get(dev_priv);
4497
4498 mutex_lock(&dev_priv->drm.struct_mutex);
4499 i915_gem_shrink_all(dev_priv);
4500 mutex_unlock(&dev_priv->drm.struct_mutex);
4501
4502 intel_runtime_pm_put(dev_priv);
4503
4504 return 0;
4505}
4506
461fb99c
CW
4507int i915_gem_freeze_late(struct drm_i915_private *dev_priv)
4508{
4509 struct drm_i915_gem_object *obj;
7aab2d53
CW
4510 struct list_head *phases[] = {
4511 &dev_priv->mm.unbound_list,
4512 &dev_priv->mm.bound_list,
4513 NULL
4514 }, **p;
461fb99c
CW
4515
4516 /* Called just before we write the hibernation image.
4517 *
4518 * We need to update the domain tracking to reflect that the CPU
4519 * will be accessing all the pages to create and restore from the
4520 * hibernation, and so upon restoration those pages will be in the
4521 * CPU domain.
4522 *
4523 * To make sure the hibernation image contains the latest state,
4524 * we update that state just before writing out the image.
7aab2d53
CW
4525 *
4526 * To try and reduce the hibernation image, we manually shrink
4527 * the objects as well.
461fb99c
CW
4528 */
4529
6a800eab
CW
4530 mutex_lock(&dev_priv->drm.struct_mutex);
4531 i915_gem_shrink(dev_priv, -1UL, I915_SHRINK_UNBOUND);
461fb99c 4532
7aab2d53 4533 for (p = phases; *p; p++) {
56cea323 4534 list_for_each_entry(obj, *p, global_link) {
7aab2d53
CW
4535 obj->base.read_domains = I915_GEM_DOMAIN_CPU;
4536 obj->base.write_domain = I915_GEM_DOMAIN_CPU;
4537 }
461fb99c 4538 }
6a800eab 4539 mutex_unlock(&dev_priv->drm.struct_mutex);
461fb99c
CW
4540
4541 return 0;
4542}
4543
f787a5f5 4544void i915_gem_release(struct drm_device *dev, struct drm_file *file)
b962442e 4545{
f787a5f5 4546 struct drm_i915_file_private *file_priv = file->driver_priv;
15f7bbc7 4547 struct drm_i915_gem_request *request;
b962442e
EA
4548
4549 /* Clean up our request list when the client is going away, so that
4550 * later retire_requests won't dereference our soon-to-be-gone
4551 * file_priv.
4552 */
1c25595f 4553 spin_lock(&file_priv->mm.lock);
15f7bbc7 4554 list_for_each_entry(request, &file_priv->mm.request_list, client_list)
f787a5f5 4555 request->file_priv = NULL;
1c25595f 4556 spin_unlock(&file_priv->mm.lock);
b29c19b6 4557
2e1b8730 4558 if (!list_empty(&file_priv->rps.link)) {
8d3afd7d 4559 spin_lock(&to_i915(dev)->rps.client_lock);
2e1b8730 4560 list_del(&file_priv->rps.link);
8d3afd7d 4561 spin_unlock(&to_i915(dev)->rps.client_lock);
1854d5ca 4562 }
b29c19b6
CW
4563}
4564
4565int i915_gem_open(struct drm_device *dev, struct drm_file *file)
4566{
4567 struct drm_i915_file_private *file_priv;
e422b888 4568 int ret;
b29c19b6
CW
4569
4570 DRM_DEBUG_DRIVER("\n");
4571
4572 file_priv = kzalloc(sizeof(*file_priv), GFP_KERNEL);
4573 if (!file_priv)
4574 return -ENOMEM;
4575
4576 file->driver_priv = file_priv;
f19ec8cb 4577 file_priv->dev_priv = to_i915(dev);
ab0e7ff9 4578 file_priv->file = file;
2e1b8730 4579 INIT_LIST_HEAD(&file_priv->rps.link);
b29c19b6
CW
4580
4581 spin_lock_init(&file_priv->mm.lock);
4582 INIT_LIST_HEAD(&file_priv->mm.request_list);
b29c19b6 4583
c80ff16e 4584 file_priv->bsd_engine = -1;
de1add36 4585
e422b888
BW
4586 ret = i915_gem_context_open(dev, file);
4587 if (ret)
4588 kfree(file_priv);
b29c19b6 4589
e422b888 4590 return ret;
b29c19b6
CW
4591}
4592
b680c37a
DV
4593/**
4594 * i915_gem_track_fb - update frontbuffer tracking
d9072a3e
GT
4595 * @old: current GEM buffer for the frontbuffer slots
4596 * @new: new GEM buffer for the frontbuffer slots
4597 * @frontbuffer_bits: bitmask of frontbuffer slots
b680c37a
DV
4598 *
4599 * This updates the frontbuffer tracking bits @frontbuffer_bits by clearing them
4600 * from @old and setting them in @new. Both @old and @new can be NULL.
4601 */
a071fa00
DV
4602void i915_gem_track_fb(struct drm_i915_gem_object *old,
4603 struct drm_i915_gem_object *new,
4604 unsigned frontbuffer_bits)
4605{
faf5bf0a
CW
4606 /* Control of individual bits within the mask are guarded by
4607 * the owning plane->mutex, i.e. we can never see concurrent
4608 * manipulation of individual bits. But since the bitfield as a whole
4609 * is updated using RMW, we need to use atomics in order to update
4610 * the bits.
4611 */
4612 BUILD_BUG_ON(INTEL_FRONTBUFFER_BITS_PER_PIPE * I915_MAX_PIPES >
4613 sizeof(atomic_t) * BITS_PER_BYTE);
4614
a071fa00 4615 if (old) {
faf5bf0a
CW
4616 WARN_ON(!(atomic_read(&old->frontbuffer_bits) & frontbuffer_bits));
4617 atomic_andnot(frontbuffer_bits, &old->frontbuffer_bits);
a071fa00
DV
4618 }
4619
4620 if (new) {
faf5bf0a
CW
4621 WARN_ON(atomic_read(&new->frontbuffer_bits) & frontbuffer_bits);
4622 atomic_or(frontbuffer_bits, &new->frontbuffer_bits);
a071fa00
DV
4623 }
4624}
4625
ea70299d
DG
4626/* Allocate a new GEM object and fill it with the supplied data */
4627struct drm_i915_gem_object *
4628i915_gem_object_create_from_data(struct drm_device *dev,
4629 const void *data, size_t size)
4630{
4631 struct drm_i915_gem_object *obj;
4632 struct sg_table *sg;
4633 size_t bytes;
4634 int ret;
4635
d37cd8a8 4636 obj = i915_gem_object_create(dev, round_up(size, PAGE_SIZE));
fe3db79b 4637 if (IS_ERR(obj))
ea70299d
DG
4638 return obj;
4639
4640 ret = i915_gem_object_set_to_cpu_domain(obj, true);
4641 if (ret)
4642 goto fail;
4643
a4f5ea64 4644 ret = i915_gem_object_pin_pages(obj);
ea70299d
DG
4645 if (ret)
4646 goto fail;
4647
a4f5ea64 4648 sg = obj->mm.pages;
ea70299d 4649 bytes = sg_copy_from_buffer(sg->sgl, sg->nents, (void *)data, size);
a4f5ea64 4650 obj->mm.dirty = true; /* Backing store is now out of date */
ea70299d
DG
4651 i915_gem_object_unpin_pages(obj);
4652
4653 if (WARN_ON(bytes != size)) {
4654 DRM_ERROR("Incomplete copy, wrote %zu of %zu", bytes, size);
4655 ret = -EFAULT;
4656 goto fail;
4657 }
4658
4659 return obj;
4660
4661fail:
f8c417cd 4662 i915_gem_object_put(obj);
ea70299d
DG
4663 return ERR_PTR(ret);
4664}
96d77634
CW
4665
4666struct scatterlist *
4667i915_gem_object_get_sg(struct drm_i915_gem_object *obj,
4668 unsigned int n,
4669 unsigned int *offset)
4670{
a4f5ea64 4671 struct i915_gem_object_page_iter *iter = &obj->mm.get_page;
96d77634
CW
4672 struct scatterlist *sg;
4673 unsigned int idx, count;
4674
4675 might_sleep();
4676 GEM_BUG_ON(n >= obj->base.size >> PAGE_SHIFT);
a4f5ea64 4677 GEM_BUG_ON(!i915_gem_object_has_pinned_pages(obj));
96d77634
CW
4678
4679 /* As we iterate forward through the sg, we record each entry in a
4680 * radixtree for quick repeated (backwards) lookups. If we have seen
4681 * this index previously, we will have an entry for it.
4682 *
4683 * Initial lookup is O(N), but this is amortized to O(1) for
4684 * sequential page access (where each new request is consecutive
4685 * to the previous one). Repeated lookups are O(lg(obj->base.size)),
4686 * i.e. O(1) with a large constant!
4687 */
4688 if (n < READ_ONCE(iter->sg_idx))
4689 goto lookup;
4690
4691 mutex_lock(&iter->lock);
4692
4693 /* We prefer to reuse the last sg so that repeated lookup of this
4694 * (or the subsequent) sg are fast - comparing against the last
4695 * sg is faster than going through the radixtree.
4696 */
4697
4698 sg = iter->sg_pos;
4699 idx = iter->sg_idx;
4700 count = __sg_page_count(sg);
4701
4702 while (idx + count <= n) {
4703 unsigned long exception, i;
4704 int ret;
4705
4706 /* If we cannot allocate and insert this entry, or the
4707 * individual pages from this range, cancel updating the
4708 * sg_idx so that on this lookup we are forced to linearly
4709 * scan onwards, but on future lookups we will try the
4710 * insertion again (in which case we need to be careful of
4711 * the error return reporting that we have already inserted
4712 * this index).
4713 */
4714 ret = radix_tree_insert(&iter->radix, idx, sg);
4715 if (ret && ret != -EEXIST)
4716 goto scan;
4717
4718 exception =
4719 RADIX_TREE_EXCEPTIONAL_ENTRY |
4720 idx << RADIX_TREE_EXCEPTIONAL_SHIFT;
4721 for (i = 1; i < count; i++) {
4722 ret = radix_tree_insert(&iter->radix, idx + i,
4723 (void *)exception);
4724 if (ret && ret != -EEXIST)
4725 goto scan;
4726 }
4727
4728 idx += count;
4729 sg = ____sg_next(sg);
4730 count = __sg_page_count(sg);
4731 }
4732
4733scan:
4734 iter->sg_pos = sg;
4735 iter->sg_idx = idx;
4736
4737 mutex_unlock(&iter->lock);
4738
4739 if (unlikely(n < idx)) /* insertion completed by another thread */
4740 goto lookup;
4741
4742 /* In case we failed to insert the entry into the radixtree, we need
4743 * to look beyond the current sg.
4744 */
4745 while (idx + count <= n) {
4746 idx += count;
4747 sg = ____sg_next(sg);
4748 count = __sg_page_count(sg);
4749 }
4750
4751 *offset = n - idx;
4752 return sg;
4753
4754lookup:
4755 rcu_read_lock();
4756
4757 sg = radix_tree_lookup(&iter->radix, n);
4758 GEM_BUG_ON(!sg);
4759
4760 /* If this index is in the middle of multi-page sg entry,
4761 * the radixtree will contain an exceptional entry that points
4762 * to the start of that range. We will return the pointer to
4763 * the base page and the offset of this page within the
4764 * sg entry's range.
4765 */
4766 *offset = 0;
4767 if (unlikely(radix_tree_exception(sg))) {
4768 unsigned long base =
4769 (unsigned long)sg >> RADIX_TREE_EXCEPTIONAL_SHIFT;
4770
4771 sg = radix_tree_lookup(&iter->radix, base);
4772 GEM_BUG_ON(!sg);
4773
4774 *offset = n - base;
4775 }
4776
4777 rcu_read_unlock();
4778
4779 return sg;
4780}
4781
4782struct page *
4783i915_gem_object_get_page(struct drm_i915_gem_object *obj, unsigned int n)
4784{
4785 struct scatterlist *sg;
4786 unsigned int offset;
4787
4788 GEM_BUG_ON(!i915_gem_object_has_struct_page(obj));
4789
4790 sg = i915_gem_object_get_sg(obj, n, &offset);
4791 return nth_page(sg_page(sg), offset);
4792}
4793
4794/* Like i915_gem_object_get_page(), but mark the returned page dirty */
4795struct page *
4796i915_gem_object_get_dirty_page(struct drm_i915_gem_object *obj,
4797 unsigned int n)
4798{
4799 struct page *page;
4800
4801 page = i915_gem_object_get_page(obj, n);
a4f5ea64 4802 if (!obj->mm.dirty)
96d77634
CW
4803 set_page_dirty(page);
4804
4805 return page;
4806}
4807
4808dma_addr_t
4809i915_gem_object_get_dma_address(struct drm_i915_gem_object *obj,
4810 unsigned long n)
4811{
4812 struct scatterlist *sg;
4813 unsigned int offset;
4814
4815 sg = i915_gem_object_get_sg(obj, n, &offset);
4816 return sg_dma_address(sg) + (offset << PAGE_SHIFT);
4817}