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