1 /*
2  * Copyright 2008 Advanced Micro Devices, Inc.
3  * Copyright 2008 Red Hat Inc.
4  * Copyright 2009 Jerome Glisse.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
19  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
20  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22  * OTHER DEALINGS IN THE SOFTWARE.
23  *
24  * Authors: Dave Airlie
25  *          Alex Deucher
26  *          Jerome Glisse
27  *          Christian König
28  */
29 #include <linux/seq_file.h>
30 #include <linux/slab.h>
31 #include <linux/uaccess.h>
32 #include <linux/debugfs.h>
33 
34 #include <drm/amdgpu_drm.h>
35 #include "amdgpu.h"
36 #include "atom.h"
37 
38 /*
39  * Rings
40  * Most engines on the GPU are fed via ring buffers.  Ring
41  * buffers are areas of GPU accessible memory that the host
42  * writes commands into and the GPU reads commands out of.
43  * There is a rptr (read pointer) that determines where the
44  * GPU is currently reading, and a wptr (write pointer)
45  * which determines where the host has written.  When the
46  * pointers are equal, the ring is idle.  When the host
47  * writes commands to the ring buffer, it increments the
48  * wptr.  The GPU then starts fetching commands and executes
49  * them until the pointers are equal again.
50  */
51 static int amdgpu_debugfs_ring_init(struct amdgpu_device *adev,
52 				    struct amdgpu_ring *ring);
53 static void amdgpu_debugfs_ring_fini(struct amdgpu_ring *ring);
54 
55 /**
56  * amdgpu_ring_alloc - allocate space on the ring buffer
57  *
58  * @adev: amdgpu_device pointer
59  * @ring: amdgpu_ring structure holding ring information
60  * @ndw: number of dwords to allocate in the ring buffer
61  *
62  * Allocate @ndw dwords in the ring buffer (all asics).
63  * Returns 0 on success, error on failure.
64  */
65 int amdgpu_ring_alloc(struct amdgpu_ring *ring, unsigned ndw)
66 {
67 	/* Align requested size with padding so unlock_commit can
68 	 * pad safely */
69 	ndw = (ndw + ring->funcs->align_mask) & ~ring->funcs->align_mask;
70 
71 	/* Make sure we aren't trying to allocate more space
72 	 * than the maximum for one submission
73 	 */
74 	if (WARN_ON_ONCE(ndw > ring->max_dw))
75 		return -ENOMEM;
76 
77 	ring->count_dw = ndw;
78 	ring->wptr_old = ring->wptr;
79 
80 	if (ring->funcs->begin_use)
81 		ring->funcs->begin_use(ring);
82 
83 	return 0;
84 }
85 
86 /** amdgpu_ring_insert_nop - insert NOP packets
87  *
88  * @ring: amdgpu_ring structure holding ring information
89  * @count: the number of NOP packets to insert
90  *
91  * This is the generic insert_nop function for rings except SDMA
92  */
93 void amdgpu_ring_insert_nop(struct amdgpu_ring *ring, uint32_t count)
94 {
95 	int i;
96 
97 	for (i = 0; i < count; i++)
98 		amdgpu_ring_write(ring, ring->funcs->nop);
99 }
100 
101 /** amdgpu_ring_generic_pad_ib - pad IB with NOP packets
102  *
103  * @ring: amdgpu_ring structure holding ring information
104  * @ib: IB to add NOP packets to
105  *
106  * This is the generic pad_ib function for rings except SDMA
107  */
108 void amdgpu_ring_generic_pad_ib(struct amdgpu_ring *ring, struct amdgpu_ib *ib)
109 {
110 	while (ib->length_dw & ring->funcs->align_mask)
111 		ib->ptr[ib->length_dw++] = ring->funcs->nop;
112 }
113 
114 /**
115  * amdgpu_ring_commit - tell the GPU to execute the new
116  * commands on the ring buffer
117  *
118  * @adev: amdgpu_device pointer
119  * @ring: amdgpu_ring structure holding ring information
120  *
121  * Update the wptr (write pointer) to tell the GPU to
122  * execute new commands on the ring buffer (all asics).
123  */
124 void amdgpu_ring_commit(struct amdgpu_ring *ring)
125 {
126 	uint32_t count;
127 
128 	/* We pad to match fetch size */
129 	count = ring->funcs->align_mask + 1 -
130 		(ring->wptr & ring->funcs->align_mask);
131 	count %= ring->funcs->align_mask + 1;
132 	ring->funcs->insert_nop(ring, count);
133 
134 	mb();
135 	amdgpu_ring_set_wptr(ring);
136 
137 	if (ring->funcs->end_use)
138 		ring->funcs->end_use(ring);
139 }
140 
141 /**
142  * amdgpu_ring_undo - reset the wptr
143  *
144  * @ring: amdgpu_ring structure holding ring information
145  *
146  * Reset the driver's copy of the wptr (all asics).
147  */
148 void amdgpu_ring_undo(struct amdgpu_ring *ring)
149 {
150 	ring->wptr = ring->wptr_old;
151 
152 	if (ring->funcs->end_use)
153 		ring->funcs->end_use(ring);
154 }
155 
156 /**
157  * amdgpu_ring_priority_put - restore a ring's priority
158  *
159  * @ring: amdgpu_ring structure holding the information
160  * @priority: target priority
161  *
162  * Release a request for executing at @priority
163  */
164 void amdgpu_ring_priority_put(struct amdgpu_ring *ring,
165 			      enum drm_sched_priority priority)
166 {
167 	int i;
168 
169 	if (!ring->funcs->set_priority)
170 		return;
171 
172 	if (atomic_dec_return(&ring->num_jobs[priority]) > 0)
173 		return;
174 
175 	/* no need to restore if the job is already at the lowest priority */
176 	if (priority == DRM_SCHED_PRIORITY_NORMAL)
177 		return;
178 
179 	mutex_lock(&ring->priority_mutex);
180 	/* something higher prio is executing, no need to decay */
181 	if (ring->priority > priority)
182 		goto out_unlock;
183 
184 	/* decay priority to the next level with a job available */
185 	for (i = priority; i >= DRM_SCHED_PRIORITY_MIN; i--) {
186 		if (i == DRM_SCHED_PRIORITY_NORMAL
187 				|| atomic_read(&ring->num_jobs[i])) {
188 			ring->priority = i;
189 			ring->funcs->set_priority(ring, i);
190 			break;
191 		}
192 	}
193 
194 out_unlock:
195 	mutex_unlock(&ring->priority_mutex);
196 }
197 
198 /**
199  * amdgpu_ring_priority_get - change the ring's priority
200  *
201  * @ring: amdgpu_ring structure holding the information
202  * @priority: target priority
203  *
204  * Request a ring's priority to be raised to @priority (refcounted).
205  */
206 void amdgpu_ring_priority_get(struct amdgpu_ring *ring,
207 			      enum drm_sched_priority priority)
208 {
209 	if (!ring->funcs->set_priority)
210 		return;
211 
212 	if (atomic_inc_return(&ring->num_jobs[priority]) <= 0)
213 		return;
214 
215 	mutex_lock(&ring->priority_mutex);
216 	if (priority <= ring->priority)
217 		goto out_unlock;
218 
219 	ring->priority = priority;
220 	ring->funcs->set_priority(ring, priority);
221 
222 out_unlock:
223 	mutex_unlock(&ring->priority_mutex);
224 }
225 
226 /**
227  * amdgpu_ring_init - init driver ring struct.
228  *
229  * @adev: amdgpu_device pointer
230  * @ring: amdgpu_ring structure holding ring information
231  * @max_ndw: maximum number of dw for ring alloc
232  * @nop: nop packet for this ring
233  *
234  * Initialize the driver information for the selected ring (all asics).
235  * Returns 0 on success, error on failure.
236  */
237 int amdgpu_ring_init(struct amdgpu_device *adev, struct amdgpu_ring *ring,
238 		     unsigned max_dw, struct amdgpu_irq_src *irq_src,
239 		     unsigned irq_type)
240 {
241 	int r, i;
242 	int sched_hw_submission = amdgpu_sched_hw_submission;
243 
244 	/* Set the hw submission limit higher for KIQ because
245 	 * it's used for a number of gfx/compute tasks by both
246 	 * KFD and KGD which may have outstanding fences and
247 	 * it doesn't really use the gpu scheduler anyway;
248 	 * KIQ tasks get submitted directly to the ring.
249 	 */
250 	if (ring->funcs->type == AMDGPU_RING_TYPE_KIQ)
251 		sched_hw_submission = max(sched_hw_submission, 256);
252 	else if (ring == &adev->sdma.instance[0].page)
253 		sched_hw_submission = 256;
254 
255 	if (ring->adev == NULL) {
256 		if (adev->num_rings >= AMDGPU_MAX_RINGS)
257 			return -EINVAL;
258 
259 		ring->adev = adev;
260 		ring->idx = adev->num_rings++;
261 		adev->rings[ring->idx] = ring;
262 		r = amdgpu_fence_driver_init_ring(ring, sched_hw_submission);
263 		if (r)
264 			return r;
265 	}
266 
267 	r = amdgpu_device_wb_get(adev, &ring->rptr_offs);
268 	if (r) {
269 		dev_err(adev->dev, "(%d) ring rptr_offs wb alloc failed\n", r);
270 		return r;
271 	}
272 
273 	r = amdgpu_device_wb_get(adev, &ring->wptr_offs);
274 	if (r) {
275 		dev_err(adev->dev, "(%d) ring wptr_offs wb alloc failed\n", r);
276 		return r;
277 	}
278 
279 	r = amdgpu_device_wb_get(adev, &ring->fence_offs);
280 	if (r) {
281 		dev_err(adev->dev, "(%d) ring fence_offs wb alloc failed\n", r);
282 		return r;
283 	}
284 
285 	r = amdgpu_device_wb_get(adev, &ring->trail_fence_offs);
286 	if (r) {
287 		dev_err(adev->dev,
288 			"(%d) ring trail_fence_offs wb alloc failed\n", r);
289 		return r;
290 	}
291 	ring->trail_fence_gpu_addr =
292 		adev->wb.gpu_addr + (ring->trail_fence_offs * 4);
293 	ring->trail_fence_cpu_addr = &adev->wb.wb[ring->trail_fence_offs];
294 
295 	r = amdgpu_device_wb_get(adev, &ring->cond_exe_offs);
296 	if (r) {
297 		dev_err(adev->dev, "(%d) ring cond_exec_polling wb alloc failed\n", r);
298 		return r;
299 	}
300 	ring->cond_exe_gpu_addr = adev->wb.gpu_addr + (ring->cond_exe_offs * 4);
301 	ring->cond_exe_cpu_addr = &adev->wb.wb[ring->cond_exe_offs];
302 	/* always set cond_exec_polling to CONTINUE */
303 	*ring->cond_exe_cpu_addr = 1;
304 
305 	r = amdgpu_fence_driver_start_ring(ring, irq_src, irq_type);
306 	if (r) {
307 		dev_err(adev->dev, "failed initializing fences (%d).\n", r);
308 		return r;
309 	}
310 
311 	ring->ring_size = roundup_pow_of_two(max_dw * 4 * sched_hw_submission);
312 
313 	ring->buf_mask = (ring->ring_size / 4) - 1;
314 	ring->ptr_mask = ring->funcs->support_64bit_ptrs ?
315 		0xffffffffffffffff : ring->buf_mask;
316 	/* Allocate ring buffer */
317 	if (ring->ring_obj == NULL) {
318 		r = amdgpu_bo_create_kernel(adev, ring->ring_size + ring->funcs->extra_dw, PAGE_SIZE,
319 					    AMDGPU_GEM_DOMAIN_GTT,
320 					    &ring->ring_obj,
321 					    &ring->gpu_addr,
322 					    (void **)&ring->ring);
323 		if (r) {
324 			dev_err(adev->dev, "(%d) ring create failed\n", r);
325 			return r;
326 		}
327 		amdgpu_ring_clear_ring(ring);
328 	}
329 
330 	ring->max_dw = max_dw;
331 	ring->priority = DRM_SCHED_PRIORITY_NORMAL;
332 	mutex_init(&ring->priority_mutex);
333 
334 	for (i = 0; i < DRM_SCHED_PRIORITY_MAX; ++i)
335 		atomic_set(&ring->num_jobs[i], 0);
336 
337 	if (amdgpu_debugfs_ring_init(adev, ring)) {
338 		DRM_ERROR("Failed to register debugfs file for rings !\n");
339 	}
340 
341 	return 0;
342 }
343 
344 /**
345  * amdgpu_ring_fini - tear down the driver ring struct.
346  *
347  * @adev: amdgpu_device pointer
348  * @ring: amdgpu_ring structure holding ring information
349  *
350  * Tear down the driver information for the selected ring (all asics).
351  */
352 void amdgpu_ring_fini(struct amdgpu_ring *ring)
353 {
354 	ring->sched.ready = false;
355 
356 	/* Not to finish a ring which is not initialized */
357 	if (!(ring->adev) || !(ring->adev->rings[ring->idx]))
358 		return;
359 
360 	amdgpu_device_wb_free(ring->adev, ring->rptr_offs);
361 	amdgpu_device_wb_free(ring->adev, ring->wptr_offs);
362 
363 	amdgpu_device_wb_free(ring->adev, ring->cond_exe_offs);
364 	amdgpu_device_wb_free(ring->adev, ring->fence_offs);
365 
366 	amdgpu_bo_free_kernel(&ring->ring_obj,
367 			      &ring->gpu_addr,
368 			      (void **)&ring->ring);
369 
370 	amdgpu_debugfs_ring_fini(ring);
371 
372 	dma_fence_put(ring->vmid_wait);
373 	ring->vmid_wait = NULL;
374 	ring->me = 0;
375 
376 	ring->adev->rings[ring->idx] = NULL;
377 }
378 
379 /**
380  * amdgpu_ring_emit_reg_write_reg_wait_helper - ring helper
381  *
382  * @adev: amdgpu_device pointer
383  * @reg0: register to write
384  * @reg1: register to wait on
385  * @ref: reference value to write/wait on
386  * @mask: mask to wait on
387  *
388  * Helper for rings that don't support write and wait in a
389  * single oneshot packet.
390  */
391 void amdgpu_ring_emit_reg_write_reg_wait_helper(struct amdgpu_ring *ring,
392 						uint32_t reg0, uint32_t reg1,
393 						uint32_t ref, uint32_t mask)
394 {
395 	amdgpu_ring_emit_wreg(ring, reg0, ref);
396 	amdgpu_ring_emit_reg_wait(ring, reg1, mask, mask);
397 }
398 
399 /**
400  * amdgpu_ring_soft_recovery - try to soft recover a ring lockup
401  *
402  * @ring: ring to try the recovery on
403  * @vmid: VMID we try to get going again
404  * @fence: timedout fence
405  *
406  * Tries to get a ring proceeding again when it is stuck.
407  */
408 bool amdgpu_ring_soft_recovery(struct amdgpu_ring *ring, unsigned int vmid,
409 			       struct dma_fence *fence)
410 {
411 	ktime_t deadline = ktime_add_us(ktime_get(), 10000);
412 
413 	if (amdgpu_sriov_vf(ring->adev) || !ring->funcs->soft_recovery || !fence)
414 		return false;
415 
416 	atomic_inc(&ring->adev->gpu_reset_counter);
417 	while (!dma_fence_is_signaled(fence) &&
418 	       ktime_to_ns(ktime_sub(deadline, ktime_get())) > 0)
419 		ring->funcs->soft_recovery(ring, vmid);
420 
421 	return dma_fence_is_signaled(fence);
422 }
423 
424 /*
425  * Debugfs info
426  */
427 #if defined(CONFIG_DEBUG_FS)
428 
429 /* Layout of file is 12 bytes consisting of
430  * - rptr
431  * - wptr
432  * - driver's copy of wptr
433  *
434  * followed by n-words of ring data
435  */
436 static ssize_t amdgpu_debugfs_ring_read(struct file *f, char __user *buf,
437 					size_t size, loff_t *pos)
438 {
439 	struct amdgpu_ring *ring = file_inode(f)->i_private;
440 	int r, i;
441 	uint32_t value, result, early[3];
442 
443 	if (*pos & 3 || size & 3)
444 		return -EINVAL;
445 
446 	result = 0;
447 
448 	if (*pos < 12) {
449 		early[0] = amdgpu_ring_get_rptr(ring) & ring->buf_mask;
450 		early[1] = amdgpu_ring_get_wptr(ring) & ring->buf_mask;
451 		early[2] = ring->wptr & ring->buf_mask;
452 		for (i = *pos / 4; i < 3 && size; i++) {
453 			r = put_user(early[i], (uint32_t *)buf);
454 			if (r)
455 				return r;
456 			buf += 4;
457 			result += 4;
458 			size -= 4;
459 			*pos += 4;
460 		}
461 	}
462 
463 	while (size) {
464 		if (*pos >= (ring->ring_size + 12))
465 			return result;
466 
467 		value = ring->ring[(*pos - 12)/4];
468 		r = put_user(value, (uint32_t*)buf);
469 		if (r)
470 			return r;
471 		buf += 4;
472 		result += 4;
473 		size -= 4;
474 		*pos += 4;
475 	}
476 
477 	return result;
478 }
479 
480 static const struct file_operations amdgpu_debugfs_ring_fops = {
481 	.owner = THIS_MODULE,
482 	.read = amdgpu_debugfs_ring_read,
483 	.llseek = default_llseek
484 };
485 
486 #endif
487 
488 static int amdgpu_debugfs_ring_init(struct amdgpu_device *adev,
489 				    struct amdgpu_ring *ring)
490 {
491 #if defined(CONFIG_DEBUG_FS)
492 	struct drm_minor *minor = adev->ddev->primary;
493 	struct dentry *ent, *root = minor->debugfs_root;
494 	char name[32];
495 
496 	sprintf(name, "amdgpu_ring_%s", ring->name);
497 
498 	ent = debugfs_create_file(name,
499 				  S_IFREG | S_IRUGO, root,
500 				  ring, &amdgpu_debugfs_ring_fops);
501 	if (!ent)
502 		return -ENOMEM;
503 
504 	i_size_write(ent->d_inode, ring->ring_size + 12);
505 	ring->ent = ent;
506 #endif
507 	return 0;
508 }
509 
510 static void amdgpu_debugfs_ring_fini(struct amdgpu_ring *ring)
511 {
512 #if defined(CONFIG_DEBUG_FS)
513 	debugfs_remove(ring->ent);
514 #endif
515 }
516 
517 /**
518  * amdgpu_ring_test_helper - tests ring and set sched readiness status
519  *
520  * @ring: ring to try the recovery on
521  *
522  * Tests ring and set sched readiness status
523  *
524  * Returns 0 on success, error on failure.
525  */
526 int amdgpu_ring_test_helper(struct amdgpu_ring *ring)
527 {
528 	struct amdgpu_device *adev = ring->adev;
529 	int r;
530 
531 	r = amdgpu_ring_test_ring(ring);
532 	if (r)
533 		DRM_DEV_ERROR(adev->dev, "ring %s test failed (%d)\n",
534 			      ring->name, r);
535 	else
536 		DRM_DEV_DEBUG(adev->dev, "ring test on %s succeeded\n",
537 			      ring->name);
538 
539 	ring->sched.ready = !r;
540 	return r;
541 }
542