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