xref: /linux/drivers/gpu/drm/i915/i915_gpu_error.c (revision 9a6b55ac)
1 /*
2  * Copyright (c) 2008 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  *
23  * Authors:
24  *    Eric Anholt <eric@anholt.net>
25  *    Keith Packard <keithp@keithp.com>
26  *    Mika Kuoppala <mika.kuoppala@intel.com>
27  *
28  */
29 
30 #include <linux/ascii85.h>
31 #include <linux/nmi.h>
32 #include <linux/pagevec.h>
33 #include <linux/scatterlist.h>
34 #include <linux/utsname.h>
35 #include <linux/zlib.h>
36 
37 #include <drm/drm_print.h>
38 
39 #include "display/intel_atomic.h"
40 #include "display/intel_overlay.h"
41 
42 #include "gem/i915_gem_context.h"
43 #include "gem/i915_gem_lmem.h"
44 
45 #include "i915_drv.h"
46 #include "i915_gpu_error.h"
47 #include "i915_memcpy.h"
48 #include "i915_scatterlist.h"
49 #include "intel_csr.h"
50 
51 #define ALLOW_FAIL (GFP_KERNEL | __GFP_RETRY_MAYFAIL | __GFP_NOWARN)
52 #define ATOMIC_MAYFAIL (GFP_ATOMIC | __GFP_NOWARN)
53 
54 static void __sg_set_buf(struct scatterlist *sg,
55 			 void *addr, unsigned int len, loff_t it)
56 {
57 	sg->page_link = (unsigned long)virt_to_page(addr);
58 	sg->offset = offset_in_page(addr);
59 	sg->length = len;
60 	sg->dma_address = it;
61 }
62 
63 static bool __i915_error_grow(struct drm_i915_error_state_buf *e, size_t len)
64 {
65 	if (!len)
66 		return false;
67 
68 	if (e->bytes + len + 1 <= e->size)
69 		return true;
70 
71 	if (e->bytes) {
72 		__sg_set_buf(e->cur++, e->buf, e->bytes, e->iter);
73 		e->iter += e->bytes;
74 		e->buf = NULL;
75 		e->bytes = 0;
76 	}
77 
78 	if (e->cur == e->end) {
79 		struct scatterlist *sgl;
80 
81 		sgl = (typeof(sgl))__get_free_page(ALLOW_FAIL);
82 		if (!sgl) {
83 			e->err = -ENOMEM;
84 			return false;
85 		}
86 
87 		if (e->cur) {
88 			e->cur->offset = 0;
89 			e->cur->length = 0;
90 			e->cur->page_link =
91 				(unsigned long)sgl | SG_CHAIN;
92 		} else {
93 			e->sgl = sgl;
94 		}
95 
96 		e->cur = sgl;
97 		e->end = sgl + SG_MAX_SINGLE_ALLOC - 1;
98 	}
99 
100 	e->size = ALIGN(len + 1, SZ_64K);
101 	e->buf = kmalloc(e->size, ALLOW_FAIL);
102 	if (!e->buf) {
103 		e->size = PAGE_ALIGN(len + 1);
104 		e->buf = kmalloc(e->size, GFP_KERNEL);
105 	}
106 	if (!e->buf) {
107 		e->err = -ENOMEM;
108 		return false;
109 	}
110 
111 	return true;
112 }
113 
114 __printf(2, 0)
115 static void i915_error_vprintf(struct drm_i915_error_state_buf *e,
116 			       const char *fmt, va_list args)
117 {
118 	va_list ap;
119 	int len;
120 
121 	if (e->err)
122 		return;
123 
124 	va_copy(ap, args);
125 	len = vsnprintf(NULL, 0, fmt, ap);
126 	va_end(ap);
127 	if (len <= 0) {
128 		e->err = len;
129 		return;
130 	}
131 
132 	if (!__i915_error_grow(e, len))
133 		return;
134 
135 	GEM_BUG_ON(e->bytes >= e->size);
136 	len = vscnprintf(e->buf + e->bytes, e->size - e->bytes, fmt, args);
137 	if (len < 0) {
138 		e->err = len;
139 		return;
140 	}
141 	e->bytes += len;
142 }
143 
144 static void i915_error_puts(struct drm_i915_error_state_buf *e, const char *str)
145 {
146 	unsigned len;
147 
148 	if (e->err || !str)
149 		return;
150 
151 	len = strlen(str);
152 	if (!__i915_error_grow(e, len))
153 		return;
154 
155 	GEM_BUG_ON(e->bytes + len > e->size);
156 	memcpy(e->buf + e->bytes, str, len);
157 	e->bytes += len;
158 }
159 
160 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
161 #define err_puts(e, s) i915_error_puts(e, s)
162 
163 static void __i915_printfn_error(struct drm_printer *p, struct va_format *vaf)
164 {
165 	i915_error_vprintf(p->arg, vaf->fmt, *vaf->va);
166 }
167 
168 static inline struct drm_printer
169 i915_error_printer(struct drm_i915_error_state_buf *e)
170 {
171 	struct drm_printer p = {
172 		.printfn = __i915_printfn_error,
173 		.arg = e,
174 	};
175 	return p;
176 }
177 
178 /* single threaded page allocator with a reserved stash for emergencies */
179 static void pool_fini(struct pagevec *pv)
180 {
181 	pagevec_release(pv);
182 }
183 
184 static int pool_refill(struct pagevec *pv, gfp_t gfp)
185 {
186 	while (pagevec_space(pv)) {
187 		struct page *p;
188 
189 		p = alloc_page(gfp);
190 		if (!p)
191 			return -ENOMEM;
192 
193 		pagevec_add(pv, p);
194 	}
195 
196 	return 0;
197 }
198 
199 static int pool_init(struct pagevec *pv, gfp_t gfp)
200 {
201 	int err;
202 
203 	pagevec_init(pv);
204 
205 	err = pool_refill(pv, gfp);
206 	if (err)
207 		pool_fini(pv);
208 
209 	return err;
210 }
211 
212 static void *pool_alloc(struct pagevec *pv, gfp_t gfp)
213 {
214 	struct page *p;
215 
216 	p = alloc_page(gfp);
217 	if (!p && pagevec_count(pv))
218 		p = pv->pages[--pv->nr];
219 
220 	return p ? page_address(p) : NULL;
221 }
222 
223 static void pool_free(struct pagevec *pv, void *addr)
224 {
225 	struct page *p = virt_to_page(addr);
226 
227 	if (pagevec_space(pv))
228 		pagevec_add(pv, p);
229 	else
230 		__free_page(p);
231 }
232 
233 #ifdef CONFIG_DRM_I915_COMPRESS_ERROR
234 
235 struct compress {
236 	struct pagevec pool;
237 	struct z_stream_s zstream;
238 	void *tmp;
239 	bool wc;
240 };
241 
242 static bool compress_init(struct compress *c)
243 {
244 	struct z_stream_s *zstream = &c->zstream;
245 
246 	if (pool_init(&c->pool, ALLOW_FAIL))
247 		return false;
248 
249 	zstream->workspace =
250 		kmalloc(zlib_deflate_workspacesize(MAX_WBITS, MAX_MEM_LEVEL),
251 			ALLOW_FAIL);
252 	if (!zstream->workspace) {
253 		pool_fini(&c->pool);
254 		return false;
255 	}
256 
257 	c->tmp = NULL;
258 	if (i915_has_memcpy_from_wc())
259 		c->tmp = pool_alloc(&c->pool, ALLOW_FAIL);
260 
261 	return true;
262 }
263 
264 static bool compress_start(struct compress *c)
265 {
266 	struct z_stream_s *zstream = &c->zstream;
267 	void *workspace = zstream->workspace;
268 
269 	memset(zstream, 0, sizeof(*zstream));
270 	zstream->workspace = workspace;
271 
272 	return zlib_deflateInit(zstream, Z_DEFAULT_COMPRESSION) == Z_OK;
273 }
274 
275 static void *compress_next_page(struct compress *c,
276 				struct drm_i915_error_object *dst)
277 {
278 	void *page;
279 
280 	if (dst->page_count >= dst->num_pages)
281 		return ERR_PTR(-ENOSPC);
282 
283 	page = pool_alloc(&c->pool, ALLOW_FAIL);
284 	if (!page)
285 		return ERR_PTR(-ENOMEM);
286 
287 	return dst->pages[dst->page_count++] = page;
288 }
289 
290 static int compress_page(struct compress *c,
291 			 void *src,
292 			 struct drm_i915_error_object *dst)
293 {
294 	struct z_stream_s *zstream = &c->zstream;
295 
296 	zstream->next_in = src;
297 	if (c->wc && c->tmp && i915_memcpy_from_wc(c->tmp, src, PAGE_SIZE))
298 		zstream->next_in = c->tmp;
299 	zstream->avail_in = PAGE_SIZE;
300 
301 	do {
302 		if (zstream->avail_out == 0) {
303 			zstream->next_out = compress_next_page(c, dst);
304 			if (IS_ERR(zstream->next_out))
305 				return PTR_ERR(zstream->next_out);
306 
307 			zstream->avail_out = PAGE_SIZE;
308 		}
309 
310 		if (zlib_deflate(zstream, Z_NO_FLUSH) != Z_OK)
311 			return -EIO;
312 	} while (zstream->avail_in);
313 
314 	/* Fallback to uncompressed if we increase size? */
315 	if (0 && zstream->total_out > zstream->total_in)
316 		return -E2BIG;
317 
318 	return 0;
319 }
320 
321 static int compress_flush(struct compress *c,
322 			  struct drm_i915_error_object *dst)
323 {
324 	struct z_stream_s *zstream = &c->zstream;
325 
326 	do {
327 		switch (zlib_deflate(zstream, Z_FINISH)) {
328 		case Z_OK: /* more space requested */
329 			zstream->next_out = compress_next_page(c, dst);
330 			if (IS_ERR(zstream->next_out))
331 				return PTR_ERR(zstream->next_out);
332 
333 			zstream->avail_out = PAGE_SIZE;
334 			break;
335 
336 		case Z_STREAM_END:
337 			goto end;
338 
339 		default: /* any error */
340 			return -EIO;
341 		}
342 	} while (1);
343 
344 end:
345 	memset(zstream->next_out, 0, zstream->avail_out);
346 	dst->unused = zstream->avail_out;
347 	return 0;
348 }
349 
350 static void compress_finish(struct compress *c)
351 {
352 	zlib_deflateEnd(&c->zstream);
353 }
354 
355 static void compress_fini(struct compress *c)
356 {
357 	kfree(c->zstream.workspace);
358 	if (c->tmp)
359 		pool_free(&c->pool, c->tmp);
360 	pool_fini(&c->pool);
361 }
362 
363 static void err_compression_marker(struct drm_i915_error_state_buf *m)
364 {
365 	err_puts(m, ":");
366 }
367 
368 #else
369 
370 struct compress {
371 	struct pagevec pool;
372 	bool wc;
373 };
374 
375 static bool compress_init(struct compress *c)
376 {
377 	return pool_init(&c->pool, ALLOW_FAIL) == 0;
378 }
379 
380 static bool compress_start(struct compress *c)
381 {
382 	return true;
383 }
384 
385 static int compress_page(struct compress *c,
386 			 void *src,
387 			 struct drm_i915_error_object *dst)
388 {
389 	void *ptr;
390 
391 	ptr = pool_alloc(&c->pool, ALLOW_FAIL);
392 	if (!ptr)
393 		return -ENOMEM;
394 
395 	if (!(c->wc && i915_memcpy_from_wc(ptr, src, PAGE_SIZE)))
396 		memcpy(ptr, src, PAGE_SIZE);
397 	dst->pages[dst->page_count++] = ptr;
398 
399 	return 0;
400 }
401 
402 static int compress_flush(struct compress *c,
403 			  struct drm_i915_error_object *dst)
404 {
405 	return 0;
406 }
407 
408 static void compress_finish(struct compress *c)
409 {
410 }
411 
412 static void compress_fini(struct compress *c)
413 {
414 	pool_fini(&c->pool);
415 }
416 
417 static void err_compression_marker(struct drm_i915_error_state_buf *m)
418 {
419 	err_puts(m, "~");
420 }
421 
422 #endif
423 
424 static void error_print_instdone(struct drm_i915_error_state_buf *m,
425 				 const struct drm_i915_error_engine *ee)
426 {
427 	const struct sseu_dev_info *sseu = &RUNTIME_INFO(m->i915)->sseu;
428 	int slice;
429 	int subslice;
430 
431 	err_printf(m, "  INSTDONE: 0x%08x\n",
432 		   ee->instdone.instdone);
433 
434 	if (ee->engine->class != RENDER_CLASS || INTEL_GEN(m->i915) <= 3)
435 		return;
436 
437 	err_printf(m, "  SC_INSTDONE: 0x%08x\n",
438 		   ee->instdone.slice_common);
439 
440 	if (INTEL_GEN(m->i915) <= 6)
441 		return;
442 
443 	for_each_instdone_slice_subslice(m->i915, sseu, slice, subslice)
444 		err_printf(m, "  SAMPLER_INSTDONE[%d][%d]: 0x%08x\n",
445 			   slice, subslice,
446 			   ee->instdone.sampler[slice][subslice]);
447 
448 	for_each_instdone_slice_subslice(m->i915, sseu, slice, subslice)
449 		err_printf(m, "  ROW_INSTDONE[%d][%d]: 0x%08x\n",
450 			   slice, subslice,
451 			   ee->instdone.row[slice][subslice]);
452 }
453 
454 static void error_print_request(struct drm_i915_error_state_buf *m,
455 				const char *prefix,
456 				const struct drm_i915_error_request *erq,
457 				const unsigned long epoch)
458 {
459 	if (!erq->seqno)
460 		return;
461 
462 	err_printf(m, "%s pid %d, seqno %8x:%08x%s%s, prio %d, emitted %dms, start %08x, head %08x, tail %08x\n",
463 		   prefix, erq->pid, erq->context, erq->seqno,
464 		   test_bit(DMA_FENCE_FLAG_SIGNALED_BIT,
465 			    &erq->flags) ? "!" : "",
466 		   test_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT,
467 			    &erq->flags) ? "+" : "",
468 		   erq->sched_attr.priority,
469 		   jiffies_to_msecs(erq->jiffies - epoch),
470 		   erq->start, erq->head, erq->tail);
471 }
472 
473 static void error_print_context(struct drm_i915_error_state_buf *m,
474 				const char *header,
475 				const struct drm_i915_error_context *ctx)
476 {
477 	err_printf(m, "%s%s[%d] prio %d, guilty %d active %d\n",
478 		   header, ctx->comm, ctx->pid, ctx->sched_attr.priority,
479 		   ctx->guilty, ctx->active);
480 }
481 
482 static void error_print_engine(struct drm_i915_error_state_buf *m,
483 			       const struct drm_i915_error_engine *ee,
484 			       const unsigned long epoch)
485 {
486 	int n;
487 
488 	err_printf(m, "%s command stream:\n", ee->engine->name);
489 	err_printf(m, "  IDLE?: %s\n", yesno(ee->idle));
490 	err_printf(m, "  START: 0x%08x\n", ee->start);
491 	err_printf(m, "  HEAD:  0x%08x [0x%08x]\n", ee->head, ee->rq_head);
492 	err_printf(m, "  TAIL:  0x%08x [0x%08x, 0x%08x]\n",
493 		   ee->tail, ee->rq_post, ee->rq_tail);
494 	err_printf(m, "  CTL:   0x%08x\n", ee->ctl);
495 	err_printf(m, "  MODE:  0x%08x\n", ee->mode);
496 	err_printf(m, "  HWS:   0x%08x\n", ee->hws);
497 	err_printf(m, "  ACTHD: 0x%08x %08x\n",
498 		   (u32)(ee->acthd>>32), (u32)ee->acthd);
499 	err_printf(m, "  IPEIR: 0x%08x\n", ee->ipeir);
500 	err_printf(m, "  IPEHR: 0x%08x\n", ee->ipehr);
501 
502 	error_print_instdone(m, ee);
503 
504 	if (ee->batchbuffer) {
505 		u64 start = ee->batchbuffer->gtt_offset;
506 		u64 end = start + ee->batchbuffer->gtt_size;
507 
508 		err_printf(m, "  batch: [0x%08x_%08x, 0x%08x_%08x]\n",
509 			   upper_32_bits(start), lower_32_bits(start),
510 			   upper_32_bits(end), lower_32_bits(end));
511 	}
512 	if (INTEL_GEN(m->i915) >= 4) {
513 		err_printf(m, "  BBADDR: 0x%08x_%08x\n",
514 			   (u32)(ee->bbaddr>>32), (u32)ee->bbaddr);
515 		err_printf(m, "  BB_STATE: 0x%08x\n", ee->bbstate);
516 		err_printf(m, "  INSTPS: 0x%08x\n", ee->instps);
517 	}
518 	err_printf(m, "  INSTPM: 0x%08x\n", ee->instpm);
519 	err_printf(m, "  FADDR: 0x%08x %08x\n", upper_32_bits(ee->faddr),
520 		   lower_32_bits(ee->faddr));
521 	if (INTEL_GEN(m->i915) >= 6) {
522 		err_printf(m, "  RC PSMI: 0x%08x\n", ee->rc_psmi);
523 		err_printf(m, "  FAULT_REG: 0x%08x\n", ee->fault_reg);
524 	}
525 	if (HAS_PPGTT(m->i915)) {
526 		err_printf(m, "  GFX_MODE: 0x%08x\n", ee->vm_info.gfx_mode);
527 
528 		if (INTEL_GEN(m->i915) >= 8) {
529 			int i;
530 			for (i = 0; i < 4; i++)
531 				err_printf(m, "  PDP%d: 0x%016llx\n",
532 					   i, ee->vm_info.pdp[i]);
533 		} else {
534 			err_printf(m, "  PP_DIR_BASE: 0x%08x\n",
535 				   ee->vm_info.pp_dir_base);
536 		}
537 	}
538 	err_printf(m, "  ring->head: 0x%08x\n", ee->cpu_ring_head);
539 	err_printf(m, "  ring->tail: 0x%08x\n", ee->cpu_ring_tail);
540 	err_printf(m, "  engine reset count: %u\n", ee->reset_count);
541 
542 	for (n = 0; n < ee->num_ports; n++) {
543 		err_printf(m, "  ELSP[%d]:", n);
544 		error_print_request(m, " ", &ee->execlist[n], epoch);
545 	}
546 
547 	error_print_context(m, "  Active context: ", &ee->context);
548 }
549 
550 void i915_error_printf(struct drm_i915_error_state_buf *e, const char *f, ...)
551 {
552 	va_list args;
553 
554 	va_start(args, f);
555 	i915_error_vprintf(e, f, args);
556 	va_end(args);
557 }
558 
559 static void print_error_obj(struct drm_i915_error_state_buf *m,
560 			    const struct intel_engine_cs *engine,
561 			    const char *name,
562 			    const struct drm_i915_error_object *obj)
563 {
564 	char out[ASCII85_BUFSZ];
565 	int page;
566 
567 	if (!obj)
568 		return;
569 
570 	if (name) {
571 		err_printf(m, "%s --- %s = 0x%08x %08x\n",
572 			   engine ? engine->name : "global", name,
573 			   upper_32_bits(obj->gtt_offset),
574 			   lower_32_bits(obj->gtt_offset));
575 	}
576 
577 	if (obj->gtt_page_sizes > I915_GTT_PAGE_SIZE_4K)
578 		err_printf(m, "gtt_page_sizes = 0x%08x\n", obj->gtt_page_sizes);
579 
580 	err_compression_marker(m);
581 	for (page = 0; page < obj->page_count; page++) {
582 		int i, len;
583 
584 		len = PAGE_SIZE;
585 		if (page == obj->page_count - 1)
586 			len -= obj->unused;
587 		len = ascii85_encode_len(len);
588 
589 		for (i = 0; i < len; i++)
590 			err_puts(m, ascii85_encode(obj->pages[page][i], out));
591 	}
592 	err_puts(m, "\n");
593 }
594 
595 static void err_print_capabilities(struct drm_i915_error_state_buf *m,
596 				   const struct intel_device_info *info,
597 				   const struct intel_runtime_info *runtime,
598 				   const struct intel_driver_caps *caps)
599 {
600 	struct drm_printer p = i915_error_printer(m);
601 
602 	intel_device_info_dump_flags(info, &p);
603 	intel_driver_caps_print(caps, &p);
604 	intel_device_info_dump_topology(&runtime->sseu, &p);
605 }
606 
607 static void err_print_params(struct drm_i915_error_state_buf *m,
608 			     const struct i915_params *params)
609 {
610 	struct drm_printer p = i915_error_printer(m);
611 
612 	i915_params_dump(params, &p);
613 }
614 
615 static void err_print_pciid(struct drm_i915_error_state_buf *m,
616 			    struct drm_i915_private *i915)
617 {
618 	struct pci_dev *pdev = i915->drm.pdev;
619 
620 	err_printf(m, "PCI ID: 0x%04x\n", pdev->device);
621 	err_printf(m, "PCI Revision: 0x%02x\n", pdev->revision);
622 	err_printf(m, "PCI Subsystem: %04x:%04x\n",
623 		   pdev->subsystem_vendor,
624 		   pdev->subsystem_device);
625 }
626 
627 static void err_print_uc(struct drm_i915_error_state_buf *m,
628 			 const struct i915_error_uc *error_uc)
629 {
630 	struct drm_printer p = i915_error_printer(m);
631 	const struct i915_gpu_state *error =
632 		container_of(error_uc, typeof(*error), uc);
633 
634 	if (!error->device_info.has_gt_uc)
635 		return;
636 
637 	intel_uc_fw_dump(&error_uc->guc_fw, &p);
638 	intel_uc_fw_dump(&error_uc->huc_fw, &p);
639 	print_error_obj(m, NULL, "GuC log buffer", error_uc->guc_log);
640 }
641 
642 static void err_free_sgl(struct scatterlist *sgl)
643 {
644 	while (sgl) {
645 		struct scatterlist *sg;
646 
647 		for (sg = sgl; !sg_is_chain(sg); sg++) {
648 			kfree(sg_virt(sg));
649 			if (sg_is_last(sg))
650 				break;
651 		}
652 
653 		sg = sg_is_last(sg) ? NULL : sg_chain_ptr(sg);
654 		free_page((unsigned long)sgl);
655 		sgl = sg;
656 	}
657 }
658 
659 static void __err_print_to_sgl(struct drm_i915_error_state_buf *m,
660 			       struct i915_gpu_state *error)
661 {
662 	const struct drm_i915_error_engine *ee;
663 	struct timespec64 ts;
664 	int i, j;
665 
666 	if (*error->error_msg)
667 		err_printf(m, "%s\n", error->error_msg);
668 	err_printf(m, "Kernel: %s %s\n",
669 		   init_utsname()->release,
670 		   init_utsname()->machine);
671 	err_printf(m, "Driver: %s\n", DRIVER_DATE);
672 	ts = ktime_to_timespec64(error->time);
673 	err_printf(m, "Time: %lld s %ld us\n",
674 		   (s64)ts.tv_sec, ts.tv_nsec / NSEC_PER_USEC);
675 	ts = ktime_to_timespec64(error->boottime);
676 	err_printf(m, "Boottime: %lld s %ld us\n",
677 		   (s64)ts.tv_sec, ts.tv_nsec / NSEC_PER_USEC);
678 	ts = ktime_to_timespec64(error->uptime);
679 	err_printf(m, "Uptime: %lld s %ld us\n",
680 		   (s64)ts.tv_sec, ts.tv_nsec / NSEC_PER_USEC);
681 	err_printf(m, "Capture: %lu jiffies; %d ms ago\n",
682 		   error->capture, jiffies_to_msecs(jiffies - error->capture));
683 
684 	for (ee = error->engine; ee; ee = ee->next)
685 		err_printf(m, "Active process (on ring %s): %s [%d]\n",
686 			   ee->engine->name,
687 			   ee->context.comm,
688 			   ee->context.pid);
689 
690 	err_printf(m, "Reset count: %u\n", error->reset_count);
691 	err_printf(m, "Suspend count: %u\n", error->suspend_count);
692 	err_printf(m, "Platform: %s\n", intel_platform_name(error->device_info.platform));
693 	err_printf(m, "Subplatform: 0x%x\n",
694 		   intel_subplatform(&error->runtime_info,
695 				     error->device_info.platform));
696 	err_print_pciid(m, m->i915);
697 
698 	err_printf(m, "IOMMU enabled?: %d\n", error->iommu);
699 
700 	if (HAS_CSR(m->i915)) {
701 		struct intel_csr *csr = &m->i915->csr;
702 
703 		err_printf(m, "DMC loaded: %s\n",
704 			   yesno(csr->dmc_payload != NULL));
705 		err_printf(m, "DMC fw version: %d.%d\n",
706 			   CSR_VERSION_MAJOR(csr->version),
707 			   CSR_VERSION_MINOR(csr->version));
708 	}
709 
710 	err_printf(m, "GT awake: %s\n", yesno(error->awake));
711 	err_printf(m, "RPM wakelock: %s\n", yesno(error->wakelock));
712 	err_printf(m, "PM suspended: %s\n", yesno(error->suspended));
713 	err_printf(m, "EIR: 0x%08x\n", error->eir);
714 	err_printf(m, "IER: 0x%08x\n", error->ier);
715 	for (i = 0; i < error->ngtier; i++)
716 		err_printf(m, "GTIER[%d]: 0x%08x\n", i, error->gtier[i]);
717 	err_printf(m, "PGTBL_ER: 0x%08x\n", error->pgtbl_er);
718 	err_printf(m, "FORCEWAKE: 0x%08x\n", error->forcewake);
719 	err_printf(m, "DERRMR: 0x%08x\n", error->derrmr);
720 	err_printf(m, "CCID: 0x%08x\n", error->ccid);
721 
722 	for (i = 0; i < error->nfence; i++)
723 		err_printf(m, "  fence[%d] = %08llx\n", i, error->fence[i]);
724 
725 	if (IS_GEN_RANGE(m->i915, 6, 11)) {
726 		err_printf(m, "ERROR: 0x%08x\n", error->error);
727 		err_printf(m, "DONE_REG: 0x%08x\n", error->done_reg);
728 	}
729 
730 	if (INTEL_GEN(m->i915) >= 8)
731 		err_printf(m, "FAULT_TLB_DATA: 0x%08x 0x%08x\n",
732 			   error->fault_data1, error->fault_data0);
733 
734 	if (IS_GEN(m->i915, 7))
735 		err_printf(m, "ERR_INT: 0x%08x\n", error->err_int);
736 
737 	if (IS_GEN_RANGE(m->i915, 8, 11))
738 		err_printf(m, "GTT_CACHE_EN: 0x%08x\n", error->gtt_cache);
739 
740 	if (IS_GEN(m->i915, 12))
741 		err_printf(m, "AUX_ERR_DBG: 0x%08x\n", error->aux_err);
742 
743 	if (INTEL_GEN(m->i915) >= 12) {
744 		int i;
745 
746 		for (i = 0; i < GEN12_SFC_DONE_MAX; i++)
747 			err_printf(m, "  SFC_DONE[%d]: 0x%08x\n", i,
748 				   error->sfc_done[i]);
749 
750 		err_printf(m, "  GAM_DONE: 0x%08x\n", error->gam_done);
751 	}
752 
753 	for (ee = error->engine; ee; ee = ee->next)
754 		error_print_engine(m, ee, error->capture);
755 
756 	for (ee = error->engine; ee; ee = ee->next) {
757 		const struct drm_i915_error_object *obj;
758 
759 		obj = ee->batchbuffer;
760 		if (obj) {
761 			err_puts(m, ee->engine->name);
762 			if (ee->context.pid)
763 				err_printf(m, " (submitted by %s [%d])",
764 					   ee->context.comm,
765 					   ee->context.pid);
766 			err_printf(m, " --- gtt_offset = 0x%08x %08x\n",
767 				   upper_32_bits(obj->gtt_offset),
768 				   lower_32_bits(obj->gtt_offset));
769 			print_error_obj(m, ee->engine, NULL, obj);
770 		}
771 
772 		for (j = 0; j < ee->user_bo_count; j++)
773 			print_error_obj(m, ee->engine, "user", ee->user_bo[j]);
774 
775 		if (ee->num_requests) {
776 			err_printf(m, "%s --- %d requests\n",
777 				   ee->engine->name,
778 				   ee->num_requests);
779 			for (j = 0; j < ee->num_requests; j++)
780 				error_print_request(m, " ",
781 						    &ee->requests[j],
782 						    error->capture);
783 		}
784 
785 		print_error_obj(m, ee->engine, "ringbuffer", ee->ringbuffer);
786 		print_error_obj(m, ee->engine, "HW Status", ee->hws_page);
787 		print_error_obj(m, ee->engine, "HW context", ee->ctx);
788 		print_error_obj(m, ee->engine, "WA context", ee->wa_ctx);
789 		print_error_obj(m, ee->engine,
790 				"WA batchbuffer", ee->wa_batchbuffer);
791 		print_error_obj(m, ee->engine,
792 				"NULL context", ee->default_state);
793 	}
794 
795 	if (error->overlay)
796 		intel_overlay_print_error_state(m, error->overlay);
797 
798 	if (error->display)
799 		intel_display_print_error_state(m, error->display);
800 
801 	err_print_capabilities(m, &error->device_info, &error->runtime_info,
802 			       &error->driver_caps);
803 	err_print_params(m, &error->params);
804 	err_print_uc(m, &error->uc);
805 }
806 
807 static int err_print_to_sgl(struct i915_gpu_state *error)
808 {
809 	struct drm_i915_error_state_buf m;
810 
811 	if (IS_ERR(error))
812 		return PTR_ERR(error);
813 
814 	if (READ_ONCE(error->sgl))
815 		return 0;
816 
817 	memset(&m, 0, sizeof(m));
818 	m.i915 = error->i915;
819 
820 	__err_print_to_sgl(&m, error);
821 
822 	if (m.buf) {
823 		__sg_set_buf(m.cur++, m.buf, m.bytes, m.iter);
824 		m.bytes = 0;
825 		m.buf = NULL;
826 	}
827 	if (m.cur) {
828 		GEM_BUG_ON(m.end < m.cur);
829 		sg_mark_end(m.cur - 1);
830 	}
831 	GEM_BUG_ON(m.sgl && !m.cur);
832 
833 	if (m.err) {
834 		err_free_sgl(m.sgl);
835 		return m.err;
836 	}
837 
838 	if (cmpxchg(&error->sgl, NULL, m.sgl))
839 		err_free_sgl(m.sgl);
840 
841 	return 0;
842 }
843 
844 ssize_t i915_gpu_state_copy_to_buffer(struct i915_gpu_state *error,
845 				      char *buf, loff_t off, size_t rem)
846 {
847 	struct scatterlist *sg;
848 	size_t count;
849 	loff_t pos;
850 	int err;
851 
852 	if (!error || !rem)
853 		return 0;
854 
855 	err = err_print_to_sgl(error);
856 	if (err)
857 		return err;
858 
859 	sg = READ_ONCE(error->fit);
860 	if (!sg || off < sg->dma_address)
861 		sg = error->sgl;
862 	if (!sg)
863 		return 0;
864 
865 	pos = sg->dma_address;
866 	count = 0;
867 	do {
868 		size_t len, start;
869 
870 		if (sg_is_chain(sg)) {
871 			sg = sg_chain_ptr(sg);
872 			GEM_BUG_ON(sg_is_chain(sg));
873 		}
874 
875 		len = sg->length;
876 		if (pos + len <= off) {
877 			pos += len;
878 			continue;
879 		}
880 
881 		start = sg->offset;
882 		if (pos < off) {
883 			GEM_BUG_ON(off - pos > len);
884 			len -= off - pos;
885 			start += off - pos;
886 			pos = off;
887 		}
888 
889 		len = min(len, rem);
890 		GEM_BUG_ON(!len || len > sg->length);
891 
892 		memcpy(buf, page_address(sg_page(sg)) + start, len);
893 
894 		count += len;
895 		pos += len;
896 
897 		buf += len;
898 		rem -= len;
899 		if (!rem) {
900 			WRITE_ONCE(error->fit, sg);
901 			break;
902 		}
903 	} while (!sg_is_last(sg++));
904 
905 	return count;
906 }
907 
908 static void i915_error_object_free(struct drm_i915_error_object *obj)
909 {
910 	int page;
911 
912 	if (obj == NULL)
913 		return;
914 
915 	for (page = 0; page < obj->page_count; page++)
916 		free_page((unsigned long)obj->pages[page]);
917 
918 	kfree(obj);
919 }
920 
921 
922 static void cleanup_params(struct i915_gpu_state *error)
923 {
924 	i915_params_free(&error->params);
925 }
926 
927 static void cleanup_uc_state(struct i915_gpu_state *error)
928 {
929 	struct i915_error_uc *error_uc = &error->uc;
930 
931 	kfree(error_uc->guc_fw.path);
932 	kfree(error_uc->huc_fw.path);
933 	i915_error_object_free(error_uc->guc_log);
934 }
935 
936 void __i915_gpu_state_free(struct kref *error_ref)
937 {
938 	struct i915_gpu_state *error =
939 		container_of(error_ref, typeof(*error), ref);
940 	long i;
941 
942 	while (error->engine) {
943 		struct drm_i915_error_engine *ee = error->engine;
944 
945 		error->engine = ee->next;
946 
947 		for (i = 0; i < ee->user_bo_count; i++)
948 			i915_error_object_free(ee->user_bo[i]);
949 		kfree(ee->user_bo);
950 
951 		i915_error_object_free(ee->batchbuffer);
952 		i915_error_object_free(ee->wa_batchbuffer);
953 		i915_error_object_free(ee->ringbuffer);
954 		i915_error_object_free(ee->hws_page);
955 		i915_error_object_free(ee->ctx);
956 		i915_error_object_free(ee->wa_ctx);
957 
958 		kfree(ee->requests);
959 		kfree(ee);
960 	}
961 
962 	kfree(error->overlay);
963 	kfree(error->display);
964 
965 	cleanup_params(error);
966 	cleanup_uc_state(error);
967 
968 	err_free_sgl(error->sgl);
969 	kfree(error);
970 }
971 
972 static struct drm_i915_error_object *
973 i915_error_object_create(struct drm_i915_private *i915,
974 			 struct i915_vma *vma,
975 			 struct compress *compress)
976 {
977 	struct i915_ggtt *ggtt = &i915->ggtt;
978 	const u64 slot = ggtt->error_capture.start;
979 	struct drm_i915_error_object *dst;
980 	unsigned long num_pages;
981 	struct sgt_iter iter;
982 	int ret;
983 
984 	might_sleep();
985 
986 	if (!vma || !vma->pages)
987 		return NULL;
988 
989 	num_pages = min_t(u64, vma->size, vma->obj->base.size) >> PAGE_SHIFT;
990 	num_pages = DIV_ROUND_UP(10 * num_pages, 8); /* worstcase zlib growth */
991 	dst = kmalloc(sizeof(*dst) + num_pages * sizeof(u32 *), ALLOW_FAIL);
992 	if (!dst)
993 		return NULL;
994 
995 	if (!compress_start(compress)) {
996 		kfree(dst);
997 		return NULL;
998 	}
999 
1000 	dst->gtt_offset = vma->node.start;
1001 	dst->gtt_size = vma->node.size;
1002 	dst->gtt_page_sizes = vma->page_sizes.gtt;
1003 	dst->num_pages = num_pages;
1004 	dst->page_count = 0;
1005 	dst->unused = 0;
1006 
1007 	compress->wc = i915_gem_object_is_lmem(vma->obj) ||
1008 		       drm_mm_node_allocated(&ggtt->error_capture);
1009 
1010 	ret = -EINVAL;
1011 	if (drm_mm_node_allocated(&ggtt->error_capture)) {
1012 		void __iomem *s;
1013 		dma_addr_t dma;
1014 
1015 		for_each_sgt_daddr(dma, iter, vma->pages) {
1016 			ggtt->vm.insert_page(&ggtt->vm, dma, slot,
1017 					     I915_CACHE_NONE, 0);
1018 
1019 			s = io_mapping_map_wc(&ggtt->iomap, slot, PAGE_SIZE);
1020 			ret = compress_page(compress, (void  __force *)s, dst);
1021 			io_mapping_unmap(s);
1022 			if (ret)
1023 				break;
1024 		}
1025 	} else if (i915_gem_object_is_lmem(vma->obj)) {
1026 		struct intel_memory_region *mem = vma->obj->mm.region;
1027 		dma_addr_t dma;
1028 
1029 		for_each_sgt_daddr(dma, iter, vma->pages) {
1030 			void __iomem *s;
1031 
1032 			s = io_mapping_map_wc(&mem->iomap, dma, PAGE_SIZE);
1033 			ret = compress_page(compress, (void __force *)s, dst);
1034 			io_mapping_unmap(s);
1035 			if (ret)
1036 				break;
1037 		}
1038 	} else {
1039 		struct page *page;
1040 
1041 		for_each_sgt_page(page, iter, vma->pages) {
1042 			void *s;
1043 
1044 			drm_clflush_pages(&page, 1);
1045 
1046 			s = kmap(page);
1047 			ret = compress_page(compress, s, dst);
1048 			kunmap(s);
1049 
1050 			drm_clflush_pages(&page, 1);
1051 
1052 			if (ret)
1053 				break;
1054 		}
1055 	}
1056 
1057 	if (ret || compress_flush(compress, dst)) {
1058 		while (dst->page_count--)
1059 			pool_free(&compress->pool, dst->pages[dst->page_count]);
1060 		kfree(dst);
1061 		dst = NULL;
1062 	}
1063 	compress_finish(compress);
1064 
1065 	return dst;
1066 }
1067 
1068 /*
1069  * Generate a semi-unique error code. The code is not meant to have meaning, The
1070  * code's only purpose is to try to prevent false duplicated bug reports by
1071  * grossly estimating a GPU error state.
1072  *
1073  * TODO Ideally, hashing the batchbuffer would be a very nice way to determine
1074  * the hang if we could strip the GTT offset information from it.
1075  *
1076  * It's only a small step better than a random number in its current form.
1077  */
1078 static u32 i915_error_generate_code(struct i915_gpu_state *error)
1079 {
1080 	const struct drm_i915_error_engine *ee = error->engine;
1081 
1082 	/*
1083 	 * IPEHR would be an ideal way to detect errors, as it's the gross
1084 	 * measure of "the command that hung." However, has some very common
1085 	 * synchronization commands which almost always appear in the case
1086 	 * strictly a client bug. Use instdone to differentiate those some.
1087 	 */
1088 	return ee ? ee->ipehr ^ ee->instdone.instdone : 0;
1089 }
1090 
1091 static void gem_record_fences(struct i915_gpu_state *error)
1092 {
1093 	struct drm_i915_private *dev_priv = error->i915;
1094 	struct intel_uncore *uncore = &dev_priv->uncore;
1095 	int i;
1096 
1097 	if (INTEL_GEN(dev_priv) >= 6) {
1098 		for (i = 0; i < dev_priv->ggtt.num_fences; i++)
1099 			error->fence[i] =
1100 				intel_uncore_read64(uncore,
1101 						    FENCE_REG_GEN6_LO(i));
1102 	} else if (INTEL_GEN(dev_priv) >= 4) {
1103 		for (i = 0; i < dev_priv->ggtt.num_fences; i++)
1104 			error->fence[i] =
1105 				intel_uncore_read64(uncore,
1106 						    FENCE_REG_965_LO(i));
1107 	} else {
1108 		for (i = 0; i < dev_priv->ggtt.num_fences; i++)
1109 			error->fence[i] =
1110 				intel_uncore_read(uncore, FENCE_REG(i));
1111 	}
1112 	error->nfence = i;
1113 }
1114 
1115 static void error_record_engine_registers(struct i915_gpu_state *error,
1116 					  struct intel_engine_cs *engine,
1117 					  struct drm_i915_error_engine *ee)
1118 {
1119 	struct drm_i915_private *dev_priv = engine->i915;
1120 
1121 	if (INTEL_GEN(dev_priv) >= 6) {
1122 		ee->rc_psmi = ENGINE_READ(engine, RING_PSMI_CTL);
1123 
1124 		if (INTEL_GEN(dev_priv) >= 12)
1125 			ee->fault_reg = I915_READ(GEN12_RING_FAULT_REG);
1126 		else if (INTEL_GEN(dev_priv) >= 8)
1127 			ee->fault_reg = I915_READ(GEN8_RING_FAULT_REG);
1128 		else
1129 			ee->fault_reg = GEN6_RING_FAULT_REG_READ(engine);
1130 	}
1131 
1132 	if (INTEL_GEN(dev_priv) >= 4) {
1133 		ee->faddr = ENGINE_READ(engine, RING_DMA_FADD);
1134 		ee->ipeir = ENGINE_READ(engine, RING_IPEIR);
1135 		ee->ipehr = ENGINE_READ(engine, RING_IPEHR);
1136 		ee->instps = ENGINE_READ(engine, RING_INSTPS);
1137 		ee->bbaddr = ENGINE_READ(engine, RING_BBADDR);
1138 		if (INTEL_GEN(dev_priv) >= 8) {
1139 			ee->faddr |= (u64)ENGINE_READ(engine, RING_DMA_FADD_UDW) << 32;
1140 			ee->bbaddr |= (u64)ENGINE_READ(engine, RING_BBADDR_UDW) << 32;
1141 		}
1142 		ee->bbstate = ENGINE_READ(engine, RING_BBSTATE);
1143 	} else {
1144 		ee->faddr = ENGINE_READ(engine, DMA_FADD_I8XX);
1145 		ee->ipeir = ENGINE_READ(engine, IPEIR);
1146 		ee->ipehr = ENGINE_READ(engine, IPEHR);
1147 	}
1148 
1149 	intel_engine_get_instdone(engine, &ee->instdone);
1150 
1151 	ee->instpm = ENGINE_READ(engine, RING_INSTPM);
1152 	ee->acthd = intel_engine_get_active_head(engine);
1153 	ee->start = ENGINE_READ(engine, RING_START);
1154 	ee->head = ENGINE_READ(engine, RING_HEAD);
1155 	ee->tail = ENGINE_READ(engine, RING_TAIL);
1156 	ee->ctl = ENGINE_READ(engine, RING_CTL);
1157 	if (INTEL_GEN(dev_priv) > 2)
1158 		ee->mode = ENGINE_READ(engine, RING_MI_MODE);
1159 
1160 	if (!HWS_NEEDS_PHYSICAL(dev_priv)) {
1161 		i915_reg_t mmio;
1162 
1163 		if (IS_GEN(dev_priv, 7)) {
1164 			switch (engine->id) {
1165 			default:
1166 				MISSING_CASE(engine->id);
1167 				/* fall through */
1168 			case RCS0:
1169 				mmio = RENDER_HWS_PGA_GEN7;
1170 				break;
1171 			case BCS0:
1172 				mmio = BLT_HWS_PGA_GEN7;
1173 				break;
1174 			case VCS0:
1175 				mmio = BSD_HWS_PGA_GEN7;
1176 				break;
1177 			case VECS0:
1178 				mmio = VEBOX_HWS_PGA_GEN7;
1179 				break;
1180 			}
1181 		} else if (IS_GEN(engine->i915, 6)) {
1182 			mmio = RING_HWS_PGA_GEN6(engine->mmio_base);
1183 		} else {
1184 			/* XXX: gen8 returns to sanity */
1185 			mmio = RING_HWS_PGA(engine->mmio_base);
1186 		}
1187 
1188 		ee->hws = I915_READ(mmio);
1189 	}
1190 
1191 	ee->idle = intel_engine_is_idle(engine);
1192 	ee->reset_count = i915_reset_engine_count(&dev_priv->gpu_error,
1193 						  engine);
1194 
1195 	if (HAS_PPGTT(dev_priv)) {
1196 		int i;
1197 
1198 		ee->vm_info.gfx_mode = ENGINE_READ(engine, RING_MODE_GEN7);
1199 
1200 		if (IS_GEN(dev_priv, 6)) {
1201 			ee->vm_info.pp_dir_base =
1202 				ENGINE_READ(engine, RING_PP_DIR_BASE_READ);
1203 		} else if (IS_GEN(dev_priv, 7)) {
1204 			ee->vm_info.pp_dir_base =
1205 				ENGINE_READ(engine, RING_PP_DIR_BASE);
1206 		} else if (INTEL_GEN(dev_priv) >= 8) {
1207 			u32 base = engine->mmio_base;
1208 
1209 			for (i = 0; i < 4; i++) {
1210 				ee->vm_info.pdp[i] =
1211 					I915_READ(GEN8_RING_PDP_UDW(base, i));
1212 				ee->vm_info.pdp[i] <<= 32;
1213 				ee->vm_info.pdp[i] |=
1214 					I915_READ(GEN8_RING_PDP_LDW(base, i));
1215 			}
1216 		}
1217 	}
1218 }
1219 
1220 static void record_request(const struct i915_request *request,
1221 			   struct drm_i915_error_request *erq)
1222 {
1223 	const struct i915_gem_context *ctx = request->gem_context;
1224 
1225 	erq->flags = request->fence.flags;
1226 	erq->context = request->fence.context;
1227 	erq->seqno = request->fence.seqno;
1228 	erq->sched_attr = request->sched.attr;
1229 	erq->jiffies = request->emitted_jiffies;
1230 	erq->start = i915_ggtt_offset(request->ring->vma);
1231 	erq->head = request->head;
1232 	erq->tail = request->tail;
1233 
1234 	rcu_read_lock();
1235 	erq->pid = ctx->pid ? pid_nr(ctx->pid) : 0;
1236 	rcu_read_unlock();
1237 }
1238 
1239 static void engine_record_requests(struct intel_engine_cs *engine,
1240 				   struct i915_request *first,
1241 				   struct drm_i915_error_engine *ee)
1242 {
1243 	struct i915_request *request;
1244 	int count;
1245 
1246 	count = 0;
1247 	request = first;
1248 	list_for_each_entry_from(request, &engine->active.requests, sched.link)
1249 		count++;
1250 	if (!count)
1251 		return;
1252 
1253 	ee->requests = kcalloc(count, sizeof(*ee->requests), ATOMIC_MAYFAIL);
1254 	if (!ee->requests)
1255 		return;
1256 
1257 	ee->num_requests = count;
1258 
1259 	count = 0;
1260 	request = first;
1261 	list_for_each_entry_from(request,
1262 				 &engine->active.requests, sched.link) {
1263 		if (count >= ee->num_requests) {
1264 			/*
1265 			 * If the ring request list was changed in
1266 			 * between the point where the error request
1267 			 * list was created and dimensioned and this
1268 			 * point then just exit early to avoid crashes.
1269 			 *
1270 			 * We don't need to communicate that the
1271 			 * request list changed state during error
1272 			 * state capture and that the error state is
1273 			 * slightly incorrect as a consequence since we
1274 			 * are typically only interested in the request
1275 			 * list state at the point of error state
1276 			 * capture, not in any changes happening during
1277 			 * the capture.
1278 			 */
1279 			break;
1280 		}
1281 
1282 		record_request(request, &ee->requests[count++]);
1283 	}
1284 	ee->num_requests = count;
1285 }
1286 
1287 static void error_record_engine_execlists(const struct intel_engine_cs *engine,
1288 					  struct drm_i915_error_engine *ee)
1289 {
1290 	const struct intel_engine_execlists * const execlists = &engine->execlists;
1291 	struct i915_request * const *port = execlists->active;
1292 	unsigned int n = 0;
1293 
1294 	while (*port)
1295 		record_request(*port++, &ee->execlist[n++]);
1296 
1297 	ee->num_ports = n;
1298 }
1299 
1300 static bool record_context(struct drm_i915_error_context *e,
1301 			   const struct i915_request *rq)
1302 {
1303 	const struct i915_gem_context *ctx = rq->gem_context;
1304 
1305 	if (ctx->pid) {
1306 		struct task_struct *task;
1307 
1308 		rcu_read_lock();
1309 		task = pid_task(ctx->pid, PIDTYPE_PID);
1310 		if (task) {
1311 			strcpy(e->comm, task->comm);
1312 			e->pid = task->pid;
1313 		}
1314 		rcu_read_unlock();
1315 	}
1316 
1317 	e->sched_attr = ctx->sched;
1318 	e->guilty = atomic_read(&ctx->guilty_count);
1319 	e->active = atomic_read(&ctx->active_count);
1320 
1321 	return i915_gem_context_no_error_capture(ctx);
1322 }
1323 
1324 struct capture_vma {
1325 	struct capture_vma *next;
1326 	void **slot;
1327 };
1328 
1329 static struct capture_vma *
1330 capture_vma(struct capture_vma *next,
1331 	    struct i915_vma *vma,
1332 	    struct drm_i915_error_object **out)
1333 {
1334 	struct capture_vma *c;
1335 
1336 	*out = NULL;
1337 	if (!vma)
1338 		return next;
1339 
1340 	c = kmalloc(sizeof(*c), ATOMIC_MAYFAIL);
1341 	if (!c)
1342 		return next;
1343 
1344 	if (!i915_active_acquire_if_busy(&vma->active)) {
1345 		kfree(c);
1346 		return next;
1347 	}
1348 
1349 	c->slot = (void **)out;
1350 	*c->slot = i915_vma_get(vma);
1351 
1352 	c->next = next;
1353 	return c;
1354 }
1355 
1356 static struct capture_vma *
1357 request_record_user_bo(struct i915_request *request,
1358 		       struct drm_i915_error_engine *ee,
1359 		       struct capture_vma *capture)
1360 {
1361 	struct i915_capture_list *c;
1362 	struct drm_i915_error_object **bo;
1363 	long count, max;
1364 
1365 	max = 0;
1366 	for (c = request->capture_list; c; c = c->next)
1367 		max++;
1368 	if (!max)
1369 		return capture;
1370 
1371 	bo = kmalloc_array(max, sizeof(*bo), ATOMIC_MAYFAIL);
1372 	if (!bo) {
1373 		/* If we can't capture everything, try to capture something. */
1374 		max = min_t(long, max, PAGE_SIZE / sizeof(*bo));
1375 		bo = kmalloc_array(max, sizeof(*bo), ATOMIC_MAYFAIL);
1376 	}
1377 	if (!bo)
1378 		return capture;
1379 
1380 	count = 0;
1381 	for (c = request->capture_list; c; c = c->next) {
1382 		capture = capture_vma(capture, c->vma, &bo[count]);
1383 		if (++count == max)
1384 			break;
1385 	}
1386 
1387 	ee->user_bo = bo;
1388 	ee->user_bo_count = count;
1389 
1390 	return capture;
1391 }
1392 
1393 static struct drm_i915_error_object *
1394 capture_object(struct drm_i915_private *dev_priv,
1395 	       struct drm_i915_gem_object *obj,
1396 	       struct compress *compress)
1397 {
1398 	if (obj && i915_gem_object_has_pages(obj)) {
1399 		struct i915_vma fake = {
1400 			.node = { .start = U64_MAX, .size = obj->base.size },
1401 			.size = obj->base.size,
1402 			.pages = obj->mm.pages,
1403 			.obj = obj,
1404 		};
1405 
1406 		return i915_error_object_create(dev_priv, &fake, compress);
1407 	} else {
1408 		return NULL;
1409 	}
1410 }
1411 
1412 static void
1413 gem_record_rings(struct i915_gpu_state *error, struct compress *compress)
1414 {
1415 	struct drm_i915_private *i915 = error->i915;
1416 	struct intel_engine_cs *engine;
1417 	struct drm_i915_error_engine *ee;
1418 
1419 	ee = kzalloc(sizeof(*ee), GFP_KERNEL);
1420 	if (!ee)
1421 		return;
1422 
1423 	for_each_uabi_engine(engine, i915) {
1424 		struct capture_vma *capture = NULL;
1425 		struct i915_request *request;
1426 		unsigned long flags;
1427 
1428 		/* Refill our page pool before entering atomic section */
1429 		pool_refill(&compress->pool, ALLOW_FAIL);
1430 
1431 		spin_lock_irqsave(&engine->active.lock, flags);
1432 		request = intel_engine_find_active_request(engine);
1433 		if (!request) {
1434 			spin_unlock_irqrestore(&engine->active.lock, flags);
1435 			continue;
1436 		}
1437 
1438 		error->simulated |= record_context(&ee->context, request);
1439 
1440 		/*
1441 		 * We need to copy these to an anonymous buffer
1442 		 * as the simplest method to avoid being overwritten
1443 		 * by userspace.
1444 		 */
1445 		capture = capture_vma(capture,
1446 				      request->batch,
1447 				      &ee->batchbuffer);
1448 
1449 		if (HAS_BROKEN_CS_TLB(i915))
1450 			capture = capture_vma(capture,
1451 					      engine->gt->scratch,
1452 					      &ee->wa_batchbuffer);
1453 
1454 		capture = request_record_user_bo(request, ee, capture);
1455 
1456 		capture = capture_vma(capture,
1457 				      request->hw_context->state,
1458 				      &ee->ctx);
1459 
1460 		capture = capture_vma(capture,
1461 				      request->ring->vma,
1462 				      &ee->ringbuffer);
1463 
1464 		ee->cpu_ring_head = request->ring->head;
1465 		ee->cpu_ring_tail = request->ring->tail;
1466 
1467 		ee->rq_head = request->head;
1468 		ee->rq_post = request->postfix;
1469 		ee->rq_tail = request->tail;
1470 
1471 		engine_record_requests(engine, request, ee);
1472 		spin_unlock_irqrestore(&engine->active.lock, flags);
1473 
1474 		error_record_engine_registers(error, engine, ee);
1475 		error_record_engine_execlists(engine, ee);
1476 
1477 		while (capture) {
1478 			struct capture_vma *this = capture;
1479 			struct i915_vma *vma = *this->slot;
1480 
1481 			*this->slot =
1482 				i915_error_object_create(i915, vma, compress);
1483 
1484 			i915_active_release(&vma->active);
1485 			i915_vma_put(vma);
1486 
1487 			capture = this->next;
1488 			kfree(this);
1489 		}
1490 
1491 		ee->hws_page =
1492 			i915_error_object_create(i915,
1493 						 engine->status_page.vma,
1494 						 compress);
1495 
1496 		ee->wa_ctx =
1497 			i915_error_object_create(i915,
1498 						 engine->wa_ctx.vma,
1499 						 compress);
1500 
1501 		ee->default_state =
1502 			capture_object(i915, engine->default_state, compress);
1503 
1504 		ee->engine = engine;
1505 
1506 		ee->next = error->engine;
1507 		error->engine = ee;
1508 
1509 		ee = kzalloc(sizeof(*ee), GFP_KERNEL);
1510 		if (!ee)
1511 			return;
1512 	}
1513 
1514 	kfree(ee);
1515 }
1516 
1517 static void
1518 capture_uc_state(struct i915_gpu_state *error, struct compress *compress)
1519 {
1520 	struct drm_i915_private *i915 = error->i915;
1521 	struct i915_error_uc *error_uc = &error->uc;
1522 	struct intel_uc *uc = &i915->gt.uc;
1523 
1524 	/* Capturing uC state won't be useful if there is no GuC */
1525 	if (!error->device_info.has_gt_uc)
1526 		return;
1527 
1528 	memcpy(&error_uc->guc_fw, &uc->guc.fw, sizeof(uc->guc.fw));
1529 	memcpy(&error_uc->huc_fw, &uc->huc.fw, sizeof(uc->huc.fw));
1530 
1531 	/* Non-default firmware paths will be specified by the modparam.
1532 	 * As modparams are generally accesible from the userspace make
1533 	 * explicit copies of the firmware paths.
1534 	 */
1535 	error_uc->guc_fw.path = kstrdup(uc->guc.fw.path, ALLOW_FAIL);
1536 	error_uc->huc_fw.path = kstrdup(uc->huc.fw.path, ALLOW_FAIL);
1537 	error_uc->guc_log = i915_error_object_create(i915,
1538 						     uc->guc.log.vma,
1539 						     compress);
1540 }
1541 
1542 /* Capture all registers which don't fit into another category. */
1543 static void capture_reg_state(struct i915_gpu_state *error)
1544 {
1545 	struct drm_i915_private *i915 = error->i915;
1546 	struct intel_uncore *uncore = &i915->uncore;
1547 	int i;
1548 
1549 	/* General organization
1550 	 * 1. Registers specific to a single generation
1551 	 * 2. Registers which belong to multiple generations
1552 	 * 3. Feature specific registers.
1553 	 * 4. Everything else
1554 	 * Please try to follow the order.
1555 	 */
1556 
1557 	/* 1: Registers specific to a single generation */
1558 	if (IS_VALLEYVIEW(i915)) {
1559 		error->gtier[0] = intel_uncore_read(uncore, GTIER);
1560 		error->ier = intel_uncore_read(uncore, VLV_IER);
1561 		error->forcewake = intel_uncore_read_fw(uncore, FORCEWAKE_VLV);
1562 	}
1563 
1564 	if (IS_GEN(i915, 7))
1565 		error->err_int = intel_uncore_read(uncore, GEN7_ERR_INT);
1566 
1567 	if (INTEL_GEN(i915) >= 12) {
1568 		error->fault_data0 = intel_uncore_read(uncore,
1569 						       GEN12_FAULT_TLB_DATA0);
1570 		error->fault_data1 = intel_uncore_read(uncore,
1571 						       GEN12_FAULT_TLB_DATA1);
1572 	} else if (INTEL_GEN(i915) >= 8) {
1573 		error->fault_data0 = intel_uncore_read(uncore,
1574 						       GEN8_FAULT_TLB_DATA0);
1575 		error->fault_data1 = intel_uncore_read(uncore,
1576 						       GEN8_FAULT_TLB_DATA1);
1577 	}
1578 
1579 	if (IS_GEN(i915, 6)) {
1580 		error->forcewake = intel_uncore_read_fw(uncore, FORCEWAKE);
1581 		error->gab_ctl = intel_uncore_read(uncore, GAB_CTL);
1582 		error->gfx_mode = intel_uncore_read(uncore, GFX_MODE);
1583 	}
1584 
1585 	/* 2: Registers which belong to multiple generations */
1586 	if (INTEL_GEN(i915) >= 7)
1587 		error->forcewake = intel_uncore_read_fw(uncore, FORCEWAKE_MT);
1588 
1589 	if (INTEL_GEN(i915) >= 6) {
1590 		error->derrmr = intel_uncore_read(uncore, DERRMR);
1591 		if (INTEL_GEN(i915) < 12) {
1592 			error->error = intel_uncore_read(uncore, ERROR_GEN6);
1593 			error->done_reg = intel_uncore_read(uncore, DONE_REG);
1594 		}
1595 	}
1596 
1597 	if (INTEL_GEN(i915) >= 5)
1598 		error->ccid = intel_uncore_read(uncore, CCID(RENDER_RING_BASE));
1599 
1600 	/* 3: Feature specific registers */
1601 	if (IS_GEN_RANGE(i915, 6, 7)) {
1602 		error->gam_ecochk = intel_uncore_read(uncore, GAM_ECOCHK);
1603 		error->gac_eco = intel_uncore_read(uncore, GAC_ECO_BITS);
1604 	}
1605 
1606 	if (IS_GEN_RANGE(i915, 8, 11))
1607 		error->gtt_cache = intel_uncore_read(uncore, HSW_GTT_CACHE_EN);
1608 
1609 	if (IS_GEN(i915, 12))
1610 		error->aux_err = intel_uncore_read(uncore, GEN12_AUX_ERR_DBG);
1611 
1612 	if (INTEL_GEN(i915) >= 12) {
1613 		for (i = 0; i < GEN12_SFC_DONE_MAX; i++) {
1614 			error->sfc_done[i] =
1615 				intel_uncore_read(uncore, GEN12_SFC_DONE(i));
1616 		}
1617 
1618 		error->gam_done = intel_uncore_read(uncore, GEN12_GAM_DONE);
1619 	}
1620 
1621 	/* 4: Everything else */
1622 	if (INTEL_GEN(i915) >= 11) {
1623 		error->ier = intel_uncore_read(uncore, GEN8_DE_MISC_IER);
1624 		error->gtier[0] =
1625 			intel_uncore_read(uncore,
1626 					  GEN11_RENDER_COPY_INTR_ENABLE);
1627 		error->gtier[1] =
1628 			intel_uncore_read(uncore, GEN11_VCS_VECS_INTR_ENABLE);
1629 		error->gtier[2] =
1630 			intel_uncore_read(uncore, GEN11_GUC_SG_INTR_ENABLE);
1631 		error->gtier[3] =
1632 			intel_uncore_read(uncore,
1633 					  GEN11_GPM_WGBOXPERF_INTR_ENABLE);
1634 		error->gtier[4] =
1635 			intel_uncore_read(uncore,
1636 					  GEN11_CRYPTO_RSVD_INTR_ENABLE);
1637 		error->gtier[5] =
1638 			intel_uncore_read(uncore,
1639 					  GEN11_GUNIT_CSME_INTR_ENABLE);
1640 		error->ngtier = 6;
1641 	} else if (INTEL_GEN(i915) >= 8) {
1642 		error->ier = intel_uncore_read(uncore, GEN8_DE_MISC_IER);
1643 		for (i = 0; i < 4; i++)
1644 			error->gtier[i] = intel_uncore_read(uncore,
1645 							    GEN8_GT_IER(i));
1646 		error->ngtier = 4;
1647 	} else if (HAS_PCH_SPLIT(i915)) {
1648 		error->ier = intel_uncore_read(uncore, DEIER);
1649 		error->gtier[0] = intel_uncore_read(uncore, GTIER);
1650 		error->ngtier = 1;
1651 	} else if (IS_GEN(i915, 2)) {
1652 		error->ier = intel_uncore_read16(uncore, GEN2_IER);
1653 	} else if (!IS_VALLEYVIEW(i915)) {
1654 		error->ier = intel_uncore_read(uncore, GEN2_IER);
1655 	}
1656 	error->eir = intel_uncore_read(uncore, EIR);
1657 	error->pgtbl_er = intel_uncore_read(uncore, PGTBL_ER);
1658 }
1659 
1660 static const char *
1661 error_msg(struct i915_gpu_state *error,
1662 	  intel_engine_mask_t engines, const char *msg)
1663 {
1664 	int len;
1665 
1666 	len = scnprintf(error->error_msg, sizeof(error->error_msg),
1667 			"GPU HANG: ecode %d:%x:0x%08x",
1668 			INTEL_GEN(error->i915), engines,
1669 			i915_error_generate_code(error));
1670 	if (error->engine) {
1671 		/* Just show the first executing process, more is confusing */
1672 		len += scnprintf(error->error_msg + len,
1673 				 sizeof(error->error_msg) - len,
1674 				 ", in %s [%d]",
1675 				 error->engine->context.comm,
1676 				 error->engine->context.pid);
1677 	}
1678 	if (msg)
1679 		len += scnprintf(error->error_msg + len,
1680 				 sizeof(error->error_msg) - len,
1681 				 ", %s", msg);
1682 
1683 	return error->error_msg;
1684 }
1685 
1686 static void capture_gen_state(struct i915_gpu_state *error)
1687 {
1688 	struct drm_i915_private *i915 = error->i915;
1689 
1690 	error->awake = i915->gt.awake;
1691 	error->wakelock = atomic_read(&i915->runtime_pm.wakeref_count);
1692 	error->suspended = i915->runtime_pm.suspended;
1693 
1694 	error->iommu = -1;
1695 #ifdef CONFIG_INTEL_IOMMU
1696 	error->iommu = intel_iommu_gfx_mapped;
1697 #endif
1698 	error->reset_count = i915_reset_count(&i915->gpu_error);
1699 	error->suspend_count = i915->suspend_count;
1700 
1701 	memcpy(&error->device_info,
1702 	       INTEL_INFO(i915),
1703 	       sizeof(error->device_info));
1704 	memcpy(&error->runtime_info,
1705 	       RUNTIME_INFO(i915),
1706 	       sizeof(error->runtime_info));
1707 	error->driver_caps = i915->caps;
1708 }
1709 
1710 static void capture_params(struct i915_gpu_state *error)
1711 {
1712 	i915_params_copy(&error->params, &i915_modparams);
1713 }
1714 
1715 static void capture_finish(struct i915_gpu_state *error)
1716 {
1717 	struct i915_ggtt *ggtt = &error->i915->ggtt;
1718 
1719 	if (drm_mm_node_allocated(&ggtt->error_capture)) {
1720 		const u64 slot = ggtt->error_capture.start;
1721 
1722 		ggtt->vm.clear_range(&ggtt->vm, slot, PAGE_SIZE);
1723 	}
1724 }
1725 
1726 #define DAY_AS_SECONDS(x) (24 * 60 * 60 * (x))
1727 
1728 struct i915_gpu_state *
1729 i915_capture_gpu_state(struct drm_i915_private *i915)
1730 {
1731 	struct i915_gpu_state *error;
1732 	struct compress compress;
1733 
1734 	/* Check if GPU capture has been disabled */
1735 	error = READ_ONCE(i915->gpu_error.first_error);
1736 	if (IS_ERR(error))
1737 		return error;
1738 
1739 	error = kzalloc(sizeof(*error), ALLOW_FAIL);
1740 	if (!error) {
1741 		i915_disable_error_state(i915, -ENOMEM);
1742 		return ERR_PTR(-ENOMEM);
1743 	}
1744 
1745 	if (!compress_init(&compress)) {
1746 		kfree(error);
1747 		i915_disable_error_state(i915, -ENOMEM);
1748 		return ERR_PTR(-ENOMEM);
1749 	}
1750 
1751 	kref_init(&error->ref);
1752 	error->i915 = i915;
1753 
1754 	error->time = ktime_get_real();
1755 	error->boottime = ktime_get_boottime();
1756 	error->uptime = ktime_sub(ktime_get(), i915->gt.last_init_time);
1757 	error->capture = jiffies;
1758 
1759 	capture_params(error);
1760 	capture_gen_state(error);
1761 	capture_uc_state(error, &compress);
1762 	capture_reg_state(error);
1763 	gem_record_fences(error);
1764 	gem_record_rings(error, &compress);
1765 
1766 	error->overlay = intel_overlay_capture_error_state(i915);
1767 	error->display = intel_display_capture_error_state(i915);
1768 
1769 	capture_finish(error);
1770 	compress_fini(&compress);
1771 
1772 	return error;
1773 }
1774 
1775 /**
1776  * i915_capture_error_state - capture an error record for later analysis
1777  * @i915: i915 device
1778  * @engine_mask: the mask of engines triggering the hang
1779  * @msg: a message to insert into the error capture header
1780  *
1781  * Should be called when an error is detected (either a hang or an error
1782  * interrupt) to capture error state from the time of the error.  Fills
1783  * out a structure which becomes available in debugfs for user level tools
1784  * to pick up.
1785  */
1786 void i915_capture_error_state(struct drm_i915_private *i915,
1787 			      intel_engine_mask_t engine_mask,
1788 			      const char *msg)
1789 {
1790 	static bool warned;
1791 	struct i915_gpu_state *error;
1792 	unsigned long flags;
1793 
1794 	if (!i915_modparams.error_capture)
1795 		return;
1796 
1797 	if (READ_ONCE(i915->gpu_error.first_error))
1798 		return;
1799 
1800 	error = i915_capture_gpu_state(i915);
1801 	if (IS_ERR(error))
1802 		return;
1803 
1804 	dev_info(i915->drm.dev, "%s\n", error_msg(error, engine_mask, msg));
1805 
1806 	if (!error->simulated) {
1807 		spin_lock_irqsave(&i915->gpu_error.lock, flags);
1808 		if (!i915->gpu_error.first_error) {
1809 			i915->gpu_error.first_error = error;
1810 			error = NULL;
1811 		}
1812 		spin_unlock_irqrestore(&i915->gpu_error.lock, flags);
1813 	}
1814 
1815 	if (error) {
1816 		__i915_gpu_state_free(&error->ref);
1817 		return;
1818 	}
1819 
1820 	if (!xchg(&warned, true) &&
1821 	    ktime_get_real_seconds() - DRIVER_TIMESTAMP < DAY_AS_SECONDS(180)) {
1822 		pr_info("GPU hangs can indicate a bug anywhere in the entire gfx stack, including userspace.\n");
1823 		pr_info("Please file a _new_ bug report on bugs.freedesktop.org against DRI -> DRM/Intel\n");
1824 		pr_info("drm/i915 developers can then reassign to the right component if it's not a kernel issue.\n");
1825 		pr_info("The GPU crash dump is required to analyze GPU hangs, so please always attach it.\n");
1826 		pr_info("GPU crash dump saved to /sys/class/drm/card%d/error\n",
1827 			i915->drm.primary->index);
1828 	}
1829 }
1830 
1831 struct i915_gpu_state *
1832 i915_first_error_state(struct drm_i915_private *i915)
1833 {
1834 	struct i915_gpu_state *error;
1835 
1836 	spin_lock_irq(&i915->gpu_error.lock);
1837 	error = i915->gpu_error.first_error;
1838 	if (!IS_ERR_OR_NULL(error))
1839 		i915_gpu_state_get(error);
1840 	spin_unlock_irq(&i915->gpu_error.lock);
1841 
1842 	return error;
1843 }
1844 
1845 void i915_reset_error_state(struct drm_i915_private *i915)
1846 {
1847 	struct i915_gpu_state *error;
1848 
1849 	spin_lock_irq(&i915->gpu_error.lock);
1850 	error = i915->gpu_error.first_error;
1851 	if (error != ERR_PTR(-ENODEV)) /* if disabled, always disabled */
1852 		i915->gpu_error.first_error = NULL;
1853 	spin_unlock_irq(&i915->gpu_error.lock);
1854 
1855 	if (!IS_ERR_OR_NULL(error))
1856 		i915_gpu_state_put(error);
1857 }
1858 
1859 void i915_disable_error_state(struct drm_i915_private *i915, int err)
1860 {
1861 	spin_lock_irq(&i915->gpu_error.lock);
1862 	if (!i915->gpu_error.first_error)
1863 		i915->gpu_error.first_error = ERR_PTR(err);
1864 	spin_unlock_irq(&i915->gpu_error.lock);
1865 }
1866