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#include <linux/device.h>
25#include <linux/export.h>
26#include <linux/err.h>
27#include <linux/fs.h>
28#include <linux/file.h>
29#include <linux/sched.h>
30#include <linux/slab.h>
31#include <linux/uaccess.h>
32#include <linux/compat.h>
33#include <uapi/linux/kfd_ioctl.h>
34#include <linux/time.h>
35#include <linux/mm.h>
36#include <linux/mman.h>
37#include <linux/ptrace.h>
38#include <linux/dma-buf.h>
39#include <linux/fdtable.h>
40#include <linux/processor.h>
41#include "kfd_priv.h"
42#include "kfd_device_queue_manager.h"
43#include "kfd_svm.h"
44#include "amdgpu_amdkfd.h"
45#include "kfd_smi_events.h"
46#include "amdgpu_dma_buf.h"
47#include "kfd_debug.h"
48
49static long kfd_ioctl(struct file *, unsigned int, unsigned long);
50static int kfd_open(struct inode *, struct file *);
51static int kfd_release(struct inode *, struct file *);
52static int kfd_mmap(struct file *, struct vm_area_struct *);
53
54static const char kfd_dev_name[] = "kfd";
55
56static const struct file_operations kfd_fops = {
57	.owner = THIS_MODULE,
58	.unlocked_ioctl = kfd_ioctl,
59	.compat_ioctl = compat_ptr_ioctl,
60	.open = kfd_open,
61	.release = kfd_release,
62	.mmap = kfd_mmap,
63};
64
65static int kfd_char_dev_major = -1;
66struct device *kfd_device;
67static const struct class kfd_class = {
68	.name = kfd_dev_name,
69};
70
71static inline struct kfd_process_device *kfd_lock_pdd_by_id(struct kfd_process *p, __u32 gpu_id)
72{
73	struct kfd_process_device *pdd;
74
75	mutex_lock(&p->mutex);
76	pdd = kfd_process_device_data_by_id(p, gpu_id);
77
78	if (pdd)
79		return pdd;
80
81	mutex_unlock(&p->mutex);
82	return NULL;
83}
84
85static inline void kfd_unlock_pdd(struct kfd_process_device *pdd)
86{
87	mutex_unlock(&pdd->process->mutex);
88}
89
90int kfd_chardev_init(void)
91{
92	int err = 0;
93
94	kfd_char_dev_major = register_chrdev(0, kfd_dev_name, &kfd_fops);
95	err = kfd_char_dev_major;
96	if (err < 0)
97		goto err_register_chrdev;
98
99	err = class_register(&kfd_class);
100	if (err)
101		goto err_class_create;
102
103	kfd_device = device_create(&kfd_class, NULL,
104				   MKDEV(kfd_char_dev_major, 0),
105				   NULL, kfd_dev_name);
106	err = PTR_ERR(kfd_device);
107	if (IS_ERR(kfd_device))
108		goto err_device_create;
109
110	return 0;
111
112err_device_create:
113	class_unregister(&kfd_class);
114err_class_create:
115	unregister_chrdev(kfd_char_dev_major, kfd_dev_name);
116err_register_chrdev:
117	return err;
118}
119
120void kfd_chardev_exit(void)
121{
122	device_destroy(&kfd_class, MKDEV(kfd_char_dev_major, 0));
123	class_unregister(&kfd_class);
124	unregister_chrdev(kfd_char_dev_major, kfd_dev_name);
125	kfd_device = NULL;
126}
127
128
129static int kfd_open(struct inode *inode, struct file *filep)
130{
131	struct kfd_process *process;
132	bool is_32bit_user_mode;
133
134	if (iminor(inode) != 0)
135		return -ENODEV;
136
137	is_32bit_user_mode = in_compat_syscall();
138
139	if (is_32bit_user_mode) {
140		dev_warn(kfd_device,
141			"Process %d (32-bit) failed to open /dev/kfd\n"
142			"32-bit processes are not supported by amdkfd\n",
143			current->pid);
144		return -EPERM;
145	}
146
147	process = kfd_create_process(current);
148	if (IS_ERR(process))
149		return PTR_ERR(process);
150
151	if (kfd_process_init_cwsr_apu(process, filep)) {
152		kfd_unref_process(process);
153		return -EFAULT;
154	}
155
156	/* filep now owns the reference returned by kfd_create_process */
157	filep->private_data = process;
158
159	dev_dbg(kfd_device, "process %d opened, compat mode (32 bit) - %d\n",
160		process->pasid, process->is_32bit_user_mode);
161
162	return 0;
163}
164
165static int kfd_release(struct inode *inode, struct file *filep)
166{
167	struct kfd_process *process = filep->private_data;
168
169	if (process)
170		kfd_unref_process(process);
171
172	return 0;
173}
174
175static int kfd_ioctl_get_version(struct file *filep, struct kfd_process *p,
176					void *data)
177{
178	struct kfd_ioctl_get_version_args *args = data;
179
180	args->major_version = KFD_IOCTL_MAJOR_VERSION;
181	args->minor_version = KFD_IOCTL_MINOR_VERSION;
182
183	return 0;
184}
185
186static int set_queue_properties_from_user(struct queue_properties *q_properties,
187				struct kfd_ioctl_create_queue_args *args)
188{
189	/*
190	 * Repurpose queue percentage to accommodate new features:
191	 * bit 0-7: queue percentage
192	 * bit 8-15: pm4_target_xcc
193	 */
194	if ((args->queue_percentage & 0xFF) > KFD_MAX_QUEUE_PERCENTAGE) {
195		pr_err("Queue percentage must be between 0 to KFD_MAX_QUEUE_PERCENTAGE\n");
196		return -EINVAL;
197	}
198
199	if (args->queue_priority > KFD_MAX_QUEUE_PRIORITY) {
200		pr_err("Queue priority must be between 0 to KFD_MAX_QUEUE_PRIORITY\n");
201		return -EINVAL;
202	}
203
204	if ((args->ring_base_address) &&
205		(!access_ok((const void __user *) args->ring_base_address,
206			sizeof(uint64_t)))) {
207		pr_err("Can't access ring base address\n");
208		return -EFAULT;
209	}
210
211	if (!is_power_of_2(args->ring_size) && (args->ring_size != 0)) {
212		pr_err("Ring size must be a power of 2 or 0\n");
213		return -EINVAL;
214	}
215
216	if (!access_ok((const void __user *) args->read_pointer_address,
217			sizeof(uint32_t))) {
218		pr_err("Can't access read pointer\n");
219		return -EFAULT;
220	}
221
222	if (!access_ok((const void __user *) args->write_pointer_address,
223			sizeof(uint32_t))) {
224		pr_err("Can't access write pointer\n");
225		return -EFAULT;
226	}
227
228	if (args->eop_buffer_address &&
229		!access_ok((const void __user *) args->eop_buffer_address,
230			sizeof(uint32_t))) {
231		pr_debug("Can't access eop buffer");
232		return -EFAULT;
233	}
234
235	if (args->ctx_save_restore_address &&
236		!access_ok((const void __user *) args->ctx_save_restore_address,
237			sizeof(uint32_t))) {
238		pr_debug("Can't access ctx save restore buffer");
239		return -EFAULT;
240	}
241
242	q_properties->is_interop = false;
243	q_properties->is_gws = false;
244	q_properties->queue_percent = args->queue_percentage & 0xFF;
245	/* bit 8-15 are repurposed to be PM4 target XCC */
246	q_properties->pm4_target_xcc = (args->queue_percentage >> 8) & 0xFF;
247	q_properties->priority = args->queue_priority;
248	q_properties->queue_address = args->ring_base_address;
249	q_properties->queue_size = args->ring_size;
250	q_properties->read_ptr = (uint32_t *) args->read_pointer_address;
251	q_properties->write_ptr = (uint32_t *) args->write_pointer_address;
252	q_properties->eop_ring_buffer_address = args->eop_buffer_address;
253	q_properties->eop_ring_buffer_size = args->eop_buffer_size;
254	q_properties->ctx_save_restore_area_address =
255			args->ctx_save_restore_address;
256	q_properties->ctx_save_restore_area_size = args->ctx_save_restore_size;
257	q_properties->ctl_stack_size = args->ctl_stack_size;
258	if (args->queue_type == KFD_IOC_QUEUE_TYPE_COMPUTE ||
259		args->queue_type == KFD_IOC_QUEUE_TYPE_COMPUTE_AQL)
260		q_properties->type = KFD_QUEUE_TYPE_COMPUTE;
261	else if (args->queue_type == KFD_IOC_QUEUE_TYPE_SDMA)
262		q_properties->type = KFD_QUEUE_TYPE_SDMA;
263	else if (args->queue_type == KFD_IOC_QUEUE_TYPE_SDMA_XGMI)
264		q_properties->type = KFD_QUEUE_TYPE_SDMA_XGMI;
265	else
266		return -ENOTSUPP;
267
268	if (args->queue_type == KFD_IOC_QUEUE_TYPE_COMPUTE_AQL)
269		q_properties->format = KFD_QUEUE_FORMAT_AQL;
270	else
271		q_properties->format = KFD_QUEUE_FORMAT_PM4;
272
273	pr_debug("Queue Percentage: %d, %d\n",
274			q_properties->queue_percent, args->queue_percentage);
275
276	pr_debug("Queue Priority: %d, %d\n",
277			q_properties->priority, args->queue_priority);
278
279	pr_debug("Queue Address: 0x%llX, 0x%llX\n",
280			q_properties->queue_address, args->ring_base_address);
281
282	pr_debug("Queue Size: 0x%llX, %u\n",
283			q_properties->queue_size, args->ring_size);
284
285	pr_debug("Queue r/w Pointers: %px, %px\n",
286			q_properties->read_ptr,
287			q_properties->write_ptr);
288
289	pr_debug("Queue Format: %d\n", q_properties->format);
290
291	pr_debug("Queue EOP: 0x%llX\n", q_properties->eop_ring_buffer_address);
292
293	pr_debug("Queue CTX save area: 0x%llX\n",
294			q_properties->ctx_save_restore_area_address);
295
296	return 0;
297}
298
299static int kfd_ioctl_create_queue(struct file *filep, struct kfd_process *p,
300					void *data)
301{
302	struct kfd_ioctl_create_queue_args *args = data;
303	struct kfd_node *dev;
304	int err = 0;
305	unsigned int queue_id;
306	struct kfd_process_device *pdd;
307	struct queue_properties q_properties;
308	uint32_t doorbell_offset_in_process = 0;
309	struct amdgpu_bo *wptr_bo = NULL;
310
311	memset(&q_properties, 0, sizeof(struct queue_properties));
312
313	pr_debug("Creating queue ioctl\n");
314
315	err = set_queue_properties_from_user(&q_properties, args);
316	if (err)
317		return err;
318
319	pr_debug("Looking for gpu id 0x%x\n", args->gpu_id);
320
321	mutex_lock(&p->mutex);
322
323	pdd = kfd_process_device_data_by_id(p, args->gpu_id);
324	if (!pdd) {
325		pr_debug("Could not find gpu id 0x%x\n", args->gpu_id);
326		err = -EINVAL;
327		goto err_pdd;
328	}
329	dev = pdd->dev;
330
331	pdd = kfd_bind_process_to_device(dev, p);
332	if (IS_ERR(pdd)) {
333		err = -ESRCH;
334		goto err_bind_process;
335	}
336
337	if (!pdd->qpd.proc_doorbells) {
338		err = kfd_alloc_process_doorbells(dev->kfd, pdd);
339		if (err) {
340			pr_debug("failed to allocate process doorbells\n");
341			goto err_bind_process;
342		}
343	}
344
345	/* Starting with GFX11, wptr BOs must be mapped to GART for MES to determine work
346	 * on unmapped queues for usermode queue oversubscription (no aggregated doorbell)
347	 */
348	if (dev->kfd->shared_resources.enable_mes &&
349			((dev->adev->mes.sched_version & AMDGPU_MES_API_VERSION_MASK)
350			>> AMDGPU_MES_API_VERSION_SHIFT) >= 2) {
351		struct amdgpu_bo_va_mapping *wptr_mapping;
352		struct amdgpu_vm *wptr_vm;
353
354		wptr_vm = drm_priv_to_vm(pdd->drm_priv);
355		err = amdgpu_bo_reserve(wptr_vm->root.bo, false);
356		if (err)
357			goto err_wptr_map_gart;
358
359		wptr_mapping = amdgpu_vm_bo_lookup_mapping(
360				wptr_vm, args->write_pointer_address >> PAGE_SHIFT);
361		amdgpu_bo_unreserve(wptr_vm->root.bo);
362		if (!wptr_mapping) {
363			pr_err("Failed to lookup wptr bo\n");
364			err = -EINVAL;
365			goto err_wptr_map_gart;
366		}
367
368		wptr_bo = wptr_mapping->bo_va->base.bo;
369		if (wptr_bo->tbo.base.size > PAGE_SIZE) {
370			pr_err("Requested GART mapping for wptr bo larger than one page\n");
371			err = -EINVAL;
372			goto err_wptr_map_gart;
373		}
374
375		err = amdgpu_amdkfd_map_gtt_bo_to_gart(wptr_bo);
376		if (err) {
377			pr_err("Failed to map wptr bo to GART\n");
378			goto err_wptr_map_gart;
379		}
380	}
381
382	pr_debug("Creating queue for PASID 0x%x on gpu 0x%x\n",
383			p->pasid,
384			dev->id);
385
386	err = pqm_create_queue(&p->pqm, dev, filep, &q_properties, &queue_id, wptr_bo,
387			NULL, NULL, NULL, &doorbell_offset_in_process);
388	if (err != 0)
389		goto err_create_queue;
390
391	args->queue_id = queue_id;
392
393
394	/* Return gpu_id as doorbell offset for mmap usage */
395	args->doorbell_offset = KFD_MMAP_TYPE_DOORBELL;
396	args->doorbell_offset |= KFD_MMAP_GPU_ID(args->gpu_id);
397	if (KFD_IS_SOC15(dev))
398		/* On SOC15 ASICs, include the doorbell offset within the
399		 * process doorbell frame, which is 2 pages.
400		 */
401		args->doorbell_offset |= doorbell_offset_in_process;
402
403	mutex_unlock(&p->mutex);
404
405	pr_debug("Queue id %d was created successfully\n", args->queue_id);
406
407	pr_debug("Ring buffer address == 0x%016llX\n",
408			args->ring_base_address);
409
410	pr_debug("Read ptr address    == 0x%016llX\n",
411			args->read_pointer_address);
412
413	pr_debug("Write ptr address   == 0x%016llX\n",
414			args->write_pointer_address);
415
416	kfd_dbg_ev_raise(KFD_EC_MASK(EC_QUEUE_NEW), p, dev, queue_id, false, NULL, 0);
417	return 0;
418
419err_create_queue:
420	if (wptr_bo)
421		amdgpu_amdkfd_free_gtt_mem(dev->adev, wptr_bo);
422err_wptr_map_gart:
423err_bind_process:
424err_pdd:
425	mutex_unlock(&p->mutex);
426	return err;
427}
428
429static int kfd_ioctl_destroy_queue(struct file *filp, struct kfd_process *p,
430					void *data)
431{
432	int retval;
433	struct kfd_ioctl_destroy_queue_args *args = data;
434
435	pr_debug("Destroying queue id %d for pasid 0x%x\n",
436				args->queue_id,
437				p->pasid);
438
439	mutex_lock(&p->mutex);
440
441	retval = pqm_destroy_queue(&p->pqm, args->queue_id);
442
443	mutex_unlock(&p->mutex);
444	return retval;
445}
446
447static int kfd_ioctl_update_queue(struct file *filp, struct kfd_process *p,
448					void *data)
449{
450	int retval;
451	struct kfd_ioctl_update_queue_args *args = data;
452	struct queue_properties properties;
453
454	/*
455	 * Repurpose queue percentage to accommodate new features:
456	 * bit 0-7: queue percentage
457	 * bit 8-15: pm4_target_xcc
458	 */
459	if ((args->queue_percentage & 0xFF) > KFD_MAX_QUEUE_PERCENTAGE) {
460		pr_err("Queue percentage must be between 0 to KFD_MAX_QUEUE_PERCENTAGE\n");
461		return -EINVAL;
462	}
463
464	if (args->queue_priority > KFD_MAX_QUEUE_PRIORITY) {
465		pr_err("Queue priority must be between 0 to KFD_MAX_QUEUE_PRIORITY\n");
466		return -EINVAL;
467	}
468
469	if ((args->ring_base_address) &&
470		(!access_ok((const void __user *) args->ring_base_address,
471			sizeof(uint64_t)))) {
472		pr_err("Can't access ring base address\n");
473		return -EFAULT;
474	}
475
476	if (!is_power_of_2(args->ring_size) && (args->ring_size != 0)) {
477		pr_err("Ring size must be a power of 2 or 0\n");
478		return -EINVAL;
479	}
480
481	properties.queue_address = args->ring_base_address;
482	properties.queue_size = args->ring_size;
483	properties.queue_percent = args->queue_percentage & 0xFF;
484	/* bit 8-15 are repurposed to be PM4 target XCC */
485	properties.pm4_target_xcc = (args->queue_percentage >> 8) & 0xFF;
486	properties.priority = args->queue_priority;
487
488	pr_debug("Updating queue id %d for pasid 0x%x\n",
489			args->queue_id, p->pasid);
490
491	mutex_lock(&p->mutex);
492
493	retval = pqm_update_queue_properties(&p->pqm, args->queue_id, &properties);
494
495	mutex_unlock(&p->mutex);
496
497	return retval;
498}
499
500static int kfd_ioctl_set_cu_mask(struct file *filp, struct kfd_process *p,
501					void *data)
502{
503	int retval;
504	const int max_num_cus = 1024;
505	struct kfd_ioctl_set_cu_mask_args *args = data;
506	struct mqd_update_info minfo = {0};
507	uint32_t __user *cu_mask_ptr = (uint32_t __user *)args->cu_mask_ptr;
508	size_t cu_mask_size = sizeof(uint32_t) * (args->num_cu_mask / 32);
509
510	if ((args->num_cu_mask % 32) != 0) {
511		pr_debug("num_cu_mask 0x%x must be a multiple of 32",
512				args->num_cu_mask);
513		return -EINVAL;
514	}
515
516	minfo.cu_mask.count = args->num_cu_mask;
517	if (minfo.cu_mask.count == 0) {
518		pr_debug("CU mask cannot be 0");
519		return -EINVAL;
520	}
521
522	/* To prevent an unreasonably large CU mask size, set an arbitrary
523	 * limit of max_num_cus bits.  We can then just drop any CU mask bits
524	 * past max_num_cus bits and just use the first max_num_cus bits.
525	 */
526	if (minfo.cu_mask.count > max_num_cus) {
527		pr_debug("CU mask cannot be greater than 1024 bits");
528		minfo.cu_mask.count = max_num_cus;
529		cu_mask_size = sizeof(uint32_t) * (max_num_cus/32);
530	}
531
532	minfo.cu_mask.ptr = kzalloc(cu_mask_size, GFP_KERNEL);
533	if (!minfo.cu_mask.ptr)
534		return -ENOMEM;
535
536	retval = copy_from_user(minfo.cu_mask.ptr, cu_mask_ptr, cu_mask_size);
537	if (retval) {
538		pr_debug("Could not copy CU mask from userspace");
539		retval = -EFAULT;
540		goto out;
541	}
542
543	mutex_lock(&p->mutex);
544
545	retval = pqm_update_mqd(&p->pqm, args->queue_id, &minfo);
546
547	mutex_unlock(&p->mutex);
548
549out:
550	kfree(minfo.cu_mask.ptr);
551	return retval;
552}
553
554static int kfd_ioctl_get_queue_wave_state(struct file *filep,
555					  struct kfd_process *p, void *data)
556{
557	struct kfd_ioctl_get_queue_wave_state_args *args = data;
558	int r;
559
560	mutex_lock(&p->mutex);
561
562	r = pqm_get_wave_state(&p->pqm, args->queue_id,
563			       (void __user *)args->ctl_stack_address,
564			       &args->ctl_stack_used_size,
565			       &args->save_area_used_size);
566
567	mutex_unlock(&p->mutex);
568
569	return r;
570}
571
572static int kfd_ioctl_set_memory_policy(struct file *filep,
573					struct kfd_process *p, void *data)
574{
575	struct kfd_ioctl_set_memory_policy_args *args = data;
576	int err = 0;
577	struct kfd_process_device *pdd;
578	enum cache_policy default_policy, alternate_policy;
579
580	if (args->default_policy != KFD_IOC_CACHE_POLICY_COHERENT
581	    && args->default_policy != KFD_IOC_CACHE_POLICY_NONCOHERENT) {
582		return -EINVAL;
583	}
584
585	if (args->alternate_policy != KFD_IOC_CACHE_POLICY_COHERENT
586	    && args->alternate_policy != KFD_IOC_CACHE_POLICY_NONCOHERENT) {
587		return -EINVAL;
588	}
589
590	mutex_lock(&p->mutex);
591	pdd = kfd_process_device_data_by_id(p, args->gpu_id);
592	if (!pdd) {
593		pr_debug("Could not find gpu id 0x%x\n", args->gpu_id);
594		err = -EINVAL;
595		goto err_pdd;
596	}
597
598	pdd = kfd_bind_process_to_device(pdd->dev, p);
599	if (IS_ERR(pdd)) {
600		err = -ESRCH;
601		goto out;
602	}
603
604	default_policy = (args->default_policy == KFD_IOC_CACHE_POLICY_COHERENT)
605			 ? cache_policy_coherent : cache_policy_noncoherent;
606
607	alternate_policy =
608		(args->alternate_policy == KFD_IOC_CACHE_POLICY_COHERENT)
609		   ? cache_policy_coherent : cache_policy_noncoherent;
610
611	if (!pdd->dev->dqm->ops.set_cache_memory_policy(pdd->dev->dqm,
612				&pdd->qpd,
613				default_policy,
614				alternate_policy,
615				(void __user *)args->alternate_aperture_base,
616				args->alternate_aperture_size))
617		err = -EINVAL;
618
619out:
620err_pdd:
621	mutex_unlock(&p->mutex);
622
623	return err;
624}
625
626static int kfd_ioctl_set_trap_handler(struct file *filep,
627					struct kfd_process *p, void *data)
628{
629	struct kfd_ioctl_set_trap_handler_args *args = data;
630	int err = 0;
631	struct kfd_process_device *pdd;
632
633	mutex_lock(&p->mutex);
634
635	pdd = kfd_process_device_data_by_id(p, args->gpu_id);
636	if (!pdd) {
637		err = -EINVAL;
638		goto err_pdd;
639	}
640
641	pdd = kfd_bind_process_to_device(pdd->dev, p);
642	if (IS_ERR(pdd)) {
643		err = -ESRCH;
644		goto out;
645	}
646
647	kfd_process_set_trap_handler(&pdd->qpd, args->tba_addr, args->tma_addr);
648
649out:
650err_pdd:
651	mutex_unlock(&p->mutex);
652
653	return err;
654}
655
656static int kfd_ioctl_dbg_register(struct file *filep,
657				struct kfd_process *p, void *data)
658{
659	return -EPERM;
660}
661
662static int kfd_ioctl_dbg_unregister(struct file *filep,
663				struct kfd_process *p, void *data)
664{
665	return -EPERM;
666}
667
668static int kfd_ioctl_dbg_address_watch(struct file *filep,
669					struct kfd_process *p, void *data)
670{
671	return -EPERM;
672}
673
674/* Parse and generate fixed size data structure for wave control */
675static int kfd_ioctl_dbg_wave_control(struct file *filep,
676					struct kfd_process *p, void *data)
677{
678	return -EPERM;
679}
680
681static int kfd_ioctl_get_clock_counters(struct file *filep,
682				struct kfd_process *p, void *data)
683{
684	struct kfd_ioctl_get_clock_counters_args *args = data;
685	struct kfd_process_device *pdd;
686
687	mutex_lock(&p->mutex);
688	pdd = kfd_process_device_data_by_id(p, args->gpu_id);
689	mutex_unlock(&p->mutex);
690	if (pdd)
691		/* Reading GPU clock counter from KGD */
692		args->gpu_clock_counter = amdgpu_amdkfd_get_gpu_clock_counter(pdd->dev->adev);
693	else
694		/* Node without GPU resource */
695		args->gpu_clock_counter = 0;
696
697	/* No access to rdtsc. Using raw monotonic time */
698	args->cpu_clock_counter = ktime_get_raw_ns();
699	args->system_clock_counter = ktime_get_boottime_ns();
700
701	/* Since the counter is in nano-seconds we use 1GHz frequency */
702	args->system_clock_freq = 1000000000;
703
704	return 0;
705}
706
707
708static int kfd_ioctl_get_process_apertures(struct file *filp,
709				struct kfd_process *p, void *data)
710{
711	struct kfd_ioctl_get_process_apertures_args *args = data;
712	struct kfd_process_device_apertures *pAperture;
713	int i;
714
715	dev_dbg(kfd_device, "get apertures for PASID 0x%x", p->pasid);
716
717	args->num_of_nodes = 0;
718
719	mutex_lock(&p->mutex);
720	/* Run over all pdd of the process */
721	for (i = 0; i < p->n_pdds; i++) {
722		struct kfd_process_device *pdd = p->pdds[i];
723
724		pAperture =
725			&args->process_apertures[args->num_of_nodes];
726		pAperture->gpu_id = pdd->dev->id;
727		pAperture->lds_base = pdd->lds_base;
728		pAperture->lds_limit = pdd->lds_limit;
729		pAperture->gpuvm_base = pdd->gpuvm_base;
730		pAperture->gpuvm_limit = pdd->gpuvm_limit;
731		pAperture->scratch_base = pdd->scratch_base;
732		pAperture->scratch_limit = pdd->scratch_limit;
733
734		dev_dbg(kfd_device,
735			"node id %u\n", args->num_of_nodes);
736		dev_dbg(kfd_device,
737			"gpu id %u\n", pdd->dev->id);
738		dev_dbg(kfd_device,
739			"lds_base %llX\n", pdd->lds_base);
740		dev_dbg(kfd_device,
741			"lds_limit %llX\n", pdd->lds_limit);
742		dev_dbg(kfd_device,
743			"gpuvm_base %llX\n", pdd->gpuvm_base);
744		dev_dbg(kfd_device,
745			"gpuvm_limit %llX\n", pdd->gpuvm_limit);
746		dev_dbg(kfd_device,
747			"scratch_base %llX\n", pdd->scratch_base);
748		dev_dbg(kfd_device,
749			"scratch_limit %llX\n", pdd->scratch_limit);
750
751		if (++args->num_of_nodes >= NUM_OF_SUPPORTED_GPUS)
752			break;
753	}
754	mutex_unlock(&p->mutex);
755
756	return 0;
757}
758
759static int kfd_ioctl_get_process_apertures_new(struct file *filp,
760				struct kfd_process *p, void *data)
761{
762	struct kfd_ioctl_get_process_apertures_new_args *args = data;
763	struct kfd_process_device_apertures *pa;
764	int ret;
765	int i;
766
767	dev_dbg(kfd_device, "get apertures for PASID 0x%x", p->pasid);
768
769	if (args->num_of_nodes == 0) {
770		/* Return number of nodes, so that user space can alloacate
771		 * sufficient memory
772		 */
773		mutex_lock(&p->mutex);
774		args->num_of_nodes = p->n_pdds;
775		goto out_unlock;
776	}
777
778	/* Fill in process-aperture information for all available
779	 * nodes, but not more than args->num_of_nodes as that is
780	 * the amount of memory allocated by user
781	 */
782	pa = kcalloc(args->num_of_nodes, sizeof(struct kfd_process_device_apertures),
783		     GFP_KERNEL);
784	if (!pa)
785		return -ENOMEM;
786
787	mutex_lock(&p->mutex);
788
789	if (!p->n_pdds) {
790		args->num_of_nodes = 0;
791		kfree(pa);
792		goto out_unlock;
793	}
794
795	/* Run over all pdd of the process */
796	for (i = 0; i < min(p->n_pdds, args->num_of_nodes); i++) {
797		struct kfd_process_device *pdd = p->pdds[i];
798
799		pa[i].gpu_id = pdd->dev->id;
800		pa[i].lds_base = pdd->lds_base;
801		pa[i].lds_limit = pdd->lds_limit;
802		pa[i].gpuvm_base = pdd->gpuvm_base;
803		pa[i].gpuvm_limit = pdd->gpuvm_limit;
804		pa[i].scratch_base = pdd->scratch_base;
805		pa[i].scratch_limit = pdd->scratch_limit;
806
807		dev_dbg(kfd_device,
808			"gpu id %u\n", pdd->dev->id);
809		dev_dbg(kfd_device,
810			"lds_base %llX\n", pdd->lds_base);
811		dev_dbg(kfd_device,
812			"lds_limit %llX\n", pdd->lds_limit);
813		dev_dbg(kfd_device,
814			"gpuvm_base %llX\n", pdd->gpuvm_base);
815		dev_dbg(kfd_device,
816			"gpuvm_limit %llX\n", pdd->gpuvm_limit);
817		dev_dbg(kfd_device,
818			"scratch_base %llX\n", pdd->scratch_base);
819		dev_dbg(kfd_device,
820			"scratch_limit %llX\n", pdd->scratch_limit);
821	}
822	mutex_unlock(&p->mutex);
823
824	args->num_of_nodes = i;
825	ret = copy_to_user(
826			(void __user *)args->kfd_process_device_apertures_ptr,
827			pa,
828			(i * sizeof(struct kfd_process_device_apertures)));
829	kfree(pa);
830	return ret ? -EFAULT : 0;
831
832out_unlock:
833	mutex_unlock(&p->mutex);
834	return 0;
835}
836
837static int kfd_ioctl_create_event(struct file *filp, struct kfd_process *p,
838					void *data)
839{
840	struct kfd_ioctl_create_event_args *args = data;
841	int err;
842
843	/* For dGPUs the event page is allocated in user mode. The
844	 * handle is passed to KFD with the first call to this IOCTL
845	 * through the event_page_offset field.
846	 */
847	if (args->event_page_offset) {
848		mutex_lock(&p->mutex);
849		err = kfd_kmap_event_page(p, args->event_page_offset);
850		mutex_unlock(&p->mutex);
851		if (err)
852			return err;
853	}
854
855	err = kfd_event_create(filp, p, args->event_type,
856				args->auto_reset != 0, args->node_id,
857				&args->event_id, &args->event_trigger_data,
858				&args->event_page_offset,
859				&args->event_slot_index);
860
861	pr_debug("Created event (id:0x%08x) (%s)\n", args->event_id, __func__);
862	return err;
863}
864
865static int kfd_ioctl_destroy_event(struct file *filp, struct kfd_process *p,
866					void *data)
867{
868	struct kfd_ioctl_destroy_event_args *args = data;
869
870	return kfd_event_destroy(p, args->event_id);
871}
872
873static int kfd_ioctl_set_event(struct file *filp, struct kfd_process *p,
874				void *data)
875{
876	struct kfd_ioctl_set_event_args *args = data;
877
878	return kfd_set_event(p, args->event_id);
879}
880
881static int kfd_ioctl_reset_event(struct file *filp, struct kfd_process *p,
882				void *data)
883{
884	struct kfd_ioctl_reset_event_args *args = data;
885
886	return kfd_reset_event(p, args->event_id);
887}
888
889static int kfd_ioctl_wait_events(struct file *filp, struct kfd_process *p,
890				void *data)
891{
892	struct kfd_ioctl_wait_events_args *args = data;
893
894	return kfd_wait_on_events(p, args->num_events,
895			(void __user *)args->events_ptr,
896			(args->wait_for_all != 0),
897			&args->timeout, &args->wait_result);
898}
899static int kfd_ioctl_set_scratch_backing_va(struct file *filep,
900					struct kfd_process *p, void *data)
901{
902	struct kfd_ioctl_set_scratch_backing_va_args *args = data;
903	struct kfd_process_device *pdd;
904	struct kfd_node *dev;
905	long err;
906
907	mutex_lock(&p->mutex);
908	pdd = kfd_process_device_data_by_id(p, args->gpu_id);
909	if (!pdd) {
910		err = -EINVAL;
911		goto err_pdd;
912	}
913	dev = pdd->dev;
914
915	pdd = kfd_bind_process_to_device(dev, p);
916	if (IS_ERR(pdd)) {
917		err = PTR_ERR(pdd);
918		goto bind_process_to_device_fail;
919	}
920
921	pdd->qpd.sh_hidden_private_base = args->va_addr;
922
923	mutex_unlock(&p->mutex);
924
925	if (dev->dqm->sched_policy == KFD_SCHED_POLICY_NO_HWS &&
926	    pdd->qpd.vmid != 0 && dev->kfd2kgd->set_scratch_backing_va)
927		dev->kfd2kgd->set_scratch_backing_va(
928			dev->adev, args->va_addr, pdd->qpd.vmid);
929
930	return 0;
931
932bind_process_to_device_fail:
933err_pdd:
934	mutex_unlock(&p->mutex);
935	return err;
936}
937
938static int kfd_ioctl_get_tile_config(struct file *filep,
939		struct kfd_process *p, void *data)
940{
941	struct kfd_ioctl_get_tile_config_args *args = data;
942	struct kfd_process_device *pdd;
943	struct tile_config config;
944	int err = 0;
945
946	mutex_lock(&p->mutex);
947	pdd = kfd_process_device_data_by_id(p, args->gpu_id);
948	mutex_unlock(&p->mutex);
949	if (!pdd)
950		return -EINVAL;
951
952	amdgpu_amdkfd_get_tile_config(pdd->dev->adev, &config);
953
954	args->gb_addr_config = config.gb_addr_config;
955	args->num_banks = config.num_banks;
956	args->num_ranks = config.num_ranks;
957
958	if (args->num_tile_configs > config.num_tile_configs)
959		args->num_tile_configs = config.num_tile_configs;
960	err = copy_to_user((void __user *)args->tile_config_ptr,
961			config.tile_config_ptr,
962			args->num_tile_configs * sizeof(uint32_t));
963	if (err) {
964		args->num_tile_configs = 0;
965		return -EFAULT;
966	}
967
968	if (args->num_macro_tile_configs > config.num_macro_tile_configs)
969		args->num_macro_tile_configs =
970				config.num_macro_tile_configs;
971	err = copy_to_user((void __user *)args->macro_tile_config_ptr,
972			config.macro_tile_config_ptr,
973			args->num_macro_tile_configs * sizeof(uint32_t));
974	if (err) {
975		args->num_macro_tile_configs = 0;
976		return -EFAULT;
977	}
978
979	return 0;
980}
981
982static int kfd_ioctl_acquire_vm(struct file *filep, struct kfd_process *p,
983				void *data)
984{
985	struct kfd_ioctl_acquire_vm_args *args = data;
986	struct kfd_process_device *pdd;
987	struct file *drm_file;
988	int ret;
989
990	drm_file = fget(args->drm_fd);
991	if (!drm_file)
992		return -EINVAL;
993
994	mutex_lock(&p->mutex);
995	pdd = kfd_process_device_data_by_id(p, args->gpu_id);
996	if (!pdd) {
997		ret = -EINVAL;
998		goto err_pdd;
999	}
1000
1001	if (pdd->drm_file) {
1002		ret = pdd->drm_file == drm_file ? 0 : -EBUSY;
1003		goto err_drm_file;
1004	}
1005
1006	ret = kfd_process_device_init_vm(pdd, drm_file);
1007	if (ret)
1008		goto err_unlock;
1009
1010	/* On success, the PDD keeps the drm_file reference */
1011	mutex_unlock(&p->mutex);
1012
1013	return 0;
1014
1015err_unlock:
1016err_pdd:
1017err_drm_file:
1018	mutex_unlock(&p->mutex);
1019	fput(drm_file);
1020	return ret;
1021}
1022
1023bool kfd_dev_is_large_bar(struct kfd_node *dev)
1024{
1025	if (dev->kfd->adev->debug_largebar) {
1026		pr_debug("Simulate large-bar allocation on non large-bar machine\n");
1027		return true;
1028	}
1029
1030	if (dev->local_mem_info.local_mem_size_private == 0 &&
1031	    dev->local_mem_info.local_mem_size_public > 0)
1032		return true;
1033
1034	if (dev->local_mem_info.local_mem_size_public == 0 &&
1035	    dev->kfd->adev->gmc.is_app_apu) {
1036		pr_debug("APP APU, Consider like a large bar system\n");
1037		return true;
1038	}
1039
1040	return false;
1041}
1042
1043static int kfd_ioctl_get_available_memory(struct file *filep,
1044					  struct kfd_process *p, void *data)
1045{
1046	struct kfd_ioctl_get_available_memory_args *args = data;
1047	struct kfd_process_device *pdd = kfd_lock_pdd_by_id(p, args->gpu_id);
1048
1049	if (!pdd)
1050		return -EINVAL;
1051	args->available = amdgpu_amdkfd_get_available_memory(pdd->dev->adev,
1052							pdd->dev->node_id);
1053	kfd_unlock_pdd(pdd);
1054	return 0;
1055}
1056
1057static int kfd_ioctl_alloc_memory_of_gpu(struct file *filep,
1058					struct kfd_process *p, void *data)
1059{
1060	struct kfd_ioctl_alloc_memory_of_gpu_args *args = data;
1061	struct kfd_process_device *pdd;
1062	void *mem;
1063	struct kfd_node *dev;
1064	int idr_handle;
1065	long err;
1066	uint64_t offset = args->mmap_offset;
1067	uint32_t flags = args->flags;
1068
1069	if (args->size == 0)
1070		return -EINVAL;
1071
1072#if IS_ENABLED(CONFIG_HSA_AMD_SVM)
1073	/* Flush pending deferred work to avoid racing with deferred actions
1074	 * from previous memory map changes (e.g. munmap).
1075	 */
1076	svm_range_list_lock_and_flush_work(&p->svms, current->mm);
1077	mutex_lock(&p->svms.lock);
1078	mmap_write_unlock(current->mm);
1079	if (interval_tree_iter_first(&p->svms.objects,
1080				     args->va_addr >> PAGE_SHIFT,
1081				     (args->va_addr + args->size - 1) >> PAGE_SHIFT)) {
1082		pr_err("Address: 0x%llx already allocated by SVM\n",
1083			args->va_addr);
1084		mutex_unlock(&p->svms.lock);
1085		return -EADDRINUSE;
1086	}
1087
1088	/* When register user buffer check if it has been registered by svm by
1089	 * buffer cpu virtual address.
1090	 */
1091	if ((flags & KFD_IOC_ALLOC_MEM_FLAGS_USERPTR) &&
1092	    interval_tree_iter_first(&p->svms.objects,
1093				     args->mmap_offset >> PAGE_SHIFT,
1094				     (args->mmap_offset  + args->size - 1) >> PAGE_SHIFT)) {
1095		pr_err("User Buffer Address: 0x%llx already allocated by SVM\n",
1096			args->mmap_offset);
1097		mutex_unlock(&p->svms.lock);
1098		return -EADDRINUSE;
1099	}
1100
1101	mutex_unlock(&p->svms.lock);
1102#endif
1103	mutex_lock(&p->mutex);
1104	pdd = kfd_process_device_data_by_id(p, args->gpu_id);
1105	if (!pdd) {
1106		err = -EINVAL;
1107		goto err_pdd;
1108	}
1109
1110	dev = pdd->dev;
1111
1112	if ((flags & KFD_IOC_ALLOC_MEM_FLAGS_PUBLIC) &&
1113		(flags & KFD_IOC_ALLOC_MEM_FLAGS_VRAM) &&
1114		!kfd_dev_is_large_bar(dev)) {
1115		pr_err("Alloc host visible vram on small bar is not allowed\n");
1116		err = -EINVAL;
1117		goto err_large_bar;
1118	}
1119
1120	pdd = kfd_bind_process_to_device(dev, p);
1121	if (IS_ERR(pdd)) {
1122		err = PTR_ERR(pdd);
1123		goto err_unlock;
1124	}
1125
1126	if (flags & KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL) {
1127		if (args->size != kfd_doorbell_process_slice(dev->kfd)) {
1128			err = -EINVAL;
1129			goto err_unlock;
1130		}
1131		offset = kfd_get_process_doorbells(pdd);
1132		if (!offset) {
1133			err = -ENOMEM;
1134			goto err_unlock;
1135		}
1136	} else if (flags & KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP) {
1137		if (args->size != PAGE_SIZE) {
1138			err = -EINVAL;
1139			goto err_unlock;
1140		}
1141		offset = dev->adev->rmmio_remap.bus_addr;
1142		if (!offset) {
1143			err = -ENOMEM;
1144			goto err_unlock;
1145		}
1146	}
1147
1148	err = amdgpu_amdkfd_gpuvm_alloc_memory_of_gpu(
1149		dev->adev, args->va_addr, args->size,
1150		pdd->drm_priv, (struct kgd_mem **) &mem, &offset,
1151		flags, false);
1152
1153	if (err)
1154		goto err_unlock;
1155
1156	idr_handle = kfd_process_device_create_obj_handle(pdd, mem);
1157	if (idr_handle < 0) {
1158		err = -EFAULT;
1159		goto err_free;
1160	}
1161
1162	/* Update the VRAM usage count */
1163	if (flags & KFD_IOC_ALLOC_MEM_FLAGS_VRAM) {
1164		uint64_t size = args->size;
1165
1166		if (flags & KFD_IOC_ALLOC_MEM_FLAGS_AQL_QUEUE_MEM)
1167			size >>= 1;
1168		WRITE_ONCE(pdd->vram_usage, pdd->vram_usage + PAGE_ALIGN(size));
1169	}
1170
1171	mutex_unlock(&p->mutex);
1172
1173	args->handle = MAKE_HANDLE(args->gpu_id, idr_handle);
1174	args->mmap_offset = offset;
1175
1176	/* MMIO is mapped through kfd device
1177	 * Generate a kfd mmap offset
1178	 */
1179	if (flags & KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)
1180		args->mmap_offset = KFD_MMAP_TYPE_MMIO
1181					| KFD_MMAP_GPU_ID(args->gpu_id);
1182
1183	return 0;
1184
1185err_free:
1186	amdgpu_amdkfd_gpuvm_free_memory_of_gpu(dev->adev, (struct kgd_mem *)mem,
1187					       pdd->drm_priv, NULL);
1188err_unlock:
1189err_pdd:
1190err_large_bar:
1191	mutex_unlock(&p->mutex);
1192	return err;
1193}
1194
1195static int kfd_ioctl_free_memory_of_gpu(struct file *filep,
1196					struct kfd_process *p, void *data)
1197{
1198	struct kfd_ioctl_free_memory_of_gpu_args *args = data;
1199	struct kfd_process_device *pdd;
1200	void *mem;
1201	int ret;
1202	uint64_t size = 0;
1203
1204	mutex_lock(&p->mutex);
1205	/*
1206	 * Safeguard to prevent user space from freeing signal BO.
1207	 * It will be freed at process termination.
1208	 */
1209	if (p->signal_handle && (p->signal_handle == args->handle)) {
1210		pr_err("Free signal BO is not allowed\n");
1211		ret = -EPERM;
1212		goto err_unlock;
1213	}
1214
1215	pdd = kfd_process_device_data_by_id(p, GET_GPU_ID(args->handle));
1216	if (!pdd) {
1217		pr_err("Process device data doesn't exist\n");
1218		ret = -EINVAL;
1219		goto err_pdd;
1220	}
1221
1222	mem = kfd_process_device_translate_handle(
1223		pdd, GET_IDR_HANDLE(args->handle));
1224	if (!mem) {
1225		ret = -EINVAL;
1226		goto err_unlock;
1227	}
1228
1229	ret = amdgpu_amdkfd_gpuvm_free_memory_of_gpu(pdd->dev->adev,
1230				(struct kgd_mem *)mem, pdd->drm_priv, &size);
1231
1232	/* If freeing the buffer failed, leave the handle in place for
1233	 * clean-up during process tear-down.
1234	 */
1235	if (!ret)
1236		kfd_process_device_remove_obj_handle(
1237			pdd, GET_IDR_HANDLE(args->handle));
1238
1239	WRITE_ONCE(pdd->vram_usage, pdd->vram_usage - size);
1240
1241err_unlock:
1242err_pdd:
1243	mutex_unlock(&p->mutex);
1244	return ret;
1245}
1246
1247static int kfd_ioctl_map_memory_to_gpu(struct file *filep,
1248					struct kfd_process *p, void *data)
1249{
1250	struct kfd_ioctl_map_memory_to_gpu_args *args = data;
1251	struct kfd_process_device *pdd, *peer_pdd;
1252	void *mem;
1253	struct kfd_node *dev;
1254	long err = 0;
1255	int i;
1256	uint32_t *devices_arr = NULL;
1257
1258	if (!args->n_devices) {
1259		pr_debug("Device IDs array empty\n");
1260		return -EINVAL;
1261	}
1262	if (args->n_success > args->n_devices) {
1263		pr_debug("n_success exceeds n_devices\n");
1264		return -EINVAL;
1265	}
1266
1267	devices_arr = kmalloc_array(args->n_devices, sizeof(*devices_arr),
1268				    GFP_KERNEL);
1269	if (!devices_arr)
1270		return -ENOMEM;
1271
1272	err = copy_from_user(devices_arr,
1273			     (void __user *)args->device_ids_array_ptr,
1274			     args->n_devices * sizeof(*devices_arr));
1275	if (err != 0) {
1276		err = -EFAULT;
1277		goto copy_from_user_failed;
1278	}
1279
1280	mutex_lock(&p->mutex);
1281	pdd = kfd_process_device_data_by_id(p, GET_GPU_ID(args->handle));
1282	if (!pdd) {
1283		err = -EINVAL;
1284		goto get_process_device_data_failed;
1285	}
1286	dev = pdd->dev;
1287
1288	pdd = kfd_bind_process_to_device(dev, p);
1289	if (IS_ERR(pdd)) {
1290		err = PTR_ERR(pdd);
1291		goto bind_process_to_device_failed;
1292	}
1293
1294	mem = kfd_process_device_translate_handle(pdd,
1295						GET_IDR_HANDLE(args->handle));
1296	if (!mem) {
1297		err = -ENOMEM;
1298		goto get_mem_obj_from_handle_failed;
1299	}
1300
1301	for (i = args->n_success; i < args->n_devices; i++) {
1302		peer_pdd = kfd_process_device_data_by_id(p, devices_arr[i]);
1303		if (!peer_pdd) {
1304			pr_debug("Getting device by id failed for 0x%x\n",
1305				 devices_arr[i]);
1306			err = -EINVAL;
1307			goto get_mem_obj_from_handle_failed;
1308		}
1309
1310		peer_pdd = kfd_bind_process_to_device(peer_pdd->dev, p);
1311		if (IS_ERR(peer_pdd)) {
1312			err = PTR_ERR(peer_pdd);
1313			goto get_mem_obj_from_handle_failed;
1314		}
1315
1316		err = amdgpu_amdkfd_gpuvm_map_memory_to_gpu(
1317			peer_pdd->dev->adev, (struct kgd_mem *)mem,
1318			peer_pdd->drm_priv);
1319		if (err) {
1320			struct pci_dev *pdev = peer_pdd->dev->adev->pdev;
1321
1322			dev_err(dev->adev->dev,
1323			       "Failed to map peer:%04x:%02x:%02x.%d mem_domain:%d\n",
1324			       pci_domain_nr(pdev->bus),
1325			       pdev->bus->number,
1326			       PCI_SLOT(pdev->devfn),
1327			       PCI_FUNC(pdev->devfn),
1328			       ((struct kgd_mem *)mem)->domain);
1329			goto map_memory_to_gpu_failed;
1330		}
1331		args->n_success = i+1;
1332	}
1333
1334	err = amdgpu_amdkfd_gpuvm_sync_memory(dev->adev, (struct kgd_mem *) mem, true);
1335	if (err) {
1336		pr_debug("Sync memory failed, wait interrupted by user signal\n");
1337		goto sync_memory_failed;
1338	}
1339
1340	mutex_unlock(&p->mutex);
1341
1342	/* Flush TLBs after waiting for the page table updates to complete */
1343	for (i = 0; i < args->n_devices; i++) {
1344		peer_pdd = kfd_process_device_data_by_id(p, devices_arr[i]);
1345		if (WARN_ON_ONCE(!peer_pdd))
1346			continue;
1347		kfd_flush_tlb(peer_pdd, TLB_FLUSH_LEGACY);
1348	}
1349	kfree(devices_arr);
1350
1351	return err;
1352
1353get_process_device_data_failed:
1354bind_process_to_device_failed:
1355get_mem_obj_from_handle_failed:
1356map_memory_to_gpu_failed:
1357sync_memory_failed:
1358	mutex_unlock(&p->mutex);
1359copy_from_user_failed:
1360	kfree(devices_arr);
1361
1362	return err;
1363}
1364
1365static int kfd_ioctl_unmap_memory_from_gpu(struct file *filep,
1366					struct kfd_process *p, void *data)
1367{
1368	struct kfd_ioctl_unmap_memory_from_gpu_args *args = data;
1369	struct kfd_process_device *pdd, *peer_pdd;
1370	void *mem;
1371	long err = 0;
1372	uint32_t *devices_arr = NULL, i;
1373	bool flush_tlb;
1374
1375	if (!args->n_devices) {
1376		pr_debug("Device IDs array empty\n");
1377		return -EINVAL;
1378	}
1379	if (args->n_success > args->n_devices) {
1380		pr_debug("n_success exceeds n_devices\n");
1381		return -EINVAL;
1382	}
1383
1384	devices_arr = kmalloc_array(args->n_devices, sizeof(*devices_arr),
1385				    GFP_KERNEL);
1386	if (!devices_arr)
1387		return -ENOMEM;
1388
1389	err = copy_from_user(devices_arr,
1390			     (void __user *)args->device_ids_array_ptr,
1391			     args->n_devices * sizeof(*devices_arr));
1392	if (err != 0) {
1393		err = -EFAULT;
1394		goto copy_from_user_failed;
1395	}
1396
1397	mutex_lock(&p->mutex);
1398	pdd = kfd_process_device_data_by_id(p, GET_GPU_ID(args->handle));
1399	if (!pdd) {
1400		err = -EINVAL;
1401		goto bind_process_to_device_failed;
1402	}
1403
1404	mem = kfd_process_device_translate_handle(pdd,
1405						GET_IDR_HANDLE(args->handle));
1406	if (!mem) {
1407		err = -ENOMEM;
1408		goto get_mem_obj_from_handle_failed;
1409	}
1410
1411	for (i = args->n_success; i < args->n_devices; i++) {
1412		peer_pdd = kfd_process_device_data_by_id(p, devices_arr[i]);
1413		if (!peer_pdd) {
1414			err = -EINVAL;
1415			goto get_mem_obj_from_handle_failed;
1416		}
1417		err = amdgpu_amdkfd_gpuvm_unmap_memory_from_gpu(
1418			peer_pdd->dev->adev, (struct kgd_mem *)mem, peer_pdd->drm_priv);
1419		if (err) {
1420			pr_err("Failed to unmap from gpu %d/%d\n",
1421			       i, args->n_devices);
1422			goto unmap_memory_from_gpu_failed;
1423		}
1424		args->n_success = i+1;
1425	}
1426
1427	flush_tlb = kfd_flush_tlb_after_unmap(pdd->dev->kfd);
1428	if (flush_tlb) {
1429		err = amdgpu_amdkfd_gpuvm_sync_memory(pdd->dev->adev,
1430				(struct kgd_mem *) mem, true);
1431		if (err) {
1432			pr_debug("Sync memory failed, wait interrupted by user signal\n");
1433			goto sync_memory_failed;
1434		}
1435	}
1436
1437	/* Flush TLBs after waiting for the page table updates to complete */
1438	for (i = 0; i < args->n_devices; i++) {
1439		peer_pdd = kfd_process_device_data_by_id(p, devices_arr[i]);
1440		if (WARN_ON_ONCE(!peer_pdd))
1441			continue;
1442		if (flush_tlb)
1443			kfd_flush_tlb(peer_pdd, TLB_FLUSH_HEAVYWEIGHT);
1444
1445		/* Remove dma mapping after tlb flush to avoid IO_PAGE_FAULT */
1446		err = amdgpu_amdkfd_gpuvm_dmaunmap_mem(mem, peer_pdd->drm_priv);
1447		if (err)
1448			goto sync_memory_failed;
1449	}
1450
1451	mutex_unlock(&p->mutex);
1452
1453	kfree(devices_arr);
1454
1455	return 0;
1456
1457bind_process_to_device_failed:
1458get_mem_obj_from_handle_failed:
1459unmap_memory_from_gpu_failed:
1460sync_memory_failed:
1461	mutex_unlock(&p->mutex);
1462copy_from_user_failed:
1463	kfree(devices_arr);
1464	return err;
1465}
1466
1467static int kfd_ioctl_alloc_queue_gws(struct file *filep,
1468		struct kfd_process *p, void *data)
1469{
1470	int retval;
1471	struct kfd_ioctl_alloc_queue_gws_args *args = data;
1472	struct queue *q;
1473	struct kfd_node *dev;
1474
1475	mutex_lock(&p->mutex);
1476	q = pqm_get_user_queue(&p->pqm, args->queue_id);
1477
1478	if (q) {
1479		dev = q->device;
1480	} else {
1481		retval = -EINVAL;
1482		goto out_unlock;
1483	}
1484
1485	if (!dev->gws) {
1486		retval = -ENODEV;
1487		goto out_unlock;
1488	}
1489
1490	if (dev->dqm->sched_policy == KFD_SCHED_POLICY_NO_HWS) {
1491		retval = -ENODEV;
1492		goto out_unlock;
1493	}
1494
1495	if (p->debug_trap_enabled && (!kfd_dbg_has_gws_support(dev) ||
1496				      kfd_dbg_has_cwsr_workaround(dev))) {
1497		retval = -EBUSY;
1498		goto out_unlock;
1499	}
1500
1501	retval = pqm_set_gws(&p->pqm, args->queue_id, args->num_gws ? dev->gws : NULL);
1502	mutex_unlock(&p->mutex);
1503
1504	args->first_gws = 0;
1505	return retval;
1506
1507out_unlock:
1508	mutex_unlock(&p->mutex);
1509	return retval;
1510}
1511
1512static int kfd_ioctl_get_dmabuf_info(struct file *filep,
1513		struct kfd_process *p, void *data)
1514{
1515	struct kfd_ioctl_get_dmabuf_info_args *args = data;
1516	struct kfd_node *dev = NULL;
1517	struct amdgpu_device *dmabuf_adev;
1518	void *metadata_buffer = NULL;
1519	uint32_t flags;
1520	int8_t xcp_id;
1521	unsigned int i;
1522	int r;
1523
1524	/* Find a KFD GPU device that supports the get_dmabuf_info query */
1525	for (i = 0; kfd_topology_enum_kfd_devices(i, &dev) == 0; i++)
1526		if (dev && !kfd_devcgroup_check_permission(dev))
1527			break;
1528	if (!dev)
1529		return -EINVAL;
1530
1531	if (args->metadata_ptr) {
1532		metadata_buffer = kzalloc(args->metadata_size, GFP_KERNEL);
1533		if (!metadata_buffer)
1534			return -ENOMEM;
1535	}
1536
1537	/* Get dmabuf info from KGD */
1538	r = amdgpu_amdkfd_get_dmabuf_info(dev->adev, args->dmabuf_fd,
1539					  &dmabuf_adev, &args->size,
1540					  metadata_buffer, args->metadata_size,
1541					  &args->metadata_size, &flags, &xcp_id);
1542	if (r)
1543		goto exit;
1544
1545	if (xcp_id >= 0)
1546		args->gpu_id = dmabuf_adev->kfd.dev->nodes[xcp_id]->id;
1547	else
1548		args->gpu_id = dev->id;
1549	args->flags = flags;
1550
1551	/* Copy metadata buffer to user mode */
1552	if (metadata_buffer) {
1553		r = copy_to_user((void __user *)args->metadata_ptr,
1554				 metadata_buffer, args->metadata_size);
1555		if (r != 0)
1556			r = -EFAULT;
1557	}
1558
1559exit:
1560	kfree(metadata_buffer);
1561
1562	return r;
1563}
1564
1565static int kfd_ioctl_import_dmabuf(struct file *filep,
1566				   struct kfd_process *p, void *data)
1567{
1568	struct kfd_ioctl_import_dmabuf_args *args = data;
1569	struct kfd_process_device *pdd;
1570	int idr_handle;
1571	uint64_t size;
1572	void *mem;
1573	int r;
1574
1575	mutex_lock(&p->mutex);
1576	pdd = kfd_process_device_data_by_id(p, args->gpu_id);
1577	if (!pdd) {
1578		r = -EINVAL;
1579		goto err_unlock;
1580	}
1581
1582	pdd = kfd_bind_process_to_device(pdd->dev, p);
1583	if (IS_ERR(pdd)) {
1584		r = PTR_ERR(pdd);
1585		goto err_unlock;
1586	}
1587
1588	r = amdgpu_amdkfd_gpuvm_import_dmabuf_fd(pdd->dev->adev, args->dmabuf_fd,
1589						 args->va_addr, pdd->drm_priv,
1590						 (struct kgd_mem **)&mem, &size,
1591						 NULL);
1592	if (r)
1593		goto err_unlock;
1594
1595	idr_handle = kfd_process_device_create_obj_handle(pdd, mem);
1596	if (idr_handle < 0) {
1597		r = -EFAULT;
1598		goto err_free;
1599	}
1600
1601	mutex_unlock(&p->mutex);
1602
1603	args->handle = MAKE_HANDLE(args->gpu_id, idr_handle);
1604
1605	return 0;
1606
1607err_free:
1608	amdgpu_amdkfd_gpuvm_free_memory_of_gpu(pdd->dev->adev, (struct kgd_mem *)mem,
1609					       pdd->drm_priv, NULL);
1610err_unlock:
1611	mutex_unlock(&p->mutex);
1612	return r;
1613}
1614
1615static int kfd_ioctl_export_dmabuf(struct file *filep,
1616				   struct kfd_process *p, void *data)
1617{
1618	struct kfd_ioctl_export_dmabuf_args *args = data;
1619	struct kfd_process_device *pdd;
1620	struct dma_buf *dmabuf;
1621	struct kfd_node *dev;
1622	void *mem;
1623	int ret = 0;
1624
1625	dev = kfd_device_by_id(GET_GPU_ID(args->handle));
1626	if (!dev)
1627		return -EINVAL;
1628
1629	mutex_lock(&p->mutex);
1630
1631	pdd = kfd_get_process_device_data(dev, p);
1632	if (!pdd) {
1633		ret = -EINVAL;
1634		goto err_unlock;
1635	}
1636
1637	mem = kfd_process_device_translate_handle(pdd,
1638						GET_IDR_HANDLE(args->handle));
1639	if (!mem) {
1640		ret = -EINVAL;
1641		goto err_unlock;
1642	}
1643
1644	ret = amdgpu_amdkfd_gpuvm_export_dmabuf(mem, &dmabuf);
1645	mutex_unlock(&p->mutex);
1646	if (ret)
1647		goto err_out;
1648
1649	ret = dma_buf_fd(dmabuf, args->flags);
1650	if (ret < 0) {
1651		dma_buf_put(dmabuf);
1652		goto err_out;
1653	}
1654	/* dma_buf_fd assigns the reference count to the fd, no need to
1655	 * put the reference here.
1656	 */
1657	args->dmabuf_fd = ret;
1658
1659	return 0;
1660
1661err_unlock:
1662	mutex_unlock(&p->mutex);
1663err_out:
1664	return ret;
1665}
1666
1667/* Handle requests for watching SMI events */
1668static int kfd_ioctl_smi_events(struct file *filep,
1669				struct kfd_process *p, void *data)
1670{
1671	struct kfd_ioctl_smi_events_args *args = data;
1672	struct kfd_process_device *pdd;
1673
1674	mutex_lock(&p->mutex);
1675
1676	pdd = kfd_process_device_data_by_id(p, args->gpuid);
1677	mutex_unlock(&p->mutex);
1678	if (!pdd)
1679		return -EINVAL;
1680
1681	return kfd_smi_event_open(pdd->dev, &args->anon_fd);
1682}
1683
1684#if IS_ENABLED(CONFIG_HSA_AMD_SVM)
1685
1686static int kfd_ioctl_set_xnack_mode(struct file *filep,
1687				    struct kfd_process *p, void *data)
1688{
1689	struct kfd_ioctl_set_xnack_mode_args *args = data;
1690	int r = 0;
1691
1692	mutex_lock(&p->mutex);
1693	if (args->xnack_enabled >= 0) {
1694		if (!list_empty(&p->pqm.queues)) {
1695			pr_debug("Process has user queues running\n");
1696			r = -EBUSY;
1697			goto out_unlock;
1698		}
1699
1700		if (p->xnack_enabled == args->xnack_enabled)
1701			goto out_unlock;
1702
1703		if (args->xnack_enabled && !kfd_process_xnack_mode(p, true)) {
1704			r = -EPERM;
1705			goto out_unlock;
1706		}
1707
1708		r = svm_range_switch_xnack_reserve_mem(p, args->xnack_enabled);
1709	} else {
1710		args->xnack_enabled = p->xnack_enabled;
1711	}
1712
1713out_unlock:
1714	mutex_unlock(&p->mutex);
1715
1716	return r;
1717}
1718
1719static int kfd_ioctl_svm(struct file *filep, struct kfd_process *p, void *data)
1720{
1721	struct kfd_ioctl_svm_args *args = data;
1722	int r = 0;
1723
1724	pr_debug("start 0x%llx size 0x%llx op 0x%x nattr 0x%x\n",
1725		 args->start_addr, args->size, args->op, args->nattr);
1726
1727	if ((args->start_addr & ~PAGE_MASK) || (args->size & ~PAGE_MASK))
1728		return -EINVAL;
1729	if (!args->start_addr || !args->size)
1730		return -EINVAL;
1731
1732	r = svm_ioctl(p, args->op, args->start_addr, args->size, args->nattr,
1733		      args->attrs);
1734
1735	return r;
1736}
1737#else
1738static int kfd_ioctl_set_xnack_mode(struct file *filep,
1739				    struct kfd_process *p, void *data)
1740{
1741	return -EPERM;
1742}
1743static int kfd_ioctl_svm(struct file *filep, struct kfd_process *p, void *data)
1744{
1745	return -EPERM;
1746}
1747#endif
1748
1749static int criu_checkpoint_process(struct kfd_process *p,
1750			     uint8_t __user *user_priv_data,
1751			     uint64_t *priv_offset)
1752{
1753	struct kfd_criu_process_priv_data process_priv;
1754	int ret;
1755
1756	memset(&process_priv, 0, sizeof(process_priv));
1757
1758	process_priv.version = KFD_CRIU_PRIV_VERSION;
1759	/* For CR, we don't consider negative xnack mode which is used for
1760	 * querying without changing it, here 0 simply means disabled and 1
1761	 * means enabled so retry for finding a valid PTE.
1762	 */
1763	process_priv.xnack_mode = p->xnack_enabled ? 1 : 0;
1764
1765	ret = copy_to_user(user_priv_data + *priv_offset,
1766				&process_priv, sizeof(process_priv));
1767
1768	if (ret) {
1769		pr_err("Failed to copy process information to user\n");
1770		ret = -EFAULT;
1771	}
1772
1773	*priv_offset += sizeof(process_priv);
1774	return ret;
1775}
1776
1777static int criu_checkpoint_devices(struct kfd_process *p,
1778			     uint32_t num_devices,
1779			     uint8_t __user *user_addr,
1780			     uint8_t __user *user_priv_data,
1781			     uint64_t *priv_offset)
1782{
1783	struct kfd_criu_device_priv_data *device_priv = NULL;
1784	struct kfd_criu_device_bucket *device_buckets = NULL;
1785	int ret = 0, i;
1786
1787	device_buckets = kvzalloc(num_devices * sizeof(*device_buckets), GFP_KERNEL);
1788	if (!device_buckets) {
1789		ret = -ENOMEM;
1790		goto exit;
1791	}
1792
1793	device_priv = kvzalloc(num_devices * sizeof(*device_priv), GFP_KERNEL);
1794	if (!device_priv) {
1795		ret = -ENOMEM;
1796		goto exit;
1797	}
1798
1799	for (i = 0; i < num_devices; i++) {
1800		struct kfd_process_device *pdd = p->pdds[i];
1801
1802		device_buckets[i].user_gpu_id = pdd->user_gpu_id;
1803		device_buckets[i].actual_gpu_id = pdd->dev->id;
1804
1805		/*
1806		 * priv_data does not contain useful information for now and is reserved for
1807		 * future use, so we do not set its contents.
1808		 */
1809	}
1810
1811	ret = copy_to_user(user_addr, device_buckets, num_devices * sizeof(*device_buckets));
1812	if (ret) {
1813		pr_err("Failed to copy device information to user\n");
1814		ret = -EFAULT;
1815		goto exit;
1816	}
1817
1818	ret = copy_to_user(user_priv_data + *priv_offset,
1819			   device_priv,
1820			   num_devices * sizeof(*device_priv));
1821	if (ret) {
1822		pr_err("Failed to copy device information to user\n");
1823		ret = -EFAULT;
1824	}
1825	*priv_offset += num_devices * sizeof(*device_priv);
1826
1827exit:
1828	kvfree(device_buckets);
1829	kvfree(device_priv);
1830	return ret;
1831}
1832
1833static uint32_t get_process_num_bos(struct kfd_process *p)
1834{
1835	uint32_t num_of_bos = 0;
1836	int i;
1837
1838	/* Run over all PDDs of the process */
1839	for (i = 0; i < p->n_pdds; i++) {
1840		struct kfd_process_device *pdd = p->pdds[i];
1841		void *mem;
1842		int id;
1843
1844		idr_for_each_entry(&pdd->alloc_idr, mem, id) {
1845			struct kgd_mem *kgd_mem = (struct kgd_mem *)mem;
1846
1847			if (!kgd_mem->va || kgd_mem->va > pdd->gpuvm_base)
1848				num_of_bos++;
1849		}
1850	}
1851	return num_of_bos;
1852}
1853
1854static int criu_get_prime_handle(struct kgd_mem *mem,
1855				 int flags, u32 *shared_fd)
1856{
1857	struct dma_buf *dmabuf;
1858	int ret;
1859
1860	ret = amdgpu_amdkfd_gpuvm_export_dmabuf(mem, &dmabuf);
1861	if (ret) {
1862		pr_err("dmabuf export failed for the BO\n");
1863		return ret;
1864	}
1865
1866	ret = dma_buf_fd(dmabuf, flags);
1867	if (ret < 0) {
1868		pr_err("dmabuf create fd failed, ret:%d\n", ret);
1869		goto out_free_dmabuf;
1870	}
1871
1872	*shared_fd = ret;
1873	return 0;
1874
1875out_free_dmabuf:
1876	dma_buf_put(dmabuf);
1877	return ret;
1878}
1879
1880static int criu_checkpoint_bos(struct kfd_process *p,
1881			       uint32_t num_bos,
1882			       uint8_t __user *user_bos,
1883			       uint8_t __user *user_priv_data,
1884			       uint64_t *priv_offset)
1885{
1886	struct kfd_criu_bo_bucket *bo_buckets;
1887	struct kfd_criu_bo_priv_data *bo_privs;
1888	int ret = 0, pdd_index, bo_index = 0, id;
1889	void *mem;
1890
1891	bo_buckets = kvzalloc(num_bos * sizeof(*bo_buckets), GFP_KERNEL);
1892	if (!bo_buckets)
1893		return -ENOMEM;
1894
1895	bo_privs = kvzalloc(num_bos * sizeof(*bo_privs), GFP_KERNEL);
1896	if (!bo_privs) {
1897		ret = -ENOMEM;
1898		goto exit;
1899	}
1900
1901	for (pdd_index = 0; pdd_index < p->n_pdds; pdd_index++) {
1902		struct kfd_process_device *pdd = p->pdds[pdd_index];
1903		struct amdgpu_bo *dumper_bo;
1904		struct kgd_mem *kgd_mem;
1905
1906		idr_for_each_entry(&pdd->alloc_idr, mem, id) {
1907			struct kfd_criu_bo_bucket *bo_bucket;
1908			struct kfd_criu_bo_priv_data *bo_priv;
1909			int i, dev_idx = 0;
1910
1911			if (!mem) {
1912				ret = -ENOMEM;
1913				goto exit;
1914			}
1915
1916			kgd_mem = (struct kgd_mem *)mem;
1917			dumper_bo = kgd_mem->bo;
1918
1919			/* Skip checkpointing BOs that are used for Trap handler
1920			 * code and state. Currently, these BOs have a VA that
1921			 * is less GPUVM Base
1922			 */
1923			if (kgd_mem->va && kgd_mem->va <= pdd->gpuvm_base)
1924				continue;
1925
1926			bo_bucket = &bo_buckets[bo_index];
1927			bo_priv = &bo_privs[bo_index];
1928
1929			bo_bucket->gpu_id = pdd->user_gpu_id;
1930			bo_bucket->addr = (uint64_t)kgd_mem->va;
1931			bo_bucket->size = amdgpu_bo_size(dumper_bo);
1932			bo_bucket->alloc_flags = (uint32_t)kgd_mem->alloc_flags;
1933			bo_priv->idr_handle = id;
1934
1935			if (bo_bucket->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_USERPTR) {
1936				ret = amdgpu_ttm_tt_get_userptr(&dumper_bo->tbo,
1937								&bo_priv->user_addr);
1938				if (ret) {
1939					pr_err("Failed to obtain user address for user-pointer bo\n");
1940					goto exit;
1941				}
1942			}
1943			if (bo_bucket->alloc_flags
1944			    & (KFD_IOC_ALLOC_MEM_FLAGS_VRAM | KFD_IOC_ALLOC_MEM_FLAGS_GTT)) {
1945				ret = criu_get_prime_handle(kgd_mem,
1946						bo_bucket->alloc_flags &
1947						KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE ? DRM_RDWR : 0,
1948						&bo_bucket->dmabuf_fd);
1949				if (ret)
1950					goto exit;
1951			} else {
1952				bo_bucket->dmabuf_fd = KFD_INVALID_FD;
1953			}
1954
1955			if (bo_bucket->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL)
1956				bo_bucket->offset = KFD_MMAP_TYPE_DOORBELL |
1957					KFD_MMAP_GPU_ID(pdd->dev->id);
1958			else if (bo_bucket->alloc_flags &
1959				KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)
1960				bo_bucket->offset = KFD_MMAP_TYPE_MMIO |
1961					KFD_MMAP_GPU_ID(pdd->dev->id);
1962			else
1963				bo_bucket->offset = amdgpu_bo_mmap_offset(dumper_bo);
1964
1965			for (i = 0; i < p->n_pdds; i++) {
1966				if (amdgpu_amdkfd_bo_mapped_to_dev(p->pdds[i]->dev->adev, kgd_mem))
1967					bo_priv->mapped_gpuids[dev_idx++] = p->pdds[i]->user_gpu_id;
1968			}
1969
1970			pr_debug("bo_size = 0x%llx, bo_addr = 0x%llx bo_offset = 0x%llx\n"
1971					"gpu_id = 0x%x alloc_flags = 0x%x idr_handle = 0x%x",
1972					bo_bucket->size,
1973					bo_bucket->addr,
1974					bo_bucket->offset,
1975					bo_bucket->gpu_id,
1976					bo_bucket->alloc_flags,
1977					bo_priv->idr_handle);
1978			bo_index++;
1979		}
1980	}
1981
1982	ret = copy_to_user(user_bos, bo_buckets, num_bos * sizeof(*bo_buckets));
1983	if (ret) {
1984		pr_err("Failed to copy BO information to user\n");
1985		ret = -EFAULT;
1986		goto exit;
1987	}
1988
1989	ret = copy_to_user(user_priv_data + *priv_offset, bo_privs, num_bos * sizeof(*bo_privs));
1990	if (ret) {
1991		pr_err("Failed to copy BO priv information to user\n");
1992		ret = -EFAULT;
1993		goto exit;
1994	}
1995
1996	*priv_offset += num_bos * sizeof(*bo_privs);
1997
1998exit:
1999	while (ret && bo_index--) {
2000		if (bo_buckets[bo_index].alloc_flags
2001		    & (KFD_IOC_ALLOC_MEM_FLAGS_VRAM | KFD_IOC_ALLOC_MEM_FLAGS_GTT))
2002			close_fd(bo_buckets[bo_index].dmabuf_fd);
2003	}
2004
2005	kvfree(bo_buckets);
2006	kvfree(bo_privs);
2007	return ret;
2008}
2009
2010static int criu_get_process_object_info(struct kfd_process *p,
2011					uint32_t *num_devices,
2012					uint32_t *num_bos,
2013					uint32_t *num_objects,
2014					uint64_t *objs_priv_size)
2015{
2016	uint64_t queues_priv_data_size, svm_priv_data_size, priv_size;
2017	uint32_t num_queues, num_events, num_svm_ranges;
2018	int ret;
2019
2020	*num_devices = p->n_pdds;
2021	*num_bos = get_process_num_bos(p);
2022
2023	ret = kfd_process_get_queue_info(p, &num_queues, &queues_priv_data_size);
2024	if (ret)
2025		return ret;
2026
2027	num_events = kfd_get_num_events(p);
2028
2029	ret = svm_range_get_info(p, &num_svm_ranges, &svm_priv_data_size);
2030	if (ret)
2031		return ret;
2032
2033	*num_objects = num_queues + num_events + num_svm_ranges;
2034
2035	if (objs_priv_size) {
2036		priv_size = sizeof(struct kfd_criu_process_priv_data);
2037		priv_size += *num_devices * sizeof(struct kfd_criu_device_priv_data);
2038		priv_size += *num_bos * sizeof(struct kfd_criu_bo_priv_data);
2039		priv_size += queues_priv_data_size;
2040		priv_size += num_events * sizeof(struct kfd_criu_event_priv_data);
2041		priv_size += svm_priv_data_size;
2042		*objs_priv_size = priv_size;
2043	}
2044	return 0;
2045}
2046
2047static int criu_checkpoint(struct file *filep,
2048			   struct kfd_process *p,
2049			   struct kfd_ioctl_criu_args *args)
2050{
2051	int ret;
2052	uint32_t num_devices, num_bos, num_objects;
2053	uint64_t priv_size, priv_offset = 0, bo_priv_offset;
2054
2055	if (!args->devices || !args->bos || !args->priv_data)
2056		return -EINVAL;
2057
2058	mutex_lock(&p->mutex);
2059
2060	if (!p->n_pdds) {
2061		pr_err("No pdd for given process\n");
2062		ret = -ENODEV;
2063		goto exit_unlock;
2064	}
2065
2066	/* Confirm all process queues are evicted */
2067	if (!p->queues_paused) {
2068		pr_err("Cannot dump process when queues are not in evicted state\n");
2069		/* CRIU plugin did not call op PROCESS_INFO before checkpointing */
2070		ret = -EINVAL;
2071		goto exit_unlock;
2072	}
2073
2074	ret = criu_get_process_object_info(p, &num_devices, &num_bos, &num_objects, &priv_size);
2075	if (ret)
2076		goto exit_unlock;
2077
2078	if (num_devices != args->num_devices ||
2079	    num_bos != args->num_bos ||
2080	    num_objects != args->num_objects ||
2081	    priv_size != args->priv_data_size) {
2082
2083		ret = -EINVAL;
2084		goto exit_unlock;
2085	}
2086
2087	/* each function will store private data inside priv_data and adjust priv_offset */
2088	ret = criu_checkpoint_process(p, (uint8_t __user *)args->priv_data, &priv_offset);
2089	if (ret)
2090		goto exit_unlock;
2091
2092	ret = criu_checkpoint_devices(p, num_devices, (uint8_t __user *)args->devices,
2093				(uint8_t __user *)args->priv_data, &priv_offset);
2094	if (ret)
2095		goto exit_unlock;
2096
2097	/* Leave room for BOs in the private data. They need to be restored
2098	 * before events, but we checkpoint them last to simplify the error
2099	 * handling.
2100	 */
2101	bo_priv_offset = priv_offset;
2102	priv_offset += num_bos * sizeof(struct kfd_criu_bo_priv_data);
2103
2104	if (num_objects) {
2105		ret = kfd_criu_checkpoint_queues(p, (uint8_t __user *)args->priv_data,
2106						 &priv_offset);
2107		if (ret)
2108			goto exit_unlock;
2109
2110		ret = kfd_criu_checkpoint_events(p, (uint8_t __user *)args->priv_data,
2111						 &priv_offset);
2112		if (ret)
2113			goto exit_unlock;
2114
2115		ret = kfd_criu_checkpoint_svm(p, (uint8_t __user *)args->priv_data, &priv_offset);
2116		if (ret)
2117			goto exit_unlock;
2118	}
2119
2120	/* This must be the last thing in this function that can fail.
2121	 * Otherwise we leak dmabuf file descriptors.
2122	 */
2123	ret = criu_checkpoint_bos(p, num_bos, (uint8_t __user *)args->bos,
2124			   (uint8_t __user *)args->priv_data, &bo_priv_offset);
2125
2126exit_unlock:
2127	mutex_unlock(&p->mutex);
2128	if (ret)
2129		pr_err("Failed to dump CRIU ret:%d\n", ret);
2130	else
2131		pr_debug("CRIU dump ret:%d\n", ret);
2132
2133	return ret;
2134}
2135
2136static int criu_restore_process(struct kfd_process *p,
2137				struct kfd_ioctl_criu_args *args,
2138				uint64_t *priv_offset,
2139				uint64_t max_priv_data_size)
2140{
2141	int ret = 0;
2142	struct kfd_criu_process_priv_data process_priv;
2143
2144	if (*priv_offset + sizeof(process_priv) > max_priv_data_size)
2145		return -EINVAL;
2146
2147	ret = copy_from_user(&process_priv,
2148				(void __user *)(args->priv_data + *priv_offset),
2149				sizeof(process_priv));
2150	if (ret) {
2151		pr_err("Failed to copy process private information from user\n");
2152		ret = -EFAULT;
2153		goto exit;
2154	}
2155	*priv_offset += sizeof(process_priv);
2156
2157	if (process_priv.version != KFD_CRIU_PRIV_VERSION) {
2158		pr_err("Invalid CRIU API version (checkpointed:%d current:%d)\n",
2159			process_priv.version, KFD_CRIU_PRIV_VERSION);
2160		return -EINVAL;
2161	}
2162
2163	pr_debug("Setting XNACK mode\n");
2164	if (process_priv.xnack_mode && !kfd_process_xnack_mode(p, true)) {
2165		pr_err("xnack mode cannot be set\n");
2166		ret = -EPERM;
2167		goto exit;
2168	} else {
2169		pr_debug("set xnack mode: %d\n", process_priv.xnack_mode);
2170		p->xnack_enabled = process_priv.xnack_mode;
2171	}
2172
2173exit:
2174	return ret;
2175}
2176
2177static int criu_restore_devices(struct kfd_process *p,
2178				struct kfd_ioctl_criu_args *args,
2179				uint64_t *priv_offset,
2180				uint64_t max_priv_data_size)
2181{
2182	struct kfd_criu_device_bucket *device_buckets;
2183	struct kfd_criu_device_priv_data *device_privs;
2184	int ret = 0;
2185	uint32_t i;
2186
2187	if (args->num_devices != p->n_pdds)
2188		return -EINVAL;
2189
2190	if (*priv_offset + (args->num_devices * sizeof(*device_privs)) > max_priv_data_size)
2191		return -EINVAL;
2192
2193	device_buckets = kmalloc_array(args->num_devices, sizeof(*device_buckets), GFP_KERNEL);
2194	if (!device_buckets)
2195		return -ENOMEM;
2196
2197	ret = copy_from_user(device_buckets, (void __user *)args->devices,
2198				args->num_devices * sizeof(*device_buckets));
2199	if (ret) {
2200		pr_err("Failed to copy devices buckets from user\n");
2201		ret = -EFAULT;
2202		goto exit;
2203	}
2204
2205	for (i = 0; i < args->num_devices; i++) {
2206		struct kfd_node *dev;
2207		struct kfd_process_device *pdd;
2208		struct file *drm_file;
2209
2210		/* device private data is not currently used */
2211
2212		if (!device_buckets[i].user_gpu_id) {
2213			pr_err("Invalid user gpu_id\n");
2214			ret = -EINVAL;
2215			goto exit;
2216		}
2217
2218		dev = kfd_device_by_id(device_buckets[i].actual_gpu_id);
2219		if (!dev) {
2220			pr_err("Failed to find device with gpu_id = %x\n",
2221				device_buckets[i].actual_gpu_id);
2222			ret = -EINVAL;
2223			goto exit;
2224		}
2225
2226		pdd = kfd_get_process_device_data(dev, p);
2227		if (!pdd) {
2228			pr_err("Failed to get pdd for gpu_id = %x\n",
2229					device_buckets[i].actual_gpu_id);
2230			ret = -EINVAL;
2231			goto exit;
2232		}
2233		pdd->user_gpu_id = device_buckets[i].user_gpu_id;
2234
2235		drm_file = fget(device_buckets[i].drm_fd);
2236		if (!drm_file) {
2237			pr_err("Invalid render node file descriptor sent from plugin (%d)\n",
2238				device_buckets[i].drm_fd);
2239			ret = -EINVAL;
2240			goto exit;
2241		}
2242
2243		if (pdd->drm_file) {
2244			ret = -EINVAL;
2245			goto exit;
2246		}
2247
2248		/* create the vm using render nodes for kfd pdd */
2249		if (kfd_process_device_init_vm(pdd, drm_file)) {
2250			pr_err("could not init vm for given pdd\n");
2251			/* On success, the PDD keeps the drm_file reference */
2252			fput(drm_file);
2253			ret = -EINVAL;
2254			goto exit;
2255		}
2256		/*
2257		 * pdd now already has the vm bound to render node so below api won't create a new
2258		 * exclusive kfd mapping but use existing one with renderDXXX but is still needed
2259		 * for iommu v2 binding  and runtime pm.
2260		 */
2261		pdd = kfd_bind_process_to_device(dev, p);
2262		if (IS_ERR(pdd)) {
2263			ret = PTR_ERR(pdd);
2264			goto exit;
2265		}
2266
2267		if (!pdd->qpd.proc_doorbells) {
2268			ret = kfd_alloc_process_doorbells(dev->kfd, pdd);
2269			if (ret)
2270				goto exit;
2271		}
2272	}
2273
2274	/*
2275	 * We are not copying device private data from user as we are not using the data for now,
2276	 * but we still adjust for its private data.
2277	 */
2278	*priv_offset += args->num_devices * sizeof(*device_privs);
2279
2280exit:
2281	kfree(device_buckets);
2282	return ret;
2283}
2284
2285static int criu_restore_memory_of_gpu(struct kfd_process_device *pdd,
2286				      struct kfd_criu_bo_bucket *bo_bucket,
2287				      struct kfd_criu_bo_priv_data *bo_priv,
2288				      struct kgd_mem **kgd_mem)
2289{
2290	int idr_handle;
2291	int ret;
2292	const bool criu_resume = true;
2293	u64 offset;
2294
2295	if (bo_bucket->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL) {
2296		if (bo_bucket->size !=
2297				kfd_doorbell_process_slice(pdd->dev->kfd))
2298			return -EINVAL;
2299
2300		offset = kfd_get_process_doorbells(pdd);
2301		if (!offset)
2302			return -ENOMEM;
2303	} else if (bo_bucket->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP) {
2304		/* MMIO BOs need remapped bus address */
2305		if (bo_bucket->size != PAGE_SIZE) {
2306			pr_err("Invalid page size\n");
2307			return -EINVAL;
2308		}
2309		offset = pdd->dev->adev->rmmio_remap.bus_addr;
2310		if (!offset) {
2311			pr_err("amdgpu_amdkfd_get_mmio_remap_phys_addr failed\n");
2312			return -ENOMEM;
2313		}
2314	} else if (bo_bucket->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_USERPTR) {
2315		offset = bo_priv->user_addr;
2316	}
2317	/* Create the BO */
2318	ret = amdgpu_amdkfd_gpuvm_alloc_memory_of_gpu(pdd->dev->adev, bo_bucket->addr,
2319						      bo_bucket->size, pdd->drm_priv, kgd_mem,
2320						      &offset, bo_bucket->alloc_flags, criu_resume);
2321	if (ret) {
2322		pr_err("Could not create the BO\n");
2323		return ret;
2324	}
2325	pr_debug("New BO created: size:0x%llx addr:0x%llx offset:0x%llx\n",
2326		 bo_bucket->size, bo_bucket->addr, offset);
2327
2328	/* Restore previous IDR handle */
2329	pr_debug("Restoring old IDR handle for the BO");
2330	idr_handle = idr_alloc(&pdd->alloc_idr, *kgd_mem, bo_priv->idr_handle,
2331			       bo_priv->idr_handle + 1, GFP_KERNEL);
2332
2333	if (idr_handle < 0) {
2334		pr_err("Could not allocate idr\n");
2335		amdgpu_amdkfd_gpuvm_free_memory_of_gpu(pdd->dev->adev, *kgd_mem, pdd->drm_priv,
2336						       NULL);
2337		return -ENOMEM;
2338	}
2339
2340	if (bo_bucket->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL)
2341		bo_bucket->restored_offset = KFD_MMAP_TYPE_DOORBELL | KFD_MMAP_GPU_ID(pdd->dev->id);
2342	if (bo_bucket->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP) {
2343		bo_bucket->restored_offset = KFD_MMAP_TYPE_MMIO | KFD_MMAP_GPU_ID(pdd->dev->id);
2344	} else if (bo_bucket->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_GTT) {
2345		bo_bucket->restored_offset = offset;
2346	} else if (bo_bucket->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_VRAM) {
2347		bo_bucket->restored_offset = offset;
2348		/* Update the VRAM usage count */
2349		WRITE_ONCE(pdd->vram_usage, pdd->vram_usage + bo_bucket->size);
2350	}
2351	return 0;
2352}
2353
2354static int criu_restore_bo(struct kfd_process *p,
2355			   struct kfd_criu_bo_bucket *bo_bucket,
2356			   struct kfd_criu_bo_priv_data *bo_priv)
2357{
2358	struct kfd_process_device *pdd;
2359	struct kgd_mem *kgd_mem;
2360	int ret;
2361	int j;
2362
2363	pr_debug("Restoring BO size:0x%llx addr:0x%llx gpu_id:0x%x flags:0x%x idr_handle:0x%x\n",
2364		 bo_bucket->size, bo_bucket->addr, bo_bucket->gpu_id, bo_bucket->alloc_flags,
2365		 bo_priv->idr_handle);
2366
2367	pdd = kfd_process_device_data_by_id(p, bo_bucket->gpu_id);
2368	if (!pdd) {
2369		pr_err("Failed to get pdd\n");
2370		return -ENODEV;
2371	}
2372
2373	ret = criu_restore_memory_of_gpu(pdd, bo_bucket, bo_priv, &kgd_mem);
2374	if (ret)
2375		return ret;
2376
2377	/* now map these BOs to GPU/s */
2378	for (j = 0; j < p->n_pdds; j++) {
2379		struct kfd_node *peer;
2380		struct kfd_process_device *peer_pdd;
2381
2382		if (!bo_priv->mapped_gpuids[j])
2383			break;
2384
2385		peer_pdd = kfd_process_device_data_by_id(p, bo_priv->mapped_gpuids[j]);
2386		if (!peer_pdd)
2387			return -EINVAL;
2388
2389		peer = peer_pdd->dev;
2390
2391		peer_pdd = kfd_bind_process_to_device(peer, p);
2392		if (IS_ERR(peer_pdd))
2393			return PTR_ERR(peer_pdd);
2394
2395		ret = amdgpu_amdkfd_gpuvm_map_memory_to_gpu(peer->adev, kgd_mem,
2396							    peer_pdd->drm_priv);
2397		if (ret) {
2398			pr_err("Failed to map to gpu %d/%d\n", j, p->n_pdds);
2399			return ret;
2400		}
2401	}
2402
2403	pr_debug("map memory was successful for the BO\n");
2404	/* create the dmabuf object and export the bo */
2405	if (bo_bucket->alloc_flags
2406	    & (KFD_IOC_ALLOC_MEM_FLAGS_VRAM | KFD_IOC_ALLOC_MEM_FLAGS_GTT)) {
2407		ret = criu_get_prime_handle(kgd_mem, DRM_RDWR,
2408					    &bo_bucket->dmabuf_fd);
2409		if (ret)
2410			return ret;
2411	} else {
2412		bo_bucket->dmabuf_fd = KFD_INVALID_FD;
2413	}
2414
2415	return 0;
2416}
2417
2418static int criu_restore_bos(struct kfd_process *p,
2419			    struct kfd_ioctl_criu_args *args,
2420			    uint64_t *priv_offset,
2421			    uint64_t max_priv_data_size)
2422{
2423	struct kfd_criu_bo_bucket *bo_buckets = NULL;
2424	struct kfd_criu_bo_priv_data *bo_privs = NULL;
2425	int ret = 0;
2426	uint32_t i = 0;
2427
2428	if (*priv_offset + (args->num_bos * sizeof(*bo_privs)) > max_priv_data_size)
2429		return -EINVAL;
2430
2431	/* Prevent MMU notifications until stage-4 IOCTL (CRIU_RESUME) is received */
2432	amdgpu_amdkfd_block_mmu_notifications(p->kgd_process_info);
2433
2434	bo_buckets = kvmalloc_array(args->num_bos, sizeof(*bo_buckets), GFP_KERNEL);
2435	if (!bo_buckets)
2436		return -ENOMEM;
2437
2438	ret = copy_from_user(bo_buckets, (void __user *)args->bos,
2439			     args->num_bos * sizeof(*bo_buckets));
2440	if (ret) {
2441		pr_err("Failed to copy BOs information from user\n");
2442		ret = -EFAULT;
2443		goto exit;
2444	}
2445
2446	bo_privs = kvmalloc_array(args->num_bos, sizeof(*bo_privs), GFP_KERNEL);
2447	if (!bo_privs) {
2448		ret = -ENOMEM;
2449		goto exit;
2450	}
2451
2452	ret = copy_from_user(bo_privs, (void __user *)args->priv_data + *priv_offset,
2453			     args->num_bos * sizeof(*bo_privs));
2454	if (ret) {
2455		pr_err("Failed to copy BOs information from user\n");
2456		ret = -EFAULT;
2457		goto exit;
2458	}
2459	*priv_offset += args->num_bos * sizeof(*bo_privs);
2460
2461	/* Create and map new BOs */
2462	for (; i < args->num_bos; i++) {
2463		ret = criu_restore_bo(p, &bo_buckets[i], &bo_privs[i]);
2464		if (ret) {
2465			pr_debug("Failed to restore BO[%d] ret%d\n", i, ret);
2466			goto exit;
2467		}
2468	} /* done */
2469
2470	/* Copy only the buckets back so user can read bo_buckets[N].restored_offset */
2471	ret = copy_to_user((void __user *)args->bos,
2472				bo_buckets,
2473				(args->num_bos * sizeof(*bo_buckets)));
2474	if (ret)
2475		ret = -EFAULT;
2476
2477exit:
2478	while (ret && i--) {
2479		if (bo_buckets[i].alloc_flags
2480		   & (KFD_IOC_ALLOC_MEM_FLAGS_VRAM | KFD_IOC_ALLOC_MEM_FLAGS_GTT))
2481			close_fd(bo_buckets[i].dmabuf_fd);
2482	}
2483	kvfree(bo_buckets);
2484	kvfree(bo_privs);
2485	return ret;
2486}
2487
2488static int criu_restore_objects(struct file *filep,
2489				struct kfd_process *p,
2490				struct kfd_ioctl_criu_args *args,
2491				uint64_t *priv_offset,
2492				uint64_t max_priv_data_size)
2493{
2494	int ret = 0;
2495	uint32_t i;
2496
2497	BUILD_BUG_ON(offsetof(struct kfd_criu_queue_priv_data, object_type));
2498	BUILD_BUG_ON(offsetof(struct kfd_criu_event_priv_data, object_type));
2499	BUILD_BUG_ON(offsetof(struct kfd_criu_svm_range_priv_data, object_type));
2500
2501	for (i = 0; i < args->num_objects; i++) {
2502		uint32_t object_type;
2503
2504		if (*priv_offset + sizeof(object_type) > max_priv_data_size) {
2505			pr_err("Invalid private data size\n");
2506			return -EINVAL;
2507		}
2508
2509		ret = get_user(object_type, (uint32_t __user *)(args->priv_data + *priv_offset));
2510		if (ret) {
2511			pr_err("Failed to copy private information from user\n");
2512			goto exit;
2513		}
2514
2515		switch (object_type) {
2516		case KFD_CRIU_OBJECT_TYPE_QUEUE:
2517			ret = kfd_criu_restore_queue(p, (uint8_t __user *)args->priv_data,
2518						     priv_offset, max_priv_data_size);
2519			if (ret)
2520				goto exit;
2521			break;
2522		case KFD_CRIU_OBJECT_TYPE_EVENT:
2523			ret = kfd_criu_restore_event(filep, p, (uint8_t __user *)args->priv_data,
2524						     priv_offset, max_priv_data_size);
2525			if (ret)
2526				goto exit;
2527			break;
2528		case KFD_CRIU_OBJECT_TYPE_SVM_RANGE:
2529			ret = kfd_criu_restore_svm(p, (uint8_t __user *)args->priv_data,
2530						     priv_offset, max_priv_data_size);
2531			if (ret)
2532				goto exit;
2533			break;
2534		default:
2535			pr_err("Invalid object type:%u at index:%d\n", object_type, i);
2536			ret = -EINVAL;
2537			goto exit;
2538		}
2539	}
2540exit:
2541	return ret;
2542}
2543
2544static int criu_restore(struct file *filep,
2545			struct kfd_process *p,
2546			struct kfd_ioctl_criu_args *args)
2547{
2548	uint64_t priv_offset = 0;
2549	int ret = 0;
2550
2551	pr_debug("CRIU restore (num_devices:%u num_bos:%u num_objects:%u priv_data_size:%llu)\n",
2552		 args->num_devices, args->num_bos, args->num_objects, args->priv_data_size);
2553
2554	if (!args->bos || !args->devices || !args->priv_data || !args->priv_data_size ||
2555	    !args->num_devices || !args->num_bos)
2556		return -EINVAL;
2557
2558	mutex_lock(&p->mutex);
2559
2560	/*
2561	 * Set the process to evicted state to avoid running any new queues before all the memory
2562	 * mappings are ready.
2563	 */
2564	ret = kfd_process_evict_queues(p, KFD_QUEUE_EVICTION_CRIU_RESTORE);
2565	if (ret)
2566		goto exit_unlock;
2567
2568	/* Each function will adjust priv_offset based on how many bytes they consumed */
2569	ret = criu_restore_process(p, args, &priv_offset, args->priv_data_size);
2570	if (ret)
2571		goto exit_unlock;
2572
2573	ret = criu_restore_devices(p, args, &priv_offset, args->priv_data_size);
2574	if (ret)
2575		goto exit_unlock;
2576
2577	ret = criu_restore_bos(p, args, &priv_offset, args->priv_data_size);
2578	if (ret)
2579		goto exit_unlock;
2580
2581	ret = criu_restore_objects(filep, p, args, &priv_offset, args->priv_data_size);
2582	if (ret)
2583		goto exit_unlock;
2584
2585	if (priv_offset != args->priv_data_size) {
2586		pr_err("Invalid private data size\n");
2587		ret = -EINVAL;
2588	}
2589
2590exit_unlock:
2591	mutex_unlock(&p->mutex);
2592	if (ret)
2593		pr_err("Failed to restore CRIU ret:%d\n", ret);
2594	else
2595		pr_debug("CRIU restore successful\n");
2596
2597	return ret;
2598}
2599
2600static int criu_unpause(struct file *filep,
2601			struct kfd_process *p,
2602			struct kfd_ioctl_criu_args *args)
2603{
2604	int ret;
2605
2606	mutex_lock(&p->mutex);
2607
2608	if (!p->queues_paused) {
2609		mutex_unlock(&p->mutex);
2610		return -EINVAL;
2611	}
2612
2613	ret = kfd_process_restore_queues(p);
2614	if (ret)
2615		pr_err("Failed to unpause queues ret:%d\n", ret);
2616	else
2617		p->queues_paused = false;
2618
2619	mutex_unlock(&p->mutex);
2620
2621	return ret;
2622}
2623
2624static int criu_resume(struct file *filep,
2625			struct kfd_process *p,
2626			struct kfd_ioctl_criu_args *args)
2627{
2628	struct kfd_process *target = NULL;
2629	struct pid *pid = NULL;
2630	int ret = 0;
2631
2632	pr_debug("Inside %s, target pid for criu restore: %d\n", __func__,
2633		 args->pid);
2634
2635	pid = find_get_pid(args->pid);
2636	if (!pid) {
2637		pr_err("Cannot find pid info for %i\n", args->pid);
2638		return -ESRCH;
2639	}
2640
2641	pr_debug("calling kfd_lookup_process_by_pid\n");
2642	target = kfd_lookup_process_by_pid(pid);
2643
2644	put_pid(pid);
2645
2646	if (!target) {
2647		pr_debug("Cannot find process info for %i\n", args->pid);
2648		return -ESRCH;
2649	}
2650
2651	mutex_lock(&target->mutex);
2652	ret = kfd_criu_resume_svm(target);
2653	if (ret) {
2654		pr_err("kfd_criu_resume_svm failed for %i\n", args->pid);
2655		goto exit;
2656	}
2657
2658	ret =  amdgpu_amdkfd_criu_resume(target->kgd_process_info);
2659	if (ret)
2660		pr_err("amdgpu_amdkfd_criu_resume failed for %i\n", args->pid);
2661
2662exit:
2663	mutex_unlock(&target->mutex);
2664
2665	kfd_unref_process(target);
2666	return ret;
2667}
2668
2669static int criu_process_info(struct file *filep,
2670				struct kfd_process *p,
2671				struct kfd_ioctl_criu_args *args)
2672{
2673	int ret = 0;
2674
2675	mutex_lock(&p->mutex);
2676
2677	if (!p->n_pdds) {
2678		pr_err("No pdd for given process\n");
2679		ret = -ENODEV;
2680		goto err_unlock;
2681	}
2682
2683	ret = kfd_process_evict_queues(p, KFD_QUEUE_EVICTION_CRIU_CHECKPOINT);
2684	if (ret)
2685		goto err_unlock;
2686
2687	p->queues_paused = true;
2688
2689	args->pid = task_pid_nr_ns(p->lead_thread,
2690					task_active_pid_ns(p->lead_thread));
2691
2692	ret = criu_get_process_object_info(p, &args->num_devices, &args->num_bos,
2693					   &args->num_objects, &args->priv_data_size);
2694	if (ret)
2695		goto err_unlock;
2696
2697	dev_dbg(kfd_device, "Num of devices:%u bos:%u objects:%u priv_data_size:%lld\n",
2698				args->num_devices, args->num_bos, args->num_objects,
2699				args->priv_data_size);
2700
2701err_unlock:
2702	if (ret) {
2703		kfd_process_restore_queues(p);
2704		p->queues_paused = false;
2705	}
2706	mutex_unlock(&p->mutex);
2707	return ret;
2708}
2709
2710static int kfd_ioctl_criu(struct file *filep, struct kfd_process *p, void *data)
2711{
2712	struct kfd_ioctl_criu_args *args = data;
2713	int ret;
2714
2715	dev_dbg(kfd_device, "CRIU operation: %d\n", args->op);
2716	switch (args->op) {
2717	case KFD_CRIU_OP_PROCESS_INFO:
2718		ret = criu_process_info(filep, p, args);
2719		break;
2720	case KFD_CRIU_OP_CHECKPOINT:
2721		ret = criu_checkpoint(filep, p, args);
2722		break;
2723	case KFD_CRIU_OP_UNPAUSE:
2724		ret = criu_unpause(filep, p, args);
2725		break;
2726	case KFD_CRIU_OP_RESTORE:
2727		ret = criu_restore(filep, p, args);
2728		break;
2729	case KFD_CRIU_OP_RESUME:
2730		ret = criu_resume(filep, p, args);
2731		break;
2732	default:
2733		dev_dbg(kfd_device, "Unsupported CRIU operation:%d\n", args->op);
2734		ret = -EINVAL;
2735		break;
2736	}
2737
2738	if (ret)
2739		dev_dbg(kfd_device, "CRIU operation:%d err:%d\n", args->op, ret);
2740
2741	return ret;
2742}
2743
2744static int runtime_enable(struct kfd_process *p, uint64_t r_debug,
2745			bool enable_ttmp_setup)
2746{
2747	int i = 0, ret = 0;
2748
2749	if (p->is_runtime_retry)
2750		goto retry;
2751
2752	if (p->runtime_info.runtime_state != DEBUG_RUNTIME_STATE_DISABLED)
2753		return -EBUSY;
2754
2755	for (i = 0; i < p->n_pdds; i++) {
2756		struct kfd_process_device *pdd = p->pdds[i];
2757
2758		if (pdd->qpd.queue_count)
2759			return -EEXIST;
2760
2761		/*
2762		 * Setup TTMPs by default.
2763		 * Note that this call must remain here for MES ADD QUEUE to
2764		 * skip_process_ctx_clear unconditionally as the first call to
2765		 * SET_SHADER_DEBUGGER clears any stale process context data
2766		 * saved in MES.
2767		 */
2768		if (pdd->dev->kfd->shared_resources.enable_mes)
2769			kfd_dbg_set_mes_debug_mode(pdd, !kfd_dbg_has_cwsr_workaround(pdd->dev));
2770	}
2771
2772	p->runtime_info.runtime_state = DEBUG_RUNTIME_STATE_ENABLED;
2773	p->runtime_info.r_debug = r_debug;
2774	p->runtime_info.ttmp_setup = enable_ttmp_setup;
2775
2776	if (p->runtime_info.ttmp_setup) {
2777		for (i = 0; i < p->n_pdds; i++) {
2778			struct kfd_process_device *pdd = p->pdds[i];
2779
2780			if (!kfd_dbg_is_rlc_restore_supported(pdd->dev)) {
2781				amdgpu_gfx_off_ctrl(pdd->dev->adev, false);
2782				pdd->dev->kfd2kgd->enable_debug_trap(
2783						pdd->dev->adev,
2784						true,
2785						pdd->dev->vm_info.last_vmid_kfd);
2786			} else if (kfd_dbg_is_per_vmid_supported(pdd->dev)) {
2787				pdd->spi_dbg_override = pdd->dev->kfd2kgd->enable_debug_trap(
2788						pdd->dev->adev,
2789						false,
2790						0);
2791			}
2792		}
2793	}
2794
2795retry:
2796	if (p->debug_trap_enabled) {
2797		if (!p->is_runtime_retry) {
2798			kfd_dbg_trap_activate(p);
2799			kfd_dbg_ev_raise(KFD_EC_MASK(EC_PROCESS_RUNTIME),
2800					p, NULL, 0, false, NULL, 0);
2801		}
2802
2803		mutex_unlock(&p->mutex);
2804		ret = down_interruptible(&p->runtime_enable_sema);
2805		mutex_lock(&p->mutex);
2806
2807		p->is_runtime_retry = !!ret;
2808	}
2809
2810	return ret;
2811}
2812
2813static int runtime_disable(struct kfd_process *p)
2814{
2815	int i = 0, ret;
2816	bool was_enabled = p->runtime_info.runtime_state == DEBUG_RUNTIME_STATE_ENABLED;
2817
2818	p->runtime_info.runtime_state = DEBUG_RUNTIME_STATE_DISABLED;
2819	p->runtime_info.r_debug = 0;
2820
2821	if (p->debug_trap_enabled) {
2822		if (was_enabled)
2823			kfd_dbg_trap_deactivate(p, false, 0);
2824
2825		if (!p->is_runtime_retry)
2826			kfd_dbg_ev_raise(KFD_EC_MASK(EC_PROCESS_RUNTIME),
2827					p, NULL, 0, false, NULL, 0);
2828
2829		mutex_unlock(&p->mutex);
2830		ret = down_interruptible(&p->runtime_enable_sema);
2831		mutex_lock(&p->mutex);
2832
2833		p->is_runtime_retry = !!ret;
2834		if (ret)
2835			return ret;
2836	}
2837
2838	if (was_enabled && p->runtime_info.ttmp_setup) {
2839		for (i = 0; i < p->n_pdds; i++) {
2840			struct kfd_process_device *pdd = p->pdds[i];
2841
2842			if (!kfd_dbg_is_rlc_restore_supported(pdd->dev))
2843				amdgpu_gfx_off_ctrl(pdd->dev->adev, true);
2844		}
2845	}
2846
2847	p->runtime_info.ttmp_setup = false;
2848
2849	/* disable ttmp setup */
2850	for (i = 0; i < p->n_pdds; i++) {
2851		struct kfd_process_device *pdd = p->pdds[i];
2852
2853		if (kfd_dbg_is_per_vmid_supported(pdd->dev)) {
2854			pdd->spi_dbg_override =
2855					pdd->dev->kfd2kgd->disable_debug_trap(
2856					pdd->dev->adev,
2857					false,
2858					pdd->dev->vm_info.last_vmid_kfd);
2859
2860			if (!pdd->dev->kfd->shared_resources.enable_mes)
2861				debug_refresh_runlist(pdd->dev->dqm);
2862			else
2863				kfd_dbg_set_mes_debug_mode(pdd,
2864							   !kfd_dbg_has_cwsr_workaround(pdd->dev));
2865		}
2866	}
2867
2868	return 0;
2869}
2870
2871static int kfd_ioctl_runtime_enable(struct file *filep, struct kfd_process *p, void *data)
2872{
2873	struct kfd_ioctl_runtime_enable_args *args = data;
2874	int r;
2875
2876	mutex_lock(&p->mutex);
2877
2878	if (args->mode_mask & KFD_RUNTIME_ENABLE_MODE_ENABLE_MASK)
2879		r = runtime_enable(p, args->r_debug,
2880				!!(args->mode_mask & KFD_RUNTIME_ENABLE_MODE_TTMP_SAVE_MASK));
2881	else
2882		r = runtime_disable(p);
2883
2884	mutex_unlock(&p->mutex);
2885
2886	return r;
2887}
2888
2889static int kfd_ioctl_set_debug_trap(struct file *filep, struct kfd_process *p, void *data)
2890{
2891	struct kfd_ioctl_dbg_trap_args *args = data;
2892	struct task_struct *thread = NULL;
2893	struct mm_struct *mm = NULL;
2894	struct pid *pid = NULL;
2895	struct kfd_process *target = NULL;
2896	struct kfd_process_device *pdd = NULL;
2897	int r = 0;
2898
2899	if (sched_policy == KFD_SCHED_POLICY_NO_HWS) {
2900		pr_err("Debugging does not support sched_policy %i", sched_policy);
2901		return -EINVAL;
2902	}
2903
2904	pid = find_get_pid(args->pid);
2905	if (!pid) {
2906		pr_debug("Cannot find pid info for %i\n", args->pid);
2907		r = -ESRCH;
2908		goto out;
2909	}
2910
2911	thread = get_pid_task(pid, PIDTYPE_PID);
2912	if (!thread) {
2913		r = -ESRCH;
2914		goto out;
2915	}
2916
2917	mm = get_task_mm(thread);
2918	if (!mm) {
2919		r = -ESRCH;
2920		goto out;
2921	}
2922
2923	if (args->op == KFD_IOC_DBG_TRAP_ENABLE) {
2924		bool create_process;
2925
2926		rcu_read_lock();
2927		create_process = thread && thread != current && ptrace_parent(thread) == current;
2928		rcu_read_unlock();
2929
2930		target = create_process ? kfd_create_process(thread) :
2931					kfd_lookup_process_by_pid(pid);
2932	} else {
2933		target = kfd_lookup_process_by_pid(pid);
2934	}
2935
2936	if (IS_ERR_OR_NULL(target)) {
2937		pr_debug("Cannot find process PID %i to debug\n", args->pid);
2938		r = target ? PTR_ERR(target) : -ESRCH;
2939		target = NULL;
2940		goto out;
2941	}
2942
2943	/* Check if target is still PTRACED. */
2944	rcu_read_lock();
2945	if (target != p && args->op != KFD_IOC_DBG_TRAP_DISABLE
2946				&& ptrace_parent(target->lead_thread) != current) {
2947		pr_err("PID %i is not PTRACED and cannot be debugged\n", args->pid);
2948		r = -EPERM;
2949	}
2950	rcu_read_unlock();
2951
2952	if (r)
2953		goto out;
2954
2955	mutex_lock(&target->mutex);
2956
2957	if (args->op != KFD_IOC_DBG_TRAP_ENABLE && !target->debug_trap_enabled) {
2958		pr_err("PID %i not debug enabled for op %i\n", args->pid, args->op);
2959		r = -EINVAL;
2960		goto unlock_out;
2961	}
2962
2963	if (target->runtime_info.runtime_state != DEBUG_RUNTIME_STATE_ENABLED &&
2964			(args->op == KFD_IOC_DBG_TRAP_SET_WAVE_LAUNCH_OVERRIDE ||
2965			 args->op == KFD_IOC_DBG_TRAP_SET_WAVE_LAUNCH_MODE ||
2966			 args->op == KFD_IOC_DBG_TRAP_SUSPEND_QUEUES ||
2967			 args->op == KFD_IOC_DBG_TRAP_RESUME_QUEUES ||
2968			 args->op == KFD_IOC_DBG_TRAP_SET_NODE_ADDRESS_WATCH ||
2969			 args->op == KFD_IOC_DBG_TRAP_CLEAR_NODE_ADDRESS_WATCH ||
2970			 args->op == KFD_IOC_DBG_TRAP_SET_FLAGS)) {
2971		r = -EPERM;
2972		goto unlock_out;
2973	}
2974
2975	if (args->op == KFD_IOC_DBG_TRAP_SET_NODE_ADDRESS_WATCH ||
2976	    args->op == KFD_IOC_DBG_TRAP_CLEAR_NODE_ADDRESS_WATCH) {
2977		int user_gpu_id = kfd_process_get_user_gpu_id(target,
2978				args->op == KFD_IOC_DBG_TRAP_SET_NODE_ADDRESS_WATCH ?
2979					args->set_node_address_watch.gpu_id :
2980					args->clear_node_address_watch.gpu_id);
2981
2982		pdd = kfd_process_device_data_by_id(target, user_gpu_id);
2983		if (user_gpu_id == -EINVAL || !pdd) {
2984			r = -ENODEV;
2985			goto unlock_out;
2986		}
2987	}
2988
2989	switch (args->op) {
2990	case KFD_IOC_DBG_TRAP_ENABLE:
2991		if (target != p)
2992			target->debugger_process = p;
2993
2994		r = kfd_dbg_trap_enable(target,
2995					args->enable.dbg_fd,
2996					(void __user *)args->enable.rinfo_ptr,
2997					&args->enable.rinfo_size);
2998		if (!r)
2999			target->exception_enable_mask = args->enable.exception_mask;
3000
3001		break;
3002	case KFD_IOC_DBG_TRAP_DISABLE:
3003		r = kfd_dbg_trap_disable(target);
3004		break;
3005	case KFD_IOC_DBG_TRAP_SEND_RUNTIME_EVENT:
3006		r = kfd_dbg_send_exception_to_runtime(target,
3007				args->send_runtime_event.gpu_id,
3008				args->send_runtime_event.queue_id,
3009				args->send_runtime_event.exception_mask);
3010		break;
3011	case KFD_IOC_DBG_TRAP_SET_EXCEPTIONS_ENABLED:
3012		kfd_dbg_set_enabled_debug_exception_mask(target,
3013				args->set_exceptions_enabled.exception_mask);
3014		break;
3015	case KFD_IOC_DBG_TRAP_SET_WAVE_LAUNCH_OVERRIDE:
3016		r = kfd_dbg_trap_set_wave_launch_override(target,
3017				args->launch_override.override_mode,
3018				args->launch_override.enable_mask,
3019				args->launch_override.support_request_mask,
3020				&args->launch_override.enable_mask,
3021				&args->launch_override.support_request_mask);
3022		break;
3023	case KFD_IOC_DBG_TRAP_SET_WAVE_LAUNCH_MODE:
3024		r = kfd_dbg_trap_set_wave_launch_mode(target,
3025				args->launch_mode.launch_mode);
3026		break;
3027	case KFD_IOC_DBG_TRAP_SUSPEND_QUEUES:
3028		r = suspend_queues(target,
3029				args->suspend_queues.num_queues,
3030				args->suspend_queues.grace_period,
3031				args->suspend_queues.exception_mask,
3032				(uint32_t *)args->suspend_queues.queue_array_ptr);
3033
3034		break;
3035	case KFD_IOC_DBG_TRAP_RESUME_QUEUES:
3036		r = resume_queues(target, args->resume_queues.num_queues,
3037				(uint32_t *)args->resume_queues.queue_array_ptr);
3038		break;
3039	case KFD_IOC_DBG_TRAP_SET_NODE_ADDRESS_WATCH:
3040		r = kfd_dbg_trap_set_dev_address_watch(pdd,
3041				args->set_node_address_watch.address,
3042				args->set_node_address_watch.mask,
3043				&args->set_node_address_watch.id,
3044				args->set_node_address_watch.mode);
3045		break;
3046	case KFD_IOC_DBG_TRAP_CLEAR_NODE_ADDRESS_WATCH:
3047		r = kfd_dbg_trap_clear_dev_address_watch(pdd,
3048				args->clear_node_address_watch.id);
3049		break;
3050	case KFD_IOC_DBG_TRAP_SET_FLAGS:
3051		r = kfd_dbg_trap_set_flags(target, &args->set_flags.flags);
3052		break;
3053	case KFD_IOC_DBG_TRAP_QUERY_DEBUG_EVENT:
3054		r = kfd_dbg_ev_query_debug_event(target,
3055				&args->query_debug_event.queue_id,
3056				&args->query_debug_event.gpu_id,
3057				args->query_debug_event.exception_mask,
3058				&args->query_debug_event.exception_mask);
3059		break;
3060	case KFD_IOC_DBG_TRAP_QUERY_EXCEPTION_INFO:
3061		r = kfd_dbg_trap_query_exception_info(target,
3062				args->query_exception_info.source_id,
3063				args->query_exception_info.exception_code,
3064				args->query_exception_info.clear_exception,
3065				(void __user *)args->query_exception_info.info_ptr,
3066				&args->query_exception_info.info_size);
3067		break;
3068	case KFD_IOC_DBG_TRAP_GET_QUEUE_SNAPSHOT:
3069		r = pqm_get_queue_snapshot(&target->pqm,
3070				args->queue_snapshot.exception_mask,
3071				(void __user *)args->queue_snapshot.snapshot_buf_ptr,
3072				&args->queue_snapshot.num_queues,
3073				&args->queue_snapshot.entry_size);
3074		break;
3075	case KFD_IOC_DBG_TRAP_GET_DEVICE_SNAPSHOT:
3076		r = kfd_dbg_trap_device_snapshot(target,
3077				args->device_snapshot.exception_mask,
3078				(void __user *)args->device_snapshot.snapshot_buf_ptr,
3079				&args->device_snapshot.num_devices,
3080				&args->device_snapshot.entry_size);
3081		break;
3082	default:
3083		pr_err("Invalid option: %i\n", args->op);
3084		r = -EINVAL;
3085	}
3086
3087unlock_out:
3088	mutex_unlock(&target->mutex);
3089
3090out:
3091	if (thread)
3092		put_task_struct(thread);
3093
3094	if (mm)
3095		mmput(mm);
3096
3097	if (pid)
3098		put_pid(pid);
3099
3100	if (target)
3101		kfd_unref_process(target);
3102
3103	return r;
3104}
3105
3106#define AMDKFD_IOCTL_DEF(ioctl, _func, _flags) \
3107	[_IOC_NR(ioctl)] = {.cmd = ioctl, .func = _func, .flags = _flags, \
3108			    .cmd_drv = 0, .name = #ioctl}
3109
3110/** Ioctl table */
3111static const struct amdkfd_ioctl_desc amdkfd_ioctls[] = {
3112	AMDKFD_IOCTL_DEF(AMDKFD_IOC_GET_VERSION,
3113			kfd_ioctl_get_version, 0),
3114
3115	AMDKFD_IOCTL_DEF(AMDKFD_IOC_CREATE_QUEUE,
3116			kfd_ioctl_create_queue, 0),
3117
3118	AMDKFD_IOCTL_DEF(AMDKFD_IOC_DESTROY_QUEUE,
3119			kfd_ioctl_destroy_queue, 0),
3120
3121	AMDKFD_IOCTL_DEF(AMDKFD_IOC_SET_MEMORY_POLICY,
3122			kfd_ioctl_set_memory_policy, 0),
3123
3124	AMDKFD_IOCTL_DEF(AMDKFD_IOC_GET_CLOCK_COUNTERS,
3125			kfd_ioctl_get_clock_counters, 0),
3126
3127	AMDKFD_IOCTL_DEF(AMDKFD_IOC_GET_PROCESS_APERTURES,
3128			kfd_ioctl_get_process_apertures, 0),
3129
3130	AMDKFD_IOCTL_DEF(AMDKFD_IOC_UPDATE_QUEUE,
3131			kfd_ioctl_update_queue, 0),
3132
3133	AMDKFD_IOCTL_DEF(AMDKFD_IOC_CREATE_EVENT,
3134			kfd_ioctl_create_event, 0),
3135
3136	AMDKFD_IOCTL_DEF(AMDKFD_IOC_DESTROY_EVENT,
3137			kfd_ioctl_destroy_event, 0),
3138
3139	AMDKFD_IOCTL_DEF(AMDKFD_IOC_SET_EVENT,
3140			kfd_ioctl_set_event, 0),
3141
3142	AMDKFD_IOCTL_DEF(AMDKFD_IOC_RESET_EVENT,
3143			kfd_ioctl_reset_event, 0),
3144
3145	AMDKFD_IOCTL_DEF(AMDKFD_IOC_WAIT_EVENTS,
3146			kfd_ioctl_wait_events, 0),
3147
3148	AMDKFD_IOCTL_DEF(AMDKFD_IOC_DBG_REGISTER_DEPRECATED,
3149			kfd_ioctl_dbg_register, 0),
3150
3151	AMDKFD_IOCTL_DEF(AMDKFD_IOC_DBG_UNREGISTER_DEPRECATED,
3152			kfd_ioctl_dbg_unregister, 0),
3153
3154	AMDKFD_IOCTL_DEF(AMDKFD_IOC_DBG_ADDRESS_WATCH_DEPRECATED,
3155			kfd_ioctl_dbg_address_watch, 0),
3156
3157	AMDKFD_IOCTL_DEF(AMDKFD_IOC_DBG_WAVE_CONTROL_DEPRECATED,
3158			kfd_ioctl_dbg_wave_control, 0),
3159
3160	AMDKFD_IOCTL_DEF(AMDKFD_IOC_SET_SCRATCH_BACKING_VA,
3161			kfd_ioctl_set_scratch_backing_va, 0),
3162
3163	AMDKFD_IOCTL_DEF(AMDKFD_IOC_GET_TILE_CONFIG,
3164			kfd_ioctl_get_tile_config, 0),
3165
3166	AMDKFD_IOCTL_DEF(AMDKFD_IOC_SET_TRAP_HANDLER,
3167			kfd_ioctl_set_trap_handler, 0),
3168
3169	AMDKFD_IOCTL_DEF(AMDKFD_IOC_GET_PROCESS_APERTURES_NEW,
3170			kfd_ioctl_get_process_apertures_new, 0),
3171
3172	AMDKFD_IOCTL_DEF(AMDKFD_IOC_ACQUIRE_VM,
3173			kfd_ioctl_acquire_vm, 0),
3174
3175	AMDKFD_IOCTL_DEF(AMDKFD_IOC_ALLOC_MEMORY_OF_GPU,
3176			kfd_ioctl_alloc_memory_of_gpu, 0),
3177
3178	AMDKFD_IOCTL_DEF(AMDKFD_IOC_FREE_MEMORY_OF_GPU,
3179			kfd_ioctl_free_memory_of_gpu, 0),
3180
3181	AMDKFD_IOCTL_DEF(AMDKFD_IOC_MAP_MEMORY_TO_GPU,
3182			kfd_ioctl_map_memory_to_gpu, 0),
3183
3184	AMDKFD_IOCTL_DEF(AMDKFD_IOC_UNMAP_MEMORY_FROM_GPU,
3185			kfd_ioctl_unmap_memory_from_gpu, 0),
3186
3187	AMDKFD_IOCTL_DEF(AMDKFD_IOC_SET_CU_MASK,
3188			kfd_ioctl_set_cu_mask, 0),
3189
3190	AMDKFD_IOCTL_DEF(AMDKFD_IOC_GET_QUEUE_WAVE_STATE,
3191			kfd_ioctl_get_queue_wave_state, 0),
3192
3193	AMDKFD_IOCTL_DEF(AMDKFD_IOC_GET_DMABUF_INFO,
3194				kfd_ioctl_get_dmabuf_info, 0),
3195
3196	AMDKFD_IOCTL_DEF(AMDKFD_IOC_IMPORT_DMABUF,
3197				kfd_ioctl_import_dmabuf, 0),
3198
3199	AMDKFD_IOCTL_DEF(AMDKFD_IOC_ALLOC_QUEUE_GWS,
3200			kfd_ioctl_alloc_queue_gws, 0),
3201
3202	AMDKFD_IOCTL_DEF(AMDKFD_IOC_SMI_EVENTS,
3203			kfd_ioctl_smi_events, 0),
3204
3205	AMDKFD_IOCTL_DEF(AMDKFD_IOC_SVM, kfd_ioctl_svm, 0),
3206
3207	AMDKFD_IOCTL_DEF(AMDKFD_IOC_SET_XNACK_MODE,
3208			kfd_ioctl_set_xnack_mode, 0),
3209
3210	AMDKFD_IOCTL_DEF(AMDKFD_IOC_CRIU_OP,
3211			kfd_ioctl_criu, KFD_IOC_FLAG_CHECKPOINT_RESTORE),
3212
3213	AMDKFD_IOCTL_DEF(AMDKFD_IOC_AVAILABLE_MEMORY,
3214			kfd_ioctl_get_available_memory, 0),
3215
3216	AMDKFD_IOCTL_DEF(AMDKFD_IOC_EXPORT_DMABUF,
3217				kfd_ioctl_export_dmabuf, 0),
3218
3219	AMDKFD_IOCTL_DEF(AMDKFD_IOC_RUNTIME_ENABLE,
3220			kfd_ioctl_runtime_enable, 0),
3221
3222	AMDKFD_IOCTL_DEF(AMDKFD_IOC_DBG_TRAP,
3223			kfd_ioctl_set_debug_trap, 0),
3224};
3225
3226#define AMDKFD_CORE_IOCTL_COUNT	ARRAY_SIZE(amdkfd_ioctls)
3227
3228static long kfd_ioctl(struct file *filep, unsigned int cmd, unsigned long arg)
3229{
3230	struct kfd_process *process;
3231	amdkfd_ioctl_t *func;
3232	const struct amdkfd_ioctl_desc *ioctl = NULL;
3233	unsigned int nr = _IOC_NR(cmd);
3234	char stack_kdata[128];
3235	char *kdata = NULL;
3236	unsigned int usize, asize;
3237	int retcode = -EINVAL;
3238	bool ptrace_attached = false;
3239
3240	if (nr >= AMDKFD_CORE_IOCTL_COUNT)
3241		goto err_i1;
3242
3243	if ((nr >= AMDKFD_COMMAND_START) && (nr < AMDKFD_COMMAND_END)) {
3244		u32 amdkfd_size;
3245
3246		ioctl = &amdkfd_ioctls[nr];
3247
3248		amdkfd_size = _IOC_SIZE(ioctl->cmd);
3249		usize = asize = _IOC_SIZE(cmd);
3250		if (amdkfd_size > asize)
3251			asize = amdkfd_size;
3252
3253		cmd = ioctl->cmd;
3254	} else
3255		goto err_i1;
3256
3257	dev_dbg(kfd_device, "ioctl cmd 0x%x (#0x%x), arg 0x%lx\n", cmd, nr, arg);
3258
3259	/* Get the process struct from the filep. Only the process
3260	 * that opened /dev/kfd can use the file descriptor. Child
3261	 * processes need to create their own KFD device context.
3262	 */
3263	process = filep->private_data;
3264
3265	rcu_read_lock();
3266	if ((ioctl->flags & KFD_IOC_FLAG_CHECKPOINT_RESTORE) &&
3267	    ptrace_parent(process->lead_thread) == current)
3268		ptrace_attached = true;
3269	rcu_read_unlock();
3270
3271	if (process->lead_thread != current->group_leader
3272	    && !ptrace_attached) {
3273		dev_dbg(kfd_device, "Using KFD FD in wrong process\n");
3274		retcode = -EBADF;
3275		goto err_i1;
3276	}
3277
3278	/* Do not trust userspace, use our own definition */
3279	func = ioctl->func;
3280
3281	if (unlikely(!func)) {
3282		dev_dbg(kfd_device, "no function\n");
3283		retcode = -EINVAL;
3284		goto err_i1;
3285	}
3286
3287	/*
3288	 * Versions of docker shipped in Ubuntu 18.xx and 20.xx do not support
3289	 * CAP_CHECKPOINT_RESTORE, so we also allow access if CAP_SYS_ADMIN as CAP_SYS_ADMIN is a
3290	 * more priviledged access.
3291	 */
3292	if (unlikely(ioctl->flags & KFD_IOC_FLAG_CHECKPOINT_RESTORE)) {
3293		if (!capable(CAP_CHECKPOINT_RESTORE) &&
3294						!capable(CAP_SYS_ADMIN)) {
3295			retcode = -EACCES;
3296			goto err_i1;
3297		}
3298	}
3299
3300	if (cmd & (IOC_IN | IOC_OUT)) {
3301		if (asize <= sizeof(stack_kdata)) {
3302			kdata = stack_kdata;
3303		} else {
3304			kdata = kmalloc(asize, GFP_KERNEL);
3305			if (!kdata) {
3306				retcode = -ENOMEM;
3307				goto err_i1;
3308			}
3309		}
3310		if (asize > usize)
3311			memset(kdata + usize, 0, asize - usize);
3312	}
3313
3314	if (cmd & IOC_IN) {
3315		if (copy_from_user(kdata, (void __user *)arg, usize) != 0) {
3316			retcode = -EFAULT;
3317			goto err_i1;
3318		}
3319	} else if (cmd & IOC_OUT) {
3320		memset(kdata, 0, usize);
3321	}
3322
3323	retcode = func(filep, process, kdata);
3324
3325	if (cmd & IOC_OUT)
3326		if (copy_to_user((void __user *)arg, kdata, usize) != 0)
3327			retcode = -EFAULT;
3328
3329err_i1:
3330	if (!ioctl)
3331		dev_dbg(kfd_device, "invalid ioctl: pid=%d, cmd=0x%02x, nr=0x%02x\n",
3332			  task_pid_nr(current), cmd, nr);
3333
3334	if (kdata != stack_kdata)
3335		kfree(kdata);
3336
3337	if (retcode)
3338		dev_dbg(kfd_device, "ioctl cmd (#0x%x), arg 0x%lx, ret = %d\n",
3339				nr, arg, retcode);
3340
3341	return retcode;
3342}
3343
3344static int kfd_mmio_mmap(struct kfd_node *dev, struct kfd_process *process,
3345		      struct vm_area_struct *vma)
3346{
3347	phys_addr_t address;
3348
3349	if (vma->vm_end - vma->vm_start != PAGE_SIZE)
3350		return -EINVAL;
3351
3352	address = dev->adev->rmmio_remap.bus_addr;
3353
3354	vm_flags_set(vma, VM_IO | VM_DONTCOPY | VM_DONTEXPAND | VM_NORESERVE |
3355				VM_DONTDUMP | VM_PFNMAP);
3356
3357	vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
3358
3359	pr_debug("pasid 0x%x mapping mmio page\n"
3360		 "     target user address == 0x%08llX\n"
3361		 "     physical address    == 0x%08llX\n"
3362		 "     vm_flags            == 0x%04lX\n"
3363		 "     size                == 0x%04lX\n",
3364		 process->pasid, (unsigned long long) vma->vm_start,
3365		 address, vma->vm_flags, PAGE_SIZE);
3366
3367	return io_remap_pfn_range(vma,
3368				vma->vm_start,
3369				address >> PAGE_SHIFT,
3370				PAGE_SIZE,
3371				vma->vm_page_prot);
3372}
3373
3374
3375static int kfd_mmap(struct file *filp, struct vm_area_struct *vma)
3376{
3377	struct kfd_process *process;
3378	struct kfd_node *dev = NULL;
3379	unsigned long mmap_offset;
3380	unsigned int gpu_id;
3381
3382	process = kfd_get_process(current);
3383	if (IS_ERR(process))
3384		return PTR_ERR(process);
3385
3386	mmap_offset = vma->vm_pgoff << PAGE_SHIFT;
3387	gpu_id = KFD_MMAP_GET_GPU_ID(mmap_offset);
3388	if (gpu_id)
3389		dev = kfd_device_by_id(gpu_id);
3390
3391	switch (mmap_offset & KFD_MMAP_TYPE_MASK) {
3392	case KFD_MMAP_TYPE_DOORBELL:
3393		if (!dev)
3394			return -ENODEV;
3395		return kfd_doorbell_mmap(dev, process, vma);
3396
3397	case KFD_MMAP_TYPE_EVENTS:
3398		return kfd_event_mmap(process, vma);
3399
3400	case KFD_MMAP_TYPE_RESERVED_MEM:
3401		if (!dev)
3402			return -ENODEV;
3403		return kfd_reserved_mem_mmap(dev, process, vma);
3404	case KFD_MMAP_TYPE_MMIO:
3405		if (!dev)
3406			return -ENODEV;
3407		return kfd_mmio_mmap(dev, process, vma);
3408	}
3409
3410	return -EFAULT;
3411}
3412