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