xref: /linux/drivers/gpu/drm/panthor/panthor_sched.c (revision 889600e21e3be388a6817c2a0dac0411df860751)
1 // SPDX-License-Identifier: GPL-2.0 or MIT
2 /* Copyright 2023 Collabora ltd. */
3 
4 #include <drm/drm_drv.h>
5 #include <drm/drm_exec.h>
6 #include <drm/drm_file.h>
7 #include <drm/drm_managed.h>
8 #include <drm/drm_print.h>
9 #include <drm/gpu_scheduler.h>
10 #include <drm/panthor_drm.h>
11 
12 #include <linux/build_bug.h>
13 #include <linux/cleanup.h>
14 #include <linux/clk.h>
15 #include <linux/delay.h>
16 #include <linux/dma-mapping.h>
17 #include <linux/dma-resv.h>
18 #include <linux/firmware.h>
19 #include <linux/interrupt.h>
20 #include <linux/io.h>
21 #include <linux/iopoll.h>
22 #include <linux/iosys-map.h>
23 #include <linux/module.h>
24 #include <linux/platform_device.h>
25 #include <linux/pm_runtime.h>
26 #include <linux/rcupdate.h>
27 
28 #include "panthor_devfreq.h"
29 #include "panthor_device.h"
30 #include "panthor_fw.h"
31 #include "panthor_fw_regs.h"
32 #include "panthor_gem.h"
33 #include "panthor_gpu.h"
34 #include "panthor_gpu_regs.h"
35 #include "panthor_heap.h"
36 #include "panthor_mmu.h"
37 #include "panthor_sched.h"
38 
39 /**
40  * DOC: Scheduler
41  *
42  * Mali CSF hardware adopts a firmware-assisted scheduling model, where
43  * the firmware takes care of scheduling aspects, to some extent.
44  *
45  * The scheduling happens at the scheduling group level, each group
46  * contains 1 to N queues (N is FW/hardware dependent, and exposed
47  * through the firmware interface). Each queue is assigned a command
48  * stream ring buffer, which serves as a way to get jobs submitted to
49  * the GPU, among other things.
50  *
51  * The firmware can schedule a maximum of M groups (M is FW/hardware
52  * dependent, and exposed through the firmware interface). Passed
53  * this maximum number of groups, the kernel must take care of
54  * rotating the groups passed to the firmware so every group gets
55  * a chance to have his queues scheduled for execution.
56  *
57  * The current implementation only supports with kernel-mode queues.
58  * In other terms, userspace doesn't have access to the ring-buffer.
59  * Instead, userspace passes indirect command stream buffers that are
60  * called from the queue ring-buffer by the kernel using a pre-defined
61  * sequence of command stream instructions to ensure the userspace driver
62  * always gets consistent results (cache maintenance,
63  * synchronization, ...).
64  *
65  * We rely on the drm_gpu_scheduler framework to deal with job
66  * dependencies and submission. As any other driver dealing with a
67  * FW-scheduler, we use the 1:1 entity:scheduler mode, such that each
68  * entity has its own job scheduler. When a job is ready to be executed
69  * (all its dependencies are met), it is pushed to the appropriate
70  * queue ring-buffer, and the group is scheduled for execution if it
71  * wasn't already active.
72  *
73  * Kernel-side group scheduling is timeslice-based. When we have less
74  * groups than there are slots, the periodic tick is disabled and we
75  * just let the FW schedule the active groups. When there are more
76  * groups than slots, we let each group a chance to execute stuff for
77  * a given amount of time, and then re-evaluate and pick new groups
78  * to schedule. The group selection algorithm is based on
79  * priority+round-robin.
80  *
81  * Even though user-mode queues is out of the scope right now, the
82  * current design takes them into account by avoiding any guess on the
83  * group/queue state that would be based on information we wouldn't have
84  * if userspace was in charge of the ring-buffer. That's also one of the
85  * reason we don't do 'cooperative' scheduling (encoding FW group slot
86  * reservation as dma_fence that would be returned from the
87  * drm_gpu_scheduler::prepare_job() hook, and treating group rotation as
88  * a queue of waiters, ordered by job submission order). This approach
89  * would work for kernel-mode queues, but would make user-mode queues a
90  * lot more complicated to retrofit.
91  */
92 
93 #define JOB_TIMEOUT_MS				5000
94 
95 #define MAX_CSG_PRIO				0xf
96 
97 #define NUM_INSTRS_PER_CACHE_LINE		(64 / sizeof(u64))
98 #define MAX_INSTRS_PER_JOB			24
99 
100 struct panthor_group;
101 
102 /**
103  * struct panthor_csg_slot - Command stream group slot
104  *
105  * This represents a FW slot for a scheduling group.
106  */
107 struct panthor_csg_slot {
108 	/** @group: Scheduling group bound to this slot. */
109 	struct panthor_group *group;
110 
111 	/** @priority: Group priority. */
112 	u8 priority;
113 };
114 
115 /**
116  * enum panthor_csg_priority - Group priority
117  */
118 enum panthor_csg_priority {
119 	/** @PANTHOR_CSG_PRIORITY_LOW: Low priority group. */
120 	PANTHOR_CSG_PRIORITY_LOW = 0,
121 
122 	/** @PANTHOR_CSG_PRIORITY_MEDIUM: Medium priority group. */
123 	PANTHOR_CSG_PRIORITY_MEDIUM,
124 
125 	/** @PANTHOR_CSG_PRIORITY_HIGH: High priority group. */
126 	PANTHOR_CSG_PRIORITY_HIGH,
127 
128 	/**
129 	 * @PANTHOR_CSG_PRIORITY_RT: Real-time priority group.
130 	 *
131 	 * Real-time priority allows one to preempt scheduling of other
132 	 * non-real-time groups. When such a group becomes executable,
133 	 * it will evict the group with the lowest non-rt priority if
134 	 * there's no free group slot available.
135 	 */
136 	PANTHOR_CSG_PRIORITY_RT,
137 
138 	/** @PANTHOR_CSG_PRIORITY_COUNT: Number of priority levels. */
139 	PANTHOR_CSG_PRIORITY_COUNT,
140 };
141 
142 /**
143  * struct panthor_scheduler - Object used to manage the scheduler
144  */
145 struct panthor_scheduler {
146 	/** @ptdev: Device. */
147 	struct panthor_device *ptdev;
148 
149 	/**
150 	 * @wq: Workqueue used by our internal scheduler logic and
151 	 * drm_gpu_scheduler.
152 	 *
153 	 * Used for the scheduler tick, group update or other kind of FW
154 	 * event processing that can't be handled in the threaded interrupt
155 	 * path. Also passed to the drm_gpu_scheduler instances embedded
156 	 * in panthor_queue.
157 	 */
158 	struct workqueue_struct *wq;
159 
160 	/**
161 	 * @heap_alloc_wq: Workqueue used to schedule tiler_oom works.
162 	 *
163 	 * We have a queue dedicated to heap chunk allocation works to avoid
164 	 * blocking the rest of the scheduler if the allocation tries to
165 	 * reclaim memory.
166 	 */
167 	struct workqueue_struct *heap_alloc_wq;
168 
169 	/** @tick_work: Work executed on a scheduling tick. */
170 	struct delayed_work tick_work;
171 
172 	/**
173 	 * @sync_upd_work: Work used to process synchronization object updates.
174 	 *
175 	 * We use this work to unblock queues/groups that were waiting on a
176 	 * synchronization object.
177 	 */
178 	struct work_struct sync_upd_work;
179 
180 	/**
181 	 * @fw_events_work: Work used to process FW events outside the interrupt path.
182 	 *
183 	 * Even if the interrupt is threaded, we need any event processing
184 	 * that require taking the panthor_scheduler::lock to be processed
185 	 * outside the interrupt path so we don't block the tick logic when
186 	 * it calls panthor_fw_{csg,wait}_wait_acks(). Since most of the
187 	 * event processing requires taking this lock, we just delegate all
188 	 * FW event processing to the scheduler workqueue.
189 	 */
190 	struct work_struct fw_events_work;
191 
192 	/**
193 	 * @fw_events: Bitmask encoding pending FW events.
194 	 */
195 	atomic_t fw_events;
196 
197 	/**
198 	 * @resched_target: When the next tick should occur.
199 	 *
200 	 * Expressed in jiffies.
201 	 */
202 	u64 resched_target;
203 
204 	/**
205 	 * @last_tick: When the last tick occurred.
206 	 *
207 	 * Expressed in jiffies.
208 	 */
209 	u64 last_tick;
210 
211 	/** @tick_period: Tick period in jiffies. */
212 	u64 tick_period;
213 
214 	/**
215 	 * @lock: Lock protecting access to all the scheduler fields.
216 	 *
217 	 * Should be taken in the tick work, the irq handler, and anywhere the @groups
218 	 * fields are touched.
219 	 */
220 	struct mutex lock;
221 
222 	/** @groups: Various lists used to classify groups. */
223 	struct {
224 		/**
225 		 * @groups.runnable: Runnable group lists.
226 		 *
227 		 * When a group has queues that want to execute something,
228 		 * its panthor_group::run_node should be inserted here.
229 		 *
230 		 * One list per-priority.
231 		 */
232 		struct list_head runnable[PANTHOR_CSG_PRIORITY_COUNT];
233 
234 		/**
235 		 * @groups.idle: Idle group lists.
236 		 *
237 		 * When all queues of a group are idle (either because they
238 		 * have nothing to execute, or because they are blocked), the
239 		 * panthor_group::run_node field should be inserted here.
240 		 *
241 		 * One list per-priority.
242 		 */
243 		struct list_head idle[PANTHOR_CSG_PRIORITY_COUNT];
244 
245 		/**
246 		 * @groups.waiting: List of groups whose queues are blocked on a
247 		 * synchronization object.
248 		 *
249 		 * Insert panthor_group::wait_node here when a group is waiting
250 		 * for synchronization objects to be signaled.
251 		 *
252 		 * This list is evaluated in the @sync_upd_work work.
253 		 */
254 		struct list_head waiting;
255 	} groups;
256 
257 	/**
258 	 * @csg_slots: FW command stream group slots.
259 	 */
260 	struct panthor_csg_slot csg_slots[MAX_CSGS];
261 
262 	/** @csg_slot_count: Number of command stream group slots exposed by the FW. */
263 	u32 csg_slot_count;
264 
265 	/** @cs_slot_count: Number of command stream slot per group slot exposed by the FW. */
266 	u32 cs_slot_count;
267 
268 	/** @as_slot_count: Number of address space slots supported by the MMU. */
269 	u32 as_slot_count;
270 
271 	/** @used_csg_slot_count: Number of command stream group slot currently used. */
272 	u32 used_csg_slot_count;
273 
274 	/** @sb_slot_count: Number of scoreboard slots. */
275 	u32 sb_slot_count;
276 
277 	/**
278 	 * @might_have_idle_groups: True if an active group might have become idle.
279 	 *
280 	 * This will force a tick, so other runnable groups can be scheduled if one
281 	 * or more active groups became idle.
282 	 */
283 	bool might_have_idle_groups;
284 
285 	/** @pm: Power management related fields. */
286 	struct {
287 		/** @pm.has_ref: True if the scheduler owns a runtime PM reference. */
288 		bool has_ref;
289 	} pm;
290 
291 	/** @reset: Reset related fields. */
292 	struct {
293 		/** @reset.lock: Lock protecting the other reset fields. */
294 		struct mutex lock;
295 
296 		/**
297 		 * @reset.in_progress: True if a reset is in progress.
298 		 *
299 		 * Set to true in panthor_sched_pre_reset() and back to false in
300 		 * panthor_sched_post_reset().
301 		 */
302 		atomic_t in_progress;
303 
304 		/**
305 		 * @reset.stopped_groups: List containing all groups that were stopped
306 		 * before a reset.
307 		 *
308 		 * Insert panthor_group::run_node in the pre_reset path.
309 		 */
310 		struct list_head stopped_groups;
311 	} reset;
312 };
313 
314 /**
315  * struct panthor_syncobj_32b - 32-bit FW synchronization object
316  */
317 struct panthor_syncobj_32b {
318 	/** @seqno: Sequence number. */
319 	u32 seqno;
320 
321 	/**
322 	 * @status: Status.
323 	 *
324 	 * Not zero on failure.
325 	 */
326 	u32 status;
327 };
328 
329 /**
330  * struct panthor_syncobj_64b - 64-bit FW synchronization object
331  */
332 struct panthor_syncobj_64b {
333 	/** @seqno: Sequence number. */
334 	u64 seqno;
335 
336 	/**
337 	 * @status: Status.
338 	 *
339 	 * Not zero on failure.
340 	 */
341 	u32 status;
342 
343 	/** @pad: MBZ. */
344 	u32 pad;
345 };
346 
347 /**
348  * struct panthor_queue - Execution queue
349  */
350 struct panthor_queue {
351 	/** @scheduler: DRM scheduler used for this queue. */
352 	struct drm_gpu_scheduler scheduler;
353 
354 	/** @entity: DRM scheduling entity used for this queue. */
355 	struct drm_sched_entity entity;
356 
357 	/** @name: DRM scheduler name for this queue. */
358 	char *name;
359 
360 	/** @timeout: Queue timeout related fields. */
361 	struct {
362 		/** @timeout.work: Work executed when a queue timeout occurs. */
363 		struct delayed_work work;
364 
365 		/**
366 		 * @timeout.remaining: Time remaining before a queue timeout.
367 		 *
368 		 * When the timer is running, this value is set to MAX_SCHEDULE_TIMEOUT.
369 		 * When the timer is suspended, it's set to the time remaining when the
370 		 * timer was suspended.
371 		 */
372 		unsigned long remaining;
373 	} timeout;
374 
375 	/**
376 	 * @doorbell_id: Doorbell assigned to this queue.
377 	 *
378 	 * Right now, all groups share the same doorbell, and the doorbell ID
379 	 * is assigned to group_slot + 1 when the group is assigned a slot. But
380 	 * we might decide to provide fine grained doorbell assignment at some
381 	 * point, so don't have to wake up all queues in a group every time one
382 	 * of them is updated.
383 	 */
384 	u8 doorbell_id;
385 
386 	/**
387 	 * @priority: Priority of the queue inside the group.
388 	 *
389 	 * Must be less than 16 (Only 4 bits available).
390 	 */
391 	u8 priority;
392 #define CSF_MAX_QUEUE_PRIO	GENMASK(3, 0)
393 
394 	/** @ringbuf: Command stream ring-buffer. */
395 	struct panthor_kernel_bo *ringbuf;
396 
397 	/** @iface: Firmware interface. */
398 	struct {
399 		/** @iface.mem: FW memory allocated for this interface. */
400 		struct panthor_kernel_bo *mem;
401 
402 		/** @iface.input: Input interface. */
403 		struct panthor_fw_ringbuf_input_iface *input;
404 
405 		/** @iface.output: Output interface. */
406 		const struct panthor_fw_ringbuf_output_iface *output;
407 
408 		/** @iface.input_fw_va: FW virtual address of the input interface buffer. */
409 		u32 input_fw_va;
410 
411 		/** @iface.output_fw_va: FW virtual address of the output interface buffer. */
412 		u32 output_fw_va;
413 	} iface;
414 
415 	/**
416 	 * @syncwait: Stores information about the synchronization object this
417 	 * queue is waiting on.
418 	 */
419 	struct {
420 		/** @syncwait.gpu_va: GPU address of the synchronization object. */
421 		u64 gpu_va;
422 
423 		/** @syncwait.ref: Reference value to compare against. */
424 		u64 ref;
425 
426 		/** @syncwait.gt: True if this is a greater-than test. */
427 		bool gt;
428 
429 		/** @syncwait.sync64: True if this is a 64-bit sync object. */
430 		bool sync64;
431 
432 		/** @syncwait.obj: Buffer object holding the synchronization object. */
433 		struct drm_gem_object *obj;
434 
435 		/** @syncwait.offset: Offset of the synchronization object inside @bo. */
436 		u64 offset;
437 
438 		/**
439 		 * @syncwait.kmap: Kernel mapping of the buffer object holding the
440 		 * synchronization object.
441 		 */
442 		void *kmap;
443 	} syncwait;
444 
445 	/** @fence_ctx: Fence context fields. */
446 	struct {
447 		/** @fence_ctx.lock: Used to protect access to all fences allocated by this context. */
448 		spinlock_t lock;
449 
450 		/**
451 		 * @fence_ctx.id: Fence context ID.
452 		 *
453 		 * Allocated with dma_fence_context_alloc().
454 		 */
455 		u64 id;
456 
457 		/** @fence_ctx.seqno: Sequence number of the last initialized fence. */
458 		atomic64_t seqno;
459 
460 		/**
461 		 * @fence_ctx.last_fence: Fence of the last submitted job.
462 		 *
463 		 * We return this fence when we get an empty command stream.
464 		 * This way, we are guaranteed that all earlier jobs have completed
465 		 * when drm_sched_job::s_fence::finished without having to feed
466 		 * the CS ring buffer with a dummy job that only signals the fence.
467 		 */
468 		struct dma_fence *last_fence;
469 
470 		/**
471 		 * @fence_ctx.in_flight_jobs: List containing all in-flight jobs.
472 		 *
473 		 * Used to keep track and signal panthor_job::done_fence when the
474 		 * synchronization object attached to the queue is signaled.
475 		 */
476 		struct list_head in_flight_jobs;
477 	} fence_ctx;
478 
479 	/** @profiling: Job profiling data slots and access information. */
480 	struct {
481 		/** @profiling.slots: Kernel BO holding the slots. */
482 		struct panthor_kernel_bo *slots;
483 
484 		/** @profiling.slot_count: Number of jobs ringbuffer can hold at once. */
485 		u32 slot_count;
486 
487 		/** @profiling.seqno: Index of the next available profiling information slot. */
488 		u32 seqno;
489 	} profiling;
490 };
491 
492 /**
493  * enum panthor_group_state - Scheduling group state.
494  */
495 enum panthor_group_state {
496 	/** @PANTHOR_CS_GROUP_CREATED: Group was created, but not scheduled yet. */
497 	PANTHOR_CS_GROUP_CREATED,
498 
499 	/** @PANTHOR_CS_GROUP_ACTIVE: Group is currently scheduled. */
500 	PANTHOR_CS_GROUP_ACTIVE,
501 
502 	/**
503 	 * @PANTHOR_CS_GROUP_SUSPENDED: Group was scheduled at least once, but is
504 	 * inactive/suspended right now.
505 	 */
506 	PANTHOR_CS_GROUP_SUSPENDED,
507 
508 	/**
509 	 * @PANTHOR_CS_GROUP_TERMINATED: Group was terminated.
510 	 *
511 	 * Can no longer be scheduled. The only allowed action is a destruction.
512 	 */
513 	PANTHOR_CS_GROUP_TERMINATED,
514 
515 	/**
516 	 * @PANTHOR_CS_GROUP_UNKNOWN_STATE: Group is an unknown state.
517 	 *
518 	 * The FW returned an inconsistent state. The group is flagged unusable
519 	 * and can no longer be scheduled. The only allowed action is a
520 	 * destruction.
521 	 *
522 	 * When that happens, we also schedule a FW reset, to start from a fresh
523 	 * state.
524 	 */
525 	PANTHOR_CS_GROUP_UNKNOWN_STATE,
526 };
527 
528 /**
529  * struct panthor_group - Scheduling group object
530  */
531 struct panthor_group {
532 	/** @refcount: Reference count */
533 	struct kref refcount;
534 
535 	/** @ptdev: Device. */
536 	struct panthor_device *ptdev;
537 
538 	/** @vm: VM bound to the group. */
539 	struct panthor_vm *vm;
540 
541 	/** @compute_core_mask: Mask of shader cores that can be used for compute jobs. */
542 	u64 compute_core_mask;
543 
544 	/** @fragment_core_mask: Mask of shader cores that can be used for fragment jobs. */
545 	u64 fragment_core_mask;
546 
547 	/** @tiler_core_mask: Mask of tiler cores that can be used for tiler jobs. */
548 	u64 tiler_core_mask;
549 
550 	/** @max_compute_cores: Maximum number of shader cores used for compute jobs. */
551 	u8 max_compute_cores;
552 
553 	/** @max_fragment_cores: Maximum number of shader cores used for fragment jobs. */
554 	u8 max_fragment_cores;
555 
556 	/** @max_tiler_cores: Maximum number of tiler cores used for tiler jobs. */
557 	u8 max_tiler_cores;
558 
559 	/** @priority: Group priority (check panthor_csg_priority). */
560 	u8 priority;
561 
562 	/** @blocked_queues: Bitmask reflecting the blocked queues. */
563 	u32 blocked_queues;
564 
565 	/** @idle_queues: Bitmask reflecting the idle queues. */
566 	u32 idle_queues;
567 
568 	/** @fatal_lock: Lock used to protect access to fatal fields. */
569 	spinlock_t fatal_lock;
570 
571 	/** @fatal_queues: Bitmask reflecting the queues that hit a fatal exception. */
572 	u32 fatal_queues;
573 
574 	/** @tiler_oom: Mask of queues that have a tiler OOM event to process. */
575 	atomic_t tiler_oom;
576 
577 	/** @queue_count: Number of queues in this group. */
578 	u32 queue_count;
579 
580 	/** @queues: Queues owned by this group. */
581 	struct panthor_queue *queues[MAX_CS_PER_CSG];
582 
583 	/**
584 	 * @csg_id: ID of the FW group slot.
585 	 *
586 	 * -1 when the group is not scheduled/active.
587 	 */
588 	int csg_id;
589 
590 	/**
591 	 * @destroyed: True when the group has been destroyed.
592 	 *
593 	 * If a group is destroyed it becomes useless: no further jobs can be submitted
594 	 * to its queues. We simply wait for all references to be dropped so we can
595 	 * release the group object.
596 	 */
597 	bool destroyed;
598 
599 	/**
600 	 * @timedout: True when a timeout occurred on any of the queues owned by
601 	 * this group.
602 	 *
603 	 * Timeouts can be reported by drm_sched or by the FW. If a reset is required,
604 	 * and the group can't be suspended, this also leads to a timeout. In any case,
605 	 * any timeout situation is unrecoverable, and the group becomes useless. We
606 	 * simply wait for all references to be dropped so we can release the group
607 	 * object.
608 	 */
609 	bool timedout;
610 
611 	/**
612 	 * @innocent: True when the group becomes unusable because the group suspension
613 	 * failed during a reset.
614 	 *
615 	 * Sometimes the FW was put in a bad state by other groups, causing the group
616 	 * suspension happening in the reset path to fail. In that case, we consider the
617 	 * group innocent.
618 	 */
619 	bool innocent;
620 
621 	/**
622 	 * @syncobjs: Pool of per-queue synchronization objects.
623 	 *
624 	 * One sync object per queue. The position of the sync object is
625 	 * determined by the queue index.
626 	 */
627 	struct panthor_kernel_bo *syncobjs;
628 
629 	/** @fdinfo: Per-file info exposed through /proc/<process>/fdinfo */
630 	struct {
631 		/** @fdinfo.data: Total sampled values for jobs in queues from this group. */
632 		struct panthor_gpu_usage data;
633 
634 		/**
635 		 * @fdinfo.lock: Spinlock to govern concurrent access from drm file's fdinfo
636 		 * callback and job post-completion processing function
637 		 */
638 		spinlock_t lock;
639 
640 		/** @fdinfo.kbo_sizes: Aggregate size of private kernel BO's held by the group. */
641 		size_t kbo_sizes;
642 	} fdinfo;
643 
644 	/** @task_info: Info of current->group_leader that created the group. */
645 	struct {
646 		/** @task_info.pid: pid of current->group_leader */
647 		pid_t pid;
648 
649 		/** @task_info.comm: comm of current->group_leader */
650 		char comm[TASK_COMM_LEN];
651 	} task_info;
652 
653 	/** @state: Group state. */
654 	enum panthor_group_state state;
655 
656 	/**
657 	 * @suspend_buf: Suspend buffer.
658 	 *
659 	 * Stores the state of the group and its queues when a group is suspended.
660 	 * Used at resume time to restore the group in its previous state.
661 	 *
662 	 * The size of the suspend buffer is exposed through the FW interface.
663 	 */
664 	struct panthor_kernel_bo *suspend_buf;
665 
666 	/**
667 	 * @protm_suspend_buf: Protection mode suspend buffer.
668 	 *
669 	 * Stores the state of the group and its queues when a group that's in
670 	 * protection mode is suspended.
671 	 *
672 	 * Used at resume time to restore the group in its previous state.
673 	 *
674 	 * The size of the protection mode suspend buffer is exposed through the
675 	 * FW interface.
676 	 */
677 	struct panthor_kernel_bo *protm_suspend_buf;
678 
679 	/** @sync_upd_work: Work used to check/signal job fences. */
680 	struct work_struct sync_upd_work;
681 
682 	/** @tiler_oom_work: Work used to process tiler OOM events happening on this group. */
683 	struct work_struct tiler_oom_work;
684 
685 	/** @term_work: Work used to finish the group termination procedure. */
686 	struct work_struct term_work;
687 
688 	/**
689 	 * @release_work: Work used to release group resources.
690 	 *
691 	 * We need to postpone the group release to avoid a deadlock when
692 	 * the last ref is released in the tick work.
693 	 */
694 	struct work_struct release_work;
695 
696 	/**
697 	 * @run_node: Node used to insert the group in the
698 	 * panthor_group::groups::{runnable,idle} and
699 	 * panthor_group::reset.stopped_groups lists.
700 	 */
701 	struct list_head run_node;
702 
703 	/**
704 	 * @wait_node: Node used to insert the group in the
705 	 * panthor_group::groups::waiting list.
706 	 */
707 	struct list_head wait_node;
708 };
709 
710 struct panthor_job_profiling_data {
711 	struct {
712 		u64 before;
713 		u64 after;
714 	} cycles;
715 
716 	struct {
717 		u64 before;
718 		u64 after;
719 	} time;
720 };
721 
722 /**
723  * group_queue_work() - Queue a group work
724  * @group: Group to queue the work for.
725  * @wname: Work name.
726  *
727  * Grabs a ref and queue a work item to the scheduler workqueue. If
728  * the work was already queued, we release the reference we grabbed.
729  *
730  * Work callbacks must release the reference we grabbed here.
731  */
732 #define group_queue_work(group, wname) \
733 	do { \
734 		group_get(group); \
735 		if (!queue_work((group)->ptdev->scheduler->wq, &(group)->wname ## _work)) \
736 			group_put(group); \
737 	} while (0)
738 
739 /**
740  * sched_queue_work() - Queue a scheduler work.
741  * @sched: Scheduler object.
742  * @wname: Work name.
743  *
744  * Conditionally queues a scheduler work if no reset is pending/in-progress.
745  */
746 #define sched_queue_work(sched, wname) \
747 	do { \
748 		if (!atomic_read(&(sched)->reset.in_progress) && \
749 		    !panthor_device_reset_is_pending((sched)->ptdev)) \
750 			queue_work((sched)->wq, &(sched)->wname ## _work); \
751 	} while (0)
752 
753 /**
754  * sched_queue_delayed_work() - Queue a scheduler delayed work.
755  * @sched: Scheduler object.
756  * @wname: Work name.
757  * @delay: Work delay in jiffies.
758  *
759  * Conditionally queues a scheduler delayed work if no reset is
760  * pending/in-progress.
761  */
762 #define sched_queue_delayed_work(sched, wname, delay) \
763 	do { \
764 		if (!atomic_read(&sched->reset.in_progress) && \
765 		    !panthor_device_reset_is_pending((sched)->ptdev)) \
766 			mod_delayed_work((sched)->wq, &(sched)->wname ## _work, delay); \
767 	} while (0)
768 
769 /*
770  * We currently set the maximum of groups per file to an arbitrary low value.
771  * But this can be updated if we need more.
772  */
773 #define MAX_GROUPS_PER_POOL 128
774 
775 /*
776  * Mark added on an entry of group pool Xarray to identify if the group has
777  * been fully initialized and can be accessed elsewhere in the driver code.
778  */
779 #define GROUP_REGISTERED XA_MARK_1
780 
781 /**
782  * struct panthor_group_pool - Group pool
783  *
784  * Each file get assigned a group pool.
785  */
786 struct panthor_group_pool {
787 	/** @xa: Xarray used to manage group handles. */
788 	struct xarray xa;
789 };
790 
791 /**
792  * struct panthor_job - Used to manage GPU job
793  */
794 struct panthor_job {
795 	/** @base: Inherit from drm_sched_job. */
796 	struct drm_sched_job base;
797 
798 	/** @refcount: Reference count. */
799 	struct kref refcount;
800 
801 	/** @group: Group of the queue this job will be pushed to. */
802 	struct panthor_group *group;
803 
804 	/** @queue_idx: Index of the queue inside @group. */
805 	u32 queue_idx;
806 
807 	/** @call_info: Information about the userspace command stream call. */
808 	struct {
809 		/** @call_info.start: GPU address of the userspace command stream. */
810 		u64 start;
811 
812 		/** @call_info.size: Size of the userspace command stream. */
813 		u32 size;
814 
815 		/**
816 		 * @call_info.latest_flush: Flush ID at the time the userspace
817 		 * command stream was built.
818 		 *
819 		 * Needed for the flush reduction mechanism.
820 		 */
821 		u32 latest_flush;
822 	} call_info;
823 
824 	/** @ringbuf: Position of this job is in the ring buffer. */
825 	struct {
826 		/** @ringbuf.start: Start offset. */
827 		u64 start;
828 
829 		/** @ringbuf.end: End offset. */
830 		u64 end;
831 	} ringbuf;
832 
833 	/**
834 	 * @node: Used to insert the job in the panthor_queue::fence_ctx::in_flight_jobs
835 	 * list.
836 	 */
837 	struct list_head node;
838 
839 	/** @done_fence: Fence signaled when the job is finished or cancelled. */
840 	struct dma_fence *done_fence;
841 
842 	/** @profiling: Job profiling information. */
843 	struct {
844 		/** @profiling.mask: Current device job profiling enablement bitmask. */
845 		u32 mask;
846 
847 		/** @profiling.slot: Job index in the profiling slots BO. */
848 		u32 slot;
849 	} profiling;
850 };
851 
852 static void
panthor_queue_put_syncwait_obj(struct panthor_queue * queue)853 panthor_queue_put_syncwait_obj(struct panthor_queue *queue)
854 {
855 	if (queue->syncwait.kmap) {
856 		struct iosys_map map = IOSYS_MAP_INIT_VADDR(queue->syncwait.kmap);
857 
858 		drm_gem_vunmap(queue->syncwait.obj, &map);
859 		queue->syncwait.kmap = NULL;
860 	}
861 
862 	drm_gem_object_put(queue->syncwait.obj);
863 	queue->syncwait.obj = NULL;
864 }
865 
866 static void *
panthor_queue_get_syncwait_obj(struct panthor_group * group,struct panthor_queue * queue)867 panthor_queue_get_syncwait_obj(struct panthor_group *group, struct panthor_queue *queue)
868 {
869 	struct panthor_device *ptdev = group->ptdev;
870 	struct panthor_gem_object *bo;
871 	struct iosys_map map;
872 	int ret;
873 
874 	if (queue->syncwait.kmap) {
875 		bo = to_panthor_bo(queue->syncwait.obj);
876 		goto out_sync;
877 	}
878 
879 	bo = panthor_vm_get_bo_for_va(group->vm,
880 				      queue->syncwait.gpu_va,
881 				      &queue->syncwait.offset);
882 	if (drm_WARN_ON(&ptdev->base, IS_ERR_OR_NULL(bo)))
883 		goto err_put_syncwait_obj;
884 
885 	queue->syncwait.obj = &bo->base;
886 	ret = drm_gem_vmap(queue->syncwait.obj, &map);
887 	if (drm_WARN_ON(&ptdev->base, ret))
888 		goto err_put_syncwait_obj;
889 
890 	queue->syncwait.kmap = map.vaddr;
891 	if (drm_WARN_ON(&ptdev->base, !queue->syncwait.kmap))
892 		goto err_put_syncwait_obj;
893 
894 out_sync:
895 	/* Make sure the CPU caches are invalidated before the seqno is read.
896 	 * panthor_gem_sync() is a NOP if map_wc=true, so no need to check
897 	 * it here.
898 	 */
899 	panthor_gem_sync(&bo->base,
900 			 DRM_PANTHOR_BO_SYNC_CPU_CACHE_FLUSH_AND_INVALIDATE,
901 			 queue->syncwait.offset,
902 			 queue->syncwait.sync64 ?
903 			 sizeof(struct panthor_syncobj_64b) :
904 			 sizeof(struct panthor_syncobj_32b));
905 
906 	return queue->syncwait.kmap + queue->syncwait.offset;
907 
908 err_put_syncwait_obj:
909 	panthor_queue_put_syncwait_obj(queue);
910 	return NULL;
911 }
912 
group_free_queue(struct panthor_group * group,struct panthor_queue * queue)913 static void group_free_queue(struct panthor_group *group, struct panthor_queue *queue)
914 {
915 	if (IS_ERR_OR_NULL(queue))
916 		return;
917 
918 	/* Disable the timeout before tearing down drm_sched components. */
919 	disable_delayed_work_sync(&queue->timeout.work);
920 
921 	if (queue->entity.fence_context)
922 		drm_sched_entity_destroy(&queue->entity);
923 
924 	if (queue->scheduler.ops)
925 		drm_sched_fini(&queue->scheduler);
926 
927 	kfree(queue->name);
928 
929 	panthor_queue_put_syncwait_obj(queue);
930 
931 	panthor_kernel_bo_destroy(queue->ringbuf);
932 	panthor_kernel_bo_destroy(queue->iface.mem);
933 	panthor_kernel_bo_destroy(queue->profiling.slots);
934 
935 	/* Release the last_fence we were holding, if any. */
936 	dma_fence_put(queue->fence_ctx.last_fence);
937 
938 	kfree(queue);
939 }
940 
group_release_work(struct work_struct * work)941 static void group_release_work(struct work_struct *work)
942 {
943 	struct panthor_group *group = container_of(work,
944 						   struct panthor_group,
945 						   release_work);
946 	u32 i;
947 
948 	/* dma-fences may still be accessing group->queues under rcu lock. */
949 	synchronize_rcu();
950 
951 	for (i = 0; i < group->queue_count; i++)
952 		group_free_queue(group, group->queues[i]);
953 
954 	panthor_kernel_bo_destroy(group->suspend_buf);
955 	panthor_kernel_bo_destroy(group->protm_suspend_buf);
956 	panthor_kernel_bo_destroy(group->syncobjs);
957 
958 	panthor_vm_put(group->vm);
959 	kfree(group);
960 }
961 
group_release(struct kref * kref)962 static void group_release(struct kref *kref)
963 {
964 	struct panthor_group *group = container_of(kref,
965 						   struct panthor_group,
966 						   refcount);
967 	struct panthor_device *ptdev = group->ptdev;
968 
969 	drm_WARN_ON(&ptdev->base, group->csg_id >= 0);
970 	drm_WARN_ON(&ptdev->base, !list_empty(&group->run_node));
971 	drm_WARN_ON(&ptdev->base, !list_empty(&group->wait_node));
972 
973 	queue_work(panthor_cleanup_wq, &group->release_work);
974 }
975 
group_put(struct panthor_group * group)976 static void group_put(struct panthor_group *group)
977 {
978 	if (group)
979 		kref_put(&group->refcount, group_release);
980 }
981 
982 static struct panthor_group *
group_get(struct panthor_group * group)983 group_get(struct panthor_group *group)
984 {
985 	if (group)
986 		kref_get(&group->refcount);
987 
988 	return group;
989 }
990 
991 /**
992  * group_bind_locked() - Bind a group to a group slot
993  * @group: Group.
994  * @csg_id: Slot.
995  *
996  * Return: 0 on success, a negative error code otherwise.
997  */
998 static int
group_bind_locked(struct panthor_group * group,u32 csg_id)999 group_bind_locked(struct panthor_group *group, u32 csg_id)
1000 {
1001 	struct panthor_device *ptdev = group->ptdev;
1002 	struct panthor_csg_slot *csg_slot;
1003 	int ret;
1004 
1005 	lockdep_assert_held(&ptdev->scheduler->lock);
1006 
1007 	if (drm_WARN_ON(&ptdev->base, group->csg_id != -1 || csg_id >= MAX_CSGS ||
1008 			ptdev->scheduler->csg_slots[csg_id].group))
1009 		return -EINVAL;
1010 
1011 	ret = panthor_vm_active(group->vm);
1012 	if (ret)
1013 		return ret;
1014 
1015 	csg_slot = &ptdev->scheduler->csg_slots[csg_id];
1016 	group_get(group);
1017 	group->csg_id = csg_id;
1018 
1019 	/* Dummy doorbell allocation: doorbell is assigned to the group and
1020 	 * all queues use the same doorbell.
1021 	 *
1022 	 * TODO: Implement LRU-based doorbell assignment, so the most often
1023 	 * updated queues get their own doorbell, thus avoiding useless checks
1024 	 * on queues belonging to the same group that are rarely updated.
1025 	 */
1026 	for (u32 i = 0; i < group->queue_count; i++)
1027 		group->queues[i]->doorbell_id = csg_id + 1;
1028 
1029 	csg_slot->group = group;
1030 
1031 	return 0;
1032 }
1033 
1034 /**
1035  * group_unbind_locked() - Unbind a group from a slot.
1036  * @group: Group to unbind.
1037  *
1038  * Return: 0 on success, a negative error code otherwise.
1039  */
1040 static int
group_unbind_locked(struct panthor_group * group)1041 group_unbind_locked(struct panthor_group *group)
1042 {
1043 	struct panthor_device *ptdev = group->ptdev;
1044 	struct panthor_csg_slot *slot;
1045 
1046 	lockdep_assert_held(&ptdev->scheduler->lock);
1047 
1048 	if (drm_WARN_ON(&ptdev->base, group->csg_id < 0 || group->csg_id >= MAX_CSGS))
1049 		return -EINVAL;
1050 
1051 	if (drm_WARN_ON(&ptdev->base, group->state == PANTHOR_CS_GROUP_ACTIVE))
1052 		return -EINVAL;
1053 
1054 	slot = &ptdev->scheduler->csg_slots[group->csg_id];
1055 	panthor_vm_idle(group->vm);
1056 	group->csg_id = -1;
1057 
1058 	/* Tiler OOM events will be re-issued next time the group is scheduled. */
1059 	atomic_set(&group->tiler_oom, 0);
1060 	if (cancel_work(&group->tiler_oom_work))
1061 		group_put(group);
1062 
1063 	for (u32 i = 0; i < group->queue_count; i++)
1064 		group->queues[i]->doorbell_id = -1;
1065 
1066 	slot->group = NULL;
1067 
1068 	group_put(group);
1069 	return 0;
1070 }
1071 
1072 static bool
group_is_idle(struct panthor_group * group)1073 group_is_idle(struct panthor_group *group)
1074 {
1075 	u32 inactive_queues = group->idle_queues | group->blocked_queues;
1076 
1077 	return hweight32(inactive_queues) == group->queue_count;
1078 }
1079 
1080 static bool
group_can_run(struct panthor_group * group)1081 group_can_run(struct panthor_group *group)
1082 {
1083 	return group->state != PANTHOR_CS_GROUP_TERMINATED &&
1084 	       group->state != PANTHOR_CS_GROUP_UNKNOWN_STATE &&
1085 	       !group->destroyed && group->fatal_queues == 0 &&
1086 	       !group->timedout;
1087 }
1088 
1089 static bool
queue_timeout_is_suspended(struct panthor_queue * queue)1090 queue_timeout_is_suspended(struct panthor_queue *queue)
1091 {
1092 	/* When running, the remaining time is set to MAX_SCHEDULE_TIMEOUT. */
1093 	return queue->timeout.remaining != MAX_SCHEDULE_TIMEOUT;
1094 }
1095 
1096 static void
queue_reset_timeout_locked(struct panthor_queue * queue)1097 queue_reset_timeout_locked(struct panthor_queue *queue)
1098 {
1099 	lockdep_assert_held(&queue->fence_ctx.lock);
1100 
1101 	if (!queue_timeout_is_suspended(queue)) {
1102 		mod_delayed_work(queue->scheduler.timeout_wq,
1103 				 &queue->timeout.work,
1104 				 msecs_to_jiffies(JOB_TIMEOUT_MS));
1105 	}
1106 }
1107 
1108 static void
queue_suspend_timeout_locked(struct panthor_queue * queue)1109 queue_suspend_timeout_locked(struct panthor_queue *queue)
1110 {
1111 	unsigned long qtimeout, now;
1112 	struct panthor_group *group;
1113 	struct panthor_job *job;
1114 	bool timer_was_active;
1115 
1116 	lockdep_assert_held(&queue->fence_ctx.lock);
1117 
1118 	/* Already suspended, nothing to do. */
1119 	if (queue_timeout_is_suspended(queue))
1120 		return;
1121 
1122 	job = list_first_entry_or_null(&queue->fence_ctx.in_flight_jobs,
1123 				       struct panthor_job, node);
1124 	group = job ? job->group : NULL;
1125 
1126 	/* If the queue is blocked and the group is idle, we want the timer to
1127 	 * keep running because the group can't be unblocked by other queues,
1128 	 * so it has to come from an external source, and we want to timebox
1129 	 * this external signalling.
1130 	 */
1131 	if (group && group_can_run(group) &&
1132 	    (group->blocked_queues & BIT(job->queue_idx)) &&
1133 	    group_is_idle(group))
1134 		return;
1135 
1136 	now = jiffies;
1137 	qtimeout = queue->timeout.work.timer.expires;
1138 
1139 	/* Cancel the timer. */
1140 	timer_was_active = cancel_delayed_work(&queue->timeout.work);
1141 	if (!timer_was_active || !job)
1142 		queue->timeout.remaining = msecs_to_jiffies(JOB_TIMEOUT_MS);
1143 	else if (time_after(qtimeout, now))
1144 		queue->timeout.remaining = qtimeout - now;
1145 	else
1146 		queue->timeout.remaining = 0;
1147 
1148 	if (WARN_ON_ONCE(queue->timeout.remaining > msecs_to_jiffies(JOB_TIMEOUT_MS)))
1149 		queue->timeout.remaining = msecs_to_jiffies(JOB_TIMEOUT_MS);
1150 }
1151 
1152 static void
queue_suspend_timeout(struct panthor_queue * queue)1153 queue_suspend_timeout(struct panthor_queue *queue)
1154 {
1155 	guard(spinlock_irqsave)(&queue->fence_ctx.lock);
1156 	queue_suspend_timeout_locked(queue);
1157 }
1158 
1159 static void
queue_resume_timeout(struct panthor_queue * queue)1160 queue_resume_timeout(struct panthor_queue *queue)
1161 {
1162 	guard(spinlock_irqsave)(&queue->fence_ctx.lock);
1163 
1164 	if (queue_timeout_is_suspended(queue)) {
1165 		mod_delayed_work(queue->scheduler.timeout_wq,
1166 				 &queue->timeout.work,
1167 				 queue->timeout.remaining);
1168 
1169 		queue->timeout.remaining = MAX_SCHEDULE_TIMEOUT;
1170 	}
1171 }
1172 
1173 /**
1174  * cs_slot_prog_locked() - Program a queue slot
1175  * @ptdev: Device.
1176  * @csg_id: Group slot ID.
1177  * @cs_id: Queue slot ID.
1178  *
1179  * Program a queue slot with the queue information so things can start being
1180  * executed on this queue.
1181  *
1182  * The group slot must have a group bound to it already (group_bind_locked()).
1183  */
1184 static void
cs_slot_prog_locked(struct panthor_device * ptdev,u32 csg_id,u32 cs_id)1185 cs_slot_prog_locked(struct panthor_device *ptdev, u32 csg_id, u32 cs_id)
1186 {
1187 	struct panthor_queue *queue = ptdev->scheduler->csg_slots[csg_id].group->queues[cs_id];
1188 	struct panthor_fw_cs_iface *cs_iface = panthor_fw_get_cs_iface(ptdev, csg_id, cs_id);
1189 
1190 	lockdep_assert_held(&ptdev->scheduler->lock);
1191 
1192 	queue->iface.input->extract = queue->iface.output->extract;
1193 	drm_WARN_ON(&ptdev->base, queue->iface.input->insert < queue->iface.input->extract);
1194 
1195 	cs_iface->input->ringbuf_base = panthor_kernel_bo_gpuva(queue->ringbuf);
1196 	cs_iface->input->ringbuf_size = panthor_kernel_bo_size(queue->ringbuf);
1197 	cs_iface->input->ringbuf_input = queue->iface.input_fw_va;
1198 	cs_iface->input->ringbuf_output = queue->iface.output_fw_va;
1199 	cs_iface->input->config = CS_CONFIG_PRIORITY(queue->priority) |
1200 				  CS_CONFIG_DOORBELL(queue->doorbell_id);
1201 	cs_iface->input->ack_irq_mask = ~0;
1202 	panthor_fw_update_reqs(cs_iface, req,
1203 			       CS_IDLE_SYNC_WAIT |
1204 			       CS_IDLE_EMPTY |
1205 			       CS_STATE_START,
1206 			       CS_IDLE_SYNC_WAIT |
1207 			       CS_IDLE_EMPTY |
1208 			       CS_STATE_MASK);
1209 	if (queue->iface.input->insert != queue->iface.input->extract)
1210 		queue_resume_timeout(queue);
1211 }
1212 
1213 /**
1214  * cs_slot_reset_locked() - Reset a queue slot
1215  * @ptdev: Device.
1216  * @csg_id: Group slot.
1217  * @cs_id: Queue slot.
1218  *
1219  * Change the queue slot state to STOP and suspend the queue timeout if
1220  * the queue is not blocked.
1221  *
1222  * The group slot must have a group bound to it (group_bind_locked()).
1223  */
1224 static int
cs_slot_reset_locked(struct panthor_device * ptdev,u32 csg_id,u32 cs_id)1225 cs_slot_reset_locked(struct panthor_device *ptdev, u32 csg_id, u32 cs_id)
1226 {
1227 	struct panthor_fw_cs_iface *cs_iface = panthor_fw_get_cs_iface(ptdev, csg_id, cs_id);
1228 	struct panthor_group *group = ptdev->scheduler->csg_slots[csg_id].group;
1229 	struct panthor_queue *queue = group->queues[cs_id];
1230 
1231 	lockdep_assert_held(&ptdev->scheduler->lock);
1232 
1233 	panthor_fw_update_reqs(cs_iface, req,
1234 			       CS_STATE_STOP,
1235 			       CS_STATE_MASK);
1236 
1237 	queue_suspend_timeout(queue);
1238 
1239 	return 0;
1240 }
1241 
1242 /**
1243  * csg_slot_sync_priority_locked() - Synchronize the group slot priority
1244  * @ptdev: Device.
1245  * @csg_id: Group slot ID.
1246  *
1247  * Group slot priority update happens asynchronously. When we receive a
1248  * %CSG_ENDPOINT_CONFIG, we know the update is effective, and can
1249  * reflect it to our panthor_csg_slot object.
1250  */
1251 static void
csg_slot_sync_priority_locked(struct panthor_device * ptdev,u32 csg_id)1252 csg_slot_sync_priority_locked(struct panthor_device *ptdev, u32 csg_id)
1253 {
1254 	struct panthor_csg_slot *csg_slot = &ptdev->scheduler->csg_slots[csg_id];
1255 	struct panthor_fw_csg_iface *csg_iface;
1256 	u64 endpoint_req;
1257 
1258 	lockdep_assert_held(&ptdev->scheduler->lock);
1259 
1260 	csg_iface = panthor_fw_get_csg_iface(ptdev, csg_id);
1261 	endpoint_req = panthor_fw_csg_endpoint_req_get(ptdev, csg_iface);
1262 	csg_slot->priority = CSG_EP_REQ_PRIORITY_GET(endpoint_req);
1263 }
1264 
1265 /**
1266  * cs_slot_sync_queue_state_locked() - Synchronize the queue slot priority
1267  * @ptdev: Device.
1268  * @csg_id: Group slot.
1269  * @cs_id: Queue slot.
1270  *
1271  * Queue state is updated on group suspend or STATUS_UPDATE event.
1272  */
1273 static void
cs_slot_sync_queue_state_locked(struct panthor_device * ptdev,u32 csg_id,u32 cs_id)1274 cs_slot_sync_queue_state_locked(struct panthor_device *ptdev, u32 csg_id, u32 cs_id)
1275 {
1276 	struct panthor_group *group = ptdev->scheduler->csg_slots[csg_id].group;
1277 	struct panthor_queue *queue = group->queues[cs_id];
1278 	struct panthor_fw_cs_iface *cs_iface =
1279 		panthor_fw_get_cs_iface(group->ptdev, csg_id, cs_id);
1280 
1281 	u32 status_wait_cond;
1282 
1283 	switch (cs_iface->output->status_blocked_reason) {
1284 	case CS_STATUS_BLOCKED_REASON_UNBLOCKED:
1285 		if (queue->iface.input->insert == queue->iface.output->extract &&
1286 		    cs_iface->output->status_scoreboards == 0)
1287 			group->idle_queues |= BIT(cs_id);
1288 		break;
1289 
1290 	case CS_STATUS_BLOCKED_REASON_SYNC_WAIT:
1291 		if (list_empty(&group->wait_node)) {
1292 			list_move_tail(&group->wait_node,
1293 				       &group->ptdev->scheduler->groups.waiting);
1294 		}
1295 
1296 		/* The queue is only blocked if there's no deferred operation
1297 		 * pending, which can be checked through the scoreboard status.
1298 		 */
1299 		if (!cs_iface->output->status_scoreboards)
1300 			group->blocked_queues |= BIT(cs_id);
1301 
1302 		queue->syncwait.gpu_va = cs_iface->output->status_wait_sync_ptr;
1303 		queue->syncwait.ref = cs_iface->output->status_wait_sync_value;
1304 		status_wait_cond = cs_iface->output->status_wait & CS_STATUS_WAIT_SYNC_COND_MASK;
1305 		queue->syncwait.gt = status_wait_cond == CS_STATUS_WAIT_SYNC_COND_GT;
1306 		if (cs_iface->output->status_wait & CS_STATUS_WAIT_SYNC_64B) {
1307 			u64 sync_val_hi = cs_iface->output->status_wait_sync_value_hi;
1308 
1309 			queue->syncwait.sync64 = true;
1310 			queue->syncwait.ref |= sync_val_hi << 32;
1311 		} else {
1312 			queue->syncwait.sync64 = false;
1313 		}
1314 		break;
1315 
1316 	default:
1317 		/* Other reasons are not blocking. Consider the queue as runnable
1318 		 * in those cases.
1319 		 */
1320 		break;
1321 	}
1322 }
1323 
1324 static void
csg_slot_sync_queues_state_locked(struct panthor_device * ptdev,u32 csg_id)1325 csg_slot_sync_queues_state_locked(struct panthor_device *ptdev, u32 csg_id)
1326 {
1327 	struct panthor_csg_slot *csg_slot = &ptdev->scheduler->csg_slots[csg_id];
1328 	struct panthor_group *group = csg_slot->group;
1329 	u32 i;
1330 
1331 	lockdep_assert_held(&ptdev->scheduler->lock);
1332 
1333 	group->idle_queues = 0;
1334 	group->blocked_queues = 0;
1335 
1336 	for (i = 0; i < group->queue_count; i++) {
1337 		if (group->queues[i])
1338 			cs_slot_sync_queue_state_locked(ptdev, csg_id, i);
1339 	}
1340 }
1341 
1342 static void
csg_slot_sync_state_locked(struct panthor_device * ptdev,u32 csg_id)1343 csg_slot_sync_state_locked(struct panthor_device *ptdev, u32 csg_id)
1344 {
1345 	struct panthor_csg_slot *csg_slot = &ptdev->scheduler->csg_slots[csg_id];
1346 	struct panthor_fw_csg_iface *csg_iface;
1347 	struct panthor_group *group;
1348 	enum panthor_group_state new_state, old_state;
1349 	u32 csg_state;
1350 
1351 	lockdep_assert_held(&ptdev->scheduler->lock);
1352 
1353 	csg_iface = panthor_fw_get_csg_iface(ptdev, csg_id);
1354 	group = csg_slot->group;
1355 
1356 	if (!group)
1357 		return;
1358 
1359 	old_state = group->state;
1360 	csg_state = csg_iface->output->ack & CSG_STATE_MASK;
1361 	switch (csg_state) {
1362 	case CSG_STATE_START:
1363 	case CSG_STATE_RESUME:
1364 		new_state = PANTHOR_CS_GROUP_ACTIVE;
1365 		break;
1366 	case CSG_STATE_TERMINATE:
1367 		new_state = PANTHOR_CS_GROUP_TERMINATED;
1368 		break;
1369 	case CSG_STATE_SUSPEND:
1370 		new_state = PANTHOR_CS_GROUP_SUSPENDED;
1371 		break;
1372 	default:
1373 		/* The unknown state might be caused by a FW state corruption,
1374 		 * which means the group metadata can't be trusted anymore, and
1375 		 * the SUSPEND operation might propagate the corruption to the
1376 		 * suspend buffers. Flag the group state as unknown to make
1377 		 * sure it's unusable after that point.
1378 		 */
1379 		drm_err(&ptdev->base, "Invalid state on CSG %d (state=%d)",
1380 			csg_id, csg_state);
1381 		new_state = PANTHOR_CS_GROUP_UNKNOWN_STATE;
1382 		break;
1383 	}
1384 
1385 	if (old_state == new_state)
1386 		return;
1387 
1388 	/* The unknown state might be caused by a FW issue, reset the FW to
1389 	 * take a fresh start.
1390 	 */
1391 	if (new_state == PANTHOR_CS_GROUP_UNKNOWN_STATE)
1392 		panthor_device_schedule_reset(ptdev);
1393 
1394 	if (new_state == PANTHOR_CS_GROUP_SUSPENDED)
1395 		csg_slot_sync_queues_state_locked(ptdev, csg_id);
1396 
1397 	if (old_state == PANTHOR_CS_GROUP_ACTIVE) {
1398 		u32 i;
1399 
1400 		/* Reset the queue slots so we start from a clean
1401 		 * state when starting/resuming a new group on this
1402 		 * CSG slot. No wait needed here, and no ringbell
1403 		 * either, since the CS slot will only be re-used
1404 		 * on the next CSG start operation.
1405 		 */
1406 		for (i = 0; i < group->queue_count; i++) {
1407 			if (group->queues[i])
1408 				cs_slot_reset_locked(ptdev, csg_id, i);
1409 		}
1410 	}
1411 
1412 	group->state = new_state;
1413 }
1414 
1415 static int
csg_slot_prog_locked(struct panthor_device * ptdev,u32 csg_id,u32 priority)1416 csg_slot_prog_locked(struct panthor_device *ptdev, u32 csg_id, u32 priority)
1417 {
1418 	struct panthor_fw_csg_iface *csg_iface;
1419 	struct panthor_csg_slot *csg_slot;
1420 	struct panthor_group *group;
1421 	u32 queue_mask = 0, i;
1422 	u64 endpoint_req;
1423 
1424 	lockdep_assert_held(&ptdev->scheduler->lock);
1425 
1426 	if (priority > MAX_CSG_PRIO)
1427 		return -EINVAL;
1428 
1429 	if (drm_WARN_ON(&ptdev->base, csg_id >= MAX_CSGS))
1430 		return -EINVAL;
1431 
1432 	csg_slot = &ptdev->scheduler->csg_slots[csg_id];
1433 	group = csg_slot->group;
1434 	if (!group || group->state == PANTHOR_CS_GROUP_ACTIVE)
1435 		return 0;
1436 
1437 	csg_iface = panthor_fw_get_csg_iface(group->ptdev, csg_id);
1438 
1439 	for (i = 0; i < group->queue_count; i++) {
1440 		if (group->queues[i]) {
1441 			cs_slot_prog_locked(ptdev, csg_id, i);
1442 			queue_mask |= BIT(i);
1443 		}
1444 	}
1445 
1446 	csg_iface->input->allow_compute = group->compute_core_mask;
1447 	csg_iface->input->allow_fragment = group->fragment_core_mask;
1448 	csg_iface->input->allow_other = group->tiler_core_mask;
1449 	endpoint_req = CSG_EP_REQ_COMPUTE(group->max_compute_cores) |
1450 		       CSG_EP_REQ_FRAGMENT(group->max_fragment_cores) |
1451 		       CSG_EP_REQ_TILER(group->max_tiler_cores) |
1452 		       CSG_EP_REQ_PRIORITY(priority);
1453 	panthor_fw_csg_endpoint_req_set(ptdev, csg_iface, endpoint_req);
1454 
1455 	csg_iface->input->config = panthor_vm_as(group->vm);
1456 
1457 	if (group->suspend_buf)
1458 		csg_iface->input->suspend_buf = panthor_kernel_bo_gpuva(group->suspend_buf);
1459 	else
1460 		csg_iface->input->suspend_buf = 0;
1461 
1462 	if (group->protm_suspend_buf) {
1463 		csg_iface->input->protm_suspend_buf =
1464 			panthor_kernel_bo_gpuva(group->protm_suspend_buf);
1465 	} else {
1466 		csg_iface->input->protm_suspend_buf = 0;
1467 	}
1468 
1469 	csg_iface->input->ack_irq_mask = ~0;
1470 	panthor_fw_toggle_reqs(csg_iface, doorbell_req, doorbell_ack, queue_mask);
1471 	return 0;
1472 }
1473 
1474 static void
cs_slot_process_fatal_event_locked(struct panthor_device * ptdev,u32 csg_id,u32 cs_id)1475 cs_slot_process_fatal_event_locked(struct panthor_device *ptdev,
1476 				   u32 csg_id, u32 cs_id)
1477 {
1478 	struct panthor_scheduler *sched = ptdev->scheduler;
1479 	struct panthor_csg_slot *csg_slot = &sched->csg_slots[csg_id];
1480 	struct panthor_group *group = csg_slot->group;
1481 	struct panthor_fw_cs_iface *cs_iface;
1482 	u32 fatal;
1483 	u64 info;
1484 
1485 	lockdep_assert_held(&sched->lock);
1486 
1487 	cs_iface = panthor_fw_get_cs_iface(ptdev, csg_id, cs_id);
1488 	fatal = cs_iface->output->fatal;
1489 	info = cs_iface->output->fatal_info;
1490 
1491 	if (group) {
1492 		drm_warn(&ptdev->base, "CS_FATAL: pid=%d, comm=%s\n",
1493 			 group->task_info.pid, group->task_info.comm);
1494 
1495 		group->fatal_queues |= BIT(cs_id);
1496 	}
1497 
1498 	if (CS_EXCEPTION_TYPE(fatal) == DRM_PANTHOR_EXCEPTION_CS_UNRECOVERABLE) {
1499 		/* If this exception is unrecoverable, queue a reset, and make
1500 		 * sure we stop scheduling groups until the reset has happened.
1501 		 */
1502 		panthor_device_schedule_reset(ptdev);
1503 		cancel_delayed_work(&sched->tick_work);
1504 	} else {
1505 		sched_queue_delayed_work(sched, tick, 0);
1506 	}
1507 
1508 	drm_warn(&ptdev->base,
1509 		 "CSG slot %d CS slot: %d\n"
1510 		 "CS_FATAL.EXCEPTION_TYPE: 0x%x (%s)\n"
1511 		 "CS_FATAL.EXCEPTION_DATA: 0x%x\n"
1512 		 "CS_FATAL_INFO.EXCEPTION_DATA: 0x%llx\n",
1513 		 csg_id, cs_id,
1514 		 (unsigned int)CS_EXCEPTION_TYPE(fatal),
1515 		 panthor_exception_name(ptdev, CS_EXCEPTION_TYPE(fatal)),
1516 		 (unsigned int)CS_EXCEPTION_DATA(fatal),
1517 		 info);
1518 }
1519 
1520 static void
cs_slot_process_fault_event_locked(struct panthor_device * ptdev,u32 csg_id,u32 cs_id)1521 cs_slot_process_fault_event_locked(struct panthor_device *ptdev,
1522 				   u32 csg_id, u32 cs_id)
1523 {
1524 	struct panthor_scheduler *sched = ptdev->scheduler;
1525 	struct panthor_csg_slot *csg_slot = &sched->csg_slots[csg_id];
1526 	struct panthor_group *group = csg_slot->group;
1527 	struct panthor_queue *queue = group && cs_id < group->queue_count ?
1528 				      group->queues[cs_id] : NULL;
1529 	struct panthor_fw_cs_iface *cs_iface;
1530 	u32 fault;
1531 	u64 info;
1532 
1533 	lockdep_assert_held(&sched->lock);
1534 
1535 	cs_iface = panthor_fw_get_cs_iface(ptdev, csg_id, cs_id);
1536 	fault = cs_iface->output->fault;
1537 	info = cs_iface->output->fault_info;
1538 
1539 	if (queue) {
1540 		u64 cs_extract = queue->iface.output->extract;
1541 		struct panthor_job *job;
1542 
1543 		guard(spinlock_irqsave)(&queue->fence_ctx.lock);
1544 		list_for_each_entry(job, &queue->fence_ctx.in_flight_jobs, node) {
1545 			if (cs_extract >= job->ringbuf.end)
1546 				continue;
1547 
1548 			if (cs_extract < job->ringbuf.start)
1549 				break;
1550 
1551 			dma_fence_set_error(job->done_fence, -EINVAL);
1552 		}
1553 	}
1554 
1555 	if (group) {
1556 		drm_warn(&ptdev->base, "CS_FAULT: pid=%d, comm=%s\n",
1557 			 group->task_info.pid, group->task_info.comm);
1558 	}
1559 
1560 	drm_warn(&ptdev->base,
1561 		 "CSG slot %d CS slot: %d\n"
1562 		 "CS_FAULT.EXCEPTION_TYPE: 0x%x (%s)\n"
1563 		 "CS_FAULT.EXCEPTION_DATA: 0x%x\n"
1564 		 "CS_FAULT_INFO.EXCEPTION_DATA: 0x%llx\n",
1565 		 csg_id, cs_id,
1566 		 (unsigned int)CS_EXCEPTION_TYPE(fault),
1567 		 panthor_exception_name(ptdev, CS_EXCEPTION_TYPE(fault)),
1568 		 (unsigned int)CS_EXCEPTION_DATA(fault),
1569 		 info);
1570 }
1571 
group_process_tiler_oom(struct panthor_group * group,u32 cs_id)1572 static int group_process_tiler_oom(struct panthor_group *group, u32 cs_id)
1573 {
1574 	struct panthor_device *ptdev = group->ptdev;
1575 	struct panthor_scheduler *sched = ptdev->scheduler;
1576 	u32 renderpasses_in_flight, pending_frag_count;
1577 	struct panthor_heap_pool *heaps = NULL;
1578 	u64 heap_address, new_chunk_va = 0;
1579 	u32 vt_start, vt_end, frag_end;
1580 	int ret, csg_id;
1581 
1582 	mutex_lock(&sched->lock);
1583 	csg_id = group->csg_id;
1584 	if (csg_id >= 0) {
1585 		struct panthor_fw_cs_iface *cs_iface;
1586 
1587 		cs_iface = panthor_fw_get_cs_iface(ptdev, csg_id, cs_id);
1588 		heaps = panthor_vm_get_heap_pool(group->vm, false);
1589 		heap_address = cs_iface->output->heap_address;
1590 		vt_start = cs_iface->output->heap_vt_start;
1591 		vt_end = cs_iface->output->heap_vt_end;
1592 		frag_end = cs_iface->output->heap_frag_end;
1593 		renderpasses_in_flight = vt_start - frag_end;
1594 		pending_frag_count = vt_end - frag_end;
1595 	}
1596 	mutex_unlock(&sched->lock);
1597 
1598 	/* The group got scheduled out, we stop here. We will get a new tiler OOM event
1599 	 * when it's scheduled again.
1600 	 */
1601 	if (unlikely(csg_id < 0))
1602 		return 0;
1603 
1604 	if (IS_ERR(heaps)) {
1605 		ret = -EINVAL;
1606 		heaps = NULL;
1607 	} else if (frag_end > vt_end || vt_end >= vt_start) {
1608 		ret = -EINVAL;
1609 	} else {
1610 		/* We do the allocation without holding the scheduler lock to avoid
1611 		 * blocking the scheduling.
1612 		 */
1613 		ret = panthor_heap_grow(heaps, heap_address,
1614 					renderpasses_in_flight,
1615 					pending_frag_count, &new_chunk_va);
1616 	}
1617 
1618 	/* If the heap context doesn't have memory for us, we want to let the
1619 	 * FW try to reclaim memory by waiting for fragment jobs to land or by
1620 	 * executing the tiler OOM exception handler, which is supposed to
1621 	 * implement incremental rendering.
1622 	 */
1623 	if (ret && ret != -ENOMEM) {
1624 		drm_warn(&ptdev->base, "Failed to extend the tiler heap\n");
1625 		group->fatal_queues |= BIT(cs_id);
1626 		sched_queue_delayed_work(sched, tick, 0);
1627 		goto out_put_heap_pool;
1628 	}
1629 
1630 	mutex_lock(&sched->lock);
1631 	csg_id = group->csg_id;
1632 	if (csg_id >= 0) {
1633 		struct panthor_fw_csg_iface *csg_iface;
1634 		struct panthor_fw_cs_iface *cs_iface;
1635 
1636 		csg_iface = panthor_fw_get_csg_iface(ptdev, csg_id);
1637 		cs_iface = panthor_fw_get_cs_iface(ptdev, csg_id, cs_id);
1638 
1639 		cs_iface->input->heap_start = new_chunk_va;
1640 		cs_iface->input->heap_end = new_chunk_va;
1641 		panthor_fw_update_reqs(cs_iface, req, cs_iface->output->ack, CS_TILER_OOM);
1642 		panthor_fw_toggle_reqs(csg_iface, doorbell_req, doorbell_ack, BIT(cs_id));
1643 		panthor_fw_ring_csg_doorbells(ptdev, BIT(csg_id));
1644 	}
1645 	mutex_unlock(&sched->lock);
1646 
1647 	/* We allocated a chunck, but couldn't link it to the heap
1648 	 * context because the group was scheduled out while we were
1649 	 * allocating memory. We need to return this chunk to the heap.
1650 	 */
1651 	if (unlikely(csg_id < 0 && new_chunk_va))
1652 		panthor_heap_return_chunk(heaps, heap_address, new_chunk_va);
1653 
1654 	ret = 0;
1655 
1656 out_put_heap_pool:
1657 	panthor_heap_pool_put(heaps);
1658 	return ret;
1659 }
1660 
group_tiler_oom_work(struct work_struct * work)1661 static void group_tiler_oom_work(struct work_struct *work)
1662 {
1663 	struct panthor_group *group =
1664 		container_of(work, struct panthor_group, tiler_oom_work);
1665 	u32 tiler_oom = atomic_xchg(&group->tiler_oom, 0);
1666 
1667 	while (tiler_oom) {
1668 		u32 cs_id = ffs(tiler_oom) - 1;
1669 
1670 		group_process_tiler_oom(group, cs_id);
1671 		tiler_oom &= ~BIT(cs_id);
1672 	}
1673 
1674 	group_put(group);
1675 }
1676 
1677 static void
cs_slot_process_tiler_oom_event_locked(struct panthor_device * ptdev,u32 csg_id,u32 cs_id)1678 cs_slot_process_tiler_oom_event_locked(struct panthor_device *ptdev,
1679 				       u32 csg_id, u32 cs_id)
1680 {
1681 	struct panthor_scheduler *sched = ptdev->scheduler;
1682 	struct panthor_csg_slot *csg_slot = &sched->csg_slots[csg_id];
1683 	struct panthor_group *group = csg_slot->group;
1684 
1685 	lockdep_assert_held(&sched->lock);
1686 
1687 	if (drm_WARN_ON(&ptdev->base, !group))
1688 		return;
1689 
1690 	atomic_or(BIT(cs_id), &group->tiler_oom);
1691 
1692 	/* We don't use group_queue_work() here because we want to queue the
1693 	 * work item to the heap_alloc_wq.
1694 	 */
1695 	group_get(group);
1696 	if (!queue_work(sched->heap_alloc_wq, &group->tiler_oom_work))
1697 		group_put(group);
1698 }
1699 
cs_slot_process_irq_locked(struct panthor_device * ptdev,u32 csg_id,u32 cs_id)1700 static bool cs_slot_process_irq_locked(struct panthor_device *ptdev,
1701 				       u32 csg_id, u32 cs_id)
1702 {
1703 	struct panthor_fw_cs_iface *cs_iface;
1704 	u32 req, ack, events;
1705 
1706 	lockdep_assert_held(&ptdev->scheduler->lock);
1707 
1708 	cs_iface = panthor_fw_get_cs_iface(ptdev, csg_id, cs_id);
1709 	req = cs_iface->input->req;
1710 	ack = cs_iface->output->ack;
1711 	events = (req ^ ack) & CS_EVT_MASK;
1712 
1713 	if (events & CS_FATAL)
1714 		cs_slot_process_fatal_event_locked(ptdev, csg_id, cs_id);
1715 
1716 	if (events & CS_FAULT)
1717 		cs_slot_process_fault_event_locked(ptdev, csg_id, cs_id);
1718 
1719 	if (events & CS_TILER_OOM)
1720 		cs_slot_process_tiler_oom_event_locked(ptdev, csg_id, cs_id);
1721 
1722 	/* We don't acknowledge the TILER_OOM event since its handling is
1723 	 * deferred to a separate work.
1724 	 */
1725 	panthor_fw_update_reqs(cs_iface, req, ack, CS_FATAL | CS_FAULT);
1726 
1727 	return (events & (CS_FAULT | CS_TILER_OOM)) != 0;
1728 }
1729 
csg_slot_process_idle_event_locked(struct panthor_device * ptdev,u32 csg_id)1730 static void csg_slot_process_idle_event_locked(struct panthor_device *ptdev, u32 csg_id)
1731 {
1732 	struct panthor_scheduler *sched = ptdev->scheduler;
1733 
1734 	lockdep_assert_held(&sched->lock);
1735 
1736 	sched->might_have_idle_groups = true;
1737 
1738 	/* Schedule a tick so we can evict idle groups and schedule non-idle
1739 	 * ones. This will also update runtime PM and devfreq busy/idle states,
1740 	 * so the device can lower its frequency or get suspended.
1741 	 */
1742 	sched_queue_delayed_work(sched, tick, 0);
1743 }
1744 
csg_slot_sync_update_locked(struct panthor_device * ptdev,u32 csg_id)1745 static void csg_slot_sync_update_locked(struct panthor_device *ptdev,
1746 					u32 csg_id)
1747 {
1748 	struct panthor_csg_slot *csg_slot = &ptdev->scheduler->csg_slots[csg_id];
1749 	struct panthor_group *group = csg_slot->group;
1750 
1751 	lockdep_assert_held(&ptdev->scheduler->lock);
1752 
1753 	if (group)
1754 		group_queue_work(group, sync_upd);
1755 
1756 	sched_queue_work(ptdev->scheduler, sync_upd);
1757 }
1758 
1759 static void
csg_slot_process_progress_timer_event_locked(struct panthor_device * ptdev,u32 csg_id)1760 csg_slot_process_progress_timer_event_locked(struct panthor_device *ptdev, u32 csg_id)
1761 {
1762 	struct panthor_scheduler *sched = ptdev->scheduler;
1763 	struct panthor_csg_slot *csg_slot = &sched->csg_slots[csg_id];
1764 	struct panthor_group *group = csg_slot->group;
1765 
1766 	lockdep_assert_held(&sched->lock);
1767 
1768 	group = csg_slot->group;
1769 	if (!drm_WARN_ON(&ptdev->base, !group)) {
1770 		drm_warn(&ptdev->base, "CSG_PROGRESS_TIMER_EVENT: pid=%d, comm=%s\n",
1771 			 group->task_info.pid, group->task_info.comm);
1772 
1773 		group->timedout = true;
1774 	}
1775 
1776 	drm_warn(&ptdev->base, "CSG slot %d progress timeout\n", csg_id);
1777 
1778 	sched_queue_delayed_work(sched, tick, 0);
1779 }
1780 
sched_process_csg_irq_locked(struct panthor_device * ptdev,u32 csg_id)1781 static void sched_process_csg_irq_locked(struct panthor_device *ptdev, u32 csg_id)
1782 {
1783 	u32 req, ack, cs_irq_req, cs_irq_ack, cs_irqs, csg_events;
1784 	struct panthor_fw_csg_iface *csg_iface;
1785 	u32 ring_cs_db_mask = 0;
1786 
1787 	lockdep_assert_held(&ptdev->scheduler->lock);
1788 
1789 	if (drm_WARN_ON(&ptdev->base, csg_id >= ptdev->scheduler->csg_slot_count))
1790 		return;
1791 
1792 	csg_iface = panthor_fw_get_csg_iface(ptdev, csg_id);
1793 	req = READ_ONCE(csg_iface->input->req);
1794 	ack = READ_ONCE(csg_iface->output->ack);
1795 	cs_irq_req = READ_ONCE(csg_iface->output->cs_irq_req);
1796 	cs_irq_ack = READ_ONCE(csg_iface->input->cs_irq_ack);
1797 	csg_events = (req ^ ack) & CSG_EVT_MASK;
1798 
1799 	/* There may not be any pending CSG/CS interrupts to process */
1800 	if (req == ack && cs_irq_req == cs_irq_ack)
1801 		return;
1802 
1803 	/* Immediately set IRQ_ACK bits to be same as the IRQ_REQ bits before
1804 	 * examining the CS_ACK & CS_REQ bits. This would ensure that Host
1805 	 * doesn't miss an interrupt for the CS in the race scenario where
1806 	 * whilst Host is servicing an interrupt for the CS, firmware sends
1807 	 * another interrupt for that CS.
1808 	 */
1809 	csg_iface->input->cs_irq_ack = cs_irq_req;
1810 
1811 	panthor_fw_update_reqs(csg_iface, req, ack,
1812 			       CSG_SYNC_UPDATE |
1813 			       CSG_IDLE |
1814 			       CSG_PROGRESS_TIMER_EVENT);
1815 
1816 	if (csg_events & CSG_IDLE)
1817 		csg_slot_process_idle_event_locked(ptdev, csg_id);
1818 
1819 	if (csg_events & CSG_PROGRESS_TIMER_EVENT)
1820 		csg_slot_process_progress_timer_event_locked(ptdev, csg_id);
1821 
1822 	cs_irqs = cs_irq_req ^ cs_irq_ack;
1823 	while (cs_irqs) {
1824 		u32 cs_id = ffs(cs_irqs) - 1;
1825 
1826 		if (cs_slot_process_irq_locked(ptdev, csg_id, cs_id))
1827 			ring_cs_db_mask |= BIT(cs_id);
1828 
1829 		cs_irqs &= ~BIT(cs_id);
1830 	}
1831 
1832 	if (csg_events & CSG_SYNC_UPDATE)
1833 		csg_slot_sync_update_locked(ptdev, csg_id);
1834 
1835 	if (ring_cs_db_mask)
1836 		panthor_fw_toggle_reqs(csg_iface, doorbell_req, doorbell_ack, ring_cs_db_mask);
1837 
1838 	panthor_fw_ring_csg_doorbells(ptdev, BIT(csg_id));
1839 }
1840 
sched_process_idle_event_locked(struct panthor_device * ptdev)1841 static void sched_process_idle_event_locked(struct panthor_device *ptdev)
1842 {
1843 	struct panthor_fw_global_iface *glb_iface = panthor_fw_get_glb_iface(ptdev);
1844 
1845 	lockdep_assert_held(&ptdev->scheduler->lock);
1846 
1847 	/* Acknowledge the idle event and schedule a tick. */
1848 	panthor_fw_update_reqs(glb_iface, req, glb_iface->output->ack, GLB_IDLE);
1849 	sched_queue_delayed_work(ptdev->scheduler, tick, 0);
1850 }
1851 
1852 /**
1853  * sched_process_global_irq_locked() - Process the scheduling part of a global IRQ
1854  * @ptdev: Device.
1855  */
sched_process_global_irq_locked(struct panthor_device * ptdev)1856 static void sched_process_global_irq_locked(struct panthor_device *ptdev)
1857 {
1858 	struct panthor_fw_global_iface *glb_iface = panthor_fw_get_glb_iface(ptdev);
1859 	u32 req, ack, evts;
1860 
1861 	lockdep_assert_held(&ptdev->scheduler->lock);
1862 
1863 	req = READ_ONCE(glb_iface->input->req);
1864 	ack = READ_ONCE(glb_iface->output->ack);
1865 	evts = (req ^ ack) & GLB_EVT_MASK;
1866 
1867 	if (evts & GLB_IDLE)
1868 		sched_process_idle_event_locked(ptdev);
1869 }
1870 
process_fw_events_work(struct work_struct * work)1871 static void process_fw_events_work(struct work_struct *work)
1872 {
1873 	struct panthor_scheduler *sched = container_of(work, struct panthor_scheduler,
1874 						      fw_events_work);
1875 	u32 events = atomic_xchg(&sched->fw_events, 0);
1876 	struct panthor_device *ptdev = sched->ptdev;
1877 
1878 	mutex_lock(&sched->lock);
1879 
1880 	if (events & JOB_INT_GLOBAL_IF) {
1881 		sched_process_global_irq_locked(ptdev);
1882 		events &= ~JOB_INT_GLOBAL_IF;
1883 	}
1884 
1885 	while (events) {
1886 		u32 csg_id = ffs(events) - 1;
1887 
1888 		sched_process_csg_irq_locked(ptdev, csg_id);
1889 		events &= ~BIT(csg_id);
1890 	}
1891 
1892 	mutex_unlock(&sched->lock);
1893 }
1894 
1895 /**
1896  * panthor_sched_report_fw_events() - Report FW events to the scheduler.
1897  * @ptdev: Device.
1898  * @events: Bitmask of pending FW events to report.
1899  */
panthor_sched_report_fw_events(struct panthor_device * ptdev,u32 events)1900 void panthor_sched_report_fw_events(struct panthor_device *ptdev, u32 events)
1901 {
1902 	if (!ptdev->scheduler)
1903 		return;
1904 
1905 	atomic_or(events, &ptdev->scheduler->fw_events);
1906 	sched_queue_work(ptdev->scheduler, fw_events);
1907 }
1908 
fence_get_driver_name(struct dma_fence * fence)1909 static const char *fence_get_driver_name(struct dma_fence *fence)
1910 {
1911 	return "panthor";
1912 }
1913 
queue_fence_get_timeline_name(struct dma_fence * fence)1914 static const char *queue_fence_get_timeline_name(struct dma_fence *fence)
1915 {
1916 	return "queue-fence";
1917 }
1918 
1919 static const struct dma_fence_ops panthor_queue_fence_ops = {
1920 	.get_driver_name = fence_get_driver_name,
1921 	.get_timeline_name = queue_fence_get_timeline_name,
1922 };
1923 
1924 struct panthor_csg_slots_upd_ctx {
1925 	u32 update_mask;
1926 	u32 timedout_mask;
1927 	struct {
1928 		u32 value;
1929 		u32 mask;
1930 	} requests[MAX_CSGS];
1931 };
1932 
csgs_upd_ctx_init(struct panthor_csg_slots_upd_ctx * ctx)1933 static void csgs_upd_ctx_init(struct panthor_csg_slots_upd_ctx *ctx)
1934 {
1935 	memset(ctx, 0, sizeof(*ctx));
1936 }
1937 
csgs_upd_ctx_queue_reqs(struct panthor_device * ptdev,struct panthor_csg_slots_upd_ctx * ctx,u32 csg_id,u32 value,u32 mask)1938 static void csgs_upd_ctx_queue_reqs(struct panthor_device *ptdev,
1939 				    struct panthor_csg_slots_upd_ctx *ctx,
1940 				    u32 csg_id, u32 value, u32 mask)
1941 {
1942 	if (drm_WARN_ON(&ptdev->base, !mask) ||
1943 	    drm_WARN_ON(&ptdev->base, csg_id >= ptdev->scheduler->csg_slot_count))
1944 		return;
1945 
1946 	ctx->requests[csg_id].value = (ctx->requests[csg_id].value & ~mask) | (value & mask);
1947 	ctx->requests[csg_id].mask |= mask;
1948 	ctx->update_mask |= BIT(csg_id);
1949 }
1950 
csgs_upd_ctx_apply_locked(struct panthor_device * ptdev,struct panthor_csg_slots_upd_ctx * ctx)1951 static int csgs_upd_ctx_apply_locked(struct panthor_device *ptdev,
1952 				     struct panthor_csg_slots_upd_ctx *ctx)
1953 {
1954 	struct panthor_scheduler *sched = ptdev->scheduler;
1955 	u32 update_slots = ctx->update_mask;
1956 
1957 	lockdep_assert_held(&sched->lock);
1958 
1959 	if (!ctx->update_mask)
1960 		return 0;
1961 
1962 	while (update_slots) {
1963 		struct panthor_fw_csg_iface *csg_iface;
1964 		u32 csg_id = ffs(update_slots) - 1;
1965 
1966 		update_slots &= ~BIT(csg_id);
1967 		csg_iface = panthor_fw_get_csg_iface(ptdev, csg_id);
1968 		panthor_fw_update_reqs(csg_iface, req,
1969 				       ctx->requests[csg_id].value,
1970 				       ctx->requests[csg_id].mask);
1971 	}
1972 
1973 	panthor_fw_ring_csg_doorbells(ptdev, ctx->update_mask);
1974 
1975 	update_slots = ctx->update_mask;
1976 	while (update_slots) {
1977 		struct panthor_fw_csg_iface *csg_iface;
1978 		u32 csg_id = ffs(update_slots) - 1;
1979 		u32 req_mask = ctx->requests[csg_id].mask, acked;
1980 		int ret;
1981 
1982 		update_slots &= ~BIT(csg_id);
1983 		csg_iface = panthor_fw_get_csg_iface(ptdev, csg_id);
1984 
1985 		ret = panthor_fw_csg_wait_acks(ptdev, csg_id, req_mask, &acked, 100);
1986 
1987 		if (acked & CSG_ENDPOINT_CONFIG)
1988 			csg_slot_sync_priority_locked(ptdev, csg_id);
1989 
1990 		if (acked & CSG_STATE_MASK)
1991 			csg_slot_sync_state_locked(ptdev, csg_id);
1992 
1993 		if (acked & CSG_STATUS_UPDATE)
1994 			csg_slot_sync_queues_state_locked(ptdev, csg_id);
1995 
1996 		if (ret && acked != req_mask &&
1997 		    ((csg_iface->input->req ^ csg_iface->output->ack) & req_mask) != 0) {
1998 			drm_err(&ptdev->base, "CSG %d update request timedout", csg_id);
1999 			ctx->timedout_mask |= BIT(csg_id);
2000 		}
2001 	}
2002 
2003 	if (ctx->timedout_mask)
2004 		return -ETIMEDOUT;
2005 
2006 	return 0;
2007 }
2008 
2009 struct panthor_sched_tick_ctx {
2010 	struct list_head old_groups[PANTHOR_CSG_PRIORITY_COUNT];
2011 	struct list_head groups[PANTHOR_CSG_PRIORITY_COUNT];
2012 	u32 idle_group_count;
2013 	u32 group_count;
2014 	struct panthor_vm *vms[MAX_CS_PER_CSG];
2015 	u32 as_count;
2016 	bool immediate_tick;
2017 	bool stop_tick;
2018 	u32 csg_upd_failed_mask;
2019 };
2020 
2021 static bool
tick_ctx_is_full(const struct panthor_scheduler * sched,const struct panthor_sched_tick_ctx * ctx)2022 tick_ctx_is_full(const struct panthor_scheduler *sched,
2023 		 const struct panthor_sched_tick_ctx *ctx)
2024 {
2025 	return ctx->group_count == sched->csg_slot_count;
2026 }
2027 
2028 static void
tick_ctx_pick_groups_from_list(const struct panthor_scheduler * sched,struct panthor_sched_tick_ctx * ctx,struct list_head * queue,bool skip_idle_groups,bool owned_by_tick_ctx)2029 tick_ctx_pick_groups_from_list(const struct panthor_scheduler *sched,
2030 			       struct panthor_sched_tick_ctx *ctx,
2031 			       struct list_head *queue,
2032 			       bool skip_idle_groups,
2033 			       bool owned_by_tick_ctx)
2034 {
2035 	struct panthor_group *group, *tmp;
2036 
2037 	if (tick_ctx_is_full(sched, ctx))
2038 		return;
2039 
2040 	list_for_each_entry_safe(group, tmp, queue, run_node) {
2041 		u32 i;
2042 
2043 		if (!group_can_run(group))
2044 			continue;
2045 
2046 		if (skip_idle_groups && group_is_idle(group))
2047 			continue;
2048 
2049 		for (i = 0; i < ctx->as_count; i++) {
2050 			if (ctx->vms[i] == group->vm)
2051 				break;
2052 		}
2053 
2054 		if (i == ctx->as_count && ctx->as_count == sched->as_slot_count)
2055 			continue;
2056 
2057 		if (!owned_by_tick_ctx)
2058 			group_get(group);
2059 
2060 		ctx->group_count++;
2061 
2062 		/* If we have more than one active group with the same priority,
2063 		 * we need to keep ticking to rotate the CSG priority.
2064 		 */
2065 		if (group_is_idle(group))
2066 			ctx->idle_group_count++;
2067 		else if (!list_empty(&ctx->groups[group->priority]))
2068 			ctx->stop_tick = false;
2069 
2070 		list_move_tail(&group->run_node, &ctx->groups[group->priority]);
2071 
2072 		if (i == ctx->as_count)
2073 			ctx->vms[ctx->as_count++] = group->vm;
2074 
2075 		if (tick_ctx_is_full(sched, ctx))
2076 			return;
2077 	}
2078 }
2079 
2080 static void
tick_ctx_insert_old_group(struct panthor_scheduler * sched,struct panthor_sched_tick_ctx * ctx,struct panthor_group * group)2081 tick_ctx_insert_old_group(struct panthor_scheduler *sched,
2082 			  struct panthor_sched_tick_ctx *ctx,
2083 			  struct panthor_group *group)
2084 {
2085 	struct panthor_csg_slot *csg_slot = &sched->csg_slots[group->csg_id];
2086 	struct panthor_group *other_group;
2087 
2088 	/* Class groups in descending priority order so we can easily rotate. */
2089 	list_for_each_entry(other_group,
2090 			    &ctx->old_groups[csg_slot->group->priority],
2091 			    run_node) {
2092 		struct panthor_csg_slot *other_csg_slot = &sched->csg_slots[other_group->csg_id];
2093 
2094 		/* Our group has a higher prio than the one we're testing against,
2095 		 * place it just before.
2096 		 */
2097 		if (csg_slot->priority > other_csg_slot->priority) {
2098 			list_add_tail(&group->run_node, &other_group->run_node);
2099 			return;
2100 		}
2101 	}
2102 
2103 	list_add_tail(&group->run_node, &ctx->old_groups[group->priority]);
2104 }
2105 
2106 static void
tick_ctx_init(struct panthor_scheduler * sched,struct panthor_sched_tick_ctx * ctx)2107 tick_ctx_init(struct panthor_scheduler *sched,
2108 	      struct panthor_sched_tick_ctx *ctx)
2109 {
2110 	struct panthor_device *ptdev = sched->ptdev;
2111 	struct panthor_csg_slots_upd_ctx upd_ctx;
2112 	int ret;
2113 	u32 i;
2114 
2115 	memset(ctx, 0, sizeof(*ctx));
2116 	csgs_upd_ctx_init(&upd_ctx);
2117 
2118 	ctx->stop_tick = true;
2119 	for (i = 0; i < ARRAY_SIZE(ctx->groups); i++) {
2120 		INIT_LIST_HEAD(&ctx->groups[i]);
2121 		INIT_LIST_HEAD(&ctx->old_groups[i]);
2122 	}
2123 
2124 	for (i = 0; i < sched->csg_slot_count; i++) {
2125 		struct panthor_csg_slot *csg_slot = &sched->csg_slots[i];
2126 		struct panthor_group *group = csg_slot->group;
2127 		struct panthor_fw_csg_iface *csg_iface;
2128 
2129 		if (!group)
2130 			continue;
2131 
2132 		csg_iface = panthor_fw_get_csg_iface(ptdev, i);
2133 		group_get(group);
2134 
2135 		/* If there was unhandled faults on the VM, force processing of
2136 		 * CSG IRQs, so we can flag the faulty queue.
2137 		 */
2138 		if (panthor_vm_has_unhandled_faults(group->vm)) {
2139 			sched_process_csg_irq_locked(ptdev, i);
2140 
2141 			/* No fatal fault reported, flag all queues as faulty. */
2142 			if (!group->fatal_queues)
2143 				group->fatal_queues |= GENMASK(group->queue_count - 1, 0);
2144 		}
2145 
2146 		tick_ctx_insert_old_group(sched, ctx, group);
2147 		csgs_upd_ctx_queue_reqs(ptdev, &upd_ctx, i,
2148 					csg_iface->output->ack ^ CSG_STATUS_UPDATE,
2149 					CSG_STATUS_UPDATE);
2150 	}
2151 
2152 	ret = csgs_upd_ctx_apply_locked(ptdev, &upd_ctx);
2153 	if (ret) {
2154 		panthor_device_schedule_reset(ptdev);
2155 		ctx->csg_upd_failed_mask |= upd_ctx.timedout_mask;
2156 	}
2157 }
2158 
2159 static void
group_term_post_processing(struct panthor_group * group)2160 group_term_post_processing(struct panthor_group *group)
2161 {
2162 	struct panthor_job *job, *tmp;
2163 	LIST_HEAD(faulty_jobs);
2164 	bool cookie;
2165 	u32 i = 0;
2166 
2167 	if (drm_WARN_ON(&group->ptdev->base, group_can_run(group)))
2168 		return;
2169 
2170 	cookie = dma_fence_begin_signalling();
2171 	for (i = 0; i < group->queue_count; i++) {
2172 		struct panthor_queue *queue = group->queues[i];
2173 		struct panthor_syncobj_64b *syncobj;
2174 		int err;
2175 
2176 		if (group->fatal_queues & BIT(i))
2177 			err = -EINVAL;
2178 		else if (group->timedout)
2179 			err = -ETIMEDOUT;
2180 		else
2181 			err = -ECANCELED;
2182 
2183 		if (!queue)
2184 			continue;
2185 
2186 		scoped_guard(spinlock_irqsave, &queue->fence_ctx.lock) {
2187 			list_for_each_entry_safe(job, tmp, &queue->fence_ctx.in_flight_jobs, node) {
2188 				list_move_tail(&job->node, &faulty_jobs);
2189 				dma_fence_set_error(job->done_fence, err);
2190 				dma_fence_signal_locked(job->done_fence);
2191 			}
2192 		}
2193 
2194 		/* Manually update the syncobj seqno to unblock waiters. */
2195 		syncobj = group->syncobjs->kmap + (i * sizeof(*syncobj));
2196 		syncobj->status = ~0;
2197 		syncobj->seqno = atomic64_read(&queue->fence_ctx.seqno);
2198 		sched_queue_work(group->ptdev->scheduler, sync_upd);
2199 	}
2200 	dma_fence_end_signalling(cookie);
2201 
2202 	list_for_each_entry_safe(job, tmp, &faulty_jobs, node) {
2203 		list_del_init(&job->node);
2204 		panthor_job_put(&job->base);
2205 	}
2206 }
2207 
group_term_work(struct work_struct * work)2208 static void group_term_work(struct work_struct *work)
2209 {
2210 	struct panthor_group *group =
2211 		container_of(work, struct panthor_group, term_work);
2212 
2213 	group_term_post_processing(group);
2214 	group_put(group);
2215 }
2216 
2217 static void
tick_ctx_cleanup(struct panthor_scheduler * sched,struct panthor_sched_tick_ctx * ctx)2218 tick_ctx_cleanup(struct panthor_scheduler *sched,
2219 		 struct panthor_sched_tick_ctx *ctx)
2220 {
2221 	struct panthor_device *ptdev = sched->ptdev;
2222 	struct panthor_group *group, *tmp;
2223 	u32 i;
2224 
2225 	for (i = 0; i < ARRAY_SIZE(ctx->old_groups); i++) {
2226 		list_for_each_entry_safe(group, tmp, &ctx->old_groups[i], run_node) {
2227 			/* If everything went fine, we should only have groups
2228 			 * to be terminated in the old_groups lists.
2229 			 */
2230 			drm_WARN_ON(&ptdev->base, !ctx->csg_upd_failed_mask &&
2231 				    group_can_run(group));
2232 
2233 			if (!group_can_run(group)) {
2234 				list_del_init(&group->run_node);
2235 				list_del_init(&group->wait_node);
2236 				group_queue_work(group, term);
2237 			} else if (group->csg_id >= 0) {
2238 				list_del_init(&group->run_node);
2239 			} else {
2240 				list_move(&group->run_node,
2241 					  group_is_idle(group) ?
2242 					  &sched->groups.idle[group->priority] :
2243 					  &sched->groups.runnable[group->priority]);
2244 			}
2245 			group_put(group);
2246 		}
2247 	}
2248 
2249 	for (i = 0; i < ARRAY_SIZE(ctx->groups); i++) {
2250 		/* If everything went fine, the groups to schedule lists should
2251 		 * be empty.
2252 		 */
2253 		drm_WARN_ON(&ptdev->base,
2254 			    !ctx->csg_upd_failed_mask && !list_empty(&ctx->groups[i]));
2255 
2256 		list_for_each_entry_safe(group, tmp, &ctx->groups[i], run_node) {
2257 			if (group->csg_id >= 0) {
2258 				list_del_init(&group->run_node);
2259 			} else {
2260 				list_move(&group->run_node,
2261 					  group_is_idle(group) ?
2262 					  &sched->groups.idle[group->priority] :
2263 					  &sched->groups.runnable[group->priority]);
2264 			}
2265 			group_put(group);
2266 		}
2267 	}
2268 }
2269 
2270 static void
tick_ctx_apply(struct panthor_scheduler * sched,struct panthor_sched_tick_ctx * ctx)2271 tick_ctx_apply(struct panthor_scheduler *sched, struct panthor_sched_tick_ctx *ctx)
2272 {
2273 	struct panthor_group *group, *tmp;
2274 	struct panthor_device *ptdev = sched->ptdev;
2275 	struct panthor_csg_slot *csg_slot;
2276 	int prio, new_csg_prio = MAX_CSG_PRIO, i;
2277 	u32 free_csg_slots = 0;
2278 	struct panthor_csg_slots_upd_ctx upd_ctx;
2279 	int ret;
2280 
2281 	csgs_upd_ctx_init(&upd_ctx);
2282 
2283 	for (prio = PANTHOR_CSG_PRIORITY_COUNT - 1; prio >= 0; prio--) {
2284 		/* Suspend or terminate evicted groups. */
2285 		list_for_each_entry(group, &ctx->old_groups[prio], run_node) {
2286 			bool term = !group_can_run(group);
2287 			int csg_id = group->csg_id;
2288 
2289 			if (drm_WARN_ON(&ptdev->base, csg_id < 0))
2290 				continue;
2291 
2292 			csg_slot = &sched->csg_slots[csg_id];
2293 			csgs_upd_ctx_queue_reqs(ptdev, &upd_ctx, csg_id,
2294 						term ? CSG_STATE_TERMINATE : CSG_STATE_SUSPEND,
2295 						CSG_STATE_MASK);
2296 		}
2297 
2298 		/* Update priorities on already running groups. */
2299 		list_for_each_entry(group, &ctx->groups[prio], run_node) {
2300 			struct panthor_fw_csg_iface *csg_iface;
2301 			int csg_id = group->csg_id;
2302 
2303 			if (csg_id < 0) {
2304 				new_csg_prio--;
2305 				continue;
2306 			}
2307 
2308 			csg_slot = &sched->csg_slots[csg_id];
2309 			csg_iface = panthor_fw_get_csg_iface(ptdev, csg_id);
2310 			if (csg_slot->priority == new_csg_prio) {
2311 				new_csg_prio--;
2312 				continue;
2313 			}
2314 
2315 			panthor_fw_csg_endpoint_req_update(ptdev, csg_iface,
2316 							   CSG_EP_REQ_PRIORITY(new_csg_prio),
2317 							   CSG_EP_REQ_PRIORITY_MASK);
2318 			csgs_upd_ctx_queue_reqs(ptdev, &upd_ctx, csg_id,
2319 						csg_iface->output->ack ^ CSG_ENDPOINT_CONFIG,
2320 						CSG_ENDPOINT_CONFIG);
2321 			new_csg_prio--;
2322 		}
2323 	}
2324 
2325 	ret = csgs_upd_ctx_apply_locked(ptdev, &upd_ctx);
2326 	if (ret) {
2327 		panthor_device_schedule_reset(ptdev);
2328 		ctx->csg_upd_failed_mask |= upd_ctx.timedout_mask;
2329 		return;
2330 	}
2331 
2332 	/* Unbind evicted groups. */
2333 	for (prio = PANTHOR_CSG_PRIORITY_COUNT - 1; prio >= 0; prio--) {
2334 		list_for_each_entry(group, &ctx->old_groups[prio], run_node) {
2335 			/* This group is gone. Process interrupts to clear
2336 			 * any pending interrupts before we start the new
2337 			 * group.
2338 			 */
2339 			if (group->csg_id >= 0)
2340 				sched_process_csg_irq_locked(ptdev, group->csg_id);
2341 
2342 			group_unbind_locked(group);
2343 		}
2344 	}
2345 
2346 	for (i = 0; i < sched->csg_slot_count; i++) {
2347 		if (!sched->csg_slots[i].group)
2348 			free_csg_slots |= BIT(i);
2349 	}
2350 
2351 	csgs_upd_ctx_init(&upd_ctx);
2352 	new_csg_prio = MAX_CSG_PRIO;
2353 
2354 	/* Start new groups. */
2355 	for (prio = PANTHOR_CSG_PRIORITY_COUNT - 1; prio >= 0; prio--) {
2356 		list_for_each_entry(group, &ctx->groups[prio], run_node) {
2357 			int csg_id = group->csg_id;
2358 			struct panthor_fw_csg_iface *csg_iface;
2359 
2360 			if (csg_id >= 0) {
2361 				new_csg_prio--;
2362 				continue;
2363 			}
2364 
2365 			csg_id = ffs(free_csg_slots) - 1;
2366 			if (drm_WARN_ON(&ptdev->base, csg_id < 0))
2367 				break;
2368 
2369 			csg_iface = panthor_fw_get_csg_iface(ptdev, csg_id);
2370 			csg_slot = &sched->csg_slots[csg_id];
2371 			ret = group_bind_locked(group, csg_id);
2372 			if (ret) {
2373 				panthor_device_schedule_reset(ptdev);
2374 				ctx->csg_upd_failed_mask |= BIT(csg_id);
2375 				return;
2376 			}
2377 
2378 			csg_slot_prog_locked(ptdev, csg_id, new_csg_prio--);
2379 			csgs_upd_ctx_queue_reqs(ptdev, &upd_ctx, csg_id,
2380 						group->state == PANTHOR_CS_GROUP_SUSPENDED ?
2381 						CSG_STATE_RESUME : CSG_STATE_START,
2382 						CSG_STATE_MASK);
2383 			csgs_upd_ctx_queue_reqs(ptdev, &upd_ctx, csg_id,
2384 						csg_iface->output->ack ^ CSG_ENDPOINT_CONFIG,
2385 						CSG_ENDPOINT_CONFIG);
2386 			free_csg_slots &= ~BIT(csg_id);
2387 		}
2388 	}
2389 
2390 	ret = csgs_upd_ctx_apply_locked(ptdev, &upd_ctx);
2391 	if (ret) {
2392 		panthor_device_schedule_reset(ptdev);
2393 		ctx->csg_upd_failed_mask |= upd_ctx.timedout_mask;
2394 		return;
2395 	}
2396 
2397 	for (prio = PANTHOR_CSG_PRIORITY_COUNT - 1; prio >= 0; prio--) {
2398 		list_for_each_entry_safe(group, tmp, &ctx->groups[prio], run_node) {
2399 			list_del_init(&group->run_node);
2400 
2401 			/* If the group has been destroyed while we were
2402 			 * scheduling, ask for an immediate tick to
2403 			 * re-evaluate as soon as possible and get rid of
2404 			 * this dangling group.
2405 			 */
2406 			if (group->destroyed)
2407 				ctx->immediate_tick = true;
2408 			group_put(group);
2409 		}
2410 
2411 		/* Return evicted groups to the idle or run queues. Groups
2412 		 * that can no longer be run (because they've been destroyed
2413 		 * or experienced an unrecoverable error) will be scheduled
2414 		 * for destruction in tick_ctx_cleanup().
2415 		 */
2416 		list_for_each_entry_safe(group, tmp, &ctx->old_groups[prio], run_node) {
2417 			if (!group_can_run(group))
2418 				continue;
2419 
2420 			if (group_is_idle(group))
2421 				list_move_tail(&group->run_node, &sched->groups.idle[prio]);
2422 			else
2423 				list_move_tail(&group->run_node, &sched->groups.runnable[prio]);
2424 			group_put(group);
2425 		}
2426 	}
2427 
2428 	sched->used_csg_slot_count = ctx->group_count;
2429 	sched->might_have_idle_groups = ctx->idle_group_count > 0;
2430 }
2431 
2432 static u64
tick_ctx_update_resched_target(struct panthor_scheduler * sched,const struct panthor_sched_tick_ctx * ctx)2433 tick_ctx_update_resched_target(struct panthor_scheduler *sched,
2434 			       const struct panthor_sched_tick_ctx *ctx)
2435 {
2436 	u64 resched_target;
2437 
2438 	if (ctx->stop_tick)
2439 		goto no_tick;
2440 
2441 	resched_target = sched->last_tick + sched->tick_period;
2442 
2443 	if (time_before64(sched->resched_target, sched->last_tick) ||
2444 	    time_before64(resched_target, sched->resched_target))
2445 		sched->resched_target = resched_target;
2446 
2447 	return sched->resched_target - sched->last_tick;
2448 
2449 no_tick:
2450 	sched->resched_target = U64_MAX;
2451 	return U64_MAX;
2452 }
2453 
tick_work(struct work_struct * work)2454 static void tick_work(struct work_struct *work)
2455 {
2456 	struct panthor_scheduler *sched = container_of(work, struct panthor_scheduler,
2457 						      tick_work.work);
2458 	struct panthor_device *ptdev = sched->ptdev;
2459 	struct panthor_sched_tick_ctx ctx;
2460 	u64 resched_target = sched->resched_target;
2461 	u64 remaining_jiffies = 0, resched_delay;
2462 	u64 now = get_jiffies_64();
2463 	int prio, ret, cookie;
2464 	bool full_tick;
2465 
2466 	if (!drm_dev_enter(&ptdev->base, &cookie))
2467 		return;
2468 
2469 	ret = panthor_device_resume_and_get(ptdev);
2470 	if (drm_WARN_ON(&ptdev->base, ret))
2471 		goto out_dev_exit;
2472 
2473 	/* If the tick is stopped, calculate when the next tick would be */
2474 	if (resched_target == U64_MAX)
2475 		resched_target = sched->last_tick + sched->tick_period;
2476 
2477 	if (time_before64(now, resched_target))
2478 		remaining_jiffies = resched_target - now;
2479 
2480 	full_tick = remaining_jiffies == 0;
2481 
2482 	mutex_lock(&sched->lock);
2483 	if (panthor_device_reset_is_pending(sched->ptdev))
2484 		goto out_unlock;
2485 
2486 	tick_ctx_init(sched, &ctx);
2487 	if (ctx.csg_upd_failed_mask)
2488 		goto out_cleanup_ctx;
2489 
2490 	if (!full_tick) {
2491 		/* Scheduling forced in the middle of a tick. Only RT groups
2492 		 * can preempt non-RT ones. Currently running RT groups can't be
2493 		 * preempted.
2494 		 */
2495 		for (prio = PANTHOR_CSG_PRIORITY_COUNT - 1;
2496 		     prio >= 0 && !tick_ctx_is_full(sched, &ctx);
2497 		     prio--) {
2498 			tick_ctx_pick_groups_from_list(sched, &ctx, &ctx.old_groups[prio],
2499 						       true, true);
2500 			if (prio == PANTHOR_CSG_PRIORITY_RT) {
2501 				tick_ctx_pick_groups_from_list(sched, &ctx,
2502 							       &sched->groups.runnable[prio],
2503 							       true, false);
2504 			}
2505 		}
2506 	}
2507 
2508 	/* First pick non-idle groups */
2509 	for (prio = PANTHOR_CSG_PRIORITY_COUNT - 1;
2510 	     prio >= 0 && !tick_ctx_is_full(sched, &ctx);
2511 	     prio--) {
2512 		struct panthor_group *old_highest_prio_group =
2513 			list_first_entry_or_null(&ctx.old_groups[prio],
2514 						 struct panthor_group, run_node);
2515 
2516 		/* Pull out the group with the highest prio for rotation. */
2517 		if (old_highest_prio_group)
2518 			list_del(&old_highest_prio_group->run_node);
2519 
2520 		/* Re-insert old active groups so they get a chance to run with higher prio. */
2521 		tick_ctx_pick_groups_from_list(sched, &ctx, &ctx.old_groups[prio], true, true);
2522 
2523 		/* Fill the remaining slots with runnable groups. */
2524 		tick_ctx_pick_groups_from_list(sched, &ctx, &sched->groups.runnable[prio],
2525 					       true, false);
2526 
2527 		/* Re-insert the old group with the highest prio, and give it a chance to be
2528 		 * scheduled again (but with a lower prio) if there's room left.
2529 		 */
2530 		if (old_highest_prio_group) {
2531 			list_add_tail(&old_highest_prio_group->run_node, &ctx.old_groups[prio]);
2532 			tick_ctx_pick_groups_from_list(sched, &ctx, &ctx.old_groups[prio],
2533 						       true, true);
2534 		}
2535 	}
2536 
2537 	/* If we have free CSG slots left, pick idle groups */
2538 	for (prio = PANTHOR_CSG_PRIORITY_COUNT - 1;
2539 	     prio >= 0 && !tick_ctx_is_full(sched, &ctx);
2540 	     prio--) {
2541 		/* Check the old_group queue first to avoid reprogramming the slots */
2542 		tick_ctx_pick_groups_from_list(sched, &ctx, &ctx.old_groups[prio], false, true);
2543 		tick_ctx_pick_groups_from_list(sched, &ctx, &sched->groups.idle[prio],
2544 					       false, false);
2545 	}
2546 
2547 	tick_ctx_apply(sched, &ctx);
2548 	if (ctx.csg_upd_failed_mask)
2549 		goto out_cleanup_ctx;
2550 
2551 	if (ctx.idle_group_count == ctx.group_count) {
2552 		panthor_devfreq_record_idle(sched->ptdev);
2553 		if (sched->pm.has_ref) {
2554 			pm_runtime_put_autosuspend(ptdev->base.dev);
2555 			sched->pm.has_ref = false;
2556 		}
2557 	} else {
2558 		panthor_devfreq_record_busy(sched->ptdev);
2559 		if (!sched->pm.has_ref) {
2560 			pm_runtime_get(ptdev->base.dev);
2561 			sched->pm.has_ref = true;
2562 		}
2563 	}
2564 
2565 	sched->last_tick = now;
2566 	resched_delay = tick_ctx_update_resched_target(sched, &ctx);
2567 	if (ctx.immediate_tick)
2568 		resched_delay = 0;
2569 
2570 	if (resched_delay != U64_MAX)
2571 		sched_queue_delayed_work(sched, tick, resched_delay);
2572 
2573 out_cleanup_ctx:
2574 	tick_ctx_cleanup(sched, &ctx);
2575 
2576 out_unlock:
2577 	mutex_unlock(&sched->lock);
2578 	pm_runtime_mark_last_busy(ptdev->base.dev);
2579 	pm_runtime_put_autosuspend(ptdev->base.dev);
2580 
2581 out_dev_exit:
2582 	drm_dev_exit(cookie);
2583 }
2584 
panthor_queue_eval_syncwait(struct panthor_group * group,u8 queue_idx)2585 static int panthor_queue_eval_syncwait(struct panthor_group *group, u8 queue_idx)
2586 {
2587 	struct panthor_queue *queue = group->queues[queue_idx];
2588 	union {
2589 		struct panthor_syncobj_64b sync64;
2590 		struct panthor_syncobj_32b sync32;
2591 	} *syncobj;
2592 	bool result;
2593 	u64 value;
2594 
2595 	syncobj = panthor_queue_get_syncwait_obj(group, queue);
2596 	if (!syncobj)
2597 		return -EINVAL;
2598 
2599 	value = queue->syncwait.sync64 ?
2600 		syncobj->sync64.seqno :
2601 		syncobj->sync32.seqno;
2602 
2603 	if (queue->syncwait.gt)
2604 		result = value > queue->syncwait.ref;
2605 	else
2606 		result = value <= queue->syncwait.ref;
2607 
2608 	if (result)
2609 		panthor_queue_put_syncwait_obj(queue);
2610 
2611 	return result;
2612 }
2613 
sync_upd_work(struct work_struct * work)2614 static void sync_upd_work(struct work_struct *work)
2615 {
2616 	struct panthor_scheduler *sched = container_of(work,
2617 						      struct panthor_scheduler,
2618 						      sync_upd_work);
2619 	struct panthor_group *group, *tmp;
2620 	bool immediate_tick = false;
2621 
2622 	mutex_lock(&sched->lock);
2623 	list_for_each_entry_safe(group, tmp, &sched->groups.waiting, wait_node) {
2624 		u32 tested_queues = group->blocked_queues;
2625 		u32 unblocked_queues = 0;
2626 
2627 		while (tested_queues) {
2628 			u32 cs_id = ffs(tested_queues) - 1;
2629 			int ret;
2630 
2631 			ret = panthor_queue_eval_syncwait(group, cs_id);
2632 			drm_WARN_ON(&group->ptdev->base, ret < 0);
2633 			if (ret)
2634 				unblocked_queues |= BIT(cs_id);
2635 
2636 			tested_queues &= ~BIT(cs_id);
2637 		}
2638 
2639 		if (unblocked_queues) {
2640 			group->blocked_queues &= ~unblocked_queues;
2641 
2642 			if (group->csg_id < 0) {
2643 				list_move(&group->run_node,
2644 					  &sched->groups.runnable[group->priority]);
2645 				if (group->priority == PANTHOR_CSG_PRIORITY_RT)
2646 					immediate_tick = true;
2647 			}
2648 		}
2649 
2650 		if (!group->blocked_queues)
2651 			list_del_init(&group->wait_node);
2652 	}
2653 	mutex_unlock(&sched->lock);
2654 
2655 	if (immediate_tick)
2656 		sched_queue_delayed_work(sched, tick, 0);
2657 }
2658 
sched_resume_tick(struct panthor_device * ptdev)2659 static void sched_resume_tick(struct panthor_device *ptdev)
2660 {
2661 	struct panthor_scheduler *sched = ptdev->scheduler;
2662 	u64 delay_jiffies, now;
2663 
2664 	drm_WARN_ON(&ptdev->base, sched->resched_target != U64_MAX);
2665 
2666 	/* Scheduler tick was off, recalculate the resched_target based on the
2667 	 * last tick event, and queue the scheduler work.
2668 	 */
2669 	now = get_jiffies_64();
2670 	sched->resched_target = sched->last_tick + sched->tick_period;
2671 	if (sched->used_csg_slot_count == sched->csg_slot_count &&
2672 	    time_before64(now, sched->resched_target))
2673 		delay_jiffies = min_t(unsigned long, sched->resched_target - now, ULONG_MAX);
2674 	else
2675 		delay_jiffies = 0;
2676 
2677 	/* We schedule immediate ticks when we need to process events on CSGs,
2678 	 * but those don't change the resched_target because we want the other
2679 	 * groups to stay scheduled for the remaining of the GPU timeslot they
2680 	 * were given. Make sure those immediate ticks don't get overruled by
2681 	 * a sched_queue_delayed_work() that would delay the tick execution.
2682 	 */
2683 	if (!delayed_work_pending(&sched->tick_work))
2684 		sched_queue_delayed_work(sched, tick, delay_jiffies);
2685 }
2686 
group_schedule_locked(struct panthor_group * group,u32 queue_mask)2687 static void group_schedule_locked(struct panthor_group *group, u32 queue_mask)
2688 {
2689 	struct panthor_device *ptdev = group->ptdev;
2690 	struct panthor_scheduler *sched = ptdev->scheduler;
2691 	struct list_head *queue = &sched->groups.runnable[group->priority];
2692 	bool was_idle;
2693 
2694 	if (!group_can_run(group))
2695 		return;
2696 
2697 	/* All updated queues are blocked, no need to wake up the scheduler. */
2698 	if ((queue_mask & group->blocked_queues) == queue_mask)
2699 		return;
2700 
2701 	was_idle = group_is_idle(group);
2702 	group->idle_queues &= ~queue_mask;
2703 
2704 	/* Don't mess up with the lists if we're in a middle of a reset. */
2705 	if (atomic_read(&sched->reset.in_progress))
2706 		return;
2707 
2708 	if (was_idle && !group_is_idle(group))
2709 		list_move_tail(&group->run_node, queue);
2710 
2711 	/* RT groups are preemptive. */
2712 	if (group->priority == PANTHOR_CSG_PRIORITY_RT) {
2713 		sched_queue_delayed_work(sched, tick, 0);
2714 		return;
2715 	}
2716 
2717 	/* Some groups might be idle, force an immediate tick to
2718 	 * re-evaluate.
2719 	 */
2720 	if (sched->might_have_idle_groups) {
2721 		sched_queue_delayed_work(sched, tick, 0);
2722 		return;
2723 	}
2724 
2725 	/* Scheduler is ticking, nothing to do. */
2726 	if (sched->resched_target != U64_MAX) {
2727 		/* If there are free slots, force immediating ticking. */
2728 		if (sched->used_csg_slot_count < sched->csg_slot_count)
2729 			sched_queue_delayed_work(sched, tick, 0);
2730 
2731 		return;
2732 	}
2733 
2734 	/* Scheduler tick was off, recalculate the resched_target based on the
2735 	 * last tick event, and queue the scheduler work.
2736 	 */
2737 	sched_resume_tick(ptdev);
2738 }
2739 
queue_stop(struct panthor_queue * queue,struct panthor_job * bad_job)2740 static void queue_stop(struct panthor_queue *queue,
2741 		       struct panthor_job *bad_job)
2742 {
2743 	disable_delayed_work_sync(&queue->timeout.work);
2744 	drm_sched_stop(&queue->scheduler, bad_job ? &bad_job->base : NULL);
2745 }
2746 
queue_start(struct panthor_queue * queue)2747 static void queue_start(struct panthor_queue *queue)
2748 {
2749 	struct panthor_job *job;
2750 
2751 	/* Re-assign the parent fences. */
2752 	list_for_each_entry(job, &queue->scheduler.pending_list, base.list)
2753 		job->base.s_fence->parent = dma_fence_get(job->done_fence);
2754 
2755 	enable_delayed_work(&queue->timeout.work);
2756 	drm_sched_start(&queue->scheduler, 0);
2757 }
2758 
panthor_group_stop(struct panthor_group * group)2759 static void panthor_group_stop(struct panthor_group *group)
2760 {
2761 	struct panthor_scheduler *sched = group->ptdev->scheduler;
2762 
2763 	lockdep_assert_held(&sched->reset.lock);
2764 
2765 	for (u32 i = 0; i < group->queue_count; i++)
2766 		queue_stop(group->queues[i], NULL);
2767 
2768 	group_get(group);
2769 	list_move_tail(&group->run_node, &sched->reset.stopped_groups);
2770 }
2771 
panthor_group_start(struct panthor_group * group)2772 static void panthor_group_start(struct panthor_group *group)
2773 {
2774 	struct panthor_scheduler *sched = group->ptdev->scheduler;
2775 
2776 	lockdep_assert_held(&group->ptdev->scheduler->reset.lock);
2777 
2778 	for (u32 i = 0; i < group->queue_count; i++)
2779 		queue_start(group->queues[i]);
2780 
2781 	if (group_can_run(group)) {
2782 		list_move_tail(&group->run_node,
2783 			       group_is_idle(group) ?
2784 			       &sched->groups.idle[group->priority] :
2785 			       &sched->groups.runnable[group->priority]);
2786 	} else {
2787 		list_del_init(&group->run_node);
2788 		list_del_init(&group->wait_node);
2789 		group_queue_work(group, term);
2790 	}
2791 
2792 	group_put(group);
2793 }
2794 
2795 /**
2796  * panthor_sched_report_mmu_fault() - Report MMU faults to the scheduler.
2797  * @ptdev: Device.
2798  */
panthor_sched_report_mmu_fault(struct panthor_device * ptdev)2799 void panthor_sched_report_mmu_fault(struct panthor_device *ptdev)
2800 {
2801 	/* Force a tick to immediately kill faulty groups. */
2802 	if (ptdev->scheduler)
2803 		sched_queue_delayed_work(ptdev->scheduler, tick, 0);
2804 }
2805 
panthor_sched_prepare_for_vm_destruction(struct panthor_device * ptdev)2806 void panthor_sched_prepare_for_vm_destruction(struct panthor_device *ptdev)
2807 {
2808 	/* FW can write out internal state, like the heap context, during CSG
2809 	 * suspend. It is therefore important that the scheduler has fully
2810 	 * evicted any pending and related groups before VM destruction can
2811 	 * safely continue. Failure to do so can lead to GPU page faults.
2812 	 * A controlled termination of a Panthor instance involves destroying
2813 	 * the group(s) before the VM. This means any relevant group eviction
2814 	 * has already been initiated by this point, and we just need to
2815 	 * ensure that any pending tick_work() has been completed.
2816 	 */
2817 	flush_work(&ptdev->scheduler->tick_work.work);
2818 }
2819 
panthor_sched_resume(struct panthor_device * ptdev)2820 void panthor_sched_resume(struct panthor_device *ptdev)
2821 {
2822 	/* Force a tick to re-evaluate after a resume. */
2823 	sched_queue_delayed_work(ptdev->scheduler, tick, 0);
2824 }
2825 
panthor_sched_suspend(struct panthor_device * ptdev)2826 void panthor_sched_suspend(struct panthor_device *ptdev)
2827 {
2828 	struct panthor_scheduler *sched = ptdev->scheduler;
2829 	struct panthor_csg_slots_upd_ctx upd_ctx;
2830 	u32 suspended_slots;
2831 	u32 i;
2832 
2833 	mutex_lock(&sched->lock);
2834 	csgs_upd_ctx_init(&upd_ctx);
2835 	for (i = 0; i < sched->csg_slot_count; i++) {
2836 		struct panthor_csg_slot *csg_slot = &sched->csg_slots[i];
2837 
2838 		if (csg_slot->group) {
2839 			csgs_upd_ctx_queue_reqs(ptdev, &upd_ctx, i,
2840 						group_can_run(csg_slot->group) ?
2841 						CSG_STATE_SUSPEND : CSG_STATE_TERMINATE,
2842 						CSG_STATE_MASK);
2843 		}
2844 	}
2845 
2846 	suspended_slots = upd_ctx.update_mask;
2847 
2848 	csgs_upd_ctx_apply_locked(ptdev, &upd_ctx);
2849 	suspended_slots &= ~upd_ctx.timedout_mask;
2850 
2851 	if (upd_ctx.timedout_mask) {
2852 		u32 slot_mask = upd_ctx.timedout_mask;
2853 
2854 		drm_err(&ptdev->base, "CSG suspend failed, escalating to termination");
2855 		csgs_upd_ctx_init(&upd_ctx);
2856 		while (slot_mask) {
2857 			u32 csg_id = ffs(slot_mask) - 1;
2858 			struct panthor_csg_slot *csg_slot = &sched->csg_slots[csg_id];
2859 
2860 			/* If the group was still usable before that point, we consider
2861 			 * it innocent.
2862 			 */
2863 			if (group_can_run(csg_slot->group))
2864 				csg_slot->group->innocent = true;
2865 
2866 			/* We consider group suspension failures as fatal and flag the
2867 			 * group as unusable by setting timedout=true.
2868 			 */
2869 			csg_slot->group->timedout = true;
2870 
2871 			csgs_upd_ctx_queue_reqs(ptdev, &upd_ctx, csg_id,
2872 						CSG_STATE_TERMINATE,
2873 						CSG_STATE_MASK);
2874 			slot_mask &= ~BIT(csg_id);
2875 		}
2876 
2877 		csgs_upd_ctx_apply_locked(ptdev, &upd_ctx);
2878 
2879 		slot_mask = upd_ctx.timedout_mask;
2880 		while (slot_mask) {
2881 			u32 csg_id = ffs(slot_mask) - 1;
2882 			struct panthor_csg_slot *csg_slot = &sched->csg_slots[csg_id];
2883 			struct panthor_group *group = csg_slot->group;
2884 
2885 			/* Terminate command timedout, but the soft-reset will
2886 			 * automatically terminate all active groups, so let's
2887 			 * force the state to halted here.
2888 			 */
2889 			if (group->state != PANTHOR_CS_GROUP_TERMINATED) {
2890 				group->state = PANTHOR_CS_GROUP_TERMINATED;
2891 
2892 				/* Reset the queue slots manually if the termination
2893 				 * request failed.
2894 				 */
2895 				for (i = 0; i < group->queue_count; i++) {
2896 					if (group->queues[i])
2897 						cs_slot_reset_locked(ptdev, csg_id, i);
2898 				}
2899 			}
2900 			slot_mask &= ~BIT(csg_id);
2901 		}
2902 	}
2903 
2904 	/* Flush L2 and LSC caches to make sure suspend state is up-to-date.
2905 	 * If the flush fails, flag all queues for termination.
2906 	 */
2907 	if (suspended_slots) {
2908 		bool flush_caches_failed = false;
2909 		u32 slot_mask = suspended_slots;
2910 
2911 		if (panthor_gpu_flush_caches(ptdev, CACHE_CLEAN, CACHE_CLEAN, 0))
2912 			flush_caches_failed = true;
2913 
2914 		while (slot_mask) {
2915 			u32 csg_id = ffs(slot_mask) - 1;
2916 			struct panthor_csg_slot *csg_slot = &sched->csg_slots[csg_id];
2917 
2918 			if (flush_caches_failed)
2919 				csg_slot->group->state = PANTHOR_CS_GROUP_TERMINATED;
2920 			else
2921 				csg_slot_sync_update_locked(ptdev, csg_id);
2922 
2923 			slot_mask &= ~BIT(csg_id);
2924 		}
2925 	}
2926 
2927 	for (i = 0; i < sched->csg_slot_count; i++) {
2928 		struct panthor_csg_slot *csg_slot = &sched->csg_slots[i];
2929 		struct panthor_group *group = csg_slot->group;
2930 
2931 		if (!group)
2932 			continue;
2933 
2934 		group_get(group);
2935 
2936 		if (group->csg_id >= 0)
2937 			sched_process_csg_irq_locked(ptdev, group->csg_id);
2938 
2939 		group_unbind_locked(group);
2940 
2941 		drm_WARN_ON(&group->ptdev->base, !list_empty(&group->run_node));
2942 
2943 		if (group_can_run(group)) {
2944 			list_add(&group->run_node,
2945 				 &sched->groups.idle[group->priority]);
2946 		} else {
2947 			/* We don't bother stopping the scheduler if the group is
2948 			 * faulty, the group termination work will finish the job.
2949 			 */
2950 			list_del_init(&group->wait_node);
2951 			group_queue_work(group, term);
2952 		}
2953 		group_put(group);
2954 	}
2955 	mutex_unlock(&sched->lock);
2956 }
2957 
panthor_sched_pre_reset(struct panthor_device * ptdev)2958 void panthor_sched_pre_reset(struct panthor_device *ptdev)
2959 {
2960 	struct panthor_scheduler *sched = ptdev->scheduler;
2961 	struct panthor_group *group, *group_tmp;
2962 	u32 i;
2963 
2964 	mutex_lock(&sched->reset.lock);
2965 	atomic_set(&sched->reset.in_progress, true);
2966 
2967 	/* Cancel all scheduler works. Once this is done, these works can't be
2968 	 * scheduled again until the reset operation is complete.
2969 	 */
2970 	cancel_work_sync(&sched->sync_upd_work);
2971 	cancel_delayed_work_sync(&sched->tick_work);
2972 
2973 	panthor_sched_suspend(ptdev);
2974 
2975 	/* Stop all groups that might still accept jobs, so we don't get passed
2976 	 * new jobs while we're resetting.
2977 	 */
2978 	for (i = 0; i < ARRAY_SIZE(sched->groups.runnable); i++) {
2979 		list_for_each_entry_safe(group, group_tmp, &sched->groups.runnable[i], run_node)
2980 			panthor_group_stop(group);
2981 	}
2982 
2983 	for (i = 0; i < ARRAY_SIZE(sched->groups.idle); i++) {
2984 		list_for_each_entry_safe(group, group_tmp, &sched->groups.idle[i], run_node)
2985 			panthor_group_stop(group);
2986 	}
2987 
2988 	mutex_unlock(&sched->reset.lock);
2989 }
2990 
panthor_sched_post_reset(struct panthor_device * ptdev,bool reset_failed)2991 void panthor_sched_post_reset(struct panthor_device *ptdev, bool reset_failed)
2992 {
2993 	struct panthor_scheduler *sched = ptdev->scheduler;
2994 	struct panthor_group *group, *group_tmp;
2995 
2996 	mutex_lock(&sched->reset.lock);
2997 
2998 	list_for_each_entry_safe(group, group_tmp, &sched->reset.stopped_groups, run_node) {
2999 		/* Consider all previously running group as terminated if the
3000 		 * reset failed.
3001 		 */
3002 		if (reset_failed)
3003 			group->state = PANTHOR_CS_GROUP_TERMINATED;
3004 
3005 		panthor_group_start(group);
3006 	}
3007 
3008 	/* We're done resetting the GPU, clear the reset.in_progress bit so we can
3009 	 * kick the scheduler.
3010 	 */
3011 	atomic_set(&sched->reset.in_progress, false);
3012 	mutex_unlock(&sched->reset.lock);
3013 
3014 	/* No need to queue a tick and update syncs if the reset failed. */
3015 	if (!reset_failed) {
3016 		sched_queue_delayed_work(sched, tick, 0);
3017 		sched_queue_work(sched, sync_upd);
3018 	}
3019 }
3020 
update_fdinfo_stats(struct panthor_job * job)3021 static void update_fdinfo_stats(struct panthor_job *job)
3022 {
3023 	struct panthor_group *group = job->group;
3024 	struct panthor_queue *queue = group->queues[job->queue_idx];
3025 	struct panthor_gpu_usage *fdinfo = &group->fdinfo.data;
3026 	struct panthor_job_profiling_data *slots = queue->profiling.slots->kmap;
3027 	struct panthor_job_profiling_data *data = &slots[job->profiling.slot];
3028 
3029 	scoped_guard(spinlock, &group->fdinfo.lock) {
3030 		if (job->profiling.mask & PANTHOR_DEVICE_PROFILING_CYCLES)
3031 			fdinfo->cycles += data->cycles.after - data->cycles.before;
3032 		if (job->profiling.mask & PANTHOR_DEVICE_PROFILING_TIMESTAMP)
3033 			fdinfo->time += data->time.after - data->time.before;
3034 	}
3035 }
3036 
panthor_fdinfo_gather_group_samples(struct panthor_file * pfile)3037 void panthor_fdinfo_gather_group_samples(struct panthor_file *pfile)
3038 {
3039 	struct panthor_group_pool *gpool = pfile->groups;
3040 	struct panthor_group *group;
3041 	unsigned long i;
3042 
3043 	if (IS_ERR_OR_NULL(gpool))
3044 		return;
3045 
3046 	xa_lock(&gpool->xa);
3047 	xa_for_each_marked(&gpool->xa, i, group, GROUP_REGISTERED) {
3048 		guard(spinlock)(&group->fdinfo.lock);
3049 		pfile->stats.cycles += group->fdinfo.data.cycles;
3050 		pfile->stats.time += group->fdinfo.data.time;
3051 		group->fdinfo.data.cycles = 0;
3052 		group->fdinfo.data.time = 0;
3053 	}
3054 	xa_unlock(&gpool->xa);
3055 }
3056 
queue_check_job_completion(struct panthor_queue * queue)3057 static bool queue_check_job_completion(struct panthor_queue *queue)
3058 {
3059 	struct panthor_syncobj_64b *syncobj = NULL;
3060 	struct panthor_job *job, *job_tmp;
3061 	bool cookie, progress = false;
3062 	LIST_HEAD(done_jobs);
3063 
3064 	cookie = dma_fence_begin_signalling();
3065 	scoped_guard(spinlock_irqsave, &queue->fence_ctx.lock) {
3066 		list_for_each_entry_safe(job, job_tmp, &queue->fence_ctx.in_flight_jobs, node) {
3067 			if (!syncobj) {
3068 				struct panthor_group *group = job->group;
3069 
3070 				syncobj = group->syncobjs->kmap +
3071 					  (job->queue_idx * sizeof(*syncobj));
3072 			}
3073 
3074 			if (syncobj->seqno < job->done_fence->seqno)
3075 				break;
3076 
3077 			list_move_tail(&job->node, &done_jobs);
3078 			dma_fence_signal_locked(job->done_fence);
3079 		}
3080 
3081 		if (list_empty(&queue->fence_ctx.in_flight_jobs)) {
3082 			/* If we have no job left, we cancel the timer, and reset remaining
3083 			 * time to its default so it can be restarted next time
3084 			 * queue_resume_timeout() is called.
3085 			 */
3086 			queue_suspend_timeout_locked(queue);
3087 
3088 			/* If there's no job pending, we consider it progress to avoid a
3089 			 * spurious timeout if the timeout handler and the sync update
3090 			 * handler raced.
3091 			 */
3092 			progress = true;
3093 		} else if (!list_empty(&done_jobs)) {
3094 			queue_reset_timeout_locked(queue);
3095 			progress = true;
3096 		}
3097 	}
3098 	dma_fence_end_signalling(cookie);
3099 
3100 	list_for_each_entry_safe(job, job_tmp, &done_jobs, node) {
3101 		if (job->profiling.mask)
3102 			update_fdinfo_stats(job);
3103 		list_del_init(&job->node);
3104 		panthor_job_put(&job->base);
3105 	}
3106 
3107 	return progress;
3108 }
3109 
group_sync_upd_work(struct work_struct * work)3110 static void group_sync_upd_work(struct work_struct *work)
3111 {
3112 	struct panthor_group *group =
3113 		container_of(work, struct panthor_group, sync_upd_work);
3114 	u32 queue_idx;
3115 	bool cookie;
3116 
3117 	cookie = dma_fence_begin_signalling();
3118 	for (queue_idx = 0; queue_idx < group->queue_count; queue_idx++) {
3119 		struct panthor_queue *queue = group->queues[queue_idx];
3120 
3121 		if (!queue)
3122 			continue;
3123 
3124 		queue_check_job_completion(queue);
3125 	}
3126 	dma_fence_end_signalling(cookie);
3127 
3128 	group_put(group);
3129 }
3130 
3131 struct panthor_job_ringbuf_instrs {
3132 	u64 buffer[MAX_INSTRS_PER_JOB];
3133 	u32 count;
3134 };
3135 
3136 struct panthor_job_instr {
3137 	u32 profile_mask;
3138 	u64 instr;
3139 };
3140 
3141 #define JOB_INSTR(__prof, __instr) \
3142 	{ \
3143 		.profile_mask = __prof, \
3144 		.instr = __instr, \
3145 	}
3146 
3147 static void
copy_instrs_to_ringbuf(struct panthor_queue * queue,struct panthor_job * job,struct panthor_job_ringbuf_instrs * instrs)3148 copy_instrs_to_ringbuf(struct panthor_queue *queue,
3149 		       struct panthor_job *job,
3150 		       struct panthor_job_ringbuf_instrs *instrs)
3151 {
3152 	u64 ringbuf_size = panthor_kernel_bo_size(queue->ringbuf);
3153 	u64 start = job->ringbuf.start & (ringbuf_size - 1);
3154 	u64 size, written;
3155 
3156 	/*
3157 	 * We need to write a whole slot, including any trailing zeroes
3158 	 * that may come at the end of it. Also, because instrs.buffer has
3159 	 * been zero-initialised, there's no need to pad it with 0's
3160 	 */
3161 	instrs->count = ALIGN(instrs->count, NUM_INSTRS_PER_CACHE_LINE);
3162 	size = instrs->count * sizeof(u64);
3163 	WARN_ON(size > ringbuf_size);
3164 	written = min(ringbuf_size - start, size);
3165 
3166 	memcpy(queue->ringbuf->kmap + start, instrs->buffer, written);
3167 
3168 	if (written < size)
3169 		memcpy(queue->ringbuf->kmap,
3170 		       &instrs->buffer[written / sizeof(u64)],
3171 		       size - written);
3172 }
3173 
3174 struct panthor_job_cs_params {
3175 	u32 profile_mask;
3176 	u64 addr_reg; u64 val_reg;
3177 	u64 cycle_reg; u64 time_reg;
3178 	u64 sync_addr; u64 times_addr;
3179 	u64 cs_start; u64 cs_size;
3180 	u32 last_flush; u32 waitall_mask;
3181 };
3182 
3183 static void
get_job_cs_params(struct panthor_job * job,struct panthor_job_cs_params * params)3184 get_job_cs_params(struct panthor_job *job, struct panthor_job_cs_params *params)
3185 {
3186 	struct panthor_group *group = job->group;
3187 	struct panthor_queue *queue = group->queues[job->queue_idx];
3188 	struct panthor_device *ptdev = group->ptdev;
3189 	struct panthor_scheduler *sched = ptdev->scheduler;
3190 
3191 	params->addr_reg = ptdev->csif_info.cs_reg_count -
3192 			   ptdev->csif_info.unpreserved_cs_reg_count;
3193 	params->val_reg = params->addr_reg + 2;
3194 	params->cycle_reg = params->addr_reg;
3195 	params->time_reg = params->val_reg;
3196 
3197 	params->sync_addr = panthor_kernel_bo_gpuva(group->syncobjs) +
3198 			    job->queue_idx * sizeof(struct panthor_syncobj_64b);
3199 	params->times_addr = panthor_kernel_bo_gpuva(queue->profiling.slots) +
3200 			     (job->profiling.slot * sizeof(struct panthor_job_profiling_data));
3201 	params->waitall_mask = GENMASK(sched->sb_slot_count - 1, 0);
3202 
3203 	params->cs_start = job->call_info.start;
3204 	params->cs_size = job->call_info.size;
3205 	params->last_flush = job->call_info.latest_flush;
3206 
3207 	params->profile_mask = job->profiling.mask;
3208 }
3209 
3210 #define JOB_INSTR_ALWAYS(instr) \
3211 	JOB_INSTR(PANTHOR_DEVICE_PROFILING_DISABLED, (instr))
3212 #define JOB_INSTR_TIMESTAMP(instr) \
3213 	JOB_INSTR(PANTHOR_DEVICE_PROFILING_TIMESTAMP, (instr))
3214 #define JOB_INSTR_CYCLES(instr) \
3215 	JOB_INSTR(PANTHOR_DEVICE_PROFILING_CYCLES, (instr))
3216 
3217 static void
prepare_job_instrs(const struct panthor_job_cs_params * params,struct panthor_job_ringbuf_instrs * instrs)3218 prepare_job_instrs(const struct panthor_job_cs_params *params,
3219 		   struct panthor_job_ringbuf_instrs *instrs)
3220 {
3221 	const struct panthor_job_instr instr_seq[] = {
3222 		/* MOV32 rX+2, cs.latest_flush */
3223 		JOB_INSTR_ALWAYS((2ull << 56) | (params->val_reg << 48) | params->last_flush),
3224 		/* FLUSH_CACHE2.clean_inv_all.no_wait.signal(0) rX+2 */
3225 		JOB_INSTR_ALWAYS((36ull << 56) | (0ull << 48) | (params->val_reg << 40) |
3226 				 (0 << 16) | 0x233),
3227 		/* MOV48 rX:rX+1, cycles_offset */
3228 		JOB_INSTR_CYCLES((1ull << 56) | (params->cycle_reg << 48) |
3229 				 (params->times_addr +
3230 				  offsetof(struct panthor_job_profiling_data, cycles.before))),
3231 		/* STORE_STATE cycles */
3232 		JOB_INSTR_CYCLES((40ull << 56) | (params->cycle_reg << 40) | (1ll << 32)),
3233 		/* MOV48 rX:rX+1, time_offset */
3234 		JOB_INSTR_TIMESTAMP((1ull << 56) | (params->time_reg << 48) |
3235 				    (params->times_addr +
3236 				     offsetof(struct panthor_job_profiling_data, time.before))),
3237 		/* STORE_STATE timer */
3238 		JOB_INSTR_TIMESTAMP((40ull << 56) | (params->time_reg << 40) | (0ll << 32)),
3239 		/* MOV48 rX:rX+1, cs.start */
3240 		JOB_INSTR_ALWAYS((1ull << 56) | (params->addr_reg << 48) | params->cs_start),
3241 		/* MOV32 rX+2, cs.size */
3242 		JOB_INSTR_ALWAYS((2ull << 56) | (params->val_reg << 48) | params->cs_size),
3243 		/* WAIT(0) => waits for FLUSH_CACHE2 instruction */
3244 		JOB_INSTR_ALWAYS((3ull << 56) | (1 << 16)),
3245 		/* CALL rX:rX+1, rX+2 */
3246 		JOB_INSTR_ALWAYS((32ull << 56) | (params->addr_reg << 40) |
3247 				 (params->val_reg << 32)),
3248 		/* MOV48 rX:rX+1, cycles_offset */
3249 		JOB_INSTR_CYCLES((1ull << 56) | (params->cycle_reg << 48) |
3250 				 (params->times_addr +
3251 				  offsetof(struct panthor_job_profiling_data, cycles.after))),
3252 		/* STORE_STATE cycles */
3253 		JOB_INSTR_CYCLES((40ull << 56) | (params->cycle_reg << 40) | (1ll << 32)),
3254 		/* MOV48 rX:rX+1, time_offset */
3255 		JOB_INSTR_TIMESTAMP((1ull << 56) | (params->time_reg << 48) |
3256 			  (params->times_addr +
3257 			   offsetof(struct panthor_job_profiling_data, time.after))),
3258 		/* STORE_STATE timer */
3259 		JOB_INSTR_TIMESTAMP((40ull << 56) | (params->time_reg << 40) | (0ll << 32)),
3260 		/* MOV48 rX:rX+1, sync_addr */
3261 		JOB_INSTR_ALWAYS((1ull << 56) | (params->addr_reg << 48) | params->sync_addr),
3262 		/* MOV48 rX+2, #1 */
3263 		JOB_INSTR_ALWAYS((1ull << 56) | (params->val_reg << 48) | 1),
3264 		/* WAIT(all) */
3265 		JOB_INSTR_ALWAYS((3ull << 56) | (params->waitall_mask << 16)),
3266 		/* SYNC_ADD64.system_scope.propage_err.nowait rX:rX+1, rX+2*/
3267 		JOB_INSTR_ALWAYS((51ull << 56) | (0ull << 48) | (params->addr_reg << 40) |
3268 				 (params->val_reg << 32) | (0 << 16) | 1),
3269 		/* ERROR_BARRIER, so we can recover from faults at job boundaries. */
3270 		JOB_INSTR_ALWAYS((47ull << 56)),
3271 	};
3272 	u32 pad;
3273 
3274 	instrs->count = 0;
3275 
3276 	/* NEED to be cacheline aligned to please the prefetcher. */
3277 	static_assert(sizeof(instrs->buffer) % 64 == 0,
3278 		      "panthor_job_ringbuf_instrs::buffer is not aligned on a cacheline");
3279 
3280 	/* Make sure we have enough storage to store the whole sequence. */
3281 	static_assert(ALIGN(ARRAY_SIZE(instr_seq), NUM_INSTRS_PER_CACHE_LINE) ==
3282 		      ARRAY_SIZE(instrs->buffer),
3283 		      "instr_seq vs panthor_job_ringbuf_instrs::buffer size mismatch");
3284 
3285 	for (u32 i = 0; i < ARRAY_SIZE(instr_seq); i++) {
3286 		/* If the profile mask of this instruction is not enabled, skip it. */
3287 		if (instr_seq[i].profile_mask &&
3288 		    !(instr_seq[i].profile_mask & params->profile_mask))
3289 			continue;
3290 
3291 		instrs->buffer[instrs->count++] = instr_seq[i].instr;
3292 	}
3293 
3294 	pad = ALIGN(instrs->count, NUM_INSTRS_PER_CACHE_LINE);
3295 	memset(&instrs->buffer[instrs->count], 0,
3296 	       (pad - instrs->count) * sizeof(instrs->buffer[0]));
3297 	instrs->count = pad;
3298 }
3299 
calc_job_credits(u32 profile_mask)3300 static u32 calc_job_credits(u32 profile_mask)
3301 {
3302 	struct panthor_job_ringbuf_instrs instrs;
3303 	struct panthor_job_cs_params params = {
3304 		.profile_mask = profile_mask,
3305 	};
3306 
3307 	prepare_job_instrs(&params, &instrs);
3308 	return instrs.count;
3309 }
3310 
3311 static struct dma_fence *
queue_run_job(struct drm_sched_job * sched_job)3312 queue_run_job(struct drm_sched_job *sched_job)
3313 {
3314 	struct panthor_job *job = container_of(sched_job, struct panthor_job, base);
3315 	struct panthor_group *group = job->group;
3316 	struct panthor_queue *queue = group->queues[job->queue_idx];
3317 	struct panthor_device *ptdev = group->ptdev;
3318 	struct panthor_scheduler *sched = ptdev->scheduler;
3319 	struct panthor_job_ringbuf_instrs instrs;
3320 	struct panthor_job_cs_params cs_params;
3321 	struct dma_fence *done_fence;
3322 	int ret;
3323 
3324 	/* Stream size is zero, nothing to do except making sure all previously
3325 	 * submitted jobs are done before we signal the
3326 	 * drm_sched_job::s_fence::finished fence.
3327 	 */
3328 	if (!job->call_info.size) {
3329 		job->done_fence = dma_fence_get(queue->fence_ctx.last_fence);
3330 		return dma_fence_get(job->done_fence);
3331 	}
3332 
3333 	ret = panthor_device_resume_and_get(ptdev);
3334 	if (drm_WARN_ON(&ptdev->base, ret))
3335 		return ERR_PTR(ret);
3336 
3337 	mutex_lock(&sched->lock);
3338 	if (!group_can_run(group)) {
3339 		done_fence = ERR_PTR(-ECANCELED);
3340 		goto out_unlock;
3341 	}
3342 
3343 	dma_fence_init(job->done_fence,
3344 		       &panthor_queue_fence_ops,
3345 		       &queue->fence_ctx.lock,
3346 		       queue->fence_ctx.id,
3347 		       atomic64_inc_return(&queue->fence_ctx.seqno));
3348 
3349 	job->profiling.slot = queue->profiling.seqno++;
3350 	if (queue->profiling.seqno == queue->profiling.slot_count)
3351 		queue->profiling.seqno = 0;
3352 
3353 	job->ringbuf.start = queue->iface.input->insert;
3354 
3355 	get_job_cs_params(job, &cs_params);
3356 	prepare_job_instrs(&cs_params, &instrs);
3357 	copy_instrs_to_ringbuf(queue, job, &instrs);
3358 
3359 	job->ringbuf.end = job->ringbuf.start + (instrs.count * sizeof(u64));
3360 
3361 	panthor_job_get(&job->base);
3362 	scoped_guard(spinlock_irqsave, &queue->fence_ctx.lock)
3363 		list_add_tail(&job->node, &queue->fence_ctx.in_flight_jobs);
3364 
3365 	/* Make sure the ring buffer is updated before the INSERT
3366 	 * register.
3367 	 */
3368 	wmb();
3369 
3370 	queue->iface.input->extract = queue->iface.output->extract;
3371 	queue->iface.input->insert = job->ringbuf.end;
3372 
3373 	if (group->csg_id < 0) {
3374 		group_schedule_locked(group, BIT(job->queue_idx));
3375 	} else {
3376 		u32 queue_mask = BIT(job->queue_idx);
3377 		bool resume_tick = group_is_idle(group) &&
3378 				   (group->idle_queues & queue_mask) &&
3379 				   !(group->blocked_queues & queue_mask) &&
3380 				   sched->resched_target == U64_MAX;
3381 
3382 		/* We just added something to the queue, so it's no longer idle. */
3383 		group->idle_queues &= ~queue_mask;
3384 
3385 		if (resume_tick)
3386 			sched_resume_tick(ptdev);
3387 
3388 		panthor_fw_ring_doorbell(ptdev, queue->doorbell_id);
3389 		if (!sched->pm.has_ref &&
3390 		    !(group->blocked_queues & BIT(job->queue_idx))) {
3391 			pm_runtime_get(ptdev->base.dev);
3392 			sched->pm.has_ref = true;
3393 		}
3394 		queue_resume_timeout(queue);
3395 		panthor_devfreq_record_busy(sched->ptdev);
3396 	}
3397 
3398 	/* Update the last fence. */
3399 	dma_fence_put(queue->fence_ctx.last_fence);
3400 	queue->fence_ctx.last_fence = dma_fence_get(job->done_fence);
3401 
3402 	done_fence = dma_fence_get(job->done_fence);
3403 
3404 out_unlock:
3405 	mutex_unlock(&sched->lock);
3406 	pm_runtime_mark_last_busy(ptdev->base.dev);
3407 	pm_runtime_put_autosuspend(ptdev->base.dev);
3408 
3409 	return done_fence;
3410 }
3411 
3412 static enum drm_gpu_sched_stat
queue_timedout_job(struct drm_sched_job * sched_job)3413 queue_timedout_job(struct drm_sched_job *sched_job)
3414 {
3415 	struct panthor_job *job = container_of(sched_job, struct panthor_job, base);
3416 	struct panthor_group *group = job->group;
3417 	struct panthor_device *ptdev = group->ptdev;
3418 	struct panthor_scheduler *sched = ptdev->scheduler;
3419 	struct panthor_queue *queue = group->queues[job->queue_idx];
3420 
3421 	drm_warn(&ptdev->base, "job timeout: pid=%d, comm=%s, seqno=%llu\n",
3422 		 group->task_info.pid, group->task_info.comm, job->done_fence->seqno);
3423 
3424 	drm_WARN_ON(&ptdev->base, atomic_read(&sched->reset.in_progress));
3425 
3426 	queue_stop(queue, job);
3427 
3428 	mutex_lock(&sched->lock);
3429 	group->timedout = true;
3430 	if (group->csg_id >= 0) {
3431 		sched_queue_delayed_work(ptdev->scheduler, tick, 0);
3432 	} else {
3433 		/* Remove from the run queues, so the scheduler can't
3434 		 * pick the group on the next tick.
3435 		 */
3436 		list_del_init(&group->run_node);
3437 		list_del_init(&group->wait_node);
3438 
3439 		group_queue_work(group, term);
3440 	}
3441 	mutex_unlock(&sched->lock);
3442 
3443 	queue_start(queue);
3444 	return DRM_GPU_SCHED_STAT_RESET;
3445 }
3446 
queue_free_job(struct drm_sched_job * sched_job)3447 static void queue_free_job(struct drm_sched_job *sched_job)
3448 {
3449 	panthor_job_put(sched_job);
3450 }
3451 
3452 static const struct drm_sched_backend_ops panthor_queue_sched_ops = {
3453 	.run_job = queue_run_job,
3454 	.timedout_job = queue_timedout_job,
3455 	.free_job = queue_free_job,
3456 };
3457 
calc_profiling_ringbuf_num_slots(struct panthor_device * ptdev,u32 cs_ringbuf_size)3458 static u32 calc_profiling_ringbuf_num_slots(struct panthor_device *ptdev,
3459 					    u32 cs_ringbuf_size)
3460 {
3461 	u32 min_profiled_job_instrs = U32_MAX;
3462 	u32 last_flag = fls(PANTHOR_DEVICE_PROFILING_ALL);
3463 
3464 	/*
3465 	 * We want to calculate the minimum size of a profiled job's CS,
3466 	 * because since they need additional instructions for the sampling
3467 	 * of performance metrics, they might take up further slots in
3468 	 * the queue's ringbuffer. This means we might not need as many job
3469 	 * slots for keeping track of their profiling information. What we
3470 	 * need is the maximum number of slots we should allocate to this end,
3471 	 * which matches the maximum number of profiled jobs we can place
3472 	 * simultaneously in the queue's ring buffer.
3473 	 * That has to be calculated separately for every single job profiling
3474 	 * flag, but not in the case job profiling is disabled, since unprofiled
3475 	 * jobs don't need to keep track of this at all.
3476 	 */
3477 	for (u32 i = 0; i < last_flag; i++) {
3478 		min_profiled_job_instrs =
3479 			min(min_profiled_job_instrs, calc_job_credits(BIT(i)));
3480 	}
3481 
3482 	return DIV_ROUND_UP(cs_ringbuf_size, min_profiled_job_instrs * sizeof(u64));
3483 }
3484 
queue_timeout_work(struct work_struct * work)3485 static void queue_timeout_work(struct work_struct *work)
3486 {
3487 	struct panthor_queue *queue = container_of(work, struct panthor_queue,
3488 						   timeout.work.work);
3489 	bool progress;
3490 
3491 	progress = queue_check_job_completion(queue);
3492 	if (!progress)
3493 		drm_sched_fault(&queue->scheduler);
3494 }
3495 
3496 static struct panthor_queue *
group_create_queue(struct panthor_group * group,const struct drm_panthor_queue_create * args,u64 drm_client_id,u32 gid,u32 qid)3497 group_create_queue(struct panthor_group *group,
3498 		   const struct drm_panthor_queue_create *args,
3499 		   u64 drm_client_id, u32 gid, u32 qid)
3500 {
3501 	struct drm_sched_init_args sched_args = {
3502 		.ops = &panthor_queue_sched_ops,
3503 		.submit_wq = group->ptdev->scheduler->wq,
3504 		.num_rqs = 1,
3505 		/*
3506 		 * The credit limit argument tells us the total number of
3507 		 * instructions across all CS slots in the ringbuffer, with
3508 		 * some jobs requiring twice as many as others, depending on
3509 		 * their profiling status.
3510 		 */
3511 		.credit_limit = args->ringbuf_size / sizeof(u64),
3512 		.timeout = MAX_SCHEDULE_TIMEOUT,
3513 		.timeout_wq = group->ptdev->reset.wq,
3514 		.dev = group->ptdev->base.dev,
3515 	};
3516 	struct drm_gpu_scheduler *drm_sched;
3517 	struct panthor_queue *queue;
3518 	int ret;
3519 
3520 	if (args->pad[0] || args->pad[1] || args->pad[2])
3521 		return ERR_PTR(-EINVAL);
3522 
3523 	if (args->ringbuf_size < SZ_4K || args->ringbuf_size > SZ_64K ||
3524 	    !is_power_of_2(args->ringbuf_size))
3525 		return ERR_PTR(-EINVAL);
3526 
3527 	if (args->priority > CSF_MAX_QUEUE_PRIO)
3528 		return ERR_PTR(-EINVAL);
3529 
3530 	queue = kzalloc_obj(*queue);
3531 	if (!queue)
3532 		return ERR_PTR(-ENOMEM);
3533 
3534 	queue->timeout.remaining = msecs_to_jiffies(JOB_TIMEOUT_MS);
3535 	INIT_DELAYED_WORK(&queue->timeout.work, queue_timeout_work);
3536 	queue->fence_ctx.id = dma_fence_context_alloc(1);
3537 	spin_lock_init(&queue->fence_ctx.lock);
3538 	INIT_LIST_HEAD(&queue->fence_ctx.in_flight_jobs);
3539 
3540 	queue->priority = args->priority;
3541 
3542 	queue->ringbuf = panthor_kernel_bo_create(group->ptdev, group->vm,
3543 						  args->ringbuf_size,
3544 						  DRM_PANTHOR_BO_NO_MMAP,
3545 						  DRM_PANTHOR_VM_BIND_OP_MAP_NOEXEC |
3546 						  DRM_PANTHOR_VM_BIND_OP_MAP_UNCACHED,
3547 						  PANTHOR_VM_KERNEL_AUTO_VA,
3548 						  "CS ring buffer");
3549 	if (IS_ERR(queue->ringbuf)) {
3550 		ret = PTR_ERR(queue->ringbuf);
3551 		goto err_free_queue;
3552 	}
3553 
3554 	ret = panthor_kernel_bo_vmap(queue->ringbuf);
3555 	if (ret)
3556 		goto err_free_queue;
3557 
3558 	queue->iface.mem = panthor_fw_alloc_queue_iface_mem(group->ptdev,
3559 							    &queue->iface.input,
3560 							    &queue->iface.output,
3561 							    &queue->iface.input_fw_va,
3562 							    &queue->iface.output_fw_va);
3563 	if (IS_ERR(queue->iface.mem)) {
3564 		ret = PTR_ERR(queue->iface.mem);
3565 		goto err_free_queue;
3566 	}
3567 
3568 	queue->profiling.slot_count =
3569 		calc_profiling_ringbuf_num_slots(group->ptdev, args->ringbuf_size);
3570 
3571 	queue->profiling.slots =
3572 		panthor_kernel_bo_create(group->ptdev, group->vm,
3573 					 queue->profiling.slot_count *
3574 					 sizeof(struct panthor_job_profiling_data),
3575 					 DRM_PANTHOR_BO_NO_MMAP,
3576 					 DRM_PANTHOR_VM_BIND_OP_MAP_NOEXEC |
3577 					 DRM_PANTHOR_VM_BIND_OP_MAP_UNCACHED,
3578 					 PANTHOR_VM_KERNEL_AUTO_VA,
3579 					 "Group job stats");
3580 
3581 	if (IS_ERR(queue->profiling.slots)) {
3582 		ret = PTR_ERR(queue->profiling.slots);
3583 		goto err_free_queue;
3584 	}
3585 
3586 	ret = panthor_kernel_bo_vmap(queue->profiling.slots);
3587 	if (ret)
3588 		goto err_free_queue;
3589 
3590 	/* assign a unique name */
3591 	queue->name = kasprintf(GFP_KERNEL, "panthor-queue-%llu-%u-%u", drm_client_id, gid, qid);
3592 	if (!queue->name) {
3593 		ret = -ENOMEM;
3594 		goto err_free_queue;
3595 	}
3596 
3597 	sched_args.name = queue->name;
3598 
3599 	ret = drm_sched_init(&queue->scheduler, &sched_args);
3600 	if (ret)
3601 		goto err_free_queue;
3602 
3603 	drm_sched = &queue->scheduler;
3604 	ret = drm_sched_entity_init(&queue->entity, 0, &drm_sched, 1, NULL);
3605 	if (ret)
3606 		goto err_free_queue;
3607 
3608 	return queue;
3609 
3610 err_free_queue:
3611 	group_free_queue(group, queue);
3612 	return ERR_PTR(ret);
3613 }
3614 
group_init_task_info(struct panthor_group * group)3615 static void group_init_task_info(struct panthor_group *group)
3616 {
3617 	struct task_struct *task = current->group_leader;
3618 
3619 	group->task_info.pid = task->pid;
3620 	get_task_comm(group->task_info.comm, task);
3621 }
3622 
add_group_kbo_sizes(struct panthor_device * ptdev,struct panthor_group * group)3623 static void add_group_kbo_sizes(struct panthor_device *ptdev,
3624 				struct panthor_group *group)
3625 {
3626 	struct panthor_queue *queue;
3627 	int i;
3628 
3629 	if (drm_WARN_ON(&ptdev->base, IS_ERR_OR_NULL(group)))
3630 		return;
3631 	if (drm_WARN_ON(&ptdev->base, ptdev != group->ptdev))
3632 		return;
3633 
3634 	group->fdinfo.kbo_sizes += group->suspend_buf->obj->size;
3635 	group->fdinfo.kbo_sizes += group->protm_suspend_buf->obj->size;
3636 	group->fdinfo.kbo_sizes += group->syncobjs->obj->size;
3637 
3638 	for (i = 0; i < group->queue_count; i++) {
3639 		queue =	group->queues[i];
3640 		group->fdinfo.kbo_sizes += queue->ringbuf->obj->size;
3641 		group->fdinfo.kbo_sizes += queue->iface.mem->obj->size;
3642 		group->fdinfo.kbo_sizes += queue->profiling.slots->obj->size;
3643 	}
3644 }
3645 
3646 #define MAX_GROUPS_PER_POOL		128
3647 
panthor_group_create(struct panthor_file * pfile,const struct drm_panthor_group_create * group_args,const struct drm_panthor_queue_create * queue_args,u64 drm_client_id)3648 int panthor_group_create(struct panthor_file *pfile,
3649 			 const struct drm_panthor_group_create *group_args,
3650 			 const struct drm_panthor_queue_create *queue_args,
3651 			 u64 drm_client_id)
3652 {
3653 	struct panthor_device *ptdev = pfile->ptdev;
3654 	struct panthor_group_pool *gpool = pfile->groups;
3655 	struct panthor_scheduler *sched = ptdev->scheduler;
3656 	struct panthor_fw_csg_iface *csg_iface = panthor_fw_get_csg_iface(ptdev, 0);
3657 	struct panthor_group *group = NULL;
3658 	u32 gid, i, suspend_size;
3659 	int ret;
3660 
3661 	if (group_args->pad)
3662 		return -EINVAL;
3663 
3664 	if (group_args->priority >= PANTHOR_CSG_PRIORITY_COUNT)
3665 		return -EINVAL;
3666 
3667 	if ((group_args->compute_core_mask & ~ptdev->gpu_info.shader_present) ||
3668 	    (group_args->fragment_core_mask & ~ptdev->gpu_info.shader_present) ||
3669 	    (group_args->tiler_core_mask & ~ptdev->gpu_info.tiler_present))
3670 		return -EINVAL;
3671 
3672 	if (hweight64(group_args->compute_core_mask) < group_args->max_compute_cores ||
3673 	    hweight64(group_args->fragment_core_mask) < group_args->max_fragment_cores ||
3674 	    hweight64(group_args->tiler_core_mask) < group_args->max_tiler_cores)
3675 		return -EINVAL;
3676 
3677 	group = kzalloc_obj(*group);
3678 	if (!group)
3679 		return -ENOMEM;
3680 
3681 	spin_lock_init(&group->fatal_lock);
3682 	kref_init(&group->refcount);
3683 	group->state = PANTHOR_CS_GROUP_CREATED;
3684 	group->csg_id = -1;
3685 
3686 	group->ptdev = ptdev;
3687 	group->max_compute_cores = group_args->max_compute_cores;
3688 	group->compute_core_mask = group_args->compute_core_mask;
3689 	group->max_fragment_cores = group_args->max_fragment_cores;
3690 	group->fragment_core_mask = group_args->fragment_core_mask;
3691 	group->max_tiler_cores = group_args->max_tiler_cores;
3692 	group->tiler_core_mask = group_args->tiler_core_mask;
3693 	group->priority = group_args->priority;
3694 
3695 	INIT_LIST_HEAD(&group->wait_node);
3696 	INIT_LIST_HEAD(&group->run_node);
3697 	INIT_WORK(&group->term_work, group_term_work);
3698 	INIT_WORK(&group->sync_upd_work, group_sync_upd_work);
3699 	INIT_WORK(&group->tiler_oom_work, group_tiler_oom_work);
3700 	INIT_WORK(&group->release_work, group_release_work);
3701 
3702 	group->vm = panthor_vm_pool_get_vm(pfile->vms, group_args->vm_id);
3703 	if (!group->vm) {
3704 		ret = -EINVAL;
3705 		goto err_put_group;
3706 	}
3707 
3708 	suspend_size = csg_iface->control->suspend_size;
3709 	group->suspend_buf = panthor_fw_alloc_suspend_buf_mem(ptdev, suspend_size);
3710 	if (IS_ERR(group->suspend_buf)) {
3711 		ret = PTR_ERR(group->suspend_buf);
3712 		group->suspend_buf = NULL;
3713 		goto err_put_group;
3714 	}
3715 
3716 	suspend_size = csg_iface->control->protm_suspend_size;
3717 	group->protm_suspend_buf = panthor_fw_alloc_suspend_buf_mem(ptdev, suspend_size);
3718 	if (IS_ERR(group->protm_suspend_buf)) {
3719 		ret = PTR_ERR(group->protm_suspend_buf);
3720 		group->protm_suspend_buf = NULL;
3721 		goto err_put_group;
3722 	}
3723 
3724 	group->syncobjs = panthor_kernel_bo_create(ptdev, group->vm,
3725 						   group_args->queues.count *
3726 						   sizeof(struct panthor_syncobj_64b),
3727 						   DRM_PANTHOR_BO_NO_MMAP,
3728 						   DRM_PANTHOR_VM_BIND_OP_MAP_NOEXEC |
3729 						   DRM_PANTHOR_VM_BIND_OP_MAP_UNCACHED,
3730 						   PANTHOR_VM_KERNEL_AUTO_VA,
3731 						   "Group sync objects");
3732 	if (IS_ERR(group->syncobjs)) {
3733 		ret = PTR_ERR(group->syncobjs);
3734 		goto err_put_group;
3735 	}
3736 
3737 	ret = panthor_kernel_bo_vmap(group->syncobjs);
3738 	if (ret)
3739 		goto err_put_group;
3740 
3741 	memset(group->syncobjs->kmap, 0,
3742 	       group_args->queues.count * sizeof(struct panthor_syncobj_64b));
3743 
3744 	ret = xa_alloc(&gpool->xa, &gid, group, XA_LIMIT(1, MAX_GROUPS_PER_POOL), GFP_KERNEL);
3745 	if (ret)
3746 		goto err_put_group;
3747 
3748 	for (i = 0; i < group_args->queues.count; i++) {
3749 		group->queues[i] = group_create_queue(group, &queue_args[i], drm_client_id, gid, i);
3750 		if (IS_ERR(group->queues[i])) {
3751 			ret = PTR_ERR(group->queues[i]);
3752 			group->queues[i] = NULL;
3753 			goto err_erase_gid;
3754 		}
3755 
3756 		group->queue_count++;
3757 	}
3758 
3759 	group->idle_queues = GENMASK(group->queue_count - 1, 0);
3760 
3761 	mutex_lock(&sched->reset.lock);
3762 	if (atomic_read(&sched->reset.in_progress)) {
3763 		panthor_group_stop(group);
3764 	} else {
3765 		mutex_lock(&sched->lock);
3766 		list_add_tail(&group->run_node,
3767 			      &sched->groups.idle[group->priority]);
3768 		mutex_unlock(&sched->lock);
3769 	}
3770 	mutex_unlock(&sched->reset.lock);
3771 
3772 	add_group_kbo_sizes(group->ptdev, group);
3773 	spin_lock_init(&group->fdinfo.lock);
3774 
3775 	group_init_task_info(group);
3776 
3777 	xa_set_mark(&gpool->xa, gid, GROUP_REGISTERED);
3778 
3779 	return gid;
3780 
3781 err_erase_gid:
3782 	xa_erase(&gpool->xa, gid);
3783 
3784 err_put_group:
3785 	group_put(group);
3786 	return ret;
3787 }
3788 
panthor_group_destroy(struct panthor_file * pfile,u32 group_handle)3789 int panthor_group_destroy(struct panthor_file *pfile, u32 group_handle)
3790 {
3791 	struct panthor_group_pool *gpool = pfile->groups;
3792 	struct panthor_device *ptdev = pfile->ptdev;
3793 	struct panthor_scheduler *sched = ptdev->scheduler;
3794 	struct panthor_group *group;
3795 
3796 	if (!xa_get_mark(&gpool->xa, group_handle, GROUP_REGISTERED))
3797 		return -EINVAL;
3798 
3799 	group = xa_erase(&gpool->xa, group_handle);
3800 	if (!group)
3801 		return -EINVAL;
3802 
3803 	mutex_lock(&sched->reset.lock);
3804 	mutex_lock(&sched->lock);
3805 	group->destroyed = true;
3806 	if (group->csg_id >= 0) {
3807 		sched_queue_delayed_work(sched, tick, 0);
3808 	} else if (!atomic_read(&sched->reset.in_progress)) {
3809 		/* Remove from the run queues, so the scheduler can't
3810 		 * pick the group on the next tick.
3811 		 */
3812 		list_del_init(&group->run_node);
3813 		list_del_init(&group->wait_node);
3814 		group_queue_work(group, term);
3815 	}
3816 	mutex_unlock(&sched->lock);
3817 	mutex_unlock(&sched->reset.lock);
3818 
3819 	group_put(group);
3820 	return 0;
3821 }
3822 
group_from_handle(struct panthor_group_pool * pool,unsigned long group_handle)3823 static struct panthor_group *group_from_handle(struct panthor_group_pool *pool,
3824 					       unsigned long group_handle)
3825 {
3826 	struct panthor_group *group;
3827 
3828 	xa_lock(&pool->xa);
3829 	group = group_get(xa_find(&pool->xa, &group_handle, group_handle, GROUP_REGISTERED));
3830 	xa_unlock(&pool->xa);
3831 
3832 	return group;
3833 }
3834 
panthor_group_get_state(struct panthor_file * pfile,struct drm_panthor_group_get_state * get_state)3835 int panthor_group_get_state(struct panthor_file *pfile,
3836 			    struct drm_panthor_group_get_state *get_state)
3837 {
3838 	struct panthor_group_pool *gpool = pfile->groups;
3839 	struct panthor_device *ptdev = pfile->ptdev;
3840 	struct panthor_scheduler *sched = ptdev->scheduler;
3841 	struct panthor_group *group;
3842 
3843 	if (get_state->pad)
3844 		return -EINVAL;
3845 
3846 	group = group_from_handle(gpool, get_state->group_handle);
3847 	if (!group)
3848 		return -EINVAL;
3849 
3850 	memset(get_state, 0, sizeof(*get_state));
3851 
3852 	mutex_lock(&sched->lock);
3853 	if (group->timedout)
3854 		get_state->state |= DRM_PANTHOR_GROUP_STATE_TIMEDOUT;
3855 	if (group->fatal_queues) {
3856 		get_state->state |= DRM_PANTHOR_GROUP_STATE_FATAL_FAULT;
3857 		get_state->fatal_queues = group->fatal_queues;
3858 	}
3859 	if (group->innocent)
3860 		get_state->state |= DRM_PANTHOR_GROUP_STATE_INNOCENT;
3861 	mutex_unlock(&sched->lock);
3862 
3863 	group_put(group);
3864 	return 0;
3865 }
3866 
panthor_group_pool_create(struct panthor_file * pfile)3867 int panthor_group_pool_create(struct panthor_file *pfile)
3868 {
3869 	struct panthor_group_pool *gpool;
3870 
3871 	gpool = kzalloc_obj(*gpool);
3872 	if (!gpool)
3873 		return -ENOMEM;
3874 
3875 	xa_init_flags(&gpool->xa, XA_FLAGS_ALLOC1);
3876 	pfile->groups = gpool;
3877 	return 0;
3878 }
3879 
panthor_group_pool_destroy(struct panthor_file * pfile)3880 void panthor_group_pool_destroy(struct panthor_file *pfile)
3881 {
3882 	struct panthor_group_pool *gpool = pfile->groups;
3883 	struct panthor_group *group;
3884 	unsigned long i;
3885 
3886 	if (IS_ERR_OR_NULL(gpool))
3887 		return;
3888 
3889 	xa_for_each(&gpool->xa, i, group)
3890 		panthor_group_destroy(pfile, i);
3891 
3892 	xa_destroy(&gpool->xa);
3893 	kfree(gpool);
3894 	pfile->groups = NULL;
3895 }
3896 
3897 /**
3898  * panthor_fdinfo_gather_group_mem_info() - Retrieve aggregate size of all private kernel BO's
3899  * belonging to all the groups owned by an open Panthor file
3900  * @pfile: File.
3901  * @stats: Memory statistics to be updated.
3902  *
3903  */
3904 void
panthor_fdinfo_gather_group_mem_info(struct panthor_file * pfile,struct drm_memory_stats * stats)3905 panthor_fdinfo_gather_group_mem_info(struct panthor_file *pfile,
3906 				     struct drm_memory_stats *stats)
3907 {
3908 	struct panthor_group_pool *gpool = pfile->groups;
3909 	struct panthor_group *group;
3910 	unsigned long i;
3911 
3912 	if (IS_ERR_OR_NULL(gpool))
3913 		return;
3914 
3915 	xa_lock(&gpool->xa);
3916 	xa_for_each_marked(&gpool->xa, i, group, GROUP_REGISTERED) {
3917 		stats->resident += group->fdinfo.kbo_sizes;
3918 		if (group->csg_id >= 0)
3919 			stats->active += group->fdinfo.kbo_sizes;
3920 	}
3921 	xa_unlock(&gpool->xa);
3922 }
3923 
job_release(struct kref * ref)3924 static void job_release(struct kref *ref)
3925 {
3926 	struct panthor_job *job = container_of(ref, struct panthor_job, refcount);
3927 
3928 	drm_WARN_ON(&job->group->ptdev->base, !list_empty(&job->node));
3929 
3930 	if (job->base.s_fence)
3931 		drm_sched_job_cleanup(&job->base);
3932 
3933 	if (dma_fence_was_initialized(job->done_fence))
3934 		dma_fence_put(job->done_fence);
3935 	else
3936 		dma_fence_free(job->done_fence);
3937 
3938 	group_put(job->group);
3939 
3940 	kfree(job);
3941 }
3942 
panthor_job_get(struct drm_sched_job * sched_job)3943 struct drm_sched_job *panthor_job_get(struct drm_sched_job *sched_job)
3944 {
3945 	if (sched_job) {
3946 		struct panthor_job *job = container_of(sched_job, struct panthor_job, base);
3947 
3948 		kref_get(&job->refcount);
3949 	}
3950 
3951 	return sched_job;
3952 }
3953 
panthor_job_put(struct drm_sched_job * sched_job)3954 void panthor_job_put(struct drm_sched_job *sched_job)
3955 {
3956 	struct panthor_job *job = container_of(sched_job, struct panthor_job, base);
3957 
3958 	if (sched_job)
3959 		kref_put(&job->refcount, job_release);
3960 }
3961 
panthor_job_vm(struct drm_sched_job * sched_job)3962 struct panthor_vm *panthor_job_vm(struct drm_sched_job *sched_job)
3963 {
3964 	struct panthor_job *job = container_of(sched_job, struct panthor_job, base);
3965 
3966 	return job->group->vm;
3967 }
3968 
3969 struct drm_sched_job *
panthor_job_create(struct panthor_file * pfile,u16 group_handle,const struct drm_panthor_queue_submit * qsubmit,u64 drm_client_id)3970 panthor_job_create(struct panthor_file *pfile,
3971 		   u16 group_handle,
3972 		   const struct drm_panthor_queue_submit *qsubmit,
3973 		   u64 drm_client_id)
3974 {
3975 	struct panthor_group_pool *gpool = pfile->groups;
3976 	struct panthor_job *job;
3977 	u32 credits;
3978 	int ret;
3979 
3980 	if (qsubmit->pad)
3981 		return ERR_PTR(-EINVAL);
3982 
3983 	/* If stream_addr is zero, so stream_size should be. */
3984 	if ((qsubmit->stream_size == 0) != (qsubmit->stream_addr == 0))
3985 		return ERR_PTR(-EINVAL);
3986 
3987 	/* Make sure the address is aligned on 64-byte (cacheline) and the size is
3988 	 * aligned on 8-byte (instruction size).
3989 	 */
3990 	if ((qsubmit->stream_addr & 63) || (qsubmit->stream_size & 7))
3991 		return ERR_PTR(-EINVAL);
3992 
3993 	/* bits 24:30 must be zero. */
3994 	if (qsubmit->latest_flush & GENMASK(30, 24))
3995 		return ERR_PTR(-EINVAL);
3996 
3997 	job = kzalloc_obj(*job);
3998 	if (!job)
3999 		return ERR_PTR(-ENOMEM);
4000 
4001 	kref_init(&job->refcount);
4002 	job->queue_idx = qsubmit->queue_index;
4003 	job->call_info.size = qsubmit->stream_size;
4004 	job->call_info.start = qsubmit->stream_addr;
4005 	job->call_info.latest_flush = qsubmit->latest_flush;
4006 	INIT_LIST_HEAD(&job->node);
4007 
4008 	job->group = group_from_handle(gpool, group_handle);
4009 	if (!job->group) {
4010 		ret = -EINVAL;
4011 		goto err_put_job;
4012 	}
4013 
4014 	if (!group_can_run(job->group)) {
4015 		ret = -EINVAL;
4016 		goto err_put_job;
4017 	}
4018 
4019 	if (job->queue_idx >= job->group->queue_count ||
4020 	    !job->group->queues[job->queue_idx]) {
4021 		ret = -EINVAL;
4022 		goto err_put_job;
4023 	}
4024 
4025 	/* Empty command streams don't need a fence, they'll pick the one from
4026 	 * the previously submitted job.
4027 	 */
4028 	if (job->call_info.size) {
4029 		job->done_fence = kzalloc_obj(*job->done_fence);
4030 		if (!job->done_fence) {
4031 			ret = -ENOMEM;
4032 			goto err_put_job;
4033 		}
4034 	}
4035 
4036 	job->profiling.mask = pfile->ptdev->profile_mask;
4037 	credits = calc_job_credits(job->profiling.mask);
4038 	if (credits == 0) {
4039 		ret = -EINVAL;
4040 		goto err_put_job;
4041 	}
4042 
4043 	ret = drm_sched_job_init(&job->base,
4044 				 &job->group->queues[job->queue_idx]->entity,
4045 				 credits, job->group, drm_client_id);
4046 	if (ret)
4047 		goto err_put_job;
4048 
4049 	return &job->base;
4050 
4051 err_put_job:
4052 	panthor_job_put(&job->base);
4053 	return ERR_PTR(ret);
4054 }
4055 
panthor_job_update_resvs(struct drm_exec * exec,struct drm_sched_job * sched_job)4056 void panthor_job_update_resvs(struct drm_exec *exec, struct drm_sched_job *sched_job)
4057 {
4058 	struct panthor_job *job = container_of(sched_job, struct panthor_job, base);
4059 
4060 	panthor_vm_update_resvs(job->group->vm, exec, &sched_job->s_fence->finished,
4061 				DMA_RESV_USAGE_BOOKKEEP, DMA_RESV_USAGE_BOOKKEEP);
4062 }
4063 
panthor_sched_unplug(struct panthor_device * ptdev)4064 void panthor_sched_unplug(struct panthor_device *ptdev)
4065 {
4066 	struct panthor_scheduler *sched = ptdev->scheduler;
4067 
4068 	disable_delayed_work_sync(&sched->tick_work);
4069 	disable_work_sync(&sched->fw_events_work);
4070 	disable_work_sync(&sched->sync_upd_work);
4071 
4072 	mutex_lock(&sched->lock);
4073 	if (sched->pm.has_ref) {
4074 		pm_runtime_put(ptdev->base.dev);
4075 		sched->pm.has_ref = false;
4076 	}
4077 	mutex_unlock(&sched->lock);
4078 }
4079 
panthor_sched_fini(struct drm_device * ddev,void * res)4080 static void panthor_sched_fini(struct drm_device *ddev, void *res)
4081 {
4082 	struct panthor_scheduler *sched = res;
4083 	int prio;
4084 
4085 	if (!sched || !sched->csg_slot_count)
4086 		return;
4087 
4088 	if (sched->wq)
4089 		destroy_workqueue(sched->wq);
4090 
4091 	if (sched->heap_alloc_wq)
4092 		destroy_workqueue(sched->heap_alloc_wq);
4093 
4094 	for (prio = PANTHOR_CSG_PRIORITY_COUNT - 1; prio >= 0; prio--) {
4095 		drm_WARN_ON(ddev, !list_empty(&sched->groups.runnable[prio]));
4096 		drm_WARN_ON(ddev, !list_empty(&sched->groups.idle[prio]));
4097 	}
4098 
4099 	drm_WARN_ON(ddev, !list_empty(&sched->groups.waiting));
4100 }
4101 
panthor_sched_init(struct panthor_device * ptdev)4102 int panthor_sched_init(struct panthor_device *ptdev)
4103 {
4104 	struct panthor_fw_global_iface *glb_iface = panthor_fw_get_glb_iface(ptdev);
4105 	struct panthor_fw_csg_iface *csg_iface = panthor_fw_get_csg_iface(ptdev, 0);
4106 	struct panthor_fw_cs_iface *cs_iface = panthor_fw_get_cs_iface(ptdev, 0, 0);
4107 	struct panthor_scheduler *sched;
4108 	u32 gpu_as_count, num_groups;
4109 	int prio, ret;
4110 
4111 	sched = drmm_kzalloc(&ptdev->base, sizeof(*sched), GFP_KERNEL);
4112 	if (!sched)
4113 		return -ENOMEM;
4114 
4115 	/* The highest bit in JOB_INT_* is reserved for globabl IRQs. That
4116 	 * leaves 31 bits for CSG IRQs, hence the MAX_CSGS clamp here.
4117 	 */
4118 	num_groups = min_t(u32, MAX_CSGS, glb_iface->control->group_num);
4119 
4120 	/* The FW-side scheduler might deadlock if two groups with the same
4121 	 * priority try to access a set of resources that overlaps, with part
4122 	 * of the resources being allocated to one group and the other part to
4123 	 * the other group, both groups waiting for the remaining resources to
4124 	 * be allocated. To avoid that, it is recommended to assign each CSG a
4125 	 * different priority. In theory we could allow several groups to have
4126 	 * the same CSG priority if they don't request the same resources, but
4127 	 * that makes the scheduling logic more complicated, so let's clamp
4128 	 * the number of CSG slots to MAX_CSG_PRIO + 1 for now.
4129 	 */
4130 	num_groups = min_t(u32, MAX_CSG_PRIO + 1, num_groups);
4131 
4132 	/* We need at least one AS for the MCU and one for the GPU contexts. */
4133 	gpu_as_count = hweight32(ptdev->gpu_info.as_present & GENMASK(31, 1));
4134 	if (!gpu_as_count) {
4135 		drm_err(&ptdev->base, "Not enough AS (%d, expected at least 2)",
4136 			gpu_as_count + 1);
4137 		return -EINVAL;
4138 	}
4139 
4140 	sched->ptdev = ptdev;
4141 	sched->sb_slot_count = CS_FEATURES_SCOREBOARDS(cs_iface->control->features);
4142 	sched->csg_slot_count = num_groups;
4143 	sched->cs_slot_count = csg_iface->control->stream_num;
4144 	sched->as_slot_count = gpu_as_count;
4145 	ptdev->csif_info.csg_slot_count = sched->csg_slot_count;
4146 	ptdev->csif_info.cs_slot_count = sched->cs_slot_count;
4147 	ptdev->csif_info.scoreboard_slot_count = sched->sb_slot_count;
4148 
4149 	sched->last_tick = 0;
4150 	sched->resched_target = U64_MAX;
4151 	sched->tick_period = msecs_to_jiffies(10);
4152 	INIT_DELAYED_WORK(&sched->tick_work, tick_work);
4153 	INIT_WORK(&sched->sync_upd_work, sync_upd_work);
4154 	INIT_WORK(&sched->fw_events_work, process_fw_events_work);
4155 
4156 	ret = drmm_mutex_init(&ptdev->base, &sched->lock);
4157 	if (ret)
4158 		return ret;
4159 
4160 	for (prio = PANTHOR_CSG_PRIORITY_COUNT - 1; prio >= 0; prio--) {
4161 		INIT_LIST_HEAD(&sched->groups.runnable[prio]);
4162 		INIT_LIST_HEAD(&sched->groups.idle[prio]);
4163 	}
4164 	INIT_LIST_HEAD(&sched->groups.waiting);
4165 
4166 	ret = drmm_mutex_init(&ptdev->base, &sched->reset.lock);
4167 	if (ret)
4168 		return ret;
4169 
4170 	INIT_LIST_HEAD(&sched->reset.stopped_groups);
4171 
4172 	/* sched->heap_alloc_wq will be used for heap chunk allocation on
4173 	 * tiler OOM events, which means we can't use the same workqueue for
4174 	 * the scheduler because works queued by the scheduler are in
4175 	 * the dma-signalling path. Allocate a dedicated heap_alloc_wq to
4176 	 * work around this limitation.
4177 	 *
4178 	 * FIXME: Ultimately, what we need is a failable/non-blocking GEM
4179 	 * allocation path that we can call when a heap OOM is reported. The
4180 	 * FW is smart enough to fall back on other methods if the kernel can't
4181 	 * allocate memory, and fail the tiling job if none of these
4182 	 * countermeasures worked.
4183 	 *
4184 	 * Set WQ_MEM_RECLAIM on sched->wq to unblock the situation when the
4185 	 * system is running out of memory.
4186 	 */
4187 	sched->heap_alloc_wq = alloc_workqueue("panthor-heap-alloc", WQ_UNBOUND, 0);
4188 	sched->wq = alloc_workqueue("panthor-csf-sched", WQ_MEM_RECLAIM | WQ_UNBOUND, 0);
4189 	if (!sched->wq || !sched->heap_alloc_wq) {
4190 		panthor_sched_fini(&ptdev->base, sched);
4191 		drm_err(&ptdev->base, "Failed to allocate the workqueues");
4192 		return -ENOMEM;
4193 	}
4194 
4195 	ret = drmm_add_action_or_reset(&ptdev->base, panthor_sched_fini, sched);
4196 	if (ret)
4197 		return ret;
4198 
4199 	ptdev->scheduler = sched;
4200 	return 0;
4201 }
4202