1 /*
2  * Copyright 2017 Advanced Micro Devices, Inc.
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
17  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
18  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
20  * OTHER DEALINGS IN THE SOFTWARE.
21  *
22  */
23 #include "amdgpu_ids.h"
24 
25 #include <linux/idr.h>
26 #include <linux/dma-fence-array.h>
27 
28 
29 #include "amdgpu.h"
30 #include "amdgpu_trace.h"
31 
32 /*
33  * PASID manager
34  *
35  * PASIDs are global address space identifiers that can be shared
36  * between the GPU, an IOMMU and the driver. VMs on different devices
37  * may use the same PASID if they share the same address
38  * space. Therefore PASIDs are allocated using a global IDA. VMs are
39  * looked up from the PASID per amdgpu_device.
40  */
41 static DEFINE_IDA(amdgpu_pasid_ida);
42 
43 /* Helper to free pasid from a fence callback */
44 struct amdgpu_pasid_cb {
45 	struct dma_fence_cb cb;
46 	u32 pasid;
47 };
48 
49 /**
50  * amdgpu_pasid_alloc - Allocate a PASID
51  * @bits: Maximum width of the PASID in bits, must be at least 1
52  *
53  * Allocates a PASID of the given width while keeping smaller PASIDs
54  * available if possible.
55  *
56  * Returns a positive integer on success. Returns %-EINVAL if bits==0.
57  * Returns %-ENOSPC if no PASID was available. Returns %-ENOMEM on
58  * memory allocation failure.
59  */
60 int amdgpu_pasid_alloc(unsigned int bits)
61 {
62 	int pasid = -EINVAL;
63 
64 	for (bits = min(bits, 31U); bits > 0; bits--) {
65 		pasid = ida_simple_get(&amdgpu_pasid_ida,
66 				       1U << (bits - 1), 1U << bits,
67 				       GFP_KERNEL);
68 		if (pasid != -ENOSPC)
69 			break;
70 	}
71 
72 	if (pasid >= 0)
73 		trace_amdgpu_pasid_allocated(pasid);
74 
75 	return pasid;
76 }
77 
78 /**
79  * amdgpu_pasid_free - Free a PASID
80  * @pasid: PASID to free
81  */
82 void amdgpu_pasid_free(u32 pasid)
83 {
84 	trace_amdgpu_pasid_freed(pasid);
85 	ida_simple_remove(&amdgpu_pasid_ida, pasid);
86 }
87 
88 static void amdgpu_pasid_free_cb(struct dma_fence *fence,
89 				 struct dma_fence_cb *_cb)
90 {
91 	struct amdgpu_pasid_cb *cb =
92 		container_of(_cb, struct amdgpu_pasid_cb, cb);
93 
94 	amdgpu_pasid_free(cb->pasid);
95 	dma_fence_put(fence);
96 	kfree(cb);
97 }
98 
99 /**
100  * amdgpu_pasid_free_delayed - free pasid when fences signal
101  *
102  * @resv: reservation object with the fences to wait for
103  * @pasid: pasid to free
104  *
105  * Free the pasid only after all the fences in resv are signaled.
106  */
107 void amdgpu_pasid_free_delayed(struct dma_resv *resv,
108 			       u32 pasid)
109 {
110 	struct amdgpu_pasid_cb *cb;
111 	struct dma_fence *fence;
112 	int r;
113 
114 	r = dma_resv_get_singleton(resv, true, &fence);
115 	if (r)
116 		goto fallback;
117 
118 	if (!fence) {
119 		amdgpu_pasid_free(pasid);
120 		return;
121 	}
122 
123 	cb = kmalloc(sizeof(*cb), GFP_KERNEL);
124 	if (!cb) {
125 		/* Last resort when we are OOM */
126 		dma_fence_wait(fence, false);
127 		dma_fence_put(fence);
128 		amdgpu_pasid_free(pasid);
129 	} else {
130 		cb->pasid = pasid;
131 		if (dma_fence_add_callback(fence, &cb->cb,
132 					   amdgpu_pasid_free_cb))
133 			amdgpu_pasid_free_cb(fence, &cb->cb);
134 	}
135 
136 	return;
137 
138 fallback:
139 	/* Not enough memory for the delayed delete, as last resort
140 	 * block for all the fences to complete.
141 	 */
142 	dma_resv_wait_timeout(resv, true, false, MAX_SCHEDULE_TIMEOUT);
143 	amdgpu_pasid_free(pasid);
144 }
145 
146 /*
147  * VMID manager
148  *
149  * VMIDs are a per VMHUB identifier for page tables handling.
150  */
151 
152 /**
153  * amdgpu_vmid_had_gpu_reset - check if reset occured since last use
154  *
155  * @adev: amdgpu_device pointer
156  * @id: VMID structure
157  *
158  * Check if GPU reset occured since last use of the VMID.
159  */
160 bool amdgpu_vmid_had_gpu_reset(struct amdgpu_device *adev,
161 			       struct amdgpu_vmid *id)
162 {
163 	return id->current_gpu_reset_count !=
164 		atomic_read(&adev->gpu_reset_counter);
165 }
166 
167 /**
168  * amdgpu_vmid_grab_idle - grab idle VMID
169  *
170  * @vm: vm to allocate id for
171  * @ring: ring we want to submit job to
172  * @sync: sync object where we add dependencies
173  * @idle: resulting idle VMID
174  *
175  * Try to find an idle VMID, if none is idle add a fence to wait to the sync
176  * object. Returns -ENOMEM when we are out of memory.
177  */
178 static int amdgpu_vmid_grab_idle(struct amdgpu_vm *vm,
179 				 struct amdgpu_ring *ring,
180 				 struct amdgpu_sync *sync,
181 				 struct amdgpu_vmid **idle)
182 {
183 	struct amdgpu_device *adev = ring->adev;
184 	unsigned vmhub = ring->funcs->vmhub;
185 	struct amdgpu_vmid_mgr *id_mgr = &adev->vm_manager.id_mgr[vmhub];
186 	struct dma_fence **fences;
187 	unsigned i;
188 	int r;
189 
190 	if (ring->vmid_wait && !dma_fence_is_signaled(ring->vmid_wait))
191 		return amdgpu_sync_fence(sync, ring->vmid_wait);
192 
193 	fences = kmalloc_array(id_mgr->num_ids, sizeof(void *), GFP_KERNEL);
194 	if (!fences)
195 		return -ENOMEM;
196 
197 	/* Check if we have an idle VMID */
198 	i = 0;
199 	list_for_each_entry((*idle), &id_mgr->ids_lru, list) {
200 		/* Don't use per engine and per process VMID at the same time */
201 		struct amdgpu_ring *r = adev->vm_manager.concurrent_flush ?
202 			NULL : ring;
203 
204 		fences[i] = amdgpu_sync_peek_fence(&(*idle)->active, r);
205 		if (!fences[i])
206 			break;
207 		++i;
208 	}
209 
210 	/* If we can't find a idle VMID to use, wait till one becomes available */
211 	if (&(*idle)->list == &id_mgr->ids_lru) {
212 		u64 fence_context = adev->vm_manager.fence_context + ring->idx;
213 		unsigned seqno = ++adev->vm_manager.seqno[ring->idx];
214 		struct dma_fence_array *array;
215 		unsigned j;
216 
217 		*idle = NULL;
218 		for (j = 0; j < i; ++j)
219 			dma_fence_get(fences[j]);
220 
221 		array = dma_fence_array_create(i, fences, fence_context,
222 					       seqno, true);
223 		if (!array) {
224 			for (j = 0; j < i; ++j)
225 				dma_fence_put(fences[j]);
226 			kfree(fences);
227 			return -ENOMEM;
228 		}
229 
230 		r = amdgpu_sync_fence(sync, &array->base);
231 		dma_fence_put(ring->vmid_wait);
232 		ring->vmid_wait = &array->base;
233 		return r;
234 	}
235 	kfree(fences);
236 
237 	return 0;
238 }
239 
240 /**
241  * amdgpu_vmid_grab_reserved - try to assign reserved VMID
242  *
243  * @vm: vm to allocate id for
244  * @ring: ring we want to submit job to
245  * @sync: sync object where we add dependencies
246  * @fence: fence protecting ID from reuse
247  * @job: job who wants to use the VMID
248  * @id: resulting VMID
249  *
250  * Try to assign a reserved VMID.
251  */
252 static int amdgpu_vmid_grab_reserved(struct amdgpu_vm *vm,
253 				     struct amdgpu_ring *ring,
254 				     struct amdgpu_sync *sync,
255 				     struct dma_fence *fence,
256 				     struct amdgpu_job *job,
257 				     struct amdgpu_vmid **id)
258 {
259 	struct amdgpu_device *adev = ring->adev;
260 	unsigned vmhub = ring->funcs->vmhub;
261 	uint64_t fence_context = adev->fence_context + ring->idx;
262 	struct dma_fence *updates = sync->last_vm_update;
263 	bool needs_flush = vm->use_cpu_for_update;
264 	int r = 0;
265 
266 	*id = vm->reserved_vmid[vmhub];
267 	if (updates && (*id)->flushed_updates &&
268 	    updates->context == (*id)->flushed_updates->context &&
269 	    !dma_fence_is_later(updates, (*id)->flushed_updates))
270 		updates = NULL;
271 
272 	if ((*id)->owner != vm->immediate.fence_context ||
273 	    job->vm_pd_addr != (*id)->pd_gpu_addr ||
274 	    updates || !(*id)->last_flush ||
275 	    ((*id)->last_flush->context != fence_context &&
276 	     !dma_fence_is_signaled((*id)->last_flush))) {
277 		struct dma_fence *tmp;
278 
279 		/* Don't use per engine and per process VMID at the same time */
280 		if (adev->vm_manager.concurrent_flush)
281 			ring = NULL;
282 
283 		/* to prevent one context starved by another context */
284 		(*id)->pd_gpu_addr = 0;
285 		tmp = amdgpu_sync_peek_fence(&(*id)->active, ring);
286 		if (tmp) {
287 			*id = NULL;
288 			r = amdgpu_sync_fence(sync, tmp);
289 			return r;
290 		}
291 		needs_flush = true;
292 	}
293 
294 	/* Good we can use this VMID. Remember this submission as
295 	* user of the VMID.
296 	*/
297 	r = amdgpu_sync_fence(&(*id)->active, fence);
298 	if (r)
299 		return r;
300 
301 	if (updates) {
302 		dma_fence_put((*id)->flushed_updates);
303 		(*id)->flushed_updates = dma_fence_get(updates);
304 	}
305 	job->vm_needs_flush = needs_flush;
306 	return 0;
307 }
308 
309 /**
310  * amdgpu_vmid_grab_used - try to reuse a VMID
311  *
312  * @vm: vm to allocate id for
313  * @ring: ring we want to submit job to
314  * @sync: sync object where we add dependencies
315  * @fence: fence protecting ID from reuse
316  * @job: job who wants to use the VMID
317  * @id: resulting VMID
318  *
319  * Try to reuse a VMID for this submission.
320  */
321 static int amdgpu_vmid_grab_used(struct amdgpu_vm *vm,
322 				 struct amdgpu_ring *ring,
323 				 struct amdgpu_sync *sync,
324 				 struct dma_fence *fence,
325 				 struct amdgpu_job *job,
326 				 struct amdgpu_vmid **id)
327 {
328 	struct amdgpu_device *adev = ring->adev;
329 	unsigned vmhub = ring->funcs->vmhub;
330 	struct amdgpu_vmid_mgr *id_mgr = &adev->vm_manager.id_mgr[vmhub];
331 	uint64_t fence_context = adev->fence_context + ring->idx;
332 	struct dma_fence *updates = sync->last_vm_update;
333 	int r;
334 
335 	job->vm_needs_flush = vm->use_cpu_for_update;
336 
337 	/* Check if we can use a VMID already assigned to this VM */
338 	list_for_each_entry_reverse((*id), &id_mgr->ids_lru, list) {
339 		bool needs_flush = vm->use_cpu_for_update;
340 		struct dma_fence *flushed;
341 
342 		/* Check all the prerequisites to using this VMID */
343 		if ((*id)->owner != vm->immediate.fence_context)
344 			continue;
345 
346 		if ((*id)->pd_gpu_addr != job->vm_pd_addr)
347 			continue;
348 
349 		if (!(*id)->last_flush ||
350 		    ((*id)->last_flush->context != fence_context &&
351 		     !dma_fence_is_signaled((*id)->last_flush)))
352 			needs_flush = true;
353 
354 		flushed  = (*id)->flushed_updates;
355 		if (updates && (!flushed || dma_fence_is_later(updates, flushed)))
356 			needs_flush = true;
357 
358 		if (needs_flush && !adev->vm_manager.concurrent_flush)
359 			continue;
360 
361 		/* Good, we can use this VMID. Remember this submission as
362 		 * user of the VMID.
363 		 */
364 		r = amdgpu_sync_fence(&(*id)->active, fence);
365 		if (r)
366 			return r;
367 
368 		if (updates && (!flushed || dma_fence_is_later(updates, flushed))) {
369 			dma_fence_put((*id)->flushed_updates);
370 			(*id)->flushed_updates = dma_fence_get(updates);
371 		}
372 
373 		job->vm_needs_flush |= needs_flush;
374 		return 0;
375 	}
376 
377 	*id = NULL;
378 	return 0;
379 }
380 
381 /**
382  * amdgpu_vmid_grab - allocate the next free VMID
383  *
384  * @vm: vm to allocate id for
385  * @ring: ring we want to submit job to
386  * @sync: sync object where we add dependencies
387  * @fence: fence protecting ID from reuse
388  * @job: job who wants to use the VMID
389  *
390  * Allocate an id for the vm, adding fences to the sync obj as necessary.
391  */
392 int amdgpu_vmid_grab(struct amdgpu_vm *vm, struct amdgpu_ring *ring,
393 		     struct amdgpu_sync *sync, struct dma_fence *fence,
394 		     struct amdgpu_job *job)
395 {
396 	struct amdgpu_device *adev = ring->adev;
397 	unsigned vmhub = ring->funcs->vmhub;
398 	struct amdgpu_vmid_mgr *id_mgr = &adev->vm_manager.id_mgr[vmhub];
399 	struct amdgpu_vmid *idle = NULL;
400 	struct amdgpu_vmid *id = NULL;
401 	int r = 0;
402 
403 	mutex_lock(&id_mgr->lock);
404 	r = amdgpu_vmid_grab_idle(vm, ring, sync, &idle);
405 	if (r || !idle)
406 		goto error;
407 
408 	if (vm->reserved_vmid[vmhub]) {
409 		r = amdgpu_vmid_grab_reserved(vm, ring, sync, fence, job, &id);
410 		if (r || !id)
411 			goto error;
412 	} else {
413 		r = amdgpu_vmid_grab_used(vm, ring, sync, fence, job, &id);
414 		if (r)
415 			goto error;
416 
417 		if (!id) {
418 			struct dma_fence *updates = sync->last_vm_update;
419 
420 			/* Still no ID to use? Then use the idle one found earlier */
421 			id = idle;
422 
423 			/* Remember this submission as user of the VMID */
424 			r = amdgpu_sync_fence(&id->active, fence);
425 			if (r)
426 				goto error;
427 
428 			dma_fence_put(id->flushed_updates);
429 			id->flushed_updates = dma_fence_get(updates);
430 			job->vm_needs_flush = true;
431 		}
432 
433 		list_move_tail(&id->list, &id_mgr->ids_lru);
434 	}
435 
436 	id->pd_gpu_addr = job->vm_pd_addr;
437 	id->owner = vm->immediate.fence_context;
438 
439 	if (job->vm_needs_flush) {
440 		dma_fence_put(id->last_flush);
441 		id->last_flush = NULL;
442 	}
443 	job->vmid = id - id_mgr->ids;
444 	job->pasid = vm->pasid;
445 	trace_amdgpu_vm_grab_id(vm, ring, job);
446 
447 error:
448 	mutex_unlock(&id_mgr->lock);
449 	return r;
450 }
451 
452 int amdgpu_vmid_alloc_reserved(struct amdgpu_device *adev,
453 			       struct amdgpu_vm *vm,
454 			       unsigned vmhub)
455 {
456 	struct amdgpu_vmid_mgr *id_mgr;
457 	struct amdgpu_vmid *idle;
458 	int r = 0;
459 
460 	id_mgr = &adev->vm_manager.id_mgr[vmhub];
461 	mutex_lock(&id_mgr->lock);
462 	if (vm->reserved_vmid[vmhub])
463 		goto unlock;
464 	if (atomic_inc_return(&id_mgr->reserved_vmid_num) >
465 	    AMDGPU_VM_MAX_RESERVED_VMID) {
466 		DRM_ERROR("Over limitation of reserved vmid\n");
467 		atomic_dec(&id_mgr->reserved_vmid_num);
468 		r = -EINVAL;
469 		goto unlock;
470 	}
471 	/* Select the first entry VMID */
472 	idle = list_first_entry(&id_mgr->ids_lru, struct amdgpu_vmid, list);
473 	list_del_init(&idle->list);
474 	vm->reserved_vmid[vmhub] = idle;
475 	mutex_unlock(&id_mgr->lock);
476 
477 	return 0;
478 unlock:
479 	mutex_unlock(&id_mgr->lock);
480 	return r;
481 }
482 
483 void amdgpu_vmid_free_reserved(struct amdgpu_device *adev,
484 			       struct amdgpu_vm *vm,
485 			       unsigned vmhub)
486 {
487 	struct amdgpu_vmid_mgr *id_mgr = &adev->vm_manager.id_mgr[vmhub];
488 
489 	mutex_lock(&id_mgr->lock);
490 	if (vm->reserved_vmid[vmhub]) {
491 		list_add(&vm->reserved_vmid[vmhub]->list,
492 			&id_mgr->ids_lru);
493 		vm->reserved_vmid[vmhub] = NULL;
494 		atomic_dec(&id_mgr->reserved_vmid_num);
495 	}
496 	mutex_unlock(&id_mgr->lock);
497 }
498 
499 /**
500  * amdgpu_vmid_reset - reset VMID to zero
501  *
502  * @adev: amdgpu device structure
503  * @vmhub: vmhub type
504  * @vmid: vmid number to use
505  *
506  * Reset saved GDW, GWS and OA to force switch on next flush.
507  */
508 void amdgpu_vmid_reset(struct amdgpu_device *adev, unsigned vmhub,
509 		       unsigned vmid)
510 {
511 	struct amdgpu_vmid_mgr *id_mgr = &adev->vm_manager.id_mgr[vmhub];
512 	struct amdgpu_vmid *id = &id_mgr->ids[vmid];
513 
514 	mutex_lock(&id_mgr->lock);
515 	id->owner = 0;
516 	id->gds_base = 0;
517 	id->gds_size = 0;
518 	id->gws_base = 0;
519 	id->gws_size = 0;
520 	id->oa_base = 0;
521 	id->oa_size = 0;
522 	mutex_unlock(&id_mgr->lock);
523 }
524 
525 /**
526  * amdgpu_vmid_reset_all - reset VMID to zero
527  *
528  * @adev: amdgpu device structure
529  *
530  * Reset VMID to force flush on next use
531  */
532 void amdgpu_vmid_reset_all(struct amdgpu_device *adev)
533 {
534 	unsigned i, j;
535 
536 	for (i = 0; i < AMDGPU_MAX_VMHUBS; ++i) {
537 		struct amdgpu_vmid_mgr *id_mgr =
538 			&adev->vm_manager.id_mgr[i];
539 
540 		for (j = 1; j < id_mgr->num_ids; ++j)
541 			amdgpu_vmid_reset(adev, i, j);
542 	}
543 }
544 
545 /**
546  * amdgpu_vmid_mgr_init - init the VMID manager
547  *
548  * @adev: amdgpu_device pointer
549  *
550  * Initialize the VM manager structures
551  */
552 void amdgpu_vmid_mgr_init(struct amdgpu_device *adev)
553 {
554 	unsigned i, j;
555 
556 	for (i = 0; i < AMDGPU_MAX_VMHUBS; ++i) {
557 		struct amdgpu_vmid_mgr *id_mgr =
558 			&adev->vm_manager.id_mgr[i];
559 
560 		mutex_init(&id_mgr->lock);
561 		INIT_LIST_HEAD(&id_mgr->ids_lru);
562 		atomic_set(&id_mgr->reserved_vmid_num, 0);
563 
564 		/* manage only VMIDs not used by KFD */
565 		id_mgr->num_ids = adev->vm_manager.first_kfd_vmid;
566 
567 		/* skip over VMID 0, since it is the system VM */
568 		for (j = 1; j < id_mgr->num_ids; ++j) {
569 			amdgpu_vmid_reset(adev, i, j);
570 			amdgpu_sync_create(&id_mgr->ids[j].active);
571 			list_add_tail(&id_mgr->ids[j].list, &id_mgr->ids_lru);
572 		}
573 	}
574 }
575 
576 /**
577  * amdgpu_vmid_mgr_fini - cleanup VM manager
578  *
579  * @adev: amdgpu_device pointer
580  *
581  * Cleanup the VM manager and free resources.
582  */
583 void amdgpu_vmid_mgr_fini(struct amdgpu_device *adev)
584 {
585 	unsigned i, j;
586 
587 	for (i = 0; i < AMDGPU_MAX_VMHUBS; ++i) {
588 		struct amdgpu_vmid_mgr *id_mgr =
589 			&adev->vm_manager.id_mgr[i];
590 
591 		mutex_destroy(&id_mgr->lock);
592 		for (j = 0; j < AMDGPU_NUM_VMID; ++j) {
593 			struct amdgpu_vmid *id = &id_mgr->ids[j];
594 
595 			amdgpu_sync_free(&id->active);
596 			dma_fence_put(id->flushed_updates);
597 			dma_fence_put(id->last_flush);
598 			dma_fence_put(id->pasid_mapping);
599 		}
600 	}
601 }
602