Merge drm/drm-next into drm-intel-next
[sfrench/cifs-2.6.git] / drivers / gpu / drm / i915 / gt / intel_engine_cs.c
1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright © 2016 Intel Corporation
4  */
5
6 #include <linux/string_helpers.h>
7
8 #include <drm/drm_print.h>
9
10 #include "gem/i915_gem_context.h"
11 #include "gem/i915_gem_internal.h"
12 #include "gt/intel_gt_regs.h"
13
14 #include "i915_cmd_parser.h"
15 #include "i915_drv.h"
16 #include "i915_irq.h"
17 #include "i915_reg.h"
18 #include "intel_breadcrumbs.h"
19 #include "intel_context.h"
20 #include "intel_engine.h"
21 #include "intel_engine_pm.h"
22 #include "intel_engine_regs.h"
23 #include "intel_engine_user.h"
24 #include "intel_execlists_submission.h"
25 #include "intel_gt.h"
26 #include "intel_gt_mcr.h"
27 #include "intel_gt_pm.h"
28 #include "intel_gt_requests.h"
29 #include "intel_lrc.h"
30 #include "intel_lrc_reg.h"
31 #include "intel_reset.h"
32 #include "intel_ring.h"
33 #include "uc/intel_guc_submission.h"
34
35 /* Haswell does have the CXT_SIZE register however it does not appear to be
36  * valid. Now, docs explain in dwords what is in the context object. The full
37  * size is 70720 bytes, however, the power context and execlist context will
38  * never be saved (power context is stored elsewhere, and execlists don't work
39  * on HSW) - so the final size, including the extra state required for the
40  * Resource Streamer, is 66944 bytes, which rounds to 17 pages.
41  */
42 #define HSW_CXT_TOTAL_SIZE              (17 * PAGE_SIZE)
43
44 #define DEFAULT_LR_CONTEXT_RENDER_SIZE  (22 * PAGE_SIZE)
45 #define GEN8_LR_CONTEXT_RENDER_SIZE     (20 * PAGE_SIZE)
46 #define GEN9_LR_CONTEXT_RENDER_SIZE     (22 * PAGE_SIZE)
47 #define GEN11_LR_CONTEXT_RENDER_SIZE    (14 * PAGE_SIZE)
48
49 #define GEN8_LR_CONTEXT_OTHER_SIZE      ( 2 * PAGE_SIZE)
50
51 #define MAX_MMIO_BASES 3
52 struct engine_info {
53         u8 class;
54         u8 instance;
55         /* mmio bases table *must* be sorted in reverse graphics_ver order */
56         struct engine_mmio_base {
57                 u32 graphics_ver : 8;
58                 u32 base : 24;
59         } mmio_bases[MAX_MMIO_BASES];
60 };
61
62 static const struct engine_info intel_engines[] = {
63         [RCS0] = {
64                 .class = RENDER_CLASS,
65                 .instance = 0,
66                 .mmio_bases = {
67                         { .graphics_ver = 1, .base = RENDER_RING_BASE }
68                 },
69         },
70         [BCS0] = {
71                 .class = COPY_ENGINE_CLASS,
72                 .instance = 0,
73                 .mmio_bases = {
74                         { .graphics_ver = 6, .base = BLT_RING_BASE }
75                 },
76         },
77         [BCS1] = {
78                 .class = COPY_ENGINE_CLASS,
79                 .instance = 1,
80                 .mmio_bases = {
81                         { .graphics_ver = 12, .base = XEHPC_BCS1_RING_BASE }
82                 },
83         },
84         [BCS2] = {
85                 .class = COPY_ENGINE_CLASS,
86                 .instance = 2,
87                 .mmio_bases = {
88                         { .graphics_ver = 12, .base = XEHPC_BCS2_RING_BASE }
89                 },
90         },
91         [BCS3] = {
92                 .class = COPY_ENGINE_CLASS,
93                 .instance = 3,
94                 .mmio_bases = {
95                         { .graphics_ver = 12, .base = XEHPC_BCS3_RING_BASE }
96                 },
97         },
98         [BCS4] = {
99                 .class = COPY_ENGINE_CLASS,
100                 .instance = 4,
101                 .mmio_bases = {
102                         { .graphics_ver = 12, .base = XEHPC_BCS4_RING_BASE }
103                 },
104         },
105         [BCS5] = {
106                 .class = COPY_ENGINE_CLASS,
107                 .instance = 5,
108                 .mmio_bases = {
109                         { .graphics_ver = 12, .base = XEHPC_BCS5_RING_BASE }
110                 },
111         },
112         [BCS6] = {
113                 .class = COPY_ENGINE_CLASS,
114                 .instance = 6,
115                 .mmio_bases = {
116                         { .graphics_ver = 12, .base = XEHPC_BCS6_RING_BASE }
117                 },
118         },
119         [BCS7] = {
120                 .class = COPY_ENGINE_CLASS,
121                 .instance = 7,
122                 .mmio_bases = {
123                         { .graphics_ver = 12, .base = XEHPC_BCS7_RING_BASE }
124                 },
125         },
126         [BCS8] = {
127                 .class = COPY_ENGINE_CLASS,
128                 .instance = 8,
129                 .mmio_bases = {
130                         { .graphics_ver = 12, .base = XEHPC_BCS8_RING_BASE }
131                 },
132         },
133         [VCS0] = {
134                 .class = VIDEO_DECODE_CLASS,
135                 .instance = 0,
136                 .mmio_bases = {
137                         { .graphics_ver = 11, .base = GEN11_BSD_RING_BASE },
138                         { .graphics_ver = 6, .base = GEN6_BSD_RING_BASE },
139                         { .graphics_ver = 4, .base = BSD_RING_BASE }
140                 },
141         },
142         [VCS1] = {
143                 .class = VIDEO_DECODE_CLASS,
144                 .instance = 1,
145                 .mmio_bases = {
146                         { .graphics_ver = 11, .base = GEN11_BSD2_RING_BASE },
147                         { .graphics_ver = 8, .base = GEN8_BSD2_RING_BASE }
148                 },
149         },
150         [VCS2] = {
151                 .class = VIDEO_DECODE_CLASS,
152                 .instance = 2,
153                 .mmio_bases = {
154                         { .graphics_ver = 11, .base = GEN11_BSD3_RING_BASE }
155                 },
156         },
157         [VCS3] = {
158                 .class = VIDEO_DECODE_CLASS,
159                 .instance = 3,
160                 .mmio_bases = {
161                         { .graphics_ver = 11, .base = GEN11_BSD4_RING_BASE }
162                 },
163         },
164         [VCS4] = {
165                 .class = VIDEO_DECODE_CLASS,
166                 .instance = 4,
167                 .mmio_bases = {
168                         { .graphics_ver = 12, .base = XEHP_BSD5_RING_BASE }
169                 },
170         },
171         [VCS5] = {
172                 .class = VIDEO_DECODE_CLASS,
173                 .instance = 5,
174                 .mmio_bases = {
175                         { .graphics_ver = 12, .base = XEHP_BSD6_RING_BASE }
176                 },
177         },
178         [VCS6] = {
179                 .class = VIDEO_DECODE_CLASS,
180                 .instance = 6,
181                 .mmio_bases = {
182                         { .graphics_ver = 12, .base = XEHP_BSD7_RING_BASE }
183                 },
184         },
185         [VCS7] = {
186                 .class = VIDEO_DECODE_CLASS,
187                 .instance = 7,
188                 .mmio_bases = {
189                         { .graphics_ver = 12, .base = XEHP_BSD8_RING_BASE }
190                 },
191         },
192         [VECS0] = {
193                 .class = VIDEO_ENHANCEMENT_CLASS,
194                 .instance = 0,
195                 .mmio_bases = {
196                         { .graphics_ver = 11, .base = GEN11_VEBOX_RING_BASE },
197                         { .graphics_ver = 7, .base = VEBOX_RING_BASE }
198                 },
199         },
200         [VECS1] = {
201                 .class = VIDEO_ENHANCEMENT_CLASS,
202                 .instance = 1,
203                 .mmio_bases = {
204                         { .graphics_ver = 11, .base = GEN11_VEBOX2_RING_BASE }
205                 },
206         },
207         [VECS2] = {
208                 .class = VIDEO_ENHANCEMENT_CLASS,
209                 .instance = 2,
210                 .mmio_bases = {
211                         { .graphics_ver = 12, .base = XEHP_VEBOX3_RING_BASE }
212                 },
213         },
214         [VECS3] = {
215                 .class = VIDEO_ENHANCEMENT_CLASS,
216                 .instance = 3,
217                 .mmio_bases = {
218                         { .graphics_ver = 12, .base = XEHP_VEBOX4_RING_BASE }
219                 },
220         },
221         [CCS0] = {
222                 .class = COMPUTE_CLASS,
223                 .instance = 0,
224                 .mmio_bases = {
225                         { .graphics_ver = 12, .base = GEN12_COMPUTE0_RING_BASE }
226                 }
227         },
228         [CCS1] = {
229                 .class = COMPUTE_CLASS,
230                 .instance = 1,
231                 .mmio_bases = {
232                         { .graphics_ver = 12, .base = GEN12_COMPUTE1_RING_BASE }
233                 }
234         },
235         [CCS2] = {
236                 .class = COMPUTE_CLASS,
237                 .instance = 2,
238                 .mmio_bases = {
239                         { .graphics_ver = 12, .base = GEN12_COMPUTE2_RING_BASE }
240                 }
241         },
242         [CCS3] = {
243                 .class = COMPUTE_CLASS,
244                 .instance = 3,
245                 .mmio_bases = {
246                         { .graphics_ver = 12, .base = GEN12_COMPUTE3_RING_BASE }
247                 }
248         },
249 };
250
251 /**
252  * intel_engine_context_size() - return the size of the context for an engine
253  * @gt: the gt
254  * @class: engine class
255  *
256  * Each engine class may require a different amount of space for a context
257  * image.
258  *
259  * Return: size (in bytes) of an engine class specific context image
260  *
261  * Note: this size includes the HWSP, which is part of the context image
262  * in LRC mode, but does not include the "shared data page" used with
263  * GuC submission. The caller should account for this if using the GuC.
264  */
265 u32 intel_engine_context_size(struct intel_gt *gt, u8 class)
266 {
267         struct intel_uncore *uncore = gt->uncore;
268         u32 cxt_size;
269
270         BUILD_BUG_ON(I915_GTT_PAGE_SIZE != PAGE_SIZE);
271
272         switch (class) {
273         case COMPUTE_CLASS:
274                 fallthrough;
275         case RENDER_CLASS:
276                 switch (GRAPHICS_VER(gt->i915)) {
277                 default:
278                         MISSING_CASE(GRAPHICS_VER(gt->i915));
279                         return DEFAULT_LR_CONTEXT_RENDER_SIZE;
280                 case 12:
281                 case 11:
282                         return GEN11_LR_CONTEXT_RENDER_SIZE;
283                 case 9:
284                         return GEN9_LR_CONTEXT_RENDER_SIZE;
285                 case 8:
286                         return GEN8_LR_CONTEXT_RENDER_SIZE;
287                 case 7:
288                         if (IS_HASWELL(gt->i915))
289                                 return HSW_CXT_TOTAL_SIZE;
290
291                         cxt_size = intel_uncore_read(uncore, GEN7_CXT_SIZE);
292                         return round_up(GEN7_CXT_TOTAL_SIZE(cxt_size) * 64,
293                                         PAGE_SIZE);
294                 case 6:
295                         cxt_size = intel_uncore_read(uncore, CXT_SIZE);
296                         return round_up(GEN6_CXT_TOTAL_SIZE(cxt_size) * 64,
297                                         PAGE_SIZE);
298                 case 5:
299                 case 4:
300                         /*
301                          * There is a discrepancy here between the size reported
302                          * by the register and the size of the context layout
303                          * in the docs. Both are described as authorative!
304                          *
305                          * The discrepancy is on the order of a few cachelines,
306                          * but the total is under one page (4k), which is our
307                          * minimum allocation anyway so it should all come
308                          * out in the wash.
309                          */
310                         cxt_size = intel_uncore_read(uncore, CXT_SIZE) + 1;
311                         drm_dbg(&gt->i915->drm,
312                                 "graphics_ver = %d CXT_SIZE = %d bytes [0x%08x]\n",
313                                 GRAPHICS_VER(gt->i915), cxt_size * 64,
314                                 cxt_size - 1);
315                         return round_up(cxt_size * 64, PAGE_SIZE);
316                 case 3:
317                 case 2:
318                 /* For the special day when i810 gets merged. */
319                 case 1:
320                         return 0;
321                 }
322                 break;
323         default:
324                 MISSING_CASE(class);
325                 fallthrough;
326         case VIDEO_DECODE_CLASS:
327         case VIDEO_ENHANCEMENT_CLASS:
328         case COPY_ENGINE_CLASS:
329                 if (GRAPHICS_VER(gt->i915) < 8)
330                         return 0;
331                 return GEN8_LR_CONTEXT_OTHER_SIZE;
332         }
333 }
334
335 static u32 __engine_mmio_base(struct drm_i915_private *i915,
336                               const struct engine_mmio_base *bases)
337 {
338         int i;
339
340         for (i = 0; i < MAX_MMIO_BASES; i++)
341                 if (GRAPHICS_VER(i915) >= bases[i].graphics_ver)
342                         break;
343
344         GEM_BUG_ON(i == MAX_MMIO_BASES);
345         GEM_BUG_ON(!bases[i].base);
346
347         return bases[i].base;
348 }
349
350 static void __sprint_engine_name(struct intel_engine_cs *engine)
351 {
352         /*
353          * Before we know what the uABI name for this engine will be,
354          * we still would like to keep track of this engine in the debug logs.
355          * We throw in a ' here as a reminder that this isn't its final name.
356          */
357         GEM_WARN_ON(snprintf(engine->name, sizeof(engine->name), "%s'%u",
358                              intel_engine_class_repr(engine->class),
359                              engine->instance) >= sizeof(engine->name));
360 }
361
362 void intel_engine_set_hwsp_writemask(struct intel_engine_cs *engine, u32 mask)
363 {
364         /*
365          * Though they added more rings on g4x/ilk, they did not add
366          * per-engine HWSTAM until gen6.
367          */
368         if (GRAPHICS_VER(engine->i915) < 6 && engine->class != RENDER_CLASS)
369                 return;
370
371         if (GRAPHICS_VER(engine->i915) >= 3)
372                 ENGINE_WRITE(engine, RING_HWSTAM, mask);
373         else
374                 ENGINE_WRITE16(engine, RING_HWSTAM, mask);
375 }
376
377 static void intel_engine_sanitize_mmio(struct intel_engine_cs *engine)
378 {
379         /* Mask off all writes into the unknown HWSP */
380         intel_engine_set_hwsp_writemask(engine, ~0u);
381 }
382
383 static void nop_irq_handler(struct intel_engine_cs *engine, u16 iir)
384 {
385         GEM_DEBUG_WARN_ON(iir);
386 }
387
388 static u32 get_reset_domain(u8 ver, enum intel_engine_id id)
389 {
390         u32 reset_domain;
391
392         if (ver >= 11) {
393                 static const u32 engine_reset_domains[] = {
394                         [RCS0]  = GEN11_GRDOM_RENDER,
395                         [BCS0]  = GEN11_GRDOM_BLT,
396                         [BCS1]  = XEHPC_GRDOM_BLT1,
397                         [BCS2]  = XEHPC_GRDOM_BLT2,
398                         [BCS3]  = XEHPC_GRDOM_BLT3,
399                         [BCS4]  = XEHPC_GRDOM_BLT4,
400                         [BCS5]  = XEHPC_GRDOM_BLT5,
401                         [BCS6]  = XEHPC_GRDOM_BLT6,
402                         [BCS7]  = XEHPC_GRDOM_BLT7,
403                         [BCS8]  = XEHPC_GRDOM_BLT8,
404                         [VCS0]  = GEN11_GRDOM_MEDIA,
405                         [VCS1]  = GEN11_GRDOM_MEDIA2,
406                         [VCS2]  = GEN11_GRDOM_MEDIA3,
407                         [VCS3]  = GEN11_GRDOM_MEDIA4,
408                         [VCS4]  = GEN11_GRDOM_MEDIA5,
409                         [VCS5]  = GEN11_GRDOM_MEDIA6,
410                         [VCS6]  = GEN11_GRDOM_MEDIA7,
411                         [VCS7]  = GEN11_GRDOM_MEDIA8,
412                         [VECS0] = GEN11_GRDOM_VECS,
413                         [VECS1] = GEN11_GRDOM_VECS2,
414                         [VECS2] = GEN11_GRDOM_VECS3,
415                         [VECS3] = GEN11_GRDOM_VECS4,
416                         [CCS0]  = GEN11_GRDOM_RENDER,
417                         [CCS1]  = GEN11_GRDOM_RENDER,
418                         [CCS2]  = GEN11_GRDOM_RENDER,
419                         [CCS3]  = GEN11_GRDOM_RENDER,
420                 };
421                 GEM_BUG_ON(id >= ARRAY_SIZE(engine_reset_domains) ||
422                            !engine_reset_domains[id]);
423                 reset_domain = engine_reset_domains[id];
424         } else {
425                 static const u32 engine_reset_domains[] = {
426                         [RCS0]  = GEN6_GRDOM_RENDER,
427                         [BCS0]  = GEN6_GRDOM_BLT,
428                         [VCS0]  = GEN6_GRDOM_MEDIA,
429                         [VCS1]  = GEN8_GRDOM_MEDIA2,
430                         [VECS0] = GEN6_GRDOM_VECS,
431                 };
432                 GEM_BUG_ON(id >= ARRAY_SIZE(engine_reset_domains) ||
433                            !engine_reset_domains[id]);
434                 reset_domain = engine_reset_domains[id];
435         }
436
437         return reset_domain;
438 }
439
440 static int intel_engine_setup(struct intel_gt *gt, enum intel_engine_id id,
441                               u8 logical_instance)
442 {
443         const struct engine_info *info = &intel_engines[id];
444         struct drm_i915_private *i915 = gt->i915;
445         struct intel_engine_cs *engine;
446         u8 guc_class;
447
448         BUILD_BUG_ON(MAX_ENGINE_CLASS >= BIT(GEN11_ENGINE_CLASS_WIDTH));
449         BUILD_BUG_ON(MAX_ENGINE_INSTANCE >= BIT(GEN11_ENGINE_INSTANCE_WIDTH));
450         BUILD_BUG_ON(I915_MAX_VCS > (MAX_ENGINE_INSTANCE + 1));
451         BUILD_BUG_ON(I915_MAX_VECS > (MAX_ENGINE_INSTANCE + 1));
452
453         if (GEM_DEBUG_WARN_ON(id >= ARRAY_SIZE(gt->engine)))
454                 return -EINVAL;
455
456         if (GEM_DEBUG_WARN_ON(info->class > MAX_ENGINE_CLASS))
457                 return -EINVAL;
458
459         if (GEM_DEBUG_WARN_ON(info->instance > MAX_ENGINE_INSTANCE))
460                 return -EINVAL;
461
462         if (GEM_DEBUG_WARN_ON(gt->engine_class[info->class][info->instance]))
463                 return -EINVAL;
464
465         engine = kzalloc(sizeof(*engine), GFP_KERNEL);
466         if (!engine)
467                 return -ENOMEM;
468
469         BUILD_BUG_ON(BITS_PER_TYPE(engine->mask) < I915_NUM_ENGINES);
470
471         INIT_LIST_HEAD(&engine->pinned_contexts_list);
472         engine->id = id;
473         engine->legacy_idx = INVALID_ENGINE;
474         engine->mask = BIT(id);
475         engine->reset_domain = get_reset_domain(GRAPHICS_VER(gt->i915),
476                                                 id);
477         engine->i915 = i915;
478         engine->gt = gt;
479         engine->uncore = gt->uncore;
480         guc_class = engine_class_to_guc_class(info->class);
481         engine->guc_id = MAKE_GUC_ID(guc_class, info->instance);
482         engine->mmio_base = __engine_mmio_base(i915, info->mmio_bases);
483
484         engine->irq_handler = nop_irq_handler;
485
486         engine->class = info->class;
487         engine->instance = info->instance;
488         engine->logical_mask = BIT(logical_instance);
489         __sprint_engine_name(engine);
490
491         if ((engine->class == COMPUTE_CLASS && !RCS_MASK(engine->gt) &&
492              __ffs(CCS_MASK(engine->gt)) == engine->instance) ||
493              engine->class == RENDER_CLASS)
494                 engine->flags |= I915_ENGINE_FIRST_RENDER_COMPUTE;
495
496         /* features common between engines sharing EUs */
497         if (engine->class == RENDER_CLASS || engine->class == COMPUTE_CLASS) {
498                 engine->flags |= I915_ENGINE_HAS_RCS_REG_STATE;
499                 engine->flags |= I915_ENGINE_HAS_EU_PRIORITY;
500         }
501
502         engine->props.heartbeat_interval_ms =
503                 CONFIG_DRM_I915_HEARTBEAT_INTERVAL;
504         engine->props.max_busywait_duration_ns =
505                 CONFIG_DRM_I915_MAX_REQUEST_BUSYWAIT;
506         engine->props.preempt_timeout_ms =
507                 CONFIG_DRM_I915_PREEMPT_TIMEOUT;
508         engine->props.stop_timeout_ms =
509                 CONFIG_DRM_I915_STOP_TIMEOUT;
510         engine->props.timeslice_duration_ms =
511                 CONFIG_DRM_I915_TIMESLICE_DURATION;
512
513         /*
514          * Mid-thread pre-emption is not available in Gen12. Unfortunately,
515          * some compute workloads run quite long threads. That means they get
516          * reset due to not pre-empting in a timely manner. So, bump the
517          * pre-emption timeout value to be much higher for compute engines.
518          */
519         if (GRAPHICS_VER(i915) == 12 && (engine->flags & I915_ENGINE_HAS_RCS_REG_STATE))
520                 engine->props.preempt_timeout_ms = CONFIG_DRM_I915_PREEMPT_TIMEOUT_COMPUTE;
521
522         /* Cap properties according to any system limits */
523 #define CLAMP_PROP(field) \
524         do { \
525                 u64 clamp = intel_clamp_##field(engine, engine->props.field); \
526                 if (clamp != engine->props.field) { \
527                         drm_notice(&engine->i915->drm, \
528                                    "Warning, clamping %s to %lld to prevent overflow\n", \
529                                    #field, clamp); \
530                         engine->props.field = clamp; \
531                 } \
532         } while (0)
533
534         CLAMP_PROP(heartbeat_interval_ms);
535         CLAMP_PROP(max_busywait_duration_ns);
536         CLAMP_PROP(preempt_timeout_ms);
537         CLAMP_PROP(stop_timeout_ms);
538         CLAMP_PROP(timeslice_duration_ms);
539
540 #undef CLAMP_PROP
541
542         engine->defaults = engine->props; /* never to change again */
543
544         engine->context_size = intel_engine_context_size(gt, engine->class);
545         if (WARN_ON(engine->context_size > BIT(20)))
546                 engine->context_size = 0;
547         if (engine->context_size)
548                 DRIVER_CAPS(i915)->has_logical_contexts = true;
549
550         ewma__engine_latency_init(&engine->latency);
551         seqcount_init(&engine->stats.execlists.lock);
552
553         ATOMIC_INIT_NOTIFIER_HEAD(&engine->context_status_notifier);
554
555         /* Scrub mmio state on takeover */
556         intel_engine_sanitize_mmio(engine);
557
558         gt->engine_class[info->class][info->instance] = engine;
559         gt->engine[id] = engine;
560
561         return 0;
562 }
563
564 u64 intel_clamp_heartbeat_interval_ms(struct intel_engine_cs *engine, u64 value)
565 {
566         value = min_t(u64, value, jiffies_to_msecs(MAX_SCHEDULE_TIMEOUT));
567
568         return value;
569 }
570
571 u64 intel_clamp_max_busywait_duration_ns(struct intel_engine_cs *engine, u64 value)
572 {
573         value = min(value, jiffies_to_nsecs(2));
574
575         return value;
576 }
577
578 u64 intel_clamp_preempt_timeout_ms(struct intel_engine_cs *engine, u64 value)
579 {
580         /*
581          * NB: The GuC API only supports 32bit values. However, the limit is further
582          * reduced due to internal calculations which would otherwise overflow.
583          */
584         if (intel_guc_submission_is_wanted(&engine->gt->uc.guc))
585                 value = min_t(u64, value, guc_policy_max_preempt_timeout_ms());
586
587         value = min_t(u64, value, jiffies_to_msecs(MAX_SCHEDULE_TIMEOUT));
588
589         return value;
590 }
591
592 u64 intel_clamp_stop_timeout_ms(struct intel_engine_cs *engine, u64 value)
593 {
594         value = min_t(u64, value, jiffies_to_msecs(MAX_SCHEDULE_TIMEOUT));
595
596         return value;
597 }
598
599 u64 intel_clamp_timeslice_duration_ms(struct intel_engine_cs *engine, u64 value)
600 {
601         /*
602          * NB: The GuC API only supports 32bit values. However, the limit is further
603          * reduced due to internal calculations which would otherwise overflow.
604          */
605         if (intel_guc_submission_is_wanted(&engine->gt->uc.guc))
606                 value = min_t(u64, value, guc_policy_max_exec_quantum_ms());
607
608         value = min_t(u64, value, jiffies_to_msecs(MAX_SCHEDULE_TIMEOUT));
609
610         return value;
611 }
612
613 static void __setup_engine_capabilities(struct intel_engine_cs *engine)
614 {
615         struct drm_i915_private *i915 = engine->i915;
616
617         if (engine->class == VIDEO_DECODE_CLASS) {
618                 /*
619                  * HEVC support is present on first engine instance
620                  * before Gen11 and on all instances afterwards.
621                  */
622                 if (GRAPHICS_VER(i915) >= 11 ||
623                     (GRAPHICS_VER(i915) >= 9 && engine->instance == 0))
624                         engine->uabi_capabilities |=
625                                 I915_VIDEO_CLASS_CAPABILITY_HEVC;
626
627                 /*
628                  * SFC block is present only on even logical engine
629                  * instances.
630                  */
631                 if ((GRAPHICS_VER(i915) >= 11 &&
632                      (engine->gt->info.vdbox_sfc_access &
633                       BIT(engine->instance))) ||
634                     (GRAPHICS_VER(i915) >= 9 && engine->instance == 0))
635                         engine->uabi_capabilities |=
636                                 I915_VIDEO_AND_ENHANCE_CLASS_CAPABILITY_SFC;
637         } else if (engine->class == VIDEO_ENHANCEMENT_CLASS) {
638                 if (GRAPHICS_VER(i915) >= 9 &&
639                     engine->gt->info.sfc_mask & BIT(engine->instance))
640                         engine->uabi_capabilities |=
641                                 I915_VIDEO_AND_ENHANCE_CLASS_CAPABILITY_SFC;
642         }
643 }
644
645 static void intel_setup_engine_capabilities(struct intel_gt *gt)
646 {
647         struct intel_engine_cs *engine;
648         enum intel_engine_id id;
649
650         for_each_engine(engine, gt, id)
651                 __setup_engine_capabilities(engine);
652 }
653
654 /**
655  * intel_engines_release() - free the resources allocated for Command Streamers
656  * @gt: pointer to struct intel_gt
657  */
658 void intel_engines_release(struct intel_gt *gt)
659 {
660         struct intel_engine_cs *engine;
661         enum intel_engine_id id;
662
663         /*
664          * Before we release the resources held by engine, we must be certain
665          * that the HW is no longer accessing them -- having the GPU scribble
666          * to or read from a page being used for something else causes no end
667          * of fun.
668          *
669          * The GPU should be reset by this point, but assume the worst just
670          * in case we aborted before completely initialising the engines.
671          */
672         GEM_BUG_ON(intel_gt_pm_is_awake(gt));
673         if (!INTEL_INFO(gt->i915)->gpu_reset_clobbers_display)
674                 __intel_gt_reset(gt, ALL_ENGINES);
675
676         /* Decouple the backend; but keep the layout for late GPU resets */
677         for_each_engine(engine, gt, id) {
678                 if (!engine->release)
679                         continue;
680
681                 intel_wakeref_wait_for_idle(&engine->wakeref);
682                 GEM_BUG_ON(intel_engine_pm_is_awake(engine));
683
684                 engine->release(engine);
685                 engine->release = NULL;
686
687                 memset(&engine->reset, 0, sizeof(engine->reset));
688         }
689 }
690
691 void intel_engine_free_request_pool(struct intel_engine_cs *engine)
692 {
693         if (!engine->request_pool)
694                 return;
695
696         kmem_cache_free(i915_request_slab_cache(), engine->request_pool);
697 }
698
699 void intel_engines_free(struct intel_gt *gt)
700 {
701         struct intel_engine_cs *engine;
702         enum intel_engine_id id;
703
704         /* Free the requests! dma-resv keeps fences around for an eternity */
705         rcu_barrier();
706
707         for_each_engine(engine, gt, id) {
708                 intel_engine_free_request_pool(engine);
709                 kfree(engine);
710                 gt->engine[id] = NULL;
711         }
712 }
713
714 static
715 bool gen11_vdbox_has_sfc(struct intel_gt *gt,
716                          unsigned int physical_vdbox,
717                          unsigned int logical_vdbox, u16 vdbox_mask)
718 {
719         struct drm_i915_private *i915 = gt->i915;
720
721         /*
722          * In Gen11, only even numbered logical VDBOXes are hooked
723          * up to an SFC (Scaler & Format Converter) unit.
724          * In Gen12, Even numbered physical instance always are connected
725          * to an SFC. Odd numbered physical instances have SFC only if
726          * previous even instance is fused off.
727          *
728          * Starting with Xe_HP, there's also a dedicated SFC_ENABLE field
729          * in the fuse register that tells us whether a specific SFC is present.
730          */
731         if ((gt->info.sfc_mask & BIT(physical_vdbox / 2)) == 0)
732                 return false;
733         else if (MEDIA_VER(i915) >= 12)
734                 return (physical_vdbox % 2 == 0) ||
735                         !(BIT(physical_vdbox - 1) & vdbox_mask);
736         else if (MEDIA_VER(i915) == 11)
737                 return logical_vdbox % 2 == 0;
738
739         return false;
740 }
741
742 static void engine_mask_apply_media_fuses(struct intel_gt *gt)
743 {
744         struct drm_i915_private *i915 = gt->i915;
745         unsigned int logical_vdbox = 0;
746         unsigned int i;
747         u32 media_fuse, fuse1;
748         u16 vdbox_mask;
749         u16 vebox_mask;
750
751         if (MEDIA_VER(gt->i915) < 11)
752                 return;
753
754         /*
755          * On newer platforms the fusing register is called 'enable' and has
756          * enable semantics, while on older platforms it is called 'disable'
757          * and bits have disable semantices.
758          */
759         media_fuse = intel_uncore_read(gt->uncore, GEN11_GT_VEBOX_VDBOX_DISABLE);
760         if (MEDIA_VER_FULL(i915) < IP_VER(12, 50))
761                 media_fuse = ~media_fuse;
762
763         vdbox_mask = media_fuse & GEN11_GT_VDBOX_DISABLE_MASK;
764         vebox_mask = (media_fuse & GEN11_GT_VEBOX_DISABLE_MASK) >>
765                       GEN11_GT_VEBOX_DISABLE_SHIFT;
766
767         if (MEDIA_VER_FULL(i915) >= IP_VER(12, 50)) {
768                 fuse1 = intel_uncore_read(gt->uncore, HSW_PAVP_FUSE1);
769                 gt->info.sfc_mask = REG_FIELD_GET(XEHP_SFC_ENABLE_MASK, fuse1);
770         } else {
771                 gt->info.sfc_mask = ~0;
772         }
773
774         for (i = 0; i < I915_MAX_VCS; i++) {
775                 if (!HAS_ENGINE(gt, _VCS(i))) {
776                         vdbox_mask &= ~BIT(i);
777                         continue;
778                 }
779
780                 if (!(BIT(i) & vdbox_mask)) {
781                         gt->info.engine_mask &= ~BIT(_VCS(i));
782                         drm_dbg(&i915->drm, "vcs%u fused off\n", i);
783                         continue;
784                 }
785
786                 if (gen11_vdbox_has_sfc(gt, i, logical_vdbox, vdbox_mask))
787                         gt->info.vdbox_sfc_access |= BIT(i);
788                 logical_vdbox++;
789         }
790         drm_dbg(&i915->drm, "vdbox enable: %04x, instances: %04lx\n",
791                 vdbox_mask, VDBOX_MASK(gt));
792         GEM_BUG_ON(vdbox_mask != VDBOX_MASK(gt));
793
794         for (i = 0; i < I915_MAX_VECS; i++) {
795                 if (!HAS_ENGINE(gt, _VECS(i))) {
796                         vebox_mask &= ~BIT(i);
797                         continue;
798                 }
799
800                 if (!(BIT(i) & vebox_mask)) {
801                         gt->info.engine_mask &= ~BIT(_VECS(i));
802                         drm_dbg(&i915->drm, "vecs%u fused off\n", i);
803                 }
804         }
805         drm_dbg(&i915->drm, "vebox enable: %04x, instances: %04lx\n",
806                 vebox_mask, VEBOX_MASK(gt));
807         GEM_BUG_ON(vebox_mask != VEBOX_MASK(gt));
808 }
809
810 static void engine_mask_apply_compute_fuses(struct intel_gt *gt)
811 {
812         struct drm_i915_private *i915 = gt->i915;
813         struct intel_gt_info *info = &gt->info;
814         int ss_per_ccs = info->sseu.max_subslices / I915_MAX_CCS;
815         unsigned long ccs_mask;
816         unsigned int i;
817
818         if (GRAPHICS_VER(i915) < 11)
819                 return;
820
821         if (hweight32(CCS_MASK(gt)) <= 1)
822                 return;
823
824         ccs_mask = intel_slicemask_from_xehp_dssmask(info->sseu.compute_subslice_mask,
825                                                      ss_per_ccs);
826         /*
827          * If all DSS in a quadrant are fused off, the corresponding CCS
828          * engine is not available for use.
829          */
830         for_each_clear_bit(i, &ccs_mask, I915_MAX_CCS) {
831                 info->engine_mask &= ~BIT(_CCS(i));
832                 drm_dbg(&i915->drm, "ccs%u fused off\n", i);
833         }
834 }
835
836 static void engine_mask_apply_copy_fuses(struct intel_gt *gt)
837 {
838         struct drm_i915_private *i915 = gt->i915;
839         struct intel_gt_info *info = &gt->info;
840         unsigned long meml3_mask;
841         unsigned long quad;
842
843         if (!(GRAPHICS_VER_FULL(i915) >= IP_VER(12, 60) &&
844               GRAPHICS_VER_FULL(i915) < IP_VER(12, 70)))
845                 return;
846
847         meml3_mask = intel_uncore_read(gt->uncore, GEN10_MIRROR_FUSE3);
848         meml3_mask = REG_FIELD_GET(GEN12_MEML3_EN_MASK, meml3_mask);
849
850         /*
851          * Link Copy engines may be fused off according to meml3_mask. Each
852          * bit is a quad that houses 2 Link Copy and two Sub Copy engines.
853          */
854         for_each_clear_bit(quad, &meml3_mask, GEN12_MAX_MSLICES) {
855                 unsigned int instance = quad * 2 + 1;
856                 intel_engine_mask_t mask = GENMASK(_BCS(instance + 1),
857                                                    _BCS(instance));
858
859                 if (mask & info->engine_mask) {
860                         drm_dbg(&i915->drm, "bcs%u fused off\n", instance);
861                         drm_dbg(&i915->drm, "bcs%u fused off\n", instance + 1);
862
863                         info->engine_mask &= ~mask;
864                 }
865         }
866 }
867
868 /*
869  * Determine which engines are fused off in our particular hardware.
870  * Note that we have a catch-22 situation where we need to be able to access
871  * the blitter forcewake domain to read the engine fuses, but at the same time
872  * we need to know which engines are available on the system to know which
873  * forcewake domains are present. We solve this by intializing the forcewake
874  * domains based on the full engine mask in the platform capabilities before
875  * calling this function and pruning the domains for fused-off engines
876  * afterwards.
877  */
878 static intel_engine_mask_t init_engine_mask(struct intel_gt *gt)
879 {
880         struct intel_gt_info *info = &gt->info;
881
882         GEM_BUG_ON(!info->engine_mask);
883
884         engine_mask_apply_media_fuses(gt);
885         engine_mask_apply_compute_fuses(gt);
886         engine_mask_apply_copy_fuses(gt);
887
888         return info->engine_mask;
889 }
890
891 static void populate_logical_ids(struct intel_gt *gt, u8 *logical_ids,
892                                  u8 class, const u8 *map, u8 num_instances)
893 {
894         int i, j;
895         u8 current_logical_id = 0;
896
897         for (j = 0; j < num_instances; ++j) {
898                 for (i = 0; i < ARRAY_SIZE(intel_engines); ++i) {
899                         if (!HAS_ENGINE(gt, i) ||
900                             intel_engines[i].class != class)
901                                 continue;
902
903                         if (intel_engines[i].instance == map[j]) {
904                                 logical_ids[intel_engines[i].instance] =
905                                         current_logical_id++;
906                                 break;
907                         }
908                 }
909         }
910 }
911
912 static void setup_logical_ids(struct intel_gt *gt, u8 *logical_ids, u8 class)
913 {
914         /*
915          * Logical to physical mapping is needed for proper support
916          * to split-frame feature.
917          */
918         if (MEDIA_VER(gt->i915) >= 11 && class == VIDEO_DECODE_CLASS) {
919                 const u8 map[] = { 0, 2, 4, 6, 1, 3, 5, 7 };
920
921                 populate_logical_ids(gt, logical_ids, class,
922                                      map, ARRAY_SIZE(map));
923         } else {
924                 int i;
925                 u8 map[MAX_ENGINE_INSTANCE + 1];
926
927                 for (i = 0; i < MAX_ENGINE_INSTANCE + 1; ++i)
928                         map[i] = i;
929                 populate_logical_ids(gt, logical_ids, class,
930                                      map, ARRAY_SIZE(map));
931         }
932 }
933
934 /**
935  * intel_engines_init_mmio() - allocate and prepare the Engine Command Streamers
936  * @gt: pointer to struct intel_gt
937  *
938  * Return: non-zero if the initialization failed.
939  */
940 int intel_engines_init_mmio(struct intel_gt *gt)
941 {
942         struct drm_i915_private *i915 = gt->i915;
943         const unsigned int engine_mask = init_engine_mask(gt);
944         unsigned int mask = 0;
945         unsigned int i, class;
946         u8 logical_ids[MAX_ENGINE_INSTANCE + 1];
947         int err;
948
949         drm_WARN_ON(&i915->drm, engine_mask == 0);
950         drm_WARN_ON(&i915->drm, engine_mask &
951                     GENMASK(BITS_PER_TYPE(mask) - 1, I915_NUM_ENGINES));
952
953         if (i915_inject_probe_failure(i915))
954                 return -ENODEV;
955
956         for (class = 0; class < MAX_ENGINE_CLASS + 1; ++class) {
957                 setup_logical_ids(gt, logical_ids, class);
958
959                 for (i = 0; i < ARRAY_SIZE(intel_engines); ++i) {
960                         u8 instance = intel_engines[i].instance;
961
962                         if (intel_engines[i].class != class ||
963                             !HAS_ENGINE(gt, i))
964                                 continue;
965
966                         err = intel_engine_setup(gt, i,
967                                                  logical_ids[instance]);
968                         if (err)
969                                 goto cleanup;
970
971                         mask |= BIT(i);
972                 }
973         }
974
975         /*
976          * Catch failures to update intel_engines table when the new engines
977          * are added to the driver by a warning and disabling the forgotten
978          * engines.
979          */
980         if (drm_WARN_ON(&i915->drm, mask != engine_mask))
981                 gt->info.engine_mask = mask;
982
983         gt->info.num_engines = hweight32(mask);
984
985         intel_gt_check_and_clear_faults(gt);
986
987         intel_setup_engine_capabilities(gt);
988
989         intel_uncore_prune_engine_fw_domains(gt->uncore, gt);
990
991         return 0;
992
993 cleanup:
994         intel_engines_free(gt);
995         return err;
996 }
997
998 void intel_engine_init_execlists(struct intel_engine_cs *engine)
999 {
1000         struct intel_engine_execlists * const execlists = &engine->execlists;
1001
1002         execlists->port_mask = 1;
1003         GEM_BUG_ON(!is_power_of_2(execlists_num_ports(execlists)));
1004         GEM_BUG_ON(execlists_num_ports(execlists) > EXECLIST_MAX_PORTS);
1005
1006         memset(execlists->pending, 0, sizeof(execlists->pending));
1007         execlists->active =
1008                 memset(execlists->inflight, 0, sizeof(execlists->inflight));
1009 }
1010
1011 static void cleanup_status_page(struct intel_engine_cs *engine)
1012 {
1013         struct i915_vma *vma;
1014
1015         /* Prevent writes into HWSP after returning the page to the system */
1016         intel_engine_set_hwsp_writemask(engine, ~0u);
1017
1018         vma = fetch_and_zero(&engine->status_page.vma);
1019         if (!vma)
1020                 return;
1021
1022         if (!HWS_NEEDS_PHYSICAL(engine->i915))
1023                 i915_vma_unpin(vma);
1024
1025         i915_gem_object_unpin_map(vma->obj);
1026         i915_gem_object_put(vma->obj);
1027 }
1028
1029 static int pin_ggtt_status_page(struct intel_engine_cs *engine,
1030                                 struct i915_gem_ww_ctx *ww,
1031                                 struct i915_vma *vma)
1032 {
1033         unsigned int flags;
1034
1035         if (!HAS_LLC(engine->i915) && i915_ggtt_has_aperture(engine->gt->ggtt))
1036                 /*
1037                  * On g33, we cannot place HWS above 256MiB, so
1038                  * restrict its pinning to the low mappable arena.
1039                  * Though this restriction is not documented for
1040                  * gen4, gen5, or byt, they also behave similarly
1041                  * and hang if the HWS is placed at the top of the
1042                  * GTT. To generalise, it appears that all !llc
1043                  * platforms have issues with us placing the HWS
1044                  * above the mappable region (even though we never
1045                  * actually map it).
1046                  */
1047                 flags = PIN_MAPPABLE;
1048         else
1049                 flags = PIN_HIGH;
1050
1051         return i915_ggtt_pin(vma, ww, 0, flags);
1052 }
1053
1054 static int init_status_page(struct intel_engine_cs *engine)
1055 {
1056         struct drm_i915_gem_object *obj;
1057         struct i915_gem_ww_ctx ww;
1058         struct i915_vma *vma;
1059         void *vaddr;
1060         int ret;
1061
1062         INIT_LIST_HEAD(&engine->status_page.timelines);
1063
1064         /*
1065          * Though the HWS register does support 36bit addresses, historically
1066          * we have had hangs and corruption reported due to wild writes if
1067          * the HWS is placed above 4G. We only allow objects to be allocated
1068          * in GFP_DMA32 for i965, and no earlier physical address users had
1069          * access to more than 4G.
1070          */
1071         obj = i915_gem_object_create_internal(engine->i915, PAGE_SIZE);
1072         if (IS_ERR(obj)) {
1073                 drm_err(&engine->i915->drm,
1074                         "Failed to allocate status page\n");
1075                 return PTR_ERR(obj);
1076         }
1077
1078         i915_gem_object_set_cache_coherency(obj, I915_CACHE_LLC);
1079
1080         vma = i915_vma_instance(obj, &engine->gt->ggtt->vm, NULL);
1081         if (IS_ERR(vma)) {
1082                 ret = PTR_ERR(vma);
1083                 goto err_put;
1084         }
1085
1086         i915_gem_ww_ctx_init(&ww, true);
1087 retry:
1088         ret = i915_gem_object_lock(obj, &ww);
1089         if (!ret && !HWS_NEEDS_PHYSICAL(engine->i915))
1090                 ret = pin_ggtt_status_page(engine, &ww, vma);
1091         if (ret)
1092                 goto err;
1093
1094         vaddr = i915_gem_object_pin_map(obj, I915_MAP_WB);
1095         if (IS_ERR(vaddr)) {
1096                 ret = PTR_ERR(vaddr);
1097                 goto err_unpin;
1098         }
1099
1100         engine->status_page.addr = memset(vaddr, 0, PAGE_SIZE);
1101         engine->status_page.vma = vma;
1102
1103 err_unpin:
1104         if (ret)
1105                 i915_vma_unpin(vma);
1106 err:
1107         if (ret == -EDEADLK) {
1108                 ret = i915_gem_ww_ctx_backoff(&ww);
1109                 if (!ret)
1110                         goto retry;
1111         }
1112         i915_gem_ww_ctx_fini(&ww);
1113 err_put:
1114         if (ret)
1115                 i915_gem_object_put(obj);
1116         return ret;
1117 }
1118
1119 static int engine_setup_common(struct intel_engine_cs *engine)
1120 {
1121         int err;
1122
1123         init_llist_head(&engine->barrier_tasks);
1124
1125         err = init_status_page(engine);
1126         if (err)
1127                 return err;
1128
1129         engine->breadcrumbs = intel_breadcrumbs_create(engine);
1130         if (!engine->breadcrumbs) {
1131                 err = -ENOMEM;
1132                 goto err_status;
1133         }
1134
1135         engine->sched_engine = i915_sched_engine_create(ENGINE_PHYSICAL);
1136         if (!engine->sched_engine) {
1137                 err = -ENOMEM;
1138                 goto err_sched_engine;
1139         }
1140         engine->sched_engine->private_data = engine;
1141
1142         err = intel_engine_init_cmd_parser(engine);
1143         if (err)
1144                 goto err_cmd_parser;
1145
1146         intel_engine_init_execlists(engine);
1147         intel_engine_init__pm(engine);
1148         intel_engine_init_retire(engine);
1149
1150         /* Use the whole device by default */
1151         engine->sseu =
1152                 intel_sseu_from_device_info(&engine->gt->info.sseu);
1153
1154         intel_engine_init_workarounds(engine);
1155         intel_engine_init_whitelist(engine);
1156         intel_engine_init_ctx_wa(engine);
1157
1158         if (GRAPHICS_VER(engine->i915) >= 12)
1159                 engine->flags |= I915_ENGINE_HAS_RELATIVE_MMIO;
1160
1161         return 0;
1162
1163 err_cmd_parser:
1164         i915_sched_engine_put(engine->sched_engine);
1165 err_sched_engine:
1166         intel_breadcrumbs_put(engine->breadcrumbs);
1167 err_status:
1168         cleanup_status_page(engine);
1169         return err;
1170 }
1171
1172 struct measure_breadcrumb {
1173         struct i915_request rq;
1174         struct intel_ring ring;
1175         u32 cs[2048];
1176 };
1177
1178 static int measure_breadcrumb_dw(struct intel_context *ce)
1179 {
1180         struct intel_engine_cs *engine = ce->engine;
1181         struct measure_breadcrumb *frame;
1182         int dw;
1183
1184         GEM_BUG_ON(!engine->gt->scratch);
1185
1186         frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1187         if (!frame)
1188                 return -ENOMEM;
1189
1190         frame->rq.engine = engine;
1191         frame->rq.context = ce;
1192         rcu_assign_pointer(frame->rq.timeline, ce->timeline);
1193         frame->rq.hwsp_seqno = ce->timeline->hwsp_seqno;
1194
1195         frame->ring.vaddr = frame->cs;
1196         frame->ring.size = sizeof(frame->cs);
1197         frame->ring.wrap =
1198                 BITS_PER_TYPE(frame->ring.size) - ilog2(frame->ring.size);
1199         frame->ring.effective_size = frame->ring.size;
1200         intel_ring_update_space(&frame->ring);
1201         frame->rq.ring = &frame->ring;
1202
1203         mutex_lock(&ce->timeline->mutex);
1204         spin_lock_irq(&engine->sched_engine->lock);
1205
1206         dw = engine->emit_fini_breadcrumb(&frame->rq, frame->cs) - frame->cs;
1207
1208         spin_unlock_irq(&engine->sched_engine->lock);
1209         mutex_unlock(&ce->timeline->mutex);
1210
1211         GEM_BUG_ON(dw & 1); /* RING_TAIL must be qword aligned */
1212
1213         kfree(frame);
1214         return dw;
1215 }
1216
1217 struct intel_context *
1218 intel_engine_create_pinned_context(struct intel_engine_cs *engine,
1219                                    struct i915_address_space *vm,
1220                                    unsigned int ring_size,
1221                                    unsigned int hwsp,
1222                                    struct lock_class_key *key,
1223                                    const char *name)
1224 {
1225         struct intel_context *ce;
1226         int err;
1227
1228         ce = intel_context_create(engine);
1229         if (IS_ERR(ce))
1230                 return ce;
1231
1232         __set_bit(CONTEXT_BARRIER_BIT, &ce->flags);
1233         ce->timeline = page_pack_bits(NULL, hwsp);
1234         ce->ring = NULL;
1235         ce->ring_size = ring_size;
1236
1237         i915_vm_put(ce->vm);
1238         ce->vm = i915_vm_get(vm);
1239
1240         err = intel_context_pin(ce); /* perma-pin so it is always available */
1241         if (err) {
1242                 intel_context_put(ce);
1243                 return ERR_PTR(err);
1244         }
1245
1246         list_add_tail(&ce->pinned_contexts_link, &engine->pinned_contexts_list);
1247
1248         /*
1249          * Give our perma-pinned kernel timelines a separate lockdep class,
1250          * so that we can use them from within the normal user timelines
1251          * should we need to inject GPU operations during their request
1252          * construction.
1253          */
1254         lockdep_set_class_and_name(&ce->timeline->mutex, key, name);
1255
1256         return ce;
1257 }
1258
1259 void intel_engine_destroy_pinned_context(struct intel_context *ce)
1260 {
1261         struct intel_engine_cs *engine = ce->engine;
1262         struct i915_vma *hwsp = engine->status_page.vma;
1263
1264         GEM_BUG_ON(ce->timeline->hwsp_ggtt != hwsp);
1265
1266         mutex_lock(&hwsp->vm->mutex);
1267         list_del(&ce->timeline->engine_link);
1268         mutex_unlock(&hwsp->vm->mutex);
1269
1270         list_del(&ce->pinned_contexts_link);
1271         intel_context_unpin(ce);
1272         intel_context_put(ce);
1273 }
1274
1275 static struct intel_context *
1276 create_kernel_context(struct intel_engine_cs *engine)
1277 {
1278         static struct lock_class_key kernel;
1279
1280         return intel_engine_create_pinned_context(engine, engine->gt->vm, SZ_4K,
1281                                                   I915_GEM_HWS_SEQNO_ADDR,
1282                                                   &kernel, "kernel_context");
1283 }
1284
1285 /**
1286  * intel_engines_init_common - initialize cengine state which might require hw access
1287  * @engine: Engine to initialize.
1288  *
1289  * Initializes @engine@ structure members shared between legacy and execlists
1290  * submission modes which do require hardware access.
1291  *
1292  * Typcally done at later stages of submission mode specific engine setup.
1293  *
1294  * Returns zero on success or an error code on failure.
1295  */
1296 static int engine_init_common(struct intel_engine_cs *engine)
1297 {
1298         struct intel_context *ce;
1299         int ret;
1300
1301         engine->set_default_submission(engine);
1302
1303         /*
1304          * We may need to do things with the shrinker which
1305          * require us to immediately switch back to the default
1306          * context. This can cause a problem as pinning the
1307          * default context also requires GTT space which may not
1308          * be available. To avoid this we always pin the default
1309          * context.
1310          */
1311         ce = create_kernel_context(engine);
1312         if (IS_ERR(ce))
1313                 return PTR_ERR(ce);
1314
1315         ret = measure_breadcrumb_dw(ce);
1316         if (ret < 0)
1317                 goto err_context;
1318
1319         engine->emit_fini_breadcrumb_dw = ret;
1320         engine->kernel_context = ce;
1321
1322         return 0;
1323
1324 err_context:
1325         intel_engine_destroy_pinned_context(ce);
1326         return ret;
1327 }
1328
1329 int intel_engines_init(struct intel_gt *gt)
1330 {
1331         int (*setup)(struct intel_engine_cs *engine);
1332         struct intel_engine_cs *engine;
1333         enum intel_engine_id id;
1334         int err;
1335
1336         if (intel_uc_uses_guc_submission(&gt->uc)) {
1337                 gt->submission_method = INTEL_SUBMISSION_GUC;
1338                 setup = intel_guc_submission_setup;
1339         } else if (HAS_EXECLISTS(gt->i915)) {
1340                 gt->submission_method = INTEL_SUBMISSION_ELSP;
1341                 setup = intel_execlists_submission_setup;
1342         } else {
1343                 gt->submission_method = INTEL_SUBMISSION_RING;
1344                 setup = intel_ring_submission_setup;
1345         }
1346
1347         for_each_engine(engine, gt, id) {
1348                 err = engine_setup_common(engine);
1349                 if (err)
1350                         return err;
1351
1352                 err = setup(engine);
1353                 if (err) {
1354                         intel_engine_cleanup_common(engine);
1355                         return err;
1356                 }
1357
1358                 /* The backend should now be responsible for cleanup */
1359                 GEM_BUG_ON(engine->release == NULL);
1360
1361                 err = engine_init_common(engine);
1362                 if (err)
1363                         return err;
1364
1365                 intel_engine_add_user(engine);
1366         }
1367
1368         return 0;
1369 }
1370
1371 /**
1372  * intel_engines_cleanup_common - cleans up the engine state created by
1373  *                                the common initiailizers.
1374  * @engine: Engine to cleanup.
1375  *
1376  * This cleans up everything created by the common helpers.
1377  */
1378 void intel_engine_cleanup_common(struct intel_engine_cs *engine)
1379 {
1380         GEM_BUG_ON(!list_empty(&engine->sched_engine->requests));
1381
1382         i915_sched_engine_put(engine->sched_engine);
1383         intel_breadcrumbs_put(engine->breadcrumbs);
1384
1385         intel_engine_fini_retire(engine);
1386         intel_engine_cleanup_cmd_parser(engine);
1387
1388         if (engine->default_state)
1389                 fput(engine->default_state);
1390
1391         if (engine->kernel_context)
1392                 intel_engine_destroy_pinned_context(engine->kernel_context);
1393
1394         GEM_BUG_ON(!llist_empty(&engine->barrier_tasks));
1395         cleanup_status_page(engine);
1396
1397         intel_wa_list_free(&engine->ctx_wa_list);
1398         intel_wa_list_free(&engine->wa_list);
1399         intel_wa_list_free(&engine->whitelist);
1400 }
1401
1402 /**
1403  * intel_engine_resume - re-initializes the HW state of the engine
1404  * @engine: Engine to resume.
1405  *
1406  * Returns zero on success or an error code on failure.
1407  */
1408 int intel_engine_resume(struct intel_engine_cs *engine)
1409 {
1410         intel_engine_apply_workarounds(engine);
1411         intel_engine_apply_whitelist(engine);
1412
1413         return engine->resume(engine);
1414 }
1415
1416 u64 intel_engine_get_active_head(const struct intel_engine_cs *engine)
1417 {
1418         struct drm_i915_private *i915 = engine->i915;
1419
1420         u64 acthd;
1421
1422         if (GRAPHICS_VER(i915) >= 8)
1423                 acthd = ENGINE_READ64(engine, RING_ACTHD, RING_ACTHD_UDW);
1424         else if (GRAPHICS_VER(i915) >= 4)
1425                 acthd = ENGINE_READ(engine, RING_ACTHD);
1426         else
1427                 acthd = ENGINE_READ(engine, ACTHD);
1428
1429         return acthd;
1430 }
1431
1432 u64 intel_engine_get_last_batch_head(const struct intel_engine_cs *engine)
1433 {
1434         u64 bbaddr;
1435
1436         if (GRAPHICS_VER(engine->i915) >= 8)
1437                 bbaddr = ENGINE_READ64(engine, RING_BBADDR, RING_BBADDR_UDW);
1438         else
1439                 bbaddr = ENGINE_READ(engine, RING_BBADDR);
1440
1441         return bbaddr;
1442 }
1443
1444 static unsigned long stop_timeout(const struct intel_engine_cs *engine)
1445 {
1446         if (in_atomic() || irqs_disabled()) /* inside atomic preempt-reset? */
1447                 return 0;
1448
1449         /*
1450          * If we are doing a normal GPU reset, we can take our time and allow
1451          * the engine to quiesce. We've stopped submission to the engine, and
1452          * if we wait long enough an innocent context should complete and
1453          * leave the engine idle. So they should not be caught unaware by
1454          * the forthcoming GPU reset (which usually follows the stop_cs)!
1455          */
1456         return READ_ONCE(engine->props.stop_timeout_ms);
1457 }
1458
1459 static int __intel_engine_stop_cs(struct intel_engine_cs *engine,
1460                                   int fast_timeout_us,
1461                                   int slow_timeout_ms)
1462 {
1463         struct intel_uncore *uncore = engine->uncore;
1464         const i915_reg_t mode = RING_MI_MODE(engine->mmio_base);
1465         int err;
1466
1467         intel_uncore_write_fw(uncore, mode, _MASKED_BIT_ENABLE(STOP_RING));
1468
1469         /*
1470          * Wa_22011802037 : gen11, gen12, Prior to doing a reset, ensure CS is
1471          * stopped, set ring stop bit and prefetch disable bit to halt CS
1472          */
1473         if (IS_GRAPHICS_VER(engine->i915, 11, 12))
1474                 intel_uncore_write_fw(uncore, RING_MODE_GEN7(engine->mmio_base),
1475                                       _MASKED_BIT_ENABLE(GEN12_GFX_PREFETCH_DISABLE));
1476
1477         err = __intel_wait_for_register_fw(engine->uncore, mode,
1478                                            MODE_IDLE, MODE_IDLE,
1479                                            fast_timeout_us,
1480                                            slow_timeout_ms,
1481                                            NULL);
1482
1483         /* A final mmio read to let GPU writes be hopefully flushed to memory */
1484         intel_uncore_posting_read_fw(uncore, mode);
1485         return err;
1486 }
1487
1488 int intel_engine_stop_cs(struct intel_engine_cs *engine)
1489 {
1490         int err = 0;
1491
1492         if (GRAPHICS_VER(engine->i915) < 3)
1493                 return -ENODEV;
1494
1495         ENGINE_TRACE(engine, "\n");
1496         /*
1497          * TODO: Find out why occasionally stopping the CS times out. Seen
1498          * especially with gem_eio tests.
1499          *
1500          * Occasionally trying to stop the cs times out, but does not adversely
1501          * affect functionality. The timeout is set as a config parameter that
1502          * defaults to 100ms. In most cases the follow up operation is to wait
1503          * for pending MI_FORCE_WAKES. The assumption is that this timeout is
1504          * sufficient for any pending MI_FORCEWAKEs to complete. Once root
1505          * caused, the caller must check and handle the return from this
1506          * function.
1507          */
1508         if (__intel_engine_stop_cs(engine, 1000, stop_timeout(engine))) {
1509                 ENGINE_TRACE(engine,
1510                              "timed out on STOP_RING -> IDLE; HEAD:%04x, TAIL:%04x\n",
1511                              ENGINE_READ_FW(engine, RING_HEAD) & HEAD_ADDR,
1512                              ENGINE_READ_FW(engine, RING_TAIL) & TAIL_ADDR);
1513
1514                 /*
1515                  * Sometimes we observe that the idle flag is not
1516                  * set even though the ring is empty. So double
1517                  * check before giving up.
1518                  */
1519                 if ((ENGINE_READ_FW(engine, RING_HEAD) & HEAD_ADDR) !=
1520                     (ENGINE_READ_FW(engine, RING_TAIL) & TAIL_ADDR))
1521                         err = -ETIMEDOUT;
1522         }
1523
1524         return err;
1525 }
1526
1527 void intel_engine_cancel_stop_cs(struct intel_engine_cs *engine)
1528 {
1529         ENGINE_TRACE(engine, "\n");
1530
1531         ENGINE_WRITE_FW(engine, RING_MI_MODE, _MASKED_BIT_DISABLE(STOP_RING));
1532 }
1533
1534 static u32 __cs_pending_mi_force_wakes(struct intel_engine_cs *engine)
1535 {
1536         static const i915_reg_t _reg[I915_NUM_ENGINES] = {
1537                 [RCS0] = MSG_IDLE_CS,
1538                 [BCS0] = MSG_IDLE_BCS,
1539                 [VCS0] = MSG_IDLE_VCS0,
1540                 [VCS1] = MSG_IDLE_VCS1,
1541                 [VCS2] = MSG_IDLE_VCS2,
1542                 [VCS3] = MSG_IDLE_VCS3,
1543                 [VCS4] = MSG_IDLE_VCS4,
1544                 [VCS5] = MSG_IDLE_VCS5,
1545                 [VCS6] = MSG_IDLE_VCS6,
1546                 [VCS7] = MSG_IDLE_VCS7,
1547                 [VECS0] = MSG_IDLE_VECS0,
1548                 [VECS1] = MSG_IDLE_VECS1,
1549                 [VECS2] = MSG_IDLE_VECS2,
1550                 [VECS3] = MSG_IDLE_VECS3,
1551                 [CCS0] = MSG_IDLE_CS,
1552                 [CCS1] = MSG_IDLE_CS,
1553                 [CCS2] = MSG_IDLE_CS,
1554                 [CCS3] = MSG_IDLE_CS,
1555         };
1556         u32 val;
1557
1558         if (!_reg[engine->id].reg) {
1559                 drm_err(&engine->i915->drm,
1560                         "MSG IDLE undefined for engine id %u\n", engine->id);
1561                 return 0;
1562         }
1563
1564         val = intel_uncore_read(engine->uncore, _reg[engine->id]);
1565
1566         /* bits[29:25] & bits[13:9] >> shift */
1567         return (val & (val >> 16) & MSG_IDLE_FW_MASK) >> MSG_IDLE_FW_SHIFT;
1568 }
1569
1570 static void __gpm_wait_for_fw_complete(struct intel_gt *gt, u32 fw_mask)
1571 {
1572         int ret;
1573
1574         /* Ensure GPM receives fw up/down after CS is stopped */
1575         udelay(1);
1576
1577         /* Wait for forcewake request to complete in GPM */
1578         ret =  __intel_wait_for_register_fw(gt->uncore,
1579                                             GEN9_PWRGT_DOMAIN_STATUS,
1580                                             fw_mask, fw_mask, 5000, 0, NULL);
1581
1582         /* Ensure CS receives fw ack from GPM */
1583         udelay(1);
1584
1585         if (ret)
1586                 GT_TRACE(gt, "Failed to complete pending forcewake %d\n", ret);
1587 }
1588
1589 /*
1590  * Wa_22011802037:gen12: In addition to stopping the cs, we need to wait for any
1591  * pending MI_FORCE_WAKEUP requests that the CS has initiated to complete. The
1592  * pending status is indicated by bits[13:9] (masked by bits[29:25]) in the
1593  * MSG_IDLE register. There's one MSG_IDLE register per reset domain. Since we
1594  * are concerned only with the gt reset here, we use a logical OR of pending
1595  * forcewakeups from all reset domains and then wait for them to complete by
1596  * querying PWRGT_DOMAIN_STATUS.
1597  */
1598 void intel_engine_wait_for_pending_mi_fw(struct intel_engine_cs *engine)
1599 {
1600         u32 fw_pending = __cs_pending_mi_force_wakes(engine);
1601
1602         if (fw_pending)
1603                 __gpm_wait_for_fw_complete(engine->gt, fw_pending);
1604 }
1605
1606 /* NB: please notice the memset */
1607 void intel_engine_get_instdone(const struct intel_engine_cs *engine,
1608                                struct intel_instdone *instdone)
1609 {
1610         struct drm_i915_private *i915 = engine->i915;
1611         struct intel_uncore *uncore = engine->uncore;
1612         u32 mmio_base = engine->mmio_base;
1613         int slice;
1614         int subslice;
1615         int iter;
1616
1617         memset(instdone, 0, sizeof(*instdone));
1618
1619         if (GRAPHICS_VER(i915) >= 8) {
1620                 instdone->instdone =
1621                         intel_uncore_read(uncore, RING_INSTDONE(mmio_base));
1622
1623                 if (engine->id != RCS0)
1624                         return;
1625
1626                 instdone->slice_common =
1627                         intel_uncore_read(uncore, GEN7_SC_INSTDONE);
1628                 if (GRAPHICS_VER(i915) >= 12) {
1629                         instdone->slice_common_extra[0] =
1630                                 intel_uncore_read(uncore, GEN12_SC_INSTDONE_EXTRA);
1631                         instdone->slice_common_extra[1] =
1632                                 intel_uncore_read(uncore, GEN12_SC_INSTDONE_EXTRA2);
1633                 }
1634
1635                 for_each_ss_steering(iter, engine->gt, slice, subslice) {
1636                         instdone->sampler[slice][subslice] =
1637                                 intel_gt_mcr_read(engine->gt,
1638                                                   GEN8_SAMPLER_INSTDONE,
1639                                                   slice, subslice);
1640                         instdone->row[slice][subslice] =
1641                                 intel_gt_mcr_read(engine->gt,
1642                                                   GEN8_ROW_INSTDONE,
1643                                                   slice, subslice);
1644                 }
1645
1646                 if (GRAPHICS_VER_FULL(i915) >= IP_VER(12, 55)) {
1647                         for_each_ss_steering(iter, engine->gt, slice, subslice)
1648                                 instdone->geom_svg[slice][subslice] =
1649                                         intel_gt_mcr_read(engine->gt,
1650                                                           XEHPG_INSTDONE_GEOM_SVG,
1651                                                           slice, subslice);
1652                 }
1653         } else if (GRAPHICS_VER(i915) >= 7) {
1654                 instdone->instdone =
1655                         intel_uncore_read(uncore, RING_INSTDONE(mmio_base));
1656
1657                 if (engine->id != RCS0)
1658                         return;
1659
1660                 instdone->slice_common =
1661                         intel_uncore_read(uncore, GEN7_SC_INSTDONE);
1662                 instdone->sampler[0][0] =
1663                         intel_uncore_read(uncore, GEN7_SAMPLER_INSTDONE);
1664                 instdone->row[0][0] =
1665                         intel_uncore_read(uncore, GEN7_ROW_INSTDONE);
1666         } else if (GRAPHICS_VER(i915) >= 4) {
1667                 instdone->instdone =
1668                         intel_uncore_read(uncore, RING_INSTDONE(mmio_base));
1669                 if (engine->id == RCS0)
1670                         /* HACK: Using the wrong struct member */
1671                         instdone->slice_common =
1672                                 intel_uncore_read(uncore, GEN4_INSTDONE1);
1673         } else {
1674                 instdone->instdone = intel_uncore_read(uncore, GEN2_INSTDONE);
1675         }
1676 }
1677
1678 static bool ring_is_idle(struct intel_engine_cs *engine)
1679 {
1680         bool idle = true;
1681
1682         if (I915_SELFTEST_ONLY(!engine->mmio_base))
1683                 return true;
1684
1685         if (!intel_engine_pm_get_if_awake(engine))
1686                 return true;
1687
1688         /* First check that no commands are left in the ring */
1689         if ((ENGINE_READ(engine, RING_HEAD) & HEAD_ADDR) !=
1690             (ENGINE_READ(engine, RING_TAIL) & TAIL_ADDR))
1691                 idle = false;
1692
1693         /* No bit for gen2, so assume the CS parser is idle */
1694         if (GRAPHICS_VER(engine->i915) > 2 &&
1695             !(ENGINE_READ(engine, RING_MI_MODE) & MODE_IDLE))
1696                 idle = false;
1697
1698         intel_engine_pm_put(engine);
1699
1700         return idle;
1701 }
1702
1703 void __intel_engine_flush_submission(struct intel_engine_cs *engine, bool sync)
1704 {
1705         struct tasklet_struct *t = &engine->sched_engine->tasklet;
1706
1707         if (!t->callback)
1708                 return;
1709
1710         local_bh_disable();
1711         if (tasklet_trylock(t)) {
1712                 /* Must wait for any GPU reset in progress. */
1713                 if (__tasklet_is_enabled(t))
1714                         t->callback(t);
1715                 tasklet_unlock(t);
1716         }
1717         local_bh_enable();
1718
1719         /* Synchronise and wait for the tasklet on another CPU */
1720         if (sync)
1721                 tasklet_unlock_wait(t);
1722 }
1723
1724 /**
1725  * intel_engine_is_idle() - Report if the engine has finished process all work
1726  * @engine: the intel_engine_cs
1727  *
1728  * Return true if there are no requests pending, nothing left to be submitted
1729  * to hardware, and that the engine is idle.
1730  */
1731 bool intel_engine_is_idle(struct intel_engine_cs *engine)
1732 {
1733         /* More white lies, if wedged, hw state is inconsistent */
1734         if (intel_gt_is_wedged(engine->gt))
1735                 return true;
1736
1737         if (!intel_engine_pm_is_awake(engine))
1738                 return true;
1739
1740         /* Waiting to drain ELSP? */
1741         intel_synchronize_hardirq(engine->i915);
1742         intel_engine_flush_submission(engine);
1743
1744         /* ELSP is empty, but there are ready requests? E.g. after reset */
1745         if (!i915_sched_engine_is_empty(engine->sched_engine))
1746                 return false;
1747
1748         /* Ring stopped? */
1749         return ring_is_idle(engine);
1750 }
1751
1752 bool intel_engines_are_idle(struct intel_gt *gt)
1753 {
1754         struct intel_engine_cs *engine;
1755         enum intel_engine_id id;
1756
1757         /*
1758          * If the driver is wedged, HW state may be very inconsistent and
1759          * report that it is still busy, even though we have stopped using it.
1760          */
1761         if (intel_gt_is_wedged(gt))
1762                 return true;
1763
1764         /* Already parked (and passed an idleness test); must still be idle */
1765         if (!READ_ONCE(gt->awake))
1766                 return true;
1767
1768         for_each_engine(engine, gt, id) {
1769                 if (!intel_engine_is_idle(engine))
1770                         return false;
1771         }
1772
1773         return true;
1774 }
1775
1776 bool intel_engine_irq_enable(struct intel_engine_cs *engine)
1777 {
1778         if (!engine->irq_enable)
1779                 return false;
1780
1781         /* Caller disables interrupts */
1782         spin_lock(engine->gt->irq_lock);
1783         engine->irq_enable(engine);
1784         spin_unlock(engine->gt->irq_lock);
1785
1786         return true;
1787 }
1788
1789 void intel_engine_irq_disable(struct intel_engine_cs *engine)
1790 {
1791         if (!engine->irq_disable)
1792                 return;
1793
1794         /* Caller disables interrupts */
1795         spin_lock(engine->gt->irq_lock);
1796         engine->irq_disable(engine);
1797         spin_unlock(engine->gt->irq_lock);
1798 }
1799
1800 void intel_engines_reset_default_submission(struct intel_gt *gt)
1801 {
1802         struct intel_engine_cs *engine;
1803         enum intel_engine_id id;
1804
1805         for_each_engine(engine, gt, id) {
1806                 if (engine->sanitize)
1807                         engine->sanitize(engine);
1808
1809                 engine->set_default_submission(engine);
1810         }
1811 }
1812
1813 bool intel_engine_can_store_dword(struct intel_engine_cs *engine)
1814 {
1815         switch (GRAPHICS_VER(engine->i915)) {
1816         case 2:
1817                 return false; /* uses physical not virtual addresses */
1818         case 3:
1819                 /* maybe only uses physical not virtual addresses */
1820                 return !(IS_I915G(engine->i915) || IS_I915GM(engine->i915));
1821         case 4:
1822                 return !IS_I965G(engine->i915); /* who knows! */
1823         case 6:
1824                 return engine->class != VIDEO_DECODE_CLASS; /* b0rked */
1825         default:
1826                 return true;
1827         }
1828 }
1829
1830 static struct intel_timeline *get_timeline(struct i915_request *rq)
1831 {
1832         struct intel_timeline *tl;
1833
1834         /*
1835          * Even though we are holding the engine->sched_engine->lock here, there
1836          * is no control over the submission queue per-se and we are
1837          * inspecting the active state at a random point in time, with an
1838          * unknown queue. Play safe and make sure the timeline remains valid.
1839          * (Only being used for pretty printing, one extra kref shouldn't
1840          * cause a camel stampede!)
1841          */
1842         rcu_read_lock();
1843         tl = rcu_dereference(rq->timeline);
1844         if (!kref_get_unless_zero(&tl->kref))
1845                 tl = NULL;
1846         rcu_read_unlock();
1847
1848         return tl;
1849 }
1850
1851 static int print_ring(char *buf, int sz, struct i915_request *rq)
1852 {
1853         int len = 0;
1854
1855         if (!i915_request_signaled(rq)) {
1856                 struct intel_timeline *tl = get_timeline(rq);
1857
1858                 len = scnprintf(buf, sz,
1859                                 "ring:{start:%08x, hwsp:%08x, seqno:%08x, runtime:%llums}, ",
1860                                 i915_ggtt_offset(rq->ring->vma),
1861                                 tl ? tl->hwsp_offset : 0,
1862                                 hwsp_seqno(rq),
1863                                 DIV_ROUND_CLOSEST_ULL(intel_context_get_total_runtime_ns(rq->context),
1864                                                       1000 * 1000));
1865
1866                 if (tl)
1867                         intel_timeline_put(tl);
1868         }
1869
1870         return len;
1871 }
1872
1873 static void hexdump(struct drm_printer *m, const void *buf, size_t len)
1874 {
1875         const size_t rowsize = 8 * sizeof(u32);
1876         const void *prev = NULL;
1877         bool skip = false;
1878         size_t pos;
1879
1880         for (pos = 0; pos < len; pos += rowsize) {
1881                 char line[128];
1882
1883                 if (prev && !memcmp(prev, buf + pos, rowsize)) {
1884                         if (!skip) {
1885                                 drm_printf(m, "*\n");
1886                                 skip = true;
1887                         }
1888                         continue;
1889                 }
1890
1891                 WARN_ON_ONCE(hex_dump_to_buffer(buf + pos, len - pos,
1892                                                 rowsize, sizeof(u32),
1893                                                 line, sizeof(line),
1894                                                 false) >= sizeof(line));
1895                 drm_printf(m, "[%04zx] %s\n", pos, line);
1896
1897                 prev = buf + pos;
1898                 skip = false;
1899         }
1900 }
1901
1902 static const char *repr_timer(const struct timer_list *t)
1903 {
1904         if (!READ_ONCE(t->expires))
1905                 return "inactive";
1906
1907         if (timer_pending(t))
1908                 return "active";
1909
1910         return "expired";
1911 }
1912
1913 static void intel_engine_print_registers(struct intel_engine_cs *engine,
1914                                          struct drm_printer *m)
1915 {
1916         struct drm_i915_private *dev_priv = engine->i915;
1917         struct intel_engine_execlists * const execlists = &engine->execlists;
1918         u64 addr;
1919
1920         if (engine->id == RENDER_CLASS && IS_GRAPHICS_VER(dev_priv, 4, 7))
1921                 drm_printf(m, "\tCCID: 0x%08x\n", ENGINE_READ(engine, CCID));
1922         if (HAS_EXECLISTS(dev_priv)) {
1923                 drm_printf(m, "\tEL_STAT_HI: 0x%08x\n",
1924                            ENGINE_READ(engine, RING_EXECLIST_STATUS_HI));
1925                 drm_printf(m, "\tEL_STAT_LO: 0x%08x\n",
1926                            ENGINE_READ(engine, RING_EXECLIST_STATUS_LO));
1927         }
1928         drm_printf(m, "\tRING_START: 0x%08x\n",
1929                    ENGINE_READ(engine, RING_START));
1930         drm_printf(m, "\tRING_HEAD:  0x%08x\n",
1931                    ENGINE_READ(engine, RING_HEAD) & HEAD_ADDR);
1932         drm_printf(m, "\tRING_TAIL:  0x%08x\n",
1933                    ENGINE_READ(engine, RING_TAIL) & TAIL_ADDR);
1934         drm_printf(m, "\tRING_CTL:   0x%08x%s\n",
1935                    ENGINE_READ(engine, RING_CTL),
1936                    ENGINE_READ(engine, RING_CTL) & (RING_WAIT | RING_WAIT_SEMAPHORE) ? " [waiting]" : "");
1937         if (GRAPHICS_VER(engine->i915) > 2) {
1938                 drm_printf(m, "\tRING_MODE:  0x%08x%s\n",
1939                            ENGINE_READ(engine, RING_MI_MODE),
1940                            ENGINE_READ(engine, RING_MI_MODE) & (MODE_IDLE) ? " [idle]" : "");
1941         }
1942
1943         if (GRAPHICS_VER(dev_priv) >= 6) {
1944                 drm_printf(m, "\tRING_IMR:   0x%08x\n",
1945                            ENGINE_READ(engine, RING_IMR));
1946                 drm_printf(m, "\tRING_ESR:   0x%08x\n",
1947                            ENGINE_READ(engine, RING_ESR));
1948                 drm_printf(m, "\tRING_EMR:   0x%08x\n",
1949                            ENGINE_READ(engine, RING_EMR));
1950                 drm_printf(m, "\tRING_EIR:   0x%08x\n",
1951                            ENGINE_READ(engine, RING_EIR));
1952         }
1953
1954         addr = intel_engine_get_active_head(engine);
1955         drm_printf(m, "\tACTHD:  0x%08x_%08x\n",
1956                    upper_32_bits(addr), lower_32_bits(addr));
1957         addr = intel_engine_get_last_batch_head(engine);
1958         drm_printf(m, "\tBBADDR: 0x%08x_%08x\n",
1959                    upper_32_bits(addr), lower_32_bits(addr));
1960         if (GRAPHICS_VER(dev_priv) >= 8)
1961                 addr = ENGINE_READ64(engine, RING_DMA_FADD, RING_DMA_FADD_UDW);
1962         else if (GRAPHICS_VER(dev_priv) >= 4)
1963                 addr = ENGINE_READ(engine, RING_DMA_FADD);
1964         else
1965                 addr = ENGINE_READ(engine, DMA_FADD_I8XX);
1966         drm_printf(m, "\tDMA_FADDR: 0x%08x_%08x\n",
1967                    upper_32_bits(addr), lower_32_bits(addr));
1968         if (GRAPHICS_VER(dev_priv) >= 4) {
1969                 drm_printf(m, "\tIPEIR: 0x%08x\n",
1970                            ENGINE_READ(engine, RING_IPEIR));
1971                 drm_printf(m, "\tIPEHR: 0x%08x\n",
1972                            ENGINE_READ(engine, RING_IPEHR));
1973         } else {
1974                 drm_printf(m, "\tIPEIR: 0x%08x\n", ENGINE_READ(engine, IPEIR));
1975                 drm_printf(m, "\tIPEHR: 0x%08x\n", ENGINE_READ(engine, IPEHR));
1976         }
1977
1978         if (HAS_EXECLISTS(dev_priv) && !intel_engine_uses_guc(engine)) {
1979                 struct i915_request * const *port, *rq;
1980                 const u32 *hws =
1981                         &engine->status_page.addr[I915_HWS_CSB_BUF0_INDEX];
1982                 const u8 num_entries = execlists->csb_size;
1983                 unsigned int idx;
1984                 u8 read, write;
1985
1986                 drm_printf(m, "\tExeclist tasklet queued? %s (%s), preempt? %s, timeslice? %s\n",
1987                            str_yes_no(test_bit(TASKLET_STATE_SCHED, &engine->sched_engine->tasklet.state)),
1988                            str_enabled_disabled(!atomic_read(&engine->sched_engine->tasklet.count)),
1989                            repr_timer(&engine->execlists.preempt),
1990                            repr_timer(&engine->execlists.timer));
1991
1992                 read = execlists->csb_head;
1993                 write = READ_ONCE(*execlists->csb_write);
1994
1995                 drm_printf(m, "\tExeclist status: 0x%08x %08x; CSB read:%d, write:%d, entries:%d\n",
1996                            ENGINE_READ(engine, RING_EXECLIST_STATUS_LO),
1997                            ENGINE_READ(engine, RING_EXECLIST_STATUS_HI),
1998                            read, write, num_entries);
1999
2000                 if (read >= num_entries)
2001                         read = 0;
2002                 if (write >= num_entries)
2003                         write = 0;
2004                 if (read > write)
2005                         write += num_entries;
2006                 while (read < write) {
2007                         idx = ++read % num_entries;
2008                         drm_printf(m, "\tExeclist CSB[%d]: 0x%08x, context: %d\n",
2009                                    idx, hws[idx * 2], hws[idx * 2 + 1]);
2010                 }
2011
2012                 i915_sched_engine_active_lock_bh(engine->sched_engine);
2013                 rcu_read_lock();
2014                 for (port = execlists->active; (rq = *port); port++) {
2015                         char hdr[160];
2016                         int len;
2017
2018                         len = scnprintf(hdr, sizeof(hdr),
2019                                         "\t\tActive[%d]:  ccid:%08x%s%s, ",
2020                                         (int)(port - execlists->active),
2021                                         rq->context->lrc.ccid,
2022                                         intel_context_is_closed(rq->context) ? "!" : "",
2023                                         intel_context_is_banned(rq->context) ? "*" : "");
2024                         len += print_ring(hdr + len, sizeof(hdr) - len, rq);
2025                         scnprintf(hdr + len, sizeof(hdr) - len, "rq: ");
2026                         i915_request_show(m, rq, hdr, 0);
2027                 }
2028                 for (port = execlists->pending; (rq = *port); port++) {
2029                         char hdr[160];
2030                         int len;
2031
2032                         len = scnprintf(hdr, sizeof(hdr),
2033                                         "\t\tPending[%d]: ccid:%08x%s%s, ",
2034                                         (int)(port - execlists->pending),
2035                                         rq->context->lrc.ccid,
2036                                         intel_context_is_closed(rq->context) ? "!" : "",
2037                                         intel_context_is_banned(rq->context) ? "*" : "");
2038                         len += print_ring(hdr + len, sizeof(hdr) - len, rq);
2039                         scnprintf(hdr + len, sizeof(hdr) - len, "rq: ");
2040                         i915_request_show(m, rq, hdr, 0);
2041                 }
2042                 rcu_read_unlock();
2043                 i915_sched_engine_active_unlock_bh(engine->sched_engine);
2044         } else if (GRAPHICS_VER(dev_priv) > 6) {
2045                 drm_printf(m, "\tPP_DIR_BASE: 0x%08x\n",
2046                            ENGINE_READ(engine, RING_PP_DIR_BASE));
2047                 drm_printf(m, "\tPP_DIR_BASE_READ: 0x%08x\n",
2048                            ENGINE_READ(engine, RING_PP_DIR_BASE_READ));
2049                 drm_printf(m, "\tPP_DIR_DCLV: 0x%08x\n",
2050                            ENGINE_READ(engine, RING_PP_DIR_DCLV));
2051         }
2052 }
2053
2054 static void print_request_ring(struct drm_printer *m, struct i915_request *rq)
2055 {
2056         struct i915_vma_resource *vma_res = rq->batch_res;
2057         void *ring;
2058         int size;
2059
2060         drm_printf(m,
2061                    "[head %04x, postfix %04x, tail %04x, batch 0x%08x_%08x]:\n",
2062                    rq->head, rq->postfix, rq->tail,
2063                    vma_res ? upper_32_bits(vma_res->start) : ~0u,
2064                    vma_res ? lower_32_bits(vma_res->start) : ~0u);
2065
2066         size = rq->tail - rq->head;
2067         if (rq->tail < rq->head)
2068                 size += rq->ring->size;
2069
2070         ring = kmalloc(size, GFP_ATOMIC);
2071         if (ring) {
2072                 const void *vaddr = rq->ring->vaddr;
2073                 unsigned int head = rq->head;
2074                 unsigned int len = 0;
2075
2076                 if (rq->tail < head) {
2077                         len = rq->ring->size - head;
2078                         memcpy(ring, vaddr + head, len);
2079                         head = 0;
2080                 }
2081                 memcpy(ring + len, vaddr + head, size - len);
2082
2083                 hexdump(m, ring, size);
2084                 kfree(ring);
2085         }
2086 }
2087
2088 static unsigned long list_count(struct list_head *list)
2089 {
2090         struct list_head *pos;
2091         unsigned long count = 0;
2092
2093         list_for_each(pos, list)
2094                 count++;
2095
2096         return count;
2097 }
2098
2099 static unsigned long read_ul(void *p, size_t x)
2100 {
2101         return *(unsigned long *)(p + x);
2102 }
2103
2104 static void print_properties(struct intel_engine_cs *engine,
2105                              struct drm_printer *m)
2106 {
2107         static const struct pmap {
2108                 size_t offset;
2109                 const char *name;
2110         } props[] = {
2111 #define P(x) { \
2112         .offset = offsetof(typeof(engine->props), x), \
2113         .name = #x \
2114 }
2115                 P(heartbeat_interval_ms),
2116                 P(max_busywait_duration_ns),
2117                 P(preempt_timeout_ms),
2118                 P(stop_timeout_ms),
2119                 P(timeslice_duration_ms),
2120
2121                 {},
2122 #undef P
2123         };
2124         const struct pmap *p;
2125
2126         drm_printf(m, "\tProperties:\n");
2127         for (p = props; p->name; p++)
2128                 drm_printf(m, "\t\t%s: %lu [default %lu]\n",
2129                            p->name,
2130                            read_ul(&engine->props, p->offset),
2131                            read_ul(&engine->defaults, p->offset));
2132 }
2133
2134 static void engine_dump_request(struct i915_request *rq, struct drm_printer *m, const char *msg)
2135 {
2136         struct intel_timeline *tl = get_timeline(rq);
2137
2138         i915_request_show(m, rq, msg, 0);
2139
2140         drm_printf(m, "\t\tring->start:  0x%08x\n",
2141                    i915_ggtt_offset(rq->ring->vma));
2142         drm_printf(m, "\t\tring->head:   0x%08x\n",
2143                    rq->ring->head);
2144         drm_printf(m, "\t\tring->tail:   0x%08x\n",
2145                    rq->ring->tail);
2146         drm_printf(m, "\t\tring->emit:   0x%08x\n",
2147                    rq->ring->emit);
2148         drm_printf(m, "\t\tring->space:  0x%08x\n",
2149                    rq->ring->space);
2150
2151         if (tl) {
2152                 drm_printf(m, "\t\tring->hwsp:   0x%08x\n",
2153                            tl->hwsp_offset);
2154                 intel_timeline_put(tl);
2155         }
2156
2157         print_request_ring(m, rq);
2158
2159         if (rq->context->lrc_reg_state) {
2160                 drm_printf(m, "Logical Ring Context:\n");
2161                 hexdump(m, rq->context->lrc_reg_state, PAGE_SIZE);
2162         }
2163 }
2164
2165 void intel_engine_dump_active_requests(struct list_head *requests,
2166                                        struct i915_request *hung_rq,
2167                                        struct drm_printer *m)
2168 {
2169         struct i915_request *rq;
2170         const char *msg;
2171         enum i915_request_state state;
2172
2173         list_for_each_entry(rq, requests, sched.link) {
2174                 if (rq == hung_rq)
2175                         continue;
2176
2177                 state = i915_test_request_state(rq);
2178                 if (state < I915_REQUEST_QUEUED)
2179                         continue;
2180
2181                 if (state == I915_REQUEST_ACTIVE)
2182                         msg = "\t\tactive on engine";
2183                 else
2184                         msg = "\t\tactive in queue";
2185
2186                 engine_dump_request(rq, m, msg);
2187         }
2188 }
2189
2190 static void engine_dump_active_requests(struct intel_engine_cs *engine, struct drm_printer *m)
2191 {
2192         struct i915_request *hung_rq = NULL;
2193         struct intel_context *ce;
2194         bool guc;
2195
2196         /*
2197          * No need for an engine->irq_seqno_barrier() before the seqno reads.
2198          * The GPU is still running so requests are still executing and any
2199          * hardware reads will be out of date by the time they are reported.
2200          * But the intention here is just to report an instantaneous snapshot
2201          * so that's fine.
2202          */
2203         lockdep_assert_held(&engine->sched_engine->lock);
2204
2205         drm_printf(m, "\tRequests:\n");
2206
2207         guc = intel_uc_uses_guc_submission(&engine->gt->uc);
2208         if (guc) {
2209                 ce = intel_engine_get_hung_context(engine);
2210                 if (ce)
2211                         hung_rq = intel_context_find_active_request(ce);
2212         } else {
2213                 hung_rq = intel_engine_execlist_find_hung_request(engine);
2214         }
2215
2216         if (hung_rq)
2217                 engine_dump_request(hung_rq, m, "\t\thung");
2218
2219         if (guc)
2220                 intel_guc_dump_active_requests(engine, hung_rq, m);
2221         else
2222                 intel_engine_dump_active_requests(&engine->sched_engine->requests,
2223                                                   hung_rq, m);
2224 }
2225
2226 void intel_engine_dump(struct intel_engine_cs *engine,
2227                        struct drm_printer *m,
2228                        const char *header, ...)
2229 {
2230         struct i915_gpu_error * const error = &engine->i915->gpu_error;
2231         struct i915_request *rq;
2232         intel_wakeref_t wakeref;
2233         unsigned long flags;
2234         ktime_t dummy;
2235
2236         if (header) {
2237                 va_list ap;
2238
2239                 va_start(ap, header);
2240                 drm_vprintf(m, header, &ap);
2241                 va_end(ap);
2242         }
2243
2244         if (intel_gt_is_wedged(engine->gt))
2245                 drm_printf(m, "*** WEDGED ***\n");
2246
2247         drm_printf(m, "\tAwake? %d\n", atomic_read(&engine->wakeref.count));
2248         drm_printf(m, "\tBarriers?: %s\n",
2249                    str_yes_no(!llist_empty(&engine->barrier_tasks)));
2250         drm_printf(m, "\tLatency: %luus\n",
2251                    ewma__engine_latency_read(&engine->latency));
2252         if (intel_engine_supports_stats(engine))
2253                 drm_printf(m, "\tRuntime: %llums\n",
2254                            ktime_to_ms(intel_engine_get_busy_time(engine,
2255                                                                   &dummy)));
2256         drm_printf(m, "\tForcewake: %x domains, %d active\n",
2257                    engine->fw_domain, READ_ONCE(engine->fw_active));
2258
2259         rcu_read_lock();
2260         rq = READ_ONCE(engine->heartbeat.systole);
2261         if (rq)
2262                 drm_printf(m, "\tHeartbeat: %d ms ago\n",
2263                            jiffies_to_msecs(jiffies - rq->emitted_jiffies));
2264         rcu_read_unlock();
2265         drm_printf(m, "\tReset count: %d (global %d)\n",
2266                    i915_reset_engine_count(error, engine),
2267                    i915_reset_count(error));
2268         print_properties(engine, m);
2269
2270         spin_lock_irqsave(&engine->sched_engine->lock, flags);
2271         engine_dump_active_requests(engine, m);
2272
2273         drm_printf(m, "\tOn hold?: %lu\n",
2274                    list_count(&engine->sched_engine->hold));
2275         spin_unlock_irqrestore(&engine->sched_engine->lock, flags);
2276
2277         drm_printf(m, "\tMMIO base:  0x%08x\n", engine->mmio_base);
2278         wakeref = intel_runtime_pm_get_if_in_use(engine->uncore->rpm);
2279         if (wakeref) {
2280                 intel_engine_print_registers(engine, m);
2281                 intel_runtime_pm_put(engine->uncore->rpm, wakeref);
2282         } else {
2283                 drm_printf(m, "\tDevice is asleep; skipping register dump\n");
2284         }
2285
2286         intel_execlists_show_requests(engine, m, i915_request_show, 8);
2287
2288         drm_printf(m, "HWSP:\n");
2289         hexdump(m, engine->status_page.addr, PAGE_SIZE);
2290
2291         drm_printf(m, "Idle? %s\n", str_yes_no(intel_engine_is_idle(engine)));
2292
2293         intel_engine_print_breadcrumbs(engine, m);
2294 }
2295
2296 /**
2297  * intel_engine_get_busy_time() - Return current accumulated engine busyness
2298  * @engine: engine to report on
2299  * @now: monotonic timestamp of sampling
2300  *
2301  * Returns accumulated time @engine was busy since engine stats were enabled.
2302  */
2303 ktime_t intel_engine_get_busy_time(struct intel_engine_cs *engine, ktime_t *now)
2304 {
2305         return engine->busyness(engine, now);
2306 }
2307
2308 struct intel_context *
2309 intel_engine_create_virtual(struct intel_engine_cs **siblings,
2310                             unsigned int count, unsigned long flags)
2311 {
2312         if (count == 0)
2313                 return ERR_PTR(-EINVAL);
2314
2315         if (count == 1 && !(flags & FORCE_VIRTUAL))
2316                 return intel_context_create(siblings[0]);
2317
2318         GEM_BUG_ON(!siblings[0]->cops->create_virtual);
2319         return siblings[0]->cops->create_virtual(siblings, count, flags);
2320 }
2321
2322 struct i915_request *
2323 intel_engine_execlist_find_hung_request(struct intel_engine_cs *engine)
2324 {
2325         struct i915_request *request, *active = NULL;
2326
2327         /*
2328          * This search does not work in GuC submission mode. However, the GuC
2329          * will report the hanging context directly to the driver itself. So
2330          * the driver should never get here when in GuC mode.
2331          */
2332         GEM_BUG_ON(intel_uc_uses_guc_submission(&engine->gt->uc));
2333
2334         /*
2335          * We are called by the error capture, reset and to dump engine
2336          * state at random points in time. In particular, note that neither is
2337          * crucially ordered with an interrupt. After a hang, the GPU is dead
2338          * and we assume that no more writes can happen (we waited long enough
2339          * for all writes that were in transaction to be flushed) - adding an
2340          * extra delay for a recent interrupt is pointless. Hence, we do
2341          * not need an engine->irq_seqno_barrier() before the seqno reads.
2342          * At all other times, we must assume the GPU is still running, but
2343          * we only care about the snapshot of this moment.
2344          */
2345         lockdep_assert_held(&engine->sched_engine->lock);
2346
2347         rcu_read_lock();
2348         request = execlists_active(&engine->execlists);
2349         if (request) {
2350                 struct intel_timeline *tl = request->context->timeline;
2351
2352                 list_for_each_entry_from_reverse(request, &tl->requests, link) {
2353                         if (__i915_request_is_complete(request))
2354                                 break;
2355
2356                         active = request;
2357                 }
2358         }
2359         rcu_read_unlock();
2360         if (active)
2361                 return active;
2362
2363         list_for_each_entry(request, &engine->sched_engine->requests,
2364                             sched.link) {
2365                 if (i915_test_request_state(request) != I915_REQUEST_ACTIVE)
2366                         continue;
2367
2368                 active = request;
2369                 break;
2370         }
2371
2372         return active;
2373 }
2374
2375 void xehp_enable_ccs_engines(struct intel_engine_cs *engine)
2376 {
2377         /*
2378          * If there are any non-fused-off CCS engines, we need to enable CCS
2379          * support in the RCU_MODE register.  This only needs to be done once,
2380          * so for simplicity we'll take care of this in the RCS engine's
2381          * resume handler; since the RCS and all CCS engines belong to the
2382          * same reset domain and are reset together, this will also take care
2383          * of re-applying the setting after i915-triggered resets.
2384          */
2385         if (!CCS_MASK(engine->gt))
2386                 return;
2387
2388         intel_uncore_write(engine->uncore, GEN12_RCU_MODE,
2389                            _MASKED_BIT_ENABLE(GEN12_RCU_MODE_CCS_ENABLE));
2390 }
2391
2392 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
2393 #include "mock_engine.c"
2394 #include "selftest_engine.c"
2395 #include "selftest_engine_cs.c"
2396 #endif