xref: /linux/drivers/gpu/drm/amd/amdkfd/kfd_priv.h (revision 570f7e331f5febb30f1384817463c7e42b65ca7d)
1 /* SPDX-License-Identifier: GPL-2.0 OR MIT */
2 /*
3  * Copyright 2014-2022 Advanced Micro Devices, Inc.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
19  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
20  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
21  * OTHER DEALINGS IN THE SOFTWARE.
22  */
23 
24 #ifndef KFD_PRIV_H_INCLUDED
25 #define KFD_PRIV_H_INCLUDED
26 
27 #include <linux/hashtable.h>
28 #include <linux/mmu_notifier.h>
29 #include <linux/memremap.h>
30 #include <linux/mutex.h>
31 #include <linux/types.h>
32 #include <linux/atomic.h>
33 #include <linux/workqueue.h>
34 #include <linux/spinlock.h>
35 #include <linux/iosys-map.h>
36 #include <uapi/linux/kfd_ioctl.h>
37 #include <linux/idr.h>
38 #include <linux/kfifo.h>
39 #include <linux/seq_file.h>
40 #include <linux/kref.h>
41 #include <linux/sysfs.h>
42 #include <linux/device_cgroup.h>
43 #include <drm/drm_file.h>
44 #include <drm/drm_drv.h>
45 #include <drm/drm_device.h>
46 #include <drm/drm_ioctl.h>
47 #include <kgd_kfd_interface.h>
48 #include <linux/swap.h>
49 
50 #include "amd_shared.h"
51 #include "amdgpu.h"
52 
53 #define KFD_MAX_RING_ENTRY_SIZE	8
54 
55 #define KFD_SYSFS_FILE_MODE 0444
56 
57 /* GPU ID hash width in bits */
58 #define KFD_GPU_ID_HASH_WIDTH 16
59 
60 /* Use upper bits of mmap offset to store KFD driver specific information.
61  * BITS[63:62] - Encode MMAP type
62  * BITS[61:46] - Encode gpu_id. To identify to which GPU the offset belongs to
63  * BITS[45:0]  - MMAP offset value
64  *
65  * NOTE: struct vm_area_struct.vm_pgoff uses offset in pages. Hence, these
66  *  defines are w.r.t to PAGE_SIZE
67  */
68 #define KFD_MMAP_TYPE_SHIFT	62
69 #define KFD_MMAP_TYPE_MASK	(0x3ULL << KFD_MMAP_TYPE_SHIFT)
70 #define KFD_MMAP_TYPE_DOORBELL	(0x3ULL << KFD_MMAP_TYPE_SHIFT)
71 #define KFD_MMAP_TYPE_EVENTS	(0x2ULL << KFD_MMAP_TYPE_SHIFT)
72 #define KFD_MMAP_TYPE_RESERVED_MEM	(0x1ULL << KFD_MMAP_TYPE_SHIFT)
73 #define KFD_MMAP_TYPE_MMIO	(0x0ULL << KFD_MMAP_TYPE_SHIFT)
74 
75 #define KFD_MMAP_GPU_ID_SHIFT 46
76 #define KFD_MMAP_GPU_ID_MASK (((1ULL << KFD_GPU_ID_HASH_WIDTH) - 1) \
77 				<< KFD_MMAP_GPU_ID_SHIFT)
78 #define KFD_MMAP_GPU_ID(gpu_id) ((((uint64_t)gpu_id) << KFD_MMAP_GPU_ID_SHIFT)\
79 				& KFD_MMAP_GPU_ID_MASK)
80 #define KFD_MMAP_GET_GPU_ID(offset)    ((offset & KFD_MMAP_GPU_ID_MASK) \
81 				>> KFD_MMAP_GPU_ID_SHIFT)
82 
83 /*
84  * When working with cp scheduler we should assign the HIQ manually or via
85  * the amdgpu driver to a fixed hqd slot, here are the fixed HIQ hqd slot
86  * definitions for Kaveri. In Kaveri only the first ME queues participates
87  * in the cp scheduling taking that in mind we set the HIQ slot in the
88  * second ME.
89  */
90 #define KFD_CIK_HIQ_PIPE 4
91 #define KFD_CIK_HIQ_QUEUE 0
92 
93 /* Macro for allocating structures */
94 #define kfd_alloc_struct(ptr_to_struct)	\
95 	((typeof(ptr_to_struct)) kzalloc_obj(*ptr_to_struct))
96 
97 #define KFD_MAX_NUM_OF_PROCESSES 512
98 #define KFD_MAX_NUM_OF_QUEUES_PER_PROCESS 1024
99 
100 /*
101  * Size of the per-process TBA+TMA buffer: 2 pages
102  *
103  * The first chunk is the TBA used for the CWSR ISA code. The second
104  * chunk is used as TMA for user-mode trap handler setup in daisy-chain mode.
105  */
106 #define KFD_CWSR_TBA_TMA_SIZE (AMDGPU_GPU_PAGE_SIZE * 2)
107 #define KFD_CWSR_TMA_OFFSET (AMDGPU_GPU_PAGE_SIZE + 2048)
108 
109 #define KFD_MAX_NUM_OF_QUEUES_PER_DEVICE		\
110 	(KFD_MAX_NUM_OF_PROCESSES *			\
111 			KFD_MAX_NUM_OF_QUEUES_PER_PROCESS)
112 
113 #define KFD_KERNEL_QUEUE_SIZE 2048
114 
115 /*  KFD_UNMAP_LATENCY_MS is the timeout CP waiting for SDMA preemption. One XCC
116  *  can be associated to 2 SDMA engines. queue_preemption_timeout_ms is the time
117  *  driver waiting for CP returning the UNMAP_QUEUE fence. Thus the math is
118  *  queue_preemption_timeout_ms = sdma_preemption_time * 2 + cp workload
119  *  The format here makes CP workload 10% of total timeout
120  */
121 #define KFD_UNMAP_LATENCY_MS	\
122 	((queue_preemption_timeout_ms - queue_preemption_timeout_ms / 10) >> 1)
123 
124 #define KFD_MAX_SDMA_QUEUES	128
125 
126 /*
127  * 512 = 0x200
128  * The doorbell index distance between SDMA RLC (2*i) and (2*i+1) in the
129  * same SDMA engine on SOC15, which has 8-byte doorbells for SDMA.
130  * 512 8-byte doorbell distance (i.e. one page away) ensures that SDMA RLC
131  * (2*i+1) doorbells (in terms of the lower 12 bit address) lie exactly in
132  * the OFFSET and SIZE set in registers like BIF_SDMA0_DOORBELL_RANGE.
133  */
134 #define KFD_QUEUE_DOORBELL_MIRROR_OFFSET 512
135 
136 /**
137  * enum kfd_ioctl_flags - KFD ioctl flags
138  * Various flags that can be set in &amdkfd_ioctl_desc.flags to control how
139  * userspace can use a given ioctl.
140  */
141 enum kfd_ioctl_flags {
142 	/*
143 	 * @KFD_IOC_FLAG_CHECKPOINT_RESTORE:
144 	 * Certain KFD ioctls such as AMDKFD_IOC_CRIU_OP can potentially
145 	 * perform privileged operations and load arbitrary data into MQDs and
146 	 * eventually HQD registers when the queue is mapped by HWS. In order to
147 	 * prevent this we should perform additional security checks.
148 	 *
149 	 * This is equivalent to callers with the CHECKPOINT_RESTORE capability.
150 	 *
151 	 * Note: Since earlier versions of docker do not support CHECKPOINT_RESTORE,
152 	 * we also allow ioctls with SYS_ADMIN capability.
153 	 */
154 	KFD_IOC_FLAG_CHECKPOINT_RESTORE = BIT(0),
155 };
156 /*
157  * Kernel module parameter to specify maximum number of supported queues per
158  * device
159  */
160 extern int max_num_of_queues_per_device;
161 
162 
163 /* Kernel module parameter to specify the scheduling policy */
164 extern int sched_policy;
165 
166 /*
167  * Kernel module parameter to specify the maximum process
168  * number per HW scheduler
169  */
170 extern int hws_max_conc_proc;
171 
172 extern int cwsr_enable;
173 
174 /*
175  * Kernel module parameter to specify whether to send sigterm to HSA process on
176  * unhandled exception
177  */
178 extern int send_sigterm;
179 
180 /*
181  * This kernel module is used to simulate large bar machine on non-large bar
182  * enabled machines.
183  */
184 extern int debug_largebar;
185 
186 /* Set sh_mem_config.retry_disable on GFX v9 */
187 extern int amdgpu_noretry;
188 
189 /* Halt if HWS hang is detected */
190 extern int halt_if_hws_hang;
191 
192 /* Whether MEC FW support GWS barriers */
193 extern bool hws_gws_support;
194 
195 /* Queue preemption timeout in ms */
196 extern int queue_preemption_timeout_ms;
197 
198 /*
199  * Don't evict process queues on vm fault
200  */
201 extern int amdgpu_no_queue_eviction_on_vm_fault;
202 
203 /* Enable eviction debug messages */
204 extern bool debug_evictions;
205 
206 extern struct mutex kfd_processes_mutex;
207 
208 enum cache_policy {
209 	cache_policy_coherent,
210 	cache_policy_noncoherent
211 };
212 
213 #define KFD_GC_VERSION(dev) (amdgpu_ip_version((dev)->adev, GC_HWIP, 0))
214 #define KFD_IS_SOC15(dev)   ((KFD_GC_VERSION(dev)) >= (IP_VERSION(9, 0, 1)))
215 #define KFD_SUPPORT_XNACK_PER_PROCESS(dev)\
216 	((KFD_GC_VERSION(dev) == IP_VERSION(9, 4, 2)) ||	\
217 	 (KFD_GC_VERSION(dev) == IP_VERSION(9, 4, 3)) ||	\
218 	 (KFD_GC_VERSION(dev) == IP_VERSION(9, 4, 4)) ||	\
219 	 (KFD_GC_VERSION(dev) == IP_VERSION(9, 5, 0)))
220 
221 struct kfd_node;
222 
223 struct kfd_event_interrupt_class {
224 	bool (*interrupt_isr)(struct kfd_node *dev,
225 			const uint32_t *ih_ring_entry, uint32_t *patched_ihre,
226 			bool *patched_flag);
227 	void (*interrupt_wq)(struct kfd_node *dev,
228 			const uint32_t *ih_ring_entry);
229 };
230 
231 struct kfd_device_info {
232 	uint32_t gfx_target_version;
233 	const struct kfd_event_interrupt_class *event_interrupt_class;
234 	unsigned int max_pasid_bits;
235 	unsigned int max_no_of_hqd;
236 	unsigned int doorbell_size;
237 	size_t ih_ring_entry_size;
238 	uint8_t num_of_watch_points;
239 	uint16_t mqd_size_aligned;
240 	bool supports_cwsr;
241 	bool needs_pci_atomics;
242 	uint32_t no_atomic_fw_version;
243 	unsigned int num_sdma_queues_per_engine;
244 	unsigned int num_reserved_sdma_queues_per_engine;
245 };
246 
247 unsigned int kfd_get_num_sdma_engines(struct kfd_node *kdev);
248 unsigned int kfd_get_num_xgmi_sdma_engines(struct kfd_node *kdev);
249 
250 struct kfd_mem_obj {
251 	uint32_t range_start;
252 	uint32_t range_end;
253 	uint64_t gpu_addr;
254 	uint32_t *cpu_ptr;
255 	void *mem;
256 };
257 
258 struct kfd_vmid_info {
259 	uint32_t first_vmid_kfd;
260 	uint32_t last_vmid_kfd;
261 	uint32_t vmid_num_kfd;
262 };
263 
264 #define MAX_KFD_NODES	8
265 
266 struct kfd_dev;
267 
268 struct kfd_node {
269 	unsigned int node_id;
270 	struct amdgpu_device *adev;     /* Duplicated here along with keeping
271 					 * a copy in kfd_dev to save a hop
272 					 */
273 	const struct kfd2kgd_calls *kfd2kgd; /* Duplicated here along with
274 					      * keeping a copy in kfd_dev to
275 					      * save a hop
276 					      */
277 	struct kfd_vmid_info vm_info;
278 	unsigned int id;                /* topology stub index */
279 	uint32_t xcc_mask; /* Instance mask of XCCs present */
280 	struct amdgpu_xcp *xcp;
281 
282 	/* Interrupts */
283 	struct kfifo ih_fifo;
284 	struct work_struct interrupt_work;
285 	spinlock_t interrupt_lock;
286 
287 	/*
288 	 * Interrupts of interest to KFD are copied
289 	 * from the HW ring into a SW ring.
290 	 */
291 	bool interrupts_active;
292 	uint32_t interrupt_bitmap; /* Only used for GFX 9.4.3 */
293 
294 	/* QCM Device instance */
295 	struct device_queue_manager *dqm;
296 
297 	/* Global GWS resource shared between processes */
298 	void *gws;
299 
300 	/* Clients watching SMI events */
301 	struct list_head smi_clients;
302 	spinlock_t smi_lock;
303 	uint32_t reset_seq_num;
304 
305 	/* SRAM ECC flag */
306 	atomic_t sram_ecc_flag;
307 
308 	/*spm process id */
309 	unsigned int spm_pasid;
310 
311 	/* Maximum process number mapped to HW scheduler */
312 	unsigned int max_proc_per_quantum;
313 
314 	unsigned int compute_vmid_bitmap;
315 
316 	struct kfd_local_mem_info local_mem_info;
317 
318 	struct kfd_dev *kfd;
319 
320 	/* Track per device allocated watch points */
321 	uint32_t alloc_watch_ids;
322 	spinlock_t watch_points_lock;
323 };
324 
325 struct kfd_dev {
326 	struct amdgpu_device *adev;
327 
328 	struct kfd_device_info device_info;
329 
330 	u32 __iomem *doorbell_kernel_ptr; /* This is a pointer for a doorbells
331 					   * page used by kernel queue
332 					   */
333 
334 	struct kgd2kfd_shared_resources shared_resources;
335 
336 	const struct kfd2kgd_calls *kfd2kgd;
337 	struct mutex doorbell_mutex;
338 
339 	void *gtt_mem;
340 	uint64_t gtt_start_gpu_addr;
341 	void *gtt_start_cpu_ptr;
342 	void *gtt_sa_bitmap;
343 	struct mutex gtt_sa_lock;
344 	unsigned int gtt_sa_chunk_size;
345 	unsigned int gtt_sa_num_of_chunks;
346 
347 	bool init_complete;
348 
349 	/* Firmware versions */
350 	uint16_t mec_fw_version;
351 	uint16_t mec2_fw_version;
352 	uint16_t sdma_fw_version;
353 
354 	/* CWSR */
355 	bool cwsr_enabled;
356 	const void *cwsr_isa;
357 	unsigned int cwsr_isa_size;
358 
359 	/* xGMI */
360 	uint64_t hive_id;
361 
362 	bool pci_atomic_requested;
363 
364 	/* Compute Profile ref. count */
365 	atomic_t compute_profile;
366 
367 	struct ida doorbell_ida;
368 	unsigned int max_doorbell_slices;
369 
370 	int noretry;
371 
372 	struct kfd_node *nodes[MAX_KFD_NODES];
373 	unsigned int num_nodes;
374 
375 	struct workqueue_struct *ih_wq;
376 
377 	/* Kernel doorbells for KFD device */
378 	struct amdgpu_bo *doorbells;
379 
380 	/* bitmap for dynamic doorbell allocation from doorbell object */
381 	unsigned long *doorbell_bitmap;
382 
383 	/* for dynamic partitioning */
384 	int kfd_dev_lock;
385 
386 	atomic_t kfd_processes_count;
387 
388 	/* Lock for profiler process */
389 	struct mutex profiler_lock;
390 	/* Process currently holding the lock */
391 	struct kfd_process *profiler_process;
392 };
393 
394 enum kfd_mempool {
395 	KFD_MEMPOOL_SYSTEM_CACHEABLE = 1,
396 	KFD_MEMPOOL_SYSTEM_WRITECOMBINE = 2,
397 	KFD_MEMPOOL_FRAMEBUFFER = 3,
398 };
399 
400 /* Character device interface */
401 int kfd_chardev_init(void);
402 void kfd_chardev_exit(void);
403 void kfd_dev_unmap_mapping_range(loff_t const holebegin, loff_t const holelen);
404 
405 /**
406  * enum kfd_unmap_queues_filter - Enum for queue filters.
407  *
408  * @KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES: Preempts all queues in the
409  *						running queues list.
410  *
411  * @KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES: Preempts all non-static queues
412  *						in the run list.
413  *
414  * @KFD_UNMAP_QUEUES_FILTER_BY_PASID: Preempts queues that belongs to
415  *						specific process.
416  *
417  */
418 enum kfd_unmap_queues_filter {
419 	KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES = 1,
420 	KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES = 2,
421 	KFD_UNMAP_QUEUES_FILTER_BY_PASID = 3
422 };
423 
424 /**
425  * enum kfd_queue_type - Enum for various queue types.
426  *
427  * @KFD_QUEUE_TYPE_COMPUTE: Regular user mode queue type.
428  *
429  * @KFD_QUEUE_TYPE_SDMA: SDMA user mode queue type.
430  *
431  * @KFD_QUEUE_TYPE_HIQ: HIQ queue type.
432  *
433  * @KFD_QUEUE_TYPE_DIQ: DIQ queue type.
434  *
435  * @KFD_QUEUE_TYPE_SDMA_XGMI: Special SDMA queue for XGMI interface.
436  *
437  * @KFD_QUEUE_TYPE_SDMA_BY_ENG_ID:  SDMA user mode queue with target SDMA engine ID.
438  */
439 enum kfd_queue_type  {
440 	KFD_QUEUE_TYPE_COMPUTE,
441 	KFD_QUEUE_TYPE_SDMA,
442 	KFD_QUEUE_TYPE_HIQ,
443 	KFD_QUEUE_TYPE_SDMA_XGMI,
444 	KFD_QUEUE_TYPE_SDMA_BY_ENG_ID,
445 	KFD_QUEUE_TYPE_MAX,
446 };
447 
448 enum kfd_queue_format {
449 	KFD_QUEUE_FORMAT_PM4,
450 	KFD_QUEUE_FORMAT_AQL
451 };
452 
453 enum KFD_QUEUE_PRIORITY {
454 	KFD_QUEUE_PRIORITY_MINIMUM = 0,
455 	KFD_QUEUE_PRIORITY_MAXIMUM = 15
456 };
457 
458 /**
459  * struct queue_properties
460  *
461  * @type: The queue type.
462  *
463  * @queue_id: Queue identifier.
464  *
465  * @queue_address: Queue ring buffer address.
466  *
467  * @queue_size: Queue ring buffer size.
468  *
469  * @priority: Defines the queue priority relative to other queues in the
470  * process.
471  * This is just an indication and HW scheduling may override the priority as
472  * necessary while keeping the relative prioritization.
473  * the priority granularity is from 0 to f which f is the highest priority.
474  * currently all queues are initialized with the highest priority.
475  *
476  * @queue_percent: This field is partially implemented and currently a zero in
477  * this field defines that the queue is non active.
478  *
479  * @read_ptr: User space address which points to the number of dwords the
480  * cp read from the ring buffer. This field updates automatically by the H/W.
481  *
482  * @write_ptr: Defines the number of dwords written to the ring buffer.
483  *
484  * @doorbell_ptr: Notifies the H/W of new packet written to the queue ring
485  * buffer. This field should be similar to write_ptr and the user should
486  * update this field after updating the write_ptr.
487  *
488  * @doorbell_off: The doorbell offset in the doorbell pci-bar.
489  *
490  * @is_interop: Defines if this is a interop queue. Interop queue means that
491  * the queue can access both graphics and compute resources.
492  *
493  * @is_evicted: Defines if the queue is evicted. Only active queues
494  * are evicted, rendering them inactive.
495  *
496  * @is_active: Defines if the queue is active or not. @is_active and
497  * @is_evicted are protected by the DQM lock.
498  *
499  * @is_gws: Defines if the queue has been updated to be GWS-capable or not.
500  * @is_gws should be protected by the DQM lock, since changing it can yield the
501  * possibility of updating DQM state on number of GWS queues.
502  *
503  * @vmid: If the scheduling mode is no cp scheduling the field defines the vmid
504  * of the queue.
505  *
506  * This structure represents the queue properties for each queue no matter if
507  * it's user mode or kernel mode queue.
508  *
509  */
510 
511 struct queue_properties {
512 	enum kfd_queue_type type;
513 	enum kfd_queue_format format;
514 	unsigned int queue_id;
515 	uint64_t queue_address;
516 	uint64_t queue_size;
517 	uint64_t metadata_queue_size;
518 	uint32_t priority;
519 	uint32_t queue_percent;
520 	void __user *read_ptr;
521 	void __user *write_ptr;
522 	void __iomem *doorbell_ptr;
523 	uint32_t doorbell_off;
524 	bool is_interop;
525 	bool is_evicted;
526 	bool is_suspended;
527 	bool is_being_destroyed;
528 	bool is_active;
529 	bool is_gws;
530 	uint32_t pm4_target_xcc;
531 	bool is_dbg_wa;
532 	bool is_user_cu_masked;
533 	bool is_reset;
534 	/* Not relevant for user mode queues in cp scheduling */
535 	unsigned int vmid;
536 	/* Relevant only for sdma queues*/
537 	uint32_t sdma_engine_id;
538 	uint32_t sdma_queue_id;
539 	uint32_t sdma_vm_addr;
540 	/* Relevant only for VI */
541 	uint64_t eop_ring_buffer_address;
542 	uint32_t eop_ring_buffer_size;
543 	uint64_t ctx_save_restore_area_address;
544 	uint32_t ctx_save_restore_area_size;
545 	uint32_t ctl_stack_size;
546 	uint64_t tba_addr;
547 	uint64_t tma_addr;
548 	uint64_t exception_status;
549 
550 	struct amdgpu_bo *wptr_bo;
551 	struct amdgpu_bo *rptr_bo;
552 	struct amdgpu_bo *ring_bo;
553 	struct amdgpu_bo *eop_buf_bo;
554 	struct amdgpu_bo *cwsr_bo;
555 };
556 
557 #define QUEUE_IS_ACTIVE(q) ((q).queue_size > 0 &&	\
558 			    (q).queue_address != 0 &&	\
559 			    (q).queue_percent > 0 &&	\
560 			    !(q).is_evicted &&		\
561 			    !(q).is_suspended)
562 
563 enum mqd_update_flag {
564 	UPDATE_FLAG_DBG_WA_ENABLE = 1,
565 	UPDATE_FLAG_DBG_WA_DISABLE = 2,
566 	UPDATE_FLAG_IS_GWS = 4, /* quirk for gfx9 IP */
567 	UPDATE_FLAG_PERFCOUNT_ENABLE = 5,
568 	UPDATE_FLAG_PERFCOUNT_DISABLE = 6,
569 };
570 
571 struct mqd_update_info {
572 	union {
573 		struct {
574 			uint32_t count; /* Must be a multiple of 32 */
575 			uint32_t *ptr;
576 		} cu_mask;
577 	};
578 	enum mqd_update_flag update_flag;
579 };
580 
581 /**
582  * struct queue
583  *
584  * @list: Queue linked list.
585  *
586  * @mqd: The queue MQD (memory queue descriptor).
587  *
588  * @mqd_mem_obj: The MQD local gpu memory object.
589  *
590  * @gart_mqd_addr: The MQD gart mc address.
591  *
592  * @properties: The queue properties.
593  *
594  * @mec: Used only in no cp scheduling mode and identifies to micro engine id
595  *	 that the queue should be executed on.
596  *
597  * @pipe: Used only in no cp scheduling mode and identifies the queue's pipe
598  *	  id.
599  *
600  * @queue: Used only in no cp scheduliong mode and identifies the queue's slot.
601  *
602  * @process: The kfd process that created this queue.
603  *
604  * @device: The kfd device that created this queue.
605  *
606  * @gws: Pointing to gws kgd_mem if this is a gws control queue; NULL
607  * otherwise.
608  *
609  * This structure represents user mode compute queues.
610  * It contains all the necessary data to handle such queues.
611  *
612  */
613 
614 struct queue {
615 	struct list_head list;
616 	void *mqd;
617 	struct kfd_mem_obj *mqd_mem_obj;
618 	uint64_t gart_mqd_addr;
619 	struct queue_properties properties;
620 
621 	uint32_t mec;
622 	uint32_t pipe;
623 	uint32_t queue;
624 
625 	unsigned int sdma_id;
626 	unsigned int doorbell_id;
627 
628 	struct kfd_process	*process;
629 	struct kfd_node		*device;
630 	void *gws;
631 
632 	/* procfs */
633 	struct kobject kobj;
634 
635 	void *gang_ctx_bo;
636 	uint64_t gang_ctx_gpu_addr;
637 	void *gang_ctx_cpu_ptr;
638 	uint32_t gang_ctx_array_index;
639 
640 	struct amdgpu_bo *wptr_bo_gart;
641 
642 	/* The VRAM-resident MQD BO (mqd_on_vram()) is unpinned at S4 suspend so
643 	 * TTM evicts it into the hibernation image, and repinned on resume. Set
644 	 * while the BO is unpinned so the resume path knows to repin it.
645 	 */
646 	bool needs_mqd_repin;
647 };
648 
649 enum KFD_MQD_TYPE {
650 	KFD_MQD_TYPE_HIQ = 0,		/* for hiq */
651 	KFD_MQD_TYPE_CP,		/* for cp queues and diq */
652 	KFD_MQD_TYPE_SDMA,		/* for sdma queues */
653 	KFD_MQD_TYPE_DIQ,		/* for diq */
654 	KFD_MQD_TYPE_MAX
655 };
656 
657 enum KFD_PIPE_PRIORITY {
658 	KFD_PIPE_PRIORITY_CS_LOW = 0,
659 	KFD_PIPE_PRIORITY_CS_MEDIUM,
660 	KFD_PIPE_PRIORITY_CS_HIGH
661 };
662 
663 struct scheduling_resources {
664 	unsigned int vmid_mask;
665 	enum kfd_queue_type type;
666 	uint64_t queue_mask;
667 	uint64_t gws_mask;
668 	uint32_t oac_mask;
669 	uint32_t gds_heap_base;
670 	uint32_t gds_heap_size;
671 };
672 
673 struct process_queue_manager {
674 	/* data */
675 	struct kfd_process	*process;
676 	struct list_head	queues;
677 	unsigned long		*queue_slot_bitmap;
678 };
679 
680 struct qcm_process_device {
681 	/* The Device Queue Manager that owns this data */
682 	struct device_queue_manager *dqm;
683 	struct process_queue_manager *pqm;
684 	/* Queues list */
685 	struct list_head queues_list;
686 	struct list_head priv_queue_list;
687 
688 	unsigned int queue_count;
689 	unsigned int vmid;
690 	bool is_debug;
691 	unsigned int evicted; /* eviction counter, 0=active */
692 
693 	/* This flag tells if we should reset all wavefronts on
694 	 * process termination
695 	 */
696 	bool reset_wavefronts;
697 
698 	/* This flag tells us if this process has a GWS-capable
699 	 * queue that will be mapped into the runlist. It's
700 	 * possible to request a GWS BO, but not have the queue
701 	 * currently mapped, and this changes how the MAP_PROCESS
702 	 * PM4 packet is configured.
703 	 */
704 	bool mapped_gws_queue;
705 
706 	/* All the memory management data should be here too */
707 	uint64_t gds_context_area;
708 	/* Contains page table flags such as AMDGPU_PTE_VALID since gfx9 */
709 	uint64_t page_table_base;
710 	uint32_t sh_mem_config;
711 	uint32_t sh_mem_bases;
712 	uint32_t sh_mem_ape1_base;
713 	uint32_t sh_mem_ape1_limit;
714 	uint32_t gds_size;
715 	uint32_t num_gws;
716 	uint32_t num_oac;
717 	uint32_t sh_hidden_private_base;
718 	uint32_t vm_cntx_cntl;
719 
720 	/* CWSR memory */
721 	struct kgd_mem *cwsr_mem;
722 	struct iosys_map cwsr_map;
723 	uint64_t cwsr_base;
724 	uint64_t tba_addr;
725 	uint64_t tma_addr;
726 
727 	/* IB memory */
728 	struct kgd_mem *ib_mem;
729 	uint64_t ib_base;
730 	void *ib_kaddr;
731 
732 	/* doorbells for kfd process */
733 	struct amdgpu_bo *proc_doorbells;
734 
735 	/* bitmap for dynamic doorbell allocation from the bo */
736 	unsigned long *doorbell_bitmap;
737 };
738 
739 /* KFD Memory Eviction */
740 
741 /* Approx. wait time before attempting to restore evicted BOs */
742 #define PROCESS_RESTORE_TIME_MS 100
743 /* Approx. back off time if restore fails due to lack of memory */
744 #define PROCESS_BACK_OFF_TIME_MS 100
745 /* Approx. time before evicting the process again */
746 #define PROCESS_ACTIVE_TIME_MS 10
747 
748 /* 8 byte handle containing GPU ID in the most significant 4 bytes and
749  * idr_handle in the least significant 4 bytes
750  */
751 #define MAKE_HANDLE(gpu_id, idr_handle) \
752 	(((uint64_t)(gpu_id) << 32) + idr_handle)
753 #define GET_GPU_ID(handle) (handle >> 32)
754 #define GET_IDR_HANDLE(handle) (handle & 0xFFFFFFFF)
755 
756 enum kfd_pdd_bound {
757 	PDD_UNBOUND = 0,
758 	PDD_BOUND,
759 	PDD_BOUND_SUSPENDED,
760 };
761 
762 #define MAX_SYSFS_FILENAME_LEN 15
763 
764 /*
765  * SDMA counter runs at 100MHz frequency.
766  * We display SDMA activity in microsecond granularity in sysfs.
767  * As a result, the divisor is 100.
768  */
769 #define SDMA_ACTIVITY_DIVISOR  100
770 
771 /* Data that is per-process-per device. */
772 struct kfd_process_device {
773 	/* The device that owns this data. */
774 	struct kfd_node *dev;
775 
776 	/* The process that owns this kfd_process_device. */
777 	struct kfd_process *process;
778 
779 	/* per-process-per device QCM data structure */
780 	struct qcm_process_device qpd;
781 
782 	/*Apertures*/
783 	uint64_t lds_base;
784 	uint64_t lds_limit;
785 	uint64_t gpuvm_base;
786 	uint64_t gpuvm_limit;
787 	uint64_t scratch_base;
788 	uint64_t scratch_limit;
789 
790 	/* VM context for GPUVM allocations */
791 	struct file *drm_file;
792 	void *drm_priv;
793 
794 	/* GPUVM allocations storage */
795 	struct idr alloc_idr;
796 
797 	/* Flag used to tell the pdd has dequeued from the dqm.
798 	 * This is used to prevent dev->dqm->ops.process_termination() from
799 	 * being called twice when it is already called in IOMMU callback
800 	 * function.
801 	 */
802 	bool already_dequeued;
803 	bool runtime_inuse;
804 
805 	/* Is this process/pasid bound to this device? (amd_iommu_bind_pasid) */
806 	enum kfd_pdd_bound bound;
807 
808 	/* VRAM usage */
809 	atomic64_t vram_usage;
810 	struct attribute attr_vram;
811 	char vram_filename[MAX_SYSFS_FILENAME_LEN];
812 
813 	/* SDMA activity tracking */
814 	uint64_t sdma_past_activity_counter;
815 	struct attribute attr_sdma;
816 	char sdma_filename[MAX_SYSFS_FILENAME_LEN];
817 
818 	/* Eviction activity tracking */
819 	uint64_t last_evict_timestamp;
820 	atomic64_t evict_duration_counter;
821 	struct attribute attr_evict;
822 
823 	struct kobject *kobj_stats;
824 
825 	/*
826 	 * @cu_occupancy: Reports occupancy of Compute Units (CU) of a process
827 	 * that is associated with device encoded by "this" struct instance. The
828 	 * value reflects CU usage by all of the waves launched by this process
829 	 * on this device. A very important property of occupancy parameter is
830 	 * that its value is a snapshot of current use.
831 	 *
832 	 * Following is to be noted regarding how this parameter is reported:
833 	 *
834 	 *  The number of waves that a CU can launch is limited by couple of
835 	 *  parameters. These are encoded by struct amdgpu_cu_info instance
836 	 *  that is part of every device definition. For GFX9 devices this
837 	 *  translates to 40 waves (simd_per_cu * max_waves_per_simd) when waves
838 	 *  do not use scratch memory and 32 waves (max_scratch_slots_per_cu)
839 	 *  when they do use scratch memory. This could change for future
840 	 *  devices and therefore this example should be considered as a guide.
841 	 *
842 	 *  All CU's of a device are available for the process. This may not be true
843 	 *  under certain conditions - e.g. CU masking.
844 	 *
845 	 *  Finally number of CU's that are occupied by a process is affected by both
846 	 *  number of CU's a device has along with number of other competing processes
847 	 */
848 	struct attribute attr_cu_occupancy;
849 
850 	/* sysfs counters for GPU retry fault and page migration tracking */
851 	struct kobject *kobj_counters;
852 	struct attribute attr_faults;
853 	struct attribute attr_page_in;
854 	struct attribute attr_page_out;
855 	uint64_t faults;
856 	uint64_t page_in;
857 	uint64_t page_out;
858 
859 	/* Exception code status*/
860 	uint64_t exception_status;
861 	void *vm_fault_exc_data;
862 	size_t vm_fault_exc_data_size;
863 
864 	/* Tracks debug per-vmid request settings */
865 	uint32_t spi_dbg_override;
866 	uint32_t spi_dbg_launch_mode;
867 	uint32_t watch_points[4];
868 	uint32_t alloc_watch_ids;
869 
870 	/*
871 	 * If this process has been checkpointed before, then the user
872 	 * application will use the original gpu_id on the
873 	 * checkpointed node to refer to this device.
874 	 */
875 	uint32_t user_gpu_id;
876 
877 	void *proc_ctx_bo;
878 	uint64_t proc_ctx_gpu_addr;
879 	void *proc_ctx_cpu_ptr;
880 
881 	uint32_t proc_ctx_array_index;
882 
883 	/* Tracks queue reset status */
884 	bool has_reset_queue;
885 
886 	u32 pasid;
887 	/* Indicates this process has requested PTL stay disabled */
888 	bool ptl_disable_req;
889 };
890 
891 #define qpd_to_pdd(x) container_of(x, struct kfd_process_device, qpd)
892 
893 struct svm_range_list {
894 	struct mutex			lock;
895 	struct rb_root_cached		objects;
896 	struct list_head		list;
897 	struct work_struct		deferred_list_work;
898 	struct list_head		deferred_range_list;
899 	struct list_head                criu_svm_metadata_list;
900 	spinlock_t			deferred_list_lock;
901 	atomic_t			evicted_ranges;
902 	atomic_t			drain_pagefaults;
903 	struct delayed_work		restore_work;
904 	DECLARE_BITMAP(bitmap_supported, MAX_GPU_INSTANCE);
905 	struct task_struct		*faulting_task;
906 	/* check point ts decides if page fault recovery need be dropped */
907 	atomic64_t			checkpoint_ts[MAX_GPU_INSTANCE];
908 
909 	/* Default granularity to use in buffer migration
910 	 * and restoration of backing memory while handling
911 	 * recoverable page faults
912 	 */
913 	uint8_t default_granularity;
914 };
915 
916 /* Process data */
917 struct kfd_process {
918 	/*
919 	 * kfd_process are stored in an mm_struct*->kfd_process*
920 	 * hash table (kfd_processes in kfd_process.c)
921 	 */
922 	struct hlist_node kfd_processes;
923 
924 	/*
925 	 * Opaque pointer to mm_struct. We don't hold a reference to
926 	 * it so it should never be dereferenced from here. This is
927 	 * only used for looking up processes by their mm.
928 	 */
929 	void *mm;
930 
931 	struct kref ref;
932 	struct work_struct release_work;
933 
934 	struct mutex mutex;
935 
936 	/*
937 	 * In any process, the thread that started main() is the lead
938 	 * thread and outlives the rest.
939 	 * It is here because amd_iommu_bind_pasid wants a task_struct.
940 	 * It can also be used for safely getting a reference to the
941 	 * mm_struct of the process.
942 	 */
943 	struct task_struct *lead_thread;
944 
945 	/* We want to receive a notification when the mm_struct is destroyed */
946 	struct mmu_notifier mmu_notifier;
947 
948 	/*
949 	 * Array of kfd_process_device pointers,
950 	 * one for each device the process is using.
951 	 */
952 	struct kfd_process_device *pdds[MAX_GPU_INSTANCE];
953 	uint32_t n_pdds;
954 
955 	struct process_queue_manager pqm;
956 
957 	/*Is the user space process 32 bit?*/
958 	bool is_32bit_user_mode;
959 
960 	/* Event-related data */
961 	struct mutex event_mutex;
962 	/* Event ID allocator and lookup */
963 	struct idr event_idr;
964 	/* Event page */
965 	u64 signal_handle;
966 	/*
967 	 * Each signal event needs a 64-bit signal slot where the signaler will
968 	 * write a 1 before sending an interrupt. (This is needed because some
969 	 * interrupts do not contain enough spare data bits to identify an
970 	 * event.) The signal page is allocated in user mode and mapped to the
971 	 * kernel; individual signal events use their event_id as slot index.
972 	 */
973 	uint64_t *signal_page;
974 	size_t signal_mapped_size;
975 	size_t signal_event_count;
976 	bool signal_event_limit_reached;
977 
978 	/**
979 	 * @kfd_sigbus_delay_ms: Per-process KFD SIGBUS delivery option for
980 	 * poison/RAS events (set via DRM_IOCTL_AMDGPU_PROC_OPTIONS /
981 	 * AMDGPU_PROC_OPTIONS_OP_KFD_SIGBUS_DELAY).
982 	 *
983 	 *   0          - send SIGBUS immediately (default)
984 	 *   0xFFFFFFFF - suppress SIGBUS delivery
985 	 *   other      - delay SIGBUS delivery by this many milliseconds
986 	 */
987 	atomic_t kfd_sigbus_delay_ms;
988 
989 	/* Delayed signal delivery to user */
990 	struct delayed_work signal_work;
991 
992 	/* Information used for memory eviction */
993 	void *kgd_process_info;
994 	/* Eviction fence that is attached to all the BOs of this process. The
995 	 * fence will be triggered during eviction and new one will be created
996 	 * during restore
997 	 */
998 	struct dma_fence __rcu *ef;
999 
1000 	/* Work items for evicting and restoring BOs */
1001 	struct delayed_work eviction_work;
1002 	struct delayed_work restore_work;
1003 	/* seqno of the last scheduled eviction */
1004 	unsigned int last_eviction_seqno;
1005 	/* Approx. the last timestamp (in jiffies) when the process was
1006 	 * restored after an eviction
1007 	 */
1008 	unsigned long last_restore_timestamp;
1009 
1010 	/* Indicates device process is debug attached with reserved vmid. */
1011 	bool debug_trap_enabled;
1012 
1013 	/* per-process-per device debug event fd file */
1014 	struct file *dbg_ev_file;
1015 
1016 	/* If the process is a kfd debugger, we need to know so we can clean
1017 	 * up at exit time.  If a process enables debugging on itself, it does
1018 	 * its own clean-up, so we don't set the flag here.  We track this by
1019 	 * counting the number of processes this process is debugging.
1020 	 */
1021 	atomic_t debugged_process_count;
1022 
1023 	/* If the process is a debugged, this is the debugger process */
1024 	struct kfd_process *debugger_process;
1025 
1026 	/* Kobj for our procfs */
1027 	struct kobject *kobj;
1028 	struct kobject *kobj_queues;
1029 	struct attribute attr_pasid;
1030 
1031 	/* Exception code enable mask and status */
1032 	uint64_t exception_enable_mask;
1033 	uint64_t exception_status;
1034 
1035 	/* Used to drain stale interrupts */
1036 	wait_queue_head_t wait_irq_drain;
1037 	bool irq_drain_is_open;
1038 
1039 	/* shared virtual memory registered by this process */
1040 	struct svm_range_list svms;
1041 
1042 	bool xnack_enabled;
1043 
1044 	/* Work area for debugger event writer worker. */
1045 	struct work_struct debug_event_workarea;
1046 
1047 	/* Tracks debug per-vmid request for debug flags */
1048 	u32 dbg_flags;
1049 
1050 	atomic_t poison;
1051 	/* Queues are in paused stated because we are in the process of doing a CRIU checkpoint */
1052 	bool queues_paused;
1053 
1054 	/* Tracks runtime enable status */
1055 	struct semaphore runtime_enable_sema;
1056 	bool is_runtime_retry;
1057 	struct kfd_runtime_info runtime_info;
1058 
1059 	/* if gpu page fault sent to KFD */
1060 	bool gpu_page_fault;
1061 
1062 	/*kfd context id */
1063 	u16 context_id;
1064 
1065 	/* The primary kfd_process allocating IDs for its secondary kfd_process, 0 for primary kfd_process */
1066 	struct ida id_table;
1067 
1068 };
1069 
1070 #define KFD_PROCESS_TABLE_SIZE 8 /* bits: 256 entries */
1071 #define KFD_CONTEXT_ID_PRIMARY	0xFFFF
1072 #define KFD_CONTEXT_ID_MIN 0
1073 
1074 extern DECLARE_HASHTABLE(kfd_processes_table, KFD_PROCESS_TABLE_SIZE);
1075 extern struct srcu_struct kfd_processes_srcu;
1076 
1077 /**
1078  * typedef amdkfd_ioctl_t - typedef for ioctl function pointer.
1079  *
1080  * @filep: pointer to file structure.
1081  * @p: amdkfd process pointer.
1082  * @data: pointer to arg that was copied from user.
1083  *
1084  * Return: returns ioctl completion code.
1085  */
1086 typedef int amdkfd_ioctl_t(struct file *filep, struct kfd_process *p,
1087 				void *data);
1088 
1089 typedef int amdkfd_ioctl_validate_t(void *kdata, unsigned int usize);
1090 
1091 struct amdkfd_ioctl_desc {
1092 	unsigned int cmd;
1093 	int flags;
1094 	amdkfd_ioctl_t *func;
1095 	amdkfd_ioctl_validate_t *validate;
1096 	unsigned int cmd_drv;
1097 	const char *name;
1098 };
1099 bool kfd_dev_is_large_bar(struct kfd_node *dev);
1100 
1101 struct kfd_process *create_process(const struct task_struct *thread, bool primary);
1102 int kfd_process_create_wq(void);
1103 void kfd_process_destroy_wq(void);
1104 void kfd_cleanup_processes(void);
1105 struct kfd_process *kfd_create_process(struct task_struct *thread);
1106 int kfd_create_process_sysfs(struct kfd_process *process);
1107 struct kfd_process *kfd_lookup_process_by_pasid(u32 pasid,
1108 						 struct kfd_process_device **pdd);
1109 struct kfd_process *kfd_lookup_process_by_mm(const struct mm_struct *mm);
1110 struct kfd_process *kfd_lookup_process_by_id(const struct mm_struct *mm, u16 id);
1111 
1112 int kfd_process_gpuidx_from_gpuid(struct kfd_process *p, uint32_t gpu_id);
1113 int kfd_process_gpuid_from_node(struct kfd_process *p, struct kfd_node *node,
1114 				uint32_t *gpuid, uint32_t *gpuidx);
1115 static inline int kfd_process_gpuid_from_gpuidx(struct kfd_process *p,
1116 				uint32_t gpuidx, uint32_t *gpuid) {
1117 	return gpuidx < p->n_pdds ? p->pdds[gpuidx]->dev->id : -EINVAL;
1118 }
1119 static inline struct kfd_process_device *kfd_process_device_from_gpuidx(
1120 				struct kfd_process *p, uint32_t gpuidx) {
1121 	return gpuidx < p->n_pdds ? p->pdds[gpuidx] : NULL;
1122 }
1123 
1124 void kfd_unref_process(struct kfd_process *p);
1125 int kfd_process_evict_queues(struct kfd_process *p, uint32_t trigger);
1126 int kfd_process_restore_queues(struct kfd_process *p);
1127 void kfd_suspend_all_processes(void);
1128 int kfd_resume_all_processes(void);
1129 
1130 struct kfd_process_device *kfd_process_device_data_by_id(struct kfd_process *process,
1131 							 uint32_t gpu_id);
1132 
1133 int kfd_process_get_user_gpu_id(struct kfd_process *p, uint32_t actual_gpu_id);
1134 
1135 int kfd_process_device_init_vm(struct kfd_process_device *pdd,
1136 			       struct file *drm_file);
1137 struct kfd_process_device *kfd_bind_process_to_device(struct kfd_node *dev,
1138 						struct kfd_process *p);
1139 struct kfd_process_device *kfd_get_process_device_data(struct kfd_node *dev,
1140 							struct kfd_process *p);
1141 struct kfd_process_device *kfd_create_process_device_data(struct kfd_node *dev,
1142 							struct kfd_process *p);
1143 
1144 bool kfd_process_xnack_mode(struct kfd_process *p, bool supported);
1145 
1146 void kfd_process_notifier_release_internal(struct kfd_process *p);
1147 
1148 /* KFD process API for creating and translating handles */
1149 int kfd_process_device_create_obj_handle(struct kfd_process_device *pdd,
1150 					void *mem);
1151 void *kfd_process_device_translate_handle(struct kfd_process_device *p,
1152 					int handle);
1153 void kfd_process_device_remove_obj_handle(struct kfd_process_device *pdd,
1154 					int handle);
1155 struct kfd_process *kfd_lookup_process_by_pid(struct pid *pid);
1156 
1157 /* PASIDs */
1158 int kfd_pasid_init(void);
1159 void kfd_pasid_exit(void);
1160 u32 kfd_pasid_alloc(void);
1161 void kfd_pasid_free(u32 pasid);
1162 
1163 /* Doorbells */
1164 size_t kfd_doorbell_process_slice(struct kfd_dev *kfd);
1165 int kfd_doorbell_init(struct kfd_dev *kfd);
1166 void kfd_doorbell_fini(struct kfd_dev *kfd);
1167 int kfd_doorbell_mmap(struct kfd_node *dev, struct kfd_process *process,
1168 		      struct vm_area_struct *vma);
1169 void __iomem *kfd_get_kernel_doorbell(struct kfd_dev *kfd,
1170 					unsigned int *doorbell_off);
1171 void kfd_release_kernel_doorbell(struct kfd_dev *kfd, u32 __iomem *db_addr);
1172 u32 read_kernel_doorbell(u32 __iomem *db);
1173 void write_kernel_doorbell(void __iomem *db, u32 value);
1174 void write_kernel_doorbell64(void __iomem *db, u64 value);
1175 unsigned int kfd_get_doorbell_dw_offset_in_bar(struct kfd_dev *kfd,
1176 					struct kfd_process_device *pdd,
1177 					unsigned int doorbell_id);
1178 phys_addr_t kfd_get_process_doorbells(struct kfd_process_device *pdd);
1179 int kfd_alloc_process_doorbells(struct kfd_dev *kfd,
1180 				struct kfd_process_device *pdd);
1181 void kfd_free_process_doorbells(struct kfd_dev *kfd,
1182 				struct kfd_process_device *pdd);
1183 /* GTT Sub-Allocator */
1184 
1185 int kfd_gtt_sa_allocate(struct kfd_node *node, unsigned int size,
1186 			struct kfd_mem_obj **mem_obj);
1187 
1188 int kfd_gtt_sa_free(struct kfd_node *node, struct kfd_mem_obj *mem_obj);
1189 
1190 extern struct device *kfd_device;
1191 
1192 /* KFD's procfs */
1193 void kfd_procfs_init(void);
1194 void kfd_procfs_shutdown(void);
1195 int kfd_procfs_add_queue(struct queue *q);
1196 void kfd_procfs_del_queue(struct queue *q);
1197 
1198 /* Topology */
1199 int kfd_topology_init(void);
1200 void kfd_topology_shutdown(void);
1201 int kfd_topology_add_device(struct kfd_node *gpu);
1202 int kfd_topology_remove_device(struct kfd_node *gpu);
1203 struct kfd_topology_device *kfd_topology_device_by_proximity_domain(
1204 						uint32_t proximity_domain);
1205 struct kfd_topology_device *kfd_topology_device_by_proximity_domain_no_lock(
1206 						uint32_t proximity_domain);
1207 struct kfd_topology_device *kfd_topology_device_by_id(uint32_t gpu_id);
1208 struct kfd_node *kfd_device_by_id(uint32_t gpu_id);
1209 static inline bool kfd_irq_is_from_node(struct kfd_node *node, uint32_t node_id,
1210 					uint32_t vmid)
1211 {
1212 	return (node->interrupt_bitmap & (1 << node_id)) != 0 &&
1213 	       (node->compute_vmid_bitmap & (1 << vmid)) != 0;
1214 }
1215 static inline struct kfd_node *kfd_node_by_irq_ids(struct amdgpu_device *adev,
1216 					uint32_t node_id, uint32_t vmid) {
1217 	struct kfd_dev *dev = adev->kfd.dev;
1218 	uint32_t i;
1219 
1220 	/*
1221 	 * On multi-aid system, attempt per-node matching. Otherwise,
1222 	 * fall back to the first node.
1223 	 */
1224 	if (!amdgpu_is_multi_aid(adev))
1225 		return dev->nodes[0];
1226 
1227 	for (i = 0; i < dev->num_nodes; i++)
1228 		if (kfd_irq_is_from_node(dev->nodes[i], node_id, vmid))
1229 			return dev->nodes[i];
1230 
1231 	return NULL;
1232 }
1233 int kfd_topology_enum_kfd_devices(uint8_t idx, struct kfd_node **kdev);
1234 uint32_t kfd_topology_get_num_devices(void);
1235 int kfd_numa_node_to_apic_id(int numa_node_id);
1236 uint32_t kfd_gpu_node_num(void);
1237 
1238 /* Interrupts */
1239 #define	KFD_IRQ_FENCE_CLIENTID	0xff
1240 #define	KFD_IRQ_FENCE_SOURCEID	0xff
1241 #define	KFD_IRQ_IS_FENCE(client, source)				\
1242 				((client) == KFD_IRQ_FENCE_CLIENTID &&	\
1243 				(source) == KFD_IRQ_FENCE_SOURCEID)
1244 int kfd_interrupt_init(struct kfd_node *dev);
1245 void kfd_interrupt_exit(struct kfd_node *dev);
1246 bool enqueue_ih_ring_entry(struct kfd_node *kfd, const void *ih_ring_entry);
1247 bool interrupt_is_wanted(struct kfd_node *dev,
1248 				const uint32_t *ih_ring_entry,
1249 				uint32_t *patched_ihre, bool *flag);
1250 int kfd_process_drain_interrupts(struct kfd_process_device *pdd);
1251 void kfd_process_close_interrupt_drain(unsigned int pasid);
1252 
1253 /* amdkfd Apertures */
1254 int kfd_init_apertures(struct kfd_process *process);
1255 
1256 void kfd_process_set_trap_handler(struct qcm_process_device *qpd,
1257 				  uint64_t tba_addr,
1258 				  uint64_t tma_addr);
1259 void kfd_process_set_trap_debug_flag(struct qcm_process_device *qpd,
1260 				     bool enabled);
1261 
1262 /* CRIU */
1263 /*
1264  * Need to increment KFD_CRIU_PRIV_VERSION each time a change is made to any of the CRIU private
1265  * structures:
1266  * kfd_criu_process_priv_data
1267  * kfd_criu_device_priv_data
1268  * kfd_criu_bo_priv_data
1269  * kfd_criu_queue_priv_data
1270  * kfd_criu_event_priv_data
1271  * kfd_criu_svm_range_priv_data
1272  */
1273 
1274 #define KFD_CRIU_PRIV_VERSION 1
1275 
1276 struct kfd_criu_process_priv_data {
1277 	uint32_t version;
1278 	uint32_t xnack_mode;
1279 };
1280 
1281 struct kfd_criu_device_priv_data {
1282 	/* For future use */
1283 	uint64_t reserved;
1284 };
1285 
1286 struct kfd_criu_bo_priv_data {
1287 	uint64_t user_addr;
1288 	uint32_t idr_handle;
1289 	uint32_t mapped_gpuids[MAX_GPU_INSTANCE];
1290 };
1291 
1292 /*
1293  * The first 4 bytes of kfd_criu_queue_priv_data, kfd_criu_event_priv_data,
1294  * kfd_criu_svm_range_priv_data is the object type
1295  */
1296 enum kfd_criu_object_type {
1297 	KFD_CRIU_OBJECT_TYPE_QUEUE,
1298 	KFD_CRIU_OBJECT_TYPE_EVENT,
1299 	KFD_CRIU_OBJECT_TYPE_SVM_RANGE,
1300 };
1301 
1302 struct kfd_criu_svm_range_priv_data {
1303 	uint32_t object_type;
1304 	uint64_t start_addr;
1305 	uint64_t size;
1306 	/* Variable length array of attributes */
1307 	struct kfd_ioctl_svm_attribute attrs[];
1308 };
1309 
1310 struct kfd_criu_queue_priv_data {
1311 	uint32_t object_type;
1312 	uint64_t q_address;
1313 	uint64_t q_size;
1314 	uint64_t read_ptr_addr;
1315 	uint64_t write_ptr_addr;
1316 	uint64_t doorbell_off;
1317 	uint64_t eop_ring_buffer_address;
1318 	uint64_t ctx_save_restore_area_address;
1319 	uint32_t gpu_id;
1320 	uint32_t type;
1321 	uint32_t format;
1322 	uint32_t q_id;
1323 	uint32_t priority;
1324 	uint32_t q_percent;
1325 	uint32_t doorbell_id;
1326 	uint32_t gws;
1327 	uint32_t sdma_id;
1328 	uint32_t eop_ring_buffer_size;
1329 	uint32_t ctx_save_restore_area_size;
1330 	uint32_t ctl_stack_size;
1331 	uint32_t mqd_size;
1332 };
1333 
1334 struct kfd_criu_event_priv_data {
1335 	uint32_t object_type;
1336 	uint64_t user_handle;
1337 	uint32_t event_id;
1338 	uint32_t auto_reset;
1339 	uint32_t type;
1340 	uint32_t signaled;
1341 
1342 	union {
1343 		struct kfd_hsa_memory_exception_data memory_exception_data;
1344 		struct kfd_hsa_hw_exception_data hw_exception_data;
1345 	};
1346 };
1347 
1348 int kfd_process_get_queue_info(struct kfd_process *p,
1349 			       uint32_t *num_queues,
1350 			       uint64_t *priv_data_sizes);
1351 
1352 int kfd_criu_checkpoint_queues(struct kfd_process *p,
1353 			 uint8_t __user *user_priv_data,
1354 			 uint64_t *priv_data_offset);
1355 
1356 int kfd_criu_restore_queue(struct kfd_process *p,
1357 			   uint8_t __user *user_priv_data,
1358 			   uint64_t *priv_data_offset,
1359 			   uint64_t max_priv_data_size);
1360 
1361 int kfd_criu_checkpoint_events(struct kfd_process *p,
1362 			 uint8_t __user *user_priv_data,
1363 			 uint64_t *priv_data_offset);
1364 
1365 int kfd_criu_restore_event(struct file *devkfd,
1366 			   struct kfd_process *p,
1367 			   uint8_t __user *user_priv_data,
1368 			   uint64_t *priv_data_offset,
1369 			   uint64_t max_priv_data_size);
1370 /* CRIU - End */
1371 
1372 /* Queue Context Management */
1373 int init_queue(struct queue **q, const struct queue_properties *properties);
1374 void uninit_queue(struct queue *q);
1375 void print_queue_properties(struct queue_properties *q);
1376 void print_queue(struct queue *q);
1377 int kfd_queue_buffer_get(struct amdgpu_vm *vm, void __user *addr, struct amdgpu_bo **pbo,
1378 			 u64 expected_size);
1379 void kfd_queue_buffer_put(struct amdgpu_bo **bo);
1380 int kfd_queue_acquire_buffers(struct kfd_process_device *pdd, struct queue_properties *properties);
1381 int kfd_queue_release_buffers(struct kfd_process_device *pdd, struct queue_properties *properties);
1382 void kfd_queue_unref_bo_va(struct amdgpu_vm *vm, struct amdgpu_bo **bo);
1383 int kfd_queue_unref_bo_vas(struct kfd_process_device *pdd,
1384 			   struct queue_properties *properties);
1385 void kfd_queue_ctx_save_restore_size(struct kfd_topology_device *dev);
1386 
1387 struct mqd_manager *mqd_manager_init_cik(enum KFD_MQD_TYPE type,
1388 		struct kfd_node *dev);
1389 struct mqd_manager *mqd_manager_init_vi(enum KFD_MQD_TYPE type,
1390 		struct kfd_node *dev);
1391 struct mqd_manager *mqd_manager_init_v9(enum KFD_MQD_TYPE type,
1392 		struct kfd_node *dev);
1393 struct mqd_manager *mqd_manager_init_v10(enum KFD_MQD_TYPE type,
1394 		struct kfd_node *dev);
1395 struct mqd_manager *mqd_manager_init_v11(enum KFD_MQD_TYPE type,
1396 		struct kfd_node *dev);
1397 struct mqd_manager *mqd_manager_init_v12(enum KFD_MQD_TYPE type,
1398 		struct kfd_node *dev);
1399 struct mqd_manager *mqd_manager_init_v12_1(enum KFD_MQD_TYPE type,
1400 		struct kfd_node *dev);
1401 struct device_queue_manager *device_queue_manager_init(struct kfd_node *dev);
1402 void device_queue_manager_uninit(struct device_queue_manager *dqm);
1403 struct kernel_queue *kernel_queue_init(struct kfd_node *dev,
1404 					enum kfd_queue_type type);
1405 void kernel_queue_uninit(struct kernel_queue *kq);
1406 int kfd_evict_process_device(struct kfd_process_device *pdd);
1407 int kfd_dqm_suspend_bad_queue_mes(struct kfd_node *knode, u32 pasid, u32 doorbell_id);
1408 
1409 /* Process Queue Manager */
1410 struct process_queue_node {
1411 	struct queue *q;
1412 	struct kernel_queue *kq;
1413 	struct list_head process_queue_list;
1414 };
1415 
1416 void kfd_process_dequeue_from_device(struct kfd_process_device *pdd);
1417 void kfd_process_dequeue_from_all_devices(struct kfd_process *p);
1418 int pqm_init(struct process_queue_manager *pqm, struct kfd_process *p);
1419 void pqm_uninit(struct process_queue_manager *pqm);
1420 int pqm_create_queue(struct process_queue_manager *pqm,
1421 			    struct kfd_node *dev,
1422 			    struct queue_properties *properties,
1423 			    unsigned int *qid,
1424 			    const struct kfd_criu_queue_priv_data *q_data,
1425 			    const void *restore_mqd,
1426 			    const void *restore_ctl_stack,
1427 			    uint32_t *p_doorbell_offset_in_process);
1428 int pqm_destroy_queue(struct process_queue_manager *pqm, unsigned int qid);
1429 int pqm_update_queue_properties(struct process_queue_manager *pqm, unsigned int qid,
1430 			struct queue_properties *p);
1431 int pqm_update_mqd(struct process_queue_manager *pqm, unsigned int qid,
1432 			struct mqd_update_info *minfo);
1433 int pqm_set_gws(struct process_queue_manager *pqm, unsigned int qid,
1434 			void *gws);
1435 struct queue *pqm_get_user_queue(struct process_queue_manager *pqm,
1436 						unsigned int qid);
1437 int pqm_get_wave_state(struct process_queue_manager *pqm,
1438 		       unsigned int qid,
1439 		       void __user *ctl_stack,
1440 		       u32 *ctl_stack_used_size,
1441 		       u32 *save_area_used_size);
1442 int pqm_get_queue_snapshot(struct process_queue_manager *pqm,
1443 			   uint64_t exception_clear_mask,
1444 			   void __user *buf,
1445 			   int *num_qss_entries,
1446 			   uint32_t *entry_size);
1447 
1448 int amdkfd_fence_wait_timeout(struct device_queue_manager *dqm,
1449 			      uint64_t fence_value,
1450 			      unsigned int timeout_ms);
1451 
1452 int pqm_get_queue_checkpoint_info(struct process_queue_manager *pqm,
1453 				  unsigned int qid,
1454 				  u32 *mqd_size,
1455 				  u32 *ctl_stack_size);
1456 /* Packet Manager */
1457 
1458 #define KFD_FENCE_COMPLETED (100)
1459 #define KFD_FENCE_INIT   (10)
1460 
1461 /**
1462  * enum kfd_config_dequeue_wait_counts_cmd - Command for configuring
1463  *  dequeue wait counts.
1464  *
1465  * @KFD_DEQUEUE_WAIT_INIT: Set optimized dequeue wait counts for a
1466  *	certain ASICs. For these ASICs, this is default value used by RESET
1467  * @KFD_DEQUEUE_WAIT_RESET: Reset dequeue wait counts to the optimized value
1468  *	for certain ASICs. For others set it to default hardware reset value
1469  * @KFD_DEQUEUE_WAIT_SET_SCH_WAVE: Set context switch latency wait
1470  *
1471  */
1472 enum kfd_config_dequeue_wait_counts_cmd {
1473 	KFD_DEQUEUE_WAIT_INIT = 1,
1474 	KFD_DEQUEUE_WAIT_RESET = 2,
1475 	KFD_DEQUEUE_WAIT_SET_SCH_WAVE = 3
1476 };
1477 
1478 
1479 struct packet_manager {
1480 	struct device_queue_manager *dqm;
1481 	struct kernel_queue *priv_queue;
1482 	struct mutex lock;
1483 	bool allocated;
1484 	struct kfd_mem_obj *ib_buffer_obj;
1485 	unsigned int ib_size_bytes;
1486 	bool is_over_subscription;
1487 
1488 	const struct packet_manager_funcs *pmf;
1489 };
1490 
1491 struct packet_manager_funcs {
1492 	/* Support ASIC-specific packet formats for PM4 packets */
1493 	int (*map_process)(struct packet_manager *pm, uint32_t *buffer,
1494 			struct qcm_process_device *qpd);
1495 	int (*runlist)(struct packet_manager *pm, uint32_t *buffer,
1496 			uint64_t ib, size_t ib_size_in_dwords, bool chain);
1497 	int (*set_resources)(struct packet_manager *pm, uint32_t *buffer,
1498 			struct scheduling_resources *res);
1499 	int (*map_queues)(struct packet_manager *pm, uint32_t *buffer,
1500 			struct queue *q, bool is_static);
1501 	int (*unmap_queues)(struct packet_manager *pm, uint32_t *buffer,
1502 			enum kfd_unmap_queues_filter mode,
1503 			uint32_t filter_param, bool reset);
1504 	int (*config_dequeue_wait_counts)(struct packet_manager *pm, uint32_t *buffer,
1505 			enum kfd_config_dequeue_wait_counts_cmd cmd, uint32_t value);
1506 	int (*query_status)(struct packet_manager *pm, uint32_t *buffer,
1507 			uint64_t fence_address,	uint64_t fence_value);
1508 	int (*release_mem)(uint64_t gpu_addr, uint32_t *buffer);
1509 
1510 	/* Packet sizes */
1511 	int map_process_size;
1512 	int runlist_size;
1513 	int set_resources_size;
1514 	int map_queues_size;
1515 	int unmap_queues_size;
1516 	int config_dequeue_wait_counts_size;
1517 	int query_status_size;
1518 	int release_mem_size;
1519 };
1520 
1521 extern const struct packet_manager_funcs kfd_vi_pm_funcs;
1522 extern const struct packet_manager_funcs kfd_v9_pm_funcs;
1523 extern const struct packet_manager_funcs kfd_aldebaran_pm_funcs;
1524 
1525 int pm_init(struct packet_manager *pm, struct device_queue_manager *dqm);
1526 void pm_uninit(struct packet_manager *pm);
1527 int pm_send_set_resources(struct packet_manager *pm,
1528 				struct scheduling_resources *res);
1529 int pm_send_runlist(struct packet_manager *pm, struct list_head *dqm_queues);
1530 int pm_send_query_status(struct packet_manager *pm, uint64_t fence_address,
1531 				uint64_t fence_value);
1532 
1533 int pm_send_unmap_queue(struct packet_manager *pm,
1534 			enum kfd_unmap_queues_filter mode,
1535 			uint32_t filter_param, bool reset);
1536 
1537 void pm_release_ib(struct packet_manager *pm);
1538 
1539 int pm_config_dequeue_wait_counts(struct packet_manager *pm,
1540 			enum kfd_config_dequeue_wait_counts_cmd cmd,
1541 			uint32_t wait_counts_config);
1542 
1543 /* Following PM funcs can be shared among VI and AI */
1544 unsigned int pm_build_pm4_header(unsigned int opcode, size_t packet_size);
1545 
1546 uint64_t kfd_get_number_elems(struct kfd_dev *kfd);
1547 
1548 /* Events */
1549 extern const struct kfd_event_interrupt_class event_interrupt_class_cik;
1550 extern const struct kfd_event_interrupt_class event_interrupt_class_v9;
1551 extern const struct kfd_event_interrupt_class event_interrupt_class_v9_4_3;
1552 extern const struct kfd_event_interrupt_class event_interrupt_class_v10;
1553 extern const struct kfd_event_interrupt_class event_interrupt_class_v11;
1554 extern const struct kfd_event_interrupt_class event_interrupt_class_v12_1;
1555 
1556 extern const struct kfd_device_global_init_class device_global_init_class_cik;
1557 
1558 int kfd_event_init_process(struct kfd_process *p);
1559 void kfd_event_free_process(struct kfd_process *p);
1560 int kfd_wait_on_events(struct kfd_process *p,
1561 		       uint32_t num_events, void __user *data,
1562 		       bool all, uint32_t *user_timeout_ms,
1563 		       uint32_t *wait_result);
1564 void kfd_signal_event_interrupt(u32 pasid, uint32_t partial_id,
1565 				uint32_t valid_id_bits, bool signal_mailbox_updated);
1566 void kfd_signal_hw_exception_event(u32 pasid);
1567 int kfd_set_event(struct kfd_process *p, uint32_t event_id);
1568 int kfd_reset_event(struct kfd_process *p, uint32_t event_id);
1569 int kfd_kmap_event_page(struct kfd_process *p, uint64_t event_page_offset);
1570 
1571 int kfd_event_create(struct file *devkfd, struct kfd_process *p,
1572 		     uint32_t event_type, bool auto_reset, uint32_t node_id,
1573 		     uint32_t *event_id, uint32_t *event_trigger_data,
1574 		     uint64_t *event_page_offset, uint32_t *event_slot_index);
1575 
1576 int kfd_get_num_events(struct kfd_process *p);
1577 int kfd_event_destroy(struct kfd_process *p, uint32_t event_id);
1578 
1579 void kfd_signal_vm_fault_event_with_userptr(struct kfd_process *p, uint64_t gpu_va);
1580 
1581 void kfd_signal_vm_fault_event(struct kfd_process_device *pdd,
1582 				struct kfd_vm_fault_info *info,
1583 				struct kfd_hsa_memory_exception_data *data);
1584 
1585 void kfd_signal_reset_event(struct kfd_node *dev);
1586 
1587 void kfd_signal_poison_consumed_event(struct kfd_node *dev, u32 pasid);
1588 void kfd_signal_sigbus_delayed_fn(struct work_struct *work);
1589 void kfd_signal_process_terminate_event(struct kfd_process *p);
1590 
1591 static inline void kfd_flush_tlb(struct kfd_process_device *pdd)
1592 {
1593 	struct amdgpu_device *adev = pdd->dev->adev;
1594 	struct amdgpu_vm *vm = drm_priv_to_vm(pdd->drm_priv);
1595 
1596 	amdgpu_vm_flush_compute_tlb(adev, vm, TLB_FLUSH_HEAVYWEIGHT,
1597 				    pdd->dev->xcc_mask);
1598 }
1599 
1600 static inline bool kfd_flush_tlb_after_unmap(struct kfd_dev *dev)
1601 {
1602 	return KFD_GC_VERSION(dev) >= IP_VERSION(9, 4, 2) ||
1603 	       (KFD_GC_VERSION(dev) == IP_VERSION(9, 4, 1) && dev->sdma_fw_version >= 18) ||
1604 	       KFD_GC_VERSION(dev) == IP_VERSION(9, 4, 0);
1605 }
1606 
1607 int kfd_send_exception_to_runtime(struct kfd_process *p,
1608 				unsigned int queue_id,
1609 				uint64_t error_reason);
1610 bool kfd_is_locked(struct kfd_dev *kfd);
1611 
1612 /* Compute profile */
1613 void kfd_inc_compute_active(struct kfd_node *dev);
1614 void kfd_dec_compute_active(struct kfd_node *dev);
1615 
1616 /* Cgroup Support */
1617 /* Check with device cgroup if @kfd device is accessible */
1618 static inline int kfd_devcgroup_check_permission(struct kfd_node *node)
1619 {
1620 #if defined(CONFIG_CGROUP_DEVICE) || defined(CONFIG_CGROUP_BPF)
1621 	struct drm_device *ddev;
1622 
1623 	if (node->xcp)
1624 		ddev = node->xcp->ddev;
1625 	else
1626 		ddev = adev_to_drm(node->adev);
1627 
1628 	return devcgroup_check_permission(DEVCG_DEV_CHAR, DRM_MAJOR,
1629 					  ddev->render->index,
1630 					  DEVCG_ACC_WRITE | DEVCG_ACC_READ);
1631 #else
1632 	return 0;
1633 #endif
1634 }
1635 
1636 static inline bool kfd_is_first_node(struct kfd_node *node)
1637 {
1638 	return (node == node->kfd->nodes[0]);
1639 }
1640 
1641 /* PTL support */
1642 int kfd_ptl_disable_request(struct kfd_process_device *pdd,
1643 		struct kfd_process *p);
1644 int kfd_ptl_disable_release(struct kfd_process_device *pdd,
1645 		struct kfd_process *p);
1646 
1647 /* Debugfs */
1648 #if defined(CONFIG_DEBUG_FS)
1649 
1650 void kfd_debugfs_init(void);
1651 void kfd_debugfs_fini(void);
1652 int kfd_debugfs_mqds_by_process(struct seq_file *m, void *data);
1653 int pqm_debugfs_mqds(struct seq_file *m, void *data);
1654 int kfd_debugfs_hqds_by_device(struct seq_file *m, void *data);
1655 int dqm_debugfs_hqds(struct seq_file *m, void *data);
1656 int kfd_debugfs_rls_by_device(struct seq_file *m, void *data);
1657 int pm_debugfs_runlist(struct seq_file *m, void *data);
1658 
1659 int kfd_debugfs_hang_hws(struct kfd_node *dev);
1660 int pm_debugfs_hang_hws(struct packet_manager *pm);
1661 int dqm_debugfs_hang_hws(struct device_queue_manager *dqm);
1662 
1663 int kfd_debugfs_add_process(struct kfd_process *p);
1664 void kfd_debugfs_remove_process(struct kfd_process *p);
1665 
1666 #else
1667 
1668 static inline void kfd_debugfs_init(void) {}
1669 static inline void kfd_debugfs_fini(void) {}
1670 static inline int kfd_debugfs_add_process(struct kfd_process *p) { return 0; }
1671 static inline void kfd_debugfs_remove_process(struct kfd_process *p) {}
1672 
1673 #endif
1674 
1675 #endif
1676