1 /*
2  * Copyright 2018 Red Hat 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 #include "nouveau_svm.h"
23 #include "nouveau_drv.h"
24 #include "nouveau_chan.h"
25 #include "nouveau_dmem.h"
26 
27 #include <nvif/notify.h>
28 #include <nvif/object.h>
29 #include <nvif/vmm.h>
30 
31 #include <nvif/class.h>
32 #include <nvif/clb069.h>
33 #include <nvif/ifc00d.h>
34 
35 #include <linux/sched/mm.h>
36 #include <linux/sort.h>
37 #include <linux/hmm.h>
38 #include <linux/rmap.h>
39 
40 struct nouveau_svm {
41 	struct nouveau_drm *drm;
42 	struct mutex mutex;
43 	struct list_head inst;
44 
45 	struct nouveau_svm_fault_buffer {
46 		int id;
47 		struct nvif_object object;
48 		u32 entries;
49 		u32 getaddr;
50 		u32 putaddr;
51 		u32 get;
52 		u32 put;
53 		struct nvif_notify notify;
54 
55 		struct nouveau_svm_fault {
56 			u64 inst;
57 			u64 addr;
58 			u64 time;
59 			u32 engine;
60 			u8  gpc;
61 			u8  hub;
62 			u8  access;
63 			u8  client;
64 			u8  fault;
65 			struct nouveau_svmm *svmm;
66 		} **fault;
67 		int fault_nr;
68 	} buffer[1];
69 };
70 
71 #define FAULT_ACCESS_READ 0
72 #define FAULT_ACCESS_WRITE 1
73 #define FAULT_ACCESS_ATOMIC 2
74 #define FAULT_ACCESS_PREFETCH 3
75 
76 #define SVM_DBG(s,f,a...) NV_DEBUG((s)->drm, "svm: "f"\n", ##a)
77 #define SVM_ERR(s,f,a...) NV_WARN((s)->drm, "svm: "f"\n", ##a)
78 
79 struct nouveau_pfnmap_args {
80 	struct nvif_ioctl_v0 i;
81 	struct nvif_ioctl_mthd_v0 m;
82 	struct nvif_vmm_pfnmap_v0 p;
83 };
84 
85 struct nouveau_ivmm {
86 	struct nouveau_svmm *svmm;
87 	u64 inst;
88 	struct list_head head;
89 };
90 
91 static struct nouveau_ivmm *
92 nouveau_ivmm_find(struct nouveau_svm *svm, u64 inst)
93 {
94 	struct nouveau_ivmm *ivmm;
95 	list_for_each_entry(ivmm, &svm->inst, head) {
96 		if (ivmm->inst == inst)
97 			return ivmm;
98 	}
99 	return NULL;
100 }
101 
102 #define SVMM_DBG(s,f,a...)                                                     \
103 	NV_DEBUG((s)->vmm->cli->drm, "svm-%p: "f"\n", (s), ##a)
104 #define SVMM_ERR(s,f,a...)                                                     \
105 	NV_WARN((s)->vmm->cli->drm, "svm-%p: "f"\n", (s), ##a)
106 
107 int
108 nouveau_svmm_bind(struct drm_device *dev, void *data,
109 		  struct drm_file *file_priv)
110 {
111 	struct nouveau_cli *cli = nouveau_cli(file_priv);
112 	struct drm_nouveau_svm_bind *args = data;
113 	unsigned target, cmd, priority;
114 	unsigned long addr, end;
115 	struct mm_struct *mm;
116 
117 	args->va_start &= PAGE_MASK;
118 	args->va_end = ALIGN(args->va_end, PAGE_SIZE);
119 
120 	/* Sanity check arguments */
121 	if (args->reserved0 || args->reserved1)
122 		return -EINVAL;
123 	if (args->header & (~NOUVEAU_SVM_BIND_VALID_MASK))
124 		return -EINVAL;
125 	if (args->va_start >= args->va_end)
126 		return -EINVAL;
127 
128 	cmd = args->header >> NOUVEAU_SVM_BIND_COMMAND_SHIFT;
129 	cmd &= NOUVEAU_SVM_BIND_COMMAND_MASK;
130 	switch (cmd) {
131 	case NOUVEAU_SVM_BIND_COMMAND__MIGRATE:
132 		break;
133 	default:
134 		return -EINVAL;
135 	}
136 
137 	priority = args->header >> NOUVEAU_SVM_BIND_PRIORITY_SHIFT;
138 	priority &= NOUVEAU_SVM_BIND_PRIORITY_MASK;
139 
140 	/* FIXME support CPU target ie all target value < GPU_VRAM */
141 	target = args->header >> NOUVEAU_SVM_BIND_TARGET_SHIFT;
142 	target &= NOUVEAU_SVM_BIND_TARGET_MASK;
143 	switch (target) {
144 	case NOUVEAU_SVM_BIND_TARGET__GPU_VRAM:
145 		break;
146 	default:
147 		return -EINVAL;
148 	}
149 
150 	/*
151 	 * FIXME: For now refuse non 0 stride, we need to change the migrate
152 	 * kernel function to handle stride to avoid to create a mess within
153 	 * each device driver.
154 	 */
155 	if (args->stride)
156 		return -EINVAL;
157 
158 	/*
159 	 * Ok we are ask to do something sane, for now we only support migrate
160 	 * commands but we will add things like memory policy (what to do on
161 	 * page fault) and maybe some other commands.
162 	 */
163 
164 	mm = get_task_mm(current);
165 	if (!mm) {
166 		return -EINVAL;
167 	}
168 	mmap_read_lock(mm);
169 
170 	if (!cli->svm.svmm) {
171 		mmap_read_unlock(mm);
172 		mmput(mm);
173 		return -EINVAL;
174 	}
175 
176 	for (addr = args->va_start, end = args->va_end; addr < end;) {
177 		struct vm_area_struct *vma;
178 		unsigned long next;
179 
180 		vma = find_vma_intersection(mm, addr, end);
181 		if (!vma)
182 			break;
183 
184 		addr = max(addr, vma->vm_start);
185 		next = min(vma->vm_end, end);
186 		/* This is a best effort so we ignore errors */
187 		nouveau_dmem_migrate_vma(cli->drm, cli->svm.svmm, vma, addr,
188 					 next);
189 		addr = next;
190 	}
191 
192 	/*
193 	 * FIXME Return the number of page we have migrated, again we need to
194 	 * update the migrate API to return that information so that we can
195 	 * report it to user space.
196 	 */
197 	args->result = 0;
198 
199 	mmap_read_unlock(mm);
200 	mmput(mm);
201 
202 	return 0;
203 }
204 
205 /* Unlink channel instance from SVMM. */
206 void
207 nouveau_svmm_part(struct nouveau_svmm *svmm, u64 inst)
208 {
209 	struct nouveau_ivmm *ivmm;
210 	if (svmm) {
211 		mutex_lock(&svmm->vmm->cli->drm->svm->mutex);
212 		ivmm = nouveau_ivmm_find(svmm->vmm->cli->drm->svm, inst);
213 		if (ivmm) {
214 			list_del(&ivmm->head);
215 			kfree(ivmm);
216 		}
217 		mutex_unlock(&svmm->vmm->cli->drm->svm->mutex);
218 	}
219 }
220 
221 /* Link channel instance to SVMM. */
222 int
223 nouveau_svmm_join(struct nouveau_svmm *svmm, u64 inst)
224 {
225 	struct nouveau_ivmm *ivmm;
226 	if (svmm) {
227 		if (!(ivmm = kmalloc(sizeof(*ivmm), GFP_KERNEL)))
228 			return -ENOMEM;
229 		ivmm->svmm = svmm;
230 		ivmm->inst = inst;
231 
232 		mutex_lock(&svmm->vmm->cli->drm->svm->mutex);
233 		list_add(&ivmm->head, &svmm->vmm->cli->drm->svm->inst);
234 		mutex_unlock(&svmm->vmm->cli->drm->svm->mutex);
235 	}
236 	return 0;
237 }
238 
239 /* Invalidate SVMM address-range on GPU. */
240 void
241 nouveau_svmm_invalidate(struct nouveau_svmm *svmm, u64 start, u64 limit)
242 {
243 	if (limit > start) {
244 		nvif_object_mthd(&svmm->vmm->vmm.object, NVIF_VMM_V0_PFNCLR,
245 				 &(struct nvif_vmm_pfnclr_v0) {
246 					.addr = start,
247 					.size = limit - start,
248 				 }, sizeof(struct nvif_vmm_pfnclr_v0));
249 	}
250 }
251 
252 static int
253 nouveau_svmm_invalidate_range_start(struct mmu_notifier *mn,
254 				    const struct mmu_notifier_range *update)
255 {
256 	struct nouveau_svmm *svmm =
257 		container_of(mn, struct nouveau_svmm, notifier);
258 	unsigned long start = update->start;
259 	unsigned long limit = update->end;
260 
261 	if (!mmu_notifier_range_blockable(update))
262 		return -EAGAIN;
263 
264 	SVMM_DBG(svmm, "invalidate %016lx-%016lx", start, limit);
265 
266 	mutex_lock(&svmm->mutex);
267 	if (unlikely(!svmm->vmm))
268 		goto out;
269 
270 	/*
271 	 * Ignore invalidation callbacks for device private pages since
272 	 * the invalidation is handled as part of the migration process.
273 	 */
274 	if (update->event == MMU_NOTIFY_MIGRATE &&
275 	    update->owner == svmm->vmm->cli->drm->dev)
276 		goto out;
277 
278 	if (limit > svmm->unmanaged.start && start < svmm->unmanaged.limit) {
279 		if (start < svmm->unmanaged.start) {
280 			nouveau_svmm_invalidate(svmm, start,
281 						svmm->unmanaged.limit);
282 		}
283 		start = svmm->unmanaged.limit;
284 	}
285 
286 	nouveau_svmm_invalidate(svmm, start, limit);
287 
288 out:
289 	mutex_unlock(&svmm->mutex);
290 	return 0;
291 }
292 
293 static void nouveau_svmm_free_notifier(struct mmu_notifier *mn)
294 {
295 	kfree(container_of(mn, struct nouveau_svmm, notifier));
296 }
297 
298 static const struct mmu_notifier_ops nouveau_mn_ops = {
299 	.invalidate_range_start = nouveau_svmm_invalidate_range_start,
300 	.free_notifier = nouveau_svmm_free_notifier,
301 };
302 
303 void
304 nouveau_svmm_fini(struct nouveau_svmm **psvmm)
305 {
306 	struct nouveau_svmm *svmm = *psvmm;
307 	if (svmm) {
308 		mutex_lock(&svmm->mutex);
309 		svmm->vmm = NULL;
310 		mutex_unlock(&svmm->mutex);
311 		mmu_notifier_put(&svmm->notifier);
312 		*psvmm = NULL;
313 	}
314 }
315 
316 int
317 nouveau_svmm_init(struct drm_device *dev, void *data,
318 		  struct drm_file *file_priv)
319 {
320 	struct nouveau_cli *cli = nouveau_cli(file_priv);
321 	struct nouveau_svmm *svmm;
322 	struct drm_nouveau_svm_init *args = data;
323 	int ret;
324 
325 	/* We need to fail if svm is disabled */
326 	if (!cli->drm->svm)
327 		return -ENOSYS;
328 
329 	/* Allocate tracking for SVM-enabled VMM. */
330 	if (!(svmm = kzalloc(sizeof(*svmm), GFP_KERNEL)))
331 		return -ENOMEM;
332 	svmm->vmm = &cli->svm;
333 	svmm->unmanaged.start = args->unmanaged_addr;
334 	svmm->unmanaged.limit = args->unmanaged_addr + args->unmanaged_size;
335 	mutex_init(&svmm->mutex);
336 
337 	/* Check that SVM isn't already enabled for the client. */
338 	mutex_lock(&cli->mutex);
339 	if (cli->svm.cli) {
340 		ret = -EBUSY;
341 		goto out_free;
342 	}
343 
344 	/* Allocate a new GPU VMM that can support SVM (managed by the
345 	 * client, with replayable faults enabled).
346 	 *
347 	 * All future channel/memory allocations will make use of this
348 	 * VMM instead of the standard one.
349 	 */
350 	ret = nvif_vmm_ctor(&cli->mmu, "svmVmm",
351 			    cli->vmm.vmm.object.oclass, true,
352 			    args->unmanaged_addr, args->unmanaged_size,
353 			    &(struct gp100_vmm_v0) {
354 				.fault_replay = true,
355 			    }, sizeof(struct gp100_vmm_v0), &cli->svm.vmm);
356 	if (ret)
357 		goto out_free;
358 
359 	mmap_write_lock(current->mm);
360 	svmm->notifier.ops = &nouveau_mn_ops;
361 	ret = __mmu_notifier_register(&svmm->notifier, current->mm);
362 	if (ret)
363 		goto out_mm_unlock;
364 	/* Note, ownership of svmm transfers to mmu_notifier */
365 
366 	cli->svm.svmm = svmm;
367 	cli->svm.cli = cli;
368 	mmap_write_unlock(current->mm);
369 	mutex_unlock(&cli->mutex);
370 	return 0;
371 
372 out_mm_unlock:
373 	mmap_write_unlock(current->mm);
374 out_free:
375 	mutex_unlock(&cli->mutex);
376 	kfree(svmm);
377 	return ret;
378 }
379 
380 /* Issue fault replay for GPU to retry accesses that faulted previously. */
381 static void
382 nouveau_svm_fault_replay(struct nouveau_svm *svm)
383 {
384 	SVM_DBG(svm, "replay");
385 	WARN_ON(nvif_object_mthd(&svm->drm->client.vmm.vmm.object,
386 				 GP100_VMM_VN_FAULT_REPLAY,
387 				 &(struct gp100_vmm_fault_replay_vn) {},
388 				 sizeof(struct gp100_vmm_fault_replay_vn)));
389 }
390 
391 /* Cancel a replayable fault that could not be handled.
392  *
393  * Cancelling the fault will trigger recovery to reset the engine
394  * and kill the offending channel (ie. GPU SIGSEGV).
395  */
396 static void
397 nouveau_svm_fault_cancel(struct nouveau_svm *svm,
398 			 u64 inst, u8 hub, u8 gpc, u8 client)
399 {
400 	SVM_DBG(svm, "cancel %016llx %d %02x %02x", inst, hub, gpc, client);
401 	WARN_ON(nvif_object_mthd(&svm->drm->client.vmm.vmm.object,
402 				 GP100_VMM_VN_FAULT_CANCEL,
403 				 &(struct gp100_vmm_fault_cancel_v0) {
404 					.hub = hub,
405 					.gpc = gpc,
406 					.client = client,
407 					.inst = inst,
408 				 }, sizeof(struct gp100_vmm_fault_cancel_v0)));
409 }
410 
411 static void
412 nouveau_svm_fault_cancel_fault(struct nouveau_svm *svm,
413 			       struct nouveau_svm_fault *fault)
414 {
415 	nouveau_svm_fault_cancel(svm, fault->inst,
416 				      fault->hub,
417 				      fault->gpc,
418 				      fault->client);
419 }
420 
421 static int
422 nouveau_svm_fault_priority(u8 fault)
423 {
424 	switch (fault) {
425 	case FAULT_ACCESS_PREFETCH:
426 		return 0;
427 	case FAULT_ACCESS_READ:
428 		return 1;
429 	case FAULT_ACCESS_WRITE:
430 		return 2;
431 	case FAULT_ACCESS_ATOMIC:
432 		return 3;
433 	default:
434 		WARN_ON_ONCE(1);
435 		return -1;
436 	}
437 }
438 
439 static int
440 nouveau_svm_fault_cmp(const void *a, const void *b)
441 {
442 	const struct nouveau_svm_fault *fa = *(struct nouveau_svm_fault **)a;
443 	const struct nouveau_svm_fault *fb = *(struct nouveau_svm_fault **)b;
444 	int ret;
445 	if ((ret = (s64)fa->inst - fb->inst))
446 		return ret;
447 	if ((ret = (s64)fa->addr - fb->addr))
448 		return ret;
449 	return nouveau_svm_fault_priority(fa->access) -
450 		nouveau_svm_fault_priority(fb->access);
451 }
452 
453 static void
454 nouveau_svm_fault_cache(struct nouveau_svm *svm,
455 			struct nouveau_svm_fault_buffer *buffer, u32 offset)
456 {
457 	struct nvif_object *memory = &buffer->object;
458 	const u32 instlo = nvif_rd32(memory, offset + 0x00);
459 	const u32 insthi = nvif_rd32(memory, offset + 0x04);
460 	const u32 addrlo = nvif_rd32(memory, offset + 0x08);
461 	const u32 addrhi = nvif_rd32(memory, offset + 0x0c);
462 	const u32 timelo = nvif_rd32(memory, offset + 0x10);
463 	const u32 timehi = nvif_rd32(memory, offset + 0x14);
464 	const u32 engine = nvif_rd32(memory, offset + 0x18);
465 	const u32   info = nvif_rd32(memory, offset + 0x1c);
466 	const u64   inst = (u64)insthi << 32 | instlo;
467 	const u8     gpc = (info & 0x1f000000) >> 24;
468 	const u8     hub = (info & 0x00100000) >> 20;
469 	const u8  client = (info & 0x00007f00) >> 8;
470 	struct nouveau_svm_fault *fault;
471 
472 	//XXX: i think we're supposed to spin waiting */
473 	if (WARN_ON(!(info & 0x80000000)))
474 		return;
475 
476 	nvif_mask(memory, offset + 0x1c, 0x80000000, 0x00000000);
477 
478 	if (!buffer->fault[buffer->fault_nr]) {
479 		fault = kmalloc(sizeof(*fault), GFP_KERNEL);
480 		if (WARN_ON(!fault)) {
481 			nouveau_svm_fault_cancel(svm, inst, hub, gpc, client);
482 			return;
483 		}
484 		buffer->fault[buffer->fault_nr] = fault;
485 	}
486 
487 	fault = buffer->fault[buffer->fault_nr++];
488 	fault->inst   = inst;
489 	fault->addr   = (u64)addrhi << 32 | addrlo;
490 	fault->time   = (u64)timehi << 32 | timelo;
491 	fault->engine = engine;
492 	fault->gpc    = gpc;
493 	fault->hub    = hub;
494 	fault->access = (info & 0x000f0000) >> 16;
495 	fault->client = client;
496 	fault->fault  = (info & 0x0000001f);
497 
498 	SVM_DBG(svm, "fault %016llx %016llx %02x",
499 		fault->inst, fault->addr, fault->access);
500 }
501 
502 struct svm_notifier {
503 	struct mmu_interval_notifier notifier;
504 	struct nouveau_svmm *svmm;
505 };
506 
507 static bool nouveau_svm_range_invalidate(struct mmu_interval_notifier *mni,
508 					 const struct mmu_notifier_range *range,
509 					 unsigned long cur_seq)
510 {
511 	struct svm_notifier *sn =
512 		container_of(mni, struct svm_notifier, notifier);
513 
514 	if (range->event == MMU_NOTIFY_EXCLUSIVE &&
515 	    range->owner == sn->svmm->vmm->cli->drm->dev)
516 		return true;
517 
518 	/*
519 	 * serializes the update to mni->invalidate_seq done by caller and
520 	 * prevents invalidation of the PTE from progressing while HW is being
521 	 * programmed. This is very hacky and only works because the normal
522 	 * notifier that does invalidation is always called after the range
523 	 * notifier.
524 	 */
525 	if (mmu_notifier_range_blockable(range))
526 		mutex_lock(&sn->svmm->mutex);
527 	else if (!mutex_trylock(&sn->svmm->mutex))
528 		return false;
529 	mmu_interval_set_seq(mni, cur_seq);
530 	mutex_unlock(&sn->svmm->mutex);
531 	return true;
532 }
533 
534 static const struct mmu_interval_notifier_ops nouveau_svm_mni_ops = {
535 	.invalidate = nouveau_svm_range_invalidate,
536 };
537 
538 static void nouveau_hmm_convert_pfn(struct nouveau_drm *drm,
539 				    struct hmm_range *range,
540 				    struct nouveau_pfnmap_args *args)
541 {
542 	struct page *page;
543 
544 	/*
545 	 * The address prepared here is passed through nvif_object_ioctl()
546 	 * to an eventual DMA map in something like gp100_vmm_pgt_pfn()
547 	 *
548 	 * This is all just encoding the internal hmm representation into a
549 	 * different nouveau internal representation.
550 	 */
551 	if (!(range->hmm_pfns[0] & HMM_PFN_VALID)) {
552 		args->p.phys[0] = 0;
553 		return;
554 	}
555 
556 	page = hmm_pfn_to_page(range->hmm_pfns[0]);
557 	/*
558 	 * Only map compound pages to the GPU if the CPU is also mapping the
559 	 * page as a compound page. Otherwise, the PTE protections might not be
560 	 * consistent (e.g., CPU only maps part of a compound page).
561 	 * Note that the underlying page might still be larger than the
562 	 * CPU mapping (e.g., a PUD sized compound page partially mapped with
563 	 * a PMD sized page table entry).
564 	 */
565 	if (hmm_pfn_to_map_order(range->hmm_pfns[0])) {
566 		unsigned long addr = args->p.addr;
567 
568 		args->p.page = hmm_pfn_to_map_order(range->hmm_pfns[0]) +
569 				PAGE_SHIFT;
570 		args->p.size = 1UL << args->p.page;
571 		args->p.addr &= ~(args->p.size - 1);
572 		page -= (addr - args->p.addr) >> PAGE_SHIFT;
573 	}
574 	if (is_device_private_page(page))
575 		args->p.phys[0] = nouveau_dmem_page_addr(page) |
576 				NVIF_VMM_PFNMAP_V0_V |
577 				NVIF_VMM_PFNMAP_V0_VRAM;
578 	else
579 		args->p.phys[0] = page_to_phys(page) |
580 				NVIF_VMM_PFNMAP_V0_V |
581 				NVIF_VMM_PFNMAP_V0_HOST;
582 	if (range->hmm_pfns[0] & HMM_PFN_WRITE)
583 		args->p.phys[0] |= NVIF_VMM_PFNMAP_V0_W;
584 }
585 
586 static int nouveau_atomic_range_fault(struct nouveau_svmm *svmm,
587 			       struct nouveau_drm *drm,
588 			       struct nouveau_pfnmap_args *args, u32 size,
589 			       struct svm_notifier *notifier)
590 {
591 	unsigned long timeout =
592 		jiffies + msecs_to_jiffies(HMM_RANGE_DEFAULT_TIMEOUT);
593 	struct mm_struct *mm = svmm->notifier.mm;
594 	struct page *page;
595 	unsigned long start = args->p.addr;
596 	unsigned long notifier_seq;
597 	int ret = 0;
598 
599 	ret = mmu_interval_notifier_insert(&notifier->notifier, mm,
600 					args->p.addr, args->p.size,
601 					&nouveau_svm_mni_ops);
602 	if (ret)
603 		return ret;
604 
605 	while (true) {
606 		if (time_after(jiffies, timeout)) {
607 			ret = -EBUSY;
608 			goto out;
609 		}
610 
611 		notifier_seq = mmu_interval_read_begin(&notifier->notifier);
612 		mmap_read_lock(mm);
613 		ret = make_device_exclusive_range(mm, start, start + PAGE_SIZE,
614 					    &page, drm->dev);
615 		mmap_read_unlock(mm);
616 		if (ret <= 0 || !page) {
617 			ret = -EINVAL;
618 			goto out;
619 		}
620 
621 		mutex_lock(&svmm->mutex);
622 		if (!mmu_interval_read_retry(&notifier->notifier,
623 					     notifier_seq))
624 			break;
625 		mutex_unlock(&svmm->mutex);
626 	}
627 
628 	/* Map the page on the GPU. */
629 	args->p.page = 12;
630 	args->p.size = PAGE_SIZE;
631 	args->p.addr = start;
632 	args->p.phys[0] = page_to_phys(page) |
633 		NVIF_VMM_PFNMAP_V0_V |
634 		NVIF_VMM_PFNMAP_V0_W |
635 		NVIF_VMM_PFNMAP_V0_A |
636 		NVIF_VMM_PFNMAP_V0_HOST;
637 
638 	ret = nvif_object_ioctl(&svmm->vmm->vmm.object, args, size, NULL);
639 	mutex_unlock(&svmm->mutex);
640 
641 	unlock_page(page);
642 	put_page(page);
643 
644 out:
645 	mmu_interval_notifier_remove(&notifier->notifier);
646 	return ret;
647 }
648 
649 static int nouveau_range_fault(struct nouveau_svmm *svmm,
650 			       struct nouveau_drm *drm,
651 			       struct nouveau_pfnmap_args *args, u32 size,
652 			       unsigned long hmm_flags,
653 			       struct svm_notifier *notifier)
654 {
655 	unsigned long timeout =
656 		jiffies + msecs_to_jiffies(HMM_RANGE_DEFAULT_TIMEOUT);
657 	/* Have HMM fault pages within the fault window to the GPU. */
658 	unsigned long hmm_pfns[1];
659 	struct hmm_range range = {
660 		.notifier = &notifier->notifier,
661 		.default_flags = hmm_flags,
662 		.hmm_pfns = hmm_pfns,
663 		.dev_private_owner = drm->dev,
664 	};
665 	struct mm_struct *mm = svmm->notifier.mm;
666 	int ret;
667 
668 	ret = mmu_interval_notifier_insert(&notifier->notifier, mm,
669 					args->p.addr, args->p.size,
670 					&nouveau_svm_mni_ops);
671 	if (ret)
672 		return ret;
673 
674 	range.start = notifier->notifier.interval_tree.start;
675 	range.end = notifier->notifier.interval_tree.last + 1;
676 
677 	while (true) {
678 		if (time_after(jiffies, timeout)) {
679 			ret = -EBUSY;
680 			goto out;
681 		}
682 
683 		range.notifier_seq = mmu_interval_read_begin(range.notifier);
684 		mmap_read_lock(mm);
685 		ret = hmm_range_fault(&range);
686 		mmap_read_unlock(mm);
687 		if (ret) {
688 			if (ret == -EBUSY)
689 				continue;
690 			goto out;
691 		}
692 
693 		mutex_lock(&svmm->mutex);
694 		if (mmu_interval_read_retry(range.notifier,
695 					    range.notifier_seq)) {
696 			mutex_unlock(&svmm->mutex);
697 			continue;
698 		}
699 		break;
700 	}
701 
702 	nouveau_hmm_convert_pfn(drm, &range, args);
703 
704 	ret = nvif_object_ioctl(&svmm->vmm->vmm.object, args, size, NULL);
705 	mutex_unlock(&svmm->mutex);
706 
707 out:
708 	mmu_interval_notifier_remove(&notifier->notifier);
709 
710 	return ret;
711 }
712 
713 static int
714 nouveau_svm_fault(struct nvif_notify *notify)
715 {
716 	struct nouveau_svm_fault_buffer *buffer =
717 		container_of(notify, typeof(*buffer), notify);
718 	struct nouveau_svm *svm =
719 		container_of(buffer, typeof(*svm), buffer[buffer->id]);
720 	struct nvif_object *device = &svm->drm->client.device.object;
721 	struct nouveau_svmm *svmm;
722 	struct {
723 		struct nouveau_pfnmap_args i;
724 		u64 phys[1];
725 	} args;
726 	unsigned long hmm_flags;
727 	u64 inst, start, limit;
728 	int fi, fn;
729 	int replay = 0, atomic = 0, ret;
730 
731 	/* Parse available fault buffer entries into a cache, and update
732 	 * the GET pointer so HW can reuse the entries.
733 	 */
734 	SVM_DBG(svm, "fault handler");
735 	if (buffer->get == buffer->put) {
736 		buffer->put = nvif_rd32(device, buffer->putaddr);
737 		buffer->get = nvif_rd32(device, buffer->getaddr);
738 		if (buffer->get == buffer->put)
739 			return NVIF_NOTIFY_KEEP;
740 	}
741 	buffer->fault_nr = 0;
742 
743 	SVM_DBG(svm, "get %08x put %08x", buffer->get, buffer->put);
744 	while (buffer->get != buffer->put) {
745 		nouveau_svm_fault_cache(svm, buffer, buffer->get * 0x20);
746 		if (++buffer->get == buffer->entries)
747 			buffer->get = 0;
748 	}
749 	nvif_wr32(device, buffer->getaddr, buffer->get);
750 	SVM_DBG(svm, "%d fault(s) pending", buffer->fault_nr);
751 
752 	/* Sort parsed faults by instance pointer to prevent unnecessary
753 	 * instance to SVMM translations, followed by address and access
754 	 * type to reduce the amount of work when handling the faults.
755 	 */
756 	sort(buffer->fault, buffer->fault_nr, sizeof(*buffer->fault),
757 	     nouveau_svm_fault_cmp, NULL);
758 
759 	/* Lookup SVMM structure for each unique instance pointer. */
760 	mutex_lock(&svm->mutex);
761 	for (fi = 0, svmm = NULL; fi < buffer->fault_nr; fi++) {
762 		if (!svmm || buffer->fault[fi]->inst != inst) {
763 			struct nouveau_ivmm *ivmm =
764 				nouveau_ivmm_find(svm, buffer->fault[fi]->inst);
765 			svmm = ivmm ? ivmm->svmm : NULL;
766 			inst = buffer->fault[fi]->inst;
767 			SVM_DBG(svm, "inst %016llx -> svm-%p", inst, svmm);
768 		}
769 		buffer->fault[fi]->svmm = svmm;
770 	}
771 	mutex_unlock(&svm->mutex);
772 
773 	/* Process list of faults. */
774 	args.i.i.version = 0;
775 	args.i.i.type = NVIF_IOCTL_V0_MTHD;
776 	args.i.m.version = 0;
777 	args.i.m.method = NVIF_VMM_V0_PFNMAP;
778 	args.i.p.version = 0;
779 
780 	for (fi = 0; fn = fi + 1, fi < buffer->fault_nr; fi = fn) {
781 		struct svm_notifier notifier;
782 		struct mm_struct *mm;
783 
784 		/* Cancel any faults from non-SVM channels. */
785 		if (!(svmm = buffer->fault[fi]->svmm)) {
786 			nouveau_svm_fault_cancel_fault(svm, buffer->fault[fi]);
787 			continue;
788 		}
789 		SVMM_DBG(svmm, "addr %016llx", buffer->fault[fi]->addr);
790 
791 		/* We try and group handling of faults within a small
792 		 * window into a single update.
793 		 */
794 		start = buffer->fault[fi]->addr;
795 		limit = start + PAGE_SIZE;
796 		if (start < svmm->unmanaged.limit)
797 			limit = min_t(u64, limit, svmm->unmanaged.start);
798 
799 		/*
800 		 * Prepare the GPU-side update of all pages within the
801 		 * fault window, determining required pages and access
802 		 * permissions based on pending faults.
803 		 */
804 		args.i.p.addr = start;
805 		args.i.p.page = PAGE_SHIFT;
806 		args.i.p.size = PAGE_SIZE;
807 		/*
808 		 * Determine required permissions based on GPU fault
809 		 * access flags.
810 		 */
811 		switch (buffer->fault[fi]->access) {
812 		case 0: /* READ. */
813 			hmm_flags = HMM_PFN_REQ_FAULT;
814 			break;
815 		case 2: /* ATOMIC. */
816 			atomic = true;
817 			break;
818 		case 3: /* PREFETCH. */
819 			hmm_flags = 0;
820 			break;
821 		default:
822 			hmm_flags = HMM_PFN_REQ_FAULT | HMM_PFN_REQ_WRITE;
823 			break;
824 		}
825 
826 		mm = svmm->notifier.mm;
827 		if (!mmget_not_zero(mm)) {
828 			nouveau_svm_fault_cancel_fault(svm, buffer->fault[fi]);
829 			continue;
830 		}
831 
832 		notifier.svmm = svmm;
833 		if (atomic)
834 			ret = nouveau_atomic_range_fault(svmm, svm->drm,
835 							 &args.i, sizeof(args),
836 							 &notifier);
837 		else
838 			ret = nouveau_range_fault(svmm, svm->drm, &args.i,
839 						  sizeof(args), hmm_flags,
840 						  &notifier);
841 		mmput(mm);
842 
843 		limit = args.i.p.addr + args.i.p.size;
844 		for (fn = fi; ++fn < buffer->fault_nr; ) {
845 			/* It's okay to skip over duplicate addresses from the
846 			 * same SVMM as faults are ordered by access type such
847 			 * that only the first one needs to be handled.
848 			 *
849 			 * ie. WRITE faults appear first, thus any handling of
850 			 * pending READ faults will already be satisfied.
851 			 * But if a large page is mapped, make sure subsequent
852 			 * fault addresses have sufficient access permission.
853 			 */
854 			if (buffer->fault[fn]->svmm != svmm ||
855 			    buffer->fault[fn]->addr >= limit ||
856 			    (buffer->fault[fi]->access == FAULT_ACCESS_READ &&
857 			     !(args.phys[0] & NVIF_VMM_PFNMAP_V0_V)) ||
858 			    (buffer->fault[fi]->access != FAULT_ACCESS_READ &&
859 			     buffer->fault[fi]->access != FAULT_ACCESS_PREFETCH &&
860 			     !(args.phys[0] & NVIF_VMM_PFNMAP_V0_W)) ||
861 			    (buffer->fault[fi]->access != FAULT_ACCESS_READ &&
862 			     buffer->fault[fi]->access != FAULT_ACCESS_WRITE &&
863 			     buffer->fault[fi]->access != FAULT_ACCESS_PREFETCH &&
864 			     !(args.phys[0] & NVIF_VMM_PFNMAP_V0_A)))
865 				break;
866 		}
867 
868 		/* If handling failed completely, cancel all faults. */
869 		if (ret) {
870 			while (fi < fn) {
871 				struct nouveau_svm_fault *fault =
872 					buffer->fault[fi++];
873 
874 				nouveau_svm_fault_cancel_fault(svm, fault);
875 			}
876 		} else
877 			replay++;
878 	}
879 
880 	/* Issue fault replay to the GPU. */
881 	if (replay)
882 		nouveau_svm_fault_replay(svm);
883 	return NVIF_NOTIFY_KEEP;
884 }
885 
886 static struct nouveau_pfnmap_args *
887 nouveau_pfns_to_args(void *pfns)
888 {
889 	return container_of(pfns, struct nouveau_pfnmap_args, p.phys);
890 }
891 
892 u64 *
893 nouveau_pfns_alloc(unsigned long npages)
894 {
895 	struct nouveau_pfnmap_args *args;
896 
897 	args = kzalloc(struct_size(args, p.phys, npages), GFP_KERNEL);
898 	if (!args)
899 		return NULL;
900 
901 	args->i.type = NVIF_IOCTL_V0_MTHD;
902 	args->m.method = NVIF_VMM_V0_PFNMAP;
903 	args->p.page = PAGE_SHIFT;
904 
905 	return args->p.phys;
906 }
907 
908 void
909 nouveau_pfns_free(u64 *pfns)
910 {
911 	struct nouveau_pfnmap_args *args = nouveau_pfns_to_args(pfns);
912 
913 	kfree(args);
914 }
915 
916 void
917 nouveau_pfns_map(struct nouveau_svmm *svmm, struct mm_struct *mm,
918 		 unsigned long addr, u64 *pfns, unsigned long npages)
919 {
920 	struct nouveau_pfnmap_args *args = nouveau_pfns_to_args(pfns);
921 	int ret;
922 
923 	args->p.addr = addr;
924 	args->p.size = npages << PAGE_SHIFT;
925 
926 	mutex_lock(&svmm->mutex);
927 
928 	ret = nvif_object_ioctl(&svmm->vmm->vmm.object, args, sizeof(*args) +
929 				npages * sizeof(args->p.phys[0]), NULL);
930 
931 	mutex_unlock(&svmm->mutex);
932 }
933 
934 static void
935 nouveau_svm_fault_buffer_fini(struct nouveau_svm *svm, int id)
936 {
937 	struct nouveau_svm_fault_buffer *buffer = &svm->buffer[id];
938 	nvif_notify_put(&buffer->notify);
939 }
940 
941 static int
942 nouveau_svm_fault_buffer_init(struct nouveau_svm *svm, int id)
943 {
944 	struct nouveau_svm_fault_buffer *buffer = &svm->buffer[id];
945 	struct nvif_object *device = &svm->drm->client.device.object;
946 	buffer->get = nvif_rd32(device, buffer->getaddr);
947 	buffer->put = nvif_rd32(device, buffer->putaddr);
948 	SVM_DBG(svm, "get %08x put %08x (init)", buffer->get, buffer->put);
949 	return nvif_notify_get(&buffer->notify);
950 }
951 
952 static void
953 nouveau_svm_fault_buffer_dtor(struct nouveau_svm *svm, int id)
954 {
955 	struct nouveau_svm_fault_buffer *buffer = &svm->buffer[id];
956 	int i;
957 
958 	if (buffer->fault) {
959 		for (i = 0; buffer->fault[i] && i < buffer->entries; i++)
960 			kfree(buffer->fault[i]);
961 		kvfree(buffer->fault);
962 	}
963 
964 	nouveau_svm_fault_buffer_fini(svm, id);
965 
966 	nvif_notify_dtor(&buffer->notify);
967 	nvif_object_dtor(&buffer->object);
968 }
969 
970 static int
971 nouveau_svm_fault_buffer_ctor(struct nouveau_svm *svm, s32 oclass, int id)
972 {
973 	struct nouveau_svm_fault_buffer *buffer = &svm->buffer[id];
974 	struct nouveau_drm *drm = svm->drm;
975 	struct nvif_object *device = &drm->client.device.object;
976 	struct nvif_clb069_v0 args = {};
977 	int ret;
978 
979 	buffer->id = id;
980 
981 	ret = nvif_object_ctor(device, "svmFaultBuffer", 0, oclass, &args,
982 			       sizeof(args), &buffer->object);
983 	if (ret < 0) {
984 		SVM_ERR(svm, "Fault buffer allocation failed: %d", ret);
985 		return ret;
986 	}
987 
988 	nvif_object_map(&buffer->object, NULL, 0);
989 	buffer->entries = args.entries;
990 	buffer->getaddr = args.get;
991 	buffer->putaddr = args.put;
992 
993 	ret = nvif_notify_ctor(&buffer->object, "svmFault", nouveau_svm_fault,
994 			       true, NVB069_V0_NTFY_FAULT, NULL, 0, 0,
995 			       &buffer->notify);
996 	if (ret)
997 		return ret;
998 
999 	buffer->fault = kvcalloc(sizeof(*buffer->fault), buffer->entries, GFP_KERNEL);
1000 	if (!buffer->fault)
1001 		return -ENOMEM;
1002 
1003 	return nouveau_svm_fault_buffer_init(svm, id);
1004 }
1005 
1006 void
1007 nouveau_svm_resume(struct nouveau_drm *drm)
1008 {
1009 	struct nouveau_svm *svm = drm->svm;
1010 	if (svm)
1011 		nouveau_svm_fault_buffer_init(svm, 0);
1012 }
1013 
1014 void
1015 nouveau_svm_suspend(struct nouveau_drm *drm)
1016 {
1017 	struct nouveau_svm *svm = drm->svm;
1018 	if (svm)
1019 		nouveau_svm_fault_buffer_fini(svm, 0);
1020 }
1021 
1022 void
1023 nouveau_svm_fini(struct nouveau_drm *drm)
1024 {
1025 	struct nouveau_svm *svm = drm->svm;
1026 	if (svm) {
1027 		nouveau_svm_fault_buffer_dtor(svm, 0);
1028 		kfree(drm->svm);
1029 		drm->svm = NULL;
1030 	}
1031 }
1032 
1033 void
1034 nouveau_svm_init(struct nouveau_drm *drm)
1035 {
1036 	static const struct nvif_mclass buffers[] = {
1037 		{   VOLTA_FAULT_BUFFER_A, 0 },
1038 		{ MAXWELL_FAULT_BUFFER_A, 0 },
1039 		{}
1040 	};
1041 	struct nouveau_svm *svm;
1042 	int ret;
1043 
1044 	/* Disable on Volta and newer until channel recovery is fixed,
1045 	 * otherwise clients will have a trivial way to trash the GPU
1046 	 * for everyone.
1047 	 */
1048 	if (drm->client.device.info.family > NV_DEVICE_INFO_V0_PASCAL)
1049 		return;
1050 
1051 	if (!(drm->svm = svm = kzalloc(sizeof(*drm->svm), GFP_KERNEL)))
1052 		return;
1053 
1054 	drm->svm->drm = drm;
1055 	mutex_init(&drm->svm->mutex);
1056 	INIT_LIST_HEAD(&drm->svm->inst);
1057 
1058 	ret = nvif_mclass(&drm->client.device.object, buffers);
1059 	if (ret < 0) {
1060 		SVM_DBG(svm, "No supported fault buffer class");
1061 		nouveau_svm_fini(drm);
1062 		return;
1063 	}
1064 
1065 	ret = nouveau_svm_fault_buffer_ctor(svm, buffers[ret].oclass, 0);
1066 	if (ret) {
1067 		nouveau_svm_fini(drm);
1068 		return;
1069 	}
1070 
1071 	SVM_DBG(svm, "Initialised");
1072 }
1073