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