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