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