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 & KFD_IOC_ALLOC_MEM_FLAGS_VRAM) {
1763 				ret = criu_get_prime_handle(&dumper_bo->tbo.base,
1764 						bo_bucket->alloc_flags &
1765 						KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE ? DRM_RDWR : 0,
1766 						&bo_bucket->dmabuf_fd);
1767 				if (ret)
1768 					goto exit;
1769 			}
1770 			if (bo_bucket->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL)
1771 				bo_bucket->offset = KFD_MMAP_TYPE_DOORBELL |
1772 					KFD_MMAP_GPU_ID(pdd->dev->id);
1773 			else if (bo_bucket->alloc_flags &
1774 				KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)
1775 				bo_bucket->offset = KFD_MMAP_TYPE_MMIO |
1776 					KFD_MMAP_GPU_ID(pdd->dev->id);
1777 			else
1778 				bo_bucket->offset = amdgpu_bo_mmap_offset(dumper_bo);
1779 
1780 			for (i = 0; i < p->n_pdds; i++) {
1781 				if (amdgpu_amdkfd_bo_mapped_to_dev(p->pdds[i]->dev->adev, kgd_mem))
1782 					bo_priv->mapped_gpuids[dev_idx++] = p->pdds[i]->user_gpu_id;
1783 			}
1784 
1785 			pr_debug("bo_size = 0x%llx, bo_addr = 0x%llx bo_offset = 0x%llx\n"
1786 					"gpu_id = 0x%x alloc_flags = 0x%x idr_handle = 0x%x",
1787 					bo_bucket->size,
1788 					bo_bucket->addr,
1789 					bo_bucket->offset,
1790 					bo_bucket->gpu_id,
1791 					bo_bucket->alloc_flags,
1792 					bo_priv->idr_handle);
1793 			bo_index++;
1794 		}
1795 	}
1796 
1797 	ret = copy_to_user(user_bos, bo_buckets, num_bos * sizeof(*bo_buckets));
1798 	if (ret) {
1799 		pr_err("Failed to copy BO information to user\n");
1800 		ret = -EFAULT;
1801 		goto exit;
1802 	}
1803 
1804 	ret = copy_to_user(user_priv_data + *priv_offset, bo_privs, num_bos * sizeof(*bo_privs));
1805 	if (ret) {
1806 		pr_err("Failed to copy BO priv information to user\n");
1807 		ret = -EFAULT;
1808 		goto exit;
1809 	}
1810 
1811 	*priv_offset += num_bos * sizeof(*bo_privs);
1812 
1813 exit:
1814 	while (ret && bo_index--) {
1815 		if (bo_buckets[bo_index].alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_VRAM)
1816 			close_fd(bo_buckets[bo_index].dmabuf_fd);
1817 	}
1818 
1819 	kvfree(bo_buckets);
1820 	kvfree(bo_privs);
1821 	return ret;
1822 }
1823 
1824 static int criu_get_process_object_info(struct kfd_process *p,
1825 					uint32_t *num_devices,
1826 					uint32_t *num_bos,
1827 					uint32_t *num_objects,
1828 					uint64_t *objs_priv_size)
1829 {
1830 	uint64_t queues_priv_data_size, svm_priv_data_size, priv_size;
1831 	uint32_t num_queues, num_events, num_svm_ranges;
1832 	int ret;
1833 
1834 	*num_devices = p->n_pdds;
1835 	*num_bos = get_process_num_bos(p);
1836 
1837 	ret = kfd_process_get_queue_info(p, &num_queues, &queues_priv_data_size);
1838 	if (ret)
1839 		return ret;
1840 
1841 	num_events = kfd_get_num_events(p);
1842 
1843 	ret = svm_range_get_info(p, &num_svm_ranges, &svm_priv_data_size);
1844 	if (ret)
1845 		return ret;
1846 
1847 	*num_objects = num_queues + num_events + num_svm_ranges;
1848 
1849 	if (objs_priv_size) {
1850 		priv_size = sizeof(struct kfd_criu_process_priv_data);
1851 		priv_size += *num_devices * sizeof(struct kfd_criu_device_priv_data);
1852 		priv_size += *num_bos * sizeof(struct kfd_criu_bo_priv_data);
1853 		priv_size += queues_priv_data_size;
1854 		priv_size += num_events * sizeof(struct kfd_criu_event_priv_data);
1855 		priv_size += svm_priv_data_size;
1856 		*objs_priv_size = priv_size;
1857 	}
1858 	return 0;
1859 }
1860 
1861 static int criu_checkpoint(struct file *filep,
1862 			   struct kfd_process *p,
1863 			   struct kfd_ioctl_criu_args *args)
1864 {
1865 	int ret;
1866 	uint32_t num_devices, num_bos, num_objects;
1867 	uint64_t priv_size, priv_offset = 0;
1868 
1869 	if (!args->devices || !args->bos || !args->priv_data)
1870 		return -EINVAL;
1871 
1872 	mutex_lock(&p->mutex);
1873 
1874 	if (!p->n_pdds) {
1875 		pr_err("No pdd for given process\n");
1876 		ret = -ENODEV;
1877 		goto exit_unlock;
1878 	}
1879 
1880 	/* Confirm all process queues are evicted */
1881 	if (!p->queues_paused) {
1882 		pr_err("Cannot dump process when queues are not in evicted state\n");
1883 		/* CRIU plugin did not call op PROCESS_INFO before checkpointing */
1884 		ret = -EINVAL;
1885 		goto exit_unlock;
1886 	}
1887 
1888 	ret = criu_get_process_object_info(p, &num_devices, &num_bos, &num_objects, &priv_size);
1889 	if (ret)
1890 		goto exit_unlock;
1891 
1892 	if (num_devices != args->num_devices ||
1893 	    num_bos != args->num_bos ||
1894 	    num_objects != args->num_objects ||
1895 	    priv_size != args->priv_data_size) {
1896 
1897 		ret = -EINVAL;
1898 		goto exit_unlock;
1899 	}
1900 
1901 	/* each function will store private data inside priv_data and adjust priv_offset */
1902 	ret = criu_checkpoint_process(p, (uint8_t __user *)args->priv_data, &priv_offset);
1903 	if (ret)
1904 		goto exit_unlock;
1905 
1906 	ret = criu_checkpoint_devices(p, num_devices, (uint8_t __user *)args->devices,
1907 				(uint8_t __user *)args->priv_data, &priv_offset);
1908 	if (ret)
1909 		goto exit_unlock;
1910 
1911 	ret = criu_checkpoint_bos(p, num_bos, (uint8_t __user *)args->bos,
1912 			    (uint8_t __user *)args->priv_data, &priv_offset);
1913 	if (ret)
1914 		goto exit_unlock;
1915 
1916 	if (num_objects) {
1917 		ret = kfd_criu_checkpoint_queues(p, (uint8_t __user *)args->priv_data,
1918 						 &priv_offset);
1919 		if (ret)
1920 			goto close_bo_fds;
1921 
1922 		ret = kfd_criu_checkpoint_events(p, (uint8_t __user *)args->priv_data,
1923 						 &priv_offset);
1924 		if (ret)
1925 			goto close_bo_fds;
1926 
1927 		ret = kfd_criu_checkpoint_svm(p, (uint8_t __user *)args->priv_data, &priv_offset);
1928 		if (ret)
1929 			goto close_bo_fds;
1930 	}
1931 
1932 close_bo_fds:
1933 	if (ret) {
1934 		/* If IOCTL returns err, user assumes all FDs opened in criu_dump_bos are closed */
1935 		uint32_t i;
1936 		struct kfd_criu_bo_bucket *bo_buckets = (struct kfd_criu_bo_bucket *) args->bos;
1937 
1938 		for (i = 0; i < num_bos; i++) {
1939 			if (bo_buckets[i].alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_VRAM)
1940 				close_fd(bo_buckets[i].dmabuf_fd);
1941 		}
1942 	}
1943 
1944 exit_unlock:
1945 	mutex_unlock(&p->mutex);
1946 	if (ret)
1947 		pr_err("Failed to dump CRIU ret:%d\n", ret);
1948 	else
1949 		pr_debug("CRIU dump ret:%d\n", ret);
1950 
1951 	return ret;
1952 }
1953 
1954 static int criu_restore_process(struct kfd_process *p,
1955 				struct kfd_ioctl_criu_args *args,
1956 				uint64_t *priv_offset,
1957 				uint64_t max_priv_data_size)
1958 {
1959 	int ret = 0;
1960 	struct kfd_criu_process_priv_data process_priv;
1961 
1962 	if (*priv_offset + sizeof(process_priv) > max_priv_data_size)
1963 		return -EINVAL;
1964 
1965 	ret = copy_from_user(&process_priv,
1966 				(void __user *)(args->priv_data + *priv_offset),
1967 				sizeof(process_priv));
1968 	if (ret) {
1969 		pr_err("Failed to copy process private information from user\n");
1970 		ret = -EFAULT;
1971 		goto exit;
1972 	}
1973 	*priv_offset += sizeof(process_priv);
1974 
1975 	if (process_priv.version != KFD_CRIU_PRIV_VERSION) {
1976 		pr_err("Invalid CRIU API version (checkpointed:%d current:%d)\n",
1977 			process_priv.version, KFD_CRIU_PRIV_VERSION);
1978 		return -EINVAL;
1979 	}
1980 
1981 	pr_debug("Setting XNACK mode\n");
1982 	if (process_priv.xnack_mode && !kfd_process_xnack_mode(p, true)) {
1983 		pr_err("xnack mode cannot be set\n");
1984 		ret = -EPERM;
1985 		goto exit;
1986 	} else {
1987 		pr_debug("set xnack mode: %d\n", process_priv.xnack_mode);
1988 		p->xnack_enabled = process_priv.xnack_mode;
1989 	}
1990 
1991 exit:
1992 	return ret;
1993 }
1994 
1995 static int criu_restore_devices(struct kfd_process *p,
1996 				struct kfd_ioctl_criu_args *args,
1997 				uint64_t *priv_offset,
1998 				uint64_t max_priv_data_size)
1999 {
2000 	struct kfd_criu_device_bucket *device_buckets;
2001 	struct kfd_criu_device_priv_data *device_privs;
2002 	int ret = 0;
2003 	uint32_t i;
2004 
2005 	if (args->num_devices != p->n_pdds)
2006 		return -EINVAL;
2007 
2008 	if (*priv_offset + (args->num_devices * sizeof(*device_privs)) > max_priv_data_size)
2009 		return -EINVAL;
2010 
2011 	device_buckets = kmalloc_array(args->num_devices, sizeof(*device_buckets), GFP_KERNEL);
2012 	if (!device_buckets)
2013 		return -ENOMEM;
2014 
2015 	ret = copy_from_user(device_buckets, (void __user *)args->devices,
2016 				args->num_devices * sizeof(*device_buckets));
2017 	if (ret) {
2018 		pr_err("Failed to copy devices buckets from user\n");
2019 		ret = -EFAULT;
2020 		goto exit;
2021 	}
2022 
2023 	for (i = 0; i < args->num_devices; i++) {
2024 		struct kfd_dev *dev;
2025 		struct kfd_process_device *pdd;
2026 		struct file *drm_file;
2027 
2028 		/* device private data is not currently used */
2029 
2030 		if (!device_buckets[i].user_gpu_id) {
2031 			pr_err("Invalid user gpu_id\n");
2032 			ret = -EINVAL;
2033 			goto exit;
2034 		}
2035 
2036 		dev = kfd_device_by_id(device_buckets[i].actual_gpu_id);
2037 		if (!dev) {
2038 			pr_err("Failed to find device with gpu_id = %x\n",
2039 				device_buckets[i].actual_gpu_id);
2040 			ret = -EINVAL;
2041 			goto exit;
2042 		}
2043 
2044 		pdd = kfd_get_process_device_data(dev, p);
2045 		if (!pdd) {
2046 			pr_err("Failed to get pdd for gpu_id = %x\n",
2047 					device_buckets[i].actual_gpu_id);
2048 			ret = -EINVAL;
2049 			goto exit;
2050 		}
2051 		pdd->user_gpu_id = device_buckets[i].user_gpu_id;
2052 
2053 		drm_file = fget(device_buckets[i].drm_fd);
2054 		if (!drm_file) {
2055 			pr_err("Invalid render node file descriptor sent from plugin (%d)\n",
2056 				device_buckets[i].drm_fd);
2057 			ret = -EINVAL;
2058 			goto exit;
2059 		}
2060 
2061 		if (pdd->drm_file) {
2062 			ret = -EINVAL;
2063 			goto exit;
2064 		}
2065 
2066 		/* create the vm using render nodes for kfd pdd */
2067 		if (kfd_process_device_init_vm(pdd, drm_file)) {
2068 			pr_err("could not init vm for given pdd\n");
2069 			/* On success, the PDD keeps the drm_file reference */
2070 			fput(drm_file);
2071 			ret = -EINVAL;
2072 			goto exit;
2073 		}
2074 		/*
2075 		 * pdd now already has the vm bound to render node so below api won't create a new
2076 		 * exclusive kfd mapping but use existing one with renderDXXX but is still needed
2077 		 * for iommu v2 binding  and runtime pm.
2078 		 */
2079 		pdd = kfd_bind_process_to_device(dev, p);
2080 		if (IS_ERR(pdd)) {
2081 			ret = PTR_ERR(pdd);
2082 			goto exit;
2083 		}
2084 	}
2085 
2086 	/*
2087 	 * We are not copying device private data from user as we are not using the data for now,
2088 	 * but we still adjust for its private data.
2089 	 */
2090 	*priv_offset += args->num_devices * sizeof(*device_privs);
2091 
2092 exit:
2093 	kfree(device_buckets);
2094 	return ret;
2095 }
2096 
2097 static int criu_restore_bos(struct kfd_process *p,
2098 			    struct kfd_ioctl_criu_args *args,
2099 			    uint64_t *priv_offset,
2100 			    uint64_t max_priv_data_size)
2101 {
2102 	struct kfd_criu_bo_bucket *bo_buckets = NULL;
2103 	struct kfd_criu_bo_priv_data *bo_privs = NULL;
2104 	const bool criu_resume = true;
2105 	bool flush_tlbs = false;
2106 	int ret = 0, j = 0;
2107 	uint32_t i = 0;
2108 
2109 	if (*priv_offset + (args->num_bos * sizeof(*bo_privs)) > max_priv_data_size)
2110 		return -EINVAL;
2111 
2112 	/* Prevent MMU notifications until stage-4 IOCTL (CRIU_RESUME) is received */
2113 	amdgpu_amdkfd_block_mmu_notifications(p->kgd_process_info);
2114 
2115 	bo_buckets = kvmalloc_array(args->num_bos, sizeof(*bo_buckets), GFP_KERNEL);
2116 	if (!bo_buckets)
2117 		return -ENOMEM;
2118 
2119 	ret = copy_from_user(bo_buckets, (void __user *)args->bos,
2120 			     args->num_bos * sizeof(*bo_buckets));
2121 	if (ret) {
2122 		pr_err("Failed to copy BOs information from user\n");
2123 		ret = -EFAULT;
2124 		goto exit;
2125 	}
2126 
2127 	bo_privs = kvmalloc_array(args->num_bos, sizeof(*bo_privs), GFP_KERNEL);
2128 	if (!bo_privs) {
2129 		ret = -ENOMEM;
2130 		goto exit;
2131 	}
2132 
2133 	ret = copy_from_user(bo_privs, (void __user *)args->priv_data + *priv_offset,
2134 			     args->num_bos * sizeof(*bo_privs));
2135 	if (ret) {
2136 		pr_err("Failed to copy BOs information from user\n");
2137 		ret = -EFAULT;
2138 		goto exit;
2139 	}
2140 	*priv_offset += args->num_bos * sizeof(*bo_privs);
2141 
2142 	/* Create and map new BOs */
2143 	for (; i < args->num_bos; i++) {
2144 		struct kfd_criu_bo_bucket *bo_bucket;
2145 		struct kfd_criu_bo_priv_data *bo_priv;
2146 		struct kfd_dev *dev;
2147 		struct kfd_process_device *pdd;
2148 		struct kgd_mem *kgd_mem;
2149 		void *mem;
2150 		u64 offset;
2151 		int idr_handle;
2152 
2153 		bo_bucket = &bo_buckets[i];
2154 		bo_priv = &bo_privs[i];
2155 
2156 		pr_debug("kfd restore ioctl - bo_bucket[%d]:\n", i);
2157 		pr_debug("size = 0x%llx, bo_addr = 0x%llx bo_offset = 0x%llx\n"
2158 			"gpu_id = 0x%x alloc_flags = 0x%x\n"
2159 			"idr_handle = 0x%x\n",
2160 			bo_bucket->size,
2161 			bo_bucket->addr,
2162 			bo_bucket->offset,
2163 			bo_bucket->gpu_id,
2164 			bo_bucket->alloc_flags,
2165 			bo_priv->idr_handle);
2166 
2167 		pdd = kfd_process_device_data_by_id(p, bo_bucket->gpu_id);
2168 		if (!pdd) {
2169 			pr_err("Failed to get pdd\n");
2170 			ret = -ENODEV;
2171 			goto exit;
2172 		}
2173 		dev = pdd->dev;
2174 
2175 		if (bo_bucket->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL) {
2176 			pr_debug("restore ioctl: KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL\n");
2177 			if (bo_bucket->size != kfd_doorbell_process_slice(dev)) {
2178 				ret = -EINVAL;
2179 				goto exit;
2180 			}
2181 			offset = kfd_get_process_doorbells(pdd);
2182 		} else if (bo_bucket->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP) {
2183 			/* MMIO BOs need remapped bus address */
2184 			pr_debug("restore ioctl :KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP\n");
2185 			if (bo_bucket->size != PAGE_SIZE) {
2186 				pr_err("Invalid page size\n");
2187 				ret = -EINVAL;
2188 				goto exit;
2189 			}
2190 			offset = dev->adev->rmmio_remap.bus_addr;
2191 			if (!offset) {
2192 				pr_err("amdgpu_amdkfd_get_mmio_remap_phys_addr failed\n");
2193 				ret = -ENOMEM;
2194 				goto exit;
2195 			}
2196 		} else if (bo_bucket->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_USERPTR) {
2197 			offset = bo_priv->user_addr;
2198 		}
2199 		/* Create the BO */
2200 		ret = amdgpu_amdkfd_gpuvm_alloc_memory_of_gpu(dev->adev,
2201 						bo_bucket->addr,
2202 						bo_bucket->size,
2203 						pdd->drm_priv,
2204 						(struct kgd_mem **) &mem,
2205 						&offset,
2206 						bo_bucket->alloc_flags,
2207 						criu_resume);
2208 		if (ret) {
2209 			pr_err("Could not create the BO\n");
2210 			ret = -ENOMEM;
2211 			goto exit;
2212 		}
2213 		pr_debug("New BO created: size = 0x%llx, bo_addr = 0x%llx bo_offset = 0x%llx\n",
2214 			bo_bucket->size, bo_bucket->addr, offset);
2215 
2216 		/* Restore previuos IDR handle */
2217 		pr_debug("Restoring old IDR handle for the BO");
2218 		idr_handle = idr_alloc(&pdd->alloc_idr, mem,
2219 				       bo_priv->idr_handle,
2220 				       bo_priv->idr_handle + 1, GFP_KERNEL);
2221 
2222 		if (idr_handle < 0) {
2223 			pr_err("Could not allocate idr\n");
2224 			amdgpu_amdkfd_gpuvm_free_memory_of_gpu(dev->adev,
2225 						(struct kgd_mem *)mem,
2226 						pdd->drm_priv, NULL);
2227 			ret = -ENOMEM;
2228 			goto exit;
2229 		}
2230 
2231 		if (bo_bucket->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL)
2232 			bo_bucket->restored_offset = KFD_MMAP_TYPE_DOORBELL |
2233 				KFD_MMAP_GPU_ID(pdd->dev->id);
2234 		if (bo_bucket->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP) {
2235 			bo_bucket->restored_offset = KFD_MMAP_TYPE_MMIO |
2236 				KFD_MMAP_GPU_ID(pdd->dev->id);
2237 		} else if (bo_bucket->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_GTT) {
2238 			bo_bucket->restored_offset = offset;
2239 			pr_debug("updating offset for GTT\n");
2240 		} else if (bo_bucket->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_VRAM) {
2241 			bo_bucket->restored_offset = offset;
2242 			/* Update the VRAM usage count */
2243 			WRITE_ONCE(pdd->vram_usage, pdd->vram_usage + bo_bucket->size);
2244 			pr_debug("updating offset for VRAM\n");
2245 		}
2246 
2247 		/* now map these BOs to GPU/s */
2248 		for (j = 0; j < p->n_pdds; j++) {
2249 			struct kfd_dev *peer;
2250 			struct kfd_process_device *peer_pdd;
2251 			bool table_freed = false;
2252 
2253 			if (!bo_priv->mapped_gpuids[j])
2254 				break;
2255 
2256 			peer_pdd = kfd_process_device_data_by_id(p, bo_priv->mapped_gpuids[j]);
2257 			if (!peer_pdd) {
2258 				ret = -EINVAL;
2259 				goto exit;
2260 			}
2261 			peer = peer_pdd->dev;
2262 
2263 			peer_pdd = kfd_bind_process_to_device(peer, p);
2264 			if (IS_ERR(peer_pdd)) {
2265 				ret = PTR_ERR(peer_pdd);
2266 				goto exit;
2267 			}
2268 			pr_debug("map mem in restore ioctl -> 0x%llx\n",
2269 				 ((struct kgd_mem *)mem)->va);
2270 			ret = amdgpu_amdkfd_gpuvm_map_memory_to_gpu(peer->adev,
2271 				(struct kgd_mem *)mem, peer_pdd->drm_priv, &table_freed);
2272 			if (ret) {
2273 				pr_err("Failed to map to gpu %d/%d\n", j, p->n_pdds);
2274 				goto exit;
2275 			}
2276 			if (table_freed)
2277 				flush_tlbs = true;
2278 		}
2279 
2280 		ret = amdgpu_amdkfd_gpuvm_sync_memory(dev->adev,
2281 						      (struct kgd_mem *) mem, true);
2282 		if (ret) {
2283 			pr_debug("Sync memory failed, wait interrupted by user signal\n");
2284 			goto exit;
2285 		}
2286 
2287 		pr_debug("map memory was successful for the BO\n");
2288 		/* create the dmabuf object and export the bo */
2289 		kgd_mem = (struct kgd_mem *)mem;
2290 		if (bo_bucket->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_VRAM) {
2291 			ret = criu_get_prime_handle(&kgd_mem->bo->tbo.base,
2292 						    DRM_RDWR,
2293 						    &bo_bucket->dmabuf_fd);
2294 			if (ret)
2295 				goto exit;
2296 		}
2297 	} /* done */
2298 
2299 	if (flush_tlbs) {
2300 		/* Flush TLBs after waiting for the page table updates to complete */
2301 		for (j = 0; j < p->n_pdds; j++) {
2302 			struct kfd_dev *peer;
2303 			struct kfd_process_device *pdd = p->pdds[j];
2304 			struct kfd_process_device *peer_pdd;
2305 
2306 			peer = kfd_device_by_id(pdd->dev->id);
2307 			if (WARN_ON_ONCE(!peer))
2308 				continue;
2309 			peer_pdd = kfd_get_process_device_data(peer, p);
2310 			if (WARN_ON_ONCE(!peer_pdd))
2311 				continue;
2312 			kfd_flush_tlb(peer_pdd, TLB_FLUSH_LEGACY);
2313 		}
2314 	}
2315 
2316 	/* Copy only the buckets back so user can read bo_buckets[N].restored_offset */
2317 	ret = copy_to_user((void __user *)args->bos,
2318 				bo_buckets,
2319 				(args->num_bos * sizeof(*bo_buckets)));
2320 	if (ret)
2321 		ret = -EFAULT;
2322 
2323 exit:
2324 	while (ret && i--) {
2325 		if (bo_buckets[i].alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_VRAM)
2326 			close_fd(bo_buckets[i].dmabuf_fd);
2327 	}
2328 	kvfree(bo_buckets);
2329 	kvfree(bo_privs);
2330 	return ret;
2331 }
2332 
2333 static int criu_restore_objects(struct file *filep,
2334 				struct kfd_process *p,
2335 				struct kfd_ioctl_criu_args *args,
2336 				uint64_t *priv_offset,
2337 				uint64_t max_priv_data_size)
2338 {
2339 	int ret = 0;
2340 	uint32_t i;
2341 
2342 	BUILD_BUG_ON(offsetof(struct kfd_criu_queue_priv_data, object_type));
2343 	BUILD_BUG_ON(offsetof(struct kfd_criu_event_priv_data, object_type));
2344 	BUILD_BUG_ON(offsetof(struct kfd_criu_svm_range_priv_data, object_type));
2345 
2346 	for (i = 0; i < args->num_objects; i++) {
2347 		uint32_t object_type;
2348 
2349 		if (*priv_offset + sizeof(object_type) > max_priv_data_size) {
2350 			pr_err("Invalid private data size\n");
2351 			return -EINVAL;
2352 		}
2353 
2354 		ret = get_user(object_type, (uint32_t __user *)(args->priv_data + *priv_offset));
2355 		if (ret) {
2356 			pr_err("Failed to copy private information from user\n");
2357 			goto exit;
2358 		}
2359 
2360 		switch (object_type) {
2361 		case KFD_CRIU_OBJECT_TYPE_QUEUE:
2362 			ret = kfd_criu_restore_queue(p, (uint8_t __user *)args->priv_data,
2363 						     priv_offset, max_priv_data_size);
2364 			if (ret)
2365 				goto exit;
2366 			break;
2367 		case KFD_CRIU_OBJECT_TYPE_EVENT:
2368 			ret = kfd_criu_restore_event(filep, p, (uint8_t __user *)args->priv_data,
2369 						     priv_offset, max_priv_data_size);
2370 			if (ret)
2371 				goto exit;
2372 			break;
2373 		case KFD_CRIU_OBJECT_TYPE_SVM_RANGE:
2374 			ret = kfd_criu_restore_svm(p, (uint8_t __user *)args->priv_data,
2375 						     priv_offset, max_priv_data_size);
2376 			if (ret)
2377 				goto exit;
2378 			break;
2379 		default:
2380 			pr_err("Invalid object type:%u at index:%d\n", object_type, i);
2381 			ret = -EINVAL;
2382 			goto exit;
2383 		}
2384 	}
2385 exit:
2386 	return ret;
2387 }
2388 
2389 static int criu_restore(struct file *filep,
2390 			struct kfd_process *p,
2391 			struct kfd_ioctl_criu_args *args)
2392 {
2393 	uint64_t priv_offset = 0;
2394 	int ret = 0;
2395 
2396 	pr_debug("CRIU restore (num_devices:%u num_bos:%u num_objects:%u priv_data_size:%llu)\n",
2397 		 args->num_devices, args->num_bos, args->num_objects, args->priv_data_size);
2398 
2399 	if (!args->bos || !args->devices || !args->priv_data || !args->priv_data_size ||
2400 	    !args->num_devices || !args->num_bos)
2401 		return -EINVAL;
2402 
2403 	mutex_lock(&p->mutex);
2404 
2405 	/*
2406 	 * Set the process to evicted state to avoid running any new queues before all the memory
2407 	 * mappings are ready.
2408 	 */
2409 	ret = kfd_process_evict_queues(p);
2410 	if (ret)
2411 		goto exit_unlock;
2412 
2413 	/* Each function will adjust priv_offset based on how many bytes they consumed */
2414 	ret = criu_restore_process(p, args, &priv_offset, args->priv_data_size);
2415 	if (ret)
2416 		goto exit_unlock;
2417 
2418 	ret = criu_restore_devices(p, args, &priv_offset, args->priv_data_size);
2419 	if (ret)
2420 		goto exit_unlock;
2421 
2422 	ret = criu_restore_bos(p, args, &priv_offset, args->priv_data_size);
2423 	if (ret)
2424 		goto exit_unlock;
2425 
2426 	ret = criu_restore_objects(filep, p, args, &priv_offset, args->priv_data_size);
2427 	if (ret)
2428 		goto exit_unlock;
2429 
2430 	if (priv_offset != args->priv_data_size) {
2431 		pr_err("Invalid private data size\n");
2432 		ret = -EINVAL;
2433 	}
2434 
2435 exit_unlock:
2436 	mutex_unlock(&p->mutex);
2437 	if (ret)
2438 		pr_err("Failed to restore CRIU ret:%d\n", ret);
2439 	else
2440 		pr_debug("CRIU restore successful\n");
2441 
2442 	return ret;
2443 }
2444 
2445 static int criu_unpause(struct file *filep,
2446 			struct kfd_process *p,
2447 			struct kfd_ioctl_criu_args *args)
2448 {
2449 	int ret;
2450 
2451 	mutex_lock(&p->mutex);
2452 
2453 	if (!p->queues_paused) {
2454 		mutex_unlock(&p->mutex);
2455 		return -EINVAL;
2456 	}
2457 
2458 	ret = kfd_process_restore_queues(p);
2459 	if (ret)
2460 		pr_err("Failed to unpause queues ret:%d\n", ret);
2461 	else
2462 		p->queues_paused = false;
2463 
2464 	mutex_unlock(&p->mutex);
2465 
2466 	return ret;
2467 }
2468 
2469 static int criu_resume(struct file *filep,
2470 			struct kfd_process *p,
2471 			struct kfd_ioctl_criu_args *args)
2472 {
2473 	struct kfd_process *target = NULL;
2474 	struct pid *pid = NULL;
2475 	int ret = 0;
2476 
2477 	pr_debug("Inside %s, target pid for criu restore: %d\n", __func__,
2478 		 args->pid);
2479 
2480 	pid = find_get_pid(args->pid);
2481 	if (!pid) {
2482 		pr_err("Cannot find pid info for %i\n", args->pid);
2483 		return -ESRCH;
2484 	}
2485 
2486 	pr_debug("calling kfd_lookup_process_by_pid\n");
2487 	target = kfd_lookup_process_by_pid(pid);
2488 
2489 	put_pid(pid);
2490 
2491 	if (!target) {
2492 		pr_debug("Cannot find process info for %i\n", args->pid);
2493 		return -ESRCH;
2494 	}
2495 
2496 	mutex_lock(&target->mutex);
2497 	ret = kfd_criu_resume_svm(target);
2498 	if (ret) {
2499 		pr_err("kfd_criu_resume_svm failed for %i\n", args->pid);
2500 		goto exit;
2501 	}
2502 
2503 	ret =  amdgpu_amdkfd_criu_resume(target->kgd_process_info);
2504 	if (ret)
2505 		pr_err("amdgpu_amdkfd_criu_resume failed for %i\n", args->pid);
2506 
2507 exit:
2508 	mutex_unlock(&target->mutex);
2509 
2510 	kfd_unref_process(target);
2511 	return ret;
2512 }
2513 
2514 static int criu_process_info(struct file *filep,
2515 				struct kfd_process *p,
2516 				struct kfd_ioctl_criu_args *args)
2517 {
2518 	int ret = 0;
2519 
2520 	mutex_lock(&p->mutex);
2521 
2522 	if (!p->n_pdds) {
2523 		pr_err("No pdd for given process\n");
2524 		ret = -ENODEV;
2525 		goto err_unlock;
2526 	}
2527 
2528 	ret = kfd_process_evict_queues(p);
2529 	if (ret)
2530 		goto err_unlock;
2531 
2532 	p->queues_paused = true;
2533 
2534 	args->pid = task_pid_nr_ns(p->lead_thread,
2535 					task_active_pid_ns(p->lead_thread));
2536 
2537 	ret = criu_get_process_object_info(p, &args->num_devices, &args->num_bos,
2538 					   &args->num_objects, &args->priv_data_size);
2539 	if (ret)
2540 		goto err_unlock;
2541 
2542 	dev_dbg(kfd_device, "Num of devices:%u bos:%u objects:%u priv_data_size:%lld\n",
2543 				args->num_devices, args->num_bos, args->num_objects,
2544 				args->priv_data_size);
2545 
2546 err_unlock:
2547 	if (ret) {
2548 		kfd_process_restore_queues(p);
2549 		p->queues_paused = false;
2550 	}
2551 	mutex_unlock(&p->mutex);
2552 	return ret;
2553 }
2554 
2555 static int kfd_ioctl_criu(struct file *filep, struct kfd_process *p, void *data)
2556 {
2557 	struct kfd_ioctl_criu_args *args = data;
2558 	int ret;
2559 
2560 	dev_dbg(kfd_device, "CRIU operation: %d\n", args->op);
2561 	switch (args->op) {
2562 	case KFD_CRIU_OP_PROCESS_INFO:
2563 		ret = criu_process_info(filep, p, args);
2564 		break;
2565 	case KFD_CRIU_OP_CHECKPOINT:
2566 		ret = criu_checkpoint(filep, p, args);
2567 		break;
2568 	case KFD_CRIU_OP_UNPAUSE:
2569 		ret = criu_unpause(filep, p, args);
2570 		break;
2571 	case KFD_CRIU_OP_RESTORE:
2572 		ret = criu_restore(filep, p, args);
2573 		break;
2574 	case KFD_CRIU_OP_RESUME:
2575 		ret = criu_resume(filep, p, args);
2576 		break;
2577 	default:
2578 		dev_dbg(kfd_device, "Unsupported CRIU operation:%d\n", args->op);
2579 		ret = -EINVAL;
2580 		break;
2581 	}
2582 
2583 	if (ret)
2584 		dev_dbg(kfd_device, "CRIU operation:%d err:%d\n", args->op, ret);
2585 
2586 	return ret;
2587 }
2588 
2589 #define AMDKFD_IOCTL_DEF(ioctl, _func, _flags) \
2590 	[_IOC_NR(ioctl)] = {.cmd = ioctl, .func = _func, .flags = _flags, \
2591 			    .cmd_drv = 0, .name = #ioctl}
2592 
2593 /** Ioctl table */
2594 static const struct amdkfd_ioctl_desc amdkfd_ioctls[] = {
2595 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_GET_VERSION,
2596 			kfd_ioctl_get_version, 0),
2597 
2598 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_CREATE_QUEUE,
2599 			kfd_ioctl_create_queue, 0),
2600 
2601 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_DESTROY_QUEUE,
2602 			kfd_ioctl_destroy_queue, 0),
2603 
2604 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_SET_MEMORY_POLICY,
2605 			kfd_ioctl_set_memory_policy, 0),
2606 
2607 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_GET_CLOCK_COUNTERS,
2608 			kfd_ioctl_get_clock_counters, 0),
2609 
2610 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_GET_PROCESS_APERTURES,
2611 			kfd_ioctl_get_process_apertures, 0),
2612 
2613 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_UPDATE_QUEUE,
2614 			kfd_ioctl_update_queue, 0),
2615 
2616 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_CREATE_EVENT,
2617 			kfd_ioctl_create_event, 0),
2618 
2619 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_DESTROY_EVENT,
2620 			kfd_ioctl_destroy_event, 0),
2621 
2622 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_SET_EVENT,
2623 			kfd_ioctl_set_event, 0),
2624 
2625 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_RESET_EVENT,
2626 			kfd_ioctl_reset_event, 0),
2627 
2628 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_WAIT_EVENTS,
2629 			kfd_ioctl_wait_events, 0),
2630 
2631 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_DBG_REGISTER_DEPRECATED,
2632 			kfd_ioctl_dbg_register, 0),
2633 
2634 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_DBG_UNREGISTER_DEPRECATED,
2635 			kfd_ioctl_dbg_unregister, 0),
2636 
2637 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_DBG_ADDRESS_WATCH_DEPRECATED,
2638 			kfd_ioctl_dbg_address_watch, 0),
2639 
2640 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_DBG_WAVE_CONTROL_DEPRECATED,
2641 			kfd_ioctl_dbg_wave_control, 0),
2642 
2643 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_SET_SCRATCH_BACKING_VA,
2644 			kfd_ioctl_set_scratch_backing_va, 0),
2645 
2646 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_GET_TILE_CONFIG,
2647 			kfd_ioctl_get_tile_config, 0),
2648 
2649 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_SET_TRAP_HANDLER,
2650 			kfd_ioctl_set_trap_handler, 0),
2651 
2652 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_GET_PROCESS_APERTURES_NEW,
2653 			kfd_ioctl_get_process_apertures_new, 0),
2654 
2655 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_ACQUIRE_VM,
2656 			kfd_ioctl_acquire_vm, 0),
2657 
2658 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_ALLOC_MEMORY_OF_GPU,
2659 			kfd_ioctl_alloc_memory_of_gpu, 0),
2660 
2661 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_FREE_MEMORY_OF_GPU,
2662 			kfd_ioctl_free_memory_of_gpu, 0),
2663 
2664 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_MAP_MEMORY_TO_GPU,
2665 			kfd_ioctl_map_memory_to_gpu, 0),
2666 
2667 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_UNMAP_MEMORY_FROM_GPU,
2668 			kfd_ioctl_unmap_memory_from_gpu, 0),
2669 
2670 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_SET_CU_MASK,
2671 			kfd_ioctl_set_cu_mask, 0),
2672 
2673 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_GET_QUEUE_WAVE_STATE,
2674 			kfd_ioctl_get_queue_wave_state, 0),
2675 
2676 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_GET_DMABUF_INFO,
2677 				kfd_ioctl_get_dmabuf_info, 0),
2678 
2679 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_IMPORT_DMABUF,
2680 				kfd_ioctl_import_dmabuf, 0),
2681 
2682 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_ALLOC_QUEUE_GWS,
2683 			kfd_ioctl_alloc_queue_gws, 0),
2684 
2685 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_SMI_EVENTS,
2686 			kfd_ioctl_smi_events, 0),
2687 
2688 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_SVM, kfd_ioctl_svm, 0),
2689 
2690 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_SET_XNACK_MODE,
2691 			kfd_ioctl_set_xnack_mode, 0),
2692 
2693 	AMDKFD_IOCTL_DEF(AMDKFD_IOC_CRIU_OP,
2694 			kfd_ioctl_criu, KFD_IOC_FLAG_CHECKPOINT_RESTORE),
2695 
2696 };
2697 
2698 #define AMDKFD_CORE_IOCTL_COUNT	ARRAY_SIZE(amdkfd_ioctls)
2699 
2700 static long kfd_ioctl(struct file *filep, unsigned int cmd, unsigned long arg)
2701 {
2702 	struct kfd_process *process;
2703 	amdkfd_ioctl_t *func;
2704 	const struct amdkfd_ioctl_desc *ioctl = NULL;
2705 	unsigned int nr = _IOC_NR(cmd);
2706 	char stack_kdata[128];
2707 	char *kdata = NULL;
2708 	unsigned int usize, asize;
2709 	int retcode = -EINVAL;
2710 	bool ptrace_attached = false;
2711 
2712 	if (nr >= AMDKFD_CORE_IOCTL_COUNT)
2713 		goto err_i1;
2714 
2715 	if ((nr >= AMDKFD_COMMAND_START) && (nr < AMDKFD_COMMAND_END)) {
2716 		u32 amdkfd_size;
2717 
2718 		ioctl = &amdkfd_ioctls[nr];
2719 
2720 		amdkfd_size = _IOC_SIZE(ioctl->cmd);
2721 		usize = asize = _IOC_SIZE(cmd);
2722 		if (amdkfd_size > asize)
2723 			asize = amdkfd_size;
2724 
2725 		cmd = ioctl->cmd;
2726 	} else
2727 		goto err_i1;
2728 
2729 	dev_dbg(kfd_device, "ioctl cmd 0x%x (#0x%x), arg 0x%lx\n", cmd, nr, arg);
2730 
2731 	/* Get the process struct from the filep. Only the process
2732 	 * that opened /dev/kfd can use the file descriptor. Child
2733 	 * processes need to create their own KFD device context.
2734 	 */
2735 	process = filep->private_data;
2736 
2737 	rcu_read_lock();
2738 	if ((ioctl->flags & KFD_IOC_FLAG_CHECKPOINT_RESTORE) &&
2739 	    ptrace_parent(process->lead_thread) == current)
2740 		ptrace_attached = true;
2741 	rcu_read_unlock();
2742 
2743 	if (process->lead_thread != current->group_leader
2744 	    && !ptrace_attached) {
2745 		dev_dbg(kfd_device, "Using KFD FD in wrong process\n");
2746 		retcode = -EBADF;
2747 		goto err_i1;
2748 	}
2749 
2750 	/* Do not trust userspace, use our own definition */
2751 	func = ioctl->func;
2752 
2753 	if (unlikely(!func)) {
2754 		dev_dbg(kfd_device, "no function\n");
2755 		retcode = -EINVAL;
2756 		goto err_i1;
2757 	}
2758 
2759 	/*
2760 	 * Versions of docker shipped in Ubuntu 18.xx and 20.xx do not support
2761 	 * CAP_CHECKPOINT_RESTORE, so we also allow access if CAP_SYS_ADMIN as CAP_SYS_ADMIN is a
2762 	 * more priviledged access.
2763 	 */
2764 	if (unlikely(ioctl->flags & KFD_IOC_FLAG_CHECKPOINT_RESTORE)) {
2765 		if (!capable(CAP_CHECKPOINT_RESTORE) &&
2766 						!capable(CAP_SYS_ADMIN)) {
2767 			retcode = -EACCES;
2768 			goto err_i1;
2769 		}
2770 	}
2771 
2772 	if (cmd & (IOC_IN | IOC_OUT)) {
2773 		if (asize <= sizeof(stack_kdata)) {
2774 			kdata = stack_kdata;
2775 		} else {
2776 			kdata = kmalloc(asize, GFP_KERNEL);
2777 			if (!kdata) {
2778 				retcode = -ENOMEM;
2779 				goto err_i1;
2780 			}
2781 		}
2782 		if (asize > usize)
2783 			memset(kdata + usize, 0, asize - usize);
2784 	}
2785 
2786 	if (cmd & IOC_IN) {
2787 		if (copy_from_user(kdata, (void __user *)arg, usize) != 0) {
2788 			retcode = -EFAULT;
2789 			goto err_i1;
2790 		}
2791 	} else if (cmd & IOC_OUT) {
2792 		memset(kdata, 0, usize);
2793 	}
2794 
2795 	retcode = func(filep, process, kdata);
2796 
2797 	if (cmd & IOC_OUT)
2798 		if (copy_to_user((void __user *)arg, kdata, usize) != 0)
2799 			retcode = -EFAULT;
2800 
2801 err_i1:
2802 	if (!ioctl)
2803 		dev_dbg(kfd_device, "invalid ioctl: pid=%d, cmd=0x%02x, nr=0x%02x\n",
2804 			  task_pid_nr(current), cmd, nr);
2805 
2806 	if (kdata != stack_kdata)
2807 		kfree(kdata);
2808 
2809 	if (retcode)
2810 		dev_dbg(kfd_device, "ioctl cmd (#0x%x), arg 0x%lx, ret = %d\n",
2811 				nr, arg, retcode);
2812 
2813 	return retcode;
2814 }
2815 
2816 static int kfd_mmio_mmap(struct kfd_dev *dev, struct kfd_process *process,
2817 		      struct vm_area_struct *vma)
2818 {
2819 	phys_addr_t address;
2820 	int ret;
2821 
2822 	if (vma->vm_end - vma->vm_start != PAGE_SIZE)
2823 		return -EINVAL;
2824 
2825 	address = dev->adev->rmmio_remap.bus_addr;
2826 
2827 	vma->vm_flags |= VM_IO | VM_DONTCOPY | VM_DONTEXPAND | VM_NORESERVE |
2828 				VM_DONTDUMP | VM_PFNMAP;
2829 
2830 	vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
2831 
2832 	pr_debug("pasid 0x%x mapping mmio page\n"
2833 		 "     target user address == 0x%08llX\n"
2834 		 "     physical address    == 0x%08llX\n"
2835 		 "     vm_flags            == 0x%04lX\n"
2836 		 "     size                == 0x%04lX\n",
2837 		 process->pasid, (unsigned long long) vma->vm_start,
2838 		 address, vma->vm_flags, PAGE_SIZE);
2839 
2840 	ret = io_remap_pfn_range(vma,
2841 				vma->vm_start,
2842 				address >> PAGE_SHIFT,
2843 				PAGE_SIZE,
2844 				vma->vm_page_prot);
2845 	return ret;
2846 }
2847 
2848 
2849 static int kfd_mmap(struct file *filp, struct vm_area_struct *vma)
2850 {
2851 	struct kfd_process *process;
2852 	struct kfd_dev *dev = NULL;
2853 	unsigned long mmap_offset;
2854 	unsigned int gpu_id;
2855 
2856 	process = kfd_get_process(current);
2857 	if (IS_ERR(process))
2858 		return PTR_ERR(process);
2859 
2860 	mmap_offset = vma->vm_pgoff << PAGE_SHIFT;
2861 	gpu_id = KFD_MMAP_GET_GPU_ID(mmap_offset);
2862 	if (gpu_id)
2863 		dev = kfd_device_by_id(gpu_id);
2864 
2865 	switch (mmap_offset & KFD_MMAP_TYPE_MASK) {
2866 	case KFD_MMAP_TYPE_DOORBELL:
2867 		if (!dev)
2868 			return -ENODEV;
2869 		return kfd_doorbell_mmap(dev, process, vma);
2870 
2871 	case KFD_MMAP_TYPE_EVENTS:
2872 		return kfd_event_mmap(process, vma);
2873 
2874 	case KFD_MMAP_TYPE_RESERVED_MEM:
2875 		if (!dev)
2876 			return -ENODEV;
2877 		return kfd_reserved_mem_mmap(dev, process, vma);
2878 	case KFD_MMAP_TYPE_MMIO:
2879 		if (!dev)
2880 			return -ENODEV;
2881 		return kfd_mmio_mmap(dev, process, vma);
2882 	}
2883 
2884 	return -EFAULT;
2885 }
2886