]> git.ipfire.org Git - thirdparty/linux.git/blame - drivers/gpu/drm/i915/i915_gem.c
drm/i915/glk: Convert a few more IS_BROXTON() to IS_GEN9_LP()
[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
de151cf6
JB
1752/**
1753 * i915_gem_fault - fault a page into the GTT
058d88c4 1754 * @area: CPU VMA in question
d9072a3e 1755 * @vmf: fault info
de151cf6
JB
1756 *
1757 * The fault handler is set up by drm_gem_mmap() when a object is GTT mapped
1758 * from userspace. The fault handler takes care of binding the object to
1759 * the GTT (if needed), allocating and programming a fence register (again,
1760 * only if needed based on whether the old reg is still valid or the object
1761 * is tiled) and inserting a new PTE into the faulting process.
1762 *
1763 * Note that the faulting process may involve evicting existing objects
1764 * from the GTT and/or fence registers to make room. So performance may
1765 * suffer if the GTT working set is large or there are few fence registers
1766 * left.
4cc69075
CW
1767 *
1768 * The current feature set supported by i915_gem_fault() and thus GTT mmaps
1769 * is exposed via I915_PARAM_MMAP_GTT_VERSION (see i915_gem_mmap_gtt_version).
de151cf6 1770 */
058d88c4 1771int i915_gem_fault(struct vm_area_struct *area, struct vm_fault *vmf)
de151cf6 1772{
03af84fe 1773#define MIN_CHUNK_PAGES ((1 << 20) >> PAGE_SHIFT) /* 1 MiB */
058d88c4 1774 struct drm_i915_gem_object *obj = to_intel_bo(area->vm_private_data);
05394f39 1775 struct drm_device *dev = obj->base.dev;
72e96d64
JL
1776 struct drm_i915_private *dev_priv = to_i915(dev);
1777 struct i915_ggtt *ggtt = &dev_priv->ggtt;
b8f9096d 1778 bool write = !!(vmf->flags & FAULT_FLAG_WRITE);
058d88c4 1779 struct i915_vma *vma;
de151cf6 1780 pgoff_t page_offset;
82118877 1781 unsigned int flags;
b8f9096d 1782 int ret;
f65c9168 1783
de151cf6 1784 /* We don't use vmf->pgoff since that has the fake offset */
1a29d85e 1785 page_offset = (vmf->address - area->vm_start) >> PAGE_SHIFT;
de151cf6 1786
db53a302
CW
1787 trace_i915_gem_object_fault(obj, page_offset, true, write);
1788
6e4930f6 1789 /* Try to flush the object off the GPU first without holding the lock.
b8f9096d 1790 * Upon acquiring the lock, we will perform our sanity checks and then
6e4930f6
CW
1791 * repeat the flush holding the lock in the normal manner to catch cases
1792 * where we are gazumped.
1793 */
e95433c7
CW
1794 ret = i915_gem_object_wait(obj,
1795 I915_WAIT_INTERRUPTIBLE,
1796 MAX_SCHEDULE_TIMEOUT,
1797 NULL);
6e4930f6 1798 if (ret)
b8f9096d
CW
1799 goto err;
1800
40e62d5d
CW
1801 ret = i915_gem_object_pin_pages(obj);
1802 if (ret)
1803 goto err;
1804
b8f9096d
CW
1805 intel_runtime_pm_get(dev_priv);
1806
1807 ret = i915_mutex_lock_interruptible(dev);
1808 if (ret)
1809 goto err_rpm;
6e4930f6 1810
eb119bd6 1811 /* Access to snoopable pages through the GTT is incoherent. */
0031fb96 1812 if (obj->cache_level != I915_CACHE_NONE && !HAS_LLC(dev_priv)) {
ddeff6ee 1813 ret = -EFAULT;
b8f9096d 1814 goto err_unlock;
eb119bd6
CW
1815 }
1816
82118877
CW
1817 /* If the object is smaller than a couple of partial vma, it is
1818 * not worth only creating a single partial vma - we may as well
1819 * clear enough space for the full object.
1820 */
1821 flags = PIN_MAPPABLE;
1822 if (obj->base.size > 2 * MIN_CHUNK_PAGES << PAGE_SHIFT)
1823 flags |= PIN_NONBLOCK | PIN_NONFAULT;
1824
a61007a8 1825 /* Now pin it into the GTT as needed */
82118877 1826 vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0, flags);
a61007a8
CW
1827 if (IS_ERR(vma)) {
1828 struct i915_ggtt_view view;
03af84fe
CW
1829 unsigned int chunk_size;
1830
a61007a8 1831 /* Use a partial view if it is bigger than available space */
03af84fe
CW
1832 chunk_size = MIN_CHUNK_PAGES;
1833 if (i915_gem_object_is_tiled(obj))
0ef723cb 1834 chunk_size = roundup(chunk_size, tile_row_pages(obj));
e7ded2d7 1835
c5ad54cf
JL
1836 memset(&view, 0, sizeof(view));
1837 view.type = I915_GGTT_VIEW_PARTIAL;
1838 view.params.partial.offset = rounddown(page_offset, chunk_size);
1839 view.params.partial.size =
a61007a8 1840 min_t(unsigned int, chunk_size,
908b1232 1841 vma_pages(area) - view.params.partial.offset);
c5ad54cf 1842
aa136d9d
CW
1843 /* If the partial covers the entire object, just create a
1844 * normal VMA.
1845 */
1846 if (chunk_size >= obj->base.size >> PAGE_SHIFT)
1847 view.type = I915_GGTT_VIEW_NORMAL;
1848
50349247
CW
1849 /* Userspace is now writing through an untracked VMA, abandon
1850 * all hope that the hardware is able to track future writes.
1851 */
1852 obj->frontbuffer_ggtt_origin = ORIGIN_CPU;
1853
a61007a8
CW
1854 vma = i915_gem_object_ggtt_pin(obj, &view, 0, 0, PIN_MAPPABLE);
1855 }
058d88c4
CW
1856 if (IS_ERR(vma)) {
1857 ret = PTR_ERR(vma);
b8f9096d 1858 goto err_unlock;
058d88c4 1859 }
4a684a41 1860
c9839303
CW
1861 ret = i915_gem_object_set_to_gtt_domain(obj, write);
1862 if (ret)
b8f9096d 1863 goto err_unpin;
74898d7e 1864
49ef5294 1865 ret = i915_vma_get_fence(vma);
d9e86c0e 1866 if (ret)
b8f9096d 1867 goto err_unpin;
7d1c4804 1868
275f039d 1869 /* Mark as being mmapped into userspace for later revocation */
9c870d03 1870 assert_rpm_wakelock_held(dev_priv);
275f039d
CW
1871 if (list_empty(&obj->userfault_link))
1872 list_add(&obj->userfault_link, &dev_priv->mm.userfault_list);
275f039d 1873
b90b91d8 1874 /* Finally, remap it using the new GTT offset */
c58305af
CW
1875 ret = remap_io_mapping(area,
1876 area->vm_start + (vma->ggtt_view.params.partial.offset << PAGE_SHIFT),
1877 (ggtt->mappable_base + vma->node.start) >> PAGE_SHIFT,
1878 min_t(u64, vma->size, area->vm_end - area->vm_start),
1879 &ggtt->mappable);
a61007a8 1880
b8f9096d 1881err_unpin:
058d88c4 1882 __i915_vma_unpin(vma);
b8f9096d 1883err_unlock:
de151cf6 1884 mutex_unlock(&dev->struct_mutex);
b8f9096d
CW
1885err_rpm:
1886 intel_runtime_pm_put(dev_priv);
40e62d5d 1887 i915_gem_object_unpin_pages(obj);
b8f9096d 1888err:
de151cf6 1889 switch (ret) {
d9bc7e9f 1890 case -EIO:
2232f031
DV
1891 /*
1892 * We eat errors when the gpu is terminally wedged to avoid
1893 * userspace unduly crashing (gl has no provisions for mmaps to
1894 * fail). But any other -EIO isn't ours (e.g. swap in failure)
1895 * and so needs to be reported.
1896 */
1897 if (!i915_terminally_wedged(&dev_priv->gpu_error)) {
f65c9168
PZ
1898 ret = VM_FAULT_SIGBUS;
1899 break;
1900 }
045e769a 1901 case -EAGAIN:
571c608d
DV
1902 /*
1903 * EAGAIN means the gpu is hung and we'll wait for the error
1904 * handler to reset everything when re-faulting in
1905 * i915_mutex_lock_interruptible.
d9bc7e9f 1906 */
c715089f
CW
1907 case 0:
1908 case -ERESTARTSYS:
bed636ab 1909 case -EINTR:
e79e0fe3
DR
1910 case -EBUSY:
1911 /*
1912 * EBUSY is ok: this just means that another thread
1913 * already did the job.
1914 */
f65c9168
PZ
1915 ret = VM_FAULT_NOPAGE;
1916 break;
de151cf6 1917 case -ENOMEM:
f65c9168
PZ
1918 ret = VM_FAULT_OOM;
1919 break;
a7c2e1aa 1920 case -ENOSPC:
45d67817 1921 case -EFAULT:
f65c9168
PZ
1922 ret = VM_FAULT_SIGBUS;
1923 break;
de151cf6 1924 default:
a7c2e1aa 1925 WARN_ONCE(ret, "unhandled error in i915_gem_fault: %i\n", ret);
f65c9168
PZ
1926 ret = VM_FAULT_SIGBUS;
1927 break;
de151cf6 1928 }
f65c9168 1929 return ret;
de151cf6
JB
1930}
1931
901782b2
CW
1932/**
1933 * i915_gem_release_mmap - remove physical page mappings
1934 * @obj: obj in question
1935 *
af901ca1 1936 * Preserve the reservation of the mmapping with the DRM core code, but
901782b2
CW
1937 * relinquish ownership of the pages back to the system.
1938 *
1939 * It is vital that we remove the page mapping if we have mapped a tiled
1940 * object through the GTT and then lose the fence register due to
1941 * resource pressure. Similarly if the object has been moved out of the
1942 * aperture, than pages mapped into userspace must be revoked. Removing the
1943 * mapping will then trigger a page fault on the next user access, allowing
1944 * fixup by i915_gem_fault().
1945 */
d05ca301 1946void
05394f39 1947i915_gem_release_mmap(struct drm_i915_gem_object *obj)
901782b2 1948{
275f039d 1949 struct drm_i915_private *i915 = to_i915(obj->base.dev);
275f039d 1950
349f2ccf
CW
1951 /* Serialisation between user GTT access and our code depends upon
1952 * revoking the CPU's PTE whilst the mutex is held. The next user
1953 * pagefault then has to wait until we release the mutex.
9c870d03
CW
1954 *
1955 * Note that RPM complicates somewhat by adding an additional
1956 * requirement that operations to the GGTT be made holding the RPM
1957 * wakeref.
349f2ccf 1958 */
275f039d 1959 lockdep_assert_held(&i915->drm.struct_mutex);
9c870d03 1960 intel_runtime_pm_get(i915);
349f2ccf 1961
3594a3e2 1962 if (list_empty(&obj->userfault_link))
9c870d03 1963 goto out;
901782b2 1964
3594a3e2 1965 list_del_init(&obj->userfault_link);
6796cb16
DR
1966 drm_vma_node_unmap(&obj->base.vma_node,
1967 obj->base.dev->anon_inode->i_mapping);
349f2ccf
CW
1968
1969 /* Ensure that the CPU's PTE are revoked and there are not outstanding
1970 * memory transactions from userspace before we return. The TLB
1971 * flushing implied above by changing the PTE above *should* be
1972 * sufficient, an extra barrier here just provides us with a bit
1973 * of paranoid documentation about our requirement to serialise
1974 * memory writes before touching registers / GSM.
1975 */
1976 wmb();
9c870d03
CW
1977
1978out:
1979 intel_runtime_pm_put(i915);
901782b2
CW
1980}
1981
7c108fd8 1982void i915_gem_runtime_suspend(struct drm_i915_private *dev_priv)
eedd10f4 1983{
3594a3e2 1984 struct drm_i915_gem_object *obj, *on;
7c108fd8 1985 int i;
eedd10f4 1986
3594a3e2
CW
1987 /*
1988 * Only called during RPM suspend. All users of the userfault_list
1989 * must be holding an RPM wakeref to ensure that this can not
1990 * run concurrently with themselves (and use the struct_mutex for
1991 * protection between themselves).
1992 */
275f039d 1993
3594a3e2
CW
1994 list_for_each_entry_safe(obj, on,
1995 &dev_priv->mm.userfault_list, userfault_link) {
1996 list_del_init(&obj->userfault_link);
275f039d
CW
1997 drm_vma_node_unmap(&obj->base.vma_node,
1998 obj->base.dev->anon_inode->i_mapping);
275f039d 1999 }
7c108fd8
CW
2000
2001 /* The fence will be lost when the device powers down. If any were
2002 * in use by hardware (i.e. they are pinned), we should not be powering
2003 * down! All other fences will be reacquired by the user upon waking.
2004 */
2005 for (i = 0; i < dev_priv->num_fence_regs; i++) {
2006 struct drm_i915_fence_reg *reg = &dev_priv->fence_regs[i];
2007
2008 if (WARN_ON(reg->pin_count))
2009 continue;
2010
2011 if (!reg->vma)
2012 continue;
2013
2014 GEM_BUG_ON(!list_empty(&reg->vma->obj->userfault_link));
2015 reg->dirty = true;
2016 }
eedd10f4
CW
2017}
2018
d8cb5086
CW
2019static int i915_gem_object_create_mmap_offset(struct drm_i915_gem_object *obj)
2020{
fac5e23e 2021 struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
f3f6184c 2022 int err;
da494d7c 2023
f3f6184c 2024 err = drm_gem_create_mmap_offset(&obj->base);
b42a13d9 2025 if (likely(!err))
f3f6184c 2026 return 0;
d8cb5086 2027
b42a13d9
CW
2028 /* Attempt to reap some mmap space from dead objects */
2029 do {
2030 err = i915_gem_wait_for_idle(dev_priv, I915_WAIT_INTERRUPTIBLE);
2031 if (err)
2032 break;
f3f6184c 2033
b42a13d9 2034 i915_gem_drain_freed_objects(dev_priv);
f3f6184c 2035 err = drm_gem_create_mmap_offset(&obj->base);
b42a13d9
CW
2036 if (!err)
2037 break;
2038
2039 } while (flush_delayed_work(&dev_priv->gt.retire_work));
da494d7c 2040
f3f6184c 2041 return err;
d8cb5086
CW
2042}
2043
2044static void i915_gem_object_free_mmap_offset(struct drm_i915_gem_object *obj)
2045{
d8cb5086
CW
2046 drm_gem_free_mmap_offset(&obj->base);
2047}
2048
da6b51d0 2049int
ff72145b
DA
2050i915_gem_mmap_gtt(struct drm_file *file,
2051 struct drm_device *dev,
da6b51d0 2052 uint32_t handle,
ff72145b 2053 uint64_t *offset)
de151cf6 2054{
05394f39 2055 struct drm_i915_gem_object *obj;
de151cf6
JB
2056 int ret;
2057
03ac0642 2058 obj = i915_gem_object_lookup(file, handle);
f3f6184c
CW
2059 if (!obj)
2060 return -ENOENT;
ab18282d 2061
d8cb5086 2062 ret = i915_gem_object_create_mmap_offset(obj);
f3f6184c
CW
2063 if (ret == 0)
2064 *offset = drm_vma_node_offset_addr(&obj->base.vma_node);
de151cf6 2065
f0cd5182 2066 i915_gem_object_put(obj);
1d7cfea1 2067 return ret;
de151cf6
JB
2068}
2069
ff72145b
DA
2070/**
2071 * i915_gem_mmap_gtt_ioctl - prepare an object for GTT mmap'ing
2072 * @dev: DRM device
2073 * @data: GTT mapping ioctl data
2074 * @file: GEM object info
2075 *
2076 * Simply returns the fake offset to userspace so it can mmap it.
2077 * The mmap call will end up in drm_gem_mmap(), which will set things
2078 * up so we can get faults in the handler above.
2079 *
2080 * The fault handler will take care of binding the object into the GTT
2081 * (since it may have been evicted to make room for something), allocating
2082 * a fence register, and mapping the appropriate aperture address into
2083 * userspace.
2084 */
2085int
2086i915_gem_mmap_gtt_ioctl(struct drm_device *dev, void *data,
2087 struct drm_file *file)
2088{
2089 struct drm_i915_gem_mmap_gtt *args = data;
2090
da6b51d0 2091 return i915_gem_mmap_gtt(file, dev, args->handle, &args->offset);
ff72145b
DA
2092}
2093
225067ee
DV
2094/* Immediately discard the backing storage */
2095static void
2096i915_gem_object_truncate(struct drm_i915_gem_object *obj)
e5281ccd 2097{
4d6294bf 2098 i915_gem_object_free_mmap_offset(obj);
1286ff73 2099
4d6294bf
CW
2100 if (obj->base.filp == NULL)
2101 return;
e5281ccd 2102
225067ee
DV
2103 /* Our goal here is to return as much of the memory as
2104 * is possible back to the system as we are called from OOM.
2105 * To do this we must instruct the shmfs to drop all of its
2106 * backing pages, *now*.
2107 */
5537252b 2108 shmem_truncate_range(file_inode(obj->base.filp), 0, (loff_t)-1);
a4f5ea64 2109 obj->mm.madv = __I915_MADV_PURGED;
225067ee 2110}
e5281ccd 2111
5537252b 2112/* Try to discard unwanted pages */
03ac84f1 2113void __i915_gem_object_invalidate(struct drm_i915_gem_object *obj)
225067ee 2114{
5537252b
CW
2115 struct address_space *mapping;
2116
1233e2db
CW
2117 lockdep_assert_held(&obj->mm.lock);
2118 GEM_BUG_ON(obj->mm.pages);
2119
a4f5ea64 2120 switch (obj->mm.madv) {
5537252b
CW
2121 case I915_MADV_DONTNEED:
2122 i915_gem_object_truncate(obj);
2123 case __I915_MADV_PURGED:
2124 return;
2125 }
2126
2127 if (obj->base.filp == NULL)
2128 return;
2129
93c76a3d 2130 mapping = obj->base.filp->f_mapping,
5537252b 2131 invalidate_mapping_pages(mapping, 0, (loff_t)-1);
e5281ccd
CW
2132}
2133
5cdf5881 2134static void
03ac84f1
CW
2135i915_gem_object_put_pages_gtt(struct drm_i915_gem_object *obj,
2136 struct sg_table *pages)
673a394b 2137{
85d1225e
DG
2138 struct sgt_iter sgt_iter;
2139 struct page *page;
1286ff73 2140
e5facdf9 2141 __i915_gem_object_release_shmem(obj, pages, true);
673a394b 2142
03ac84f1 2143 i915_gem_gtt_finish_pages(obj, pages);
e2273302 2144
6dacfd2f 2145 if (i915_gem_object_needs_bit17_swizzle(obj))
03ac84f1 2146 i915_gem_object_save_bit_17_swizzle(obj, pages);
280b713b 2147
03ac84f1 2148 for_each_sgt_page(page, sgt_iter, pages) {
a4f5ea64 2149 if (obj->mm.dirty)
9da3da66 2150 set_page_dirty(page);
3ef94daa 2151
a4f5ea64 2152 if (obj->mm.madv == I915_MADV_WILLNEED)
9da3da66 2153 mark_page_accessed(page);
3ef94daa 2154
09cbfeaf 2155 put_page(page);
3ef94daa 2156 }
a4f5ea64 2157 obj->mm.dirty = false;
673a394b 2158
03ac84f1
CW
2159 sg_free_table(pages);
2160 kfree(pages);
37e680a1 2161}
6c085a72 2162
96d77634
CW
2163static void __i915_gem_object_reset_page_iter(struct drm_i915_gem_object *obj)
2164{
2165 struct radix_tree_iter iter;
2166 void **slot;
2167
a4f5ea64
CW
2168 radix_tree_for_each_slot(slot, &obj->mm.get_page.radix, &iter, 0)
2169 radix_tree_delete(&obj->mm.get_page.radix, iter.index);
96d77634
CW
2170}
2171
548625ee
CW
2172void __i915_gem_object_put_pages(struct drm_i915_gem_object *obj,
2173 enum i915_mm_subclass subclass)
37e680a1 2174{
03ac84f1 2175 struct sg_table *pages;
37e680a1 2176
a4f5ea64 2177 if (i915_gem_object_has_pinned_pages(obj))
03ac84f1 2178 return;
a5570178 2179
15717de2 2180 GEM_BUG_ON(obj->bind_count);
1233e2db
CW
2181 if (!READ_ONCE(obj->mm.pages))
2182 return;
2183
2184 /* May be called by shrinker from within get_pages() (on another bo) */
548625ee 2185 mutex_lock_nested(&obj->mm.lock, subclass);
1233e2db
CW
2186 if (unlikely(atomic_read(&obj->mm.pages_pin_count)))
2187 goto unlock;
3e123027 2188
a2165e31
CW
2189 /* ->put_pages might need to allocate memory for the bit17 swizzle
2190 * array, hence protect them from being reaped by removing them from gtt
2191 * lists early. */
03ac84f1
CW
2192 pages = fetch_and_zero(&obj->mm.pages);
2193 GEM_BUG_ON(!pages);
a2165e31 2194
a4f5ea64 2195 if (obj->mm.mapping) {
4b30cb23
CW
2196 void *ptr;
2197
a4f5ea64 2198 ptr = ptr_mask_bits(obj->mm.mapping);
4b30cb23
CW
2199 if (is_vmalloc_addr(ptr))
2200 vunmap(ptr);
fb8621d3 2201 else
4b30cb23
CW
2202 kunmap(kmap_to_page(ptr));
2203
a4f5ea64 2204 obj->mm.mapping = NULL;
0a798eb9
CW
2205 }
2206
96d77634
CW
2207 __i915_gem_object_reset_page_iter(obj);
2208
03ac84f1 2209 obj->ops->put_pages(obj, pages);
1233e2db
CW
2210unlock:
2211 mutex_unlock(&obj->mm.lock);
6c085a72
CW
2212}
2213
4ff340f0 2214static unsigned int swiotlb_max_size(void)
871dfbd6
CW
2215{
2216#if IS_ENABLED(CONFIG_SWIOTLB)
2217 return rounddown(swiotlb_nr_tbl() << IO_TLB_SHIFT, PAGE_SIZE);
2218#else
2219 return 0;
2220#endif
2221}
2222
0c40ce13
TU
2223static void i915_sg_trim(struct sg_table *orig_st)
2224{
2225 struct sg_table new_st;
2226 struct scatterlist *sg, *new_sg;
2227 unsigned int i;
2228
2229 if (orig_st->nents == orig_st->orig_nents)
2230 return;
2231
8bfc478f 2232 if (sg_alloc_table(&new_st, orig_st->nents, GFP_KERNEL | __GFP_NOWARN))
0c40ce13
TU
2233 return;
2234
2235 new_sg = new_st.sgl;
2236 for_each_sg(orig_st->sgl, sg, orig_st->nents, i) {
2237 sg_set_page(new_sg, sg_page(sg), sg->length, 0);
2238 /* called before being DMA mapped, no need to copy sg->dma_* */
2239 new_sg = sg_next(new_sg);
2240 }
c2dc6cc9 2241 GEM_BUG_ON(new_sg); /* Should walk exactly nents and hit the end */
0c40ce13
TU
2242
2243 sg_free_table(orig_st);
2244
2245 *orig_st = new_st;
2246}
2247
03ac84f1 2248static struct sg_table *
6c085a72 2249i915_gem_object_get_pages_gtt(struct drm_i915_gem_object *obj)
e5281ccd 2250{
fac5e23e 2251 struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
d766ef53
CW
2252 const unsigned long page_count = obj->base.size / PAGE_SIZE;
2253 unsigned long i;
e5281ccd 2254 struct address_space *mapping;
9da3da66
CW
2255 struct sg_table *st;
2256 struct scatterlist *sg;
85d1225e 2257 struct sgt_iter sgt_iter;
e5281ccd 2258 struct page *page;
90797e6d 2259 unsigned long last_pfn = 0; /* suppress gcc warning */
4ff340f0 2260 unsigned int max_segment;
e2273302 2261 int ret;
6c085a72 2262 gfp_t gfp;
e5281ccd 2263
6c085a72
CW
2264 /* Assert that the object is not currently in any GPU domain. As it
2265 * wasn't in the GTT, there shouldn't be any way it could have been in
2266 * a GPU cache
2267 */
03ac84f1
CW
2268 GEM_BUG_ON(obj->base.read_domains & I915_GEM_GPU_DOMAINS);
2269 GEM_BUG_ON(obj->base.write_domain & I915_GEM_GPU_DOMAINS);
6c085a72 2270
871dfbd6
CW
2271 max_segment = swiotlb_max_size();
2272 if (!max_segment)
4ff340f0 2273 max_segment = rounddown(UINT_MAX, PAGE_SIZE);
871dfbd6 2274
9da3da66
CW
2275 st = kmalloc(sizeof(*st), GFP_KERNEL);
2276 if (st == NULL)
03ac84f1 2277 return ERR_PTR(-ENOMEM);
9da3da66 2278
d766ef53 2279rebuild_st:
9da3da66 2280 if (sg_alloc_table(st, page_count, GFP_KERNEL)) {
9da3da66 2281 kfree(st);
03ac84f1 2282 return ERR_PTR(-ENOMEM);
9da3da66 2283 }
e5281ccd 2284
9da3da66
CW
2285 /* Get the list of pages out of our struct file. They'll be pinned
2286 * at this point until we release them.
2287 *
2288 * Fail silently without starting the shrinker
2289 */
93c76a3d 2290 mapping = obj->base.filp->f_mapping;
c62d2555 2291 gfp = mapping_gfp_constraint(mapping, ~(__GFP_IO | __GFP_RECLAIM));
d0164adc 2292 gfp |= __GFP_NORETRY | __GFP_NOWARN;
90797e6d
ID
2293 sg = st->sgl;
2294 st->nents = 0;
2295 for (i = 0; i < page_count; i++) {
6c085a72
CW
2296 page = shmem_read_mapping_page_gfp(mapping, i, gfp);
2297 if (IS_ERR(page)) {
21ab4e74
CW
2298 i915_gem_shrink(dev_priv,
2299 page_count,
2300 I915_SHRINK_BOUND |
2301 I915_SHRINK_UNBOUND |
2302 I915_SHRINK_PURGEABLE);
6c085a72
CW
2303 page = shmem_read_mapping_page_gfp(mapping, i, gfp);
2304 }
2305 if (IS_ERR(page)) {
2306 /* We've tried hard to allocate the memory by reaping
2307 * our own buffer, now let the real VM do its job and
2308 * go down in flames if truly OOM.
2309 */
f461d1be 2310 page = shmem_read_mapping_page(mapping, i);
e2273302
ID
2311 if (IS_ERR(page)) {
2312 ret = PTR_ERR(page);
b17993b7 2313 goto err_sg;
e2273302 2314 }
6c085a72 2315 }
871dfbd6
CW
2316 if (!i ||
2317 sg->length >= max_segment ||
2318 page_to_pfn(page) != last_pfn + 1) {
90797e6d
ID
2319 if (i)
2320 sg = sg_next(sg);
2321 st->nents++;
2322 sg_set_page(sg, page, PAGE_SIZE, 0);
2323 } else {
2324 sg->length += PAGE_SIZE;
2325 }
2326 last_pfn = page_to_pfn(page);
3bbbe706
DV
2327
2328 /* Check that the i965g/gm workaround works. */
2329 WARN_ON((gfp & __GFP_DMA32) && (last_pfn >= 0x00100000UL));
e5281ccd 2330 }
871dfbd6 2331 if (sg) /* loop terminated early; short sg table */
426729dc 2332 sg_mark_end(sg);
74ce6b6c 2333
0c40ce13
TU
2334 /* Trim unused sg entries to avoid wasting memory. */
2335 i915_sg_trim(st);
2336
03ac84f1 2337 ret = i915_gem_gtt_prepare_pages(obj, st);
d766ef53
CW
2338 if (ret) {
2339 /* DMA remapping failed? One possible cause is that
2340 * it could not reserve enough large entries, asking
2341 * for PAGE_SIZE chunks instead may be helpful.
2342 */
2343 if (max_segment > PAGE_SIZE) {
2344 for_each_sgt_page(page, sgt_iter, st)
2345 put_page(page);
2346 sg_free_table(st);
2347
2348 max_segment = PAGE_SIZE;
2349 goto rebuild_st;
2350 } else {
2351 dev_warn(&dev_priv->drm.pdev->dev,
2352 "Failed to DMA remap %lu pages\n",
2353 page_count);
2354 goto err_pages;
2355 }
2356 }
e2273302 2357
6dacfd2f 2358 if (i915_gem_object_needs_bit17_swizzle(obj))
03ac84f1 2359 i915_gem_object_do_bit_17_swizzle(obj, st);
e5281ccd 2360
03ac84f1 2361 return st;
e5281ccd 2362
b17993b7 2363err_sg:
90797e6d 2364 sg_mark_end(sg);
b17993b7 2365err_pages:
85d1225e
DG
2366 for_each_sgt_page(page, sgt_iter, st)
2367 put_page(page);
9da3da66
CW
2368 sg_free_table(st);
2369 kfree(st);
0820baf3
CW
2370
2371 /* shmemfs first checks if there is enough memory to allocate the page
2372 * and reports ENOSPC should there be insufficient, along with the usual
2373 * ENOMEM for a genuine allocation failure.
2374 *
2375 * We use ENOSPC in our driver to mean that we have run out of aperture
2376 * space and so want to translate the error from shmemfs back to our
2377 * usual understanding of ENOMEM.
2378 */
e2273302
ID
2379 if (ret == -ENOSPC)
2380 ret = -ENOMEM;
2381
03ac84f1
CW
2382 return ERR_PTR(ret);
2383}
2384
2385void __i915_gem_object_set_pages(struct drm_i915_gem_object *obj,
2386 struct sg_table *pages)
2387{
1233e2db 2388 lockdep_assert_held(&obj->mm.lock);
03ac84f1
CW
2389
2390 obj->mm.get_page.sg_pos = pages->sgl;
2391 obj->mm.get_page.sg_idx = 0;
2392
2393 obj->mm.pages = pages;
2c3a3f44
CW
2394
2395 if (i915_gem_object_is_tiled(obj) &&
2396 to_i915(obj->base.dev)->quirks & QUIRK_PIN_SWIZZLED_PAGES) {
2397 GEM_BUG_ON(obj->mm.quirked);
2398 __i915_gem_object_pin_pages(obj);
2399 obj->mm.quirked = true;
2400 }
03ac84f1
CW
2401}
2402
2403static int ____i915_gem_object_get_pages(struct drm_i915_gem_object *obj)
2404{
2405 struct sg_table *pages;
2406
2c3a3f44
CW
2407 GEM_BUG_ON(i915_gem_object_has_pinned_pages(obj));
2408
03ac84f1
CW
2409 if (unlikely(obj->mm.madv != I915_MADV_WILLNEED)) {
2410 DRM_DEBUG("Attempting to obtain a purgeable object\n");
2411 return -EFAULT;
2412 }
2413
2414 pages = obj->ops->get_pages(obj);
2415 if (unlikely(IS_ERR(pages)))
2416 return PTR_ERR(pages);
2417
2418 __i915_gem_object_set_pages(obj, pages);
2419 return 0;
673a394b
EA
2420}
2421
37e680a1 2422/* Ensure that the associated pages are gathered from the backing storage
1233e2db 2423 * and pinned into our object. i915_gem_object_pin_pages() may be called
37e680a1 2424 * multiple times before they are released by a single call to
1233e2db 2425 * i915_gem_object_unpin_pages() - once the pages are no longer referenced
37e680a1
CW
2426 * either as a result of memory pressure (reaping pages under the shrinker)
2427 * or as the object is itself released.
2428 */
a4f5ea64 2429int __i915_gem_object_get_pages(struct drm_i915_gem_object *obj)
37e680a1 2430{
03ac84f1 2431 int err;
37e680a1 2432
1233e2db
CW
2433 err = mutex_lock_interruptible(&obj->mm.lock);
2434 if (err)
2435 return err;
4c7d62c6 2436
2c3a3f44
CW
2437 if (unlikely(!obj->mm.pages)) {
2438 err = ____i915_gem_object_get_pages(obj);
2439 if (err)
2440 goto unlock;
37e680a1 2441
2c3a3f44
CW
2442 smp_mb__before_atomic();
2443 }
2444 atomic_inc(&obj->mm.pages_pin_count);
ee286370 2445
1233e2db
CW
2446unlock:
2447 mutex_unlock(&obj->mm.lock);
03ac84f1 2448 return err;
673a394b
EA
2449}
2450
dd6034c6 2451/* The 'mapping' part of i915_gem_object_pin_map() below */
d31d7cb1
CW
2452static void *i915_gem_object_map(const struct drm_i915_gem_object *obj,
2453 enum i915_map_type type)
dd6034c6
DG
2454{
2455 unsigned long n_pages = obj->base.size >> PAGE_SHIFT;
a4f5ea64 2456 struct sg_table *sgt = obj->mm.pages;
85d1225e
DG
2457 struct sgt_iter sgt_iter;
2458 struct page *page;
b338fa47
DG
2459 struct page *stack_pages[32];
2460 struct page **pages = stack_pages;
dd6034c6 2461 unsigned long i = 0;
d31d7cb1 2462 pgprot_t pgprot;
dd6034c6
DG
2463 void *addr;
2464
2465 /* A single page can always be kmapped */
d31d7cb1 2466 if (n_pages == 1 && type == I915_MAP_WB)
dd6034c6
DG
2467 return kmap(sg_page(sgt->sgl));
2468
b338fa47
DG
2469 if (n_pages > ARRAY_SIZE(stack_pages)) {
2470 /* Too big for stack -- allocate temporary array instead */
2471 pages = drm_malloc_gfp(n_pages, sizeof(*pages), GFP_TEMPORARY);
2472 if (!pages)
2473 return NULL;
2474 }
dd6034c6 2475
85d1225e
DG
2476 for_each_sgt_page(page, sgt_iter, sgt)
2477 pages[i++] = page;
dd6034c6
DG
2478
2479 /* Check that we have the expected number of pages */
2480 GEM_BUG_ON(i != n_pages);
2481
d31d7cb1
CW
2482 switch (type) {
2483 case I915_MAP_WB:
2484 pgprot = PAGE_KERNEL;
2485 break;
2486 case I915_MAP_WC:
2487 pgprot = pgprot_writecombine(PAGE_KERNEL_IO);
2488 break;
2489 }
2490 addr = vmap(pages, n_pages, 0, pgprot);
dd6034c6 2491
b338fa47
DG
2492 if (pages != stack_pages)
2493 drm_free_large(pages);
dd6034c6
DG
2494
2495 return addr;
2496}
2497
2498/* get, pin, and map the pages of the object into kernel space */
d31d7cb1
CW
2499void *i915_gem_object_pin_map(struct drm_i915_gem_object *obj,
2500 enum i915_map_type type)
0a798eb9 2501{
d31d7cb1
CW
2502 enum i915_map_type has_type;
2503 bool pinned;
2504 void *ptr;
0a798eb9
CW
2505 int ret;
2506
d31d7cb1 2507 GEM_BUG_ON(!i915_gem_object_has_struct_page(obj));
0a798eb9 2508
1233e2db 2509 ret = mutex_lock_interruptible(&obj->mm.lock);
0a798eb9
CW
2510 if (ret)
2511 return ERR_PTR(ret);
2512
1233e2db
CW
2513 pinned = true;
2514 if (!atomic_inc_not_zero(&obj->mm.pages_pin_count)) {
2c3a3f44
CW
2515 if (unlikely(!obj->mm.pages)) {
2516 ret = ____i915_gem_object_get_pages(obj);
2517 if (ret)
2518 goto err_unlock;
1233e2db 2519
2c3a3f44
CW
2520 smp_mb__before_atomic();
2521 }
2522 atomic_inc(&obj->mm.pages_pin_count);
1233e2db
CW
2523 pinned = false;
2524 }
2525 GEM_BUG_ON(!obj->mm.pages);
0a798eb9 2526
a4f5ea64 2527 ptr = ptr_unpack_bits(obj->mm.mapping, has_type);
d31d7cb1
CW
2528 if (ptr && has_type != type) {
2529 if (pinned) {
2530 ret = -EBUSY;
1233e2db 2531 goto err_unpin;
0a798eb9 2532 }
d31d7cb1
CW
2533
2534 if (is_vmalloc_addr(ptr))
2535 vunmap(ptr);
2536 else
2537 kunmap(kmap_to_page(ptr));
2538
a4f5ea64 2539 ptr = obj->mm.mapping = NULL;
0a798eb9
CW
2540 }
2541
d31d7cb1
CW
2542 if (!ptr) {
2543 ptr = i915_gem_object_map(obj, type);
2544 if (!ptr) {
2545 ret = -ENOMEM;
1233e2db 2546 goto err_unpin;
d31d7cb1
CW
2547 }
2548
a4f5ea64 2549 obj->mm.mapping = ptr_pack_bits(ptr, type);
d31d7cb1
CW
2550 }
2551
1233e2db
CW
2552out_unlock:
2553 mutex_unlock(&obj->mm.lock);
d31d7cb1
CW
2554 return ptr;
2555
1233e2db
CW
2556err_unpin:
2557 atomic_dec(&obj->mm.pages_pin_count);
2558err_unlock:
2559 ptr = ERR_PTR(ret);
2560 goto out_unlock;
0a798eb9
CW
2561}
2562
6095868a 2563static bool ban_context(const struct i915_gem_context *ctx)
be62acb4 2564{
6095868a
CW
2565 return (i915_gem_context_is_bannable(ctx) &&
2566 ctx->ban_score >= CONTEXT_SCORE_BAN_THRESHOLD);
be62acb4
MK
2567}
2568
e5e1fc47 2569static void i915_gem_context_mark_guilty(struct i915_gem_context *ctx)
aa60c664 2570{
bc1d53c6 2571 ctx->guilty_count++;
6095868a
CW
2572 ctx->ban_score += CONTEXT_SCORE_GUILTY;
2573 if (ban_context(ctx))
2574 i915_gem_context_set_banned(ctx);
b083a087
MK
2575
2576 DRM_DEBUG_DRIVER("context %s marked guilty (score %d) banned? %s\n",
bc1d53c6 2577 ctx->name, ctx->ban_score,
6095868a 2578 yesno(i915_gem_context_is_banned(ctx)));
b083a087 2579
6095868a 2580 if (!i915_gem_context_is_banned(ctx) || IS_ERR_OR_NULL(ctx->file_priv))
b083a087
MK
2581 return;
2582
d9e9da64
CW
2583 ctx->file_priv->context_bans++;
2584 DRM_DEBUG_DRIVER("client %s has had %d context banned\n",
2585 ctx->name, ctx->file_priv->context_bans);
e5e1fc47
MK
2586}
2587
2588static void i915_gem_context_mark_innocent(struct i915_gem_context *ctx)
2589{
bc1d53c6 2590 ctx->active_count++;
aa60c664
MK
2591}
2592
8d9fc7fd 2593struct drm_i915_gem_request *
0bc40be8 2594i915_gem_find_active_request(struct intel_engine_cs *engine)
9375e446 2595{
4db080f9
CW
2596 struct drm_i915_gem_request *request;
2597
f69a02c9
CW
2598 /* We are called by the error capture and reset at a random
2599 * point in time. In particular, note that neither is crucially
2600 * ordered with an interrupt. After a hang, the GPU is dead and we
2601 * assume that no more writes can happen (we waited long enough for
2602 * all writes that were in transaction to be flushed) - adding an
2603 * extra delay for a recent interrupt is pointless. Hence, we do
2604 * not need an engine->irq_seqno_barrier() before the seqno reads.
2605 */
73cb9701 2606 list_for_each_entry(request, &engine->timeline->requests, link) {
80b204bc 2607 if (__i915_gem_request_completed(request))
4db080f9 2608 continue;
aa60c664 2609
b6b0fac0 2610 return request;
4db080f9 2611 }
b6b0fac0
MK
2612
2613 return NULL;
2614}
2615
821ed7df
CW
2616static void reset_request(struct drm_i915_gem_request *request)
2617{
2618 void *vaddr = request->ring->vaddr;
2619 u32 head;
2620
2621 /* As this request likely depends on state from the lost
2622 * context, clear out all the user operations leaving the
2623 * breadcrumb at the end (so we get the fence notifications).
2624 */
2625 head = request->head;
2626 if (request->postfix < head) {
2627 memset(vaddr + head, 0, request->ring->size - head);
2628 head = 0;
2629 }
2630 memset(vaddr + head, 0, request->postfix - head);
2631}
2632
b1ed35d9
CW
2633void i915_gem_reset_prepare(struct drm_i915_private *dev_priv)
2634{
2635 i915_gem_revoke_fences(dev_priv);
2636}
2637
821ed7df 2638static void i915_gem_reset_engine(struct intel_engine_cs *engine)
b6b0fac0
MK
2639{
2640 struct drm_i915_gem_request *request;
7ec73b7e 2641 struct i915_gem_context *hung_ctx;
80b204bc 2642 struct intel_timeline *timeline;
00c25e3f 2643 unsigned long flags;
b6b0fac0
MK
2644 bool ring_hung;
2645
821ed7df
CW
2646 if (engine->irq_seqno_barrier)
2647 engine->irq_seqno_barrier(engine);
2648
0bc40be8 2649 request = i915_gem_find_active_request(engine);
821ed7df 2650 if (!request)
b6b0fac0
MK
2651 return;
2652
7ec73b7e
CW
2653 hung_ctx = request->ctx;
2654
3fe3b030
MK
2655 ring_hung = engine->hangcheck.stalled;
2656 if (engine->hangcheck.seqno != intel_engine_get_seqno(engine)) {
2657 DRM_DEBUG_DRIVER("%s pardoned, was guilty? %s\n",
2658 engine->name,
2659 yesno(ring_hung));
77c60701 2660 ring_hung = false;
3fe3b030 2661 }
77c60701 2662
e5e1fc47 2663 if (ring_hung)
7ec73b7e 2664 i915_gem_context_mark_guilty(hung_ctx);
e5e1fc47 2665 else
7ec73b7e 2666 i915_gem_context_mark_innocent(hung_ctx);
e5e1fc47 2667
821ed7df
CW
2668 if (!ring_hung)
2669 return;
2670
2671 DRM_DEBUG_DRIVER("resetting %s to restart from tail of request 0x%x\n",
65e4760e 2672 engine->name, request->global_seqno);
821ed7df
CW
2673
2674 /* Setup the CS to resume from the breadcrumb of the hung request */
2675 engine->reset_hw(engine, request);
2676
7ec73b7e
CW
2677 /* If this context is now banned, skip all of its pending requests. */
2678 if (!i915_gem_context_is_banned(hung_ctx))
2679 return;
2680
821ed7df
CW
2681 /* Users of the default context do not rely on logical state
2682 * preserved between batches. They have to emit full state on
2683 * every batch and so it is safe to execute queued requests following
2684 * the hang.
2685 *
2686 * Other contexts preserve state, now corrupt. We want to skip all
2687 * queued requests that reference the corrupt context.
2688 */
7ec73b7e 2689 if (i915_gem_context_is_default(hung_ctx))
821ed7df
CW
2690 return;
2691
7ec73b7e 2692 timeline = i915_gem_context_lookup_timeline(hung_ctx, engine);
00c25e3f
CW
2693
2694 spin_lock_irqsave(&engine->timeline->lock, flags);
2695 spin_lock(&timeline->lock);
2696
73cb9701 2697 list_for_each_entry_continue(request, &engine->timeline->requests, link)
7ec73b7e 2698 if (request->ctx == hung_ctx)
821ed7df 2699 reset_request(request);
80b204bc 2700
80b204bc
CW
2701 list_for_each_entry(request, &timeline->requests, link)
2702 reset_request(request);
00c25e3f
CW
2703
2704 spin_unlock(&timeline->lock);
2705 spin_unlock_irqrestore(&engine->timeline->lock, flags);
4db080f9 2706}
aa60c664 2707
b1ed35d9 2708void i915_gem_reset_finish(struct drm_i915_private *dev_priv)
4db080f9 2709{
821ed7df 2710 struct intel_engine_cs *engine;
3b3f1650 2711 enum intel_engine_id id;
608c1a52 2712
4c7d62c6
CW
2713 lockdep_assert_held(&dev_priv->drm.struct_mutex);
2714
821ed7df
CW
2715 i915_gem_retire_requests(dev_priv);
2716
3b3f1650 2717 for_each_engine(engine, dev_priv, id)
821ed7df
CW
2718 i915_gem_reset_engine(engine);
2719
4362f4f6 2720 i915_gem_restore_fences(dev_priv);
f2a91d1a
CW
2721
2722 if (dev_priv->gt.awake) {
2723 intel_sanitize_gt_powersave(dev_priv);
2724 intel_enable_gt_powersave(dev_priv);
2725 if (INTEL_GEN(dev_priv) >= 6)
2726 gen6_rps_busy(dev_priv);
2727 }
821ed7df
CW
2728}
2729
2730static void nop_submit_request(struct drm_i915_gem_request *request)
2731{
3dcf93f7
CW
2732 i915_gem_request_submit(request);
2733 intel_engine_init_global_seqno(request->engine, request->global_seqno);
821ed7df
CW
2734}
2735
2736static void i915_gem_cleanup_engine(struct intel_engine_cs *engine)
2737{
20e4933c
CW
2738 /* We need to be sure that no thread is running the old callback as
2739 * we install the nop handler (otherwise we would submit a request
2740 * to hardware that will never complete). In order to prevent this
2741 * race, we wait until the machine is idle before making the swap
2742 * (using stop_machine()).
2743 */
821ed7df 2744 engine->submit_request = nop_submit_request;
70c2a24d 2745
c4b0930b
CW
2746 /* Mark all pending requests as complete so that any concurrent
2747 * (lockless) lookup doesn't try and wait upon the request as we
2748 * reset it.
2749 */
73cb9701 2750 intel_engine_init_global_seqno(engine,
cb399eab 2751 intel_engine_last_submit(engine));
c4b0930b 2752
dcb4c12a
OM
2753 /*
2754 * Clear the execlists queue up before freeing the requests, as those
2755 * are the ones that keep the context and ringbuffer backing objects
2756 * pinned in place.
2757 */
dcb4c12a 2758
7de1691a 2759 if (i915.enable_execlists) {
663f71e7
CW
2760 unsigned long flags;
2761
2762 spin_lock_irqsave(&engine->timeline->lock, flags);
2763
70c2a24d
CW
2764 i915_gem_request_put(engine->execlist_port[0].request);
2765 i915_gem_request_put(engine->execlist_port[1].request);
2766 memset(engine->execlist_port, 0, sizeof(engine->execlist_port));
20311bd3
CW
2767 engine->execlist_queue = RB_ROOT;
2768 engine->execlist_first = NULL;
663f71e7
CW
2769
2770 spin_unlock_irqrestore(&engine->timeline->lock, flags);
dcb4c12a 2771 }
673a394b
EA
2772}
2773
20e4933c 2774static int __i915_gem_set_wedged_BKL(void *data)
673a394b 2775{
20e4933c 2776 struct drm_i915_private *i915 = data;
e2f80391 2777 struct intel_engine_cs *engine;
3b3f1650 2778 enum intel_engine_id id;
673a394b 2779
20e4933c
CW
2780 for_each_engine(engine, i915, id)
2781 i915_gem_cleanup_engine(engine);
2782
2783 return 0;
2784}
2785
2786void i915_gem_set_wedged(struct drm_i915_private *dev_priv)
2787{
821ed7df
CW
2788 lockdep_assert_held(&dev_priv->drm.struct_mutex);
2789 set_bit(I915_WEDGED, &dev_priv->gpu_error.flags);
4db080f9 2790
20e4933c 2791 stop_machine(__i915_gem_set_wedged_BKL, dev_priv, NULL);
dfaae392 2792
20e4933c 2793 i915_gem_context_lost(dev_priv);
821ed7df 2794 i915_gem_retire_requests(dev_priv);
20e4933c
CW
2795
2796 mod_delayed_work(dev_priv->wq, &dev_priv->gt.idle_work, 0);
673a394b
EA
2797}
2798
75ef9da2 2799static void
673a394b
EA
2800i915_gem_retire_work_handler(struct work_struct *work)
2801{
b29c19b6 2802 struct drm_i915_private *dev_priv =
67d97da3 2803 container_of(work, typeof(*dev_priv), gt.retire_work.work);
91c8a326 2804 struct drm_device *dev = &dev_priv->drm;
673a394b 2805
891b48cf 2806 /* Come back later if the device is busy... */
b29c19b6 2807 if (mutex_trylock(&dev->struct_mutex)) {
67d97da3 2808 i915_gem_retire_requests(dev_priv);
b29c19b6 2809 mutex_unlock(&dev->struct_mutex);
673a394b 2810 }
67d97da3
CW
2811
2812 /* Keep the retire handler running until we are finally idle.
2813 * We do not need to do this test under locking as in the worst-case
2814 * we queue the retire worker once too often.
2815 */
c9615613
CW
2816 if (READ_ONCE(dev_priv->gt.awake)) {
2817 i915_queue_hangcheck(dev_priv);
67d97da3
CW
2818 queue_delayed_work(dev_priv->wq,
2819 &dev_priv->gt.retire_work,
bcb45086 2820 round_jiffies_up_relative(HZ));
c9615613 2821 }
b29c19b6 2822}
0a58705b 2823
b29c19b6
CW
2824static void
2825i915_gem_idle_work_handler(struct work_struct *work)
2826{
2827 struct drm_i915_private *dev_priv =
67d97da3 2828 container_of(work, typeof(*dev_priv), gt.idle_work.work);
91c8a326 2829 struct drm_device *dev = &dev_priv->drm;
b4ac5afc 2830 struct intel_engine_cs *engine;
3b3f1650 2831 enum intel_engine_id id;
67d97da3
CW
2832 bool rearm_hangcheck;
2833
2834 if (!READ_ONCE(dev_priv->gt.awake))
2835 return;
2836
0cb5670b
ID
2837 /*
2838 * Wait for last execlists context complete, but bail out in case a
2839 * new request is submitted.
2840 */
2841 wait_for(READ_ONCE(dev_priv->gt.active_requests) ||
2842 intel_execlists_idle(dev_priv), 10);
2843
28176ef4 2844 if (READ_ONCE(dev_priv->gt.active_requests))
67d97da3
CW
2845 return;
2846
2847 rearm_hangcheck =
2848 cancel_delayed_work_sync(&dev_priv->gpu_error.hangcheck_work);
2849
2850 if (!mutex_trylock(&dev->struct_mutex)) {
2851 /* Currently busy, come back later */
2852 mod_delayed_work(dev_priv->wq,
2853 &dev_priv->gt.idle_work,
2854 msecs_to_jiffies(50));
2855 goto out_rearm;
2856 }
2857
93c97dc1
ID
2858 /*
2859 * New request retired after this work handler started, extend active
2860 * period until next instance of the work.
2861 */
2862 if (work_pending(work))
2863 goto out_unlock;
2864
28176ef4 2865 if (dev_priv->gt.active_requests)
67d97da3 2866 goto out_unlock;
b29c19b6 2867
0cb5670b
ID
2868 if (wait_for(intel_execlists_idle(dev_priv), 10))
2869 DRM_ERROR("Timeout waiting for engines to idle\n");
2870
3b3f1650 2871 for_each_engine(engine, dev_priv, id)
67d97da3 2872 i915_gem_batch_pool_fini(&engine->batch_pool);
35c94185 2873
67d97da3
CW
2874 GEM_BUG_ON(!dev_priv->gt.awake);
2875 dev_priv->gt.awake = false;
2876 rearm_hangcheck = false;
30ecad77 2877
67d97da3
CW
2878 if (INTEL_GEN(dev_priv) >= 6)
2879 gen6_rps_idle(dev_priv);
2880 intel_runtime_pm_put(dev_priv);
2881out_unlock:
2882 mutex_unlock(&dev->struct_mutex);
b29c19b6 2883
67d97da3
CW
2884out_rearm:
2885 if (rearm_hangcheck) {
2886 GEM_BUG_ON(!dev_priv->gt.awake);
2887 i915_queue_hangcheck(dev_priv);
35c94185 2888 }
673a394b
EA
2889}
2890
b1f788c6
CW
2891void i915_gem_close_object(struct drm_gem_object *gem, struct drm_file *file)
2892{
2893 struct drm_i915_gem_object *obj = to_intel_bo(gem);
2894 struct drm_i915_file_private *fpriv = file->driver_priv;
2895 struct i915_vma *vma, *vn;
2896
2897 mutex_lock(&obj->base.dev->struct_mutex);
2898 list_for_each_entry_safe(vma, vn, &obj->vma_list, obj_link)
2899 if (vma->vm->file == fpriv)
2900 i915_vma_close(vma);
f8a7fde4
CW
2901
2902 if (i915_gem_object_is_active(obj) &&
2903 !i915_gem_object_has_active_reference(obj)) {
2904 i915_gem_object_set_active_reference(obj);
2905 i915_gem_object_get(obj);
2906 }
b1f788c6
CW
2907 mutex_unlock(&obj->base.dev->struct_mutex);
2908}
2909
e95433c7
CW
2910static unsigned long to_wait_timeout(s64 timeout_ns)
2911{
2912 if (timeout_ns < 0)
2913 return MAX_SCHEDULE_TIMEOUT;
2914
2915 if (timeout_ns == 0)
2916 return 0;
2917
2918 return nsecs_to_jiffies_timeout(timeout_ns);
2919}
2920
23ba4fd0
BW
2921/**
2922 * i915_gem_wait_ioctl - implements DRM_IOCTL_I915_GEM_WAIT
14bb2c11
TU
2923 * @dev: drm device pointer
2924 * @data: ioctl data blob
2925 * @file: drm file pointer
23ba4fd0
BW
2926 *
2927 * Returns 0 if successful, else an error is returned with the remaining time in
2928 * the timeout parameter.
2929 * -ETIME: object is still busy after timeout
2930 * -ERESTARTSYS: signal interrupted the wait
2931 * -ENONENT: object doesn't exist
2932 * Also possible, but rare:
2933 * -EAGAIN: GPU wedged
2934 * -ENOMEM: damn
2935 * -ENODEV: Internal IRQ fail
2936 * -E?: The add request failed
2937 *
2938 * The wait ioctl with a timeout of 0 reimplements the busy ioctl. With any
2939 * non-zero timeout parameter the wait ioctl will wait for the given number of
2940 * nanoseconds on an object becoming unbusy. Since the wait itself does so
2941 * without holding struct_mutex the object may become re-busied before this
2942 * function completes. A similar but shorter * race condition exists in the busy
2943 * ioctl
2944 */
2945int
2946i915_gem_wait_ioctl(struct drm_device *dev, void *data, struct drm_file *file)
2947{
2948 struct drm_i915_gem_wait *args = data;
2949 struct drm_i915_gem_object *obj;
e95433c7
CW
2950 ktime_t start;
2951 long ret;
23ba4fd0 2952
11b5d511
DV
2953 if (args->flags != 0)
2954 return -EINVAL;
2955
03ac0642 2956 obj = i915_gem_object_lookup(file, args->bo_handle);
033d549b 2957 if (!obj)
23ba4fd0 2958 return -ENOENT;
23ba4fd0 2959
e95433c7
CW
2960 start = ktime_get();
2961
2962 ret = i915_gem_object_wait(obj,
2963 I915_WAIT_INTERRUPTIBLE | I915_WAIT_ALL,
2964 to_wait_timeout(args->timeout_ns),
2965 to_rps_client(file));
2966
2967 if (args->timeout_ns > 0) {
2968 args->timeout_ns -= ktime_to_ns(ktime_sub(ktime_get(), start));
2969 if (args->timeout_ns < 0)
2970 args->timeout_ns = 0;
b4716185
CW
2971 }
2972
f0cd5182 2973 i915_gem_object_put(obj);
ff865885 2974 return ret;
23ba4fd0
BW
2975}
2976
73cb9701 2977static int wait_for_timeline(struct i915_gem_timeline *tl, unsigned int flags)
4df2faf4 2978{
73cb9701 2979 int ret, i;
4df2faf4 2980
73cb9701
CW
2981 for (i = 0; i < ARRAY_SIZE(tl->engine); i++) {
2982 ret = i915_gem_active_wait(&tl->engine[i].last_request, flags);
2983 if (ret)
2984 return ret;
2985 }
62e63007 2986
73cb9701
CW
2987 return 0;
2988}
2989
2990int i915_gem_wait_for_idle(struct drm_i915_private *i915, unsigned int flags)
2991{
73cb9701
CW
2992 int ret;
2993
9caa34aa
CW
2994 if (flags & I915_WAIT_LOCKED) {
2995 struct i915_gem_timeline *tl;
2996
2997 lockdep_assert_held(&i915->drm.struct_mutex);
2998
2999 list_for_each_entry(tl, &i915->gt.timelines, link) {
3000 ret = wait_for_timeline(tl, flags);
3001 if (ret)
3002 return ret;
3003 }
3004 } else {
3005 ret = wait_for_timeline(&i915->gt.global_timeline, flags);
1ec14ad3
CW
3006 if (ret)
3007 return ret;
3008 }
4df2faf4 3009
8a1a49f9 3010 return 0;
4df2faf4
DV
3011}
3012
d0da48cf
CW
3013void i915_gem_clflush_object(struct drm_i915_gem_object *obj,
3014 bool force)
673a394b 3015{
673a394b
EA
3016 /* If we don't have a page list set up, then we're not pinned
3017 * to GPU, and we can ignore the cache flush because it'll happen
3018 * again at bind time.
3019 */
a4f5ea64 3020 if (!obj->mm.pages)
d0da48cf 3021 return;
673a394b 3022
769ce464
ID
3023 /*
3024 * Stolen memory is always coherent with the GPU as it is explicitly
3025 * marked as wc by the system, or the system is cache-coherent.
3026 */
6a2c4232 3027 if (obj->stolen || obj->phys_handle)
d0da48cf 3028 return;
769ce464 3029
9c23f7fc
CW
3030 /* If the GPU is snooping the contents of the CPU cache,
3031 * we do not need to manually clear the CPU cache lines. However,
3032 * the caches are only snooped when the render cache is
3033 * flushed/invalidated. As we always have to emit invalidations
3034 * and flushes when moving into and out of the RENDER domain, correct
3035 * snooping behaviour occurs naturally as the result of our domain
3036 * tracking.
3037 */
0f71979a
CW
3038 if (!force && cpu_cache_is_coherent(obj->base.dev, obj->cache_level)) {
3039 obj->cache_dirty = true;
d0da48cf 3040 return;
0f71979a 3041 }
9c23f7fc 3042
1c5d22f7 3043 trace_i915_gem_object_clflush(obj);
a4f5ea64 3044 drm_clflush_sg(obj->mm.pages);
0f71979a 3045 obj->cache_dirty = false;
e47c68e9
EA
3046}
3047
3048/** Flushes the GTT write domain for the object if it's dirty. */
3049static void
05394f39 3050i915_gem_object_flush_gtt_write_domain(struct drm_i915_gem_object *obj)
e47c68e9 3051{
3b5724d7 3052 struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
1c5d22f7 3053
05394f39 3054 if (obj->base.write_domain != I915_GEM_DOMAIN_GTT)
e47c68e9
EA
3055 return;
3056
63256ec5 3057 /* No actual flushing is required for the GTT write domain. Writes
3b5724d7 3058 * to it "immediately" go to main memory as far as we know, so there's
e47c68e9 3059 * no chipset flush. It also doesn't land in render cache.
63256ec5
CW
3060 *
3061 * However, we do have to enforce the order so that all writes through
3062 * the GTT land before any writes to the device, such as updates to
3063 * the GATT itself.
3b5724d7
CW
3064 *
3065 * We also have to wait a bit for the writes to land from the GTT.
3066 * An uncached read (i.e. mmio) seems to be ideal for the round-trip
3067 * timing. This issue has only been observed when switching quickly
3068 * between GTT writes and CPU reads from inside the kernel on recent hw,
3069 * and it appears to only affect discrete GTT blocks (i.e. on LLC
3070 * system agents we cannot reproduce this behaviour).
e47c68e9 3071 */
63256ec5 3072 wmb();
3b5724d7 3073 if (INTEL_GEN(dev_priv) >= 6 && !HAS_LLC(dev_priv))
3b3f1650 3074 POSTING_READ(RING_ACTHD(dev_priv->engine[RCS]->mmio_base));
63256ec5 3075
d243ad82 3076 intel_fb_obj_flush(obj, false, write_origin(obj, I915_GEM_DOMAIN_GTT));
f99d7069 3077
b0dc465f 3078 obj->base.write_domain = 0;
1c5d22f7 3079 trace_i915_gem_object_change_domain(obj,
05394f39 3080 obj->base.read_domains,
b0dc465f 3081 I915_GEM_DOMAIN_GTT);
e47c68e9
EA
3082}
3083
3084/** Flushes the CPU write domain for the object if it's dirty. */
3085static void
e62b59e4 3086i915_gem_object_flush_cpu_write_domain(struct drm_i915_gem_object *obj)
e47c68e9 3087{
05394f39 3088 if (obj->base.write_domain != I915_GEM_DOMAIN_CPU)
e47c68e9
EA
3089 return;
3090
d0da48cf 3091 i915_gem_clflush_object(obj, obj->pin_display);
de152b62 3092 intel_fb_obj_flush(obj, false, ORIGIN_CPU);
f99d7069 3093
b0dc465f 3094 obj->base.write_domain = 0;
1c5d22f7 3095 trace_i915_gem_object_change_domain(obj,
05394f39 3096 obj->base.read_domains,
b0dc465f 3097 I915_GEM_DOMAIN_CPU);
e47c68e9
EA
3098}
3099
2ef7eeaa
EA
3100/**
3101 * Moves a single object to the GTT read, and possibly write domain.
14bb2c11
TU
3102 * @obj: object to act on
3103 * @write: ask for write access or read only
2ef7eeaa
EA
3104 *
3105 * This function returns when the move is complete, including waiting on
3106 * flushes to occur.
3107 */
79e53945 3108int
2021746e 3109i915_gem_object_set_to_gtt_domain(struct drm_i915_gem_object *obj, bool write)
2ef7eeaa 3110{
1c5d22f7 3111 uint32_t old_write_domain, old_read_domains;
e47c68e9 3112 int ret;
2ef7eeaa 3113
e95433c7 3114 lockdep_assert_held(&obj->base.dev->struct_mutex);
4c7d62c6 3115
e95433c7
CW
3116 ret = i915_gem_object_wait(obj,
3117 I915_WAIT_INTERRUPTIBLE |
3118 I915_WAIT_LOCKED |
3119 (write ? I915_WAIT_ALL : 0),
3120 MAX_SCHEDULE_TIMEOUT,
3121 NULL);
88241785
CW
3122 if (ret)
3123 return ret;
3124
c13d87ea
CW
3125 if (obj->base.write_domain == I915_GEM_DOMAIN_GTT)
3126 return 0;
3127
43566ded
CW
3128 /* Flush and acquire obj->pages so that we are coherent through
3129 * direct access in memory with previous cached writes through
3130 * shmemfs and that our cache domain tracking remains valid.
3131 * For example, if the obj->filp was moved to swap without us
3132 * being notified and releasing the pages, we would mistakenly
3133 * continue to assume that the obj remained out of the CPU cached
3134 * domain.
3135 */
a4f5ea64 3136 ret = i915_gem_object_pin_pages(obj);
43566ded
CW
3137 if (ret)
3138 return ret;
3139
e62b59e4 3140 i915_gem_object_flush_cpu_write_domain(obj);
1c5d22f7 3141
d0a57789
CW
3142 /* Serialise direct access to this object with the barriers for
3143 * coherent writes from the GPU, by effectively invalidating the
3144 * GTT domain upon first access.
3145 */
3146 if ((obj->base.read_domains & I915_GEM_DOMAIN_GTT) == 0)
3147 mb();
3148
05394f39
CW
3149 old_write_domain = obj->base.write_domain;
3150 old_read_domains = obj->base.read_domains;
1c5d22f7 3151
e47c68e9
EA
3152 /* It should now be out of any other write domains, and we can update
3153 * the domain values for our changes.
3154 */
40e62d5d 3155 GEM_BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_GTT) != 0);
05394f39 3156 obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
e47c68e9 3157 if (write) {
05394f39
CW
3158 obj->base.read_domains = I915_GEM_DOMAIN_GTT;
3159 obj->base.write_domain = I915_GEM_DOMAIN_GTT;
a4f5ea64 3160 obj->mm.dirty = true;
2ef7eeaa
EA
3161 }
3162
1c5d22f7
CW
3163 trace_i915_gem_object_change_domain(obj,
3164 old_read_domains,
3165 old_write_domain);
3166
a4f5ea64 3167 i915_gem_object_unpin_pages(obj);
e47c68e9
EA
3168 return 0;
3169}
3170
ef55f92a
CW
3171/**
3172 * Changes the cache-level of an object across all VMA.
14bb2c11
TU
3173 * @obj: object to act on
3174 * @cache_level: new cache level to set for the object
ef55f92a
CW
3175 *
3176 * After this function returns, the object will be in the new cache-level
3177 * across all GTT and the contents of the backing storage will be coherent,
3178 * with respect to the new cache-level. In order to keep the backing storage
3179 * coherent for all users, we only allow a single cache level to be set
3180 * globally on the object and prevent it from being changed whilst the
3181 * hardware is reading from the object. That is if the object is currently
3182 * on the scanout it will be set to uncached (or equivalent display
3183 * cache coherency) and all non-MOCS GPU access will also be uncached so
3184 * that all direct access to the scanout remains coherent.
3185 */
e4ffd173
CW
3186int i915_gem_object_set_cache_level(struct drm_i915_gem_object *obj,
3187 enum i915_cache_level cache_level)
3188{
aa653a68 3189 struct i915_vma *vma;
a6a7cc4b 3190 int ret;
e4ffd173 3191
4c7d62c6
CW
3192 lockdep_assert_held(&obj->base.dev->struct_mutex);
3193
e4ffd173 3194 if (obj->cache_level == cache_level)
a6a7cc4b 3195 return 0;
e4ffd173 3196
ef55f92a
CW
3197 /* Inspect the list of currently bound VMA and unbind any that would
3198 * be invalid given the new cache-level. This is principally to
3199 * catch the issue of the CS prefetch crossing page boundaries and
3200 * reading an invalid PTE on older architectures.
3201 */
aa653a68
CW
3202restart:
3203 list_for_each_entry(vma, &obj->vma_list, obj_link) {
ef55f92a
CW
3204 if (!drm_mm_node_allocated(&vma->node))
3205 continue;
3206
20dfbde4 3207 if (i915_vma_is_pinned(vma)) {
ef55f92a
CW
3208 DRM_DEBUG("can not change the cache level of pinned objects\n");
3209 return -EBUSY;
3210 }
3211
aa653a68
CW
3212 if (i915_gem_valid_gtt_space(vma, cache_level))
3213 continue;
3214
3215 ret = i915_vma_unbind(vma);
3216 if (ret)
3217 return ret;
3218
3219 /* As unbinding may affect other elements in the
3220 * obj->vma_list (due to side-effects from retiring
3221 * an active vma), play safe and restart the iterator.
3222 */
3223 goto restart;
42d6ab48
CW
3224 }
3225
ef55f92a
CW
3226 /* We can reuse the existing drm_mm nodes but need to change the
3227 * cache-level on the PTE. We could simply unbind them all and
3228 * rebind with the correct cache-level on next use. However since
3229 * we already have a valid slot, dma mapping, pages etc, we may as
3230 * rewrite the PTE in the belief that doing so tramples upon less
3231 * state and so involves less work.
3232 */
15717de2 3233 if (obj->bind_count) {
ef55f92a
CW
3234 /* Before we change the PTE, the GPU must not be accessing it.
3235 * If we wait upon the object, we know that all the bound
3236 * VMA are no longer active.
3237 */
e95433c7
CW
3238 ret = i915_gem_object_wait(obj,
3239 I915_WAIT_INTERRUPTIBLE |
3240 I915_WAIT_LOCKED |
3241 I915_WAIT_ALL,
3242 MAX_SCHEDULE_TIMEOUT,
3243 NULL);
e4ffd173
CW
3244 if (ret)
3245 return ret;
3246
0031fb96
TU
3247 if (!HAS_LLC(to_i915(obj->base.dev)) &&
3248 cache_level != I915_CACHE_NONE) {
ef55f92a
CW
3249 /* Access to snoopable pages through the GTT is
3250 * incoherent and on some machines causes a hard
3251 * lockup. Relinquish the CPU mmaping to force
3252 * userspace to refault in the pages and we can
3253 * then double check if the GTT mapping is still
3254 * valid for that pointer access.
3255 */
3256 i915_gem_release_mmap(obj);
3257
3258 /* As we no longer need a fence for GTT access,
3259 * we can relinquish it now (and so prevent having
3260 * to steal a fence from someone else on the next
3261 * fence request). Note GPU activity would have
3262 * dropped the fence as all snoopable access is
3263 * supposed to be linear.
3264 */
49ef5294
CW
3265 list_for_each_entry(vma, &obj->vma_list, obj_link) {
3266 ret = i915_vma_put_fence(vma);
3267 if (ret)
3268 return ret;
3269 }
ef55f92a
CW
3270 } else {
3271 /* We either have incoherent backing store and
3272 * so no GTT access or the architecture is fully
3273 * coherent. In such cases, existing GTT mmaps
3274 * ignore the cache bit in the PTE and we can
3275 * rewrite it without confusing the GPU or having
3276 * to force userspace to fault back in its mmaps.
3277 */
e4ffd173
CW
3278 }
3279
1c7f4bca 3280 list_for_each_entry(vma, &obj->vma_list, obj_link) {
ef55f92a
CW
3281 if (!drm_mm_node_allocated(&vma->node))
3282 continue;
3283
3284 ret = i915_vma_bind(vma, cache_level, PIN_UPDATE);
3285 if (ret)
3286 return ret;
3287 }
e4ffd173
CW
3288 }
3289
a6a7cc4b
CW
3290 if (obj->base.write_domain == I915_GEM_DOMAIN_CPU &&
3291 cpu_cache_is_coherent(obj->base.dev, obj->cache_level))
3292 obj->cache_dirty = true;
3293
1c7f4bca 3294 list_for_each_entry(vma, &obj->vma_list, obj_link)
2c22569b
CW
3295 vma->node.color = cache_level;
3296 obj->cache_level = cache_level;
3297
e4ffd173
CW
3298 return 0;
3299}
3300
199adf40
BW
3301int i915_gem_get_caching_ioctl(struct drm_device *dev, void *data,
3302 struct drm_file *file)
e6994aee 3303{
199adf40 3304 struct drm_i915_gem_caching *args = data;
e6994aee 3305 struct drm_i915_gem_object *obj;
fbbd37b3 3306 int err = 0;
e6994aee 3307
fbbd37b3
CW
3308 rcu_read_lock();
3309 obj = i915_gem_object_lookup_rcu(file, args->handle);
3310 if (!obj) {
3311 err = -ENOENT;
3312 goto out;
3313 }
e6994aee 3314
651d794f
CW
3315 switch (obj->cache_level) {
3316 case I915_CACHE_LLC:
3317 case I915_CACHE_L3_LLC:
3318 args->caching = I915_CACHING_CACHED;
3319 break;
3320
4257d3ba
CW
3321 case I915_CACHE_WT:
3322 args->caching = I915_CACHING_DISPLAY;
3323 break;
3324
651d794f
CW
3325 default:
3326 args->caching = I915_CACHING_NONE;
3327 break;
3328 }
fbbd37b3
CW
3329out:
3330 rcu_read_unlock();
3331 return err;
e6994aee
CW
3332}
3333
199adf40
BW
3334int i915_gem_set_caching_ioctl(struct drm_device *dev, void *data,
3335 struct drm_file *file)
e6994aee 3336{
9c870d03 3337 struct drm_i915_private *i915 = to_i915(dev);
199adf40 3338 struct drm_i915_gem_caching *args = data;
e6994aee
CW
3339 struct drm_i915_gem_object *obj;
3340 enum i915_cache_level level;
3341 int ret;
3342
199adf40
BW
3343 switch (args->caching) {
3344 case I915_CACHING_NONE:
e6994aee
CW
3345 level = I915_CACHE_NONE;
3346 break;
199adf40 3347 case I915_CACHING_CACHED:
e5756c10
ID
3348 /*
3349 * Due to a HW issue on BXT A stepping, GPU stores via a
3350 * snooped mapping may leave stale data in a corresponding CPU
3351 * cacheline, whereas normally such cachelines would get
3352 * invalidated.
3353 */
9c870d03 3354 if (!HAS_LLC(i915) && !HAS_SNOOP(i915))
e5756c10
ID
3355 return -ENODEV;
3356
e6994aee
CW
3357 level = I915_CACHE_LLC;
3358 break;
4257d3ba 3359 case I915_CACHING_DISPLAY:
9c870d03 3360 level = HAS_WT(i915) ? I915_CACHE_WT : I915_CACHE_NONE;
4257d3ba 3361 break;
e6994aee
CW
3362 default:
3363 return -EINVAL;
3364 }
3365
3bc2913e
BW
3366 ret = i915_mutex_lock_interruptible(dev);
3367 if (ret)
9c870d03 3368 return ret;
3bc2913e 3369
03ac0642
CW
3370 obj = i915_gem_object_lookup(file, args->handle);
3371 if (!obj) {
e6994aee
CW
3372 ret = -ENOENT;
3373 goto unlock;
3374 }
3375
3376 ret = i915_gem_object_set_cache_level(obj, level);
f8c417cd 3377 i915_gem_object_put(obj);
e6994aee
CW
3378unlock:
3379 mutex_unlock(&dev->struct_mutex);
3380 return ret;
3381}
3382
b9241ea3 3383/*
2da3b9b9
CW
3384 * Prepare buffer for display plane (scanout, cursors, etc).
3385 * Can be called from an uninterruptible phase (modesetting) and allows
3386 * any flushes to be pipelined (for pageflips).
b9241ea3 3387 */
058d88c4 3388struct i915_vma *
2da3b9b9
CW
3389i915_gem_object_pin_to_display_plane(struct drm_i915_gem_object *obj,
3390 u32 alignment,
e6617330 3391 const struct i915_ggtt_view *view)
b9241ea3 3392{
058d88c4 3393 struct i915_vma *vma;
2da3b9b9 3394 u32 old_read_domains, old_write_domain;
b9241ea3
ZW
3395 int ret;
3396
4c7d62c6
CW
3397 lockdep_assert_held(&obj->base.dev->struct_mutex);
3398
cc98b413
CW
3399 /* Mark the pin_display early so that we account for the
3400 * display coherency whilst setting up the cache domains.
3401 */
8a0c39b1 3402 obj->pin_display++;
cc98b413 3403
a7ef0640
EA
3404 /* The display engine is not coherent with the LLC cache on gen6. As
3405 * a result, we make sure that the pinning that is about to occur is
3406 * done with uncached PTEs. This is lowest common denominator for all
3407 * chipsets.
3408 *
3409 * However for gen6+, we could do better by using the GFDT bit instead
3410 * of uncaching, which would allow us to flush all the LLC-cached data
3411 * with that bit in the PTE to main memory with just one PIPE_CONTROL.
3412 */
651d794f 3413 ret = i915_gem_object_set_cache_level(obj,
8652744b
TU
3414 HAS_WT(to_i915(obj->base.dev)) ?
3415 I915_CACHE_WT : I915_CACHE_NONE);
058d88c4
CW
3416 if (ret) {
3417 vma = ERR_PTR(ret);
cc98b413 3418 goto err_unpin_display;
058d88c4 3419 }
a7ef0640 3420
2da3b9b9
CW
3421 /* As the user may map the buffer once pinned in the display plane
3422 * (e.g. libkms for the bootup splash), we have to ensure that we
2efb813d
CW
3423 * always use map_and_fenceable for all scanout buffers. However,
3424 * it may simply be too big to fit into mappable, in which case
3425 * put it anyway and hope that userspace can cope (but always first
3426 * try to preserve the existing ABI).
2da3b9b9 3427 */
2efb813d
CW
3428 vma = ERR_PTR(-ENOSPC);
3429 if (view->type == I915_GGTT_VIEW_NORMAL)
3430 vma = i915_gem_object_ggtt_pin(obj, view, 0, alignment,
3431 PIN_MAPPABLE | PIN_NONBLOCK);
767a222e
CW
3432 if (IS_ERR(vma)) {
3433 struct drm_i915_private *i915 = to_i915(obj->base.dev);
3434 unsigned int flags;
3435
3436 /* Valleyview is definitely limited to scanning out the first
3437 * 512MiB. Lets presume this behaviour was inherited from the
3438 * g4x display engine and that all earlier gen are similarly
3439 * limited. Testing suggests that it is a little more
3440 * complicated than this. For example, Cherryview appears quite
3441 * happy to scanout from anywhere within its global aperture.
3442 */
3443 flags = 0;
3444 if (HAS_GMCH_DISPLAY(i915))
3445 flags = PIN_MAPPABLE;
3446 vma = i915_gem_object_ggtt_pin(obj, view, 0, alignment, flags);
3447 }
058d88c4 3448 if (IS_ERR(vma))
cc98b413 3449 goto err_unpin_display;
2da3b9b9 3450
d8923dcf
CW
3451 vma->display_alignment = max_t(u64, vma->display_alignment, alignment);
3452
a6a7cc4b
CW
3453 /* Treat this as an end-of-frame, like intel_user_framebuffer_dirty() */
3454 if (obj->cache_dirty) {
3455 i915_gem_clflush_object(obj, true);
3456 intel_fb_obj_flush(obj, false, ORIGIN_DIRTYFB);
3457 }
b118c1e3 3458
2da3b9b9 3459 old_write_domain = obj->base.write_domain;
05394f39 3460 old_read_domains = obj->base.read_domains;
2da3b9b9
CW
3461
3462 /* It should now be out of any other write domains, and we can update
3463 * the domain values for our changes.
3464 */
e5f1d962 3465 obj->base.write_domain = 0;
05394f39 3466 obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
b9241ea3
ZW
3467
3468 trace_i915_gem_object_change_domain(obj,
3469 old_read_domains,
2da3b9b9 3470 old_write_domain);
b9241ea3 3471
058d88c4 3472 return vma;
cc98b413
CW
3473
3474err_unpin_display:
8a0c39b1 3475 obj->pin_display--;
058d88c4 3476 return vma;
cc98b413
CW
3477}
3478
3479void
058d88c4 3480i915_gem_object_unpin_from_display_plane(struct i915_vma *vma)
cc98b413 3481{
49d73912 3482 lockdep_assert_held(&vma->vm->i915->drm.struct_mutex);
4c7d62c6 3483
058d88c4 3484 if (WARN_ON(vma->obj->pin_display == 0))
8a0c39b1
TU
3485 return;
3486
d8923dcf 3487 if (--vma->obj->pin_display == 0)
944397f0 3488 vma->display_alignment = 4096;
e6617330 3489
383d5823
CW
3490 /* Bump the LRU to try and avoid premature eviction whilst flipping */
3491 if (!i915_vma_is_active(vma))
3492 list_move_tail(&vma->vm_link, &vma->vm->inactive_list);
3493
058d88c4 3494 i915_vma_unpin(vma);
b9241ea3
ZW
3495}
3496
e47c68e9
EA
3497/**
3498 * Moves a single object to the CPU read, and possibly write domain.
14bb2c11
TU
3499 * @obj: object to act on
3500 * @write: requesting write or read-only access
e47c68e9
EA
3501 *
3502 * This function returns when the move is complete, including waiting on
3503 * flushes to occur.
3504 */
dabdfe02 3505int
919926ae 3506i915_gem_object_set_to_cpu_domain(struct drm_i915_gem_object *obj, bool write)
e47c68e9 3507{
1c5d22f7 3508 uint32_t old_write_domain, old_read_domains;
e47c68e9
EA
3509 int ret;
3510
e95433c7 3511 lockdep_assert_held(&obj->base.dev->struct_mutex);
4c7d62c6 3512
e95433c7
CW
3513 ret = i915_gem_object_wait(obj,
3514 I915_WAIT_INTERRUPTIBLE |
3515 I915_WAIT_LOCKED |
3516 (write ? I915_WAIT_ALL : 0),
3517 MAX_SCHEDULE_TIMEOUT,
3518 NULL);
88241785
CW
3519 if (ret)
3520 return ret;
3521
c13d87ea
CW
3522 if (obj->base.write_domain == I915_GEM_DOMAIN_CPU)
3523 return 0;
3524
e47c68e9 3525 i915_gem_object_flush_gtt_write_domain(obj);
2ef7eeaa 3526
05394f39
CW
3527 old_write_domain = obj->base.write_domain;
3528 old_read_domains = obj->base.read_domains;
1c5d22f7 3529
e47c68e9 3530 /* Flush the CPU cache if it's still invalid. */
05394f39 3531 if ((obj->base.read_domains & I915_GEM_DOMAIN_CPU) == 0) {
2c22569b 3532 i915_gem_clflush_object(obj, false);
2ef7eeaa 3533
05394f39 3534 obj->base.read_domains |= I915_GEM_DOMAIN_CPU;
2ef7eeaa
EA
3535 }
3536
3537 /* It should now be out of any other write domains, and we can update
3538 * the domain values for our changes.
3539 */
40e62d5d 3540 GEM_BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_CPU) != 0);
e47c68e9
EA
3541
3542 /* If we're writing through the CPU, then the GPU read domains will
3543 * need to be invalidated at next use.
3544 */
3545 if (write) {
05394f39
CW
3546 obj->base.read_domains = I915_GEM_DOMAIN_CPU;
3547 obj->base.write_domain = I915_GEM_DOMAIN_CPU;
e47c68e9 3548 }
2ef7eeaa 3549
1c5d22f7
CW
3550 trace_i915_gem_object_change_domain(obj,
3551 old_read_domains,
3552 old_write_domain);
3553
2ef7eeaa
EA
3554 return 0;
3555}
3556
673a394b
EA
3557/* Throttle our rendering by waiting until the ring has completed our requests
3558 * emitted over 20 msec ago.
3559 *
b962442e
EA
3560 * Note that if we were to use the current jiffies each time around the loop,
3561 * we wouldn't escape the function with any frames outstanding if the time to
3562 * render a frame was over 20ms.
3563 *
673a394b
EA
3564 * This should get us reasonable parallelism between CPU and GPU but also
3565 * relatively low latency when blocking on a particular request to finish.
3566 */
40a5f0de 3567static int
f787a5f5 3568i915_gem_ring_throttle(struct drm_device *dev, struct drm_file *file)
40a5f0de 3569{
fac5e23e 3570 struct drm_i915_private *dev_priv = to_i915(dev);
f787a5f5 3571 struct drm_i915_file_private *file_priv = file->driver_priv;
d0bc54f2 3572 unsigned long recent_enough = jiffies - DRM_I915_THROTTLE_JIFFIES;
54fb2411 3573 struct drm_i915_gem_request *request, *target = NULL;
e95433c7 3574 long ret;
93533c29 3575
f4457ae7
CW
3576 /* ABI: return -EIO if already wedged */
3577 if (i915_terminally_wedged(&dev_priv->gpu_error))
3578 return -EIO;
e110e8d6 3579
1c25595f 3580 spin_lock(&file_priv->mm.lock);
f787a5f5 3581 list_for_each_entry(request, &file_priv->mm.request_list, client_list) {
b962442e
EA
3582 if (time_after_eq(request->emitted_jiffies, recent_enough))
3583 break;
40a5f0de 3584
fcfa423c
JH
3585 /*
3586 * Note that the request might not have been submitted yet.
3587 * In which case emitted_jiffies will be zero.
3588 */
3589 if (!request->emitted_jiffies)
3590 continue;
3591
54fb2411 3592 target = request;
b962442e 3593 }
ff865885 3594 if (target)
e8a261ea 3595 i915_gem_request_get(target);
1c25595f 3596 spin_unlock(&file_priv->mm.lock);
40a5f0de 3597
54fb2411 3598 if (target == NULL)
f787a5f5 3599 return 0;
2bc43b5c 3600
e95433c7
CW
3601 ret = i915_wait_request(target,
3602 I915_WAIT_INTERRUPTIBLE,
3603 MAX_SCHEDULE_TIMEOUT);
e8a261ea 3604 i915_gem_request_put(target);
ff865885 3605
e95433c7 3606 return ret < 0 ? ret : 0;
40a5f0de
EA
3607}
3608
058d88c4 3609struct i915_vma *
ec7adb6e
JL
3610i915_gem_object_ggtt_pin(struct drm_i915_gem_object *obj,
3611 const struct i915_ggtt_view *view,
91b2db6f 3612 u64 size,
2ffffd0f
CW
3613 u64 alignment,
3614 u64 flags)
ec7adb6e 3615{
ad16d2ed
CW
3616 struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
3617 struct i915_address_space *vm = &dev_priv->ggtt.base;
59bfa124
CW
3618 struct i915_vma *vma;
3619 int ret;
72e96d64 3620
4c7d62c6
CW
3621 lockdep_assert_held(&obj->base.dev->struct_mutex);
3622
058d88c4 3623 vma = i915_gem_obj_lookup_or_create_vma(obj, vm, view);
59bfa124 3624 if (IS_ERR(vma))
058d88c4 3625 return vma;
59bfa124
CW
3626
3627 if (i915_vma_misplaced(vma, size, alignment, flags)) {
3628 if (flags & PIN_NONBLOCK &&
3629 (i915_vma_is_pinned(vma) || i915_vma_is_active(vma)))
058d88c4 3630 return ERR_PTR(-ENOSPC);
59bfa124 3631
ad16d2ed 3632 if (flags & PIN_MAPPABLE) {
ad16d2ed
CW
3633 /* If the required space is larger than the available
3634 * aperture, we will not able to find a slot for the
3635 * object and unbinding the object now will be in
3636 * vain. Worse, doing so may cause us to ping-pong
3637 * the object in and out of the Global GTT and
3638 * waste a lot of cycles under the mutex.
3639 */
944397f0 3640 if (vma->fence_size > dev_priv->ggtt.mappable_end)
ad16d2ed
CW
3641 return ERR_PTR(-E2BIG);
3642
3643 /* If NONBLOCK is set the caller is optimistically
3644 * trying to cache the full object within the mappable
3645 * aperture, and *must* have a fallback in place for
3646 * situations where we cannot bind the object. We
3647 * can be a little more lax here and use the fallback
3648 * more often to avoid costly migrations of ourselves
3649 * and other objects within the aperture.
3650 *
3651 * Half-the-aperture is used as a simple heuristic.
3652 * More interesting would to do search for a free
3653 * block prior to making the commitment to unbind.
3654 * That caters for the self-harm case, and with a
3655 * little more heuristics (e.g. NOFAULT, NOEVICT)
3656 * we could try to minimise harm to others.
3657 */
3658 if (flags & PIN_NONBLOCK &&
944397f0 3659 vma->fence_size > dev_priv->ggtt.mappable_end / 2)
ad16d2ed
CW
3660 return ERR_PTR(-ENOSPC);
3661 }
3662
59bfa124
CW
3663 WARN(i915_vma_is_pinned(vma),
3664 "bo is already pinned in ggtt with incorrect alignment:"
05a20d09
CW
3665 " offset=%08x, req.alignment=%llx,"
3666 " req.map_and_fenceable=%d, vma->map_and_fenceable=%d\n",
3667 i915_ggtt_offset(vma), alignment,
59bfa124 3668 !!(flags & PIN_MAPPABLE),
05a20d09 3669 i915_vma_is_map_and_fenceable(vma));
59bfa124
CW
3670 ret = i915_vma_unbind(vma);
3671 if (ret)
058d88c4 3672 return ERR_PTR(ret);
59bfa124
CW
3673 }
3674
058d88c4
CW
3675 ret = i915_vma_pin(vma, size, alignment, flags | PIN_GLOBAL);
3676 if (ret)
3677 return ERR_PTR(ret);
ec7adb6e 3678
058d88c4 3679 return vma;
673a394b
EA
3680}
3681
edf6b76f 3682static __always_inline unsigned int __busy_read_flag(unsigned int id)
3fdc13c7
CW
3683{
3684 /* Note that we could alias engines in the execbuf API, but
3685 * that would be very unwise as it prevents userspace from
3686 * fine control over engine selection. Ahem.
3687 *
3688 * This should be something like EXEC_MAX_ENGINE instead of
3689 * I915_NUM_ENGINES.
3690 */
3691 BUILD_BUG_ON(I915_NUM_ENGINES > 16);
3692 return 0x10000 << id;
3693}
3694
3695static __always_inline unsigned int __busy_write_id(unsigned int id)
3696{
70cb472c
CW
3697 /* The uABI guarantees an active writer is also amongst the read
3698 * engines. This would be true if we accessed the activity tracking
3699 * under the lock, but as we perform the lookup of the object and
3700 * its activity locklessly we can not guarantee that the last_write
3701 * being active implies that we have set the same engine flag from
3702 * last_read - hence we always set both read and write busy for
3703 * last_write.
3704 */
3705 return id | __busy_read_flag(id);
3fdc13c7
CW
3706}
3707
edf6b76f 3708static __always_inline unsigned int
d07f0e59 3709__busy_set_if_active(const struct dma_fence *fence,
3fdc13c7
CW
3710 unsigned int (*flag)(unsigned int id))
3711{
d07f0e59 3712 struct drm_i915_gem_request *rq;
3fdc13c7 3713
d07f0e59
CW
3714 /* We have to check the current hw status of the fence as the uABI
3715 * guarantees forward progress. We could rely on the idle worker
3716 * to eventually flush us, but to minimise latency just ask the
3717 * hardware.
1255501d 3718 *
d07f0e59 3719 * Note we only report on the status of native fences.
1255501d 3720 */
d07f0e59
CW
3721 if (!dma_fence_is_i915(fence))
3722 return 0;
3723
3724 /* opencode to_request() in order to avoid const warnings */
3725 rq = container_of(fence, struct drm_i915_gem_request, fence);
3726 if (i915_gem_request_completed(rq))
3727 return 0;
3728
3729 return flag(rq->engine->exec_id);
3fdc13c7
CW
3730}
3731
edf6b76f 3732static __always_inline unsigned int
d07f0e59 3733busy_check_reader(const struct dma_fence *fence)
3fdc13c7 3734{
d07f0e59 3735 return __busy_set_if_active(fence, __busy_read_flag);
3fdc13c7
CW
3736}
3737
edf6b76f 3738static __always_inline unsigned int
d07f0e59 3739busy_check_writer(const struct dma_fence *fence)
3fdc13c7 3740{
d07f0e59
CW
3741 if (!fence)
3742 return 0;
3743
3744 return __busy_set_if_active(fence, __busy_write_id);
3fdc13c7
CW
3745}
3746
673a394b
EA
3747int
3748i915_gem_busy_ioctl(struct drm_device *dev, void *data,
05394f39 3749 struct drm_file *file)
673a394b
EA
3750{
3751 struct drm_i915_gem_busy *args = data;
05394f39 3752 struct drm_i915_gem_object *obj;
d07f0e59
CW
3753 struct reservation_object_list *list;
3754 unsigned int seq;
fbbd37b3 3755 int err;
673a394b 3756
d07f0e59 3757 err = -ENOENT;
fbbd37b3
CW
3758 rcu_read_lock();
3759 obj = i915_gem_object_lookup_rcu(file, args->handle);
d07f0e59 3760 if (!obj)
fbbd37b3 3761 goto out;
d1b851fc 3762
d07f0e59
CW
3763 /* A discrepancy here is that we do not report the status of
3764 * non-i915 fences, i.e. even though we may report the object as idle,
3765 * a call to set-domain may still stall waiting for foreign rendering.
3766 * This also means that wait-ioctl may report an object as busy,
3767 * where busy-ioctl considers it idle.
3768 *
3769 * We trade the ability to warn of foreign fences to report on which
3770 * i915 engines are active for the object.
3771 *
3772 * Alternatively, we can trade that extra information on read/write
3773 * activity with
3774 * args->busy =
3775 * !reservation_object_test_signaled_rcu(obj->resv, true);
3776 * to report the overall busyness. This is what the wait-ioctl does.
3777 *
3778 */
3779retry:
3780 seq = raw_read_seqcount(&obj->resv->seq);
426960be 3781
d07f0e59
CW
3782 /* Translate the exclusive fence to the READ *and* WRITE engine */
3783 args->busy = busy_check_writer(rcu_dereference(obj->resv->fence_excl));
3fdc13c7 3784
d07f0e59
CW
3785 /* Translate shared fences to READ set of engines */
3786 list = rcu_dereference(obj->resv->fence);
3787 if (list) {
3788 unsigned int shared_count = list->shared_count, i;
3fdc13c7 3789
d07f0e59
CW
3790 for (i = 0; i < shared_count; ++i) {
3791 struct dma_fence *fence =
3792 rcu_dereference(list->shared[i]);
3793
3794 args->busy |= busy_check_reader(fence);
3795 }
426960be 3796 }
673a394b 3797
d07f0e59
CW
3798 if (args->busy && read_seqcount_retry(&obj->resv->seq, seq))
3799 goto retry;
3800
3801 err = 0;
fbbd37b3
CW
3802out:
3803 rcu_read_unlock();
3804 return err;
673a394b
EA
3805}
3806
3807int
3808i915_gem_throttle_ioctl(struct drm_device *dev, void *data,
3809 struct drm_file *file_priv)
3810{
0206e353 3811 return i915_gem_ring_throttle(dev, file_priv);
673a394b
EA
3812}
3813
3ef94daa
CW
3814int
3815i915_gem_madvise_ioctl(struct drm_device *dev, void *data,
3816 struct drm_file *file_priv)
3817{
fac5e23e 3818 struct drm_i915_private *dev_priv = to_i915(dev);
3ef94daa 3819 struct drm_i915_gem_madvise *args = data;
05394f39 3820 struct drm_i915_gem_object *obj;
1233e2db 3821 int err;
3ef94daa
CW
3822
3823 switch (args->madv) {
3824 case I915_MADV_DONTNEED:
3825 case I915_MADV_WILLNEED:
3826 break;
3827 default:
3828 return -EINVAL;
3829 }
3830
03ac0642 3831 obj = i915_gem_object_lookup(file_priv, args->handle);
1233e2db
CW
3832 if (!obj)
3833 return -ENOENT;
3834
3835 err = mutex_lock_interruptible(&obj->mm.lock);
3836 if (err)
3837 goto out;
3ef94daa 3838
a4f5ea64 3839 if (obj->mm.pages &&
3e510a8e 3840 i915_gem_object_is_tiled(obj) &&
656bfa3a 3841 dev_priv->quirks & QUIRK_PIN_SWIZZLED_PAGES) {
bc0629a7
CW
3842 if (obj->mm.madv == I915_MADV_WILLNEED) {
3843 GEM_BUG_ON(!obj->mm.quirked);
a4f5ea64 3844 __i915_gem_object_unpin_pages(obj);
bc0629a7
CW
3845 obj->mm.quirked = false;
3846 }
3847 if (args->madv == I915_MADV_WILLNEED) {
2c3a3f44 3848 GEM_BUG_ON(obj->mm.quirked);
a4f5ea64 3849 __i915_gem_object_pin_pages(obj);
bc0629a7
CW
3850 obj->mm.quirked = true;
3851 }
656bfa3a
DV
3852 }
3853
a4f5ea64
CW
3854 if (obj->mm.madv != __I915_MADV_PURGED)
3855 obj->mm.madv = args->madv;
3ef94daa 3856
6c085a72 3857 /* if the object is no longer attached, discard its backing storage */
a4f5ea64 3858 if (obj->mm.madv == I915_MADV_DONTNEED && !obj->mm.pages)
2d7ef395
CW
3859 i915_gem_object_truncate(obj);
3860
a4f5ea64 3861 args->retained = obj->mm.madv != __I915_MADV_PURGED;
1233e2db 3862 mutex_unlock(&obj->mm.lock);
bb6baf76 3863
1233e2db 3864out:
f8c417cd 3865 i915_gem_object_put(obj);
1233e2db 3866 return err;
3ef94daa
CW
3867}
3868
5b8c8aec
CW
3869static void
3870frontbuffer_retire(struct i915_gem_active *active,
3871 struct drm_i915_gem_request *request)
3872{
3873 struct drm_i915_gem_object *obj =
3874 container_of(active, typeof(*obj), frontbuffer_write);
3875
3876 intel_fb_obj_flush(obj, true, ORIGIN_CS);
3877}
3878
37e680a1
CW
3879void i915_gem_object_init(struct drm_i915_gem_object *obj,
3880 const struct drm_i915_gem_object_ops *ops)
0327d6ba 3881{
1233e2db
CW
3882 mutex_init(&obj->mm.lock);
3883
56cea323 3884 INIT_LIST_HEAD(&obj->global_link);
275f039d 3885 INIT_LIST_HEAD(&obj->userfault_link);
b25cb2f8 3886 INIT_LIST_HEAD(&obj->obj_exec_link);
2f633156 3887 INIT_LIST_HEAD(&obj->vma_list);
8d9d5744 3888 INIT_LIST_HEAD(&obj->batch_pool_link);
0327d6ba 3889
37e680a1
CW
3890 obj->ops = ops;
3891
d07f0e59
CW
3892 reservation_object_init(&obj->__builtin_resv);
3893 obj->resv = &obj->__builtin_resv;
3894
50349247 3895 obj->frontbuffer_ggtt_origin = ORIGIN_GTT;
5b8c8aec 3896 init_request_active(&obj->frontbuffer_write, frontbuffer_retire);
a4f5ea64
CW
3897
3898 obj->mm.madv = I915_MADV_WILLNEED;
3899 INIT_RADIX_TREE(&obj->mm.get_page.radix, GFP_KERNEL | __GFP_NOWARN);
3900 mutex_init(&obj->mm.get_page.lock);
0327d6ba 3901
f19ec8cb 3902 i915_gem_info_add_obj(to_i915(obj->base.dev), obj->base.size);
0327d6ba
CW
3903}
3904
37e680a1 3905static const struct drm_i915_gem_object_ops i915_gem_object_ops = {
3599a91c
TU
3906 .flags = I915_GEM_OBJECT_HAS_STRUCT_PAGE |
3907 I915_GEM_OBJECT_IS_SHRINKABLE,
37e680a1
CW
3908 .get_pages = i915_gem_object_get_pages_gtt,
3909 .put_pages = i915_gem_object_put_pages_gtt,
3910};
3911
b4bcbe2a 3912struct drm_i915_gem_object *
12d79d78 3913i915_gem_object_create(struct drm_i915_private *dev_priv, u64 size)
ac52bc56 3914{
c397b908 3915 struct drm_i915_gem_object *obj;
5949eac4 3916 struct address_space *mapping;
1a240d4d 3917 gfp_t mask;
fe3db79b 3918 int ret;
ac52bc56 3919
b4bcbe2a
CW
3920 /* There is a prevalence of the assumption that we fit the object's
3921 * page count inside a 32bit _signed_ variable. Let's document this and
3922 * catch if we ever need to fix it. In the meantime, if you do spot
3923 * such a local variable, please consider fixing!
3924 */
3925 if (WARN_ON(size >> PAGE_SHIFT > INT_MAX))
3926 return ERR_PTR(-E2BIG);
3927
3928 if (overflows_type(size, obj->base.size))
3929 return ERR_PTR(-E2BIG);
3930
187685cb 3931 obj = i915_gem_object_alloc(dev_priv);
c397b908 3932 if (obj == NULL)
fe3db79b 3933 return ERR_PTR(-ENOMEM);
673a394b 3934
12d79d78 3935 ret = drm_gem_object_init(&dev_priv->drm, &obj->base, size);
fe3db79b
CW
3936 if (ret)
3937 goto fail;
673a394b 3938
bed1ea95 3939 mask = GFP_HIGHUSER | __GFP_RECLAIMABLE;
c0f86832 3940 if (IS_I965GM(dev_priv) || IS_I965G(dev_priv)) {
bed1ea95
CW
3941 /* 965gm cannot relocate objects above 4GiB. */
3942 mask &= ~__GFP_HIGHMEM;
3943 mask |= __GFP_DMA32;
3944 }
3945
93c76a3d 3946 mapping = obj->base.filp->f_mapping;
bed1ea95 3947 mapping_set_gfp_mask(mapping, mask);
5949eac4 3948
37e680a1 3949 i915_gem_object_init(obj, &i915_gem_object_ops);
73aa808f 3950
c397b908
DV
3951 obj->base.write_domain = I915_GEM_DOMAIN_CPU;
3952 obj->base.read_domains = I915_GEM_DOMAIN_CPU;
673a394b 3953
0031fb96 3954 if (HAS_LLC(dev_priv)) {
3d29b842 3955 /* On some devices, we can have the GPU use the LLC (the CPU
a1871112
EA
3956 * cache) for about a 10% performance improvement
3957 * compared to uncached. Graphics requests other than
3958 * display scanout are coherent with the CPU in
3959 * accessing this cache. This means in this mode we
3960 * don't need to clflush on the CPU side, and on the
3961 * GPU side we only need to flush internal caches to
3962 * get data visible to the CPU.
3963 *
3964 * However, we maintain the display planes as UC, and so
3965 * need to rebind when first used as such.
3966 */
3967 obj->cache_level = I915_CACHE_LLC;
3968 } else
3969 obj->cache_level = I915_CACHE_NONE;
3970
d861e338
DV
3971 trace_i915_gem_object_create(obj);
3972
05394f39 3973 return obj;
fe3db79b
CW
3974
3975fail:
3976 i915_gem_object_free(obj);
fe3db79b 3977 return ERR_PTR(ret);
c397b908
DV
3978}
3979
340fbd8c
CW
3980static bool discard_backing_storage(struct drm_i915_gem_object *obj)
3981{
3982 /* If we are the last user of the backing storage (be it shmemfs
3983 * pages or stolen etc), we know that the pages are going to be
3984 * immediately released. In this case, we can then skip copying
3985 * back the contents from the GPU.
3986 */
3987
a4f5ea64 3988 if (obj->mm.madv != I915_MADV_WILLNEED)
340fbd8c
CW
3989 return false;
3990
3991 if (obj->base.filp == NULL)
3992 return true;
3993
3994 /* At first glance, this looks racy, but then again so would be
3995 * userspace racing mmap against close. However, the first external
3996 * reference to the filp can only be obtained through the
3997 * i915_gem_mmap_ioctl() which safeguards us against the user
3998 * acquiring such a reference whilst we are in the middle of
3999 * freeing the object.
4000 */
4001 return atomic_long_read(&obj->base.filp->f_count) == 1;
4002}
4003
fbbd37b3
CW
4004static void __i915_gem_free_objects(struct drm_i915_private *i915,
4005 struct llist_node *freed)
673a394b 4006{
fbbd37b3 4007 struct drm_i915_gem_object *obj, *on;
673a394b 4008
fbbd37b3
CW
4009 mutex_lock(&i915->drm.struct_mutex);
4010 intel_runtime_pm_get(i915);
4011 llist_for_each_entry(obj, freed, freed) {
4012 struct i915_vma *vma, *vn;
4013
4014 trace_i915_gem_object_destroy(obj);
4015
4016 GEM_BUG_ON(i915_gem_object_is_active(obj));
4017 list_for_each_entry_safe(vma, vn,
4018 &obj->vma_list, obj_link) {
4019 GEM_BUG_ON(!i915_vma_is_ggtt(vma));
4020 GEM_BUG_ON(i915_vma_is_active(vma));
4021 vma->flags &= ~I915_VMA_PIN_MASK;
4022 i915_vma_close(vma);
4023 }
db6c2b41
CW
4024 GEM_BUG_ON(!list_empty(&obj->vma_list));
4025 GEM_BUG_ON(!RB_EMPTY_ROOT(&obj->vma_tree));
fbbd37b3 4026
56cea323 4027 list_del(&obj->global_link);
fbbd37b3
CW
4028 }
4029 intel_runtime_pm_put(i915);
4030 mutex_unlock(&i915->drm.struct_mutex);
4031
4032 llist_for_each_entry_safe(obj, on, freed, freed) {
4033 GEM_BUG_ON(obj->bind_count);
4034 GEM_BUG_ON(atomic_read(&obj->frontbuffer_bits));
4035
4036 if (obj->ops->release)
4037 obj->ops->release(obj);
f65c9168 4038
fbbd37b3
CW
4039 if (WARN_ON(i915_gem_object_has_pinned_pages(obj)))
4040 atomic_set(&obj->mm.pages_pin_count, 0);
548625ee 4041 __i915_gem_object_put_pages(obj, I915_MM_NORMAL);
fbbd37b3
CW
4042 GEM_BUG_ON(obj->mm.pages);
4043
4044 if (obj->base.import_attach)
4045 drm_prime_gem_destroy(&obj->base, NULL);
4046
d07f0e59 4047 reservation_object_fini(&obj->__builtin_resv);
fbbd37b3
CW
4048 drm_gem_object_release(&obj->base);
4049 i915_gem_info_remove_obj(i915, obj->base.size);
4050
4051 kfree(obj->bit_17);
4052 i915_gem_object_free(obj);
4053 }
4054}
4055
4056static void i915_gem_flush_free_objects(struct drm_i915_private *i915)
4057{
4058 struct llist_node *freed;
4059
4060 freed = llist_del_all(&i915->mm.free_list);
4061 if (unlikely(freed))
4062 __i915_gem_free_objects(i915, freed);
4063}
4064
4065static void __i915_gem_free_work(struct work_struct *work)
4066{
4067 struct drm_i915_private *i915 =
4068 container_of(work, struct drm_i915_private, mm.free_work);
4069 struct llist_node *freed;
26e12f89 4070
b1f788c6
CW
4071 /* All file-owned VMA should have been released by this point through
4072 * i915_gem_close_object(), or earlier by i915_gem_context_close().
4073 * However, the object may also be bound into the global GTT (e.g.
4074 * older GPUs without per-process support, or for direct access through
4075 * the GTT either for the user or for scanout). Those VMA still need to
4076 * unbound now.
4077 */
1488fc08 4078
fbbd37b3
CW
4079 while ((freed = llist_del_all(&i915->mm.free_list)))
4080 __i915_gem_free_objects(i915, freed);
4081}
a071fa00 4082
fbbd37b3
CW
4083static void __i915_gem_free_object_rcu(struct rcu_head *head)
4084{
4085 struct drm_i915_gem_object *obj =
4086 container_of(head, typeof(*obj), rcu);
4087 struct drm_i915_private *i915 = to_i915(obj->base.dev);
4088
4089 /* We can't simply use call_rcu() from i915_gem_free_object()
4090 * as we need to block whilst unbinding, and the call_rcu
4091 * task may be called from softirq context. So we take a
4092 * detour through a worker.
4093 */
4094 if (llist_add(&obj->freed, &i915->mm.free_list))
4095 schedule_work(&i915->mm.free_work);
4096}
656bfa3a 4097
fbbd37b3
CW
4098void i915_gem_free_object(struct drm_gem_object *gem_obj)
4099{
4100 struct drm_i915_gem_object *obj = to_intel_bo(gem_obj);
a4f5ea64 4101
bc0629a7
CW
4102 if (obj->mm.quirked)
4103 __i915_gem_object_unpin_pages(obj);
4104
340fbd8c 4105 if (discard_backing_storage(obj))
a4f5ea64 4106 obj->mm.madv = I915_MADV_DONTNEED;
de151cf6 4107
fbbd37b3
CW
4108 /* Before we free the object, make sure any pure RCU-only
4109 * read-side critical sections are complete, e.g.
4110 * i915_gem_busy_ioctl(). For the corresponding synchronized
4111 * lookup see i915_gem_object_lookup_rcu().
4112 */
4113 call_rcu(&obj->rcu, __i915_gem_free_object_rcu);
673a394b
EA
4114}
4115
f8a7fde4
CW
4116void __i915_gem_object_release_unless_active(struct drm_i915_gem_object *obj)
4117{
4118 lockdep_assert_held(&obj->base.dev->struct_mutex);
4119
4120 GEM_BUG_ON(i915_gem_object_has_active_reference(obj));
4121 if (i915_gem_object_is_active(obj))
4122 i915_gem_object_set_active_reference(obj);
4123 else
4124 i915_gem_object_put(obj);
4125}
4126
3033acab
CW
4127static void assert_kernel_context_is_current(struct drm_i915_private *dev_priv)
4128{
4129 struct intel_engine_cs *engine;
4130 enum intel_engine_id id;
4131
4132 for_each_engine(engine, dev_priv, id)
984ff29f 4133 GEM_BUG_ON(!i915_gem_context_is_kernel(engine->last_retired_context));
3033acab
CW
4134}
4135
bf9e8429 4136int i915_gem_suspend(struct drm_i915_private *dev_priv)
29105ccc 4137{
bf9e8429 4138 struct drm_device *dev = &dev_priv->drm;
dcff85c8 4139 int ret;
28dfe52a 4140
54b4f68f
CW
4141 intel_suspend_gt_powersave(dev_priv);
4142
45c5f202 4143 mutex_lock(&dev->struct_mutex);
5ab57c70
CW
4144
4145 /* We have to flush all the executing contexts to main memory so
4146 * that they can saved in the hibernation image. To ensure the last
4147 * context image is coherent, we have to switch away from it. That
4148 * leaves the dev_priv->kernel_context still active when
4149 * we actually suspend, and its image in memory may not match the GPU
4150 * state. Fortunately, the kernel_context is disposable and we do
4151 * not rely on its state.
4152 */
4153 ret = i915_gem_switch_to_kernel_context(dev_priv);
4154 if (ret)
4155 goto err;
4156
22dd3bb9
CW
4157 ret = i915_gem_wait_for_idle(dev_priv,
4158 I915_WAIT_INTERRUPTIBLE |
4159 I915_WAIT_LOCKED);
f7403347 4160 if (ret)
45c5f202 4161 goto err;
f7403347 4162
c033666a 4163 i915_gem_retire_requests(dev_priv);
28176ef4 4164 GEM_BUG_ON(dev_priv->gt.active_requests);
673a394b 4165
3033acab 4166 assert_kernel_context_is_current(dev_priv);
b2e862d0 4167 i915_gem_context_lost(dev_priv);
45c5f202
CW
4168 mutex_unlock(&dev->struct_mutex);
4169
737b1506 4170 cancel_delayed_work_sync(&dev_priv->gpu_error.hangcheck_work);
67d97da3 4171 cancel_delayed_work_sync(&dev_priv->gt.retire_work);
bdeb9785
CW
4172
4173 /* As the idle_work is rearming if it detects a race, play safe and
4174 * repeat the flush until it is definitely idle.
4175 */
4176 while (flush_delayed_work(&dev_priv->gt.idle_work))
4177 ;
4178
4179 i915_gem_drain_freed_objects(dev_priv);
29105ccc 4180
bdcf120b
CW
4181 /* Assert that we sucessfully flushed all the work and
4182 * reset the GPU back to its idle, low power state.
4183 */
67d97da3 4184 WARN_ON(dev_priv->gt.awake);
31ab49ab 4185 WARN_ON(!intel_execlists_idle(dev_priv));
bdcf120b 4186
1c777c5d
ID
4187 /*
4188 * Neither the BIOS, ourselves or any other kernel
4189 * expects the system to be in execlists mode on startup,
4190 * so we need to reset the GPU back to legacy mode. And the only
4191 * known way to disable logical contexts is through a GPU reset.
4192 *
4193 * So in order to leave the system in a known default configuration,
4194 * always reset the GPU upon unload and suspend. Afterwards we then
4195 * clean up the GEM state tracking, flushing off the requests and
4196 * leaving the system in a known idle state.
4197 *
4198 * Note that is of the upmost importance that the GPU is idle and
4199 * all stray writes are flushed *before* we dismantle the backing
4200 * storage for the pinned objects.
4201 *
4202 * However, since we are uncertain that resetting the GPU on older
4203 * machines is a good idea, we don't - just in case it leaves the
4204 * machine in an unusable condition.
4205 */
0031fb96 4206 if (HAS_HW_CONTEXTS(dev_priv)) {
1c777c5d
ID
4207 int reset = intel_gpu_reset(dev_priv, ALL_ENGINES);
4208 WARN_ON(reset && reset != -ENODEV);
4209 }
4210
673a394b 4211 return 0;
45c5f202
CW
4212
4213err:
4214 mutex_unlock(&dev->struct_mutex);
4215 return ret;
673a394b
EA
4216}
4217
bf9e8429 4218void i915_gem_resume(struct drm_i915_private *dev_priv)
5ab57c70 4219{
bf9e8429 4220 struct drm_device *dev = &dev_priv->drm;
5ab57c70 4221
31ab49ab
ID
4222 WARN_ON(dev_priv->gt.awake);
4223
5ab57c70 4224 mutex_lock(&dev->struct_mutex);
275a991c 4225 i915_gem_restore_gtt_mappings(dev_priv);
5ab57c70
CW
4226
4227 /* As we didn't flush the kernel context before suspend, we cannot
4228 * guarantee that the context image is complete. So let's just reset
4229 * it and start again.
4230 */
821ed7df 4231 dev_priv->gt.resume(dev_priv);
5ab57c70
CW
4232
4233 mutex_unlock(&dev->struct_mutex);
4234}
4235
c6be607a 4236void i915_gem_init_swizzling(struct drm_i915_private *dev_priv)
f691e2f4 4237{
c6be607a 4238 if (INTEL_GEN(dev_priv) < 5 ||
f691e2f4
DV
4239 dev_priv->mm.bit_6_swizzle_x == I915_BIT_6_SWIZZLE_NONE)
4240 return;
4241
4242 I915_WRITE(DISP_ARB_CTL, I915_READ(DISP_ARB_CTL) |
4243 DISP_TILE_SURFACE_SWIZZLING);
4244
5db94019 4245 if (IS_GEN5(dev_priv))
11782b02
DV
4246 return;
4247
f691e2f4 4248 I915_WRITE(TILECTL, I915_READ(TILECTL) | TILECTL_SWZCTL);
5db94019 4249 if (IS_GEN6(dev_priv))
6b26c86d 4250 I915_WRITE(ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_SNB));
5db94019 4251 else if (IS_GEN7(dev_priv))
6b26c86d 4252 I915_WRITE(ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_IVB));
5db94019 4253 else if (IS_GEN8(dev_priv))
31a5336e 4254 I915_WRITE(GAMTARBMODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_BDW));
8782e26c
BW
4255 else
4256 BUG();
f691e2f4 4257}
e21af88d 4258
50a0bc90 4259static void init_unused_ring(struct drm_i915_private *dev_priv, u32 base)
81e7f200 4260{
81e7f200
VS
4261 I915_WRITE(RING_CTL(base), 0);
4262 I915_WRITE(RING_HEAD(base), 0);
4263 I915_WRITE(RING_TAIL(base), 0);
4264 I915_WRITE(RING_START(base), 0);
4265}
4266
50a0bc90 4267static void init_unused_rings(struct drm_i915_private *dev_priv)
81e7f200 4268{
50a0bc90
TU
4269 if (IS_I830(dev_priv)) {
4270 init_unused_ring(dev_priv, PRB1_BASE);
4271 init_unused_ring(dev_priv, SRB0_BASE);
4272 init_unused_ring(dev_priv, SRB1_BASE);
4273 init_unused_ring(dev_priv, SRB2_BASE);
4274 init_unused_ring(dev_priv, SRB3_BASE);
4275 } else if (IS_GEN2(dev_priv)) {
4276 init_unused_ring(dev_priv, SRB0_BASE);
4277 init_unused_ring(dev_priv, SRB1_BASE);
4278 } else if (IS_GEN3(dev_priv)) {
4279 init_unused_ring(dev_priv, PRB1_BASE);
4280 init_unused_ring(dev_priv, PRB2_BASE);
81e7f200
VS
4281 }
4282}
4283
4fc7c971 4284int
bf9e8429 4285i915_gem_init_hw(struct drm_i915_private *dev_priv)
4fc7c971 4286{
e2f80391 4287 struct intel_engine_cs *engine;
3b3f1650 4288 enum intel_engine_id id;
d200cda6 4289 int ret;
4fc7c971 4290
de867c20
CW
4291 dev_priv->gt.last_init_time = ktime_get();
4292
5e4f5189
CW
4293 /* Double layer security blanket, see i915_gem_init() */
4294 intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
4295
0031fb96 4296 if (HAS_EDRAM(dev_priv) && INTEL_GEN(dev_priv) < 9)
05e21cc4 4297 I915_WRITE(HSW_IDICR, I915_READ(HSW_IDICR) | IDIHASHMSK(0xf));
4fc7c971 4298
772c2a51 4299 if (IS_HASWELL(dev_priv))
50a0bc90 4300 I915_WRITE(MI_PREDICATE_RESULT_2, IS_HSW_GT3(dev_priv) ?
0bf21347 4301 LOWER_SLICE_ENABLED : LOWER_SLICE_DISABLED);
9435373e 4302
6e266956 4303 if (HAS_PCH_NOP(dev_priv)) {
fd6b8f43 4304 if (IS_IVYBRIDGE(dev_priv)) {
6ba844b0
DV
4305 u32 temp = I915_READ(GEN7_MSG_CTL);
4306 temp &= ~(WAIT_FOR_PCH_FLR_ACK | WAIT_FOR_PCH_RESET_ACK);
4307 I915_WRITE(GEN7_MSG_CTL, temp);
c6be607a 4308 } else if (INTEL_GEN(dev_priv) >= 7) {
6ba844b0
DV
4309 u32 temp = I915_READ(HSW_NDE_RSTWRN_OPT);
4310 temp &= ~RESET_PCH_HANDSHAKE_ENABLE;
4311 I915_WRITE(HSW_NDE_RSTWRN_OPT, temp);
4312 }
88a2b2a3
BW
4313 }
4314
c6be607a 4315 i915_gem_init_swizzling(dev_priv);
4fc7c971 4316
d5abdfda
DV
4317 /*
4318 * At least 830 can leave some of the unused rings
4319 * "active" (ie. head != tail) after resume which
4320 * will prevent c3 entry. Makes sure all unused rings
4321 * are totally idle.
4322 */
50a0bc90 4323 init_unused_rings(dev_priv);
d5abdfda 4324
ed54c1a1 4325 BUG_ON(!dev_priv->kernel_context);
90638cc1 4326
c6be607a 4327 ret = i915_ppgtt_init_hw(dev_priv);
4ad2fd88
JH
4328 if (ret) {
4329 DRM_ERROR("PPGTT enable HW failed %d\n", ret);
4330 goto out;
4331 }
4332
4333 /* Need to do basic initialisation of all rings first: */
3b3f1650 4334 for_each_engine(engine, dev_priv, id) {
e2f80391 4335 ret = engine->init_hw(engine);
35a57ffb 4336 if (ret)
5e4f5189 4337 goto out;
35a57ffb 4338 }
99433931 4339
bf9e8429 4340 intel_mocs_init_l3cc_table(dev_priv);
0ccdacf6 4341
33a732f4 4342 /* We can't enable contexts until all firmware is loaded */
bf9e8429 4343 ret = intel_guc_setup(dev_priv);
e556f7c1
DG
4344 if (ret)
4345 goto out;
33a732f4 4346
5e4f5189
CW
4347out:
4348 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
2fa48d8d 4349 return ret;
8187a2b7
ZN
4350}
4351
39df9190
CW
4352bool intel_sanitize_semaphores(struct drm_i915_private *dev_priv, int value)
4353{
4354 if (INTEL_INFO(dev_priv)->gen < 6)
4355 return false;
4356
4357 /* TODO: make semaphores and Execlists play nicely together */
4358 if (i915.enable_execlists)
4359 return false;
4360
4361 if (value >= 0)
4362 return value;
4363
4364#ifdef CONFIG_INTEL_IOMMU
4365 /* Enable semaphores on SNB when IO remapping is off */
4366 if (INTEL_INFO(dev_priv)->gen == 6 && intel_iommu_gfx_mapped)
4367 return false;
4368#endif
4369
4370 return true;
4371}
4372
bf9e8429 4373int i915_gem_init(struct drm_i915_private *dev_priv)
1070a42b 4374{
1070a42b
CW
4375 int ret;
4376
bf9e8429 4377 mutex_lock(&dev_priv->drm.struct_mutex);
d62b4892 4378
a83014d3 4379 if (!i915.enable_execlists) {
821ed7df 4380 dev_priv->gt.resume = intel_legacy_submission_resume;
7e37f889 4381 dev_priv->gt.cleanup_engine = intel_engine_cleanup;
454afebd 4382 } else {
821ed7df 4383 dev_priv->gt.resume = intel_lr_context_resume;
117897f4 4384 dev_priv->gt.cleanup_engine = intel_logical_ring_cleanup;
a83014d3
OM
4385 }
4386
5e4f5189
CW
4387 /* This is just a security blanket to placate dragons.
4388 * On some systems, we very sporadically observe that the first TLBs
4389 * used by the CS may be stale, despite us poking the TLB reset. If
4390 * we hold the forcewake during initialisation these problems
4391 * just magically go away.
4392 */
4393 intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
4394
72778cb2 4395 i915_gem_init_userptr(dev_priv);
f6b9d5ca
CW
4396
4397 ret = i915_gem_init_ggtt(dev_priv);
4398 if (ret)
4399 goto out_unlock;
d62b4892 4400
bf9e8429 4401 ret = i915_gem_context_init(dev_priv);
7bcc3777
JN
4402 if (ret)
4403 goto out_unlock;
2fa48d8d 4404
bf9e8429 4405 ret = intel_engines_init(dev_priv);
35a57ffb 4406 if (ret)
7bcc3777 4407 goto out_unlock;
2fa48d8d 4408
bf9e8429 4409 ret = i915_gem_init_hw(dev_priv);
60990320 4410 if (ret == -EIO) {
7e21d648 4411 /* Allow engine initialisation to fail by marking the GPU as
60990320
CW
4412 * wedged. But we only want to do this where the GPU is angry,
4413 * for all other failure, such as an allocation failure, bail.
4414 */
4415 DRM_ERROR("Failed to initialize GPU, declaring it wedged\n");
821ed7df 4416 i915_gem_set_wedged(dev_priv);
60990320 4417 ret = 0;
1070a42b 4418 }
7bcc3777
JN
4419
4420out_unlock:
5e4f5189 4421 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
bf9e8429 4422 mutex_unlock(&dev_priv->drm.struct_mutex);
1070a42b 4423
60990320 4424 return ret;
1070a42b
CW
4425}
4426
8187a2b7 4427void
cb15d9f8 4428i915_gem_cleanup_engines(struct drm_i915_private *dev_priv)
8187a2b7 4429{
e2f80391 4430 struct intel_engine_cs *engine;
3b3f1650 4431 enum intel_engine_id id;
8187a2b7 4432
3b3f1650 4433 for_each_engine(engine, dev_priv, id)
117897f4 4434 dev_priv->gt.cleanup_engine(engine);
8187a2b7
ZN
4435}
4436
40ae4e16
ID
4437void
4438i915_gem_load_init_fences(struct drm_i915_private *dev_priv)
4439{
49ef5294 4440 int i;
40ae4e16
ID
4441
4442 if (INTEL_INFO(dev_priv)->gen >= 7 && !IS_VALLEYVIEW(dev_priv) &&
4443 !IS_CHERRYVIEW(dev_priv))
4444 dev_priv->num_fence_regs = 32;
73f67aa8
JN
4445 else if (INTEL_INFO(dev_priv)->gen >= 4 ||
4446 IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
4447 IS_G33(dev_priv) || IS_PINEVIEW(dev_priv))
40ae4e16
ID
4448 dev_priv->num_fence_regs = 16;
4449 else
4450 dev_priv->num_fence_regs = 8;
4451
c033666a 4452 if (intel_vgpu_active(dev_priv))
40ae4e16
ID
4453 dev_priv->num_fence_regs =
4454 I915_READ(vgtif_reg(avail_rs.fence_num));
4455
4456 /* Initialize fence registers to zero */
49ef5294
CW
4457 for (i = 0; i < dev_priv->num_fence_regs; i++) {
4458 struct drm_i915_fence_reg *fence = &dev_priv->fence_regs[i];
4459
4460 fence->i915 = dev_priv;
4461 fence->id = i;
4462 list_add_tail(&fence->link, &dev_priv->mm.fence_list);
4463 }
4362f4f6 4464 i915_gem_restore_fences(dev_priv);
40ae4e16 4465
4362f4f6 4466 i915_gem_detect_bit_6_swizzle(dev_priv);
40ae4e16
ID
4467}
4468
73cb9701 4469int
cb15d9f8 4470i915_gem_load_init(struct drm_i915_private *dev_priv)
673a394b 4471{
a933568e 4472 int err = -ENOMEM;
42dcedd4 4473
a933568e
TU
4474 dev_priv->objects = KMEM_CACHE(drm_i915_gem_object, SLAB_HWCACHE_ALIGN);
4475 if (!dev_priv->objects)
73cb9701 4476 goto err_out;
73cb9701 4477
a933568e
TU
4478 dev_priv->vmas = KMEM_CACHE(i915_vma, SLAB_HWCACHE_ALIGN);
4479 if (!dev_priv->vmas)
73cb9701 4480 goto err_objects;
73cb9701 4481
a933568e
TU
4482 dev_priv->requests = KMEM_CACHE(drm_i915_gem_request,
4483 SLAB_HWCACHE_ALIGN |
4484 SLAB_RECLAIM_ACCOUNT |
4485 SLAB_DESTROY_BY_RCU);
4486 if (!dev_priv->requests)
73cb9701 4487 goto err_vmas;
73cb9701 4488
52e54209
CW
4489 dev_priv->dependencies = KMEM_CACHE(i915_dependency,
4490 SLAB_HWCACHE_ALIGN |
4491 SLAB_RECLAIM_ACCOUNT);
4492 if (!dev_priv->dependencies)
4493 goto err_requests;
4494
73cb9701
CW
4495 mutex_lock(&dev_priv->drm.struct_mutex);
4496 INIT_LIST_HEAD(&dev_priv->gt.timelines);
bb89485e 4497 err = i915_gem_timeline_init__global(dev_priv);
73cb9701
CW
4498 mutex_unlock(&dev_priv->drm.struct_mutex);
4499 if (err)
52e54209 4500 goto err_dependencies;
673a394b 4501
a33afea5 4502 INIT_LIST_HEAD(&dev_priv->context_list);
fbbd37b3
CW
4503 INIT_WORK(&dev_priv->mm.free_work, __i915_gem_free_work);
4504 init_llist_head(&dev_priv->mm.free_list);
6c085a72
CW
4505 INIT_LIST_HEAD(&dev_priv->mm.unbound_list);
4506 INIT_LIST_HEAD(&dev_priv->mm.bound_list);
a09ba7fa 4507 INIT_LIST_HEAD(&dev_priv->mm.fence_list);
275f039d 4508 INIT_LIST_HEAD(&dev_priv->mm.userfault_list);
67d97da3 4509 INIT_DELAYED_WORK(&dev_priv->gt.retire_work,
673a394b 4510 i915_gem_retire_work_handler);
67d97da3 4511 INIT_DELAYED_WORK(&dev_priv->gt.idle_work,
b29c19b6 4512 i915_gem_idle_work_handler);
1f15b76f 4513 init_waitqueue_head(&dev_priv->gpu_error.wait_queue);
1f83fee0 4514 init_waitqueue_head(&dev_priv->gpu_error.reset_queue);
31169714 4515
72bfa19c
CW
4516 dev_priv->relative_constants_mode = I915_EXEC_CONSTANTS_REL_GENERAL;
4517
6b95a207 4518 init_waitqueue_head(&dev_priv->pending_flip_queue);
17250b71 4519
ce453d81
CW
4520 dev_priv->mm.interruptible = true;
4521
6f633402
JL
4522 atomic_set(&dev_priv->mm.bsd_engine_dispatch_index, 0);
4523
b5add959 4524 spin_lock_init(&dev_priv->fb_tracking.lock);
73cb9701
CW
4525
4526 return 0;
4527
52e54209
CW
4528err_dependencies:
4529 kmem_cache_destroy(dev_priv->dependencies);
73cb9701
CW
4530err_requests:
4531 kmem_cache_destroy(dev_priv->requests);
4532err_vmas:
4533 kmem_cache_destroy(dev_priv->vmas);
4534err_objects:
4535 kmem_cache_destroy(dev_priv->objects);
4536err_out:
4537 return err;
673a394b 4538}
71acb5eb 4539
cb15d9f8 4540void i915_gem_load_cleanup(struct drm_i915_private *dev_priv)
d64aa096 4541{
7d5d59e5
CW
4542 WARN_ON(!llist_empty(&dev_priv->mm.free_list));
4543
ea84aa77
MA
4544 mutex_lock(&dev_priv->drm.struct_mutex);
4545 i915_gem_timeline_fini(&dev_priv->gt.global_timeline);
4546 WARN_ON(!list_empty(&dev_priv->gt.timelines));
4547 mutex_unlock(&dev_priv->drm.struct_mutex);
4548
52e54209 4549 kmem_cache_destroy(dev_priv->dependencies);
d64aa096
ID
4550 kmem_cache_destroy(dev_priv->requests);
4551 kmem_cache_destroy(dev_priv->vmas);
4552 kmem_cache_destroy(dev_priv->objects);
0eafec6d
CW
4553
4554 /* And ensure that our DESTROY_BY_RCU slabs are truly destroyed */
4555 rcu_barrier();
d64aa096
ID
4556}
4557
6a800eab
CW
4558int i915_gem_freeze(struct drm_i915_private *dev_priv)
4559{
4560 intel_runtime_pm_get(dev_priv);
4561
4562 mutex_lock(&dev_priv->drm.struct_mutex);
4563 i915_gem_shrink_all(dev_priv);
4564 mutex_unlock(&dev_priv->drm.struct_mutex);
4565
4566 intel_runtime_pm_put(dev_priv);
4567
4568 return 0;
4569}
4570
461fb99c
CW
4571int i915_gem_freeze_late(struct drm_i915_private *dev_priv)
4572{
4573 struct drm_i915_gem_object *obj;
7aab2d53
CW
4574 struct list_head *phases[] = {
4575 &dev_priv->mm.unbound_list,
4576 &dev_priv->mm.bound_list,
4577 NULL
4578 }, **p;
461fb99c
CW
4579
4580 /* Called just before we write the hibernation image.
4581 *
4582 * We need to update the domain tracking to reflect that the CPU
4583 * will be accessing all the pages to create and restore from the
4584 * hibernation, and so upon restoration those pages will be in the
4585 * CPU domain.
4586 *
4587 * To make sure the hibernation image contains the latest state,
4588 * we update that state just before writing out the image.
7aab2d53
CW
4589 *
4590 * To try and reduce the hibernation image, we manually shrink
4591 * the objects as well.
461fb99c
CW
4592 */
4593
6a800eab
CW
4594 mutex_lock(&dev_priv->drm.struct_mutex);
4595 i915_gem_shrink(dev_priv, -1UL, I915_SHRINK_UNBOUND);
461fb99c 4596
7aab2d53 4597 for (p = phases; *p; p++) {
56cea323 4598 list_for_each_entry(obj, *p, global_link) {
7aab2d53
CW
4599 obj->base.read_domains = I915_GEM_DOMAIN_CPU;
4600 obj->base.write_domain = I915_GEM_DOMAIN_CPU;
4601 }
461fb99c 4602 }
6a800eab 4603 mutex_unlock(&dev_priv->drm.struct_mutex);
461fb99c
CW
4604
4605 return 0;
4606}
4607
f787a5f5 4608void i915_gem_release(struct drm_device *dev, struct drm_file *file)
b962442e 4609{
f787a5f5 4610 struct drm_i915_file_private *file_priv = file->driver_priv;
15f7bbc7 4611 struct drm_i915_gem_request *request;
b962442e
EA
4612
4613 /* Clean up our request list when the client is going away, so that
4614 * later retire_requests won't dereference our soon-to-be-gone
4615 * file_priv.
4616 */
1c25595f 4617 spin_lock(&file_priv->mm.lock);
15f7bbc7 4618 list_for_each_entry(request, &file_priv->mm.request_list, client_list)
f787a5f5 4619 request->file_priv = NULL;
1c25595f 4620 spin_unlock(&file_priv->mm.lock);
b29c19b6 4621
2e1b8730 4622 if (!list_empty(&file_priv->rps.link)) {
8d3afd7d 4623 spin_lock(&to_i915(dev)->rps.client_lock);
2e1b8730 4624 list_del(&file_priv->rps.link);
8d3afd7d 4625 spin_unlock(&to_i915(dev)->rps.client_lock);
1854d5ca 4626 }
b29c19b6
CW
4627}
4628
4629int i915_gem_open(struct drm_device *dev, struct drm_file *file)
4630{
4631 struct drm_i915_file_private *file_priv;
e422b888 4632 int ret;
b29c19b6 4633
c4c29d7b 4634 DRM_DEBUG("\n");
b29c19b6
CW
4635
4636 file_priv = kzalloc(sizeof(*file_priv), GFP_KERNEL);
4637 if (!file_priv)
4638 return -ENOMEM;
4639
4640 file->driver_priv = file_priv;
f19ec8cb 4641 file_priv->dev_priv = to_i915(dev);
ab0e7ff9 4642 file_priv->file = file;
2e1b8730 4643 INIT_LIST_HEAD(&file_priv->rps.link);
b29c19b6
CW
4644
4645 spin_lock_init(&file_priv->mm.lock);
4646 INIT_LIST_HEAD(&file_priv->mm.request_list);
b29c19b6 4647
c80ff16e 4648 file_priv->bsd_engine = -1;
de1add36 4649
e422b888
BW
4650 ret = i915_gem_context_open(dev, file);
4651 if (ret)
4652 kfree(file_priv);
b29c19b6 4653
e422b888 4654 return ret;
b29c19b6
CW
4655}
4656
b680c37a
DV
4657/**
4658 * i915_gem_track_fb - update frontbuffer tracking
d9072a3e
GT
4659 * @old: current GEM buffer for the frontbuffer slots
4660 * @new: new GEM buffer for the frontbuffer slots
4661 * @frontbuffer_bits: bitmask of frontbuffer slots
b680c37a
DV
4662 *
4663 * This updates the frontbuffer tracking bits @frontbuffer_bits by clearing them
4664 * from @old and setting them in @new. Both @old and @new can be NULL.
4665 */
a071fa00
DV
4666void i915_gem_track_fb(struct drm_i915_gem_object *old,
4667 struct drm_i915_gem_object *new,
4668 unsigned frontbuffer_bits)
4669{
faf5bf0a
CW
4670 /* Control of individual bits within the mask are guarded by
4671 * the owning plane->mutex, i.e. we can never see concurrent
4672 * manipulation of individual bits. But since the bitfield as a whole
4673 * is updated using RMW, we need to use atomics in order to update
4674 * the bits.
4675 */
4676 BUILD_BUG_ON(INTEL_FRONTBUFFER_BITS_PER_PIPE * I915_MAX_PIPES >
4677 sizeof(atomic_t) * BITS_PER_BYTE);
4678
a071fa00 4679 if (old) {
faf5bf0a
CW
4680 WARN_ON(!(atomic_read(&old->frontbuffer_bits) & frontbuffer_bits));
4681 atomic_andnot(frontbuffer_bits, &old->frontbuffer_bits);
a071fa00
DV
4682 }
4683
4684 if (new) {
faf5bf0a
CW
4685 WARN_ON(atomic_read(&new->frontbuffer_bits) & frontbuffer_bits);
4686 atomic_or(frontbuffer_bits, &new->frontbuffer_bits);
a071fa00
DV
4687 }
4688}
4689
ea70299d
DG
4690/* Allocate a new GEM object and fill it with the supplied data */
4691struct drm_i915_gem_object *
12d79d78 4692i915_gem_object_create_from_data(struct drm_i915_private *dev_priv,
ea70299d
DG
4693 const void *data, size_t size)
4694{
4695 struct drm_i915_gem_object *obj;
4696 struct sg_table *sg;
4697 size_t bytes;
4698 int ret;
4699
12d79d78 4700 obj = i915_gem_object_create(dev_priv, round_up(size, PAGE_SIZE));
fe3db79b 4701 if (IS_ERR(obj))
ea70299d
DG
4702 return obj;
4703
4704 ret = i915_gem_object_set_to_cpu_domain(obj, true);
4705 if (ret)
4706 goto fail;
4707
a4f5ea64 4708 ret = i915_gem_object_pin_pages(obj);
ea70299d
DG
4709 if (ret)
4710 goto fail;
4711
a4f5ea64 4712 sg = obj->mm.pages;
ea70299d 4713 bytes = sg_copy_from_buffer(sg->sgl, sg->nents, (void *)data, size);
a4f5ea64 4714 obj->mm.dirty = true; /* Backing store is now out of date */
ea70299d
DG
4715 i915_gem_object_unpin_pages(obj);
4716
4717 if (WARN_ON(bytes != size)) {
4718 DRM_ERROR("Incomplete copy, wrote %zu of %zu", bytes, size);
4719 ret = -EFAULT;
4720 goto fail;
4721 }
4722
4723 return obj;
4724
4725fail:
f8c417cd 4726 i915_gem_object_put(obj);
ea70299d
DG
4727 return ERR_PTR(ret);
4728}
96d77634
CW
4729
4730struct scatterlist *
4731i915_gem_object_get_sg(struct drm_i915_gem_object *obj,
4732 unsigned int n,
4733 unsigned int *offset)
4734{
a4f5ea64 4735 struct i915_gem_object_page_iter *iter = &obj->mm.get_page;
96d77634
CW
4736 struct scatterlist *sg;
4737 unsigned int idx, count;
4738
4739 might_sleep();
4740 GEM_BUG_ON(n >= obj->base.size >> PAGE_SHIFT);
a4f5ea64 4741 GEM_BUG_ON(!i915_gem_object_has_pinned_pages(obj));
96d77634
CW
4742
4743 /* As we iterate forward through the sg, we record each entry in a
4744 * radixtree for quick repeated (backwards) lookups. If we have seen
4745 * this index previously, we will have an entry for it.
4746 *
4747 * Initial lookup is O(N), but this is amortized to O(1) for
4748 * sequential page access (where each new request is consecutive
4749 * to the previous one). Repeated lookups are O(lg(obj->base.size)),
4750 * i.e. O(1) with a large constant!
4751 */
4752 if (n < READ_ONCE(iter->sg_idx))
4753 goto lookup;
4754
4755 mutex_lock(&iter->lock);
4756
4757 /* We prefer to reuse the last sg so that repeated lookup of this
4758 * (or the subsequent) sg are fast - comparing against the last
4759 * sg is faster than going through the radixtree.
4760 */
4761
4762 sg = iter->sg_pos;
4763 idx = iter->sg_idx;
4764 count = __sg_page_count(sg);
4765
4766 while (idx + count <= n) {
4767 unsigned long exception, i;
4768 int ret;
4769
4770 /* If we cannot allocate and insert this entry, or the
4771 * individual pages from this range, cancel updating the
4772 * sg_idx so that on this lookup we are forced to linearly
4773 * scan onwards, but on future lookups we will try the
4774 * insertion again (in which case we need to be careful of
4775 * the error return reporting that we have already inserted
4776 * this index).
4777 */
4778 ret = radix_tree_insert(&iter->radix, idx, sg);
4779 if (ret && ret != -EEXIST)
4780 goto scan;
4781
4782 exception =
4783 RADIX_TREE_EXCEPTIONAL_ENTRY |
4784 idx << RADIX_TREE_EXCEPTIONAL_SHIFT;
4785 for (i = 1; i < count; i++) {
4786 ret = radix_tree_insert(&iter->radix, idx + i,
4787 (void *)exception);
4788 if (ret && ret != -EEXIST)
4789 goto scan;
4790 }
4791
4792 idx += count;
4793 sg = ____sg_next(sg);
4794 count = __sg_page_count(sg);
4795 }
4796
4797scan:
4798 iter->sg_pos = sg;
4799 iter->sg_idx = idx;
4800
4801 mutex_unlock(&iter->lock);
4802
4803 if (unlikely(n < idx)) /* insertion completed by another thread */
4804 goto lookup;
4805
4806 /* In case we failed to insert the entry into the radixtree, we need
4807 * to look beyond the current sg.
4808 */
4809 while (idx + count <= n) {
4810 idx += count;
4811 sg = ____sg_next(sg);
4812 count = __sg_page_count(sg);
4813 }
4814
4815 *offset = n - idx;
4816 return sg;
4817
4818lookup:
4819 rcu_read_lock();
4820
4821 sg = radix_tree_lookup(&iter->radix, n);
4822 GEM_BUG_ON(!sg);
4823
4824 /* If this index is in the middle of multi-page sg entry,
4825 * the radixtree will contain an exceptional entry that points
4826 * to the start of that range. We will return the pointer to
4827 * the base page and the offset of this page within the
4828 * sg entry's range.
4829 */
4830 *offset = 0;
4831 if (unlikely(radix_tree_exception(sg))) {
4832 unsigned long base =
4833 (unsigned long)sg >> RADIX_TREE_EXCEPTIONAL_SHIFT;
4834
4835 sg = radix_tree_lookup(&iter->radix, base);
4836 GEM_BUG_ON(!sg);
4837
4838 *offset = n - base;
4839 }
4840
4841 rcu_read_unlock();
4842
4843 return sg;
4844}
4845
4846struct page *
4847i915_gem_object_get_page(struct drm_i915_gem_object *obj, unsigned int n)
4848{
4849 struct scatterlist *sg;
4850 unsigned int offset;
4851
4852 GEM_BUG_ON(!i915_gem_object_has_struct_page(obj));
4853
4854 sg = i915_gem_object_get_sg(obj, n, &offset);
4855 return nth_page(sg_page(sg), offset);
4856}
4857
4858/* Like i915_gem_object_get_page(), but mark the returned page dirty */
4859struct page *
4860i915_gem_object_get_dirty_page(struct drm_i915_gem_object *obj,
4861 unsigned int n)
4862{
4863 struct page *page;
4864
4865 page = i915_gem_object_get_page(obj, n);
a4f5ea64 4866 if (!obj->mm.dirty)
96d77634
CW
4867 set_page_dirty(page);
4868
4869 return page;
4870}
4871
4872dma_addr_t
4873i915_gem_object_get_dma_address(struct drm_i915_gem_object *obj,
4874 unsigned long n)
4875{
4876 struct scatterlist *sg;
4877 unsigned int offset;
4878
4879 sg = i915_gem_object_get_sg(obj, n, &offset);
4880 return sg_dma_address(sg) + (offset << PAGE_SHIFT);
4881}