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 	bool table_freed = false;
1150 
1151 	if (!args->n_devices) {
1152 		pr_debug("Device IDs array empty\n");
1153 		return -EINVAL;
1154 	}
1155 	if (args->n_success > args->n_devices) {
1156 		pr_debug("n_success exceeds n_devices\n");
1157 		return -EINVAL;
1158 	}
1159 
1160 	devices_arr = kmalloc_array(args->n_devices, sizeof(*devices_arr),
1161 				    GFP_KERNEL);
1162 	if (!devices_arr)
1163 		return -ENOMEM;
1164 
1165 	err = copy_from_user(devices_arr,
1166 			     (void __user *)args->device_ids_array_ptr,
1167 			     args->n_devices * sizeof(*devices_arr));
1168 	if (err != 0) {
1169 		err = -EFAULT;
1170 		goto copy_from_user_failed;
1171 	}
1172 
1173 	mutex_lock(&p->mutex);
1174 	pdd = kfd_process_device_data_by_id(p, GET_GPU_ID(args->handle));
1175 	if (!pdd) {
1176 		err = -EINVAL;
1177 		goto get_process_device_data_failed;
1178 	}
1179 	dev = pdd->dev;
1180 
1181 	pdd = kfd_bind_process_to_device(dev, p);
1182 	if (IS_ERR(pdd)) {
1183 		err = PTR_ERR(pdd);
1184 		goto bind_process_to_device_failed;
1185 	}
1186 
1187 	mem = kfd_process_device_translate_handle(pdd,
1188 						GET_IDR_HANDLE(args->handle));
1189 	if (!mem) {
1190 		err = -ENOMEM;
1191 		goto get_mem_obj_from_handle_failed;
1192 	}
1193 
1194 	for (i = args->n_success; i < args->n_devices; i++) {
1195 		peer_pdd = kfd_process_device_data_by_id(p, devices_arr[i]);
1196 		if (!peer_pdd) {
1197 			pr_debug("Getting device by id failed for 0x%x\n",
1198 				 devices_arr[i]);
1199 			err = -EINVAL;
1200 			goto get_mem_obj_from_handle_failed;
1201 		}
1202 
1203 		peer_pdd = kfd_bind_process_to_device(peer_pdd->dev, p);
1204 		if (IS_ERR(peer_pdd)) {
1205 			err = PTR_ERR(peer_pdd);
1206 			goto get_mem_obj_from_handle_failed;
1207 		}
1208 
1209 		err = amdgpu_amdkfd_gpuvm_map_memory_to_gpu(
1210 			peer_pdd->dev->adev, (struct kgd_mem *)mem,
1211 			peer_pdd->drm_priv, &table_freed);
1212 		if (err) {
1213 			struct pci_dev *pdev = peer_pdd->dev->adev->pdev;
1214 
1215 			dev_err(dev->adev->dev,
1216 			       "Failed to map peer:%04x:%02x:%02x.%d mem_domain:%d\n",
1217 			       pci_domain_nr(pdev->bus),
1218 			       pdev->bus->number,
1219 			       PCI_SLOT(pdev->devfn),
1220 			       PCI_FUNC(pdev->devfn),
1221 			       ((struct kgd_mem *)mem)->domain);
1222 			goto map_memory_to_gpu_failed;
1223 		}
1224 		args->n_success = i+1;
1225 	}
1226 
1227 	mutex_unlock(&p->mutex);
1228 
1229 	err = amdgpu_amdkfd_gpuvm_sync_memory(dev->adev, (struct kgd_mem *) mem, true);
1230 	if (err) {
1231 		pr_debug("Sync memory failed, wait interrupted by user signal\n");
1232 		goto sync_memory_failed;
1233 	}
1234 
1235 	/* Flush TLBs after waiting for the page table updates to complete */
1236 	if (table_freed || !kfd_flush_tlb_after_unmap(dev)) {
1237 		for (i = 0; i < args->n_devices; i++) {
1238 			peer_pdd = kfd_process_device_data_by_id(p, devices_arr[i]);
1239 			if (WARN_ON_ONCE(!peer_pdd))
1240 				continue;
1241 			kfd_flush_tlb(peer_pdd, TLB_FLUSH_LEGACY);
1242 		}
1243 	}
1244 	kfree(devices_arr);
1245 
1246 	return err;
1247 
1248 get_process_device_data_failed:
1249 bind_process_to_device_failed:
1250 get_mem_obj_from_handle_failed:
1251 map_memory_to_gpu_failed:
1252 	mutex_unlock(&p->mutex);
1253 copy_from_user_failed:
1254 sync_memory_failed:
1255 	kfree(devices_arr);
1256 
1257 	return err;
1258 }
1259 
1260 static int kfd_ioctl_unmap_memory_from_gpu(struct file *filep,
1261 					struct kfd_process *p, void *data)
1262 {
1263 	struct kfd_ioctl_unmap_memory_from_gpu_args *args = data;
1264 	struct kfd_process_device *pdd, *peer_pdd;
1265 	void *mem;
1266 	long err = 0;
1267 	uint32_t *devices_arr = NULL, i;
1268 
1269 	if (!args->n_devices) {
1270 		pr_debug("Device IDs array empty\n");
1271 		return -EINVAL;
1272 	}
1273 	if (args->n_success > args->n_devices) {
1274 		pr_debug("n_success exceeds n_devices\n");
1275 		return -EINVAL;
1276 	}
1277 
1278 	devices_arr = kmalloc_array(args->n_devices, sizeof(*devices_arr),
1279 				    GFP_KERNEL);
1280 	if (!devices_arr)
1281 		return -ENOMEM;
1282 
1283 	err = copy_from_user(devices_arr,
1284 			     (void __user *)args->device_ids_array_ptr,
1285 			     args->n_devices * sizeof(*devices_arr));
1286 	if (err != 0) {
1287 		err = -EFAULT;
1288 		goto copy_from_user_failed;
1289 	}
1290 
1291 	mutex_lock(&p->mutex);
1292 	pdd = kfd_process_device_data_by_id(p, GET_GPU_ID(args->handle));
1293 	if (!pdd) {
1294 		err = -EINVAL;
1295 		goto bind_process_to_device_failed;
1296 	}
1297 
1298 	mem = kfd_process_device_translate_handle(pdd,
1299 						GET_IDR_HANDLE(args->handle));
1300 	if (!mem) {
1301 		err = -ENOMEM;
1302 		goto get_mem_obj_from_handle_failed;
1303 	}
1304 
1305 	for (i = args->n_success; i < args->n_devices; i++) {
1306 		peer_pdd = kfd_process_device_data_by_id(p, devices_arr[i]);
1307 		if (!peer_pdd) {
1308 			err = -EINVAL;
1309 			goto get_mem_obj_from_handle_failed;
1310 		}
1311 		err = amdgpu_amdkfd_gpuvm_unmap_memory_from_gpu(
1312 			peer_pdd->dev->adev, (struct kgd_mem *)mem, peer_pdd->drm_priv);
1313 		if (err) {
1314 			pr_err("Failed to unmap from gpu %d/%d\n",
1315 			       i, args->n_devices);
1316 			goto unmap_memory_from_gpu_failed;
1317 		}
1318 		args->n_success = i+1;
1319 	}
1320 	mutex_unlock(&p->mutex);
1321 
1322 	if (kfd_flush_tlb_after_unmap(pdd->dev)) {
1323 		err = amdgpu_amdkfd_gpuvm_sync_memory(pdd->dev->adev,
1324 				(struct kgd_mem *) mem, true);
1325 		if (err) {
1326 			pr_debug("Sync memory failed, wait interrupted by user signal\n");
1327 			goto sync_memory_failed;
1328 		}
1329 
1330 		/* Flush TLBs after waiting for the page table updates to complete */
1331 		for (i = 0; i < args->n_devices; i++) {
1332 			peer_pdd = kfd_process_device_data_by_id(p, devices_arr[i]);
1333 			if (WARN_ON_ONCE(!peer_pdd))
1334 				continue;
1335 			kfd_flush_tlb(peer_pdd, TLB_FLUSH_HEAVYWEIGHT);
1336 		}
1337 	}
1338 	kfree(devices_arr);
1339 
1340 	return 0;
1341 
1342 bind_process_to_device_failed:
1343 get_mem_obj_from_handle_failed:
1344 unmap_memory_from_gpu_failed:
1345 	mutex_unlock(&p->mutex);
1346 copy_from_user_failed:
1347 sync_memory_failed:
1348 	kfree(devices_arr);
1349 	return err;
1350 }
1351 
1352 static int kfd_ioctl_alloc_queue_gws(struct file *filep,
1353 		struct kfd_process *p, void *data)
1354 {
1355 	int retval;
1356 	struct kfd_ioctl_alloc_queue_gws_args *args = data;
1357 	struct queue *q;
1358 	struct kfd_dev *dev;
1359 
1360 	mutex_lock(&p->mutex);
1361 	q = pqm_get_user_queue(&p->pqm, args->queue_id);
1362 
1363 	if (q) {
1364 		dev = q->device;
1365 	} else {
1366 		retval = -EINVAL;
1367 		goto out_unlock;
1368 	}
1369 
1370 	if (!dev->gws) {
1371 		retval = -ENODEV;
1372 		goto out_unlock;
1373 	}
1374 
1375 	if (dev->dqm->sched_policy == KFD_SCHED_POLICY_NO_HWS) {
1376 		retval = -ENODEV;
1377 		goto out_unlock;
1378 	}
1379 
1380 	retval = pqm_set_gws(&p->pqm, args->queue_id, args->num_gws ? dev->gws : NULL);
1381 	mutex_unlock(&p->mutex);
1382 
1383 	args->first_gws = 0;
1384 	return retval;
1385 
1386 out_unlock:
1387 	mutex_unlock(&p->mutex);
1388 	return retval;
1389 }
1390 
1391 static int kfd_ioctl_get_dmabuf_info(struct file *filep,
1392 		struct kfd_process *p, void *data)
1393 {
1394 	struct kfd_ioctl_get_dmabuf_info_args *args = data;
1395 	struct kfd_dev *dev = NULL;
1396 	struct amdgpu_device *dmabuf_adev;
1397 	void *metadata_buffer = NULL;
1398 	uint32_t flags;
1399 	unsigned int i;
1400 	int r;
1401 
1402 	/* Find a KFD GPU device that supports the get_dmabuf_info query */
1403 	for (i = 0; kfd_topology_enum_kfd_devices(i, &dev) == 0; i++)
1404 		if (dev)
1405 			break;
1406 	if (!dev)
1407 		return -EINVAL;
1408 
1409 	if (args->metadata_ptr) {
1410 		metadata_buffer = kzalloc(args->metadata_size, GFP_KERNEL);
1411 		if (!metadata_buffer)
1412 			return -ENOMEM;
1413 	}
1414 
1415 	/* Get dmabuf info from KGD */
1416 	r = amdgpu_amdkfd_get_dmabuf_info(dev->adev, args->dmabuf_fd,
1417 					  &dmabuf_adev, &args->size,
1418 					  metadata_buffer, args->metadata_size,
1419 					  &args->metadata_size, &flags);
1420 	if (r)
1421 		goto exit;
1422 
1423 	/* Reverse-lookup gpu_id from kgd pointer */
1424 	dev = kfd_device_by_adev(dmabuf_adev);
1425 	if (!dev) {
1426 		r = -EINVAL;
1427 		goto exit;
1428 	}
1429 	args->gpu_id = dev->id;
1430 	args->flags = flags;
1431 
1432 	/* Copy metadata buffer to user mode */
1433 	if (metadata_buffer) {
1434 		r = copy_to_user((void __user *)args->metadata_ptr,
1435 				 metadata_buffer, args->metadata_size);
1436 		if (r != 0)
1437 			r = -EFAULT;
1438 	}
1439 
1440 exit:
1441 	kfree(metadata_buffer);
1442 
1443 	return r;
1444 }
1445 
1446 static int kfd_ioctl_import_dmabuf(struct file *filep,
1447 				   struct kfd_process *p, void *data)
1448 {
1449 	struct kfd_ioctl_import_dmabuf_args *args = data;
1450 	struct kfd_process_device *pdd;
1451 	struct dma_buf *dmabuf;
1452 	int idr_handle;
1453 	uint64_t size;
1454 	void *mem;
1455 	int r;
1456 
1457 	dmabuf = dma_buf_get(args->dmabuf_fd);
1458 	if (IS_ERR(dmabuf))
1459 		return PTR_ERR(dmabuf);
1460 
1461 	mutex_lock(&p->mutex);
1462 	pdd = kfd_process_device_data_by_id(p, args->gpu_id);
1463 	if (!pdd) {
1464 		r = -EINVAL;
1465 		goto err_unlock;
1466 	}
1467 
1468 	pdd = kfd_bind_process_to_device(pdd->dev, p);
1469 	if (IS_ERR(pdd)) {
1470 		r = PTR_ERR(pdd);
1471 		goto err_unlock;
1472 	}
1473 
1474 	r = amdgpu_amdkfd_gpuvm_import_dmabuf(pdd->dev->adev, dmabuf,
1475 					      args->va_addr, pdd->drm_priv,
1476 					      (struct kgd_mem **)&mem, &size,
1477 					      NULL);
1478 	if (r)
1479 		goto err_unlock;
1480 
1481 	idr_handle = kfd_process_device_create_obj_handle(pdd, mem);
1482 	if (idr_handle < 0) {
1483 		r = -EFAULT;
1484 		goto err_free;
1485 	}
1486 
1487 	mutex_unlock(&p->mutex);
1488 	dma_buf_put(dmabuf);
1489 
1490 	args->handle = MAKE_HANDLE(args->gpu_id, idr_handle);
1491 
1492 	return 0;
1493 
1494 err_free:
1495 	amdgpu_amdkfd_gpuvm_free_memory_of_gpu(pdd->dev->adev, (struct kgd_mem *)mem,
1496 					       pdd->drm_priv, NULL);
1497 err_unlock:
1498 	mutex_unlock(&p->mutex);
1499 	dma_buf_put(dmabuf);
1500 	return r;
1501 }
1502 
1503 /* Handle requests for watching SMI events */
1504 static int kfd_ioctl_smi_events(struct file *filep,
1505 				struct kfd_process *p, void *data)
1506 {
1507 	struct kfd_ioctl_smi_events_args *args = data;
1508 	struct kfd_process_device *pdd;
1509 
1510 	mutex_lock(&p->mutex);
1511 
1512 	pdd = kfd_process_device_data_by_id(p, args->gpuid);
1513 	mutex_unlock(&p->mutex);
1514 	if (!pdd)
1515 		return -EINVAL;
1516 
1517 	return kfd_smi_event_open(pdd->dev, &args->anon_fd);
1518 }
1519 
1520 static int kfd_ioctl_set_xnack_mode(struct file *filep,
1521 				    struct kfd_process *p, void *data)
1522 {
1523 	struct kfd_ioctl_set_xnack_mode_args *args = data;
1524 	int r = 0;
1525 
1526 	mutex_lock(&p->mutex);
1527 	if (args->xnack_enabled >= 0) {
1528 		if (!list_empty(&p->pqm.queues)) {
1529 			pr_debug("Process has user queues running\n");
1530 			mutex_unlock(&p->mutex);
1531 			return -EBUSY;
1532 		}
1533 		if (args->xnack_enabled && !kfd_process_xnack_mode(p, true))
1534 			r = -EPERM;
1535 		else
1536 			p->xnack_enabled = args->xnack_enabled;
1537 	} else {
1538 		args->xnack_enabled = p->xnack_enabled;
1539 	}
1540 	mutex_unlock(&p->mutex);
1541 
1542 	return r;
1543 }
1544 
1545 #if IS_ENABLED(CONFIG_HSA_AMD_SVM)
1546 static int kfd_ioctl_svm(struct file *filep, struct kfd_process *p, void *data)
1547 {
1548 	struct kfd_ioctl_svm_args *args = data;
1549 	int r = 0;
1550 
1551 	pr_debug("start 0x%llx size 0x%llx op 0x%x nattr 0x%x\n",
1552 		 args->start_addr, args->size, args->op, args->nattr);
1553 
1554 	if ((args->start_addr & ~PAGE_MASK) || (args->size & ~PAGE_MASK))
1555 		return -EINVAL;
1556 	if (!args->start_addr || !args->size)
1557 		return -EINVAL;
1558 
1559 	r = svm_ioctl(p, args->op, args->start_addr, args->size, args->nattr,
1560 		      args->attrs);
1561 
1562 	return r;
1563 }
1564 #else
1565 static int kfd_ioctl_svm(struct file *filep, struct kfd_process *p, void *data)
1566 {
1567 	return -EPERM;
1568 }
1569 #endif
1570 
1571 static int criu_checkpoint_process(struct kfd_process *p,
1572 			     uint8_t __user *user_priv_data,
1573 			     uint64_t *priv_offset)
1574 {
1575 	struct kfd_criu_process_priv_data process_priv;
1576 	int ret;
1577 
1578 	memset(&process_priv, 0, sizeof(process_priv));
1579 
1580 	process_priv.version = KFD_CRIU_PRIV_VERSION;
1581 	/* For CR, we don't consider negative xnack mode which is used for
1582 	 * querying without changing it, here 0 simply means disabled and 1
1583 	 * means enabled so retry for finding a valid PTE.
1584 	 */
1585 	process_priv.xnack_mode = p->xnack_enabled ? 1 : 0;
1586 
1587 	ret = copy_to_user(user_priv_data + *priv_offset,
1588 				&process_priv, sizeof(process_priv));
1589 
1590 	if (ret) {
1591 		pr_err("Failed to copy process information to user\n");
1592 		ret = -EFAULT;
1593 	}
1594 
1595 	*priv_offset += sizeof(process_priv);
1596 	return ret;
1597 }
1598 
1599 static int criu_checkpoint_devices(struct kfd_process *p,
1600 			     uint32_t num_devices,
1601 			     uint8_t __user *user_addr,
1602 			     uint8_t __user *user_priv_data,
1603 			     uint64_t *priv_offset)
1604 {
1605 	struct kfd_criu_device_priv_data *device_priv = NULL;
1606 	struct kfd_criu_device_bucket *device_buckets = NULL;
1607 	int ret = 0, i;
1608 
1609 	device_buckets = kvzalloc(num_devices * sizeof(*device_buckets), GFP_KERNEL);
1610 	if (!device_buckets) {
1611 		ret = -ENOMEM;
1612 		goto exit;
1613 	}
1614 
1615 	device_priv = kvzalloc(num_devices * sizeof(*device_priv), GFP_KERNEL);
1616 	if (!device_priv) {
1617 		ret = -ENOMEM;
1618 		goto exit;
1619 	}
1620 
1621 	for (i = 0; i < num_devices; i++) {
1622 		struct kfd_process_device *pdd = p->pdds[i];
1623 
1624 		device_buckets[i].user_gpu_id = pdd->user_gpu_id;
1625 		device_buckets[i].actual_gpu_id = pdd->dev->id;
1626 
1627 		/*
1628 		 * priv_data does not contain useful information for now and is reserved for
1629 		 * future use, so we do not set its contents.
1630 		 */
1631 	}
1632 
1633 	ret = copy_to_user(user_addr, device_buckets, num_devices * sizeof(*device_buckets));
1634 	if (ret) {
1635 		pr_err("Failed to copy device information to user\n");
1636 		ret = -EFAULT;
1637 		goto exit;
1638 	}
1639 
1640 	ret = copy_to_user(user_priv_data + *priv_offset,
1641 			   device_priv,
1642 			   num_devices * sizeof(*device_priv));
1643 	if (ret) {
1644 		pr_err("Failed to copy device information to user\n");
1645 		ret = -EFAULT;
1646 	}
1647 	*priv_offset += num_devices * sizeof(*device_priv);
1648 
1649 exit:
1650 	kvfree(device_buckets);
1651 	kvfree(device_priv);
1652 	return ret;
1653 }
1654 
1655 static uint32_t get_process_num_bos(struct kfd_process *p)
1656 {
1657 	uint32_t num_of_bos = 0;
1658 	int i;
1659 
1660 	/* Run over all PDDs of the process */
1661 	for (i = 0; i < p->n_pdds; i++) {
1662 		struct kfd_process_device *pdd = p->pdds[i];
1663 		void *mem;
1664 		int id;
1665 
1666 		idr_for_each_entry(&pdd->alloc_idr, mem, id) {
1667 			struct kgd_mem *kgd_mem = (struct kgd_mem *)mem;
1668 
1669 			if ((uint64_t)kgd_mem->va > pdd->gpuvm_base)
1670 				num_of_bos++;
1671 		}
1672 	}
1673 	return num_of_bos;
1674 }
1675 
1676 static int criu_get_prime_handle(struct drm_gem_object *gobj, int flags,
1677 				      u32 *shared_fd)
1678 {
1679 	struct dma_buf *dmabuf;
1680 	int ret;
1681 
1682 	dmabuf = amdgpu_gem_prime_export(gobj, flags);
1683 	if (IS_ERR(dmabuf)) {
1684 		ret = PTR_ERR(dmabuf);
1685 		pr_err("dmabuf export failed for the BO\n");
1686 		return ret;
1687 	}
1688 
1689 	ret = dma_buf_fd(dmabuf, flags);
1690 	if (ret < 0) {
1691 		pr_err("dmabuf create fd failed, ret:%d\n", ret);
1692 		goto out_free_dmabuf;
1693 	}
1694 
1695 	*shared_fd = ret;
1696 	return 0;
1697 
1698 out_free_dmabuf:
1699 	dma_buf_put(dmabuf);
1700 	return ret;
1701 }
1702 
1703 static int criu_checkpoint_bos(struct kfd_process *p,
1704 			       uint32_t num_bos,
1705 			       uint8_t __user *user_bos,
1706 			       uint8_t __user *user_priv_data,
1707 			       uint64_t *priv_offset)
1708 {
1709 	struct kfd_criu_bo_bucket *bo_buckets;
1710 	struct kfd_criu_bo_priv_data *bo_privs;
1711 	int ret = 0, pdd_index, bo_index = 0, id;
1712 	void *mem;
1713 
1714 	bo_buckets = kvzalloc(num_bos * sizeof(*bo_buckets), GFP_KERNEL);
1715 	if (!bo_buckets)
1716 		return -ENOMEM;
1717 
1718 	bo_privs = kvzalloc(num_bos * sizeof(*bo_privs), GFP_KERNEL);
1719 	if (!bo_privs) {
1720 		ret = -ENOMEM;
1721 		goto exit;
1722 	}
1723 
1724 	for (pdd_index = 0; pdd_index < p->n_pdds; pdd_index++) {
1725 		struct kfd_process_device *pdd = p->pdds[pdd_index];
1726 		struct amdgpu_bo *dumper_bo;
1727 		struct kgd_mem *kgd_mem;
1728 
1729 		idr_for_each_entry(&pdd->alloc_idr, mem, id) {
1730 			struct kfd_criu_bo_bucket *bo_bucket;
1731 			struct kfd_criu_bo_priv_data *bo_priv;
1732 			int i, dev_idx = 0;
1733 
1734 			if (!mem) {
1735 				ret = -ENOMEM;
1736 				goto exit;
1737 			}
1738 
1739 			kgd_mem = (struct kgd_mem *)mem;
1740 			dumper_bo = kgd_mem->bo;
1741 
1742 			if ((uint64_t)kgd_mem->va <= pdd->gpuvm_base)
1743 				continue;
1744 
1745 			bo_bucket = &bo_buckets[bo_index];
1746 			bo_priv = &bo_privs[bo_index];
1747 
1748 			bo_bucket->gpu_id = pdd->user_gpu_id;
1749 			bo_bucket->addr = (uint64_t)kgd_mem->va;
1750 			bo_bucket->size = amdgpu_bo_size(dumper_bo);
1751 			bo_bucket->alloc_flags = (uint32_t)kgd_mem->alloc_flags;
1752 			bo_priv->idr_handle = id;
1753 
1754 			if (bo_bucket->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_USERPTR) {
1755 				ret = amdgpu_ttm_tt_get_userptr(&dumper_bo->tbo,
1756 								&bo_priv->user_addr);
1757 				if (ret) {
1758 					pr_err("Failed to obtain user address for user-pointer bo\n");
1759 					goto exit;
1760 				}
1761 			}
1762 			if (bo_bucket->alloc_flags
1763 			    & (KFD_IOC_ALLOC_MEM_FLAGS_VRAM | KFD_IOC_ALLOC_MEM_FLAGS_GTT)) {
1764 				ret = criu_get_prime_handle(&dumper_bo->tbo.base,
1765 						bo_bucket->alloc_flags &
1766 						KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE ? DRM_RDWR : 0,
1767 						&bo_bucket->dmabuf_fd);
1768 				if (ret)
1769 					goto exit;
1770 			} else {
1771 				bo_bucket->dmabuf_fd = KFD_INVALID_FD;
1772 			}
1773 
1774 			if (bo_bucket->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL)
1775 				bo_bucket->offset = KFD_MMAP_TYPE_DOORBELL |
1776 					KFD_MMAP_GPU_ID(pdd->dev->id);
1777 			else if (bo_bucket->alloc_flags &
1778 				KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)
1779 				bo_bucket->offset = KFD_MMAP_TYPE_MMIO |
1780 					KFD_MMAP_GPU_ID(pdd->dev->id);
1781 			else
1782 				bo_bucket->offset = amdgpu_bo_mmap_offset(dumper_bo);
1783 
1784 			for (i = 0; i < p->n_pdds; i++) {
1785 				if (amdgpu_amdkfd_bo_mapped_to_dev(p->pdds[i]->dev->adev, kgd_mem))
1786 					bo_priv->mapped_gpuids[dev_idx++] = p->pdds[i]->user_gpu_id;
1787 			}
1788 
1789 			pr_debug("bo_size = 0x%llx, bo_addr = 0x%llx bo_offset = 0x%llx\n"
1790 					"gpu_id = 0x%x alloc_flags = 0x%x idr_handle = 0x%x",
1791 					bo_bucket->size,
1792 					bo_bucket->addr,
1793 					bo_bucket->offset,
1794 					bo_bucket->gpu_id,
1795 					bo_bucket->alloc_flags,
1796 					bo_priv->idr_handle);
1797 			bo_index++;
1798 		}
1799 	}
1800 
1801 	ret = copy_to_user(user_bos, bo_buckets, num_bos * sizeof(*bo_buckets));
1802 	if (ret) {
1803 		pr_err("Failed to copy BO information to user\n");
1804 		ret = -EFAULT;
1805 		goto exit;
1806 	}
1807 
1808 	ret = copy_to_user(user_priv_data + *priv_offset, bo_privs, num_bos * sizeof(*bo_privs));
1809 	if (ret) {
1810 		pr_err("Failed to copy BO priv information to user\n");
1811 		ret = -EFAULT;
1812 		goto exit;
1813 	}
1814 
1815 	*priv_offset += num_bos * sizeof(*bo_privs);
1816 
1817 exit:
1818 	while (ret && bo_index--) {
1819 		if (bo_buckets[bo_index].alloc_flags
1820 		    & (KFD_IOC_ALLOC_MEM_FLAGS_VRAM | KFD_IOC_ALLOC_MEM_FLAGS_GTT))
1821 			close_fd(bo_buckets[bo_index].dmabuf_fd);
1822 	}
1823 
1824 	kvfree(bo_buckets);
1825 	kvfree(bo_privs);
1826 	return ret;
1827 }
1828 
1829 static int criu_get_process_object_info(struct kfd_process *p,
1830 					uint32_t *num_devices,
1831 					uint32_t *num_bos,
1832 					uint32_t *num_objects,
1833 					uint64_t *objs_priv_size)
1834 {
1835 	uint64_t queues_priv_data_size, svm_priv_data_size, priv_size;
1836 	uint32_t num_queues, num_events, num_svm_ranges;
1837 	int ret;
1838 
1839 	*num_devices = p->n_pdds;
1840 	*num_bos = get_process_num_bos(p);
1841 
1842 	ret = kfd_process_get_queue_info(p, &num_queues, &queues_priv_data_size);
1843 	if (ret)
1844 		return ret;
1845 
1846 	num_events = kfd_get_num_events(p);
1847 
1848 	ret = svm_range_get_info(p, &num_svm_ranges, &svm_priv_data_size);
1849 	if (ret)
1850 		return ret;
1851 
1852 	*num_objects = num_queues + num_events + num_svm_ranges;
1853 
1854 	if (objs_priv_size) {
1855 		priv_size = sizeof(struct kfd_criu_process_priv_data);
1856 		priv_size += *num_devices * sizeof(struct kfd_criu_device_priv_data);
1857 		priv_size += *num_bos * sizeof(struct kfd_criu_bo_priv_data);
1858 		priv_size += queues_priv_data_size;
1859 		priv_size += num_events * sizeof(struct kfd_criu_event_priv_data);
1860 		priv_size += svm_priv_data_size;
1861 		*objs_priv_size = priv_size;
1862 	}
1863 	return 0;
1864 }
1865 
1866 static int criu_checkpoint(struct file *filep,
1867 			   struct kfd_process *p,
1868 			   struct kfd_ioctl_criu_args *args)
1869 {
1870 	int ret;
1871 	uint32_t num_devices, num_bos, num_objects;
1872 	uint64_t priv_size, priv_offset = 0;
1873 
1874 	if (!args->devices || !args->bos || !args->priv_data)
1875 		return -EINVAL;
1876 
1877 	mutex_lock(&p->mutex);
1878 
1879 	if (!p->n_pdds) {
1880 		pr_err("No pdd for given process\n");
1881 		ret = -ENODEV;
1882 		goto exit_unlock;
1883 	}
1884 
1885 	/* Confirm all process queues are evicted */
1886 	if (!p->queues_paused) {
1887 		pr_err("Cannot dump process when queues are not in evicted state\n");
1888 		/* CRIU plugin did not call op PROCESS_INFO before checkpointing */
1889 		ret = -EINVAL;
1890 		goto exit_unlock;
1891 	}
1892 
1893 	ret = criu_get_process_object_info(p, &num_devices, &num_bos, &num_objects, &priv_size);
1894 	if (ret)
1895 		goto exit_unlock;
1896 
1897 	if (num_devices != args->num_devices ||
1898 	    num_bos != args->num_bos ||
1899 	    num_objects != args->num_objects ||
1900 	    priv_size != args->priv_data_size) {
1901 
1902 		ret = -EINVAL;
1903 		goto exit_unlock;
1904 	}
1905 
1906 	/* each function will store private data inside priv_data and adjust priv_offset */
1907 	ret = criu_checkpoint_process(p, (uint8_t __user *)args->priv_data, &priv_offset);
1908 	if (ret)
1909 		goto exit_unlock;
1910 
1911 	ret = criu_checkpoint_devices(p, num_devices, (uint8_t __user *)args->devices,
1912 				(uint8_t __user *)args->priv_data, &priv_offset);
1913 	if (ret)
1914 		goto exit_unlock;
1915 
1916 	ret = criu_checkpoint_bos(p, num_bos, (uint8_t __user *)args->bos,
1917 			    (uint8_t __user *)args->priv_data, &priv_offset);
1918 	if (ret)
1919 		goto exit_unlock;
1920 
1921 	if (num_objects) {
1922 		ret = kfd_criu_checkpoint_queues(p, (uint8_t __user *)args->priv_data,
1923 						 &priv_offset);
1924 		if (ret)
1925 			goto close_bo_fds;
1926 
1927 		ret = kfd_criu_checkpoint_events(p, (uint8_t __user *)args->priv_data,
1928 						 &priv_offset);
1929 		if (ret)
1930 			goto close_bo_fds;
1931 
1932 		ret = kfd_criu_checkpoint_svm(p, (uint8_t __user *)args->priv_data, &priv_offset);
1933 		if (ret)
1934 			goto close_bo_fds;
1935 	}
1936 
1937 close_bo_fds:
1938 	if (ret) {
1939 		/* If IOCTL returns err, user assumes all FDs opened in criu_dump_bos are closed */
1940 		uint32_t i;
1941 		struct kfd_criu_bo_bucket *bo_buckets = (struct kfd_criu_bo_bucket *) args->bos;
1942 
1943 		for (i = 0; i < num_bos; i++) {
1944 			if (bo_buckets[i].alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_VRAM)
1945 				close_fd(bo_buckets[i].dmabuf_fd);
1946 		}
1947 	}
1948 
1949 exit_unlock:
1950 	mutex_unlock(&p->mutex);
1951 	if (ret)
1952 		pr_err("Failed to dump CRIU ret:%d\n", ret);
1953 	else
1954 		pr_debug("CRIU dump ret:%d\n", ret);
1955 
1956 	return ret;
1957 }
1958 
1959 static int criu_restore_process(struct kfd_process *p,
1960 				struct kfd_ioctl_criu_args *args,
1961 				uint64_t *priv_offset,
1962 				uint64_t max_priv_data_size)
1963 {
1964 	int ret = 0;
1965 	struct kfd_criu_process_priv_data process_priv;
1966 
1967 	if (*priv_offset + sizeof(process_priv) > max_priv_data_size)
1968 		return -EINVAL;
1969 
1970 	ret = copy_from_user(&process_priv,
1971 				(void __user *)(args->priv_data + *priv_offset),
1972 				sizeof(process_priv));
1973 	if (ret) {
1974 		pr_err("Failed to copy process private information from user\n");
1975 		ret = -EFAULT;
1976 		goto exit;
1977 	}
1978 	*priv_offset += sizeof(process_priv);
1979 
1980 	if (process_priv.version != KFD_CRIU_PRIV_VERSION) {
1981 		pr_err("Invalid CRIU API version (checkpointed:%d current:%d)\n",
1982 			process_priv.version, KFD_CRIU_PRIV_VERSION);
1983 		return -EINVAL;
1984 	}
1985 
1986 	pr_debug("Setting XNACK mode\n");
1987 	if (process_priv.xnack_mode && !kfd_process_xnack_mode(p, true)) {
1988 		pr_err("xnack mode cannot be set\n");
1989 		ret = -EPERM;
1990 		goto exit;
1991 	} else {
1992 		pr_debug("set xnack mode: %d\n", process_priv.xnack_mode);
1993 		p->xnack_enabled = process_priv.xnack_mode;
1994 	}
1995 
1996 exit:
1997 	return ret;
1998 }
1999 
2000 static int criu_restore_devices(struct kfd_process *p,
2001 				struct kfd_ioctl_criu_args *args,
2002 				uint64_t *priv_offset,
2003 				uint64_t max_priv_data_size)
2004 {
2005 	struct kfd_criu_device_bucket *device_buckets;
2006 	struct kfd_criu_device_priv_data *device_privs;
2007 	int ret = 0;
2008 	uint32_t i;
2009 
2010 	if (args->num_devices != p->n_pdds)
2011 		return -EINVAL;
2012 
2013 	if (*priv_offset + (args->num_devices * sizeof(*device_privs)) > max_priv_data_size)
2014 		return -EINVAL;
2015 
2016 	device_buckets = kmalloc_array(args->num_devices, sizeof(*device_buckets), GFP_KERNEL);
2017 	if (!device_buckets)
2018 		return -ENOMEM;
2019 
2020 	ret = copy_from_user(device_buckets, (void __user *)args->devices,
2021 				args->num_devices * sizeof(*device_buckets));
2022 	if (ret) {
2023 		pr_err("Failed to copy devices buckets from user\n");
2024 		ret = -EFAULT;
2025 		goto exit;
2026 	}
2027 
2028 	for (i = 0; i < args->num_devices; i++) {
2029 		struct kfd_dev *dev;
2030 		struct kfd_process_device *pdd;
2031 		struct file *drm_file;
2032 
2033 		/* device private data is not currently used */
2034 
2035 		if (!device_buckets[i].user_gpu_id) {
2036 			pr_err("Invalid user gpu_id\n");
2037 			ret = -EINVAL;
2038 			goto exit;
2039 		}
2040 
2041 		dev = kfd_device_by_id(device_buckets[i].actual_gpu_id);
2042 		if (!dev) {
2043 			pr_err("Failed to find device with gpu_id = %x\n",
2044 				device_buckets[i].actual_gpu_id);
2045 			ret = -EINVAL;
2046 			goto exit;
2047 		}
2048 
2049 		pdd = kfd_get_process_device_data(dev, p);
2050 		if (!pdd) {
2051 			pr_err("Failed to get pdd for gpu_id = %x\n",
2052 					device_buckets[i].actual_gpu_id);
2053 			ret = -EINVAL;
2054 			goto exit;
2055 		}
2056 		pdd->user_gpu_id = device_buckets[i].user_gpu_id;
2057 
2058 		drm_file = fget(device_buckets[i].drm_fd);
2059 		if (!drm_file) {
2060 			pr_err("Invalid render node file descriptor sent from plugin (%d)\n",
2061 				device_buckets[i].drm_fd);
2062 			ret = -EINVAL;
2063 			goto exit;
2064 		}
2065 
2066 		if (pdd->drm_file) {
2067 			ret = -EINVAL;
2068 			goto exit;
2069 		}
2070 
2071 		/* create the vm using render nodes for kfd pdd */
2072 		if (kfd_process_device_init_vm(pdd, drm_file)) {
2073 			pr_err("could not init vm for given pdd\n");
2074 			/* On success, the PDD keeps the drm_file reference */
2075 			fput(drm_file);
2076 			ret = -EINVAL;
2077 			goto exit;
2078 		}
2079 		/*
2080 		 * pdd now already has the vm bound to render node so below api won't create a new
2081 		 * exclusive kfd mapping but use existing one with renderDXXX but is still needed
2082 		 * for iommu v2 binding  and runtime pm.
2083 		 */
2084 		pdd = kfd_bind_process_to_device(dev, p);
2085 		if (IS_ERR(pdd)) {
2086 			ret = PTR_ERR(pdd);
2087 			goto exit;
2088 		}
2089 	}
2090 
2091 	/*
2092 	 * We are not copying device private data from user as we are not using the data for now,
2093 	 * but we still adjust for its private data.
2094 	 */
2095 	*priv_offset += args->num_devices * sizeof(*device_privs);
2096 
2097 exit:
2098 	kfree(device_buckets);
2099 	return ret;
2100 }
2101 
2102 static int criu_restore_memory_of_gpu(struct kfd_process_device *pdd,
2103 				      struct kfd_criu_bo_bucket *bo_bucket,
2104 				      struct kfd_criu_bo_priv_data *bo_priv,
2105 				      struct kgd_mem **kgd_mem)
2106 {
2107 	int idr_handle;
2108 	int ret;
2109 	const bool criu_resume = true;
2110 	u64 offset;
2111 
2112 	if (bo_bucket->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL) {
2113 		if (bo_bucket->size != kfd_doorbell_process_slice(pdd->dev))
2114 			return -EINVAL;
2115 
2116 		offset = kfd_get_process_doorbells(pdd);
2117 	} else if (bo_bucket->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP) {
2118 		/* MMIO BOs need remapped bus address */
2119 		if (bo_bucket->size != PAGE_SIZE) {
2120 			pr_err("Invalid page size\n");
2121 			return -EINVAL;
2122 		}
2123 		offset = pdd->dev->adev->rmmio_remap.bus_addr;
2124 		if (!offset) {
2125 			pr_err("amdgpu_amdkfd_get_mmio_remap_phys_addr failed\n");
2126 			return -ENOMEM;
2127 		}
2128 	} else if (bo_bucket->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_USERPTR) {
2129 		offset = bo_priv->user_addr;
2130 	}
2131 	/* Create the BO */
2132 	ret = amdgpu_amdkfd_gpuvm_alloc_memory_of_gpu(pdd->dev->adev, bo_bucket->addr,
2133 						      bo_bucket->size, pdd->drm_priv, kgd_mem,
2134 						      &offset, bo_bucket->alloc_flags, criu_resume);
2135 	if (ret) {
2136 		pr_err("Could not create the BO\n");
2137 		return ret;
2138 	}
2139 	pr_debug("New BO created: size:0x%llx addr:0x%llx offset:0x%llx\n",
2140 		 bo_bucket->size, bo_bucket->addr, offset);
2141 
2142 	/* Restore previous IDR handle */
2143 	pr_debug("Restoring old IDR handle for the BO");
2144 	idr_handle = idr_alloc(&pdd->alloc_idr, *kgd_mem, bo_priv->idr_handle,
2145 			       bo_priv->idr_handle + 1, GFP_KERNEL);
2146 
2147 	if (idr_handle < 0) {
2148 		pr_err("Could not allocate idr\n");
2149 		amdgpu_amdkfd_gpuvm_free_memory_of_gpu(pdd->dev->adev, *kgd_mem, pdd->drm_priv,
2150 						       NULL);
2151 		return -ENOMEM;
2152 	}
2153 
2154 	if (bo_bucket->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL)
2155 		bo_bucket->restored_offset = KFD_MMAP_TYPE_DOORBELL | KFD_MMAP_GPU_ID(pdd->dev->id);
2156 	if (bo_bucket->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP) {
2157 		bo_bucket->restored_offset = KFD_MMAP_TYPE_MMIO | KFD_MMAP_GPU_ID(pdd->dev->id);
2158 	} else if (bo_bucket->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_GTT) {
2159 		bo_bucket->restored_offset = offset;
2160 	} else if (bo_bucket->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_VRAM) {
2161 		bo_bucket->restored_offset = offset;
2162 		/* Update the VRAM usage count */
2163 		WRITE_ONCE(pdd->vram_usage, pdd->vram_usage + bo_bucket->size);
2164 	}
2165 	return 0;
2166 }
2167 
2168 static int criu_restore_bo(struct kfd_process *p,
2169 			   struct kfd_criu_bo_bucket *bo_bucket,
2170 			   struct kfd_criu_bo_priv_data *bo_priv)
2171 {
2172 	struct kfd_process_device *pdd;
2173 	struct kgd_mem *kgd_mem;
2174 	int ret;
2175 	int j;
2176 
2177 	pr_debug("Restoring BO size:0x%llx addr:0x%llx gpu_id:0x%x flags:0x%x idr_handle:0x%x\n",
2178 		 bo_bucket->size, bo_bucket->addr, bo_bucket->gpu_id, bo_bucket->alloc_flags,
2179 		 bo_priv->idr_handle);
2180 
2181 	pdd = kfd_process_device_data_by_id(p, bo_bucket->gpu_id);
2182 	if (!pdd) {
2183 		pr_err("Failed to get pdd\n");
2184 		return -ENODEV;
2185 	}
2186 
2187 	ret = criu_restore_memory_of_gpu(pdd, bo_bucket, bo_priv, &kgd_mem);
2188 	if (ret)
2189 		return ret;
2190 
2191 	/* now map these BOs to GPU/s */
2192 	for (j = 0; j < p->n_pdds; j++) {
2193 		struct kfd_dev *peer;
2194 		struct kfd_process_device *peer_pdd;
2195 
2196 		if (!bo_priv->mapped_gpuids[j])
2197 			break;
2198 
2199 		peer_pdd = kfd_process_device_data_by_id(p, bo_priv->mapped_gpuids[j]);
2200 		if (!peer_pdd)
2201 			return -EINVAL;
2202 
2203 		peer = peer_pdd->dev;
2204 
2205 		peer_pdd = kfd_bind_process_to_device(peer, p);
2206 		if (IS_ERR(peer_pdd))
2207 			return PTR_ERR(peer_pdd);
2208 
2209 		ret = amdgpu_amdkfd_gpuvm_map_memory_to_gpu(peer->adev, kgd_mem, peer_pdd->drm_priv,
2210 							    NULL);
2211 		if (ret) {
2212 			pr_err("Failed to map to gpu %d/%d\n", j, p->n_pdds);
2213 			return ret;
2214 		}
2215 	}
2216 
2217 	pr_debug("map memory was successful for the BO\n");
2218 	/* create the dmabuf object and export the bo */
2219 	if (bo_bucket->alloc_flags
2220 	    & (KFD_IOC_ALLOC_MEM_FLAGS_VRAM | KFD_IOC_ALLOC_MEM_FLAGS_GTT)) {
2221 		ret = criu_get_prime_handle(&kgd_mem->bo->tbo.base, DRM_RDWR,
2222 					    &bo_bucket->dmabuf_fd);
2223 		if (ret)
2224 			return ret;
2225 	} else {
2226 		bo_bucket->dmabuf_fd = KFD_INVALID_FD;
2227 	}
2228 
2229 	return 0;
2230 }
2231 
2232 static int criu_restore_bos(struct kfd_process *p,
2233 			    struct kfd_ioctl_criu_args *args,
2234 			    uint64_t *priv_offset,
2235 			    uint64_t max_priv_data_size)
2236 {
2237 	struct kfd_criu_bo_bucket *bo_buckets = NULL;
2238 	struct kfd_criu_bo_priv_data *bo_privs = NULL;
2239 	int ret = 0;
2240 	uint32_t i = 0;
2241 
2242 	if (*priv_offset + (args->num_bos * sizeof(*bo_privs)) > max_priv_data_size)
2243 		return -EINVAL;
2244 
2245 	/* Prevent MMU notifications until stage-4 IOCTL (CRIU_RESUME) is received */
2246 	amdgpu_amdkfd_block_mmu_notifications(p->kgd_process_info);
2247 
2248 	bo_buckets = kvmalloc_array(args->num_bos, sizeof(*bo_buckets), GFP_KERNEL);
2249 	if (!bo_buckets)
2250 		return -ENOMEM;
2251 
2252 	ret = copy_from_user(bo_buckets, (void __user *)args->bos,
2253 			     args->num_bos * sizeof(*bo_buckets));
2254 	if (ret) {
2255 		pr_err("Failed to copy BOs information from user\n");
2256 		ret = -EFAULT;
2257 		goto exit;
2258 	}
2259 
2260 	bo_privs = kvmalloc_array(args->num_bos, sizeof(*bo_privs), GFP_KERNEL);
2261 	if (!bo_privs) {
2262 		ret = -ENOMEM;
2263 		goto exit;
2264 	}
2265 
2266 	ret = copy_from_user(bo_privs, (void __user *)args->priv_data + *priv_offset,
2267 			     args->num_bos * sizeof(*bo_privs));
2268 	if (ret) {
2269 		pr_err("Failed to copy BOs information from user\n");
2270 		ret = -EFAULT;
2271 		goto exit;
2272 	}
2273 	*priv_offset += args->num_bos * sizeof(*bo_privs);
2274 
2275 	/* Create and map new BOs */
2276 	for (; i < args->num_bos; i++) {
2277 		ret = criu_restore_bo(p, &bo_buckets[i], &bo_privs[i]);
2278 		if (ret) {
2279 			pr_debug("Failed to restore BO[%d] ret%d\n", i, ret);
2280 			goto exit;
2281 		}
2282 	} /* done */
2283 
2284 	/* Copy only the buckets back so user can read bo_buckets[N].restored_offset */
2285 	ret = copy_to_user((void __user *)args->bos,
2286 				bo_buckets,
2287 				(args->num_bos * sizeof(*bo_buckets)));
2288 	if (ret)
2289 		ret = -EFAULT;
2290 
2291 exit:
2292 	while (ret && i--) {
2293 		if (bo_buckets[i].alloc_flags
2294 		   & (KFD_IOC_ALLOC_MEM_FLAGS_VRAM | KFD_IOC_ALLOC_MEM_FLAGS_GTT))
2295 			close_fd(bo_buckets[i].dmabuf_fd);
2296 	}
2297 	kvfree(bo_buckets);
2298 	kvfree(bo_privs);
2299 	return ret;
2300 }
2301 
2302 static int criu_restore_objects(struct file *filep,
2303 				struct kfd_process *p,
2304 				struct kfd_ioctl_criu_args *args,
2305 				uint64_t *priv_offset,
2306 				uint64_t max_priv_data_size)
2307 {
2308 	int ret = 0;
2309 	uint32_t i;
2310 
2311 	BUILD_BUG_ON(offsetof(struct kfd_criu_queue_priv_data, object_type));
2312 	BUILD_BUG_ON(offsetof(struct kfd_criu_event_priv_data, object_type));
2313 	BUILD_BUG_ON(offsetof(struct kfd_criu_svm_range_priv_data, object_type));
2314 
2315 	for (i = 0; i < args->num_objects; i++) {
2316 		uint32_t object_type;
2317 
2318 		if (*priv_offset + sizeof(object_type) > max_priv_data_size) {
2319 			pr_err("Invalid private data size\n");
2320 			return -EINVAL;
2321 		}
2322 
2323 		ret = get_user(object_type, (uint32_t __user *)(args->priv_data + *priv_offset));
2324 		if (ret) {
2325 			pr_err("Failed to copy private information from user\n");
2326 			goto exit;
2327 		}
2328 
2329 		switch (object_type) {
2330 		case KFD_CRIU_OBJECT_TYPE_QUEUE:
2331 			ret = kfd_criu_restore_queue(p, (uint8_t __user *)args->priv_data,
2332 						     priv_offset, max_priv_data_size);
2333 			if (ret)
2334 				goto exit;
2335 			break;
2336 		case KFD_CRIU_OBJECT_TYPE_EVENT:
2337 			ret = kfd_criu_restore_event(filep, p, (uint8_t __user *)args->priv_data,
2338 						     priv_offset, max_priv_data_size);
2339 			if (ret)
2340 				goto exit;
2341 			break;
2342 		case KFD_CRIU_OBJECT_TYPE_SVM_RANGE:
2343 			ret = kfd_criu_restore_svm(p, (uint8_t __user *)args->priv_data,
2344 						     priv_offset, max_priv_data_size);
2345 			if (ret)
2346 				goto exit;
2347 			break;
2348 		default:
2349 			pr_err("Invalid object type:%u at index:%d\n", object_type, i);
2350 			ret = -EINVAL;
2351 			goto exit;
2352 		}
2353 	}
2354 exit:
2355 	return ret;
2356 }
2357 
2358 static int criu_restore(struct file *filep,
2359 			struct kfd_process *p,
2360 			struct kfd_ioctl_criu_args *args)
2361 {
2362 	uint64_t priv_offset = 0;
2363 	int ret = 0;
2364 
2365 	pr_debug("CRIU restore (num_devices:%u num_bos:%u num_objects:%u priv_data_size:%llu)\n",
2366 		 args->num_devices, args->num_bos, args->num_objects, args->priv_data_size);
2367 
2368 	if (!args->bos || !args->devices || !args->priv_data || !args->priv_data_size ||
2369 	    !args->num_devices || !args->num_bos)
2370 		return -EINVAL;
2371 
2372 	mutex_lock(&p->mutex);
2373 
2374 	/*
2375 	 * Set the process to evicted state to avoid running any new queues before all the memory
2376 	 * mappings are ready.
2377 	 */
2378 	ret = kfd_process_evict_queues(p);
2379 	if (ret)
2380 		goto exit_unlock;
2381 
2382 	/* Each function will adjust priv_offset based on how many bytes they consumed */
2383 	ret = criu_restore_process(p, args, &priv_offset, args->priv_data_size);
2384 	if (ret)
2385 		goto exit_unlock;
2386 
2387 	ret = criu_restore_devices(p, args, &priv_offset, args->priv_data_size);
2388 	if (ret)
2389 		goto exit_unlock;
2390 
2391 	ret = criu_restore_bos(p, args, &priv_offset, args->priv_data_size);
2392 	if (ret)
2393 		goto exit_unlock;
2394 
2395 	ret = criu_restore_objects(filep, p, args, &priv_offset, args->priv_data_size);
2396 	if (ret)
2397 		goto exit_unlock;
2398 
2399 	if (priv_offset != args->priv_data_size) {
2400 		pr_err("Invalid private data size\n");
2401 		ret = -EINVAL;
2402 	}
2403 
2404 exit_unlock:
2405 	mutex_unlock(&p->mutex);
2406 	if (ret)
2407 		pr_err("Failed to restore CRIU ret:%d\n", ret);
2408 	else
2409 		pr_debug("CRIU restore successful\n");
2410 
2411 	return ret;
2412 }
2413 
2414 static int criu_unpause(struct file *filep,
2415 			struct kfd_process *p,
2416 			struct kfd_ioctl_criu_args *args)
2417 {
2418 	int ret;
2419 
2420 	mutex_lock(&p->mutex);
2421 
2422 	if (!p->queues_paused) {
2423 		mutex_unlock(&p->mutex);
2424 		return -EINVAL;
2425 	}
2426 
2427 	ret = kfd_process_restore_queues(p);
2428 	if (ret)
2429 		pr_err("Failed to unpause queues ret:%d\n", ret);
2430 	else
2431 		p->queues_paused = false;
2432 
2433 	mutex_unlock(&p->mutex);
2434 
2435 	return ret;
2436 }
2437 
2438 static int criu_resume(struct file *filep,
2439 			struct kfd_process *p,
2440 			struct kfd_ioctl_criu_args *args)
2441 {
2442 	struct kfd_process *target = NULL;
2443 	struct pid *pid = NULL;
2444 	int ret = 0;
2445 
2446 	pr_debug("Inside %s, target pid for criu restore: %d\n", __func__,
2447 		 args->pid);
2448 
2449 	pid = find_get_pid(args->pid);
2450 	if (!pid) {
2451 		pr_err("Cannot find pid info for %i\n", args->pid);
2452 		return -ESRCH;
2453 	}
2454 
2455 	pr_debug("calling kfd_lookup_process_by_pid\n");
2456 	target = kfd_lookup_process_by_pid(pid);
2457 
2458 	put_pid(pid);
2459 
2460 	if (!target) {
2461 		pr_debug("Cannot find process info for %i\n", args->pid);
2462 		return -ESRCH;
2463 	}
2464 
2465 	mutex_lock(&target->mutex);
2466 	ret = kfd_criu_resume_svm(target);
2467 	if (ret) {
2468 		pr_err("kfd_criu_resume_svm failed for %i\n", args->pid);
2469 		goto exit;
2470 	}
2471 
2472 	ret =  amdgpu_amdkfd_criu_resume(target->kgd_process_info);
2473 	if (ret)
2474 		pr_err("amdgpu_amdkfd_criu_resume failed for %i\n", args->pid);
2475 
2476 exit:
2477 	mutex_unlock(&target->mutex);
2478 
2479 	kfd_unref_process(target);
2480 	return ret;
2481 }
2482 
2483 static int criu_process_info(struct file *filep,
2484 				struct kfd_process *p,
2485 				struct kfd_ioctl_criu_args *args)
2486 {
2487 	int ret = 0;
2488 
2489 	mutex_lock(&p->mutex);
2490 
2491 	if (!p->n_pdds) {
2492 		pr_err("No pdd for given process\n");
2493 		ret = -ENODEV;
2494 		goto err_unlock;
2495 	}
2496 
2497 	ret = kfd_process_evict_queues(p);
2498 	if (ret)
2499 		goto err_unlock;
2500 
2501 	p->queues_paused = true;
2502 
2503 	args->pid = task_pid_nr_ns(p->lead_thread,
2504 					task_active_pid_ns(p->lead_thread));
2505 
2506 	ret = criu_get_process_object_info(p, &args->num_devices, &args->num_bos,
2507 					   &args->num_objects, &args->priv_data_size);
2508 	if (ret)
2509 		goto err_unlock;
2510 
2511 	dev_dbg(kfd_device, "Num of devices:%u bos:%u objects:%u priv_data_size:%lld\n",
2512 				args->num_devices, args->num_bos, args->num_objects,
2513 				args->priv_data_size);
2514 
2515 err_unlock:
2516 	if (ret) {
2517 		kfd_process_restore_queues(p);
2518 		p->queues_paused = false;
2519 	}
2520 	mutex_unlock(&p->mutex);
2521 	return ret;
2522 }
2523 
2524 static int kfd_ioctl_criu(struct file *filep, struct kfd_process *p, void *data)
2525 {
2526 	struct kfd_ioctl_criu_args *args = data;
2527 	int ret;
2528 
2529 	dev_dbg(kfd_device, "CRIU operation: %d\n", args->op);
2530 	switch (args->op) {
2531 	case KFD_CRIU_OP_PROCESS_INFO:
2532 		ret = criu_process_info(filep, p, args);
2533 		break;
2534 	case KFD_CRIU_OP_CHECKPOINT:
2535 		ret = criu_checkpoint(filep, p, args);
2536 		break;
2537 	case KFD_CRIU_OP_UNPAUSE:
2538 		ret = criu_unpause(filep, p, args);
2539 		break;
2540 	case KFD_CRIU_OP_RESTORE:
2541 		ret = criu_restore(filep, p, args);
2542 		break;
2543 	case KFD_CRIU_OP_RESUME:
2544 		ret = criu_resume(filep, p, args);
2545 		break;
2546 	default:
2547 		dev_dbg(kfd_device, "Unsupported CRIU operation:%d\n", args->op);
2548 		ret = -EINVAL;
2549 		break;
2550 	}
2551 
2552 	if (ret)
2553 		dev_dbg(kfd_device, "CRIU operation:%d err:%d\n", args->op, ret);
2554 
2555 	return ret;
2556 }
2557 
2558 #define AMDKFD_IOCTL_DEF(ioctl, _func, _flags) \
2559 	[_IOC_NR(ioctl)] = {.cmd = ioctl, .func = _func, .flags = _flags, \
2560 			    .cmd_drv = 0, .name = #ioctl}
2561 
2562 /** Ioctl table */
2563 static const struct amdkfd_ioctl_desc amdkfd_ioctls[] = {
2564 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_GET_VERSION,
2565 			kfd_ioctl_get_version, 0),
2566 
2567 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_CREATE_QUEUE,
2568 			kfd_ioctl_create_queue, 0),
2569 
2570 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_DESTROY_QUEUE,
2571 			kfd_ioctl_destroy_queue, 0),
2572 
2573 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_SET_MEMORY_POLICY,
2574 			kfd_ioctl_set_memory_policy, 0),
2575 
2576 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_GET_CLOCK_COUNTERS,
2577 			kfd_ioctl_get_clock_counters, 0),
2578 
2579 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_GET_PROCESS_APERTURES,
2580 			kfd_ioctl_get_process_apertures, 0),
2581 
2582 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_UPDATE_QUEUE,
2583 			kfd_ioctl_update_queue, 0),
2584 
2585 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_CREATE_EVENT,
2586 			kfd_ioctl_create_event, 0),
2587 
2588 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_DESTROY_EVENT,
2589 			kfd_ioctl_destroy_event, 0),
2590 
2591 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_SET_EVENT,
2592 			kfd_ioctl_set_event, 0),
2593 
2594 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_RESET_EVENT,
2595 			kfd_ioctl_reset_event, 0),
2596 
2597 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_WAIT_EVENTS,
2598 			kfd_ioctl_wait_events, 0),
2599 
2600 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_DBG_REGISTER_DEPRECATED,
2601 			kfd_ioctl_dbg_register, 0),
2602 
2603 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_DBG_UNREGISTER_DEPRECATED,
2604 			kfd_ioctl_dbg_unregister, 0),
2605 
2606 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_DBG_ADDRESS_WATCH_DEPRECATED,
2607 			kfd_ioctl_dbg_address_watch, 0),
2608 
2609 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_DBG_WAVE_CONTROL_DEPRECATED,
2610 			kfd_ioctl_dbg_wave_control, 0),
2611 
2612 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_SET_SCRATCH_BACKING_VA,
2613 			kfd_ioctl_set_scratch_backing_va, 0),
2614 
2615 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_GET_TILE_CONFIG,
2616 			kfd_ioctl_get_tile_config, 0),
2617 
2618 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_SET_TRAP_HANDLER,
2619 			kfd_ioctl_set_trap_handler, 0),
2620 
2621 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_GET_PROCESS_APERTURES_NEW,
2622 			kfd_ioctl_get_process_apertures_new, 0),
2623 
2624 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_ACQUIRE_VM,
2625 			kfd_ioctl_acquire_vm, 0),
2626 
2627 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_ALLOC_MEMORY_OF_GPU,
2628 			kfd_ioctl_alloc_memory_of_gpu, 0),
2629 
2630 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_FREE_MEMORY_OF_GPU,
2631 			kfd_ioctl_free_memory_of_gpu, 0),
2632 
2633 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_MAP_MEMORY_TO_GPU,
2634 			kfd_ioctl_map_memory_to_gpu, 0),
2635 
2636 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_UNMAP_MEMORY_FROM_GPU,
2637 			kfd_ioctl_unmap_memory_from_gpu, 0),
2638 
2639 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_SET_CU_MASK,
2640 			kfd_ioctl_set_cu_mask, 0),
2641 
2642 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_GET_QUEUE_WAVE_STATE,
2643 			kfd_ioctl_get_queue_wave_state, 0),
2644 
2645 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_GET_DMABUF_INFO,
2646 				kfd_ioctl_get_dmabuf_info, 0),
2647 
2648 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_IMPORT_DMABUF,
2649 				kfd_ioctl_import_dmabuf, 0),
2650 
2651 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_ALLOC_QUEUE_GWS,
2652 			kfd_ioctl_alloc_queue_gws, 0),
2653 
2654 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_SMI_EVENTS,
2655 			kfd_ioctl_smi_events, 0),
2656 
2657 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_SVM, kfd_ioctl_svm, 0),
2658 
2659 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_SET_XNACK_MODE,
2660 			kfd_ioctl_set_xnack_mode, 0),
2661 
2662 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_CRIU_OP,
2663 			kfd_ioctl_criu, KFD_IOC_FLAG_CHECKPOINT_RESTORE),
2664 
2665 };
2666 
2667 #define AMDKFD_CORE_IOCTL_COUNT	ARRAY_SIZE(amdkfd_ioctls)
2668 
2669 static long kfd_ioctl(struct file *filep, unsigned int cmd, unsigned long arg)
2670 {
2671 	struct kfd_process *process;
2672 	amdkfd_ioctl_t *func;
2673 	const struct amdkfd_ioctl_desc *ioctl = NULL;
2674 	unsigned int nr = _IOC_NR(cmd);
2675 	char stack_kdata[128];
2676 	char *kdata = NULL;
2677 	unsigned int usize, asize;
2678 	int retcode = -EINVAL;
2679 	bool ptrace_attached = false;
2680 
2681 	if (nr >= AMDKFD_CORE_IOCTL_COUNT)
2682 		goto err_i1;
2683 
2684 	if ((nr >= AMDKFD_COMMAND_START) && (nr < AMDKFD_COMMAND_END)) {
2685 		u32 amdkfd_size;
2686 
2687 		ioctl = &amdkfd_ioctls[nr];
2688 
2689 		amdkfd_size = _IOC_SIZE(ioctl->cmd);
2690 		usize = asize = _IOC_SIZE(cmd);
2691 		if (amdkfd_size > asize)
2692 			asize = amdkfd_size;
2693 
2694 		cmd = ioctl->cmd;
2695 	} else
2696 		goto err_i1;
2697 
2698 	dev_dbg(kfd_device, "ioctl cmd 0x%x (#0x%x), arg 0x%lx\n", cmd, nr, arg);
2699 
2700 	/* Get the process struct from the filep. Only the process
2701 	 * that opened /dev/kfd can use the file descriptor. Child
2702 	 * processes need to create their own KFD device context.
2703 	 */
2704 	process = filep->private_data;
2705 
2706 	rcu_read_lock();
2707 	if ((ioctl->flags & KFD_IOC_FLAG_CHECKPOINT_RESTORE) &&
2708 	    ptrace_parent(process->lead_thread) == current)
2709 		ptrace_attached = true;
2710 	rcu_read_unlock();
2711 
2712 	if (process->lead_thread != current->group_leader
2713 	    && !ptrace_attached) {
2714 		dev_dbg(kfd_device, "Using KFD FD in wrong process\n");
2715 		retcode = -EBADF;
2716 		goto err_i1;
2717 	}
2718 
2719 	/* Do not trust userspace, use our own definition */
2720 	func = ioctl->func;
2721 
2722 	if (unlikely(!func)) {
2723 		dev_dbg(kfd_device, "no function\n");
2724 		retcode = -EINVAL;
2725 		goto err_i1;
2726 	}
2727 
2728 	/*
2729 	 * Versions of docker shipped in Ubuntu 18.xx and 20.xx do not support
2730 	 * CAP_CHECKPOINT_RESTORE, so we also allow access if CAP_SYS_ADMIN as CAP_SYS_ADMIN is a
2731 	 * more priviledged access.
2732 	 */
2733 	if (unlikely(ioctl->flags & KFD_IOC_FLAG_CHECKPOINT_RESTORE)) {
2734 		if (!capable(CAP_CHECKPOINT_RESTORE) &&
2735 						!capable(CAP_SYS_ADMIN)) {
2736 			retcode = -EACCES;
2737 			goto err_i1;
2738 		}
2739 	}
2740 
2741 	if (cmd & (IOC_IN | IOC_OUT)) {
2742 		if (asize <= sizeof(stack_kdata)) {
2743 			kdata = stack_kdata;
2744 		} else {
2745 			kdata = kmalloc(asize, GFP_KERNEL);
2746 			if (!kdata) {
2747 				retcode = -ENOMEM;
2748 				goto err_i1;
2749 			}
2750 		}
2751 		if (asize > usize)
2752 			memset(kdata + usize, 0, asize - usize);
2753 	}
2754 
2755 	if (cmd & IOC_IN) {
2756 		if (copy_from_user(kdata, (void __user *)arg, usize) != 0) {
2757 			retcode = -EFAULT;
2758 			goto err_i1;
2759 		}
2760 	} else if (cmd & IOC_OUT) {
2761 		memset(kdata, 0, usize);
2762 	}
2763 
2764 	retcode = func(filep, process, kdata);
2765 
2766 	if (cmd & IOC_OUT)
2767 		if (copy_to_user((void __user *)arg, kdata, usize) != 0)
2768 			retcode = -EFAULT;
2769 
2770 err_i1:
2771 	if (!ioctl)
2772 		dev_dbg(kfd_device, "invalid ioctl: pid=%d, cmd=0x%02x, nr=0x%02x\n",
2773 			  task_pid_nr(current), cmd, nr);
2774 
2775 	if (kdata != stack_kdata)
2776 		kfree(kdata);
2777 
2778 	if (retcode)
2779 		dev_dbg(kfd_device, "ioctl cmd (#0x%x), arg 0x%lx, ret = %d\n",
2780 				nr, arg, retcode);
2781 
2782 	return retcode;
2783 }
2784 
2785 static int kfd_mmio_mmap(struct kfd_dev *dev, struct kfd_process *process,
2786 		      struct vm_area_struct *vma)
2787 {
2788 	phys_addr_t address;
2789 	int ret;
2790 
2791 	if (vma->vm_end - vma->vm_start != PAGE_SIZE)
2792 		return -EINVAL;
2793 
2794 	address = dev->adev->rmmio_remap.bus_addr;
2795 
2796 	vma->vm_flags |= VM_IO | VM_DONTCOPY | VM_DONTEXPAND | VM_NORESERVE |
2797 				VM_DONTDUMP | VM_PFNMAP;
2798 
2799 	vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
2800 
2801 	pr_debug("pasid 0x%x mapping mmio page\n"
2802 		 "     target user address == 0x%08llX\n"
2803 		 "     physical address    == 0x%08llX\n"
2804 		 "     vm_flags            == 0x%04lX\n"
2805 		 "     size                == 0x%04lX\n",
2806 		 process->pasid, (unsigned long long) vma->vm_start,
2807 		 address, vma->vm_flags, PAGE_SIZE);
2808 
2809 	ret = io_remap_pfn_range(vma,
2810 				vma->vm_start,
2811 				address >> PAGE_SHIFT,
2812 				PAGE_SIZE,
2813 				vma->vm_page_prot);
2814 	return ret;
2815 }
2816 
2817 
2818 static int kfd_mmap(struct file *filp, struct vm_area_struct *vma)
2819 {
2820 	struct kfd_process *process;
2821 	struct kfd_dev *dev = NULL;
2822 	unsigned long mmap_offset;
2823 	unsigned int gpu_id;
2824 
2825 	process = kfd_get_process(current);
2826 	if (IS_ERR(process))
2827 		return PTR_ERR(process);
2828 
2829 	mmap_offset = vma->vm_pgoff << PAGE_SHIFT;
2830 	gpu_id = KFD_MMAP_GET_GPU_ID(mmap_offset);
2831 	if (gpu_id)
2832 		dev = kfd_device_by_id(gpu_id);
2833 
2834 	switch (mmap_offset & KFD_MMAP_TYPE_MASK) {
2835 	case KFD_MMAP_TYPE_DOORBELL:
2836 		if (!dev)
2837 			return -ENODEV;
2838 		return kfd_doorbell_mmap(dev, process, vma);
2839 
2840 	case KFD_MMAP_TYPE_EVENTS:
2841 		return kfd_event_mmap(process, vma);
2842 
2843 	case KFD_MMAP_TYPE_RESERVED_MEM:
2844 		if (!dev)
2845 			return -ENODEV;
2846 		return kfd_reserved_mem_mmap(dev, process, vma);
2847 	case KFD_MMAP_TYPE_MMIO:
2848 		if (!dev)
2849 			return -ENODEV;
2850 		return kfd_mmio_mmap(dev, process, vma);
2851 	}
2852 
2853 	return -EFAULT;
2854 }
2855