xref: /linux/drivers/gpu/drm/nouveau/nouveau_svm.c (revision fba4168edecdd2781bcd83cb131977ec1157f87c)
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_ivmm {
74 	struct nouveau_svmm *svmm;
75 	u64 inst;
76 	struct list_head head;
77 };
78 
79 static struct nouveau_ivmm *
80 nouveau_ivmm_find(struct nouveau_svm *svm, u64 inst)
81 {
82 	struct nouveau_ivmm *ivmm;
83 	list_for_each_entry(ivmm, &svm->inst, head) {
84 		if (ivmm->inst == inst)
85 			return ivmm;
86 	}
87 	return NULL;
88 }
89 
90 struct nouveau_svmm {
91 	struct mmu_notifier notifier;
92 	struct nouveau_vmm *vmm;
93 	struct {
94 		unsigned long start;
95 		unsigned long limit;
96 	} unmanaged;
97 
98 	struct mutex mutex;
99 };
100 
101 #define SVMM_DBG(s,f,a...)                                                     \
102 	NV_DEBUG((s)->vmm->cli->drm, "svm-%p: "f"\n", (s), ##a)
103 #define SVMM_ERR(s,f,a...)                                                     \
104 	NV_WARN((s)->vmm->cli->drm, "svm-%p: "f"\n", (s), ##a)
105 
106 int
107 nouveau_svmm_bind(struct drm_device *dev, void *data,
108 		  struct drm_file *file_priv)
109 {
110 	struct nouveau_cli *cli = nouveau_cli(file_priv);
111 	struct drm_nouveau_svm_bind *args = data;
112 	unsigned target, cmd, priority;
113 	unsigned long addr, end, size;
114 	struct mm_struct *mm;
115 
116 	args->va_start &= PAGE_MASK;
117 	args->va_end &= PAGE_MASK;
118 
119 	/* Sanity check arguments */
120 	if (args->reserved0 || args->reserved1)
121 		return -EINVAL;
122 	if (args->header & (~NOUVEAU_SVM_BIND_VALID_MASK))
123 		return -EINVAL;
124 	if (args->va_start >= args->va_end)
125 		return -EINVAL;
126 	if (!args->npages)
127 		return -EINVAL;
128 
129 	cmd = args->header >> NOUVEAU_SVM_BIND_COMMAND_SHIFT;
130 	cmd &= NOUVEAU_SVM_BIND_COMMAND_MASK;
131 	switch (cmd) {
132 	case NOUVEAU_SVM_BIND_COMMAND__MIGRATE:
133 		break;
134 	default:
135 		return -EINVAL;
136 	}
137 
138 	priority = args->header >> NOUVEAU_SVM_BIND_PRIORITY_SHIFT;
139 	priority &= NOUVEAU_SVM_BIND_PRIORITY_MASK;
140 
141 	/* FIXME support CPU target ie all target value < GPU_VRAM */
142 	target = args->header >> NOUVEAU_SVM_BIND_TARGET_SHIFT;
143 	target &= NOUVEAU_SVM_BIND_TARGET_MASK;
144 	switch (target) {
145 	case NOUVEAU_SVM_BIND_TARGET__GPU_VRAM:
146 		break;
147 	default:
148 		return -EINVAL;
149 	}
150 
151 	/*
152 	 * FIXME: For now refuse non 0 stride, we need to change the migrate
153 	 * kernel function to handle stride to avoid to create a mess within
154 	 * each device driver.
155 	 */
156 	if (args->stride)
157 		return -EINVAL;
158 
159 	size = ((unsigned long)args->npages) << PAGE_SHIFT;
160 	if ((args->va_start + size) <= args->va_start)
161 		return -EINVAL;
162 	if ((args->va_start + size) > args->va_end)
163 		return -EINVAL;
164 
165 	/*
166 	 * Ok we are ask to do something sane, for now we only support migrate
167 	 * commands but we will add things like memory policy (what to do on
168 	 * page fault) and maybe some other commands.
169 	 */
170 
171 	mm = get_task_mm(current);
172 	down_read(&mm->mmap_sem);
173 
174 	for (addr = args->va_start, end = args->va_start + size; addr < end;) {
175 		struct vm_area_struct *vma;
176 		unsigned long next;
177 
178 		vma = find_vma_intersection(mm, addr, end);
179 		if (!vma)
180 			break;
181 
182 		next = min(vma->vm_end, end);
183 		/* This is a best effort so we ignore errors */
184 		nouveau_dmem_migrate_vma(cli->drm, vma, addr, next);
185 		addr = next;
186 	}
187 
188 	/*
189 	 * FIXME Return the number of page we have migrated, again we need to
190 	 * update the migrate API to return that information so that we can
191 	 * report it to user space.
192 	 */
193 	args->result = 0;
194 
195 	up_read(&mm->mmap_sem);
196 	mmput(mm);
197 
198 	return 0;
199 }
200 
201 /* Unlink channel instance from SVMM. */
202 void
203 nouveau_svmm_part(struct nouveau_svmm *svmm, u64 inst)
204 {
205 	struct nouveau_ivmm *ivmm;
206 	if (svmm) {
207 		mutex_lock(&svmm->vmm->cli->drm->svm->mutex);
208 		ivmm = nouveau_ivmm_find(svmm->vmm->cli->drm->svm, inst);
209 		if (ivmm) {
210 			list_del(&ivmm->head);
211 			kfree(ivmm);
212 		}
213 		mutex_unlock(&svmm->vmm->cli->drm->svm->mutex);
214 	}
215 }
216 
217 /* Link channel instance to SVMM. */
218 int
219 nouveau_svmm_join(struct nouveau_svmm *svmm, u64 inst)
220 {
221 	struct nouveau_ivmm *ivmm;
222 	if (svmm) {
223 		if (!(ivmm = kmalloc(sizeof(*ivmm), GFP_KERNEL)))
224 			return -ENOMEM;
225 		ivmm->svmm = svmm;
226 		ivmm->inst = inst;
227 
228 		mutex_lock(&svmm->vmm->cli->drm->svm->mutex);
229 		list_add(&ivmm->head, &svmm->vmm->cli->drm->svm->inst);
230 		mutex_unlock(&svmm->vmm->cli->drm->svm->mutex);
231 	}
232 	return 0;
233 }
234 
235 /* Invalidate SVMM address-range on GPU. */
236 static void
237 nouveau_svmm_invalidate(struct nouveau_svmm *svmm, u64 start, u64 limit)
238 {
239 	if (limit > start) {
240 		bool super = svmm->vmm->vmm.object.client->super;
241 		svmm->vmm->vmm.object.client->super = true;
242 		nvif_object_mthd(&svmm->vmm->vmm.object, NVIF_VMM_V0_PFNCLR,
243 				 &(struct nvif_vmm_pfnclr_v0) {
244 					.addr = start,
245 					.size = limit - start,
246 				 }, sizeof(struct nvif_vmm_pfnclr_v0));
247 		svmm->vmm->vmm.object.client->super = super;
248 	}
249 }
250 
251 static int
252 nouveau_svmm_invalidate_range_start(struct mmu_notifier *mn,
253 				    const struct mmu_notifier_range *update)
254 {
255 	struct nouveau_svmm *svmm =
256 		container_of(mn, struct nouveau_svmm, notifier);
257 	unsigned long start = update->start;
258 	unsigned long limit = update->end;
259 
260 	if (!mmu_notifier_range_blockable(update))
261 		return -EAGAIN;
262 
263 	SVMM_DBG(svmm, "invalidate %016lx-%016lx", start, limit);
264 
265 	mutex_lock(&svmm->mutex);
266 	if (unlikely(!svmm->vmm))
267 		goto out;
268 
269 	if (limit > svmm->unmanaged.start && start < svmm->unmanaged.limit) {
270 		if (start < svmm->unmanaged.start) {
271 			nouveau_svmm_invalidate(svmm, start,
272 						svmm->unmanaged.limit);
273 		}
274 		start = svmm->unmanaged.limit;
275 	}
276 
277 	nouveau_svmm_invalidate(svmm, start, limit);
278 
279 out:
280 	mutex_unlock(&svmm->mutex);
281 	return 0;
282 }
283 
284 static void nouveau_svmm_free_notifier(struct mmu_notifier *mn)
285 {
286 	kfree(container_of(mn, struct nouveau_svmm, notifier));
287 }
288 
289 static const struct mmu_notifier_ops nouveau_mn_ops = {
290 	.invalidate_range_start = nouveau_svmm_invalidate_range_start,
291 	.free_notifier = nouveau_svmm_free_notifier,
292 };
293 
294 void
295 nouveau_svmm_fini(struct nouveau_svmm **psvmm)
296 {
297 	struct nouveau_svmm *svmm = *psvmm;
298 	if (svmm) {
299 		mutex_lock(&svmm->mutex);
300 		svmm->vmm = NULL;
301 		mutex_unlock(&svmm->mutex);
302 		mmu_notifier_put(&svmm->notifier);
303 		*psvmm = NULL;
304 	}
305 }
306 
307 int
308 nouveau_svmm_init(struct drm_device *dev, void *data,
309 		  struct drm_file *file_priv)
310 {
311 	struct nouveau_cli *cli = nouveau_cli(file_priv);
312 	struct nouveau_svmm *svmm;
313 	struct drm_nouveau_svm_init *args = data;
314 	int ret;
315 
316 	/* Allocate tracking for SVM-enabled VMM. */
317 	if (!(svmm = kzalloc(sizeof(*svmm), GFP_KERNEL)))
318 		return -ENOMEM;
319 	svmm->vmm = &cli->svm;
320 	svmm->unmanaged.start = args->unmanaged_addr;
321 	svmm->unmanaged.limit = args->unmanaged_addr + args->unmanaged_size;
322 	mutex_init(&svmm->mutex);
323 
324 	/* Check that SVM isn't already enabled for the client. */
325 	mutex_lock(&cli->mutex);
326 	if (cli->svm.cli) {
327 		ret = -EBUSY;
328 		goto out_free;
329 	}
330 
331 	/* Allocate a new GPU VMM that can support SVM (managed by the
332 	 * client, with replayable faults enabled).
333 	 *
334 	 * All future channel/memory allocations will make use of this
335 	 * VMM instead of the standard one.
336 	 */
337 	ret = nvif_vmm_init(&cli->mmu, cli->vmm.vmm.object.oclass, true,
338 			    args->unmanaged_addr, args->unmanaged_size,
339 			    &(struct gp100_vmm_v0) {
340 				.fault_replay = true,
341 			    }, sizeof(struct gp100_vmm_v0), &cli->svm.vmm);
342 	if (ret)
343 		goto out_free;
344 
345 	down_write(&current->mm->mmap_sem);
346 	svmm->notifier.ops = &nouveau_mn_ops;
347 	ret = __mmu_notifier_register(&svmm->notifier, current->mm);
348 	if (ret)
349 		goto out_mm_unlock;
350 	/* Note, ownership of svmm transfers to mmu_notifier */
351 
352 	cli->svm.svmm = svmm;
353 	cli->svm.cli = cli;
354 	up_write(&current->mm->mmap_sem);
355 	mutex_unlock(&cli->mutex);
356 	return 0;
357 
358 out_mm_unlock:
359 	up_write(&current->mm->mmap_sem);
360 out_free:
361 	mutex_unlock(&cli->mutex);
362 	kfree(svmm);
363 	return ret;
364 }
365 
366 static const u64
367 nouveau_svm_pfn_flags[HMM_PFN_FLAG_MAX] = {
368 	[HMM_PFN_VALID         ] = NVIF_VMM_PFNMAP_V0_V,
369 	[HMM_PFN_WRITE         ] = NVIF_VMM_PFNMAP_V0_W,
370 };
371 
372 static const u64
373 nouveau_svm_pfn_values[HMM_PFN_VALUE_MAX] = {
374 	[HMM_PFN_ERROR  ] = ~NVIF_VMM_PFNMAP_V0_V,
375 	[HMM_PFN_NONE   ] =  NVIF_VMM_PFNMAP_V0_NONE,
376 	[HMM_PFN_SPECIAL] = ~NVIF_VMM_PFNMAP_V0_V,
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 int nouveau_range_fault(struct nouveau_svmm *svmm,
517 			       struct nouveau_drm *drm, void *data, u32 size,
518 			       u64 *pfns, struct svm_notifier *notifier)
519 {
520 	unsigned long timeout =
521 		jiffies + msecs_to_jiffies(HMM_RANGE_DEFAULT_TIMEOUT);
522 	/* Have HMM fault pages within the fault window to the GPU. */
523 	struct hmm_range range = {
524 		.notifier = &notifier->notifier,
525 		.start = notifier->notifier.interval_tree.start,
526 		.end = notifier->notifier.interval_tree.last + 1,
527 		.pfns = pfns,
528 		.flags = nouveau_svm_pfn_flags,
529 		.values = nouveau_svm_pfn_values,
530 		.pfn_shift = NVIF_VMM_PFNMAP_V0_ADDR_SHIFT,
531 	};
532 	struct mm_struct *mm = notifier->notifier.mm;
533 	long ret;
534 
535 	while (true) {
536 		if (time_after(jiffies, timeout))
537 			return -EBUSY;
538 
539 		range.notifier_seq = mmu_interval_read_begin(range.notifier);
540 		range.default_flags = 0;
541 		range.pfn_flags_mask = -1UL;
542 		down_read(&mm->mmap_sem);
543 		ret = hmm_range_fault(&range);
544 		up_read(&mm->mmap_sem);
545 		if (ret <= 0) {
546 			if (ret == 0 || ret == -EBUSY)
547 				continue;
548 			return ret;
549 		}
550 
551 		mutex_lock(&svmm->mutex);
552 		if (mmu_interval_read_retry(range.notifier,
553 					    range.notifier_seq)) {
554 			mutex_unlock(&svmm->mutex);
555 			continue;
556 		}
557 		break;
558 	}
559 
560 	nouveau_dmem_convert_pfn(drm, &range);
561 
562 	svmm->vmm->vmm.object.client->super = true;
563 	ret = nvif_object_ioctl(&svmm->vmm->vmm.object, data, size, NULL);
564 	svmm->vmm->vmm.object.client->super = false;
565 	mutex_unlock(&svmm->mutex);
566 
567 	return ret;
568 }
569 
570 static int
571 nouveau_svm_fault(struct nvif_notify *notify)
572 {
573 	struct nouveau_svm_fault_buffer *buffer =
574 		container_of(notify, typeof(*buffer), notify);
575 	struct nouveau_svm *svm =
576 		container_of(buffer, typeof(*svm), buffer[buffer->id]);
577 	struct nvif_object *device = &svm->drm->client.device.object;
578 	struct nouveau_svmm *svmm;
579 	struct {
580 		struct {
581 			struct nvif_ioctl_v0 i;
582 			struct nvif_ioctl_mthd_v0 m;
583 			struct nvif_vmm_pfnmap_v0 p;
584 		} i;
585 		u64 phys[16];
586 	} args;
587 	struct vm_area_struct *vma;
588 	u64 inst, start, limit;
589 	int fi, fn, pi, fill;
590 	int replay = 0, ret;
591 
592 	/* Parse available fault buffer entries into a cache, and update
593 	 * the GET pointer so HW can reuse the entries.
594 	 */
595 	SVM_DBG(svm, "fault handler");
596 	if (buffer->get == buffer->put) {
597 		buffer->put = nvif_rd32(device, buffer->putaddr);
598 		buffer->get = nvif_rd32(device, buffer->getaddr);
599 		if (buffer->get == buffer->put)
600 			return NVIF_NOTIFY_KEEP;
601 	}
602 	buffer->fault_nr = 0;
603 
604 	SVM_DBG(svm, "get %08x put %08x", buffer->get, buffer->put);
605 	while (buffer->get != buffer->put) {
606 		nouveau_svm_fault_cache(svm, buffer, buffer->get * 0x20);
607 		if (++buffer->get == buffer->entries)
608 			buffer->get = 0;
609 	}
610 	nvif_wr32(device, buffer->getaddr, buffer->get);
611 	SVM_DBG(svm, "%d fault(s) pending", buffer->fault_nr);
612 
613 	/* Sort parsed faults by instance pointer to prevent unnecessary
614 	 * instance to SVMM translations, followed by address and access
615 	 * type to reduce the amount of work when handling the faults.
616 	 */
617 	sort(buffer->fault, buffer->fault_nr, sizeof(*buffer->fault),
618 	     nouveau_svm_fault_cmp, NULL);
619 
620 	/* Lookup SVMM structure for each unique instance pointer. */
621 	mutex_lock(&svm->mutex);
622 	for (fi = 0, svmm = NULL; fi < buffer->fault_nr; fi++) {
623 		if (!svmm || buffer->fault[fi]->inst != inst) {
624 			struct nouveau_ivmm *ivmm =
625 				nouveau_ivmm_find(svm, buffer->fault[fi]->inst);
626 			svmm = ivmm ? ivmm->svmm : NULL;
627 			inst = buffer->fault[fi]->inst;
628 			SVM_DBG(svm, "inst %016llx -> svm-%p", inst, svmm);
629 		}
630 		buffer->fault[fi]->svmm = svmm;
631 	}
632 	mutex_unlock(&svm->mutex);
633 
634 	/* Process list of faults. */
635 	args.i.i.version = 0;
636 	args.i.i.type = NVIF_IOCTL_V0_MTHD;
637 	args.i.m.version = 0;
638 	args.i.m.method = NVIF_VMM_V0_PFNMAP;
639 	args.i.p.version = 0;
640 
641 	for (fi = 0; fn = fi + 1, fi < buffer->fault_nr; fi = fn) {
642 		struct svm_notifier notifier;
643 		struct mm_struct *mm;
644 
645 		/* Cancel any faults from non-SVM channels. */
646 		if (!(svmm = buffer->fault[fi]->svmm)) {
647 			nouveau_svm_fault_cancel_fault(svm, buffer->fault[fi]);
648 			continue;
649 		}
650 		SVMM_DBG(svmm, "addr %016llx", buffer->fault[fi]->addr);
651 
652 		/* We try and group handling of faults within a small
653 		 * window into a single update.
654 		 */
655 		start = buffer->fault[fi]->addr;
656 		limit = start + (ARRAY_SIZE(args.phys) << PAGE_SHIFT);
657 		if (start < svmm->unmanaged.limit)
658 			limit = min_t(u64, limit, svmm->unmanaged.start);
659 		else
660 		if (limit > svmm->unmanaged.start)
661 			start = max_t(u64, start, svmm->unmanaged.limit);
662 		SVMM_DBG(svmm, "wndw %016llx-%016llx", start, limit);
663 
664 		mm = svmm->notifier.mm;
665 		if (!mmget_not_zero(mm)) {
666 			nouveau_svm_fault_cancel_fault(svm, buffer->fault[fi]);
667 			continue;
668 		}
669 
670 		/* Intersect fault window with the CPU VMA, cancelling
671 		 * the fault if the address is invalid.
672 		 */
673 		down_read(&mm->mmap_sem);
674 		vma = find_vma_intersection(mm, start, limit);
675 		if (!vma) {
676 			SVMM_ERR(svmm, "wndw %016llx-%016llx", start, limit);
677 			up_read(&mm->mmap_sem);
678 			mmput(mm);
679 			nouveau_svm_fault_cancel_fault(svm, buffer->fault[fi]);
680 			continue;
681 		}
682 		start = max_t(u64, start, vma->vm_start);
683 		limit = min_t(u64, limit, vma->vm_end);
684 		up_read(&mm->mmap_sem);
685 		SVMM_DBG(svmm, "wndw %016llx-%016llx", start, limit);
686 
687 		if (buffer->fault[fi]->addr != start) {
688 			SVMM_ERR(svmm, "addr %016llx", buffer->fault[fi]->addr);
689 			mmput(mm);
690 			nouveau_svm_fault_cancel_fault(svm, buffer->fault[fi]);
691 			continue;
692 		}
693 
694 		/* Prepare the GPU-side update of all pages within the
695 		 * fault window, determining required pages and access
696 		 * permissions based on pending faults.
697 		 */
698 		args.i.p.page = PAGE_SHIFT;
699 		args.i.p.addr = start;
700 		for (fn = fi, pi = 0;;) {
701 			/* Determine required permissions based on GPU fault
702 			 * access flags.
703 			 *XXX: atomic?
704 			 */
705 			if (buffer->fault[fn]->access != 0 /* READ. */ &&
706 			    buffer->fault[fn]->access != 3 /* PREFETCH. */) {
707 				args.phys[pi++] = NVIF_VMM_PFNMAP_V0_V |
708 						  NVIF_VMM_PFNMAP_V0_W;
709 			} else {
710 				args.phys[pi++] = NVIF_VMM_PFNMAP_V0_V;
711 			}
712 			args.i.p.size = pi << PAGE_SHIFT;
713 
714 			/* It's okay to skip over duplicate addresses from the
715 			 * same SVMM as faults are ordered by access type such
716 			 * that only the first one needs to be handled.
717 			 *
718 			 * ie. WRITE faults appear first, thus any handling of
719 			 * pending READ faults will already be satisfied.
720 			 */
721 			while (++fn < buffer->fault_nr &&
722 			       buffer->fault[fn]->svmm == svmm &&
723 			       buffer->fault[fn    ]->addr ==
724 			       buffer->fault[fn - 1]->addr);
725 
726 			/* If the next fault is outside the window, or all GPU
727 			 * faults have been dealt with, we're done here.
728 			 */
729 			if (fn >= buffer->fault_nr ||
730 			    buffer->fault[fn]->svmm != svmm ||
731 			    buffer->fault[fn]->addr >= limit)
732 				break;
733 
734 			/* Fill in the gap between this fault and the next. */
735 			fill = (buffer->fault[fn    ]->addr -
736 				buffer->fault[fn - 1]->addr) >> PAGE_SHIFT;
737 			while (--fill)
738 				args.phys[pi++] = NVIF_VMM_PFNMAP_V0_NONE;
739 		}
740 
741 		SVMM_DBG(svmm, "wndw %016llx-%016llx covering %d fault(s)",
742 			 args.i.p.addr,
743 			 args.i.p.addr + args.i.p.size, fn - fi);
744 
745 		notifier.svmm = svmm;
746 		ret = mmu_interval_notifier_insert(&notifier.notifier,
747 						   svmm->notifier.mm,
748 						   args.i.p.addr, args.i.p.size,
749 						   &nouveau_svm_mni_ops);
750 		if (!ret) {
751 			ret = nouveau_range_fault(
752 				svmm, svm->drm, &args,
753 				sizeof(args.i) + pi * sizeof(args.phys[0]),
754 				args.phys, &notifier);
755 			mmu_interval_notifier_remove(&notifier.notifier);
756 		}
757 		mmput(mm);
758 
759 		/* Cancel any faults in the window whose pages didn't manage
760 		 * to keep their valid bit, or stay writeable when required.
761 		 *
762 		 * If handling failed completely, cancel all faults.
763 		 */
764 		while (fi < fn) {
765 			struct nouveau_svm_fault *fault = buffer->fault[fi++];
766 			pi = (fault->addr - args.i.p.addr) >> PAGE_SHIFT;
767 			if (ret ||
768 			     !(args.phys[pi] & NVIF_VMM_PFNMAP_V0_V) ||
769 			    (!(args.phys[pi] & NVIF_VMM_PFNMAP_V0_W) &&
770 			     fault->access != 0 && fault->access != 3)) {
771 				nouveau_svm_fault_cancel_fault(svm, fault);
772 				continue;
773 			}
774 			replay++;
775 		}
776 	}
777 
778 	/* Issue fault replay to the GPU. */
779 	if (replay)
780 		nouveau_svm_fault_replay(svm);
781 	return NVIF_NOTIFY_KEEP;
782 }
783 
784 static void
785 nouveau_svm_fault_buffer_fini(struct nouveau_svm *svm, int id)
786 {
787 	struct nouveau_svm_fault_buffer *buffer = &svm->buffer[id];
788 	nvif_notify_put(&buffer->notify);
789 }
790 
791 static int
792 nouveau_svm_fault_buffer_init(struct nouveau_svm *svm, int id)
793 {
794 	struct nouveau_svm_fault_buffer *buffer = &svm->buffer[id];
795 	struct nvif_object *device = &svm->drm->client.device.object;
796 	buffer->get = nvif_rd32(device, buffer->getaddr);
797 	buffer->put = nvif_rd32(device, buffer->putaddr);
798 	SVM_DBG(svm, "get %08x put %08x (init)", buffer->get, buffer->put);
799 	return nvif_notify_get(&buffer->notify);
800 }
801 
802 static void
803 nouveau_svm_fault_buffer_dtor(struct nouveau_svm *svm, int id)
804 {
805 	struct nouveau_svm_fault_buffer *buffer = &svm->buffer[id];
806 	int i;
807 
808 	if (buffer->fault) {
809 		for (i = 0; buffer->fault[i] && i < buffer->entries; i++)
810 			kfree(buffer->fault[i]);
811 		kvfree(buffer->fault);
812 	}
813 
814 	nouveau_svm_fault_buffer_fini(svm, id);
815 
816 	nvif_notify_fini(&buffer->notify);
817 	nvif_object_fini(&buffer->object);
818 }
819 
820 static int
821 nouveau_svm_fault_buffer_ctor(struct nouveau_svm *svm, s32 oclass, int id)
822 {
823 	struct nouveau_svm_fault_buffer *buffer = &svm->buffer[id];
824 	struct nouveau_drm *drm = svm->drm;
825 	struct nvif_object *device = &drm->client.device.object;
826 	struct nvif_clb069_v0 args = {};
827 	int ret;
828 
829 	buffer->id = id;
830 
831 	ret = nvif_object_init(device, 0, oclass, &args, sizeof(args),
832 			       &buffer->object);
833 	if (ret < 0) {
834 		SVM_ERR(svm, "Fault buffer allocation failed: %d", ret);
835 		return ret;
836 	}
837 
838 	nvif_object_map(&buffer->object, NULL, 0);
839 	buffer->entries = args.entries;
840 	buffer->getaddr = args.get;
841 	buffer->putaddr = args.put;
842 
843 	ret = nvif_notify_init(&buffer->object, nouveau_svm_fault, true,
844 			       NVB069_V0_NTFY_FAULT, NULL, 0, 0,
845 			       &buffer->notify);
846 	if (ret)
847 		return ret;
848 
849 	buffer->fault = kvzalloc(sizeof(*buffer->fault) * buffer->entries, GFP_KERNEL);
850 	if (!buffer->fault)
851 		return -ENOMEM;
852 
853 	return nouveau_svm_fault_buffer_init(svm, id);
854 }
855 
856 void
857 nouveau_svm_resume(struct nouveau_drm *drm)
858 {
859 	struct nouveau_svm *svm = drm->svm;
860 	if (svm)
861 		nouveau_svm_fault_buffer_init(svm, 0);
862 }
863 
864 void
865 nouveau_svm_suspend(struct nouveau_drm *drm)
866 {
867 	struct nouveau_svm *svm = drm->svm;
868 	if (svm)
869 		nouveau_svm_fault_buffer_fini(svm, 0);
870 }
871 
872 void
873 nouveau_svm_fini(struct nouveau_drm *drm)
874 {
875 	struct nouveau_svm *svm = drm->svm;
876 	if (svm) {
877 		nouveau_svm_fault_buffer_dtor(svm, 0);
878 		kfree(drm->svm);
879 		drm->svm = NULL;
880 	}
881 }
882 
883 void
884 nouveau_svm_init(struct nouveau_drm *drm)
885 {
886 	static const struct nvif_mclass buffers[] = {
887 		{   VOLTA_FAULT_BUFFER_A, 0 },
888 		{ MAXWELL_FAULT_BUFFER_A, 0 },
889 		{}
890 	};
891 	struct nouveau_svm *svm;
892 	int ret;
893 
894 	/* Disable on Volta and newer until channel recovery is fixed,
895 	 * otherwise clients will have a trivial way to trash the GPU
896 	 * for everyone.
897 	 */
898 	if (drm->client.device.info.family > NV_DEVICE_INFO_V0_PASCAL)
899 		return;
900 
901 	if (!(drm->svm = svm = kzalloc(sizeof(*drm->svm), GFP_KERNEL)))
902 		return;
903 
904 	drm->svm->drm = drm;
905 	mutex_init(&drm->svm->mutex);
906 	INIT_LIST_HEAD(&drm->svm->inst);
907 
908 	ret = nvif_mclass(&drm->client.device.object, buffers);
909 	if (ret < 0) {
910 		SVM_DBG(svm, "No supported fault buffer class");
911 		nouveau_svm_fini(drm);
912 		return;
913 	}
914 
915 	ret = nouveau_svm_fault_buffer_ctor(svm, buffers[ret].oclass, 0);
916 	if (ret) {
917 		nouveau_svm_fini(drm);
918 		return;
919 	}
920 
921 	SVM_DBG(svm, "Initialised");
922 }
923