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