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