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