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