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