xref: /linux/drivers/gpu/drm/amd/amdkfd/kfd_process.c (revision bf62221e9d0e1e4ba50ab2b331a0008c15de97be)
1 /*
2  * Copyright 2014 Advanced Micro Devices, Inc.
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
17  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
18  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
20  * OTHER DEALINGS IN THE SOFTWARE.
21  */
22 
23 #include <linux/mutex.h>
24 #include <linux/log2.h>
25 #include <linux/sched.h>
26 #include <linux/sched/mm.h>
27 #include <linux/sched/task.h>
28 #include <linux/mmu_context.h>
29 #include <linux/slab.h>
30 #include <linux/amd-iommu.h>
31 #include <linux/notifier.h>
32 #include <linux/compat.h>
33 #include <linux/mman.h>
34 #include <linux/file.h>
35 #include <linux/pm_runtime.h>
36 #include "amdgpu_amdkfd.h"
37 #include "amdgpu.h"
38 #include "kfd_svm.h"
39 
40 struct mm_struct;
41 
42 #include "kfd_priv.h"
43 #include "kfd_device_queue_manager.h"
44 #include "kfd_dbgmgr.h"
45 #include "kfd_iommu.h"
46 #include "kfd_svm.h"
47 
48 /*
49  * List of struct kfd_process (field kfd_process).
50  * Unique/indexed by mm_struct*
51  */
52 DEFINE_HASHTABLE(kfd_processes_table, KFD_PROCESS_TABLE_SIZE);
53 static DEFINE_MUTEX(kfd_processes_mutex);
54 
55 DEFINE_SRCU(kfd_processes_srcu);
56 
57 /* For process termination handling */
58 static struct workqueue_struct *kfd_process_wq;
59 
60 /* Ordered, single-threaded workqueue for restoring evicted
61  * processes. Restoring multiple processes concurrently under memory
62  * pressure can lead to processes blocking each other from validating
63  * their BOs and result in a live-lock situation where processes
64  * remain evicted indefinitely.
65  */
66 static struct workqueue_struct *kfd_restore_wq;
67 
68 static struct kfd_process *find_process(const struct task_struct *thread);
69 static void kfd_process_ref_release(struct kref *ref);
70 static struct kfd_process *create_process(const struct task_struct *thread);
71 static int kfd_process_init_cwsr_apu(struct kfd_process *p, struct file *filep);
72 
73 static void evict_process_worker(struct work_struct *work);
74 static void restore_process_worker(struct work_struct *work);
75 
76 struct kfd_procfs_tree {
77 	struct kobject *kobj;
78 };
79 
80 static struct kfd_procfs_tree procfs;
81 
82 /*
83  * Structure for SDMA activity tracking
84  */
85 struct kfd_sdma_activity_handler_workarea {
86 	struct work_struct sdma_activity_work;
87 	struct kfd_process_device *pdd;
88 	uint64_t sdma_activity_counter;
89 };
90 
91 struct temp_sdma_queue_list {
92 	uint64_t __user *rptr;
93 	uint64_t sdma_val;
94 	unsigned int queue_id;
95 	struct list_head list;
96 };
97 
98 static void kfd_sdma_activity_worker(struct work_struct *work)
99 {
100 	struct kfd_sdma_activity_handler_workarea *workarea;
101 	struct kfd_process_device *pdd;
102 	uint64_t val;
103 	struct mm_struct *mm;
104 	struct queue *q;
105 	struct qcm_process_device *qpd;
106 	struct device_queue_manager *dqm;
107 	int ret = 0;
108 	struct temp_sdma_queue_list sdma_q_list;
109 	struct temp_sdma_queue_list *sdma_q, *next;
110 
111 	workarea = container_of(work, struct kfd_sdma_activity_handler_workarea,
112 				sdma_activity_work);
113 
114 	pdd = workarea->pdd;
115 	if (!pdd)
116 		return;
117 	dqm = pdd->dev->dqm;
118 	qpd = &pdd->qpd;
119 	if (!dqm || !qpd)
120 		return;
121 	/*
122 	 * Total SDMA activity is current SDMA activity + past SDMA activity
123 	 * Past SDMA count is stored in pdd.
124 	 * To get the current activity counters for all active SDMA queues,
125 	 * we loop over all SDMA queues and get their counts from user-space.
126 	 *
127 	 * We cannot call get_user() with dqm_lock held as it can cause
128 	 * a circular lock dependency situation. To read the SDMA stats,
129 	 * we need to do the following:
130 	 *
131 	 * 1. Create a temporary list of SDMA queue nodes from the qpd->queues_list,
132 	 *    with dqm_lock/dqm_unlock().
133 	 * 2. Call get_user() for each node in temporary list without dqm_lock.
134 	 *    Save the SDMA count for each node and also add the count to the total
135 	 *    SDMA count counter.
136 	 *    Its possible, during this step, a few SDMA queue nodes got deleted
137 	 *    from the qpd->queues_list.
138 	 * 3. Do a second pass over qpd->queues_list to check if any nodes got deleted.
139 	 *    If any node got deleted, its SDMA count would be captured in the sdma
140 	 *    past activity counter. So subtract the SDMA counter stored in step 2
141 	 *    for this node from the total SDMA count.
142 	 */
143 	INIT_LIST_HEAD(&sdma_q_list.list);
144 
145 	/*
146 	 * Create the temp list of all SDMA queues
147 	 */
148 	dqm_lock(dqm);
149 
150 	list_for_each_entry(q, &qpd->queues_list, list) {
151 		if ((q->properties.type != KFD_QUEUE_TYPE_SDMA) &&
152 		    (q->properties.type != KFD_QUEUE_TYPE_SDMA_XGMI))
153 			continue;
154 
155 		sdma_q = kzalloc(sizeof(struct temp_sdma_queue_list), GFP_KERNEL);
156 		if (!sdma_q) {
157 			dqm_unlock(dqm);
158 			goto cleanup;
159 		}
160 
161 		INIT_LIST_HEAD(&sdma_q->list);
162 		sdma_q->rptr = (uint64_t __user *)q->properties.read_ptr;
163 		sdma_q->queue_id = q->properties.queue_id;
164 		list_add_tail(&sdma_q->list, &sdma_q_list.list);
165 	}
166 
167 	/*
168 	 * If the temp list is empty, then no SDMA queues nodes were found in
169 	 * qpd->queues_list. Return the past activity count as the total sdma
170 	 * count
171 	 */
172 	if (list_empty(&sdma_q_list.list)) {
173 		workarea->sdma_activity_counter = pdd->sdma_past_activity_counter;
174 		dqm_unlock(dqm);
175 		return;
176 	}
177 
178 	dqm_unlock(dqm);
179 
180 	/*
181 	 * Get the usage count for each SDMA queue in temp_list.
182 	 */
183 	mm = get_task_mm(pdd->process->lead_thread);
184 	if (!mm)
185 		goto cleanup;
186 
187 	kthread_use_mm(mm);
188 
189 	list_for_each_entry(sdma_q, &sdma_q_list.list, list) {
190 		val = 0;
191 		ret = read_sdma_queue_counter(sdma_q->rptr, &val);
192 		if (ret) {
193 			pr_debug("Failed to read SDMA queue active counter for queue id: %d",
194 				 sdma_q->queue_id);
195 		} else {
196 			sdma_q->sdma_val = val;
197 			workarea->sdma_activity_counter += val;
198 		}
199 	}
200 
201 	kthread_unuse_mm(mm);
202 	mmput(mm);
203 
204 	/*
205 	 * Do a second iteration over qpd_queues_list to check if any SDMA
206 	 * nodes got deleted while fetching SDMA counter.
207 	 */
208 	dqm_lock(dqm);
209 
210 	workarea->sdma_activity_counter += pdd->sdma_past_activity_counter;
211 
212 	list_for_each_entry(q, &qpd->queues_list, list) {
213 		if (list_empty(&sdma_q_list.list))
214 			break;
215 
216 		if ((q->properties.type != KFD_QUEUE_TYPE_SDMA) &&
217 		    (q->properties.type != KFD_QUEUE_TYPE_SDMA_XGMI))
218 			continue;
219 
220 		list_for_each_entry_safe(sdma_q, next, &sdma_q_list.list, list) {
221 			if (((uint64_t __user *)q->properties.read_ptr == sdma_q->rptr) &&
222 			     (sdma_q->queue_id == q->properties.queue_id)) {
223 				list_del(&sdma_q->list);
224 				kfree(sdma_q);
225 				break;
226 			}
227 		}
228 	}
229 
230 	dqm_unlock(dqm);
231 
232 	/*
233 	 * If temp list is not empty, it implies some queues got deleted
234 	 * from qpd->queues_list during SDMA usage read. Subtract the SDMA
235 	 * count for each node from the total SDMA count.
236 	 */
237 	list_for_each_entry_safe(sdma_q, next, &sdma_q_list.list, list) {
238 		workarea->sdma_activity_counter -= sdma_q->sdma_val;
239 		list_del(&sdma_q->list);
240 		kfree(sdma_q);
241 	}
242 
243 	return;
244 
245 cleanup:
246 	list_for_each_entry_safe(sdma_q, next, &sdma_q_list.list, list) {
247 		list_del(&sdma_q->list);
248 		kfree(sdma_q);
249 	}
250 }
251 
252 /**
253  * @kfd_get_cu_occupancy - Collect number of waves in-flight on this device
254  * by current process. Translates acquired wave count into number of compute units
255  * that are occupied.
256  *
257  * @atr: Handle of attribute that allows reporting of wave count. The attribute
258  * handle encapsulates GPU device it is associated with, thereby allowing collection
259  * of waves in flight, etc
260  *
261  * @buffer: Handle of user provided buffer updated with wave count
262  *
263  * Return: Number of bytes written to user buffer or an error value
264  */
265 static int kfd_get_cu_occupancy(struct attribute *attr, char *buffer)
266 {
267 	int cu_cnt;
268 	int wave_cnt;
269 	int max_waves_per_cu;
270 	struct kfd_dev *dev = NULL;
271 	struct kfd_process *proc = NULL;
272 	struct kfd_process_device *pdd = NULL;
273 
274 	pdd = container_of(attr, struct kfd_process_device, attr_cu_occupancy);
275 	dev = pdd->dev;
276 	if (dev->kfd2kgd->get_cu_occupancy == NULL)
277 		return -EINVAL;
278 
279 	cu_cnt = 0;
280 	proc = pdd->process;
281 	if (pdd->qpd.queue_count == 0) {
282 		pr_debug("Gpu-Id: %d has no active queues for process %d\n",
283 			 dev->id, proc->pasid);
284 		return snprintf(buffer, PAGE_SIZE, "%d\n", cu_cnt);
285 	}
286 
287 	/* Collect wave count from device if it supports */
288 	wave_cnt = 0;
289 	max_waves_per_cu = 0;
290 	dev->kfd2kgd->get_cu_occupancy(dev->kgd, proc->pasid, &wave_cnt,
291 			&max_waves_per_cu);
292 
293 	/* Translate wave count to number of compute units */
294 	cu_cnt = (wave_cnt + (max_waves_per_cu - 1)) / max_waves_per_cu;
295 	return snprintf(buffer, PAGE_SIZE, "%d\n", cu_cnt);
296 }
297 
298 static ssize_t kfd_procfs_show(struct kobject *kobj, struct attribute *attr,
299 			       char *buffer)
300 {
301 	if (strcmp(attr->name, "pasid") == 0) {
302 		struct kfd_process *p = container_of(attr, struct kfd_process,
303 						     attr_pasid);
304 
305 		return snprintf(buffer, PAGE_SIZE, "%d\n", p->pasid);
306 	} else if (strncmp(attr->name, "vram_", 5) == 0) {
307 		struct kfd_process_device *pdd = container_of(attr, struct kfd_process_device,
308 							      attr_vram);
309 		return snprintf(buffer, PAGE_SIZE, "%llu\n", READ_ONCE(pdd->vram_usage));
310 	} else if (strncmp(attr->name, "sdma_", 5) == 0) {
311 		struct kfd_process_device *pdd = container_of(attr, struct kfd_process_device,
312 							      attr_sdma);
313 		struct kfd_sdma_activity_handler_workarea sdma_activity_work_handler;
314 
315 		INIT_WORK(&sdma_activity_work_handler.sdma_activity_work,
316 					kfd_sdma_activity_worker);
317 
318 		sdma_activity_work_handler.pdd = pdd;
319 		sdma_activity_work_handler.sdma_activity_counter = 0;
320 
321 		schedule_work(&sdma_activity_work_handler.sdma_activity_work);
322 
323 		flush_work(&sdma_activity_work_handler.sdma_activity_work);
324 
325 		return snprintf(buffer, PAGE_SIZE, "%llu\n",
326 				(sdma_activity_work_handler.sdma_activity_counter)/
327 				 SDMA_ACTIVITY_DIVISOR);
328 	} else {
329 		pr_err("Invalid attribute");
330 		return -EINVAL;
331 	}
332 
333 	return 0;
334 }
335 
336 static void kfd_procfs_kobj_release(struct kobject *kobj)
337 {
338 	kfree(kobj);
339 }
340 
341 static const struct sysfs_ops kfd_procfs_ops = {
342 	.show = kfd_procfs_show,
343 };
344 
345 static struct kobj_type procfs_type = {
346 	.release = kfd_procfs_kobj_release,
347 	.sysfs_ops = &kfd_procfs_ops,
348 };
349 
350 void kfd_procfs_init(void)
351 {
352 	int ret = 0;
353 
354 	procfs.kobj = kfd_alloc_struct(procfs.kobj);
355 	if (!procfs.kobj)
356 		return;
357 
358 	ret = kobject_init_and_add(procfs.kobj, &procfs_type,
359 				   &kfd_device->kobj, "proc");
360 	if (ret) {
361 		pr_warn("Could not create procfs proc folder");
362 		/* If we fail to create the procfs, clean up */
363 		kfd_procfs_shutdown();
364 	}
365 }
366 
367 void kfd_procfs_shutdown(void)
368 {
369 	if (procfs.kobj) {
370 		kobject_del(procfs.kobj);
371 		kobject_put(procfs.kobj);
372 		procfs.kobj = NULL;
373 	}
374 }
375 
376 static ssize_t kfd_procfs_queue_show(struct kobject *kobj,
377 				     struct attribute *attr, char *buffer)
378 {
379 	struct queue *q = container_of(kobj, struct queue, kobj);
380 
381 	if (!strcmp(attr->name, "size"))
382 		return snprintf(buffer, PAGE_SIZE, "%llu",
383 				q->properties.queue_size);
384 	else if (!strcmp(attr->name, "type"))
385 		return snprintf(buffer, PAGE_SIZE, "%d", q->properties.type);
386 	else if (!strcmp(attr->name, "gpuid"))
387 		return snprintf(buffer, PAGE_SIZE, "%u", q->device->id);
388 	else
389 		pr_err("Invalid attribute");
390 
391 	return 0;
392 }
393 
394 static ssize_t kfd_procfs_stats_show(struct kobject *kobj,
395 				     struct attribute *attr, char *buffer)
396 {
397 	if (strcmp(attr->name, "evicted_ms") == 0) {
398 		struct kfd_process_device *pdd = container_of(attr,
399 				struct kfd_process_device,
400 				attr_evict);
401 		uint64_t evict_jiffies;
402 
403 		evict_jiffies = atomic64_read(&pdd->evict_duration_counter);
404 
405 		return snprintf(buffer,
406 				PAGE_SIZE,
407 				"%llu\n",
408 				jiffies64_to_msecs(evict_jiffies));
409 
410 	/* Sysfs handle that gets CU occupancy is per device */
411 	} else if (strcmp(attr->name, "cu_occupancy") == 0) {
412 		return kfd_get_cu_occupancy(attr, buffer);
413 	} else {
414 		pr_err("Invalid attribute");
415 	}
416 
417 	return 0;
418 }
419 
420 static struct attribute attr_queue_size = {
421 	.name = "size",
422 	.mode = KFD_SYSFS_FILE_MODE
423 };
424 
425 static struct attribute attr_queue_type = {
426 	.name = "type",
427 	.mode = KFD_SYSFS_FILE_MODE
428 };
429 
430 static struct attribute attr_queue_gpuid = {
431 	.name = "gpuid",
432 	.mode = KFD_SYSFS_FILE_MODE
433 };
434 
435 static struct attribute *procfs_queue_attrs[] = {
436 	&attr_queue_size,
437 	&attr_queue_type,
438 	&attr_queue_gpuid,
439 	NULL
440 };
441 
442 static const struct sysfs_ops procfs_queue_ops = {
443 	.show = kfd_procfs_queue_show,
444 };
445 
446 static struct kobj_type procfs_queue_type = {
447 	.sysfs_ops = &procfs_queue_ops,
448 	.default_attrs = procfs_queue_attrs,
449 };
450 
451 static const struct sysfs_ops procfs_stats_ops = {
452 	.show = kfd_procfs_stats_show,
453 };
454 
455 static struct attribute *procfs_stats_attrs[] = {
456 	NULL
457 };
458 
459 static struct kobj_type procfs_stats_type = {
460 	.sysfs_ops = &procfs_stats_ops,
461 	.default_attrs = procfs_stats_attrs,
462 };
463 
464 int kfd_procfs_add_queue(struct queue *q)
465 {
466 	struct kfd_process *proc;
467 	int ret;
468 
469 	if (!q || !q->process)
470 		return -EINVAL;
471 	proc = q->process;
472 
473 	/* Create proc/<pid>/queues/<queue id> folder */
474 	if (!proc->kobj_queues)
475 		return -EFAULT;
476 	ret = kobject_init_and_add(&q->kobj, &procfs_queue_type,
477 			proc->kobj_queues, "%u", q->properties.queue_id);
478 	if (ret < 0) {
479 		pr_warn("Creating proc/<pid>/queues/%u failed",
480 			q->properties.queue_id);
481 		kobject_put(&q->kobj);
482 		return ret;
483 	}
484 
485 	return 0;
486 }
487 
488 static int kfd_sysfs_create_file(struct kfd_process *p, struct attribute *attr,
489 				 char *name)
490 {
491 	int ret = 0;
492 
493 	if (!p || !attr || !name)
494 		return -EINVAL;
495 
496 	attr->name = name;
497 	attr->mode = KFD_SYSFS_FILE_MODE;
498 	sysfs_attr_init(attr);
499 
500 	ret = sysfs_create_file(p->kobj, attr);
501 
502 	return ret;
503 }
504 
505 static int kfd_procfs_add_sysfs_stats(struct kfd_process *p)
506 {
507 	int ret = 0;
508 	int i;
509 	char stats_dir_filename[MAX_SYSFS_FILENAME_LEN];
510 
511 	if (!p)
512 		return -EINVAL;
513 
514 	if (!p->kobj)
515 		return -EFAULT;
516 
517 	/*
518 	 * Create sysfs files for each GPU:
519 	 * - proc/<pid>/stats_<gpuid>/
520 	 * - proc/<pid>/stats_<gpuid>/evicted_ms
521 	 * - proc/<pid>/stats_<gpuid>/cu_occupancy
522 	 */
523 	for (i = 0; i < p->n_pdds; i++) {
524 		struct kfd_process_device *pdd = p->pdds[i];
525 		struct kobject *kobj_stats;
526 
527 		snprintf(stats_dir_filename, MAX_SYSFS_FILENAME_LEN,
528 				"stats_%u", pdd->dev->id);
529 		kobj_stats = kfd_alloc_struct(kobj_stats);
530 		if (!kobj_stats)
531 			return -ENOMEM;
532 
533 		ret = kobject_init_and_add(kobj_stats,
534 						&procfs_stats_type,
535 						p->kobj,
536 						stats_dir_filename);
537 
538 		if (ret) {
539 			pr_warn("Creating KFD proc/stats_%s folder failed",
540 					stats_dir_filename);
541 			kobject_put(kobj_stats);
542 			goto err;
543 		}
544 
545 		pdd->kobj_stats = kobj_stats;
546 		pdd->attr_evict.name = "evicted_ms";
547 		pdd->attr_evict.mode = KFD_SYSFS_FILE_MODE;
548 		sysfs_attr_init(&pdd->attr_evict);
549 		ret = sysfs_create_file(kobj_stats, &pdd->attr_evict);
550 		if (ret)
551 			pr_warn("Creating eviction stats for gpuid %d failed",
552 					(int)pdd->dev->id);
553 
554 		/* Add sysfs file to report compute unit occupancy */
555 		if (pdd->dev->kfd2kgd->get_cu_occupancy != NULL) {
556 			pdd->attr_cu_occupancy.name = "cu_occupancy";
557 			pdd->attr_cu_occupancy.mode = KFD_SYSFS_FILE_MODE;
558 			sysfs_attr_init(&pdd->attr_cu_occupancy);
559 			ret = sysfs_create_file(kobj_stats,
560 						&pdd->attr_cu_occupancy);
561 			if (ret)
562 				pr_warn("Creating %s failed for gpuid: %d",
563 					pdd->attr_cu_occupancy.name,
564 					(int)pdd->dev->id);
565 		}
566 	}
567 err:
568 	return ret;
569 }
570 
571 
572 static int kfd_procfs_add_sysfs_files(struct kfd_process *p)
573 {
574 	int ret = 0;
575 	int i;
576 
577 	if (!p)
578 		return -EINVAL;
579 
580 	if (!p->kobj)
581 		return -EFAULT;
582 
583 	/*
584 	 * Create sysfs files for each GPU:
585 	 * - proc/<pid>/vram_<gpuid>
586 	 * - proc/<pid>/sdma_<gpuid>
587 	 */
588 	for (i = 0; i < p->n_pdds; i++) {
589 		struct kfd_process_device *pdd = p->pdds[i];
590 
591 		snprintf(pdd->vram_filename, MAX_SYSFS_FILENAME_LEN, "vram_%u",
592 			 pdd->dev->id);
593 		ret = kfd_sysfs_create_file(p, &pdd->attr_vram, pdd->vram_filename);
594 		if (ret)
595 			pr_warn("Creating vram usage for gpu id %d failed",
596 				(int)pdd->dev->id);
597 
598 		snprintf(pdd->sdma_filename, MAX_SYSFS_FILENAME_LEN, "sdma_%u",
599 			 pdd->dev->id);
600 		ret = kfd_sysfs_create_file(p, &pdd->attr_sdma, pdd->sdma_filename);
601 		if (ret)
602 			pr_warn("Creating sdma usage for gpu id %d failed",
603 				(int)pdd->dev->id);
604 	}
605 
606 	return ret;
607 }
608 
609 void kfd_procfs_del_queue(struct queue *q)
610 {
611 	if (!q)
612 		return;
613 
614 	kobject_del(&q->kobj);
615 	kobject_put(&q->kobj);
616 }
617 
618 int kfd_process_create_wq(void)
619 {
620 	if (!kfd_process_wq)
621 		kfd_process_wq = alloc_workqueue("kfd_process_wq", 0, 0);
622 	if (!kfd_restore_wq)
623 		kfd_restore_wq = alloc_ordered_workqueue("kfd_restore_wq", 0);
624 
625 	if (!kfd_process_wq || !kfd_restore_wq) {
626 		kfd_process_destroy_wq();
627 		return -ENOMEM;
628 	}
629 
630 	return 0;
631 }
632 
633 void kfd_process_destroy_wq(void)
634 {
635 	if (kfd_process_wq) {
636 		destroy_workqueue(kfd_process_wq);
637 		kfd_process_wq = NULL;
638 	}
639 	if (kfd_restore_wq) {
640 		destroy_workqueue(kfd_restore_wq);
641 		kfd_restore_wq = NULL;
642 	}
643 }
644 
645 static void kfd_process_free_gpuvm(struct kgd_mem *mem,
646 			struct kfd_process_device *pdd)
647 {
648 	struct kfd_dev *dev = pdd->dev;
649 
650 	amdgpu_amdkfd_gpuvm_unmap_memory_from_gpu(dev->kgd, mem, pdd->drm_priv);
651 	amdgpu_amdkfd_gpuvm_free_memory_of_gpu(dev->kgd, mem, pdd->drm_priv,
652 					       NULL);
653 }
654 
655 /* kfd_process_alloc_gpuvm - Allocate GPU VM for the KFD process
656  *	This function should be only called right after the process
657  *	is created and when kfd_processes_mutex is still being held
658  *	to avoid concurrency. Because of that exclusiveness, we do
659  *	not need to take p->mutex.
660  */
661 static int kfd_process_alloc_gpuvm(struct kfd_process_device *pdd,
662 				   uint64_t gpu_va, uint32_t size,
663 				   uint32_t flags, void **kptr)
664 {
665 	struct kfd_dev *kdev = pdd->dev;
666 	struct kgd_mem *mem = NULL;
667 	int handle;
668 	int err;
669 
670 	err = amdgpu_amdkfd_gpuvm_alloc_memory_of_gpu(kdev->kgd, gpu_va, size,
671 						 pdd->drm_priv, &mem, NULL, flags);
672 	if (err)
673 		goto err_alloc_mem;
674 
675 	err = amdgpu_amdkfd_gpuvm_map_memory_to_gpu(kdev->kgd, mem,
676 			pdd->drm_priv, NULL);
677 	if (err)
678 		goto err_map_mem;
679 
680 	err = amdgpu_amdkfd_gpuvm_sync_memory(kdev->kgd, mem, true);
681 	if (err) {
682 		pr_debug("Sync memory failed, wait interrupted by user signal\n");
683 		goto sync_memory_failed;
684 	}
685 
686 	/* Create an obj handle so kfd_process_device_remove_obj_handle
687 	 * will take care of the bo removal when the process finishes.
688 	 * We do not need to take p->mutex, because the process is just
689 	 * created and the ioctls have not had the chance to run.
690 	 */
691 	handle = kfd_process_device_create_obj_handle(pdd, mem);
692 
693 	if (handle < 0) {
694 		err = handle;
695 		goto free_gpuvm;
696 	}
697 
698 	if (kptr) {
699 		err = amdgpu_amdkfd_gpuvm_map_gtt_bo_to_kernel(kdev->kgd,
700 				(struct kgd_mem *)mem, kptr, NULL);
701 		if (err) {
702 			pr_debug("Map GTT BO to kernel failed\n");
703 			goto free_obj_handle;
704 		}
705 	}
706 
707 	return err;
708 
709 free_obj_handle:
710 	kfd_process_device_remove_obj_handle(pdd, handle);
711 free_gpuvm:
712 sync_memory_failed:
713 	kfd_process_free_gpuvm(mem, pdd);
714 	return err;
715 
716 err_map_mem:
717 	amdgpu_amdkfd_gpuvm_free_memory_of_gpu(kdev->kgd, mem, pdd->drm_priv,
718 					       NULL);
719 err_alloc_mem:
720 	*kptr = NULL;
721 	return err;
722 }
723 
724 /* kfd_process_device_reserve_ib_mem - Reserve memory inside the
725  *	process for IB usage The memory reserved is for KFD to submit
726  *	IB to AMDGPU from kernel.  If the memory is reserved
727  *	successfully, ib_kaddr will have the CPU/kernel
728  *	address. Check ib_kaddr before accessing the memory.
729  */
730 static int kfd_process_device_reserve_ib_mem(struct kfd_process_device *pdd)
731 {
732 	struct qcm_process_device *qpd = &pdd->qpd;
733 	uint32_t flags = KFD_IOC_ALLOC_MEM_FLAGS_GTT |
734 			KFD_IOC_ALLOC_MEM_FLAGS_NO_SUBSTITUTE |
735 			KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE |
736 			KFD_IOC_ALLOC_MEM_FLAGS_EXECUTABLE;
737 	void *kaddr;
738 	int ret;
739 
740 	if (qpd->ib_kaddr || !qpd->ib_base)
741 		return 0;
742 
743 	/* ib_base is only set for dGPU */
744 	ret = kfd_process_alloc_gpuvm(pdd, qpd->ib_base, PAGE_SIZE, flags,
745 				      &kaddr);
746 	if (ret)
747 		return ret;
748 
749 	qpd->ib_kaddr = kaddr;
750 
751 	return 0;
752 }
753 
754 struct kfd_process *kfd_create_process(struct file *filep)
755 {
756 	struct kfd_process *process;
757 	struct task_struct *thread = current;
758 	int ret;
759 
760 	if (!thread->mm)
761 		return ERR_PTR(-EINVAL);
762 
763 	/* Only the pthreads threading model is supported. */
764 	if (thread->group_leader->mm != thread->mm)
765 		return ERR_PTR(-EINVAL);
766 
767 	/*
768 	 * take kfd processes mutex before starting of process creation
769 	 * so there won't be a case where two threads of the same process
770 	 * create two kfd_process structures
771 	 */
772 	mutex_lock(&kfd_processes_mutex);
773 
774 	/* A prior open of /dev/kfd could have already created the process. */
775 	process = find_process(thread);
776 	if (process) {
777 		pr_debug("Process already found\n");
778 	} else {
779 		process = create_process(thread);
780 		if (IS_ERR(process))
781 			goto out;
782 
783 		ret = kfd_process_init_cwsr_apu(process, filep);
784 		if (ret)
785 			goto out_destroy;
786 
787 		if (!procfs.kobj)
788 			goto out;
789 
790 		process->kobj = kfd_alloc_struct(process->kobj);
791 		if (!process->kobj) {
792 			pr_warn("Creating procfs kobject failed");
793 			goto out;
794 		}
795 		ret = kobject_init_and_add(process->kobj, &procfs_type,
796 					   procfs.kobj, "%d",
797 					   (int)process->lead_thread->pid);
798 		if (ret) {
799 			pr_warn("Creating procfs pid directory failed");
800 			kobject_put(process->kobj);
801 			goto out;
802 		}
803 
804 		process->attr_pasid.name = "pasid";
805 		process->attr_pasid.mode = KFD_SYSFS_FILE_MODE;
806 		sysfs_attr_init(&process->attr_pasid);
807 		ret = sysfs_create_file(process->kobj, &process->attr_pasid);
808 		if (ret)
809 			pr_warn("Creating pasid for pid %d failed",
810 					(int)process->lead_thread->pid);
811 
812 		process->kobj_queues = kobject_create_and_add("queues",
813 							process->kobj);
814 		if (!process->kobj_queues)
815 			pr_warn("Creating KFD proc/queues folder failed");
816 
817 		ret = kfd_procfs_add_sysfs_stats(process);
818 		if (ret)
819 			pr_warn("Creating sysfs stats dir for pid %d failed",
820 				(int)process->lead_thread->pid);
821 
822 		ret = kfd_procfs_add_sysfs_files(process);
823 		if (ret)
824 			pr_warn("Creating sysfs usage file for pid %d failed",
825 				(int)process->lead_thread->pid);
826 	}
827 out:
828 	if (!IS_ERR(process))
829 		kref_get(&process->ref);
830 	mutex_unlock(&kfd_processes_mutex);
831 
832 	return process;
833 
834 out_destroy:
835 	hash_del_rcu(&process->kfd_processes);
836 	mutex_unlock(&kfd_processes_mutex);
837 	synchronize_srcu(&kfd_processes_srcu);
838 	/* kfd_process_free_notifier will trigger the cleanup */
839 	mmu_notifier_put(&process->mmu_notifier);
840 	return ERR_PTR(ret);
841 }
842 
843 struct kfd_process *kfd_get_process(const struct task_struct *thread)
844 {
845 	struct kfd_process *process;
846 
847 	if (!thread->mm)
848 		return ERR_PTR(-EINVAL);
849 
850 	/* Only the pthreads threading model is supported. */
851 	if (thread->group_leader->mm != thread->mm)
852 		return ERR_PTR(-EINVAL);
853 
854 	process = find_process(thread);
855 	if (!process)
856 		return ERR_PTR(-EINVAL);
857 
858 	return process;
859 }
860 
861 static struct kfd_process *find_process_by_mm(const struct mm_struct *mm)
862 {
863 	struct kfd_process *process;
864 
865 	hash_for_each_possible_rcu(kfd_processes_table, process,
866 					kfd_processes, (uintptr_t)mm)
867 		if (process->mm == mm)
868 			return process;
869 
870 	return NULL;
871 }
872 
873 static struct kfd_process *find_process(const struct task_struct *thread)
874 {
875 	struct kfd_process *p;
876 	int idx;
877 
878 	idx = srcu_read_lock(&kfd_processes_srcu);
879 	p = find_process_by_mm(thread->mm);
880 	srcu_read_unlock(&kfd_processes_srcu, idx);
881 
882 	return p;
883 }
884 
885 void kfd_unref_process(struct kfd_process *p)
886 {
887 	kref_put(&p->ref, kfd_process_ref_release);
888 }
889 
890 
891 static void kfd_process_device_free_bos(struct kfd_process_device *pdd)
892 {
893 	struct kfd_process *p = pdd->process;
894 	void *mem;
895 	int id;
896 	int i;
897 
898 	/*
899 	 * Remove all handles from idr and release appropriate
900 	 * local memory object
901 	 */
902 	idr_for_each_entry(&pdd->alloc_idr, mem, id) {
903 
904 		for (i = 0; i < p->n_pdds; i++) {
905 			struct kfd_process_device *peer_pdd = p->pdds[i];
906 
907 			if (!peer_pdd->drm_priv)
908 				continue;
909 			amdgpu_amdkfd_gpuvm_unmap_memory_from_gpu(
910 				peer_pdd->dev->kgd, mem, peer_pdd->drm_priv);
911 		}
912 
913 		amdgpu_amdkfd_gpuvm_free_memory_of_gpu(pdd->dev->kgd, mem,
914 						       pdd->drm_priv, NULL);
915 		kfd_process_device_remove_obj_handle(pdd, id);
916 	}
917 }
918 
919 static void kfd_process_free_outstanding_kfd_bos(struct kfd_process *p)
920 {
921 	int i;
922 
923 	for (i = 0; i < p->n_pdds; i++)
924 		kfd_process_device_free_bos(p->pdds[i]);
925 }
926 
927 static void kfd_process_destroy_pdds(struct kfd_process *p)
928 {
929 	int i;
930 
931 	for (i = 0; i < p->n_pdds; i++) {
932 		struct kfd_process_device *pdd = p->pdds[i];
933 
934 		pr_debug("Releasing pdd (topology id %d) for process (pasid 0x%x)\n",
935 				pdd->dev->id, p->pasid);
936 
937 		if (pdd->drm_file) {
938 			amdgpu_amdkfd_gpuvm_release_process_vm(
939 					pdd->dev->kgd, pdd->drm_priv);
940 			fput(pdd->drm_file);
941 		}
942 
943 		if (pdd->qpd.cwsr_kaddr && !pdd->qpd.cwsr_base)
944 			free_pages((unsigned long)pdd->qpd.cwsr_kaddr,
945 				get_order(KFD_CWSR_TBA_TMA_SIZE));
946 
947 		kfree(pdd->qpd.doorbell_bitmap);
948 		idr_destroy(&pdd->alloc_idr);
949 
950 		kfd_free_process_doorbells(pdd->dev, pdd->doorbell_index);
951 
952 		/*
953 		 * before destroying pdd, make sure to report availability
954 		 * for auto suspend
955 		 */
956 		if (pdd->runtime_inuse) {
957 			pm_runtime_mark_last_busy(pdd->dev->ddev->dev);
958 			pm_runtime_put_autosuspend(pdd->dev->ddev->dev);
959 			pdd->runtime_inuse = false;
960 		}
961 
962 		kfree(pdd);
963 		p->pdds[i] = NULL;
964 	}
965 	p->n_pdds = 0;
966 }
967 
968 /* No process locking is needed in this function, because the process
969  * is not findable any more. We must assume that no other thread is
970  * using it any more, otherwise we couldn't safely free the process
971  * structure in the end.
972  */
973 static void kfd_process_wq_release(struct work_struct *work)
974 {
975 	struct kfd_process *p = container_of(work, struct kfd_process,
976 					     release_work);
977 	int i;
978 
979 	/* Remove the procfs files */
980 	if (p->kobj) {
981 		sysfs_remove_file(p->kobj, &p->attr_pasid);
982 		kobject_del(p->kobj_queues);
983 		kobject_put(p->kobj_queues);
984 		p->kobj_queues = NULL;
985 
986 		for (i = 0; i < p->n_pdds; i++) {
987 			struct kfd_process_device *pdd = p->pdds[i];
988 
989 			sysfs_remove_file(p->kobj, &pdd->attr_vram);
990 			sysfs_remove_file(p->kobj, &pdd->attr_sdma);
991 			sysfs_remove_file(p->kobj, &pdd->attr_evict);
992 			if (pdd->dev->kfd2kgd->get_cu_occupancy != NULL)
993 				sysfs_remove_file(p->kobj, &pdd->attr_cu_occupancy);
994 			kobject_del(pdd->kobj_stats);
995 			kobject_put(pdd->kobj_stats);
996 			pdd->kobj_stats = NULL;
997 		}
998 
999 		kobject_del(p->kobj);
1000 		kobject_put(p->kobj);
1001 		p->kobj = NULL;
1002 	}
1003 
1004 	kfd_iommu_unbind_process(p);
1005 
1006 	kfd_process_free_outstanding_kfd_bos(p);
1007 	svm_range_list_fini(p);
1008 
1009 	kfd_process_destroy_pdds(p);
1010 	dma_fence_put(p->ef);
1011 
1012 	kfd_event_free_process(p);
1013 
1014 	kfd_pasid_free(p->pasid);
1015 	mutex_destroy(&p->mutex);
1016 
1017 	put_task_struct(p->lead_thread);
1018 
1019 	kfree(p);
1020 }
1021 
1022 static void kfd_process_ref_release(struct kref *ref)
1023 {
1024 	struct kfd_process *p = container_of(ref, struct kfd_process, ref);
1025 
1026 	INIT_WORK(&p->release_work, kfd_process_wq_release);
1027 	queue_work(kfd_process_wq, &p->release_work);
1028 }
1029 
1030 static struct mmu_notifier *kfd_process_alloc_notifier(struct mm_struct *mm)
1031 {
1032 	int idx = srcu_read_lock(&kfd_processes_srcu);
1033 	struct kfd_process *p = find_process_by_mm(mm);
1034 
1035 	srcu_read_unlock(&kfd_processes_srcu, idx);
1036 
1037 	return p ? &p->mmu_notifier : ERR_PTR(-ESRCH);
1038 }
1039 
1040 static void kfd_process_free_notifier(struct mmu_notifier *mn)
1041 {
1042 	kfd_unref_process(container_of(mn, struct kfd_process, mmu_notifier));
1043 }
1044 
1045 static void kfd_process_notifier_release(struct mmu_notifier *mn,
1046 					struct mm_struct *mm)
1047 {
1048 	struct kfd_process *p;
1049 	int i;
1050 
1051 	/*
1052 	 * The kfd_process structure can not be free because the
1053 	 * mmu_notifier srcu is read locked
1054 	 */
1055 	p = container_of(mn, struct kfd_process, mmu_notifier);
1056 	if (WARN_ON(p->mm != mm))
1057 		return;
1058 
1059 	mutex_lock(&kfd_processes_mutex);
1060 	hash_del_rcu(&p->kfd_processes);
1061 	mutex_unlock(&kfd_processes_mutex);
1062 	synchronize_srcu(&kfd_processes_srcu);
1063 
1064 	cancel_delayed_work_sync(&p->eviction_work);
1065 	cancel_delayed_work_sync(&p->restore_work);
1066 	cancel_delayed_work_sync(&p->svms.restore_work);
1067 
1068 	mutex_lock(&p->mutex);
1069 
1070 	/* Iterate over all process device data structures and if the
1071 	 * pdd is in debug mode, we should first force unregistration,
1072 	 * then we will be able to destroy the queues
1073 	 */
1074 	for (i = 0; i < p->n_pdds; i++) {
1075 		struct kfd_dev *dev = p->pdds[i]->dev;
1076 
1077 		mutex_lock(kfd_get_dbgmgr_mutex());
1078 		if (dev && dev->dbgmgr && dev->dbgmgr->pasid == p->pasid) {
1079 			if (!kfd_dbgmgr_unregister(dev->dbgmgr, p)) {
1080 				kfd_dbgmgr_destroy(dev->dbgmgr);
1081 				dev->dbgmgr = NULL;
1082 			}
1083 		}
1084 		mutex_unlock(kfd_get_dbgmgr_mutex());
1085 	}
1086 
1087 	kfd_process_dequeue_from_all_devices(p);
1088 	pqm_uninit(&p->pqm);
1089 
1090 	/* Indicate to other users that MM is no longer valid */
1091 	p->mm = NULL;
1092 	/* Signal the eviction fence after user mode queues are
1093 	 * destroyed. This allows any BOs to be freed without
1094 	 * triggering pointless evictions or waiting for fences.
1095 	 */
1096 	dma_fence_signal(p->ef);
1097 
1098 	mutex_unlock(&p->mutex);
1099 
1100 	mmu_notifier_put(&p->mmu_notifier);
1101 }
1102 
1103 static const struct mmu_notifier_ops kfd_process_mmu_notifier_ops = {
1104 	.release = kfd_process_notifier_release,
1105 	.alloc_notifier = kfd_process_alloc_notifier,
1106 	.free_notifier = kfd_process_free_notifier,
1107 };
1108 
1109 static int kfd_process_init_cwsr_apu(struct kfd_process *p, struct file *filep)
1110 {
1111 	unsigned long  offset;
1112 	int i;
1113 
1114 	for (i = 0; i < p->n_pdds; i++) {
1115 		struct kfd_dev *dev = p->pdds[i]->dev;
1116 		struct qcm_process_device *qpd = &p->pdds[i]->qpd;
1117 
1118 		if (!dev->cwsr_enabled || qpd->cwsr_kaddr || qpd->cwsr_base)
1119 			continue;
1120 
1121 		offset = KFD_MMAP_TYPE_RESERVED_MEM | KFD_MMAP_GPU_ID(dev->id);
1122 		qpd->tba_addr = (int64_t)vm_mmap(filep, 0,
1123 			KFD_CWSR_TBA_TMA_SIZE, PROT_READ | PROT_EXEC,
1124 			MAP_SHARED, offset);
1125 
1126 		if (IS_ERR_VALUE(qpd->tba_addr)) {
1127 			int err = qpd->tba_addr;
1128 
1129 			pr_err("Failure to set tba address. error %d.\n", err);
1130 			qpd->tba_addr = 0;
1131 			qpd->cwsr_kaddr = NULL;
1132 			return err;
1133 		}
1134 
1135 		memcpy(qpd->cwsr_kaddr, dev->cwsr_isa, dev->cwsr_isa_size);
1136 
1137 		qpd->tma_addr = qpd->tba_addr + KFD_CWSR_TMA_OFFSET;
1138 		pr_debug("set tba :0x%llx, tma:0x%llx, cwsr_kaddr:%p for pqm.\n",
1139 			qpd->tba_addr, qpd->tma_addr, qpd->cwsr_kaddr);
1140 	}
1141 
1142 	return 0;
1143 }
1144 
1145 static int kfd_process_device_init_cwsr_dgpu(struct kfd_process_device *pdd)
1146 {
1147 	struct kfd_dev *dev = pdd->dev;
1148 	struct qcm_process_device *qpd = &pdd->qpd;
1149 	uint32_t flags = KFD_IOC_ALLOC_MEM_FLAGS_GTT
1150 			| KFD_IOC_ALLOC_MEM_FLAGS_NO_SUBSTITUTE
1151 			| KFD_IOC_ALLOC_MEM_FLAGS_EXECUTABLE;
1152 	void *kaddr;
1153 	int ret;
1154 
1155 	if (!dev->cwsr_enabled || qpd->cwsr_kaddr || !qpd->cwsr_base)
1156 		return 0;
1157 
1158 	/* cwsr_base is only set for dGPU */
1159 	ret = kfd_process_alloc_gpuvm(pdd, qpd->cwsr_base,
1160 				      KFD_CWSR_TBA_TMA_SIZE, flags, &kaddr);
1161 	if (ret)
1162 		return ret;
1163 
1164 	qpd->cwsr_kaddr = kaddr;
1165 	qpd->tba_addr = qpd->cwsr_base;
1166 
1167 	memcpy(qpd->cwsr_kaddr, dev->cwsr_isa, dev->cwsr_isa_size);
1168 
1169 	qpd->tma_addr = qpd->tba_addr + KFD_CWSR_TMA_OFFSET;
1170 	pr_debug("set tba :0x%llx, tma:0x%llx, cwsr_kaddr:%p for pqm.\n",
1171 		 qpd->tba_addr, qpd->tma_addr, qpd->cwsr_kaddr);
1172 
1173 	return 0;
1174 }
1175 
1176 void kfd_process_set_trap_handler(struct qcm_process_device *qpd,
1177 				  uint64_t tba_addr,
1178 				  uint64_t tma_addr)
1179 {
1180 	if (qpd->cwsr_kaddr) {
1181 		/* KFD trap handler is bound, record as second-level TBA/TMA
1182 		 * in first-level TMA. First-level trap will jump to second.
1183 		 */
1184 		uint64_t *tma =
1185 			(uint64_t *)(qpd->cwsr_kaddr + KFD_CWSR_TMA_OFFSET);
1186 		tma[0] = tba_addr;
1187 		tma[1] = tma_addr;
1188 	} else {
1189 		/* No trap handler bound, bind as first-level TBA/TMA. */
1190 		qpd->tba_addr = tba_addr;
1191 		qpd->tma_addr = tma_addr;
1192 	}
1193 }
1194 
1195 bool kfd_process_xnack_mode(struct kfd_process *p, bool supported)
1196 {
1197 	int i;
1198 
1199 	/* On most GFXv9 GPUs, the retry mode in the SQ must match the
1200 	 * boot time retry setting. Mixing processes with different
1201 	 * XNACK/retry settings can hang the GPU.
1202 	 *
1203 	 * Different GPUs can have different noretry settings depending
1204 	 * on HW bugs or limitations. We need to find at least one
1205 	 * XNACK mode for this process that's compatible with all GPUs.
1206 	 * Fortunately GPUs with retry enabled (noretry=0) can run code
1207 	 * built for XNACK-off. On GFXv9 it may perform slower.
1208 	 *
1209 	 * Therefore applications built for XNACK-off can always be
1210 	 * supported and will be our fallback if any GPU does not
1211 	 * support retry.
1212 	 */
1213 	for (i = 0; i < p->n_pdds; i++) {
1214 		struct kfd_dev *dev = p->pdds[i]->dev;
1215 
1216 		/* Only consider GFXv9 and higher GPUs. Older GPUs don't
1217 		 * support the SVM APIs and don't need to be considered
1218 		 * for the XNACK mode selection.
1219 		 */
1220 		if (dev->device_info->asic_family < CHIP_VEGA10)
1221 			continue;
1222 		/* Aldebaran can always support XNACK because it can support
1223 		 * per-process XNACK mode selection. But let the dev->noretry
1224 		 * setting still influence the default XNACK mode.
1225 		 */
1226 		if (supported &&
1227 		    dev->device_info->asic_family == CHIP_ALDEBARAN)
1228 			continue;
1229 
1230 		/* GFXv10 and later GPUs do not support shader preemption
1231 		 * during page faults. This can lead to poor QoS for queue
1232 		 * management and memory-manager-related preemptions or
1233 		 * even deadlocks.
1234 		 */
1235 		if (dev->device_info->asic_family >= CHIP_NAVI10)
1236 			return false;
1237 
1238 		if (dev->noretry)
1239 			return false;
1240 	}
1241 
1242 	return true;
1243 }
1244 
1245 /*
1246  * On return the kfd_process is fully operational and will be freed when the
1247  * mm is released
1248  */
1249 static struct kfd_process *create_process(const struct task_struct *thread)
1250 {
1251 	struct kfd_process *process;
1252 	struct mmu_notifier *mn;
1253 	int err = -ENOMEM;
1254 
1255 	process = kzalloc(sizeof(*process), GFP_KERNEL);
1256 	if (!process)
1257 		goto err_alloc_process;
1258 
1259 	kref_init(&process->ref);
1260 	mutex_init(&process->mutex);
1261 	process->mm = thread->mm;
1262 	process->lead_thread = thread->group_leader;
1263 	process->n_pdds = 0;
1264 	process->svm_disabled = false;
1265 	INIT_DELAYED_WORK(&process->eviction_work, evict_process_worker);
1266 	INIT_DELAYED_WORK(&process->restore_work, restore_process_worker);
1267 	process->last_restore_timestamp = get_jiffies_64();
1268 	kfd_event_init_process(process);
1269 	process->is_32bit_user_mode = in_compat_syscall();
1270 
1271 	process->pasid = kfd_pasid_alloc();
1272 	if (process->pasid == 0)
1273 		goto err_alloc_pasid;
1274 
1275 	err = pqm_init(&process->pqm, process);
1276 	if (err != 0)
1277 		goto err_process_pqm_init;
1278 
1279 	/* init process apertures*/
1280 	err = kfd_init_apertures(process);
1281 	if (err != 0)
1282 		goto err_init_apertures;
1283 
1284 	/* Check XNACK support after PDDs are created in kfd_init_apertures */
1285 	process->xnack_enabled = kfd_process_xnack_mode(process, false);
1286 
1287 	err = svm_range_list_init(process);
1288 	if (err)
1289 		goto err_init_svm_range_list;
1290 
1291 	/* alloc_notifier needs to find the process in the hash table */
1292 	hash_add_rcu(kfd_processes_table, &process->kfd_processes,
1293 			(uintptr_t)process->mm);
1294 
1295 	/* MMU notifier registration must be the last call that can fail
1296 	 * because after this point we cannot unwind the process creation.
1297 	 * After this point, mmu_notifier_put will trigger the cleanup by
1298 	 * dropping the last process reference in the free_notifier.
1299 	 */
1300 	mn = mmu_notifier_get(&kfd_process_mmu_notifier_ops, process->mm);
1301 	if (IS_ERR(mn)) {
1302 		err = PTR_ERR(mn);
1303 		goto err_register_notifier;
1304 	}
1305 	BUG_ON(mn != &process->mmu_notifier);
1306 
1307 	get_task_struct(process->lead_thread);
1308 
1309 	return process;
1310 
1311 err_register_notifier:
1312 	hash_del_rcu(&process->kfd_processes);
1313 	svm_range_list_fini(process);
1314 err_init_svm_range_list:
1315 	kfd_process_free_outstanding_kfd_bos(process);
1316 	kfd_process_destroy_pdds(process);
1317 err_init_apertures:
1318 	pqm_uninit(&process->pqm);
1319 err_process_pqm_init:
1320 	kfd_pasid_free(process->pasid);
1321 err_alloc_pasid:
1322 	mutex_destroy(&process->mutex);
1323 	kfree(process);
1324 err_alloc_process:
1325 	return ERR_PTR(err);
1326 }
1327 
1328 static int init_doorbell_bitmap(struct qcm_process_device *qpd,
1329 			struct kfd_dev *dev)
1330 {
1331 	unsigned int i;
1332 	int range_start = dev->shared_resources.non_cp_doorbells_start;
1333 	int range_end = dev->shared_resources.non_cp_doorbells_end;
1334 
1335 	if (!KFD_IS_SOC15(dev->device_info->asic_family))
1336 		return 0;
1337 
1338 	qpd->doorbell_bitmap =
1339 		kzalloc(DIV_ROUND_UP(KFD_MAX_NUM_OF_QUEUES_PER_PROCESS,
1340 				     BITS_PER_BYTE), GFP_KERNEL);
1341 	if (!qpd->doorbell_bitmap)
1342 		return -ENOMEM;
1343 
1344 	/* Mask out doorbells reserved for SDMA, IH, and VCN on SOC15. */
1345 	pr_debug("reserved doorbell 0x%03x - 0x%03x\n", range_start, range_end);
1346 	pr_debug("reserved doorbell 0x%03x - 0x%03x\n",
1347 			range_start + KFD_QUEUE_DOORBELL_MIRROR_OFFSET,
1348 			range_end + KFD_QUEUE_DOORBELL_MIRROR_OFFSET);
1349 
1350 	for (i = 0; i < KFD_MAX_NUM_OF_QUEUES_PER_PROCESS / 2; i++) {
1351 		if (i >= range_start && i <= range_end) {
1352 			set_bit(i, qpd->doorbell_bitmap);
1353 			set_bit(i + KFD_QUEUE_DOORBELL_MIRROR_OFFSET,
1354 				qpd->doorbell_bitmap);
1355 		}
1356 	}
1357 
1358 	return 0;
1359 }
1360 
1361 struct kfd_process_device *kfd_get_process_device_data(struct kfd_dev *dev,
1362 							struct kfd_process *p)
1363 {
1364 	int i;
1365 
1366 	for (i = 0; i < p->n_pdds; i++)
1367 		if (p->pdds[i]->dev == dev)
1368 			return p->pdds[i];
1369 
1370 	return NULL;
1371 }
1372 
1373 struct kfd_process_device *kfd_create_process_device_data(struct kfd_dev *dev,
1374 							struct kfd_process *p)
1375 {
1376 	struct kfd_process_device *pdd = NULL;
1377 
1378 	if (WARN_ON_ONCE(p->n_pdds >= MAX_GPU_INSTANCE))
1379 		return NULL;
1380 	pdd = kzalloc(sizeof(*pdd), GFP_KERNEL);
1381 	if (!pdd)
1382 		return NULL;
1383 
1384 	if (kfd_alloc_process_doorbells(dev, &pdd->doorbell_index) < 0) {
1385 		pr_err("Failed to alloc doorbell for pdd\n");
1386 		goto err_free_pdd;
1387 	}
1388 
1389 	if (init_doorbell_bitmap(&pdd->qpd, dev)) {
1390 		pr_err("Failed to init doorbell for process\n");
1391 		goto err_free_pdd;
1392 	}
1393 
1394 	pdd->dev = dev;
1395 	INIT_LIST_HEAD(&pdd->qpd.queues_list);
1396 	INIT_LIST_HEAD(&pdd->qpd.priv_queue_list);
1397 	pdd->qpd.dqm = dev->dqm;
1398 	pdd->qpd.pqm = &p->pqm;
1399 	pdd->qpd.evicted = 0;
1400 	pdd->qpd.mapped_gws_queue = false;
1401 	pdd->process = p;
1402 	pdd->bound = PDD_UNBOUND;
1403 	pdd->already_dequeued = false;
1404 	pdd->runtime_inuse = false;
1405 	pdd->vram_usage = 0;
1406 	pdd->sdma_past_activity_counter = 0;
1407 	atomic64_set(&pdd->evict_duration_counter, 0);
1408 	p->pdds[p->n_pdds++] = pdd;
1409 
1410 	/* Init idr used for memory handle translation */
1411 	idr_init(&pdd->alloc_idr);
1412 
1413 	return pdd;
1414 
1415 err_free_pdd:
1416 	kfree(pdd);
1417 	return NULL;
1418 }
1419 
1420 /**
1421  * kfd_process_device_init_vm - Initialize a VM for a process-device
1422  *
1423  * @pdd: The process-device
1424  * @drm_file: Optional pointer to a DRM file descriptor
1425  *
1426  * If @drm_file is specified, it will be used to acquire the VM from
1427  * that file descriptor. If successful, the @pdd takes ownership of
1428  * the file descriptor.
1429  *
1430  * If @drm_file is NULL, a new VM is created.
1431  *
1432  * Returns 0 on success, -errno on failure.
1433  */
1434 int kfd_process_device_init_vm(struct kfd_process_device *pdd,
1435 			       struct file *drm_file)
1436 {
1437 	struct kfd_process *p;
1438 	struct kfd_dev *dev;
1439 	int ret;
1440 
1441 	if (!drm_file)
1442 		return -EINVAL;
1443 
1444 	if (pdd->drm_priv)
1445 		return -EBUSY;
1446 
1447 	p = pdd->process;
1448 	dev = pdd->dev;
1449 
1450 	ret = amdgpu_amdkfd_gpuvm_acquire_process_vm(
1451 		dev->kgd, drm_file, p->pasid,
1452 		&p->kgd_process_info, &p->ef);
1453 	if (ret) {
1454 		pr_err("Failed to create process VM object\n");
1455 		return ret;
1456 	}
1457 	pdd->drm_priv = drm_file->private_data;
1458 
1459 	ret = kfd_process_device_reserve_ib_mem(pdd);
1460 	if (ret)
1461 		goto err_reserve_ib_mem;
1462 	ret = kfd_process_device_init_cwsr_dgpu(pdd);
1463 	if (ret)
1464 		goto err_init_cwsr;
1465 
1466 	pdd->drm_file = drm_file;
1467 
1468 	return 0;
1469 
1470 err_init_cwsr:
1471 err_reserve_ib_mem:
1472 	kfd_process_device_free_bos(pdd);
1473 	pdd->drm_priv = NULL;
1474 
1475 	return ret;
1476 }
1477 
1478 /*
1479  * Direct the IOMMU to bind the process (specifically the pasid->mm)
1480  * to the device.
1481  * Unbinding occurs when the process dies or the device is removed.
1482  *
1483  * Assumes that the process lock is held.
1484  */
1485 struct kfd_process_device *kfd_bind_process_to_device(struct kfd_dev *dev,
1486 							struct kfd_process *p)
1487 {
1488 	struct kfd_process_device *pdd;
1489 	int err;
1490 
1491 	pdd = kfd_get_process_device_data(dev, p);
1492 	if (!pdd) {
1493 		pr_err("Process device data doesn't exist\n");
1494 		return ERR_PTR(-ENOMEM);
1495 	}
1496 
1497 	if (!pdd->drm_priv)
1498 		return ERR_PTR(-ENODEV);
1499 
1500 	/*
1501 	 * signal runtime-pm system to auto resume and prevent
1502 	 * further runtime suspend once device pdd is created until
1503 	 * pdd is destroyed.
1504 	 */
1505 	if (!pdd->runtime_inuse) {
1506 		err = pm_runtime_get_sync(dev->ddev->dev);
1507 		if (err < 0) {
1508 			pm_runtime_put_autosuspend(dev->ddev->dev);
1509 			return ERR_PTR(err);
1510 		}
1511 	}
1512 
1513 	err = kfd_iommu_bind_process_to_device(pdd);
1514 	if (err)
1515 		goto out;
1516 
1517 	/*
1518 	 * make sure that runtime_usage counter is incremented just once
1519 	 * per pdd
1520 	 */
1521 	pdd->runtime_inuse = true;
1522 
1523 	return pdd;
1524 
1525 out:
1526 	/* balance runpm reference count and exit with error */
1527 	if (!pdd->runtime_inuse) {
1528 		pm_runtime_mark_last_busy(dev->ddev->dev);
1529 		pm_runtime_put_autosuspend(dev->ddev->dev);
1530 	}
1531 
1532 	return ERR_PTR(err);
1533 }
1534 
1535 /* Create specific handle mapped to mem from process local memory idr
1536  * Assumes that the process lock is held.
1537  */
1538 int kfd_process_device_create_obj_handle(struct kfd_process_device *pdd,
1539 					void *mem)
1540 {
1541 	return idr_alloc(&pdd->alloc_idr, mem, 0, 0, GFP_KERNEL);
1542 }
1543 
1544 /* Translate specific handle from process local memory idr
1545  * Assumes that the process lock is held.
1546  */
1547 void *kfd_process_device_translate_handle(struct kfd_process_device *pdd,
1548 					int handle)
1549 {
1550 	if (handle < 0)
1551 		return NULL;
1552 
1553 	return idr_find(&pdd->alloc_idr, handle);
1554 }
1555 
1556 /* Remove specific handle from process local memory idr
1557  * Assumes that the process lock is held.
1558  */
1559 void kfd_process_device_remove_obj_handle(struct kfd_process_device *pdd,
1560 					int handle)
1561 {
1562 	if (handle >= 0)
1563 		idr_remove(&pdd->alloc_idr, handle);
1564 }
1565 
1566 /* This increments the process->ref counter. */
1567 struct kfd_process *kfd_lookup_process_by_pasid(u32 pasid)
1568 {
1569 	struct kfd_process *p, *ret_p = NULL;
1570 	unsigned int temp;
1571 
1572 	int idx = srcu_read_lock(&kfd_processes_srcu);
1573 
1574 	hash_for_each_rcu(kfd_processes_table, temp, p, kfd_processes) {
1575 		if (p->pasid == pasid) {
1576 			kref_get(&p->ref);
1577 			ret_p = p;
1578 			break;
1579 		}
1580 	}
1581 
1582 	srcu_read_unlock(&kfd_processes_srcu, idx);
1583 
1584 	return ret_p;
1585 }
1586 
1587 /* This increments the process->ref counter. */
1588 struct kfd_process *kfd_lookup_process_by_mm(const struct mm_struct *mm)
1589 {
1590 	struct kfd_process *p;
1591 
1592 	int idx = srcu_read_lock(&kfd_processes_srcu);
1593 
1594 	p = find_process_by_mm(mm);
1595 	if (p)
1596 		kref_get(&p->ref);
1597 
1598 	srcu_read_unlock(&kfd_processes_srcu, idx);
1599 
1600 	return p;
1601 }
1602 
1603 /* kfd_process_evict_queues - Evict all user queues of a process
1604  *
1605  * Eviction is reference-counted per process-device. This means multiple
1606  * evictions from different sources can be nested safely.
1607  */
1608 int kfd_process_evict_queues(struct kfd_process *p)
1609 {
1610 	int r = 0;
1611 	int i;
1612 	unsigned int n_evicted = 0;
1613 
1614 	for (i = 0; i < p->n_pdds; i++) {
1615 		struct kfd_process_device *pdd = p->pdds[i];
1616 
1617 		r = pdd->dev->dqm->ops.evict_process_queues(pdd->dev->dqm,
1618 							    &pdd->qpd);
1619 		if (r) {
1620 			pr_err("Failed to evict process queues\n");
1621 			goto fail;
1622 		}
1623 		n_evicted++;
1624 	}
1625 
1626 	return r;
1627 
1628 fail:
1629 	/* To keep state consistent, roll back partial eviction by
1630 	 * restoring queues
1631 	 */
1632 	for (i = 0; i < p->n_pdds; i++) {
1633 		struct kfd_process_device *pdd = p->pdds[i];
1634 
1635 		if (n_evicted == 0)
1636 			break;
1637 		if (pdd->dev->dqm->ops.restore_process_queues(pdd->dev->dqm,
1638 							      &pdd->qpd))
1639 			pr_err("Failed to restore queues\n");
1640 
1641 		n_evicted--;
1642 	}
1643 
1644 	return r;
1645 }
1646 
1647 /* kfd_process_restore_queues - Restore all user queues of a process */
1648 int kfd_process_restore_queues(struct kfd_process *p)
1649 {
1650 	int r, ret = 0;
1651 	int i;
1652 
1653 	for (i = 0; i < p->n_pdds; i++) {
1654 		struct kfd_process_device *pdd = p->pdds[i];
1655 
1656 		r = pdd->dev->dqm->ops.restore_process_queues(pdd->dev->dqm,
1657 							      &pdd->qpd);
1658 		if (r) {
1659 			pr_err("Failed to restore process queues\n");
1660 			if (!ret)
1661 				ret = r;
1662 		}
1663 	}
1664 
1665 	return ret;
1666 }
1667 
1668 int kfd_process_gpuidx_from_gpuid(struct kfd_process *p, uint32_t gpu_id)
1669 {
1670 	int i;
1671 
1672 	for (i = 0; i < p->n_pdds; i++)
1673 		if (p->pdds[i] && gpu_id == p->pdds[i]->dev->id)
1674 			return i;
1675 	return -EINVAL;
1676 }
1677 
1678 int
1679 kfd_process_gpuid_from_kgd(struct kfd_process *p, struct amdgpu_device *adev,
1680 			   uint32_t *gpuid, uint32_t *gpuidx)
1681 {
1682 	struct kgd_dev *kgd = (struct kgd_dev *)adev;
1683 	int i;
1684 
1685 	for (i = 0; i < p->n_pdds; i++)
1686 		if (p->pdds[i] && p->pdds[i]->dev->kgd == kgd) {
1687 			*gpuid = p->pdds[i]->dev->id;
1688 			*gpuidx = i;
1689 			return 0;
1690 		}
1691 	return -EINVAL;
1692 }
1693 
1694 static void evict_process_worker(struct work_struct *work)
1695 {
1696 	int ret;
1697 	struct kfd_process *p;
1698 	struct delayed_work *dwork;
1699 
1700 	dwork = to_delayed_work(work);
1701 
1702 	/* Process termination destroys this worker thread. So during the
1703 	 * lifetime of this thread, kfd_process p will be valid
1704 	 */
1705 	p = container_of(dwork, struct kfd_process, eviction_work);
1706 	WARN_ONCE(p->last_eviction_seqno != p->ef->seqno,
1707 		  "Eviction fence mismatch\n");
1708 
1709 	/* Narrow window of overlap between restore and evict work
1710 	 * item is possible. Once amdgpu_amdkfd_gpuvm_restore_process_bos
1711 	 * unreserves KFD BOs, it is possible to evicted again. But
1712 	 * restore has few more steps of finish. So lets wait for any
1713 	 * previous restore work to complete
1714 	 */
1715 	flush_delayed_work(&p->restore_work);
1716 
1717 	pr_debug("Started evicting pasid 0x%x\n", p->pasid);
1718 	ret = kfd_process_evict_queues(p);
1719 	if (!ret) {
1720 		dma_fence_signal(p->ef);
1721 		dma_fence_put(p->ef);
1722 		p->ef = NULL;
1723 		queue_delayed_work(kfd_restore_wq, &p->restore_work,
1724 				msecs_to_jiffies(PROCESS_RESTORE_TIME_MS));
1725 
1726 		pr_debug("Finished evicting pasid 0x%x\n", p->pasid);
1727 	} else
1728 		pr_err("Failed to evict queues of pasid 0x%x\n", p->pasid);
1729 }
1730 
1731 static void restore_process_worker(struct work_struct *work)
1732 {
1733 	struct delayed_work *dwork;
1734 	struct kfd_process *p;
1735 	int ret = 0;
1736 
1737 	dwork = to_delayed_work(work);
1738 
1739 	/* Process termination destroys this worker thread. So during the
1740 	 * lifetime of this thread, kfd_process p will be valid
1741 	 */
1742 	p = container_of(dwork, struct kfd_process, restore_work);
1743 	pr_debug("Started restoring pasid 0x%x\n", p->pasid);
1744 
1745 	/* Setting last_restore_timestamp before successful restoration.
1746 	 * Otherwise this would have to be set by KGD (restore_process_bos)
1747 	 * before KFD BOs are unreserved. If not, the process can be evicted
1748 	 * again before the timestamp is set.
1749 	 * If restore fails, the timestamp will be set again in the next
1750 	 * attempt. This would mean that the minimum GPU quanta would be
1751 	 * PROCESS_ACTIVE_TIME_MS - (time to execute the following two
1752 	 * functions)
1753 	 */
1754 
1755 	p->last_restore_timestamp = get_jiffies_64();
1756 	ret = amdgpu_amdkfd_gpuvm_restore_process_bos(p->kgd_process_info,
1757 						     &p->ef);
1758 	if (ret) {
1759 		pr_debug("Failed to restore BOs of pasid 0x%x, retry after %d ms\n",
1760 			 p->pasid, PROCESS_BACK_OFF_TIME_MS);
1761 		ret = queue_delayed_work(kfd_restore_wq, &p->restore_work,
1762 				msecs_to_jiffies(PROCESS_BACK_OFF_TIME_MS));
1763 		WARN(!ret, "reschedule restore work failed\n");
1764 		return;
1765 	}
1766 
1767 	ret = kfd_process_restore_queues(p);
1768 	if (!ret)
1769 		pr_debug("Finished restoring pasid 0x%x\n", p->pasid);
1770 	else
1771 		pr_err("Failed to restore queues of pasid 0x%x\n", p->pasid);
1772 }
1773 
1774 void kfd_suspend_all_processes(void)
1775 {
1776 	struct kfd_process *p;
1777 	unsigned int temp;
1778 	int idx = srcu_read_lock(&kfd_processes_srcu);
1779 
1780 	WARN(debug_evictions, "Evicting all processes");
1781 	hash_for_each_rcu(kfd_processes_table, temp, p, kfd_processes) {
1782 		cancel_delayed_work_sync(&p->eviction_work);
1783 		cancel_delayed_work_sync(&p->restore_work);
1784 
1785 		if (kfd_process_evict_queues(p))
1786 			pr_err("Failed to suspend process 0x%x\n", p->pasid);
1787 		dma_fence_signal(p->ef);
1788 		dma_fence_put(p->ef);
1789 		p->ef = NULL;
1790 	}
1791 	srcu_read_unlock(&kfd_processes_srcu, idx);
1792 }
1793 
1794 int kfd_resume_all_processes(void)
1795 {
1796 	struct kfd_process *p;
1797 	unsigned int temp;
1798 	int ret = 0, idx = srcu_read_lock(&kfd_processes_srcu);
1799 
1800 	hash_for_each_rcu(kfd_processes_table, temp, p, kfd_processes) {
1801 		if (!queue_delayed_work(kfd_restore_wq, &p->restore_work, 0)) {
1802 			pr_err("Restore process %d failed during resume\n",
1803 			       p->pasid);
1804 			ret = -EFAULT;
1805 		}
1806 	}
1807 	srcu_read_unlock(&kfd_processes_srcu, idx);
1808 	return ret;
1809 }
1810 
1811 int kfd_reserved_mem_mmap(struct kfd_dev *dev, struct kfd_process *process,
1812 			  struct vm_area_struct *vma)
1813 {
1814 	struct kfd_process_device *pdd;
1815 	struct qcm_process_device *qpd;
1816 
1817 	if ((vma->vm_end - vma->vm_start) != KFD_CWSR_TBA_TMA_SIZE) {
1818 		pr_err("Incorrect CWSR mapping size.\n");
1819 		return -EINVAL;
1820 	}
1821 
1822 	pdd = kfd_get_process_device_data(dev, process);
1823 	if (!pdd)
1824 		return -EINVAL;
1825 	qpd = &pdd->qpd;
1826 
1827 	qpd->cwsr_kaddr = (void *)__get_free_pages(GFP_KERNEL | __GFP_ZERO,
1828 					get_order(KFD_CWSR_TBA_TMA_SIZE));
1829 	if (!qpd->cwsr_kaddr) {
1830 		pr_err("Error allocating per process CWSR buffer.\n");
1831 		return -ENOMEM;
1832 	}
1833 
1834 	vma->vm_flags |= VM_IO | VM_DONTCOPY | VM_DONTEXPAND
1835 		| VM_NORESERVE | VM_DONTDUMP | VM_PFNMAP;
1836 	/* Mapping pages to user process */
1837 	return remap_pfn_range(vma, vma->vm_start,
1838 			       PFN_DOWN(__pa(qpd->cwsr_kaddr)),
1839 			       KFD_CWSR_TBA_TMA_SIZE, vma->vm_page_prot);
1840 }
1841 
1842 void kfd_flush_tlb(struct kfd_process_device *pdd, enum TLB_FLUSH_TYPE type)
1843 {
1844 	struct kfd_dev *dev = pdd->dev;
1845 
1846 	if (dev->dqm->sched_policy == KFD_SCHED_POLICY_NO_HWS) {
1847 		/* Nothing to flush until a VMID is assigned, which
1848 		 * only happens when the first queue is created.
1849 		 */
1850 		if (pdd->qpd.vmid)
1851 			amdgpu_amdkfd_flush_gpu_tlb_vmid(dev->kgd,
1852 							pdd->qpd.vmid);
1853 	} else {
1854 		amdgpu_amdkfd_flush_gpu_tlb_pasid(dev->kgd,
1855 					pdd->process->pasid, type);
1856 	}
1857 }
1858 
1859 #if defined(CONFIG_DEBUG_FS)
1860 
1861 int kfd_debugfs_mqds_by_process(struct seq_file *m, void *data)
1862 {
1863 	struct kfd_process *p;
1864 	unsigned int temp;
1865 	int r = 0;
1866 
1867 	int idx = srcu_read_lock(&kfd_processes_srcu);
1868 
1869 	hash_for_each_rcu(kfd_processes_table, temp, p, kfd_processes) {
1870 		seq_printf(m, "Process %d PASID 0x%x:\n",
1871 			   p->lead_thread->tgid, p->pasid);
1872 
1873 		mutex_lock(&p->mutex);
1874 		r = pqm_debugfs_mqds(m, &p->pqm);
1875 		mutex_unlock(&p->mutex);
1876 
1877 		if (r)
1878 			break;
1879 	}
1880 
1881 	srcu_read_unlock(&kfd_processes_srcu, idx);
1882 
1883 	return r;
1884 }
1885 
1886 #endif
1887 
1888