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