xref: /linux/drivers/gpu/drm/amd/amdgpu/amdgpu_ring.c (revision f2b96986851203e9c50ca0d13aaa3581ca3e8ebd)
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 "amdgpu_ras_mgr.h"
37 #include "atom.h"
38 
39 /*
40  * Rings
41  * Most engines on the GPU are fed via ring buffers.  Ring
42  * buffers are areas of GPU accessible memory that the host
43  * writes commands into and the GPU reads commands out of.
44  * There is a rptr (read pointer) that determines where the
45  * GPU is currently reading, and a wptr (write pointer)
46  * which determines where the host has written.  When the
47  * pointers are equal, the ring is idle.  When the host
48  * writes commands to the ring buffer, it increments the
49  * wptr.  The GPU then starts fetching commands and executes
50  * them until the pointers are equal again.
51  */
52 
53 /**
54  * amdgpu_ring_max_ibs - Return max IBs that fit in a single submission.
55  *
56  * @type: ring type for which to return the limit.
57  */
58 unsigned int amdgpu_ring_max_ibs(enum amdgpu_ring_type type)
59 {
60 	switch (type) {
61 	case AMDGPU_RING_TYPE_GFX:
62 		/* Need to keep at least 192 on GFX7+ for old radv. */
63 		return 192;
64 	case AMDGPU_RING_TYPE_COMPUTE:
65 		return 125;
66 	case AMDGPU_RING_TYPE_VCN_JPEG:
67 		return 16;
68 	default:
69 		return 49;
70 	}
71 }
72 
73 /**
74  * amdgpu_ring_alloc - allocate space on the ring buffer
75  *
76  * @ring: amdgpu_ring structure holding ring information
77  * @ndw: number of dwords to allocate in the ring buffer
78  *
79  * Allocate @ndw dwords in the ring buffer. The number of dwords should be the
80  * sum of all commands written to the ring.
81  *
82  * Returns:
83  * 0 on success, otherwise -ENOMEM if it tries to allocate more than the
84  * maximum dword allowed for one submission.
85  */
86 int amdgpu_ring_alloc(struct amdgpu_ring *ring, unsigned int ndw)
87 {
88 	/* Align requested size with padding so unlock_commit can
89 	 * pad safely */
90 	ndw = (ndw + ring->funcs->align_mask) & ~ring->funcs->align_mask;
91 
92 	/* Make sure we aren't trying to allocate more space
93 	 * than the maximum for one submission.  Skip for reemit
94 	 * since we may be reemitting several submissions.
95 	 */
96 	if (!ring->reemit) {
97 		if (WARN_ON_ONCE(ndw > ring->max_dw))
98 			return -ENOMEM;
99 	}
100 
101 	ring->count_dw = ndw;
102 	ring->wptr_old = ring->wptr;
103 
104 	if (ring->funcs->begin_use)
105 		ring->funcs->begin_use(ring);
106 
107 	return 0;
108 }
109 
110 /**
111  * amdgpu_ring_insert_nop - insert NOP packets
112  *
113  * @ring: amdgpu_ring structure holding ring information
114  * @count: the number of NOP packets to insert
115  *
116  * This is the generic insert_nop function for rings except SDMA
117  */
118 void amdgpu_ring_insert_nop(struct amdgpu_ring *ring, uint32_t count)
119 {
120 	amdgpu_ring_fill(ring, ring->funcs->nop, count);
121 }
122 
123 /**
124  * amdgpu_ring_generic_pad_ib - pad IB with NOP packets
125  *
126  * @ring: amdgpu_ring structure holding ring information
127  * @ib: IB to add NOP packets to
128  *
129  * This is the generic pad_ib function for rings except SDMA
130  */
131 void amdgpu_ring_generic_pad_ib(struct amdgpu_ring *ring, struct amdgpu_ib *ib)
132 {
133 	u32 align_mask = ring->funcs->align_mask;
134 	u32 count = ib->length_dw & align_mask;
135 
136 	if (count) {
137 		count = align_mask + 1 - count;
138 
139 		memset32(&ib->ptr[ib->length_dw], ring->funcs->nop, count);
140 
141 		ib->length_dw += count;
142 	}
143 }
144 
145 /**
146  * amdgpu_ring_commit - tell the GPU to execute the new
147  * commands on the ring buffer
148  *
149  * @ring: amdgpu_ring structure holding ring information
150  *
151  * Update the wptr (write pointer) to tell the GPU to
152  * execute new commands on the ring buffer (all asics).
153  */
154 void amdgpu_ring_commit(struct amdgpu_ring *ring)
155 {
156 	uint32_t count;
157 
158 	if (ring->count_dw < 0)
159 		drm_err(adev_to_drm(ring->adev), "writing more dwords to the ring than expected!\n");
160 
161 	/* We pad to match fetch size */
162 	count = ring->funcs->align_mask + 1 -
163 		(ring->wptr & ring->funcs->align_mask);
164 	count &= ring->funcs->align_mask;
165 
166 	if (count != 0)
167 		ring->funcs->insert_nop(ring, count);
168 
169 	mb();
170 	amdgpu_ring_set_wptr(ring);
171 
172 	if (ring->funcs->end_use)
173 		ring->funcs->end_use(ring);
174 }
175 
176 /**
177  * amdgpu_ring_undo - reset the wptr
178  *
179  * @ring: amdgpu_ring structure holding ring information
180  *
181  * Reset the driver's copy of the wptr (all asics).
182  */
183 void amdgpu_ring_undo(struct amdgpu_ring *ring)
184 {
185 	ring->wptr = ring->wptr_old;
186 
187 	if (ring->funcs->end_use)
188 		ring->funcs->end_use(ring);
189 }
190 
191 #define amdgpu_ring_get_gpu_addr(ring, offset)				\
192 	 (ring->adev->wb.gpu_addr + offset * 4)
193 
194 #define amdgpu_ring_get_cpu_addr(ring, offset)				\
195 	 (&ring->adev->wb.wb[offset])
196 
197 /**
198  * amdgpu_ring_init - init driver ring struct.
199  *
200  * @adev: amdgpu_device pointer
201  * @ring: amdgpu_ring structure holding ring information
202  * @max_dw: maximum number of dw for ring alloc
203  * @irq_src: interrupt source to use for this ring
204  * @irq_type: interrupt type to use for this ring
205  * @hw_prio: ring priority (NORMAL/HIGH)
206  * @sched_score: optional score atomic shared with other schedulers
207  *
208  * Initialize the driver information for the selected ring (all asics).
209  * Returns 0 on success, error on failure.
210  */
211 int amdgpu_ring_init(struct amdgpu_device *adev, struct amdgpu_ring *ring,
212 		     unsigned int max_dw, struct amdgpu_irq_src *irq_src,
213 		     unsigned int irq_type, unsigned int hw_prio,
214 		     atomic_t *sched_score)
215 {
216 	int r;
217 	int sched_hw_submission = amdgpu_sched_hw_submission;
218 	u32 *num_sched;
219 	u32 hw_ip;
220 	unsigned int max_ibs_dw;
221 
222 	/* Set the hw submission limit higher for KIQ because
223 	 * it's used for a number of gfx/compute tasks by both
224 	 * KFD and KGD which may have outstanding fences and
225 	 * it doesn't really use the gpu scheduler anyway;
226 	 * KIQ tasks get submitted directly to the ring.
227 	 */
228 	if (ring->funcs->type == AMDGPU_RING_TYPE_KIQ)
229 		sched_hw_submission = max(sched_hw_submission, 256);
230 	if (ring->funcs->type == AMDGPU_RING_TYPE_MES)
231 		sched_hw_submission = 8;
232 	else if (ring == &adev->sdma.instance[0].page)
233 		sched_hw_submission = 256;
234 
235 	if (ring->adev == NULL) {
236 		if (adev->num_rings >= AMDGPU_MAX_RINGS)
237 			return -EINVAL;
238 
239 		ring->adev = adev;
240 		ring->num_hw_submission = sched_hw_submission;
241 		ring->sched_score = sched_score;
242 
243 		ring->idx = adev->num_rings++;
244 		adev->rings[ring->idx] = ring;
245 
246 		r = amdgpu_fence_driver_init_ring(ring);
247 		if (r)
248 			return r;
249 	}
250 
251 	r = amdgpu_wb_get(adev, &ring->rptr_offs);
252 	if (r) {
253 		dev_err(adev->dev, "(%d) ring rptr_offs wb alloc failed\n", r);
254 		return r;
255 	}
256 
257 	r = amdgpu_wb_get(adev, &ring->wptr_offs);
258 	if (r) {
259 		dev_err(adev->dev, "(%d) ring wptr_offs wb alloc failed\n", r);
260 		return r;
261 	}
262 
263 	r = amdgpu_wb_get(adev, &ring->fence_offs);
264 	if (r) {
265 		dev_err(adev->dev, "(%d) ring fence_offs wb alloc failed\n", r);
266 		return r;
267 	}
268 
269 	r = amdgpu_wb_get(adev, &ring->trail_fence_offs);
270 	if (r) {
271 		dev_err(adev->dev, "(%d) ring trail_fence_offs wb alloc failed\n", r);
272 		return r;
273 	}
274 
275 	r = amdgpu_wb_get(adev, &ring->cond_exe_offs);
276 	if (r) {
277 		dev_err(adev->dev, "(%d) ring cond_exec_polling wb alloc failed\n", r);
278 		return r;
279 	}
280 
281 	ring->fence_gpu_addr =
282 		amdgpu_ring_get_gpu_addr(ring, ring->fence_offs);
283 	ring->fence_cpu_addr =
284 		amdgpu_ring_get_cpu_addr(ring, ring->fence_offs);
285 
286 	ring->rptr_gpu_addr =
287 		amdgpu_ring_get_gpu_addr(ring, ring->rptr_offs);
288 	ring->rptr_cpu_addr =
289 		amdgpu_ring_get_cpu_addr(ring, ring->rptr_offs);
290 
291 	ring->wptr_gpu_addr =
292 		amdgpu_ring_get_gpu_addr(ring, ring->wptr_offs);
293 	ring->wptr_cpu_addr =
294 		amdgpu_ring_get_cpu_addr(ring, ring->wptr_offs);
295 
296 	ring->trail_fence_gpu_addr =
297 		amdgpu_ring_get_gpu_addr(ring, ring->trail_fence_offs);
298 	ring->trail_fence_cpu_addr =
299 		amdgpu_ring_get_cpu_addr(ring, ring->trail_fence_offs);
300 
301 	ring->cond_exe_gpu_addr =
302 		amdgpu_ring_get_gpu_addr(ring, ring->cond_exe_offs);
303 	ring->cond_exe_cpu_addr =
304 		amdgpu_ring_get_cpu_addr(ring, ring->cond_exe_offs);
305 
306 	/* always set cond_exec_polling to CONTINUE */
307 	*ring->cond_exe_cpu_addr = 1;
308 
309 	if (ring->funcs->type != AMDGPU_RING_TYPE_CPER) {
310 		r = amdgpu_fence_driver_start_ring(ring, irq_src, irq_type);
311 		if (r) {
312 			dev_err(adev->dev, "failed initializing fences (%d).\n", r);
313 			return r;
314 		}
315 
316 		max_ibs_dw = ring->funcs->emit_frame_size +
317 			     amdgpu_ring_max_ibs(ring->funcs->type) * ring->funcs->emit_ib_size;
318 		max_ibs_dw = (max_ibs_dw + ring->funcs->align_mask) & ~ring->funcs->align_mask;
319 
320 		if (WARN_ON(max_ibs_dw > max_dw))
321 			max_dw = max_ibs_dw;
322 
323 		ring->ring_size = roundup_pow_of_two(max_dw * 4 * sched_hw_submission);
324 	} else {
325 		ring->ring_size = roundup_pow_of_two(max_dw * 4);
326 		ring->count_dw = (ring->ring_size - 4) >> 2;
327 		/* ring buffer is empty now */
328 		ring->wptr = *ring->rptr_cpu_addr = 0;
329 	}
330 
331 	ring->buf_mask = (ring->ring_size / 4) - 1;
332 	ring->ptr_mask = ring->funcs->support_64bit_ptrs ?
333 		0xffffffffffffffff : ring->buf_mask;
334 
335 	if (!ring->ring_backup) {
336 		ring->ring_backup = kvzalloc(ring->ring_size, GFP_KERNEL);
337 		if (!ring->ring_backup)
338 			return -ENOMEM;
339 	}
340 
341 	/* Allocate ring buffer */
342 	if (ring->ring_obj == NULL) {
343 		r = amdgpu_bo_create_kernel(adev, ring->ring_size + ring->funcs->extra_bytes,
344 					    PAGE_SIZE,
345 					    AMDGPU_GEM_DOMAIN_GTT,
346 					    &ring->ring_obj,
347 					    &ring->gpu_addr,
348 					    (void **)&ring->ring);
349 		if (r) {
350 			dev_err(adev->dev, "(%d) ring create failed\n", r);
351 			kvfree(ring->ring_backup);
352 			return r;
353 		}
354 		amdgpu_ring_clear_ring(ring);
355 	}
356 
357 	ring->max_dw = max_dw;
358 	ring->hw_prio = hw_prio;
359 	ring->vmid_wait = dma_fence_get_stub();
360 
361 	if (!ring->no_scheduler && ring->funcs->type < AMDGPU_HW_IP_NUM) {
362 		hw_ip = ring->funcs->type;
363 		num_sched = &adev->gpu_sched[hw_ip][hw_prio].num_scheds;
364 		adev->gpu_sched[hw_ip][hw_prio].sched[(*num_sched)++] =
365 			&ring->sched;
366 	}
367 
368 	return 0;
369 }
370 
371 /**
372  * amdgpu_ring_fini - tear down the driver ring struct.
373  *
374  * @ring: amdgpu_ring structure holding ring information
375  *
376  * Tear down the driver information for the selected ring (all asics).
377  */
378 void amdgpu_ring_fini(struct amdgpu_ring *ring)
379 {
380 
381 	/* Not to finish a ring which is not initialized */
382 	if (!(ring->adev) || !(ring->adev->rings[ring->idx]))
383 		return;
384 
385 	ring->sched.ready = false;
386 
387 	amdgpu_wb_free(ring->adev, ring->rptr_offs);
388 	amdgpu_wb_free(ring->adev, ring->wptr_offs);
389 
390 	amdgpu_wb_free(ring->adev, ring->cond_exe_offs);
391 	amdgpu_wb_free(ring->adev, ring->fence_offs);
392 
393 	amdgpu_bo_free_kernel(&ring->ring_obj,
394 			      &ring->gpu_addr,
395 			      (void **)&ring->ring);
396 	kvfree(ring->ring_backup);
397 	ring->ring_backup = NULL;
398 
399 	dma_fence_put(ring->vmid_wait);
400 	ring->vmid_wait = NULL;
401 	ring->me = 0;
402 }
403 
404 /**
405  * amdgpu_ring_emit_reg_write_reg_wait_helper - ring helper
406  *
407  * @ring: ring to write to
408  * @reg0: register to write
409  * @reg1: register to wait on
410  * @ref: reference value to write/wait on
411  * @mask: mask to wait on
412  *
413  * Helper for rings that don't support write and wait in a
414  * single oneshot packet.
415  */
416 void amdgpu_ring_emit_reg_write_reg_wait_helper(struct amdgpu_ring *ring,
417 						uint32_t reg0, uint32_t reg1,
418 						uint32_t ref, uint32_t mask)
419 {
420 	amdgpu_ring_emit_wreg(ring, reg0, ref);
421 	amdgpu_ring_emit_reg_wait(ring, reg1, mask, mask);
422 }
423 
424 /**
425  * amdgpu_ring_soft_recovery - try to soft recover a ring lockup
426  *
427  * @ring: ring to try the recovery on
428  * @vmid: VMID we try to get going again
429  * @fence: timedout fence
430  *
431  * Tries to get a ring proceeding again when it is stuck.
432  */
433 bool amdgpu_ring_soft_recovery(struct amdgpu_ring *ring, unsigned int vmid,
434 			       struct dma_fence *fence)
435 {
436 	unsigned long flags;
437 	ktime_t deadline;
438 	bool ret;
439 
440 	deadline = ktime_add_us(ktime_get(), 10000);
441 
442 	if (amdgpu_sriov_vf(ring->adev) || !ring->funcs->soft_recovery || !fence)
443 		return false;
444 
445 	dma_fence_lock_irqsave(fence, flags);
446 	if (!dma_fence_is_signaled_locked(fence))
447 		dma_fence_set_error(fence, -ENODATA);
448 	dma_fence_unlock_irqrestore(fence, flags);
449 
450 	while (!dma_fence_is_signaled(fence) &&
451 	       ktime_to_ns(ktime_sub(deadline, ktime_get())) > 0)
452 		ring->funcs->soft_recovery(ring, vmid);
453 
454 	ret = dma_fence_is_signaled(fence);
455 	/* increment the counter only if soft reset worked */
456 	if (ret)
457 		atomic_inc(&ring->adev->gpu_reset_counter);
458 
459 	return ret;
460 }
461 
462 /*
463  * Debugfs info
464  */
465 #if defined(CONFIG_DEBUG_FS)
466 
467 static ssize_t amdgpu_ras_cper_debugfs_read(struct file *f, char __user *buf,
468 					    size_t size, loff_t *offset)
469 {
470 	const u8 ring_header_size = 12;
471 	struct amdgpu_ring *ring = file_inode(f)->i_private;
472 	struct ras_cmd_cper_snapshot_req *snapshot_req __free(kfree) =
473 		kzalloc_obj(struct ras_cmd_cper_snapshot_req);
474 	struct ras_cmd_cper_snapshot_rsp *snapshot_rsp __free(kfree) =
475 		kzalloc_obj(struct ras_cmd_cper_snapshot_rsp);
476 	struct ras_cmd_cper_record_req *record_req __free(kfree) =
477 		kzalloc_obj(struct ras_cmd_cper_record_req);
478 	struct ras_cmd_cper_record_rsp *record_rsp __free(kfree) =
479 		kzalloc_obj(struct ras_cmd_cper_record_rsp);
480 	u32 *ring_header __free(kfree) =
481 		kzalloc(ring_header_size, GFP_KERNEL);
482 	char __user *data_buf = buf;
483 	size_t data_size = size;
484 	u32 total_cper_num;
485 	u64 start_cper_id;
486 	u64 cper_offset;
487 	size_t chunk_size;
488 	size_t total_data_size = 0;
489 	bool read_header;
490 	int r;
491 
492 	if (!snapshot_req || !snapshot_rsp || !record_req || !record_rsp ||
493 	    !ring_header)
494 		return -ENOMEM;
495 
496 	read_header = !(*offset);
497 	cper_offset = read_header ? 0 : *offset - 1;
498 
499 	if (read_header) {
500 		/* Need at least 12 bytes for the header on the first read */
501 		if (size < ring_header_size)
502 			return -EINVAL;
503 		data_buf += ring_header_size;
504 		data_size -= ring_header_size;
505 	}
506 
507 	r = amdgpu_ras_mgr_handle_ras_cmd(ring->adev,
508 					  RAS_CMD__GET_CPER_SNAPSHOT,
509 					  snapshot_req, sizeof(struct ras_cmd_cper_snapshot_req),
510 					  snapshot_rsp, sizeof(struct ras_cmd_cper_snapshot_rsp));
511 	if (r)
512 		return -EINVAL;
513 
514 	if (!snapshot_rsp->total_cper_num) {
515 		if (!read_header)
516 			return 0;
517 
518 		if (copy_to_user(buf, ring_header, ring_header_size))
519 			return -EFAULT;
520 
521 		*offset = 1;
522 		return ring_header_size;
523 	}
524 
525 	start_cper_id = snapshot_rsp->start_cper_id;
526 	total_cper_num = snapshot_rsp->total_cper_num;
527 	if (read_header && !data_size) {
528 		if (copy_to_user(buf, ring_header, ring_header_size))
529 			return -EFAULT;
530 
531 		*offset = cper_offset + 1;
532 		return ring_header_size;
533 	}
534 
535 	if (!data_size)
536 		return 0;
537 
538 	while (data_size && cper_offset < total_cper_num) {
539 		memset(record_req, 0, sizeof(*record_req));
540 		memset(record_rsp, 0, sizeof(*record_rsp));
541 		chunk_size = min_t(size_t, data_size, RAS_CMD_MAX_CPER_BUF_SZ);
542 
543 		record_req->buf_ptr = (u64)(uintptr_t)data_buf;
544 		record_req->buf_size = chunk_size;
545 		record_req->cper_start_id = start_cper_id + cper_offset;
546 		record_req->cper_num = total_cper_num - cper_offset;
547 		r = amdgpu_ras_mgr_handle_ras_cmd(ring->adev,
548 						  RAS_CMD__GET_CPER_RECORD,
549 						  record_req,
550 						  sizeof(struct ras_cmd_cper_record_req),
551 						  record_rsp,
552 						  sizeof(struct ras_cmd_cper_record_rsp));
553 		if (r)
554 			return -EINVAL;
555 
556 		if (!record_rsp->real_data_size || !record_rsp->real_cper_num)
557 			break;
558 		if (record_rsp->real_data_size > data_size)
559 			return -EIO;
560 
561 		data_buf += record_rsp->real_data_size;
562 		data_size -= record_rsp->real_data_size;
563 		total_data_size += record_rsp->real_data_size;
564 		cper_offset += record_rsp->real_cper_num;
565 	}
566 
567 	if (read_header) {
568 		ring_header[1] = total_data_size >> 2;
569 		ring_header[2] = ring_header[1];
570 
571 		if (copy_to_user(buf, ring_header, ring_header_size))
572 			return -EFAULT;
573 	}
574 
575 	r = read_header ? total_data_size + ring_header_size : total_data_size;
576 	*offset = cper_offset + 1;
577 
578 	return r;
579 }
580 
581 /* Layout of file is 12 bytes consisting of
582  * - rptr
583  * - wptr
584  * - driver's copy of wptr
585  *
586  * followed by n-words of ring data
587  */
588 static ssize_t amdgpu_debugfs_ring_read(struct file *f, char __user *buf,
589 					size_t size, loff_t *pos)
590 {
591 	struct amdgpu_ring *ring = file_inode(f)->i_private;
592 	u32 value, result, early[3] = { 0 };
593 	uint64_t p;
594 	u32 avail_dw, start_dw, read_dw;
595 	loff_t i;
596 	int r;
597 
598 	if (ring->funcs->type == AMDGPU_RING_TYPE_CPER && amdgpu_uniras_enabled(ring->adev))
599 		return amdgpu_ras_cper_debugfs_read(f, buf, size, pos);
600 
601 	if (*pos & 3 || size & 3)
602 		return -EINVAL;
603 
604 	result = 0;
605 
606 	if (ring->funcs->type == AMDGPU_RING_TYPE_CPER)
607 		mutex_lock(&ring->adev->cper.ring_lock);
608 
609 	if (*pos < 12) {
610 		early[0] = amdgpu_ring_get_rptr(ring) & ring->buf_mask;
611 		early[1] = amdgpu_ring_get_wptr(ring) & ring->buf_mask;
612 		early[2] = ring->wptr & ring->buf_mask;
613 		for (i = *pos / 4; i < 3 && size; i++) {
614 			r = put_user(early[i], (uint32_t *)buf);
615 			if (r) {
616 				result = r;
617 				goto out;
618 			}
619 			buf += 4;
620 			result += 4;
621 			size -= 4;
622 			*pos += 4;
623 		}
624 	}
625 
626 	if (ring->funcs->type != AMDGPU_RING_TYPE_CPER) {
627 		while (size) {
628 			if (*pos >= (ring->ring_size + 12))
629 				return result;
630 
631 			value = ring->ring[(*pos - 12)/4];
632 			r = put_user(value, (uint32_t *)buf);
633 			if (r)
634 				return r;
635 			buf += 4;
636 			result += 4;
637 			size -= 4;
638 			*pos += 4;
639 		}
640 	} else {
641 		early[0] = amdgpu_ring_get_rptr(ring) & ring->buf_mask;
642 		early[1] = amdgpu_ring_get_wptr(ring) & ring->buf_mask;
643 
644 		p = early[0];
645 		if (early[0] <= early[1])
646 			avail_dw = early[1] - early[0];
647 		else
648 			avail_dw = ring->buf_mask + 1 - (early[0] - early[1]);
649 
650 		start_dw = (*pos > 12) ? ((*pos - 12) >> 2) : 0;
651 		if (start_dw >= avail_dw)
652 			goto out;
653 
654 		p = (p + start_dw) & ring->ptr_mask;
655 		avail_dw -= start_dw;
656 		read_dw = min_t(u32, avail_dw, size >> 2);
657 
658 		while (read_dw) {
659 			if (p == early[1])
660 				goto out;
661 
662 			value = ring->ring[p];
663 			r = put_user(value, (uint32_t *)buf);
664 			if (r) {
665 				result = r;
666 				goto out;
667 			}
668 
669 			buf += 4;
670 			result += 4;
671 			read_dw--;
672 			p++;
673 			p &= ring->ptr_mask;
674 			*pos += 4;
675 		}
676 	}
677 
678 out:
679 	if (ring->funcs->type == AMDGPU_RING_TYPE_CPER)
680 		mutex_unlock(&ring->adev->cper.ring_lock);
681 
682 	return result;
683 }
684 
685 static ssize_t amdgpu_debugfs_virt_ring_read(struct file *f, char __user *buf,
686 	size_t size, loff_t *pos)
687 {
688 	struct amdgpu_ring *ring = file_inode(f)->i_private;
689 
690 	if (*pos & 3 || size & 3)
691 		return -EINVAL;
692 
693 	if (ring->funcs->type == AMDGPU_RING_TYPE_CPER)
694 		amdgpu_virt_req_ras_cper_dump(ring->adev, false);
695 
696 	return amdgpu_debugfs_ring_read(f, buf, size, pos);
697 }
698 
699 static const struct file_operations amdgpu_debugfs_ring_fops = {
700 	.owner = THIS_MODULE,
701 	.read = amdgpu_debugfs_ring_read,
702 	.llseek = default_llseek
703 };
704 
705 static const struct file_operations amdgpu_debugfs_virt_ring_fops = {
706 	.owner = THIS_MODULE,
707 	.read = amdgpu_debugfs_virt_ring_read,
708 	.llseek = default_llseek
709 };
710 
711 static ssize_t amdgpu_debugfs_mqd_read(struct file *f, char __user *buf,
712 				       size_t size, loff_t *pos)
713 {
714 	struct amdgpu_ring *ring = file_inode(f)->i_private;
715 	ssize_t bytes = min_t(ssize_t, ring->mqd_size - *pos, size);
716 	void *from = ((u8 *)ring->mqd_ptr) + *pos;
717 
718 	if (*pos > ring->mqd_size)
719 		return 0;
720 
721 	if (copy_to_user(buf, from, bytes))
722 		return -EFAULT;
723 
724 	*pos += bytes;
725 	return bytes;
726 }
727 
728 static const struct file_operations amdgpu_debugfs_mqd_fops = {
729 	.owner = THIS_MODULE,
730 	.read = amdgpu_debugfs_mqd_read,
731 	.llseek = default_llseek
732 };
733 
734 static int amdgpu_debugfs_ring_error(void *data, u64 val)
735 {
736 	struct amdgpu_ring *ring = data;
737 
738 	amdgpu_fence_driver_set_error(ring, val);
739 	return 0;
740 }
741 
742 DEFINE_DEBUGFS_ATTRIBUTE_SIGNED(amdgpu_debugfs_error_fops, NULL,
743 				amdgpu_debugfs_ring_error, "%lld\n");
744 
745 #endif
746 
747 void amdgpu_debugfs_ring_init(struct amdgpu_device *adev,
748 			      struct amdgpu_ring *ring)
749 {
750 #if defined(CONFIG_DEBUG_FS)
751 	struct drm_minor *minor = adev_to_drm(adev)->primary;
752 	struct dentry *root = minor->debugfs_root;
753 	char name[32];
754 
755 	sprintf(name, "amdgpu_ring_%s", ring->name);
756 	if (amdgpu_sriov_vf(adev))
757 		debugfs_create_file_size(name, S_IFREG | 0444, root, ring,
758 					 &amdgpu_debugfs_virt_ring_fops,
759 					 ring->ring_size + 12);
760 	else
761 		debugfs_create_file_size(name, S_IFREG | 0444, root, ring,
762 					 &amdgpu_debugfs_ring_fops,
763 					 ring->ring_size + 12);
764 
765 	if (ring->mqd_obj) {
766 		sprintf(name, "amdgpu_mqd_%s", ring->name);
767 		debugfs_create_file_size(name, S_IFREG | 0444, root, ring,
768 					 &amdgpu_debugfs_mqd_fops,
769 					 ring->mqd_size);
770 	}
771 
772 	sprintf(name, "amdgpu_error_%s", ring->name);
773 	debugfs_create_file(name, 0200, root, ring,
774 			    &amdgpu_debugfs_error_fops);
775 
776 #endif
777 }
778 
779 /**
780  * amdgpu_ring_test_helper - tests ring and set sched readiness status
781  *
782  * @ring: ring to try the recovery on
783  *
784  * Tests ring and set sched readiness status
785  *
786  * Returns 0 on success, error on failure.
787  */
788 int amdgpu_ring_test_helper(struct amdgpu_ring *ring)
789 {
790 	struct amdgpu_device *adev = ring->adev;
791 	int r;
792 
793 	r = amdgpu_ring_test_ring(ring);
794 	if (r)
795 		DRM_DEV_ERROR(adev->dev, "ring %s test failed (%d)\n",
796 			      ring->name, r);
797 	else
798 		DRM_DEV_DEBUG(adev->dev, "ring test on %s succeeded\n",
799 			      ring->name);
800 
801 	ring->sched.ready = !r;
802 
803 	return r;
804 }
805 
806 static void amdgpu_ring_to_mqd_prop(struct amdgpu_ring *ring,
807 				    struct amdgpu_mqd_prop *prop)
808 {
809 	struct amdgpu_device *adev = ring->adev;
810 	bool is_high_prio_compute = ring->funcs->type == AMDGPU_RING_TYPE_COMPUTE &&
811 				    amdgpu_gfx_is_high_priority_compute_queue(adev, ring);
812 	bool is_high_prio_gfx = ring->funcs->type == AMDGPU_RING_TYPE_GFX &&
813 				amdgpu_gfx_is_high_priority_graphics_queue(adev, ring);
814 
815 	memset(prop, 0, sizeof(*prop));
816 
817 	prop->mqd_gpu_addr = ring->mqd_gpu_addr;
818 	prop->hqd_base_gpu_addr = ring->gpu_addr;
819 	prop->rptr_gpu_addr = ring->rptr_gpu_addr;
820 	prop->wptr_gpu_addr = ring->wptr_gpu_addr;
821 	prop->queue_size = ring->ring_size;
822 	prop->eop_gpu_addr = ring->eop_gpu_addr;
823 	prop->use_doorbell = ring->use_doorbell;
824 	prop->doorbell_index = ring->doorbell_index;
825 	prop->kernel_queue = true;
826 
827 	/* map_queues packet doesn't need activate the queue,
828 	 * so only kiq need set this field.
829 	 */
830 	prop->hqd_active = ring->funcs->type == AMDGPU_RING_TYPE_KIQ;
831 
832 	prop->allow_tunneling = is_high_prio_compute;
833 	if (is_high_prio_compute || is_high_prio_gfx) {
834 		prop->hqd_pipe_priority = AMDGPU_GFX_PIPE_PRIO_HIGH;
835 		prop->hqd_queue_priority = AMDGPU_GFX_QUEUE_PRIORITY_MAXIMUM;
836 	}
837 }
838 
839 int amdgpu_ring_init_mqd(struct amdgpu_ring *ring)
840 {
841 	struct amdgpu_device *adev = ring->adev;
842 	struct amdgpu_mqd *mqd_mgr;
843 	struct amdgpu_mqd_prop prop;
844 
845 	amdgpu_ring_to_mqd_prop(ring, &prop);
846 
847 	ring->wptr = 0;
848 
849 	if (ring->funcs->type == AMDGPU_RING_TYPE_KIQ)
850 		mqd_mgr = &adev->mqds[AMDGPU_HW_IP_COMPUTE];
851 	else
852 		mqd_mgr = &adev->mqds[ring->funcs->type];
853 
854 	return mqd_mgr->init_mqd(adev, ring->mqd_ptr, &prop);
855 }
856 
857 void amdgpu_ring_ib_begin(struct amdgpu_ring *ring)
858 {
859 	if (ring->is_sw_ring)
860 		amdgpu_sw_ring_ib_begin(ring);
861 }
862 
863 void amdgpu_ring_ib_end(struct amdgpu_ring *ring)
864 {
865 	if (ring->is_sw_ring)
866 		amdgpu_sw_ring_ib_end(ring);
867 }
868 
869 void amdgpu_ring_ib_on_emit_cntl(struct amdgpu_ring *ring)
870 {
871 	if (ring->is_sw_ring)
872 		amdgpu_sw_ring_ib_mark_offset(ring, AMDGPU_MUX_OFFSET_TYPE_CONTROL);
873 }
874 
875 void amdgpu_ring_ib_on_emit_ce(struct amdgpu_ring *ring)
876 {
877 	if (ring->is_sw_ring)
878 		amdgpu_sw_ring_ib_mark_offset(ring, AMDGPU_MUX_OFFSET_TYPE_CE);
879 }
880 
881 void amdgpu_ring_ib_on_emit_de(struct amdgpu_ring *ring)
882 {
883 	if (ring->is_sw_ring)
884 		amdgpu_sw_ring_ib_mark_offset(ring, AMDGPU_MUX_OFFSET_TYPE_DE);
885 }
886 
887 bool amdgpu_ring_sched_ready(struct amdgpu_ring *ring)
888 {
889 	if (!ring)
890 		return false;
891 
892 	if (ring->no_scheduler || !drm_sched_wqueue_ready(&ring->sched))
893 		return false;
894 
895 	return true;
896 }
897 
898 void amdgpu_ring_reset_helper_begin(struct amdgpu_ring *ring,
899 				    struct amdgpu_fence *guilty_fence)
900 {
901 	/* back up the non-guilty commands */
902 	amdgpu_ring_backup_unprocessed_commands(ring, guilty_fence);
903 }
904 
905 int amdgpu_ring_reset_helper_end(struct amdgpu_ring *ring,
906 				 struct amdgpu_fence *guilty_fence)
907 {
908 	int r;
909 
910 	/* verify that the ring is functional */
911 	r = amdgpu_ring_test_ring(ring);
912 	if (r)
913 		return r;
914 
915 	/* set an error on all fences from the context and reemit */
916 	amdgpu_ring_set_fence_errors_and_reemit(ring, guilty_fence);
917 
918 	return 0;
919 }
920 
921 /**
922  * amdgpu_multi_ring_reset_helper_begin() - Prepare multiple rings for a reset.
923  *
924  * @ring_type_mask: Bitmask of affected ring types
925  * @guilty_ring: The ring which is guilty of causing a reset.
926  * @guilty_fence: The fence which didn't signal on the guilty ring.
927  *
928  * Useful when performing a GPU reset method that affects
929  * multiple rings at the same time, such as an IP block soft
930  * reset. For example, a GFX IP block soft reset will affect
931  * every graphics and compute queue.
932  *
933  * This function should be called before such a reset.
934  *
935  * Prepare the affected rings before the reset, make sure to
936  * minimize collateral damage, and backup the contents of
937  * the rings. Then the caller can call the actual HW specific
938  * reset function.
939  *
940  * After the reset is complete, the caller should then call
941  * amdgpu_multi_ring_reset_helper_end() to restore the rings.
942  */
943 void amdgpu_multi_ring_reset_helper_begin(const u32 ring_type_mask,
944 					  struct amdgpu_ring *guilty_ring,
945 					  struct amdgpu_fence *guilty_fence)
946 {
947 	struct amdgpu_device *adev = guilty_ring->adev;
948 	struct amdgpu_fence *ring_guilty_fence;
949 	struct amdgpu_ring *ring;
950 	bool rings_busy;
951 	int i;
952 	u32 t;
953 
954 	for (i = 0; i < adev->num_rings; ++i) {
955 		ring = adev->rings[i];
956 
957 		if (!(BIT(ring->funcs->type) & ring_type_mask))
958 			continue;
959 
960 		/* Don't accept new submissions on the ring. */
961 		if (amdgpu_ring_sched_ready(ring) && !drm_sched_is_stopped(&ring->sched))
962 			drm_sched_wqueue_stop(&ring->sched);
963 
964 		/*
965 		 * Clear the preempt condition to stop the ring
966 		 * from starting its next submission. This ensures
967 		 * that only the currently executing submission
968 		 * can be rejected because of the reset and helps
969 		 * minimize collateral damage.
970 		 */
971 		if (ring->funcs->init_cond_exec)
972 			amdgpu_ring_set_preempt_cond_exec(ring, false);
973 	}
974 
975 	/* Flush HDP cache so the GPU can see the updated COND_EXEC values */
976 	amdgpu_device_flush_hdp(adev, NULL);
977 
978 	/*
979 	 * Give some time for non-guilty rings to finish their
980 	 * current submission, to try to minimize collateral damage.
981 	 *
982 	 * Note that this is just a best effort, but really there
983 	 * is no way to really know which ring is actually responsible
984 	 * because different rings may share resources, eg. a compute
985 	 * ring may hog shader engines, causing a graphics ring to hang.
986 	 */
987 	for (t = 0; t < adev->usec_timeout; t += 10000) {
988 		rings_busy = false;
989 
990 		/* Check if any of the non-guilty rings are busy */
991 		for (i = 0; i < adev->num_rings; ++i) {
992 			ring = adev->rings[i];
993 
994 			if (!(BIT(ring->funcs->type) & ring_type_mask))
995 				continue;
996 
997 			if (ring == guilty_ring)
998 				continue;
999 
1000 			rings_busy |=
1001 				atomic_read(&ring->fence_drv.last_seq) !=
1002 				READ_ONCE(ring->fence_drv.sync_seq);
1003 		}
1004 
1005 		if (!rings_busy)
1006 			break;
1007 
1008 		mdelay(10);
1009 	}
1010 
1011 	for (i = 0; i < adev->num_rings; ++i) {
1012 		ring = adev->rings[i];
1013 
1014 		if (!(BIT(ring->funcs->type) & ring_type_mask))
1015 			continue;
1016 
1017 		/*
1018 		 * Find guilty fences, ie. the fences that didn't signal
1019 		 * on each ring. At this point there is no way to know
1020 		 * which one is really responsible for the hang, and no
1021 		 * way to save any of them, so we treat all of them as guilty.
1022 		 */
1023 		ring_guilty_fence =
1024 			ring == guilty_ring ? guilty_fence :
1025 			amdgpu_ring_find_guilty_fence(ring);
1026 
1027 		/*
1028 		 * Backup current contents of the ring.
1029 		 * The helper takes care to only reemit unsignalled fences
1030 		 * so we don't have to worry about that here.
1031 		 */
1032 		amdgpu_ring_reset_helper_begin(ring, ring_guilty_fence);
1033 	}
1034 }
1035 
1036 /**
1037  * amdgpu_multi_ring_reset_helper_end() - Prepare multiple rings for a reset.
1038  *
1039  * @ring_type_mask: Bitmask of affected ring types
1040  * @guilty_ring: The ring which is guilty of causing a reset.
1041  * @ret: Return code from the reset function.
1042  *
1043  * After calling amdgpu_multi_ring_reset_helper_begin()
1044  * and executing the actual reset method, call this
1045  * function to restore normal operation.
1046  *
1047  * In case the reset failed, this function should still
1048  * be called to restore preemption state, but it won't attempt to
1049  * fully restore the ring contents.
1050  */
1051 int amdgpu_multi_ring_reset_helper_end(const u32 ring_type_mask,
1052 				       struct amdgpu_ring *guilty_ring, int ret)
1053 {
1054 	struct amdgpu_device *adev = guilty_ring->adev;
1055 	struct amdgpu_ring *ring;
1056 	int i, r;
1057 
1058 	/* Set preempt condition, rings are now allowed to execute submissions */
1059 	for (i = 0; i < adev->num_rings; ++i) {
1060 		ring = adev->rings[i];
1061 
1062 		if (!(BIT(ring->funcs->type) & ring_type_mask))
1063 			continue;
1064 
1065 		if (ring->funcs->init_cond_exec)
1066 			amdgpu_ring_set_preempt_cond_exec(ring, true);
1067 	}
1068 
1069 	/* Flush HDP cache so the GPU can see the updated COND_EXEC values */
1070 	amdgpu_device_flush_hdp(adev, NULL);
1071 
1072 	/* If the reset was unsuccessful, return without restoring anything else. */
1073 	if (ret)
1074 		return ret;
1075 
1076 	/* Restore contents of all rings */
1077 	for (i = 0; i < adev->num_rings; ++i) {
1078 		ring = adev->rings[i];
1079 
1080 		if (!(BIT(ring->funcs->type) & ring_type_mask))
1081 			continue;
1082 
1083 		/* Restore contents of the ring */
1084 		r = amdgpu_ring_reset_helper_end(ring, ring->guilty_fence);
1085 		if (r) {
1086 			dev_err(adev->dev,
1087 				"Failed to recover ring %s after soft reset\n",
1088 				ring->name);
1089 			return r;
1090 		}
1091 	}
1092 
1093 	/* Accept submissions on all rings again */
1094 	for (i = 0; i < adev->num_rings; ++i) {
1095 		ring = adev->rings[i];
1096 
1097 		if (!(BIT(ring->funcs->type) & ring_type_mask))
1098 			continue;
1099 
1100 		if (!amdgpu_ring_sched_ready(ring))
1101 			continue;
1102 
1103 		drm_sched_wqueue_start(&ring->sched);
1104 	}
1105 
1106 	return 0;
1107 }
1108 
1109 bool amdgpu_ring_is_reset_type_supported(struct amdgpu_ring *ring,
1110 					 u32 reset_type)
1111 {
1112 	switch (ring->funcs->type) {
1113 	case AMDGPU_RING_TYPE_GFX:
1114 		if (ring->adev->gfx.gfx_supported_reset & reset_type)
1115 			return true;
1116 		break;
1117 	case AMDGPU_RING_TYPE_COMPUTE:
1118 		if (ring->adev->gfx.compute_supported_reset & reset_type)
1119 			return true;
1120 		break;
1121 	case AMDGPU_RING_TYPE_SDMA:
1122 		if (ring->adev->sdma.supported_reset & reset_type)
1123 			return true;
1124 		break;
1125 	case AMDGPU_RING_TYPE_VCN_DEC:
1126 	case AMDGPU_RING_TYPE_VCN_ENC:
1127 		if (ring->adev->vcn.supported_reset & reset_type)
1128 			return true;
1129 		break;
1130 	case AMDGPU_RING_TYPE_VCN_JPEG:
1131 		if (ring->adev->jpeg.supported_reset & reset_type)
1132 			return true;
1133 		break;
1134 	default:
1135 		break;
1136 	}
1137 	return false;
1138 }
1139