xref: /linux/drivers/accel/qaic/qaic_data.c (revision a4ff64edf9edc8f05e2183610dc8306d3279c6ac)
1 // SPDX-License-Identifier: GPL-2.0-only
2 
3 /* Copyright (c) 2019-2021, The Linux Foundation. All rights reserved. */
4 /* Copyright (c) 2021-2023 Qualcomm Innovation Center, Inc. All rights reserved. */
5 
6 #include <linux/bitfield.h>
7 #include <linux/bits.h>
8 #include <linux/completion.h>
9 #include <linux/delay.h>
10 #include <linux/dma-buf.h>
11 #include <linux/dma-mapping.h>
12 #include <linux/interrupt.h>
13 #include <linux/kref.h>
14 #include <linux/list.h>
15 #include <linux/math64.h>
16 #include <linux/mm.h>
17 #include <linux/moduleparam.h>
18 #include <linux/scatterlist.h>
19 #include <linux/spinlock.h>
20 #include <linux/srcu.h>
21 #include <linux/types.h>
22 #include <linux/uaccess.h>
23 #include <linux/wait.h>
24 #include <drm/drm_file.h>
25 #include <drm/drm_gem.h>
26 #include <drm/drm_prime.h>
27 #include <drm/drm_print.h>
28 #include <uapi/drm/qaic_accel.h>
29 
30 #include "qaic.h"
31 
32 #define SEM_VAL_MASK	GENMASK_ULL(11, 0)
33 #define SEM_INDEX_MASK	GENMASK_ULL(4, 0)
34 #define BULK_XFER	BIT(3)
35 #define GEN_COMPLETION	BIT(4)
36 #define INBOUND_XFER	1
37 #define OUTBOUND_XFER	2
38 #define REQHP_OFF	0x0 /* we read this */
39 #define REQTP_OFF	0x4 /* we write this */
40 #define RSPHP_OFF	0x8 /* we write this */
41 #define RSPTP_OFF	0xc /* we read this */
42 
43 #define ENCODE_SEM(val, index, sync, cmd, flags)			\
44 		({							\
45 			FIELD_PREP(GENMASK(11, 0), (val)) |		\
46 			FIELD_PREP(GENMASK(20, 16), (index)) |		\
47 			FIELD_PREP(BIT(22), (sync)) |			\
48 			FIELD_PREP(GENMASK(26, 24), (cmd)) |		\
49 			FIELD_PREP(GENMASK(30, 29), (flags)) |		\
50 			FIELD_PREP(BIT(31), (cmd) ? 1 : 0);		\
51 		})
52 #define NUM_EVENTS	128
53 #define NUM_DELAYS	10
54 
55 static unsigned int wait_exec_default_timeout_ms = 5000; /* 5 sec default */
56 module_param(wait_exec_default_timeout_ms, uint, 0600);
57 MODULE_PARM_DESC(wait_exec_default_timeout_ms, "Default timeout for DRM_IOCTL_QAIC_WAIT_BO");
58 
59 static unsigned int datapath_poll_interval_us = 100; /* 100 usec default */
60 module_param(datapath_poll_interval_us, uint, 0600);
61 MODULE_PARM_DESC(datapath_poll_interval_us,
62 		 "Amount of time to sleep between activity when datapath polling is enabled");
63 
64 struct dbc_req {
65 	/*
66 	 * A request ID is assigned to each memory handle going in DMA queue.
67 	 * As a single memory handle can enqueue multiple elements in DMA queue
68 	 * all of them will have the same request ID.
69 	 */
70 	__le16	req_id;
71 	/* Future use */
72 	__u8	seq_id;
73 	/*
74 	 * Special encoded variable
75 	 * 7	0 - Do not force to generate MSI after DMA is completed
76 	 *	1 - Force to generate MSI after DMA is completed
77 	 * 6:5	Reserved
78 	 * 4	1 - Generate completion element in the response queue
79 	 *	0 - No Completion Code
80 	 * 3	0 - DMA request is a Link list transfer
81 	 *	1 - DMA request is a Bulk transfer
82 	 * 2	Reserved
83 	 * 1:0	00 - No DMA transfer involved
84 	 *	01 - DMA transfer is part of inbound transfer
85 	 *	10 - DMA transfer has outbound transfer
86 	 *	11 - NA
87 	 */
88 	__u8	cmd;
89 	__le32	resv;
90 	/* Source address for the transfer */
91 	__le64	src_addr;
92 	/* Destination address for the transfer */
93 	__le64	dest_addr;
94 	/* Length of transfer request */
95 	__le32	len;
96 	__le32	resv2;
97 	/* Doorbell address */
98 	__le64	db_addr;
99 	/*
100 	 * Special encoded variable
101 	 * 7	1 - Doorbell(db) write
102 	 *	0 - No doorbell write
103 	 * 6:2	Reserved
104 	 * 1:0	00 - 32 bit access, db address must be aligned to 32bit-boundary
105 	 *	01 - 16 bit access, db address must be aligned to 16bit-boundary
106 	 *	10 - 8 bit access, db address must be aligned to 8bit-boundary
107 	 *	11 - Reserved
108 	 */
109 	__u8	db_len;
110 	__u8	resv3;
111 	__le16	resv4;
112 	/* 32 bit data written to doorbell address */
113 	__le32	db_data;
114 	/*
115 	 * Special encoded variable
116 	 * All the fields of sem_cmdX are passed from user and all are ORed
117 	 * together to form sem_cmd.
118 	 * 0:11		Semaphore value
119 	 * 15:12	Reserved
120 	 * 20:16	Semaphore index
121 	 * 21		Reserved
122 	 * 22		Semaphore Sync
123 	 * 23		Reserved
124 	 * 26:24	Semaphore command
125 	 * 28:27	Reserved
126 	 * 29		Semaphore DMA out bound sync fence
127 	 * 30		Semaphore DMA in bound sync fence
128 	 * 31		Enable semaphore command
129 	 */
130 	__le32	sem_cmd0;
131 	__le32	sem_cmd1;
132 	__le32	sem_cmd2;
133 	__le32	sem_cmd3;
134 } __packed;
135 
136 struct dbc_rsp {
137 	/* Request ID of the memory handle whose DMA transaction is completed */
138 	__le16	req_id;
139 	/* Status of the DMA transaction. 0 : Success otherwise failure */
140 	__le16	status;
141 } __packed;
142 
143 inline int get_dbc_req_elem_size(void)
144 {
145 	return sizeof(struct dbc_req);
146 }
147 
148 inline int get_dbc_rsp_elem_size(void)
149 {
150 	return sizeof(struct dbc_rsp);
151 }
152 
153 static void free_slice(struct kref *kref)
154 {
155 	struct bo_slice *slice = container_of(kref, struct bo_slice, ref_count);
156 
157 	slice->bo->total_slice_nents -= slice->nents;
158 	list_del(&slice->slice);
159 	drm_gem_object_put(&slice->bo->base);
160 	sg_free_table(slice->sgt);
161 	kfree(slice->sgt);
162 	kfree(slice->reqs);
163 	kfree(slice);
164 }
165 
166 static int clone_range_of_sgt_for_slice(struct qaic_device *qdev, struct sg_table **sgt_out,
167 					struct sg_table *sgt_in, u64 size, u64 offset)
168 {
169 	int total_len, len, nents, offf = 0, offl = 0;
170 	struct scatterlist *sg, *sgn, *sgf, *sgl;
171 	struct sg_table *sgt;
172 	int ret, j;
173 
174 	/* find out number of relevant nents needed for this mem */
175 	total_len = 0;
176 	sgf = NULL;
177 	sgl = NULL;
178 	nents = 0;
179 
180 	size = size ? size : PAGE_SIZE;
181 	for (sg = sgt_in->sgl; sg; sg = sg_next(sg)) {
182 		len = sg_dma_len(sg);
183 
184 		if (!len)
185 			continue;
186 		if (offset >= total_len && offset < total_len + len) {
187 			sgf = sg;
188 			offf = offset - total_len;
189 		}
190 		if (sgf)
191 			nents++;
192 		if (offset + size >= total_len &&
193 		    offset + size <= total_len + len) {
194 			sgl = sg;
195 			offl = offset + size - total_len;
196 			break;
197 		}
198 		total_len += len;
199 	}
200 
201 	if (!sgf || !sgl) {
202 		ret = -EINVAL;
203 		goto out;
204 	}
205 
206 	sgt = kzalloc(sizeof(*sgt), GFP_KERNEL);
207 	if (!sgt) {
208 		ret = -ENOMEM;
209 		goto out;
210 	}
211 
212 	ret = sg_alloc_table(sgt, nents, GFP_KERNEL);
213 	if (ret)
214 		goto free_sgt;
215 
216 	/* copy relevant sg node and fix page and length */
217 	sgn = sgf;
218 	for_each_sgtable_sg(sgt, sg, j) {
219 		memcpy(sg, sgn, sizeof(*sg));
220 		if (sgn == sgf) {
221 			sg_dma_address(sg) += offf;
222 			sg_dma_len(sg) -= offf;
223 			sg_set_page(sg, sg_page(sgn), sg_dma_len(sg), offf);
224 		} else {
225 			offf = 0;
226 		}
227 		if (sgn == sgl) {
228 			sg_dma_len(sg) = offl - offf;
229 			sg_set_page(sg, sg_page(sgn), offl - offf, offf);
230 			sg_mark_end(sg);
231 			break;
232 		}
233 		sgn = sg_next(sgn);
234 	}
235 
236 	*sgt_out = sgt;
237 	return ret;
238 
239 free_sgt:
240 	kfree(sgt);
241 out:
242 	*sgt_out = NULL;
243 	return ret;
244 }
245 
246 static int encode_reqs(struct qaic_device *qdev, struct bo_slice *slice,
247 		       struct qaic_attach_slice_entry *req)
248 {
249 	__le64 db_addr = cpu_to_le64(req->db_addr);
250 	__le32 db_data = cpu_to_le32(req->db_data);
251 	struct scatterlist *sg;
252 	__u8 cmd = BULK_XFER;
253 	int presync_sem;
254 	u64 dev_addr;
255 	__u8 db_len;
256 	int i;
257 
258 	if (!slice->no_xfer)
259 		cmd |= (slice->dir == DMA_TO_DEVICE ? INBOUND_XFER : OUTBOUND_XFER);
260 
261 	if (req->db_len && !IS_ALIGNED(req->db_addr, req->db_len / 8))
262 		return -EINVAL;
263 
264 	presync_sem = req->sem0.presync + req->sem1.presync + req->sem2.presync + req->sem3.presync;
265 	if (presync_sem > 1)
266 		return -EINVAL;
267 
268 	presync_sem = req->sem0.presync << 0 | req->sem1.presync << 1 |
269 		      req->sem2.presync << 2 | req->sem3.presync << 3;
270 
271 	switch (req->db_len) {
272 	case 32:
273 		db_len = BIT(7);
274 		break;
275 	case 16:
276 		db_len = BIT(7) | 1;
277 		break;
278 	case 8:
279 		db_len = BIT(7) | 2;
280 		break;
281 	case 0:
282 		db_len = 0; /* doorbell is not active for this command */
283 		break;
284 	default:
285 		return -EINVAL; /* should never hit this */
286 	}
287 
288 	/*
289 	 * When we end up splitting up a single request (ie a buf slice) into
290 	 * multiple DMA requests, we have to manage the sync data carefully.
291 	 * There can only be one presync sem. That needs to be on every xfer
292 	 * so that the DMA engine doesn't transfer data before the receiver is
293 	 * ready. We only do the doorbell and postsync sems after the xfer.
294 	 * To guarantee previous xfers for the request are complete, we use a
295 	 * fence.
296 	 */
297 	dev_addr = req->dev_addr;
298 	for_each_sgtable_sg(slice->sgt, sg, i) {
299 		slice->reqs[i].cmd = cmd;
300 		slice->reqs[i].src_addr = cpu_to_le64(slice->dir == DMA_TO_DEVICE ?
301 						      sg_dma_address(sg) : dev_addr);
302 		slice->reqs[i].dest_addr = cpu_to_le64(slice->dir == DMA_TO_DEVICE ?
303 						       dev_addr : sg_dma_address(sg));
304 		/*
305 		 * sg_dma_len(sg) returns size of a DMA segment, maximum DMA
306 		 * segment size is set to UINT_MAX by qaic and hence return
307 		 * values of sg_dma_len(sg) can never exceed u32 range. So,
308 		 * by down sizing we are not corrupting the value.
309 		 */
310 		slice->reqs[i].len = cpu_to_le32((u32)sg_dma_len(sg));
311 		switch (presync_sem) {
312 		case BIT(0):
313 			slice->reqs[i].sem_cmd0 = cpu_to_le32(ENCODE_SEM(req->sem0.val,
314 									 req->sem0.index,
315 									 req->sem0.presync,
316 									 req->sem0.cmd,
317 									 req->sem0.flags));
318 			break;
319 		case BIT(1):
320 			slice->reqs[i].sem_cmd1 = cpu_to_le32(ENCODE_SEM(req->sem1.val,
321 									 req->sem1.index,
322 									 req->sem1.presync,
323 									 req->sem1.cmd,
324 									 req->sem1.flags));
325 			break;
326 		case BIT(2):
327 			slice->reqs[i].sem_cmd2 = cpu_to_le32(ENCODE_SEM(req->sem2.val,
328 									 req->sem2.index,
329 									 req->sem2.presync,
330 									 req->sem2.cmd,
331 									 req->sem2.flags));
332 			break;
333 		case BIT(3):
334 			slice->reqs[i].sem_cmd3 = cpu_to_le32(ENCODE_SEM(req->sem3.val,
335 									 req->sem3.index,
336 									 req->sem3.presync,
337 									 req->sem3.cmd,
338 									 req->sem3.flags));
339 			break;
340 		}
341 		dev_addr += sg_dma_len(sg);
342 	}
343 	/* add post transfer stuff to last segment */
344 	i--;
345 	slice->reqs[i].cmd |= GEN_COMPLETION;
346 	slice->reqs[i].db_addr = db_addr;
347 	slice->reqs[i].db_len = db_len;
348 	slice->reqs[i].db_data = db_data;
349 	/*
350 	 * Add a fence if we have more than one request going to the hardware
351 	 * representing the entirety of the user request, and the user request
352 	 * has no presync condition.
353 	 * Fences are expensive, so we try to avoid them. We rely on the
354 	 * hardware behavior to avoid needing one when there is a presync
355 	 * condition. When a presync exists, all requests for that same
356 	 * presync will be queued into a fifo. Thus, since we queue the
357 	 * post xfer activity only on the last request we queue, the hardware
358 	 * will ensure that the last queued request is processed last, thus
359 	 * making sure the post xfer activity happens at the right time without
360 	 * a fence.
361 	 */
362 	if (i && !presync_sem)
363 		req->sem0.flags |= (slice->dir == DMA_TO_DEVICE ?
364 				    QAIC_SEM_INSYNCFENCE : QAIC_SEM_OUTSYNCFENCE);
365 	slice->reqs[i].sem_cmd0 = cpu_to_le32(ENCODE_SEM(req->sem0.val, req->sem0.index,
366 							 req->sem0.presync, req->sem0.cmd,
367 							 req->sem0.flags));
368 	slice->reqs[i].sem_cmd1 = cpu_to_le32(ENCODE_SEM(req->sem1.val, req->sem1.index,
369 							 req->sem1.presync, req->sem1.cmd,
370 							 req->sem1.flags));
371 	slice->reqs[i].sem_cmd2 = cpu_to_le32(ENCODE_SEM(req->sem2.val, req->sem2.index,
372 							 req->sem2.presync, req->sem2.cmd,
373 							 req->sem2.flags));
374 	slice->reqs[i].sem_cmd3 = cpu_to_le32(ENCODE_SEM(req->sem3.val, req->sem3.index,
375 							 req->sem3.presync, req->sem3.cmd,
376 							 req->sem3.flags));
377 
378 	return 0;
379 }
380 
381 static int qaic_map_one_slice(struct qaic_device *qdev, struct qaic_bo *bo,
382 			      struct qaic_attach_slice_entry *slice_ent)
383 {
384 	struct sg_table *sgt = NULL;
385 	struct bo_slice *slice;
386 	int ret;
387 
388 	ret = clone_range_of_sgt_for_slice(qdev, &sgt, bo->sgt, slice_ent->size, slice_ent->offset);
389 	if (ret)
390 		goto out;
391 
392 	slice = kmalloc(sizeof(*slice), GFP_KERNEL);
393 	if (!slice) {
394 		ret = -ENOMEM;
395 		goto free_sgt;
396 	}
397 
398 	slice->reqs = kcalloc(sgt->nents, sizeof(*slice->reqs), GFP_KERNEL);
399 	if (!slice->reqs) {
400 		ret = -ENOMEM;
401 		goto free_slice;
402 	}
403 
404 	slice->no_xfer = !slice_ent->size;
405 	slice->sgt = sgt;
406 	slice->nents = sgt->nents;
407 	slice->dir = bo->dir;
408 	slice->bo = bo;
409 	slice->size = slice_ent->size;
410 	slice->offset = slice_ent->offset;
411 
412 	ret = encode_reqs(qdev, slice, slice_ent);
413 	if (ret)
414 		goto free_req;
415 
416 	bo->total_slice_nents += sgt->nents;
417 	kref_init(&slice->ref_count);
418 	drm_gem_object_get(&bo->base);
419 	list_add_tail(&slice->slice, &bo->slices);
420 
421 	return 0;
422 
423 free_req:
424 	kfree(slice->reqs);
425 free_slice:
426 	kfree(slice);
427 free_sgt:
428 	sg_free_table(sgt);
429 	kfree(sgt);
430 out:
431 	return ret;
432 }
433 
434 static int create_sgt(struct qaic_device *qdev, struct sg_table **sgt_out, u64 size)
435 {
436 	struct scatterlist *sg;
437 	struct sg_table *sgt;
438 	struct page **pages;
439 	int *pages_order;
440 	int buf_extra;
441 	int max_order;
442 	int nr_pages;
443 	int ret = 0;
444 	int i, j, k;
445 	int order;
446 
447 	if (size) {
448 		nr_pages = DIV_ROUND_UP(size, PAGE_SIZE);
449 		/*
450 		 * calculate how much extra we are going to allocate, to remove
451 		 * later
452 		 */
453 		buf_extra = (PAGE_SIZE - size % PAGE_SIZE) % PAGE_SIZE;
454 		max_order = min(MAX_ORDER - 1, get_order(size));
455 	} else {
456 		/* allocate a single page for book keeping */
457 		nr_pages = 1;
458 		buf_extra = 0;
459 		max_order = 0;
460 	}
461 
462 	pages = kvmalloc_array(nr_pages, sizeof(*pages) + sizeof(*pages_order), GFP_KERNEL);
463 	if (!pages) {
464 		ret = -ENOMEM;
465 		goto out;
466 	}
467 	pages_order = (void *)pages + sizeof(*pages) * nr_pages;
468 
469 	/*
470 	 * Allocate requested memory using alloc_pages. It is possible to allocate
471 	 * the requested memory in multiple chunks by calling alloc_pages
472 	 * multiple times. Use SG table to handle multiple allocated pages.
473 	 */
474 	i = 0;
475 	while (nr_pages > 0) {
476 		order = min(get_order(nr_pages * PAGE_SIZE), max_order);
477 		while (1) {
478 			pages[i] = alloc_pages(GFP_KERNEL | GFP_HIGHUSER |
479 					       __GFP_NOWARN | __GFP_ZERO |
480 					       (order ? __GFP_NORETRY : __GFP_RETRY_MAYFAIL),
481 					       order);
482 			if (pages[i])
483 				break;
484 			if (!order--) {
485 				ret = -ENOMEM;
486 				goto free_partial_alloc;
487 			}
488 		}
489 
490 		max_order = order;
491 		pages_order[i] = order;
492 
493 		nr_pages -= 1 << order;
494 		if (nr_pages <= 0)
495 			/* account for over allocation */
496 			buf_extra += abs(nr_pages) * PAGE_SIZE;
497 		i++;
498 	}
499 
500 	sgt = kmalloc(sizeof(*sgt), GFP_KERNEL);
501 	if (!sgt) {
502 		ret = -ENOMEM;
503 		goto free_partial_alloc;
504 	}
505 
506 	if (sg_alloc_table(sgt, i, GFP_KERNEL)) {
507 		ret = -ENOMEM;
508 		goto free_sgt;
509 	}
510 
511 	/* Populate the SG table with the allocated memory pages */
512 	sg = sgt->sgl;
513 	for (k = 0; k < i; k++, sg = sg_next(sg)) {
514 		/* Last entry requires special handling */
515 		if (k < i - 1) {
516 			sg_set_page(sg, pages[k], PAGE_SIZE << pages_order[k], 0);
517 		} else {
518 			sg_set_page(sg, pages[k], (PAGE_SIZE << pages_order[k]) - buf_extra, 0);
519 			sg_mark_end(sg);
520 		}
521 	}
522 
523 	kvfree(pages);
524 	*sgt_out = sgt;
525 	return ret;
526 
527 free_sgt:
528 	kfree(sgt);
529 free_partial_alloc:
530 	for (j = 0; j < i; j++)
531 		__free_pages(pages[j], pages_order[j]);
532 	kvfree(pages);
533 out:
534 	*sgt_out = NULL;
535 	return ret;
536 }
537 
538 static bool invalid_sem(struct qaic_sem *sem)
539 {
540 	if (sem->val & ~SEM_VAL_MASK || sem->index & ~SEM_INDEX_MASK ||
541 	    !(sem->presync == 0 || sem->presync == 1) || sem->pad ||
542 	    sem->flags & ~(QAIC_SEM_INSYNCFENCE | QAIC_SEM_OUTSYNCFENCE) ||
543 	    sem->cmd > QAIC_SEM_WAIT_GT_0)
544 		return true;
545 	return false;
546 }
547 
548 static int qaic_validate_req(struct qaic_device *qdev, struct qaic_attach_slice_entry *slice_ent,
549 			     u32 count, u64 total_size)
550 {
551 	int i;
552 
553 	for (i = 0; i < count; i++) {
554 		if (!(slice_ent[i].db_len == 32 || slice_ent[i].db_len == 16 ||
555 		      slice_ent[i].db_len == 8 || slice_ent[i].db_len == 0) ||
556 		      invalid_sem(&slice_ent[i].sem0) || invalid_sem(&slice_ent[i].sem1) ||
557 		      invalid_sem(&slice_ent[i].sem2) || invalid_sem(&slice_ent[i].sem3))
558 			return -EINVAL;
559 
560 		if (slice_ent[i].offset + slice_ent[i].size > total_size)
561 			return -EINVAL;
562 	}
563 
564 	return 0;
565 }
566 
567 static void qaic_free_sgt(struct sg_table *sgt)
568 {
569 	struct scatterlist *sg;
570 
571 	for (sg = sgt->sgl; sg; sg = sg_next(sg))
572 		if (sg_page(sg))
573 			__free_pages(sg_page(sg), get_order(sg->length));
574 	sg_free_table(sgt);
575 	kfree(sgt);
576 }
577 
578 static void qaic_gem_print_info(struct drm_printer *p, unsigned int indent,
579 				const struct drm_gem_object *obj)
580 {
581 	struct qaic_bo *bo = to_qaic_bo(obj);
582 
583 	drm_printf_indent(p, indent, "BO DMA direction %d\n", bo->dir);
584 }
585 
586 static const struct vm_operations_struct drm_vm_ops = {
587 	.open = drm_gem_vm_open,
588 	.close = drm_gem_vm_close,
589 };
590 
591 static int qaic_gem_object_mmap(struct drm_gem_object *obj, struct vm_area_struct *vma)
592 {
593 	struct qaic_bo *bo = to_qaic_bo(obj);
594 	unsigned long offset = 0;
595 	struct scatterlist *sg;
596 	int ret = 0;
597 
598 	if (obj->import_attach)
599 		return -EINVAL;
600 
601 	for (sg = bo->sgt->sgl; sg; sg = sg_next(sg)) {
602 		if (sg_page(sg)) {
603 			ret = remap_pfn_range(vma, vma->vm_start + offset, page_to_pfn(sg_page(sg)),
604 					      sg->length, vma->vm_page_prot);
605 			if (ret)
606 				goto out;
607 			offset += sg->length;
608 		}
609 	}
610 
611 out:
612 	return ret;
613 }
614 
615 static void qaic_free_object(struct drm_gem_object *obj)
616 {
617 	struct qaic_bo *bo = to_qaic_bo(obj);
618 
619 	if (obj->import_attach) {
620 		/* DMABUF/PRIME Path */
621 		drm_prime_gem_destroy(obj, NULL);
622 	} else {
623 		/* Private buffer allocation path */
624 		qaic_free_sgt(bo->sgt);
625 	}
626 
627 	mutex_destroy(&bo->lock);
628 	drm_gem_object_release(obj);
629 	kfree(bo);
630 }
631 
632 static const struct drm_gem_object_funcs qaic_gem_funcs = {
633 	.free = qaic_free_object,
634 	.print_info = qaic_gem_print_info,
635 	.mmap = qaic_gem_object_mmap,
636 	.vm_ops = &drm_vm_ops,
637 };
638 
639 static void qaic_init_bo(struct qaic_bo *bo, bool reinit)
640 {
641 	if (reinit) {
642 		bo->sliced = false;
643 		reinit_completion(&bo->xfer_done);
644 	} else {
645 		mutex_init(&bo->lock);
646 		init_completion(&bo->xfer_done);
647 	}
648 	complete_all(&bo->xfer_done);
649 	INIT_LIST_HEAD(&bo->slices);
650 }
651 
652 static struct qaic_bo *qaic_alloc_init_bo(void)
653 {
654 	struct qaic_bo *bo;
655 
656 	bo = kzalloc(sizeof(*bo), GFP_KERNEL);
657 	if (!bo)
658 		return ERR_PTR(-ENOMEM);
659 
660 	qaic_init_bo(bo, false);
661 
662 	return bo;
663 }
664 
665 int qaic_create_bo_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv)
666 {
667 	struct qaic_create_bo *args = data;
668 	int usr_rcu_id, qdev_rcu_id;
669 	struct drm_gem_object *obj;
670 	struct qaic_device *qdev;
671 	struct qaic_user *usr;
672 	struct qaic_bo *bo;
673 	size_t size;
674 	int ret;
675 
676 	if (args->pad)
677 		return -EINVAL;
678 
679 	size = PAGE_ALIGN(args->size);
680 	if (size == 0)
681 		return -EINVAL;
682 
683 	usr = file_priv->driver_priv;
684 	usr_rcu_id = srcu_read_lock(&usr->qddev_lock);
685 	if (!usr->qddev) {
686 		ret = -ENODEV;
687 		goto unlock_usr_srcu;
688 	}
689 
690 	qdev = usr->qddev->qdev;
691 	qdev_rcu_id = srcu_read_lock(&qdev->dev_lock);
692 	if (qdev->in_reset) {
693 		ret = -ENODEV;
694 		goto unlock_dev_srcu;
695 	}
696 
697 	bo = qaic_alloc_init_bo();
698 	if (IS_ERR(bo)) {
699 		ret = PTR_ERR(bo);
700 		goto unlock_dev_srcu;
701 	}
702 	obj = &bo->base;
703 
704 	drm_gem_private_object_init(dev, obj, size);
705 
706 	obj->funcs = &qaic_gem_funcs;
707 	ret = create_sgt(qdev, &bo->sgt, size);
708 	if (ret)
709 		goto free_bo;
710 
711 	ret = drm_gem_handle_create(file_priv, obj, &args->handle);
712 	if (ret)
713 		goto free_sgt;
714 
715 	bo->handle = args->handle;
716 	drm_gem_object_put(obj);
717 	srcu_read_unlock(&qdev->dev_lock, qdev_rcu_id);
718 	srcu_read_unlock(&usr->qddev_lock, usr_rcu_id);
719 
720 	return 0;
721 
722 free_sgt:
723 	qaic_free_sgt(bo->sgt);
724 free_bo:
725 	kfree(bo);
726 unlock_dev_srcu:
727 	srcu_read_unlock(&qdev->dev_lock, qdev_rcu_id);
728 unlock_usr_srcu:
729 	srcu_read_unlock(&usr->qddev_lock, usr_rcu_id);
730 	return ret;
731 }
732 
733 int qaic_mmap_bo_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv)
734 {
735 	struct qaic_mmap_bo *args = data;
736 	int usr_rcu_id, qdev_rcu_id;
737 	struct drm_gem_object *obj;
738 	struct qaic_device *qdev;
739 	struct qaic_user *usr;
740 	int ret;
741 
742 	usr = file_priv->driver_priv;
743 	usr_rcu_id = srcu_read_lock(&usr->qddev_lock);
744 	if (!usr->qddev) {
745 		ret = -ENODEV;
746 		goto unlock_usr_srcu;
747 	}
748 
749 	qdev = usr->qddev->qdev;
750 	qdev_rcu_id = srcu_read_lock(&qdev->dev_lock);
751 	if (qdev->in_reset) {
752 		ret = -ENODEV;
753 		goto unlock_dev_srcu;
754 	}
755 
756 	obj = drm_gem_object_lookup(file_priv, args->handle);
757 	if (!obj) {
758 		ret = -ENOENT;
759 		goto unlock_dev_srcu;
760 	}
761 
762 	ret = drm_gem_create_mmap_offset(obj);
763 	if (ret == 0)
764 		args->offset = drm_vma_node_offset_addr(&obj->vma_node);
765 
766 	drm_gem_object_put(obj);
767 
768 unlock_dev_srcu:
769 	srcu_read_unlock(&qdev->dev_lock, qdev_rcu_id);
770 unlock_usr_srcu:
771 	srcu_read_unlock(&usr->qddev_lock, usr_rcu_id);
772 	return ret;
773 }
774 
775 struct drm_gem_object *qaic_gem_prime_import(struct drm_device *dev, struct dma_buf *dma_buf)
776 {
777 	struct dma_buf_attachment *attach;
778 	struct drm_gem_object *obj;
779 	struct qaic_bo *bo;
780 	size_t size;
781 	int ret;
782 
783 	bo = qaic_alloc_init_bo();
784 	if (IS_ERR(bo)) {
785 		ret = PTR_ERR(bo);
786 		goto out;
787 	}
788 
789 	obj = &bo->base;
790 	get_dma_buf(dma_buf);
791 
792 	attach = dma_buf_attach(dma_buf, dev->dev);
793 	if (IS_ERR(attach)) {
794 		ret = PTR_ERR(attach);
795 		goto attach_fail;
796 	}
797 
798 	size = PAGE_ALIGN(attach->dmabuf->size);
799 	if (size == 0) {
800 		ret = -EINVAL;
801 		goto size_align_fail;
802 	}
803 
804 	drm_gem_private_object_init(dev, obj, size);
805 	/*
806 	 * skipping dma_buf_map_attachment() as we do not know the direction
807 	 * just yet. Once the direction is known in the subsequent IOCTL to
808 	 * attach slicing, we can do it then.
809 	 */
810 
811 	obj->funcs = &qaic_gem_funcs;
812 	obj->import_attach = attach;
813 	obj->resv = dma_buf->resv;
814 
815 	return obj;
816 
817 size_align_fail:
818 	dma_buf_detach(dma_buf, attach);
819 attach_fail:
820 	dma_buf_put(dma_buf);
821 	kfree(bo);
822 out:
823 	return ERR_PTR(ret);
824 }
825 
826 static int qaic_prepare_import_bo(struct qaic_bo *bo, struct qaic_attach_slice_hdr *hdr)
827 {
828 	struct drm_gem_object *obj = &bo->base;
829 	struct sg_table *sgt;
830 	int ret;
831 
832 	if (obj->import_attach->dmabuf->size < hdr->size)
833 		return -EINVAL;
834 
835 	sgt = dma_buf_map_attachment(obj->import_attach, hdr->dir);
836 	if (IS_ERR(sgt)) {
837 		ret = PTR_ERR(sgt);
838 		return ret;
839 	}
840 
841 	bo->sgt = sgt;
842 
843 	return 0;
844 }
845 
846 static int qaic_prepare_export_bo(struct qaic_device *qdev, struct qaic_bo *bo,
847 				  struct qaic_attach_slice_hdr *hdr)
848 {
849 	int ret;
850 
851 	if (bo->base.size < hdr->size)
852 		return -EINVAL;
853 
854 	ret = dma_map_sgtable(&qdev->pdev->dev, bo->sgt, hdr->dir, 0);
855 	if (ret)
856 		return -EFAULT;
857 
858 	return 0;
859 }
860 
861 static int qaic_prepare_bo(struct qaic_device *qdev, struct qaic_bo *bo,
862 			   struct qaic_attach_slice_hdr *hdr)
863 {
864 	int ret;
865 
866 	if (bo->base.import_attach)
867 		ret = qaic_prepare_import_bo(bo, hdr);
868 	else
869 		ret = qaic_prepare_export_bo(qdev, bo, hdr);
870 	bo->dir = hdr->dir;
871 	bo->dbc = &qdev->dbc[hdr->dbc_id];
872 	bo->nr_slice = hdr->count;
873 
874 	return ret;
875 }
876 
877 static void qaic_unprepare_import_bo(struct qaic_bo *bo)
878 {
879 	dma_buf_unmap_attachment(bo->base.import_attach, bo->sgt, bo->dir);
880 	bo->sgt = NULL;
881 }
882 
883 static void qaic_unprepare_export_bo(struct qaic_device *qdev, struct qaic_bo *bo)
884 {
885 	dma_unmap_sgtable(&qdev->pdev->dev, bo->sgt, bo->dir, 0);
886 }
887 
888 static void qaic_unprepare_bo(struct qaic_device *qdev, struct qaic_bo *bo)
889 {
890 	if (bo->base.import_attach)
891 		qaic_unprepare_import_bo(bo);
892 	else
893 		qaic_unprepare_export_bo(qdev, bo);
894 
895 	bo->dir = 0;
896 	bo->dbc = NULL;
897 	bo->nr_slice = 0;
898 }
899 
900 static void qaic_free_slices_bo(struct qaic_bo *bo)
901 {
902 	struct bo_slice *slice, *temp;
903 
904 	list_for_each_entry_safe(slice, temp, &bo->slices, slice)
905 		kref_put(&slice->ref_count, free_slice);
906 	if (WARN_ON_ONCE(bo->total_slice_nents != 0))
907 		bo->total_slice_nents = 0;
908 	bo->nr_slice = 0;
909 }
910 
911 static int qaic_attach_slicing_bo(struct qaic_device *qdev, struct qaic_bo *bo,
912 				  struct qaic_attach_slice_hdr *hdr,
913 				  struct qaic_attach_slice_entry *slice_ent)
914 {
915 	int ret, i;
916 
917 	for (i = 0; i < hdr->count; i++) {
918 		ret = qaic_map_one_slice(qdev, bo, &slice_ent[i]);
919 		if (ret) {
920 			qaic_free_slices_bo(bo);
921 			return ret;
922 		}
923 	}
924 
925 	if (bo->total_slice_nents > bo->dbc->nelem) {
926 		qaic_free_slices_bo(bo);
927 		return -ENOSPC;
928 	}
929 
930 	return 0;
931 }
932 
933 int qaic_attach_slice_bo_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv)
934 {
935 	struct qaic_attach_slice_entry *slice_ent;
936 	struct qaic_attach_slice *args = data;
937 	int rcu_id, usr_rcu_id, qdev_rcu_id;
938 	struct dma_bridge_chan	*dbc;
939 	struct drm_gem_object *obj;
940 	struct qaic_device *qdev;
941 	unsigned long arg_size;
942 	struct qaic_user *usr;
943 	u8 __user *user_data;
944 	struct qaic_bo *bo;
945 	int ret;
946 
947 	if (args->hdr.count == 0)
948 		return -EINVAL;
949 
950 	arg_size = args->hdr.count * sizeof(*slice_ent);
951 	if (arg_size / args->hdr.count != sizeof(*slice_ent))
952 		return -EINVAL;
953 
954 	if (args->hdr.size == 0)
955 		return -EINVAL;
956 
957 	if (!(args->hdr.dir == DMA_TO_DEVICE || args->hdr.dir == DMA_FROM_DEVICE))
958 		return -EINVAL;
959 
960 	if (args->data == 0)
961 		return -EINVAL;
962 
963 	usr = file_priv->driver_priv;
964 	usr_rcu_id = srcu_read_lock(&usr->qddev_lock);
965 	if (!usr->qddev) {
966 		ret = -ENODEV;
967 		goto unlock_usr_srcu;
968 	}
969 
970 	qdev = usr->qddev->qdev;
971 	qdev_rcu_id = srcu_read_lock(&qdev->dev_lock);
972 	if (qdev->in_reset) {
973 		ret = -ENODEV;
974 		goto unlock_dev_srcu;
975 	}
976 
977 	if (args->hdr.dbc_id >= qdev->num_dbc) {
978 		ret = -EINVAL;
979 		goto unlock_dev_srcu;
980 	}
981 
982 	user_data = u64_to_user_ptr(args->data);
983 
984 	slice_ent = kzalloc(arg_size, GFP_KERNEL);
985 	if (!slice_ent) {
986 		ret = -EINVAL;
987 		goto unlock_dev_srcu;
988 	}
989 
990 	ret = copy_from_user(slice_ent, user_data, arg_size);
991 	if (ret) {
992 		ret = -EFAULT;
993 		goto free_slice_ent;
994 	}
995 
996 	ret = qaic_validate_req(qdev, slice_ent, args->hdr.count, args->hdr.size);
997 	if (ret)
998 		goto free_slice_ent;
999 
1000 	obj = drm_gem_object_lookup(file_priv, args->hdr.handle);
1001 	if (!obj) {
1002 		ret = -ENOENT;
1003 		goto free_slice_ent;
1004 	}
1005 
1006 	bo = to_qaic_bo(obj);
1007 	ret = mutex_lock_interruptible(&bo->lock);
1008 	if (ret)
1009 		goto put_bo;
1010 
1011 	if (bo->sliced) {
1012 		ret = -EINVAL;
1013 		goto unlock_bo;
1014 	}
1015 
1016 	dbc = &qdev->dbc[args->hdr.dbc_id];
1017 	rcu_id = srcu_read_lock(&dbc->ch_lock);
1018 	if (dbc->usr != usr) {
1019 		ret = -EINVAL;
1020 		goto unlock_ch_srcu;
1021 	}
1022 
1023 	ret = qaic_prepare_bo(qdev, bo, &args->hdr);
1024 	if (ret)
1025 		goto unlock_ch_srcu;
1026 
1027 	ret = qaic_attach_slicing_bo(qdev, bo, &args->hdr, slice_ent);
1028 	if (ret)
1029 		goto unprepare_bo;
1030 
1031 	if (args->hdr.dir == DMA_TO_DEVICE)
1032 		dma_sync_sgtable_for_cpu(&qdev->pdev->dev, bo->sgt, args->hdr.dir);
1033 
1034 	bo->sliced = true;
1035 	list_add_tail(&bo->bo_list, &bo->dbc->bo_lists);
1036 	srcu_read_unlock(&dbc->ch_lock, rcu_id);
1037 	mutex_unlock(&bo->lock);
1038 	kfree(slice_ent);
1039 	srcu_read_unlock(&qdev->dev_lock, qdev_rcu_id);
1040 	srcu_read_unlock(&usr->qddev_lock, usr_rcu_id);
1041 
1042 	return 0;
1043 
1044 unprepare_bo:
1045 	qaic_unprepare_bo(qdev, bo);
1046 unlock_ch_srcu:
1047 	srcu_read_unlock(&dbc->ch_lock, rcu_id);
1048 unlock_bo:
1049 	mutex_unlock(&bo->lock);
1050 put_bo:
1051 	drm_gem_object_put(obj);
1052 free_slice_ent:
1053 	kfree(slice_ent);
1054 unlock_dev_srcu:
1055 	srcu_read_unlock(&qdev->dev_lock, qdev_rcu_id);
1056 unlock_usr_srcu:
1057 	srcu_read_unlock(&usr->qddev_lock, usr_rcu_id);
1058 	return ret;
1059 }
1060 
1061 static inline int copy_exec_reqs(struct qaic_device *qdev, struct bo_slice *slice, u32 dbc_id,
1062 				 u32 head, u32 *ptail)
1063 {
1064 	struct dma_bridge_chan *dbc = &qdev->dbc[dbc_id];
1065 	struct dbc_req *reqs = slice->reqs;
1066 	u32 tail = *ptail;
1067 	u32 avail;
1068 
1069 	avail = head - tail;
1070 	if (head <= tail)
1071 		avail += dbc->nelem;
1072 
1073 	--avail;
1074 
1075 	if (avail < slice->nents)
1076 		return -EAGAIN;
1077 
1078 	if (tail + slice->nents > dbc->nelem) {
1079 		avail = dbc->nelem - tail;
1080 		avail = min_t(u32, avail, slice->nents);
1081 		memcpy(dbc->req_q_base + tail * get_dbc_req_elem_size(), reqs,
1082 		       sizeof(*reqs) * avail);
1083 		reqs += avail;
1084 		avail = slice->nents - avail;
1085 		if (avail)
1086 			memcpy(dbc->req_q_base, reqs, sizeof(*reqs) * avail);
1087 	} else {
1088 		memcpy(dbc->req_q_base + tail * get_dbc_req_elem_size(), reqs,
1089 		       sizeof(*reqs) * slice->nents);
1090 	}
1091 
1092 	*ptail = (tail + slice->nents) % dbc->nelem;
1093 
1094 	return 0;
1095 }
1096 
1097 /*
1098  * Based on the value of resize we may only need to transmit first_n
1099  * entries and the last entry, with last_bytes to send from the last entry.
1100  * Note that first_n could be 0.
1101  */
1102 static inline int copy_partial_exec_reqs(struct qaic_device *qdev, struct bo_slice *slice,
1103 					 u64 resize, u32 dbc_id, u32 head, u32 *ptail)
1104 {
1105 	struct dma_bridge_chan *dbc = &qdev->dbc[dbc_id];
1106 	struct dbc_req *reqs = slice->reqs;
1107 	struct dbc_req *last_req;
1108 	u32 tail = *ptail;
1109 	u64 total_bytes;
1110 	u64 last_bytes;
1111 	u32 first_n;
1112 	u32 avail;
1113 	int ret;
1114 	int i;
1115 
1116 	avail = head - tail;
1117 	if (head <= tail)
1118 		avail += dbc->nelem;
1119 
1120 	--avail;
1121 
1122 	total_bytes = 0;
1123 	for (i = 0; i < slice->nents; i++) {
1124 		total_bytes += le32_to_cpu(reqs[i].len);
1125 		if (total_bytes >= resize)
1126 			break;
1127 	}
1128 
1129 	if (total_bytes < resize) {
1130 		/* User space should have used the full buffer path. */
1131 		ret = -EINVAL;
1132 		return ret;
1133 	}
1134 
1135 	first_n = i;
1136 	last_bytes = i ? resize + le32_to_cpu(reqs[i].len) - total_bytes : resize;
1137 
1138 	if (avail < (first_n + 1))
1139 		return -EAGAIN;
1140 
1141 	if (first_n) {
1142 		if (tail + first_n > dbc->nelem) {
1143 			avail = dbc->nelem - tail;
1144 			avail = min_t(u32, avail, first_n);
1145 			memcpy(dbc->req_q_base + tail * get_dbc_req_elem_size(), reqs,
1146 			       sizeof(*reqs) * avail);
1147 			last_req = reqs + avail;
1148 			avail = first_n - avail;
1149 			if (avail)
1150 				memcpy(dbc->req_q_base, last_req, sizeof(*reqs) * avail);
1151 		} else {
1152 			memcpy(dbc->req_q_base + tail * get_dbc_req_elem_size(), reqs,
1153 			       sizeof(*reqs) * first_n);
1154 		}
1155 	}
1156 
1157 	/* Copy over the last entry. Here we need to adjust len to the left over
1158 	 * size, and set src and dst to the entry it is copied to.
1159 	 */
1160 	last_req = dbc->req_q_base + (tail + first_n) % dbc->nelem * get_dbc_req_elem_size();
1161 	memcpy(last_req, reqs + slice->nents - 1, sizeof(*reqs));
1162 
1163 	/*
1164 	 * last_bytes holds size of a DMA segment, maximum DMA segment size is
1165 	 * set to UINT_MAX by qaic and hence last_bytes can never exceed u32
1166 	 * range. So, by down sizing we are not corrupting the value.
1167 	 */
1168 	last_req->len = cpu_to_le32((u32)last_bytes);
1169 	last_req->src_addr = reqs[first_n].src_addr;
1170 	last_req->dest_addr = reqs[first_n].dest_addr;
1171 
1172 	*ptail = (tail + first_n + 1) % dbc->nelem;
1173 
1174 	return 0;
1175 }
1176 
1177 static int send_bo_list_to_device(struct qaic_device *qdev, struct drm_file *file_priv,
1178 				  struct qaic_execute_entry *exec, unsigned int count,
1179 				  bool is_partial, struct dma_bridge_chan *dbc, u32 head,
1180 				  u32 *tail)
1181 {
1182 	struct qaic_partial_execute_entry *pexec = (struct qaic_partial_execute_entry *)exec;
1183 	struct drm_gem_object *obj;
1184 	struct bo_slice *slice;
1185 	unsigned long flags;
1186 	struct qaic_bo *bo;
1187 	bool queued;
1188 	int i, j;
1189 	int ret;
1190 
1191 	for (i = 0; i < count; i++) {
1192 		/*
1193 		 * ref count will be decremented when the transfer of this
1194 		 * buffer is complete. It is inside dbc_irq_threaded_fn().
1195 		 */
1196 		obj = drm_gem_object_lookup(file_priv,
1197 					    is_partial ? pexec[i].handle : exec[i].handle);
1198 		if (!obj) {
1199 			ret = -ENOENT;
1200 			goto failed_to_send_bo;
1201 		}
1202 
1203 		bo = to_qaic_bo(obj);
1204 		ret = mutex_lock_interruptible(&bo->lock);
1205 		if (ret)
1206 			goto failed_to_send_bo;
1207 
1208 		if (!bo->sliced) {
1209 			ret = -EINVAL;
1210 			goto unlock_bo;
1211 		}
1212 
1213 		if (is_partial && pexec[i].resize > bo->base.size) {
1214 			ret = -EINVAL;
1215 			goto unlock_bo;
1216 		}
1217 
1218 		spin_lock_irqsave(&dbc->xfer_lock, flags);
1219 		queued = bo->queued;
1220 		bo->queued = true;
1221 		if (queued) {
1222 			spin_unlock_irqrestore(&dbc->xfer_lock, flags);
1223 			ret = -EINVAL;
1224 			goto unlock_bo;
1225 		}
1226 
1227 		bo->req_id = dbc->next_req_id++;
1228 
1229 		list_for_each_entry(slice, &bo->slices, slice) {
1230 			/*
1231 			 * If this slice does not fall under the given
1232 			 * resize then skip this slice and continue the loop
1233 			 */
1234 			if (is_partial && pexec[i].resize && pexec[i].resize <= slice->offset)
1235 				continue;
1236 
1237 			for (j = 0; j < slice->nents; j++)
1238 				slice->reqs[j].req_id = cpu_to_le16(bo->req_id);
1239 
1240 			/*
1241 			 * If it is a partial execute ioctl call then check if
1242 			 * resize has cut this slice short then do a partial copy
1243 			 * else do complete copy
1244 			 */
1245 			if (is_partial && pexec[i].resize &&
1246 			    pexec[i].resize < slice->offset + slice->size)
1247 				ret = copy_partial_exec_reqs(qdev, slice,
1248 							     pexec[i].resize - slice->offset,
1249 							     dbc->id, head, tail);
1250 			else
1251 				ret = copy_exec_reqs(qdev, slice, dbc->id, head, tail);
1252 			if (ret) {
1253 				bo->queued = false;
1254 				spin_unlock_irqrestore(&dbc->xfer_lock, flags);
1255 				goto unlock_bo;
1256 			}
1257 		}
1258 		reinit_completion(&bo->xfer_done);
1259 		list_add_tail(&bo->xfer_list, &dbc->xfer_list);
1260 		spin_unlock_irqrestore(&dbc->xfer_lock, flags);
1261 		dma_sync_sgtable_for_device(&qdev->pdev->dev, bo->sgt, bo->dir);
1262 		mutex_unlock(&bo->lock);
1263 	}
1264 
1265 	return 0;
1266 
1267 unlock_bo:
1268 	mutex_unlock(&bo->lock);
1269 failed_to_send_bo:
1270 	if (likely(obj))
1271 		drm_gem_object_put(obj);
1272 	for (j = 0; j < i; j++) {
1273 		spin_lock_irqsave(&dbc->xfer_lock, flags);
1274 		bo = list_last_entry(&dbc->xfer_list, struct qaic_bo, xfer_list);
1275 		obj = &bo->base;
1276 		bo->queued = false;
1277 		list_del(&bo->xfer_list);
1278 		spin_unlock_irqrestore(&dbc->xfer_lock, flags);
1279 		dma_sync_sgtable_for_cpu(&qdev->pdev->dev, bo->sgt, bo->dir);
1280 		drm_gem_object_put(obj);
1281 	}
1282 	return ret;
1283 }
1284 
1285 static void update_profiling_data(struct drm_file *file_priv,
1286 				  struct qaic_execute_entry *exec, unsigned int count,
1287 				  bool is_partial, u64 received_ts, u64 submit_ts, u32 queue_level)
1288 {
1289 	struct qaic_partial_execute_entry *pexec = (struct qaic_partial_execute_entry *)exec;
1290 	struct drm_gem_object *obj;
1291 	struct qaic_bo *bo;
1292 	int i;
1293 
1294 	for (i = 0; i < count; i++) {
1295 		/*
1296 		 * Since we already committed the BO to hardware, the only way
1297 		 * this should fail is a pending signal. We can't cancel the
1298 		 * submit to hardware, so we have to just skip the profiling
1299 		 * data. In case the signal is not fatal to the process, we
1300 		 * return success so that the user doesn't try to resubmit.
1301 		 */
1302 		obj = drm_gem_object_lookup(file_priv,
1303 					    is_partial ? pexec[i].handle : exec[i].handle);
1304 		if (!obj)
1305 			break;
1306 		bo = to_qaic_bo(obj);
1307 		bo->perf_stats.req_received_ts = received_ts;
1308 		bo->perf_stats.req_submit_ts = submit_ts;
1309 		bo->perf_stats.queue_level_before = queue_level;
1310 		queue_level += bo->total_slice_nents;
1311 		drm_gem_object_put(obj);
1312 	}
1313 }
1314 
1315 static int __qaic_execute_bo_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv,
1316 				   bool is_partial)
1317 {
1318 	struct qaic_execute *args = data;
1319 	struct qaic_execute_entry *exec;
1320 	struct dma_bridge_chan *dbc;
1321 	int usr_rcu_id, qdev_rcu_id;
1322 	struct qaic_device *qdev;
1323 	struct qaic_user *usr;
1324 	u8 __user *user_data;
1325 	unsigned long n;
1326 	u64 received_ts;
1327 	u32 queue_level;
1328 	u64 submit_ts;
1329 	int rcu_id;
1330 	u32 head;
1331 	u32 tail;
1332 	u64 size;
1333 	int ret;
1334 
1335 	received_ts = ktime_get_ns();
1336 
1337 	size = is_partial ? sizeof(struct qaic_partial_execute_entry) : sizeof(*exec);
1338 	n = (unsigned long)size * args->hdr.count;
1339 	if (args->hdr.count == 0 || n / args->hdr.count != size)
1340 		return -EINVAL;
1341 
1342 	user_data = u64_to_user_ptr(args->data);
1343 
1344 	exec = kcalloc(args->hdr.count, size, GFP_KERNEL);
1345 	if (!exec)
1346 		return -ENOMEM;
1347 
1348 	if (copy_from_user(exec, user_data, n)) {
1349 		ret = -EFAULT;
1350 		goto free_exec;
1351 	}
1352 
1353 	usr = file_priv->driver_priv;
1354 	usr_rcu_id = srcu_read_lock(&usr->qddev_lock);
1355 	if (!usr->qddev) {
1356 		ret = -ENODEV;
1357 		goto unlock_usr_srcu;
1358 	}
1359 
1360 	qdev = usr->qddev->qdev;
1361 	qdev_rcu_id = srcu_read_lock(&qdev->dev_lock);
1362 	if (qdev->in_reset) {
1363 		ret = -ENODEV;
1364 		goto unlock_dev_srcu;
1365 	}
1366 
1367 	if (args->hdr.dbc_id >= qdev->num_dbc) {
1368 		ret = -EINVAL;
1369 		goto unlock_dev_srcu;
1370 	}
1371 
1372 	dbc = &qdev->dbc[args->hdr.dbc_id];
1373 
1374 	rcu_id = srcu_read_lock(&dbc->ch_lock);
1375 	if (!dbc->usr || dbc->usr->handle != usr->handle) {
1376 		ret = -EPERM;
1377 		goto release_ch_rcu;
1378 	}
1379 
1380 	head = readl(dbc->dbc_base + REQHP_OFF);
1381 	tail = readl(dbc->dbc_base + REQTP_OFF);
1382 
1383 	if (head == U32_MAX || tail == U32_MAX) {
1384 		/* PCI link error */
1385 		ret = -ENODEV;
1386 		goto release_ch_rcu;
1387 	}
1388 
1389 	queue_level = head <= tail ? tail - head : dbc->nelem - (head - tail);
1390 
1391 	ret = send_bo_list_to_device(qdev, file_priv, exec, args->hdr.count, is_partial, dbc,
1392 				     head, &tail);
1393 	if (ret)
1394 		goto release_ch_rcu;
1395 
1396 	/* Finalize commit to hardware */
1397 	submit_ts = ktime_get_ns();
1398 	writel(tail, dbc->dbc_base + REQTP_OFF);
1399 
1400 	update_profiling_data(file_priv, exec, args->hdr.count, is_partial, received_ts,
1401 			      submit_ts, queue_level);
1402 
1403 	if (datapath_polling)
1404 		schedule_work(&dbc->poll_work);
1405 
1406 release_ch_rcu:
1407 	srcu_read_unlock(&dbc->ch_lock, rcu_id);
1408 unlock_dev_srcu:
1409 	srcu_read_unlock(&qdev->dev_lock, qdev_rcu_id);
1410 unlock_usr_srcu:
1411 	srcu_read_unlock(&usr->qddev_lock, usr_rcu_id);
1412 free_exec:
1413 	kfree(exec);
1414 	return ret;
1415 }
1416 
1417 int qaic_execute_bo_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv)
1418 {
1419 	return __qaic_execute_bo_ioctl(dev, data, file_priv, false);
1420 }
1421 
1422 int qaic_partial_execute_bo_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv)
1423 {
1424 	return __qaic_execute_bo_ioctl(dev, data, file_priv, true);
1425 }
1426 
1427 /*
1428  * Our interrupt handling is a bit more complicated than a simple ideal, but
1429  * sadly necessary.
1430  *
1431  * Each dbc has a completion queue. Entries in the queue correspond to DMA
1432  * requests which the device has processed. The hardware already has a built
1433  * in irq mitigation. When the device puts an entry into the queue, it will
1434  * only trigger an interrupt if the queue was empty. Therefore, when adding
1435  * the Nth event to a non-empty queue, the hardware doesn't trigger an
1436  * interrupt. This means the host doesn't get additional interrupts signaling
1437  * the same thing - the queue has something to process.
1438  * This behavior can be overridden in the DMA request.
1439  * This means that when the host receives an interrupt, it is required to
1440  * drain the queue.
1441  *
1442  * This behavior is what NAPI attempts to accomplish, although we can't use
1443  * NAPI as we don't have a netdev. We use threaded irqs instead.
1444  *
1445  * However, there is a situation where the host drains the queue fast enough
1446  * that every event causes an interrupt. Typically this is not a problem as
1447  * the rate of events would be low. However, that is not the case with
1448  * lprnet for example. On an Intel Xeon D-2191 where we run 8 instances of
1449  * lprnet, the host receives roughly 80k interrupts per second from the device
1450  * (per /proc/interrupts). While NAPI documentation indicates the host should
1451  * just chug along, sadly that behavior causes instability in some hosts.
1452  *
1453  * Therefore, we implement an interrupt disable scheme similar to NAPI. The
1454  * key difference is that we will delay after draining the queue for a small
1455  * time to allow additional events to come in via polling. Using the above
1456  * lprnet workload, this reduces the number of interrupts processed from
1457  * ~80k/sec to about 64 in 5 minutes and appears to solve the system
1458  * instability.
1459  */
1460 irqreturn_t dbc_irq_handler(int irq, void *data)
1461 {
1462 	struct dma_bridge_chan *dbc = data;
1463 	int rcu_id;
1464 	u32 head;
1465 	u32 tail;
1466 
1467 	rcu_id = srcu_read_lock(&dbc->ch_lock);
1468 
1469 	if (!dbc->usr) {
1470 		srcu_read_unlock(&dbc->ch_lock, rcu_id);
1471 		return IRQ_HANDLED;
1472 	}
1473 
1474 	head = readl(dbc->dbc_base + RSPHP_OFF);
1475 	if (head == U32_MAX) { /* PCI link error */
1476 		srcu_read_unlock(&dbc->ch_lock, rcu_id);
1477 		return IRQ_NONE;
1478 	}
1479 
1480 	tail = readl(dbc->dbc_base + RSPTP_OFF);
1481 	if (tail == U32_MAX) { /* PCI link error */
1482 		srcu_read_unlock(&dbc->ch_lock, rcu_id);
1483 		return IRQ_NONE;
1484 	}
1485 
1486 	if (head == tail) { /* queue empty */
1487 		srcu_read_unlock(&dbc->ch_lock, rcu_id);
1488 		return IRQ_NONE;
1489 	}
1490 
1491 	disable_irq_nosync(irq);
1492 	srcu_read_unlock(&dbc->ch_lock, rcu_id);
1493 	return IRQ_WAKE_THREAD;
1494 }
1495 
1496 void irq_polling_work(struct work_struct *work)
1497 {
1498 	struct dma_bridge_chan *dbc = container_of(work, struct dma_bridge_chan,  poll_work);
1499 	unsigned long flags;
1500 	int rcu_id;
1501 	u32 head;
1502 	u32 tail;
1503 
1504 	rcu_id = srcu_read_lock(&dbc->ch_lock);
1505 
1506 	while (1) {
1507 		if (dbc->qdev->in_reset) {
1508 			srcu_read_unlock(&dbc->ch_lock, rcu_id);
1509 			return;
1510 		}
1511 		if (!dbc->usr) {
1512 			srcu_read_unlock(&dbc->ch_lock, rcu_id);
1513 			return;
1514 		}
1515 		spin_lock_irqsave(&dbc->xfer_lock, flags);
1516 		if (list_empty(&dbc->xfer_list)) {
1517 			spin_unlock_irqrestore(&dbc->xfer_lock, flags);
1518 			srcu_read_unlock(&dbc->ch_lock, rcu_id);
1519 			return;
1520 		}
1521 		spin_unlock_irqrestore(&dbc->xfer_lock, flags);
1522 
1523 		head = readl(dbc->dbc_base + RSPHP_OFF);
1524 		if (head == U32_MAX) { /* PCI link error */
1525 			srcu_read_unlock(&dbc->ch_lock, rcu_id);
1526 			return;
1527 		}
1528 
1529 		tail = readl(dbc->dbc_base + RSPTP_OFF);
1530 		if (tail == U32_MAX) { /* PCI link error */
1531 			srcu_read_unlock(&dbc->ch_lock, rcu_id);
1532 			return;
1533 		}
1534 
1535 		if (head != tail) {
1536 			irq_wake_thread(dbc->irq, dbc);
1537 			srcu_read_unlock(&dbc->ch_lock, rcu_id);
1538 			return;
1539 		}
1540 
1541 		cond_resched();
1542 		usleep_range(datapath_poll_interval_us, 2 * datapath_poll_interval_us);
1543 	}
1544 }
1545 
1546 irqreturn_t dbc_irq_threaded_fn(int irq, void *data)
1547 {
1548 	struct dma_bridge_chan *dbc = data;
1549 	int event_count = NUM_EVENTS;
1550 	int delay_count = NUM_DELAYS;
1551 	struct qaic_device *qdev;
1552 	struct qaic_bo *bo, *i;
1553 	struct dbc_rsp *rsp;
1554 	unsigned long flags;
1555 	int rcu_id;
1556 	u16 status;
1557 	u16 req_id;
1558 	u32 head;
1559 	u32 tail;
1560 
1561 	rcu_id = srcu_read_lock(&dbc->ch_lock);
1562 
1563 	head = readl(dbc->dbc_base + RSPHP_OFF);
1564 	if (head == U32_MAX) /* PCI link error */
1565 		goto error_out;
1566 
1567 	qdev = dbc->qdev;
1568 read_fifo:
1569 
1570 	if (!event_count) {
1571 		event_count = NUM_EVENTS;
1572 		cond_resched();
1573 	}
1574 
1575 	/*
1576 	 * if this channel isn't assigned or gets unassigned during processing
1577 	 * we have nothing further to do
1578 	 */
1579 	if (!dbc->usr)
1580 		goto error_out;
1581 
1582 	tail = readl(dbc->dbc_base + RSPTP_OFF);
1583 	if (tail == U32_MAX) /* PCI link error */
1584 		goto error_out;
1585 
1586 	if (head == tail) { /* queue empty */
1587 		if (delay_count) {
1588 			--delay_count;
1589 			usleep_range(100, 200);
1590 			goto read_fifo; /* check for a new event */
1591 		}
1592 		goto normal_out;
1593 	}
1594 
1595 	delay_count = NUM_DELAYS;
1596 	while (head != tail) {
1597 		if (!event_count)
1598 			break;
1599 		--event_count;
1600 		rsp = dbc->rsp_q_base + head * sizeof(*rsp);
1601 		req_id = le16_to_cpu(rsp->req_id);
1602 		status = le16_to_cpu(rsp->status);
1603 		if (status)
1604 			pci_dbg(qdev->pdev, "req_id %d failed with status %d\n", req_id, status);
1605 		spin_lock_irqsave(&dbc->xfer_lock, flags);
1606 		/*
1607 		 * A BO can receive multiple interrupts, since a BO can be
1608 		 * divided into multiple slices and a buffer receives as many
1609 		 * interrupts as slices. So until it receives interrupts for
1610 		 * all the slices we cannot mark that buffer complete.
1611 		 */
1612 		list_for_each_entry_safe(bo, i, &dbc->xfer_list, xfer_list) {
1613 			if (bo->req_id == req_id)
1614 				bo->nr_slice_xfer_done++;
1615 			else
1616 				continue;
1617 
1618 			if (bo->nr_slice_xfer_done < bo->nr_slice)
1619 				break;
1620 
1621 			/*
1622 			 * At this point we have received all the interrupts for
1623 			 * BO, which means BO execution is complete.
1624 			 */
1625 			dma_sync_sgtable_for_cpu(&qdev->pdev->dev, bo->sgt, bo->dir);
1626 			bo->nr_slice_xfer_done = 0;
1627 			bo->queued = false;
1628 			list_del(&bo->xfer_list);
1629 			bo->perf_stats.req_processed_ts = ktime_get_ns();
1630 			complete_all(&bo->xfer_done);
1631 			drm_gem_object_put(&bo->base);
1632 			break;
1633 		}
1634 		spin_unlock_irqrestore(&dbc->xfer_lock, flags);
1635 		head = (head + 1) % dbc->nelem;
1636 	}
1637 
1638 	/*
1639 	 * Update the head pointer of response queue and let the device know
1640 	 * that we have consumed elements from the queue.
1641 	 */
1642 	writel(head, dbc->dbc_base + RSPHP_OFF);
1643 
1644 	/* elements might have been put in the queue while we were processing */
1645 	goto read_fifo;
1646 
1647 normal_out:
1648 	if (likely(!datapath_polling))
1649 		enable_irq(irq);
1650 	else
1651 		schedule_work(&dbc->poll_work);
1652 	/* checking the fifo and enabling irqs is a race, missed event check */
1653 	tail = readl(dbc->dbc_base + RSPTP_OFF);
1654 	if (tail != U32_MAX && head != tail) {
1655 		if (likely(!datapath_polling))
1656 			disable_irq_nosync(irq);
1657 		goto read_fifo;
1658 	}
1659 	srcu_read_unlock(&dbc->ch_lock, rcu_id);
1660 	return IRQ_HANDLED;
1661 
1662 error_out:
1663 	srcu_read_unlock(&dbc->ch_lock, rcu_id);
1664 	if (likely(!datapath_polling))
1665 		enable_irq(irq);
1666 	else
1667 		schedule_work(&dbc->poll_work);
1668 
1669 	return IRQ_HANDLED;
1670 }
1671 
1672 int qaic_wait_bo_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv)
1673 {
1674 	struct qaic_wait *args = data;
1675 	int usr_rcu_id, qdev_rcu_id;
1676 	struct dma_bridge_chan *dbc;
1677 	struct drm_gem_object *obj;
1678 	struct qaic_device *qdev;
1679 	unsigned long timeout;
1680 	struct qaic_user *usr;
1681 	struct qaic_bo *bo;
1682 	int rcu_id;
1683 	int ret;
1684 
1685 	if (args->pad != 0)
1686 		return -EINVAL;
1687 
1688 	usr = file_priv->driver_priv;
1689 	usr_rcu_id = srcu_read_lock(&usr->qddev_lock);
1690 	if (!usr->qddev) {
1691 		ret = -ENODEV;
1692 		goto unlock_usr_srcu;
1693 	}
1694 
1695 	qdev = usr->qddev->qdev;
1696 	qdev_rcu_id = srcu_read_lock(&qdev->dev_lock);
1697 	if (qdev->in_reset) {
1698 		ret = -ENODEV;
1699 		goto unlock_dev_srcu;
1700 	}
1701 
1702 	if (args->dbc_id >= qdev->num_dbc) {
1703 		ret = -EINVAL;
1704 		goto unlock_dev_srcu;
1705 	}
1706 
1707 	dbc = &qdev->dbc[args->dbc_id];
1708 
1709 	rcu_id = srcu_read_lock(&dbc->ch_lock);
1710 	if (dbc->usr != usr) {
1711 		ret = -EPERM;
1712 		goto unlock_ch_srcu;
1713 	}
1714 
1715 	obj = drm_gem_object_lookup(file_priv, args->handle);
1716 	if (!obj) {
1717 		ret = -ENOENT;
1718 		goto unlock_ch_srcu;
1719 	}
1720 
1721 	bo = to_qaic_bo(obj);
1722 	timeout = args->timeout ? args->timeout : wait_exec_default_timeout_ms;
1723 	timeout = msecs_to_jiffies(timeout);
1724 	ret = wait_for_completion_interruptible_timeout(&bo->xfer_done, timeout);
1725 	if (!ret) {
1726 		ret = -ETIMEDOUT;
1727 		goto put_obj;
1728 	}
1729 	if (ret > 0)
1730 		ret = 0;
1731 
1732 	if (!dbc->usr)
1733 		ret = -EPERM;
1734 
1735 put_obj:
1736 	drm_gem_object_put(obj);
1737 unlock_ch_srcu:
1738 	srcu_read_unlock(&dbc->ch_lock, rcu_id);
1739 unlock_dev_srcu:
1740 	srcu_read_unlock(&qdev->dev_lock, qdev_rcu_id);
1741 unlock_usr_srcu:
1742 	srcu_read_unlock(&usr->qddev_lock, usr_rcu_id);
1743 	return ret;
1744 }
1745 
1746 int qaic_perf_stats_bo_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv)
1747 {
1748 	struct qaic_perf_stats_entry *ent = NULL;
1749 	struct qaic_perf_stats *args = data;
1750 	int usr_rcu_id, qdev_rcu_id;
1751 	struct drm_gem_object *obj;
1752 	struct qaic_device *qdev;
1753 	struct qaic_user *usr;
1754 	struct qaic_bo *bo;
1755 	int ret, i;
1756 
1757 	usr = file_priv->driver_priv;
1758 	usr_rcu_id = srcu_read_lock(&usr->qddev_lock);
1759 	if (!usr->qddev) {
1760 		ret = -ENODEV;
1761 		goto unlock_usr_srcu;
1762 	}
1763 
1764 	qdev = usr->qddev->qdev;
1765 	qdev_rcu_id = srcu_read_lock(&qdev->dev_lock);
1766 	if (qdev->in_reset) {
1767 		ret = -ENODEV;
1768 		goto unlock_dev_srcu;
1769 	}
1770 
1771 	if (args->hdr.dbc_id >= qdev->num_dbc) {
1772 		ret = -EINVAL;
1773 		goto unlock_dev_srcu;
1774 	}
1775 
1776 	ent = kcalloc(args->hdr.count, sizeof(*ent), GFP_KERNEL);
1777 	if (!ent) {
1778 		ret = -EINVAL;
1779 		goto unlock_dev_srcu;
1780 	}
1781 
1782 	ret = copy_from_user(ent, u64_to_user_ptr(args->data), args->hdr.count * sizeof(*ent));
1783 	if (ret) {
1784 		ret = -EFAULT;
1785 		goto free_ent;
1786 	}
1787 
1788 	for (i = 0; i < args->hdr.count; i++) {
1789 		obj = drm_gem_object_lookup(file_priv, ent[i].handle);
1790 		if (!obj) {
1791 			ret = -ENOENT;
1792 			goto free_ent;
1793 		}
1794 		bo = to_qaic_bo(obj);
1795 		/*
1796 		 * perf stats ioctl is called before wait ioctl is complete then
1797 		 * the latency information is invalid.
1798 		 */
1799 		if (bo->perf_stats.req_processed_ts < bo->perf_stats.req_submit_ts) {
1800 			ent[i].device_latency_us = 0;
1801 		} else {
1802 			ent[i].device_latency_us = div_u64((bo->perf_stats.req_processed_ts -
1803 							    bo->perf_stats.req_submit_ts), 1000);
1804 		}
1805 		ent[i].submit_latency_us = div_u64((bo->perf_stats.req_submit_ts -
1806 						    bo->perf_stats.req_received_ts), 1000);
1807 		ent[i].queue_level_before = bo->perf_stats.queue_level_before;
1808 		ent[i].num_queue_element = bo->total_slice_nents;
1809 		drm_gem_object_put(obj);
1810 	}
1811 
1812 	if (copy_to_user(u64_to_user_ptr(args->data), ent, args->hdr.count * sizeof(*ent)))
1813 		ret = -EFAULT;
1814 
1815 free_ent:
1816 	kfree(ent);
1817 unlock_dev_srcu:
1818 	srcu_read_unlock(&qdev->dev_lock, qdev_rcu_id);
1819 unlock_usr_srcu:
1820 	srcu_read_unlock(&usr->qddev_lock, usr_rcu_id);
1821 	return ret;
1822 }
1823 
1824 static void detach_slice_bo(struct qaic_device *qdev, struct qaic_bo *bo)
1825 {
1826 	qaic_free_slices_bo(bo);
1827 	qaic_unprepare_bo(qdev, bo);
1828 	qaic_init_bo(bo, true);
1829 	list_del(&bo->bo_list);
1830 	drm_gem_object_put(&bo->base);
1831 }
1832 
1833 int qaic_detach_slice_bo_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv)
1834 {
1835 	struct qaic_detach_slice *args = data;
1836 	int rcu_id, usr_rcu_id, qdev_rcu_id;
1837 	struct dma_bridge_chan *dbc;
1838 	struct drm_gem_object *obj;
1839 	struct qaic_device *qdev;
1840 	struct qaic_user *usr;
1841 	unsigned long flags;
1842 	struct qaic_bo *bo;
1843 	int ret;
1844 
1845 	if (args->pad != 0)
1846 		return -EINVAL;
1847 
1848 	usr = file_priv->driver_priv;
1849 	usr_rcu_id = srcu_read_lock(&usr->qddev_lock);
1850 	if (!usr->qddev) {
1851 		ret = -ENODEV;
1852 		goto unlock_usr_srcu;
1853 	}
1854 
1855 	qdev = usr->qddev->qdev;
1856 	qdev_rcu_id = srcu_read_lock(&qdev->dev_lock);
1857 	if (qdev->in_reset) {
1858 		ret = -ENODEV;
1859 		goto unlock_dev_srcu;
1860 	}
1861 
1862 	obj = drm_gem_object_lookup(file_priv, args->handle);
1863 	if (!obj) {
1864 		ret = -ENOENT;
1865 		goto unlock_dev_srcu;
1866 	}
1867 
1868 	bo = to_qaic_bo(obj);
1869 	ret = mutex_lock_interruptible(&bo->lock);
1870 	if (ret)
1871 		goto put_bo;
1872 
1873 	if (!bo->sliced) {
1874 		ret = -EINVAL;
1875 		goto unlock_bo;
1876 	}
1877 
1878 	dbc = bo->dbc;
1879 	rcu_id = srcu_read_lock(&dbc->ch_lock);
1880 	if (dbc->usr != usr) {
1881 		ret = -EINVAL;
1882 		goto unlock_ch_srcu;
1883 	}
1884 
1885 	/* Check if BO is committed to H/W for DMA */
1886 	spin_lock_irqsave(&dbc->xfer_lock, flags);
1887 	if (bo->queued) {
1888 		spin_unlock_irqrestore(&dbc->xfer_lock, flags);
1889 		ret = -EBUSY;
1890 		goto unlock_ch_srcu;
1891 	}
1892 	spin_unlock_irqrestore(&dbc->xfer_lock, flags);
1893 
1894 	detach_slice_bo(qdev, bo);
1895 
1896 unlock_ch_srcu:
1897 	srcu_read_unlock(&dbc->ch_lock, rcu_id);
1898 unlock_bo:
1899 	mutex_unlock(&bo->lock);
1900 put_bo:
1901 	drm_gem_object_put(obj);
1902 unlock_dev_srcu:
1903 	srcu_read_unlock(&qdev->dev_lock, qdev_rcu_id);
1904 unlock_usr_srcu:
1905 	srcu_read_unlock(&usr->qddev_lock, usr_rcu_id);
1906 	return ret;
1907 }
1908 
1909 static void empty_xfer_list(struct qaic_device *qdev, struct dma_bridge_chan *dbc)
1910 {
1911 	unsigned long flags;
1912 	struct qaic_bo *bo;
1913 
1914 	spin_lock_irqsave(&dbc->xfer_lock, flags);
1915 	while (!list_empty(&dbc->xfer_list)) {
1916 		bo = list_first_entry(&dbc->xfer_list, typeof(*bo), xfer_list);
1917 		bo->queued = false;
1918 		list_del(&bo->xfer_list);
1919 		spin_unlock_irqrestore(&dbc->xfer_lock, flags);
1920 		bo->nr_slice_xfer_done = 0;
1921 		bo->req_id = 0;
1922 		bo->perf_stats.req_received_ts = 0;
1923 		bo->perf_stats.req_submit_ts = 0;
1924 		bo->perf_stats.req_processed_ts = 0;
1925 		bo->perf_stats.queue_level_before = 0;
1926 		dma_sync_sgtable_for_cpu(&qdev->pdev->dev, bo->sgt, bo->dir);
1927 		complete_all(&bo->xfer_done);
1928 		drm_gem_object_put(&bo->base);
1929 		spin_lock_irqsave(&dbc->xfer_lock, flags);
1930 	}
1931 	spin_unlock_irqrestore(&dbc->xfer_lock, flags);
1932 }
1933 
1934 int disable_dbc(struct qaic_device *qdev, u32 dbc_id, struct qaic_user *usr)
1935 {
1936 	if (!qdev->dbc[dbc_id].usr || qdev->dbc[dbc_id].usr->handle != usr->handle)
1937 		return -EPERM;
1938 
1939 	qdev->dbc[dbc_id].usr = NULL;
1940 	synchronize_srcu(&qdev->dbc[dbc_id].ch_lock);
1941 	return 0;
1942 }
1943 
1944 /**
1945  * enable_dbc - Enable the DBC. DBCs are disabled by removing the context of
1946  * user. Add user context back to DBC to enable it. This function trusts the
1947  * DBC ID passed and expects the DBC to be disabled.
1948  * @qdev: Qranium device handle
1949  * @dbc_id: ID of the DBC
1950  * @usr: User context
1951  */
1952 void enable_dbc(struct qaic_device *qdev, u32 dbc_id, struct qaic_user *usr)
1953 {
1954 	qdev->dbc[dbc_id].usr = usr;
1955 }
1956 
1957 void wakeup_dbc(struct qaic_device *qdev, u32 dbc_id)
1958 {
1959 	struct dma_bridge_chan *dbc = &qdev->dbc[dbc_id];
1960 
1961 	dbc->usr = NULL;
1962 	empty_xfer_list(qdev, dbc);
1963 	synchronize_srcu(&dbc->ch_lock);
1964 	/*
1965 	 * Threads holding channel lock, may add more elements in the xfer_list.
1966 	 * Flush out these elements from xfer_list.
1967 	 */
1968 	empty_xfer_list(qdev, dbc);
1969 }
1970 
1971 void release_dbc(struct qaic_device *qdev, u32 dbc_id)
1972 {
1973 	struct qaic_bo *bo, *bo_temp;
1974 	struct dma_bridge_chan *dbc;
1975 
1976 	dbc = &qdev->dbc[dbc_id];
1977 	if (!dbc->in_use)
1978 		return;
1979 
1980 	wakeup_dbc(qdev, dbc_id);
1981 
1982 	dma_free_coherent(&qdev->pdev->dev, dbc->total_size, dbc->req_q_base, dbc->dma_addr);
1983 	dbc->total_size = 0;
1984 	dbc->req_q_base = NULL;
1985 	dbc->dma_addr = 0;
1986 	dbc->nelem = 0;
1987 	dbc->usr = NULL;
1988 
1989 	list_for_each_entry_safe(bo, bo_temp, &dbc->bo_lists, bo_list) {
1990 		drm_gem_object_get(&bo->base);
1991 		mutex_lock(&bo->lock);
1992 		detach_slice_bo(qdev, bo);
1993 		mutex_unlock(&bo->lock);
1994 		drm_gem_object_put(&bo->base);
1995 	}
1996 
1997 	dbc->in_use = false;
1998 	wake_up(&dbc->dbc_release);
1999 }
2000