xref: /linux/drivers/accel/qaic/qaic_data.c (revision 9b966ae42235a88eaea714be09ff3d698535bdfe)
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 	kfree(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 = kcalloc(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 	kfree(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 const struct drm_gem_object_funcs qaic_gem_funcs = {
648 	.free = qaic_free_object,
649 	.print_info = qaic_gem_print_info,
650 	.mmap = qaic_gem_object_mmap,
651 	.vm_ops = &drm_vm_ops,
652 };
653 
654 static void qaic_init_bo(struct qaic_bo *bo, bool reinit)
655 {
656 	if (reinit) {
657 		bo->sliced = false;
658 		reinit_completion(&bo->xfer_done);
659 	} else {
660 		mutex_init(&bo->lock);
661 		init_completion(&bo->xfer_done);
662 	}
663 	complete_all(&bo->xfer_done);
664 	INIT_LIST_HEAD(&bo->slices);
665 	INIT_LIST_HEAD(&bo->xfer_list);
666 }
667 
668 static struct qaic_bo *qaic_alloc_init_bo(void)
669 {
670 	struct qaic_bo *bo;
671 
672 	bo = kzalloc(sizeof(*bo), GFP_KERNEL);
673 	if (!bo)
674 		return ERR_PTR(-ENOMEM);
675 
676 	qaic_init_bo(bo, false);
677 
678 	return bo;
679 }
680 
681 int qaic_create_bo_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv)
682 {
683 	struct qaic_create_bo *args = data;
684 	int usr_rcu_id, qdev_rcu_id;
685 	struct drm_gem_object *obj;
686 	struct qaic_device *qdev;
687 	struct qaic_user *usr;
688 	struct qaic_bo *bo;
689 	size_t size;
690 	int ret;
691 
692 	if (args->pad)
693 		return -EINVAL;
694 
695 	size = PAGE_ALIGN(args->size);
696 	if (size == 0)
697 		return -EINVAL;
698 
699 	usr = file_priv->driver_priv;
700 	usr_rcu_id = srcu_read_lock(&usr->qddev_lock);
701 	if (!usr->qddev) {
702 		ret = -ENODEV;
703 		goto unlock_usr_srcu;
704 	}
705 
706 	qdev = usr->qddev->qdev;
707 	qdev_rcu_id = srcu_read_lock(&qdev->dev_lock);
708 	if (qdev->dev_state != QAIC_ONLINE) {
709 		ret = -ENODEV;
710 		goto unlock_dev_srcu;
711 	}
712 
713 	bo = qaic_alloc_init_bo();
714 	if (IS_ERR(bo)) {
715 		ret = PTR_ERR(bo);
716 		goto unlock_dev_srcu;
717 	}
718 	obj = &bo->base;
719 
720 	drm_gem_private_object_init(dev, obj, size);
721 
722 	obj->funcs = &qaic_gem_funcs;
723 	ret = create_sgt(qdev, &bo->sgt, size);
724 	if (ret)
725 		goto free_bo;
726 
727 	ret = drm_gem_create_mmap_offset(obj);
728 	if (ret)
729 		goto free_bo;
730 
731 	ret = drm_gem_handle_create(file_priv, obj, &args->handle);
732 	if (ret)
733 		goto free_bo;
734 
735 	drm_gem_object_put(obj);
736 	srcu_read_unlock(&qdev->dev_lock, qdev_rcu_id);
737 	srcu_read_unlock(&usr->qddev_lock, usr_rcu_id);
738 
739 	return 0;
740 
741 free_bo:
742 	drm_gem_object_put(obj);
743 unlock_dev_srcu:
744 	srcu_read_unlock(&qdev->dev_lock, qdev_rcu_id);
745 unlock_usr_srcu:
746 	srcu_read_unlock(&usr->qddev_lock, usr_rcu_id);
747 	return ret;
748 }
749 
750 int qaic_mmap_bo_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv)
751 {
752 	struct qaic_mmap_bo *args = data;
753 	int usr_rcu_id, qdev_rcu_id;
754 	struct drm_gem_object *obj;
755 	struct qaic_device *qdev;
756 	struct qaic_user *usr;
757 	int ret = 0;
758 
759 	usr = file_priv->driver_priv;
760 	usr_rcu_id = srcu_read_lock(&usr->qddev_lock);
761 	if (!usr->qddev) {
762 		ret = -ENODEV;
763 		goto unlock_usr_srcu;
764 	}
765 
766 	qdev = usr->qddev->qdev;
767 	qdev_rcu_id = srcu_read_lock(&qdev->dev_lock);
768 	if (qdev->dev_state != QAIC_ONLINE) {
769 		ret = -ENODEV;
770 		goto unlock_dev_srcu;
771 	}
772 
773 	obj = drm_gem_object_lookup(file_priv, args->handle);
774 	if (!obj) {
775 		ret = -ENOENT;
776 		goto unlock_dev_srcu;
777 	}
778 
779 	args->offset = drm_vma_node_offset_addr(&obj->vma_node);
780 
781 	drm_gem_object_put(obj);
782 
783 unlock_dev_srcu:
784 	srcu_read_unlock(&qdev->dev_lock, qdev_rcu_id);
785 unlock_usr_srcu:
786 	srcu_read_unlock(&usr->qddev_lock, usr_rcu_id);
787 	return ret;
788 }
789 
790 struct drm_gem_object *qaic_gem_prime_import(struct drm_device *dev, struct dma_buf *dma_buf)
791 {
792 	struct dma_buf_attachment *attach;
793 	struct drm_gem_object *obj;
794 	struct qaic_bo *bo;
795 	int ret;
796 
797 	bo = qaic_alloc_init_bo();
798 	if (IS_ERR(bo)) {
799 		ret = PTR_ERR(bo);
800 		goto out;
801 	}
802 
803 	obj = &bo->base;
804 	get_dma_buf(dma_buf);
805 
806 	attach = dma_buf_attach(dma_buf, dev->dev);
807 	if (IS_ERR(attach)) {
808 		ret = PTR_ERR(attach);
809 		goto attach_fail;
810 	}
811 
812 	if (!attach->dmabuf->size) {
813 		ret = -EINVAL;
814 		goto size_align_fail;
815 	}
816 
817 	drm_gem_private_object_init(dev, obj, attach->dmabuf->size);
818 	/*
819 	 * skipping dma_buf_map_attachment() as we do not know the direction
820 	 * just yet. Once the direction is known in the subsequent IOCTL to
821 	 * attach slicing, we can do it then.
822 	 */
823 
824 	obj->funcs = &qaic_gem_funcs;
825 	obj->import_attach = attach;
826 	obj->resv = dma_buf->resv;
827 
828 	return obj;
829 
830 size_align_fail:
831 	dma_buf_detach(dma_buf, attach);
832 attach_fail:
833 	dma_buf_put(dma_buf);
834 	kfree(bo);
835 out:
836 	return ERR_PTR(ret);
837 }
838 
839 static int qaic_prepare_import_bo(struct qaic_bo *bo, struct qaic_attach_slice_hdr *hdr)
840 {
841 	struct drm_gem_object *obj = &bo->base;
842 	struct sg_table *sgt;
843 	int ret;
844 
845 	sgt = dma_buf_map_attachment(obj->import_attach, hdr->dir);
846 	if (IS_ERR(sgt)) {
847 		ret = PTR_ERR(sgt);
848 		return ret;
849 	}
850 
851 	bo->sgt = sgt;
852 
853 	return 0;
854 }
855 
856 static int qaic_prepare_export_bo(struct qaic_device *qdev, struct qaic_bo *bo,
857 				  struct qaic_attach_slice_hdr *hdr)
858 {
859 	int ret;
860 
861 	ret = dma_map_sgtable(&qdev->pdev->dev, bo->sgt, hdr->dir, 0);
862 	if (ret)
863 		return -EFAULT;
864 
865 	return 0;
866 }
867 
868 static int qaic_prepare_bo(struct qaic_device *qdev, struct qaic_bo *bo,
869 			   struct qaic_attach_slice_hdr *hdr)
870 {
871 	int ret;
872 
873 	if (drm_gem_is_imported(&bo->base))
874 		ret = qaic_prepare_import_bo(bo, hdr);
875 	else
876 		ret = qaic_prepare_export_bo(qdev, bo, hdr);
877 	bo->dir = hdr->dir;
878 	bo->dbc = &qdev->dbc[hdr->dbc_id];
879 	bo->nr_slice = hdr->count;
880 
881 	return ret;
882 }
883 
884 static void qaic_unprepare_import_bo(struct qaic_bo *bo)
885 {
886 	dma_buf_unmap_attachment(bo->base.import_attach, bo->sgt, bo->dir);
887 	bo->sgt = NULL;
888 }
889 
890 static void qaic_unprepare_export_bo(struct qaic_device *qdev, struct qaic_bo *bo)
891 {
892 	dma_unmap_sgtable(&qdev->pdev->dev, bo->sgt, bo->dir, 0);
893 }
894 
895 static void qaic_unprepare_bo(struct qaic_device *qdev, struct qaic_bo *bo)
896 {
897 	if (drm_gem_is_imported(&bo->base))
898 		qaic_unprepare_import_bo(bo);
899 	else
900 		qaic_unprepare_export_bo(qdev, bo);
901 
902 	bo->dir = 0;
903 	bo->dbc = NULL;
904 	bo->nr_slice = 0;
905 }
906 
907 static void qaic_free_slices_bo(struct qaic_bo *bo)
908 {
909 	struct bo_slice *slice, *temp;
910 
911 	list_for_each_entry_safe(slice, temp, &bo->slices, slice)
912 		kref_put(&slice->ref_count, free_slice);
913 	if (WARN_ON_ONCE(bo->total_slice_nents != 0))
914 		bo->total_slice_nents = 0;
915 	bo->nr_slice = 0;
916 }
917 
918 static int qaic_attach_slicing_bo(struct qaic_device *qdev, struct qaic_bo *bo,
919 				  struct qaic_attach_slice_hdr *hdr,
920 				  struct qaic_attach_slice_entry *slice_ent)
921 {
922 	int ret, i;
923 
924 	for (i = 0; i < hdr->count; i++) {
925 		ret = qaic_map_one_slice(qdev, bo, &slice_ent[i]);
926 		if (ret) {
927 			qaic_free_slices_bo(bo);
928 			return ret;
929 		}
930 	}
931 
932 	if (bo->total_slice_nents > bo->dbc->nelem) {
933 		qaic_free_slices_bo(bo);
934 		return -ENOSPC;
935 	}
936 
937 	return 0;
938 }
939 
940 int qaic_attach_slice_bo_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv)
941 {
942 	struct qaic_attach_slice_entry *slice_ent;
943 	struct qaic_attach_slice *args = data;
944 	int rcu_id, usr_rcu_id, qdev_rcu_id;
945 	struct dma_bridge_chan	*dbc;
946 	struct drm_gem_object *obj;
947 	struct qaic_device *qdev;
948 	unsigned long arg_size;
949 	struct qaic_user *usr;
950 	u8 __user *user_data;
951 	struct qaic_bo *bo;
952 	int ret;
953 
954 	if (args->hdr.count == 0)
955 		return -EINVAL;
956 
957 	arg_size = args->hdr.count * sizeof(*slice_ent);
958 	if (arg_size / args->hdr.count != sizeof(*slice_ent))
959 		return -EINVAL;
960 
961 	if (!(args->hdr.dir == DMA_TO_DEVICE || args->hdr.dir == DMA_FROM_DEVICE))
962 		return -EINVAL;
963 
964 	if (args->data == 0)
965 		return -EINVAL;
966 
967 	usr = file_priv->driver_priv;
968 	usr_rcu_id = srcu_read_lock(&usr->qddev_lock);
969 	if (!usr->qddev) {
970 		ret = -ENODEV;
971 		goto unlock_usr_srcu;
972 	}
973 
974 	qdev = usr->qddev->qdev;
975 	qdev_rcu_id = srcu_read_lock(&qdev->dev_lock);
976 	if (qdev->dev_state != QAIC_ONLINE) {
977 		ret = -ENODEV;
978 		goto unlock_dev_srcu;
979 	}
980 
981 	if (args->hdr.dbc_id >= qdev->num_dbc) {
982 		ret = -EINVAL;
983 		goto unlock_dev_srcu;
984 	}
985 
986 	user_data = u64_to_user_ptr(args->data);
987 
988 	slice_ent = memdup_user(user_data, arg_size);
989 	if (IS_ERR(slice_ent)) {
990 		ret = PTR_ERR(slice_ent);
991 		goto unlock_dev_srcu;
992 	}
993 
994 	obj = drm_gem_object_lookup(file_priv, args->hdr.handle);
995 	if (!obj) {
996 		ret = -ENOENT;
997 		goto free_slice_ent;
998 	}
999 
1000 	ret = qaic_validate_req(qdev, slice_ent, args->hdr.count, obj->size);
1001 	if (ret)
1002 		goto put_bo;
1003 
1004 	bo = to_qaic_bo(obj);
1005 	ret = mutex_lock_interruptible(&bo->lock);
1006 	if (ret)
1007 		goto put_bo;
1008 
1009 	if (bo->sliced) {
1010 		ret = -EINVAL;
1011 		goto unlock_bo;
1012 	}
1013 
1014 	dbc = &qdev->dbc[args->hdr.dbc_id];
1015 	rcu_id = srcu_read_lock(&dbc->ch_lock);
1016 	if (dbc->usr != usr) {
1017 		ret = -EINVAL;
1018 		goto unlock_ch_srcu;
1019 	}
1020 
1021 	ret = qaic_prepare_bo(qdev, bo, &args->hdr);
1022 	if (ret)
1023 		goto unlock_ch_srcu;
1024 
1025 	ret = qaic_attach_slicing_bo(qdev, bo, &args->hdr, slice_ent);
1026 	if (ret)
1027 		goto unprepare_bo;
1028 
1029 	if (args->hdr.dir == DMA_TO_DEVICE)
1030 		dma_sync_sgtable_for_cpu(&qdev->pdev->dev, bo->sgt, args->hdr.dir);
1031 
1032 	bo->sliced = true;
1033 	list_add_tail(&bo->bo_list, &bo->dbc->bo_lists);
1034 	srcu_read_unlock(&dbc->ch_lock, rcu_id);
1035 	mutex_unlock(&bo->lock);
1036 	kfree(slice_ent);
1037 	srcu_read_unlock(&qdev->dev_lock, qdev_rcu_id);
1038 	srcu_read_unlock(&usr->qddev_lock, usr_rcu_id);
1039 
1040 	return 0;
1041 
1042 unprepare_bo:
1043 	qaic_unprepare_bo(qdev, bo);
1044 unlock_ch_srcu:
1045 	srcu_read_unlock(&dbc->ch_lock, rcu_id);
1046 unlock_bo:
1047 	mutex_unlock(&bo->lock);
1048 put_bo:
1049 	drm_gem_object_put(obj);
1050 free_slice_ent:
1051 	kfree(slice_ent);
1052 unlock_dev_srcu:
1053 	srcu_read_unlock(&qdev->dev_lock, qdev_rcu_id);
1054 unlock_usr_srcu:
1055 	srcu_read_unlock(&usr->qddev_lock, usr_rcu_id);
1056 	return ret;
1057 }
1058 
1059 static inline u32 fifo_space_avail(u32 head, u32 tail, u32 q_size)
1060 {
1061 	u32 avail = head - tail - 1;
1062 
1063 	if (head <= tail)
1064 		avail += q_size;
1065 
1066 	return avail;
1067 }
1068 
1069 static inline int copy_exec_reqs(struct qaic_device *qdev, struct bo_slice *slice, u32 dbc_id,
1070 				 u32 head, u32 *ptail)
1071 {
1072 	struct dma_bridge_chan *dbc = &qdev->dbc[dbc_id];
1073 	struct dbc_req *reqs = slice->reqs;
1074 	u32 tail = *ptail;
1075 	u32 avail;
1076 
1077 	avail = fifo_space_avail(head, tail, dbc->nelem);
1078 	if (avail < slice->nents)
1079 		return -EAGAIN;
1080 
1081 	if (tail + slice->nents > dbc->nelem) {
1082 		avail = dbc->nelem - tail;
1083 		avail = min_t(u32, avail, slice->nents);
1084 		memcpy(fifo_at(dbc->req_q_base, tail), reqs, sizeof(*reqs) * avail);
1085 		reqs += avail;
1086 		avail = slice->nents - avail;
1087 		if (avail)
1088 			memcpy(dbc->req_q_base, reqs, sizeof(*reqs) * avail);
1089 	} else {
1090 		memcpy(fifo_at(dbc->req_q_base, tail), reqs, sizeof(*reqs) * slice->nents);
1091 	}
1092 
1093 	*ptail = (tail + slice->nents) % dbc->nelem;
1094 
1095 	return 0;
1096 }
1097 
1098 static inline int copy_partial_exec_reqs(struct qaic_device *qdev, struct bo_slice *slice,
1099 					 u64 resize, struct dma_bridge_chan *dbc, u32 head,
1100 					 u32 *ptail)
1101 {
1102 	struct dbc_req *reqs = slice->reqs;
1103 	struct dbc_req *last_req;
1104 	u32 tail = *ptail;
1105 	u64 last_bytes;
1106 	u32 first_n;
1107 	u32 avail;
1108 
1109 	avail = fifo_space_avail(head, tail, dbc->nelem);
1110 
1111 	/*
1112 	 * After this for loop is complete, first_n represents the index
1113 	 * of the last DMA request of this slice that needs to be
1114 	 * transferred after resizing and last_bytes represents DMA size
1115 	 * of that request.
1116 	 */
1117 	last_bytes = resize;
1118 	for (first_n = 0; first_n < slice->nents; first_n++)
1119 		if (last_bytes > le32_to_cpu(reqs[first_n].len))
1120 			last_bytes -= le32_to_cpu(reqs[first_n].len);
1121 		else
1122 			break;
1123 
1124 	if (avail < (first_n + 1))
1125 		return -EAGAIN;
1126 
1127 	if (first_n) {
1128 		if (tail + first_n > dbc->nelem) {
1129 			avail = dbc->nelem - tail;
1130 			avail = min_t(u32, avail, first_n);
1131 			memcpy(fifo_at(dbc->req_q_base, tail), reqs, sizeof(*reqs) * avail);
1132 			last_req = reqs + avail;
1133 			avail = first_n - avail;
1134 			if (avail)
1135 				memcpy(dbc->req_q_base, last_req, sizeof(*reqs) * avail);
1136 		} else {
1137 			memcpy(fifo_at(dbc->req_q_base, tail), reqs, sizeof(*reqs) * first_n);
1138 		}
1139 	}
1140 
1141 	/*
1142 	 * Copy over the last entry. Here we need to adjust len to the left over
1143 	 * size, and set src and dst to the entry it is copied to.
1144 	 */
1145 	last_req = fifo_at(dbc->req_q_base, (tail + first_n) % dbc->nelem);
1146 	memcpy(last_req, reqs + slice->nents - 1, sizeof(*reqs));
1147 
1148 	/*
1149 	 * last_bytes holds size of a DMA segment, maximum DMA segment size is
1150 	 * set to UINT_MAX by qaic and hence last_bytes can never exceed u32
1151 	 * range. So, by down sizing we are not corrupting the value.
1152 	 */
1153 	last_req->len = cpu_to_le32((u32)last_bytes);
1154 	last_req->src_addr = reqs[first_n].src_addr;
1155 	last_req->dest_addr = reqs[first_n].dest_addr;
1156 	if (!last_bytes)
1157 		/* Disable DMA transfer */
1158 		last_req->cmd = GENMASK(7, 2) & reqs[first_n].cmd;
1159 
1160 	*ptail = (tail + first_n + 1) % dbc->nelem;
1161 
1162 	return 0;
1163 }
1164 
1165 static int send_bo_list_to_device(struct qaic_device *qdev, struct drm_file *file_priv,
1166 				  struct qaic_execute_entry *exec, unsigned int count,
1167 				  bool is_partial, struct dma_bridge_chan *dbc, u32 head,
1168 				  u32 *tail)
1169 {
1170 	struct qaic_partial_execute_entry *pexec = (struct qaic_partial_execute_entry *)exec;
1171 	struct drm_gem_object *obj;
1172 	struct bo_slice *slice;
1173 	unsigned long flags;
1174 	struct qaic_bo *bo;
1175 	int i, j;
1176 	int ret;
1177 
1178 	for (i = 0; i < count; i++) {
1179 		/*
1180 		 * ref count will be decremented when the transfer of this
1181 		 * buffer is complete. It is inside dbc_irq_threaded_fn().
1182 		 */
1183 		obj = drm_gem_object_lookup(file_priv,
1184 					    is_partial ? pexec[i].handle : exec[i].handle);
1185 		if (!obj) {
1186 			ret = -ENOENT;
1187 			goto failed_to_send_bo;
1188 		}
1189 
1190 		bo = to_qaic_bo(obj);
1191 		ret = mutex_lock_interruptible(&bo->lock);
1192 		if (ret)
1193 			goto failed_to_send_bo;
1194 
1195 		if (!bo->sliced) {
1196 			ret = -EINVAL;
1197 			goto unlock_bo;
1198 		}
1199 
1200 		if (is_partial && pexec[i].resize > bo->base.size) {
1201 			ret = -EINVAL;
1202 			goto unlock_bo;
1203 		}
1204 
1205 		spin_lock_irqsave(&dbc->xfer_lock, flags);
1206 		if (bo_queued(bo)) {
1207 			spin_unlock_irqrestore(&dbc->xfer_lock, flags);
1208 			ret = -EINVAL;
1209 			goto unlock_bo;
1210 		}
1211 
1212 		bo->req_id = dbc->next_req_id++;
1213 
1214 		list_for_each_entry(slice, &bo->slices, slice) {
1215 			for (j = 0; j < slice->nents; j++)
1216 				slice->reqs[j].req_id = cpu_to_le16(bo->req_id);
1217 
1218 			if (is_partial && (!pexec[i].resize || pexec[i].resize <= slice->offset))
1219 				/* Configure the slice for no DMA transfer */
1220 				ret = copy_partial_exec_reqs(qdev, slice, 0, dbc, head, tail);
1221 			else if (is_partial && pexec[i].resize < slice->offset + slice->size)
1222 				/* Configure the slice to be partially DMA transferred */
1223 				ret = copy_partial_exec_reqs(qdev, slice,
1224 							     pexec[i].resize - slice->offset, dbc,
1225 							     head, tail);
1226 			else
1227 				ret = copy_exec_reqs(qdev, slice, dbc->id, head, tail);
1228 			if (ret) {
1229 				spin_unlock_irqrestore(&dbc->xfer_lock, flags);
1230 				goto unlock_bo;
1231 			}
1232 		}
1233 		reinit_completion(&bo->xfer_done);
1234 		list_add_tail(&bo->xfer_list, &dbc->xfer_list);
1235 		spin_unlock_irqrestore(&dbc->xfer_lock, flags);
1236 		dma_sync_sgtable_for_device(&qdev->pdev->dev, bo->sgt, bo->dir);
1237 		mutex_unlock(&bo->lock);
1238 	}
1239 
1240 	return 0;
1241 
1242 unlock_bo:
1243 	mutex_unlock(&bo->lock);
1244 failed_to_send_bo:
1245 	if (likely(obj))
1246 		drm_gem_object_put(obj);
1247 	for (j = 0; j < i; j++) {
1248 		spin_lock_irqsave(&dbc->xfer_lock, flags);
1249 		bo = list_last_entry(&dbc->xfer_list, struct qaic_bo, xfer_list);
1250 		obj = &bo->base;
1251 		list_del_init(&bo->xfer_list);
1252 		spin_unlock_irqrestore(&dbc->xfer_lock, flags);
1253 		dma_sync_sgtable_for_cpu(&qdev->pdev->dev, bo->sgt, bo->dir);
1254 		drm_gem_object_put(obj);
1255 	}
1256 	return ret;
1257 }
1258 
1259 static void update_profiling_data(struct drm_file *file_priv,
1260 				  struct qaic_execute_entry *exec, unsigned int count,
1261 				  bool is_partial, u64 received_ts, u64 submit_ts, u32 queue_level)
1262 {
1263 	struct qaic_partial_execute_entry *pexec = (struct qaic_partial_execute_entry *)exec;
1264 	struct drm_gem_object *obj;
1265 	struct qaic_bo *bo;
1266 	int i;
1267 
1268 	for (i = 0; i < count; i++) {
1269 		/*
1270 		 * Since we already committed the BO to hardware, the only way
1271 		 * this should fail is a pending signal. We can't cancel the
1272 		 * submit to hardware, so we have to just skip the profiling
1273 		 * data. In case the signal is not fatal to the process, we
1274 		 * return success so that the user doesn't try to resubmit.
1275 		 */
1276 		obj = drm_gem_object_lookup(file_priv,
1277 					    is_partial ? pexec[i].handle : exec[i].handle);
1278 		if (!obj)
1279 			break;
1280 		bo = to_qaic_bo(obj);
1281 		bo->perf_stats.req_received_ts = received_ts;
1282 		bo->perf_stats.req_submit_ts = submit_ts;
1283 		bo->perf_stats.queue_level_before = queue_level;
1284 		queue_level += bo->total_slice_nents;
1285 		drm_gem_object_put(obj);
1286 	}
1287 }
1288 
1289 static int __qaic_execute_bo_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv,
1290 				   bool is_partial)
1291 {
1292 	struct qaic_execute *args = data;
1293 	struct qaic_execute_entry *exec;
1294 	struct dma_bridge_chan *dbc;
1295 	int usr_rcu_id, qdev_rcu_id;
1296 	struct qaic_device *qdev;
1297 	struct qaic_user *usr;
1298 	u64 received_ts;
1299 	u32 queue_level;
1300 	u64 submit_ts;
1301 	int rcu_id;
1302 	u32 head;
1303 	u32 tail;
1304 	u64 size;
1305 	int ret;
1306 
1307 	received_ts = ktime_get_ns();
1308 
1309 	size = is_partial ? sizeof(struct qaic_partial_execute_entry) : sizeof(*exec);
1310 	if (args->hdr.count == 0)
1311 		return -EINVAL;
1312 
1313 	exec = memdup_array_user(u64_to_user_ptr(args->data), args->hdr.count, size);
1314 	if (IS_ERR(exec))
1315 		return PTR_ERR(exec);
1316 
1317 	usr = file_priv->driver_priv;
1318 	usr_rcu_id = srcu_read_lock(&usr->qddev_lock);
1319 	if (!usr->qddev) {
1320 		ret = -ENODEV;
1321 		goto unlock_usr_srcu;
1322 	}
1323 
1324 	qdev = usr->qddev->qdev;
1325 	qdev_rcu_id = srcu_read_lock(&qdev->dev_lock);
1326 	if (qdev->dev_state != QAIC_ONLINE) {
1327 		ret = -ENODEV;
1328 		goto unlock_dev_srcu;
1329 	}
1330 
1331 	if (args->hdr.dbc_id >= qdev->num_dbc) {
1332 		ret = -EINVAL;
1333 		goto unlock_dev_srcu;
1334 	}
1335 
1336 	dbc = &qdev->dbc[args->hdr.dbc_id];
1337 
1338 	rcu_id = srcu_read_lock(&dbc->ch_lock);
1339 	if (!dbc->usr || dbc->usr->handle != usr->handle) {
1340 		ret = -EPERM;
1341 		goto release_ch_rcu;
1342 	}
1343 
1344 	head = readl(dbc->dbc_base + REQHP_OFF);
1345 	tail = readl(dbc->dbc_base + REQTP_OFF);
1346 
1347 	if (head == U32_MAX || tail == U32_MAX) {
1348 		/* PCI link error */
1349 		ret = -ENODEV;
1350 		goto release_ch_rcu;
1351 	}
1352 
1353 	queue_level = head <= tail ? tail - head : dbc->nelem - (head - tail);
1354 
1355 	ret = send_bo_list_to_device(qdev, file_priv, exec, args->hdr.count, is_partial, dbc,
1356 				     head, &tail);
1357 	if (ret)
1358 		goto release_ch_rcu;
1359 
1360 	/* Finalize commit to hardware */
1361 	submit_ts = ktime_get_ns();
1362 	writel(tail, dbc->dbc_base + REQTP_OFF);
1363 
1364 	update_profiling_data(file_priv, exec, args->hdr.count, is_partial, received_ts,
1365 			      submit_ts, queue_level);
1366 
1367 	if (datapath_polling)
1368 		schedule_work(&dbc->poll_work);
1369 
1370 release_ch_rcu:
1371 	srcu_read_unlock(&dbc->ch_lock, rcu_id);
1372 unlock_dev_srcu:
1373 	srcu_read_unlock(&qdev->dev_lock, qdev_rcu_id);
1374 unlock_usr_srcu:
1375 	srcu_read_unlock(&usr->qddev_lock, usr_rcu_id);
1376 	kfree(exec);
1377 	return ret;
1378 }
1379 
1380 int qaic_execute_bo_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv)
1381 {
1382 	return __qaic_execute_bo_ioctl(dev, data, file_priv, false);
1383 }
1384 
1385 int qaic_partial_execute_bo_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv)
1386 {
1387 	return __qaic_execute_bo_ioctl(dev, data, file_priv, true);
1388 }
1389 
1390 /*
1391  * Our interrupt handling is a bit more complicated than a simple ideal, but
1392  * sadly necessary.
1393  *
1394  * Each dbc has a completion queue. Entries in the queue correspond to DMA
1395  * requests which the device has processed. The hardware already has a built
1396  * in irq mitigation. When the device puts an entry into the queue, it will
1397  * only trigger an interrupt if the queue was empty. Therefore, when adding
1398  * the Nth event to a non-empty queue, the hardware doesn't trigger an
1399  * interrupt. This means the host doesn't get additional interrupts signaling
1400  * the same thing - the queue has something to process.
1401  * This behavior can be overridden in the DMA request.
1402  * This means that when the host receives an interrupt, it is required to
1403  * drain the queue.
1404  *
1405  * This behavior is what NAPI attempts to accomplish, although we can't use
1406  * NAPI as we don't have a netdev. We use threaded irqs instead.
1407  *
1408  * However, there is a situation where the host drains the queue fast enough
1409  * that every event causes an interrupt. Typically this is not a problem as
1410  * the rate of events would be low. However, that is not the case with
1411  * lprnet for example. On an Intel Xeon D-2191 where we run 8 instances of
1412  * lprnet, the host receives roughly 80k interrupts per second from the device
1413  * (per /proc/interrupts). While NAPI documentation indicates the host should
1414  * just chug along, sadly that behavior causes instability in some hosts.
1415  *
1416  * Therefore, we implement an interrupt disable scheme similar to NAPI. The
1417  * key difference is that we will delay after draining the queue for a small
1418  * time to allow additional events to come in via polling. Using the above
1419  * lprnet workload, this reduces the number of interrupts processed from
1420  * ~80k/sec to about 64 in 5 minutes and appears to solve the system
1421  * instability.
1422  */
1423 irqreturn_t dbc_irq_handler(int irq, void *data)
1424 {
1425 	struct dma_bridge_chan *dbc = data;
1426 	int rcu_id;
1427 	u32 head;
1428 	u32 tail;
1429 
1430 	rcu_id = srcu_read_lock(&dbc->ch_lock);
1431 
1432 	if (datapath_polling) {
1433 		srcu_read_unlock(&dbc->ch_lock, rcu_id);
1434 		/*
1435 		 * Normally datapath_polling will not have irqs enabled, but
1436 		 * when running with only one MSI the interrupt is shared with
1437 		 * MHI so it cannot be disabled. Return ASAP instead.
1438 		 */
1439 		return IRQ_HANDLED;
1440 	}
1441 
1442 	if (!dbc->usr) {
1443 		srcu_read_unlock(&dbc->ch_lock, rcu_id);
1444 		return IRQ_HANDLED;
1445 	}
1446 
1447 	head = readl(dbc->dbc_base + RSPHP_OFF);
1448 	if (head == U32_MAX) { /* PCI link error */
1449 		srcu_read_unlock(&dbc->ch_lock, rcu_id);
1450 		return IRQ_NONE;
1451 	}
1452 
1453 	tail = readl(dbc->dbc_base + RSPTP_OFF);
1454 	if (tail == U32_MAX) { /* PCI link error */
1455 		srcu_read_unlock(&dbc->ch_lock, rcu_id);
1456 		return IRQ_NONE;
1457 	}
1458 
1459 	if (head == tail) { /* queue empty */
1460 		srcu_read_unlock(&dbc->ch_lock, rcu_id);
1461 		return IRQ_NONE;
1462 	}
1463 
1464 	if (!dbc->qdev->single_msi)
1465 		disable_irq_nosync(irq);
1466 	srcu_read_unlock(&dbc->ch_lock, rcu_id);
1467 	return IRQ_WAKE_THREAD;
1468 }
1469 
1470 void irq_polling_work(struct work_struct *work)
1471 {
1472 	struct dma_bridge_chan *dbc = container_of(work, struct dma_bridge_chan,  poll_work);
1473 	unsigned long flags;
1474 	int rcu_id;
1475 	u32 head;
1476 	u32 tail;
1477 
1478 	rcu_id = srcu_read_lock(&dbc->ch_lock);
1479 
1480 	while (1) {
1481 		if (dbc->qdev->dev_state != QAIC_ONLINE) {
1482 			srcu_read_unlock(&dbc->ch_lock, rcu_id);
1483 			return;
1484 		}
1485 		if (!dbc->usr) {
1486 			srcu_read_unlock(&dbc->ch_lock, rcu_id);
1487 			return;
1488 		}
1489 		spin_lock_irqsave(&dbc->xfer_lock, flags);
1490 		if (list_empty(&dbc->xfer_list)) {
1491 			spin_unlock_irqrestore(&dbc->xfer_lock, flags);
1492 			srcu_read_unlock(&dbc->ch_lock, rcu_id);
1493 			return;
1494 		}
1495 		spin_unlock_irqrestore(&dbc->xfer_lock, flags);
1496 
1497 		head = readl(dbc->dbc_base + RSPHP_OFF);
1498 		if (head == U32_MAX) { /* PCI link error */
1499 			srcu_read_unlock(&dbc->ch_lock, rcu_id);
1500 			return;
1501 		}
1502 
1503 		tail = readl(dbc->dbc_base + RSPTP_OFF);
1504 		if (tail == U32_MAX) { /* PCI link error */
1505 			srcu_read_unlock(&dbc->ch_lock, rcu_id);
1506 			return;
1507 		}
1508 
1509 		if (head != tail) {
1510 			irq_wake_thread(dbc->irq, dbc);
1511 			srcu_read_unlock(&dbc->ch_lock, rcu_id);
1512 			return;
1513 		}
1514 
1515 		cond_resched();
1516 		usleep_range(datapath_poll_interval_us, 2 * datapath_poll_interval_us);
1517 	}
1518 }
1519 
1520 irqreturn_t dbc_irq_threaded_fn(int irq, void *data)
1521 {
1522 	struct dma_bridge_chan *dbc = data;
1523 	int event_count = NUM_EVENTS;
1524 	int delay_count = NUM_DELAYS;
1525 	struct qaic_device *qdev;
1526 	struct qaic_bo *bo, *i;
1527 	struct dbc_rsp *rsp;
1528 	unsigned long flags;
1529 	int rcu_id;
1530 	u16 status;
1531 	u16 req_id;
1532 	u32 head;
1533 	u32 tail;
1534 
1535 	rcu_id = srcu_read_lock(&dbc->ch_lock);
1536 	qdev = dbc->qdev;
1537 
1538 	head = readl(dbc->dbc_base + RSPHP_OFF);
1539 	if (head == U32_MAX) /* PCI link error */
1540 		goto error_out;
1541 
1542 read_fifo:
1543 
1544 	if (!event_count) {
1545 		event_count = NUM_EVENTS;
1546 		cond_resched();
1547 	}
1548 
1549 	/*
1550 	 * if this channel isn't assigned or gets unassigned during processing
1551 	 * we have nothing further to do
1552 	 */
1553 	if (!dbc->usr)
1554 		goto error_out;
1555 
1556 	tail = readl(dbc->dbc_base + RSPTP_OFF);
1557 	if (tail == U32_MAX) /* PCI link error */
1558 		goto error_out;
1559 
1560 	if (head == tail) { /* queue empty */
1561 		if (delay_count) {
1562 			--delay_count;
1563 			usleep_range(100, 200);
1564 			goto read_fifo; /* check for a new event */
1565 		}
1566 		goto normal_out;
1567 	}
1568 
1569 	delay_count = NUM_DELAYS;
1570 	while (head != tail) {
1571 		if (!event_count)
1572 			break;
1573 		--event_count;
1574 		rsp = dbc->rsp_q_base + head * sizeof(*rsp);
1575 		req_id = le16_to_cpu(rsp->req_id);
1576 		status = le16_to_cpu(rsp->status);
1577 		if (status)
1578 			pci_dbg(qdev->pdev, "req_id %d failed with status %d\n", req_id, status);
1579 		spin_lock_irqsave(&dbc->xfer_lock, flags);
1580 		/*
1581 		 * A BO can receive multiple interrupts, since a BO can be
1582 		 * divided into multiple slices and a buffer receives as many
1583 		 * interrupts as slices. So until it receives interrupts for
1584 		 * all the slices we cannot mark that buffer complete.
1585 		 */
1586 		list_for_each_entry_safe(bo, i, &dbc->xfer_list, xfer_list) {
1587 			if (bo->req_id == req_id)
1588 				bo->nr_slice_xfer_done++;
1589 			else
1590 				continue;
1591 
1592 			if (bo->nr_slice_xfer_done < bo->nr_slice)
1593 				break;
1594 
1595 			/*
1596 			 * At this point we have received all the interrupts for
1597 			 * BO, which means BO execution is complete.
1598 			 */
1599 			dma_sync_sgtable_for_cpu(&qdev->pdev->dev, bo->sgt, bo->dir);
1600 			bo->nr_slice_xfer_done = 0;
1601 			list_del_init(&bo->xfer_list);
1602 			bo->perf_stats.req_processed_ts = ktime_get_ns();
1603 			complete_all(&bo->xfer_done);
1604 			drm_gem_object_put(&bo->base);
1605 			break;
1606 		}
1607 		spin_unlock_irqrestore(&dbc->xfer_lock, flags);
1608 		head = (head + 1) % dbc->nelem;
1609 	}
1610 
1611 	/*
1612 	 * Update the head pointer of response queue and let the device know
1613 	 * that we have consumed elements from the queue.
1614 	 */
1615 	writel(head, dbc->dbc_base + RSPHP_OFF);
1616 
1617 	/* elements might have been put in the queue while we were processing */
1618 	goto read_fifo;
1619 
1620 normal_out:
1621 	if (!qdev->single_msi && likely(!datapath_polling))
1622 		enable_irq(irq);
1623 	else if (unlikely(datapath_polling))
1624 		schedule_work(&dbc->poll_work);
1625 	/* checking the fifo and enabling irqs is a race, missed event check */
1626 	tail = readl(dbc->dbc_base + RSPTP_OFF);
1627 	if (tail != U32_MAX && head != tail) {
1628 		if (!qdev->single_msi && likely(!datapath_polling))
1629 			disable_irq_nosync(irq);
1630 		goto read_fifo;
1631 	}
1632 	srcu_read_unlock(&dbc->ch_lock, rcu_id);
1633 	return IRQ_HANDLED;
1634 
1635 error_out:
1636 	srcu_read_unlock(&dbc->ch_lock, rcu_id);
1637 	if (!qdev->single_msi && likely(!datapath_polling))
1638 		enable_irq(irq);
1639 	else if (unlikely(datapath_polling))
1640 		schedule_work(&dbc->poll_work);
1641 
1642 	return IRQ_HANDLED;
1643 }
1644 
1645 int qaic_wait_bo_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv)
1646 {
1647 	struct qaic_wait *args = data;
1648 	int usr_rcu_id, qdev_rcu_id;
1649 	struct dma_bridge_chan *dbc;
1650 	struct drm_gem_object *obj;
1651 	struct qaic_device *qdev;
1652 	unsigned long timeout;
1653 	struct qaic_user *usr;
1654 	struct qaic_bo *bo;
1655 	int rcu_id;
1656 	int ret;
1657 
1658 	if (args->pad != 0)
1659 		return -EINVAL;
1660 
1661 	usr = file_priv->driver_priv;
1662 	usr_rcu_id = srcu_read_lock(&usr->qddev_lock);
1663 	if (!usr->qddev) {
1664 		ret = -ENODEV;
1665 		goto unlock_usr_srcu;
1666 	}
1667 
1668 	qdev = usr->qddev->qdev;
1669 	qdev_rcu_id = srcu_read_lock(&qdev->dev_lock);
1670 	if (qdev->dev_state != QAIC_ONLINE) {
1671 		ret = -ENODEV;
1672 		goto unlock_dev_srcu;
1673 	}
1674 
1675 	if (args->dbc_id >= qdev->num_dbc) {
1676 		ret = -EINVAL;
1677 		goto unlock_dev_srcu;
1678 	}
1679 
1680 	dbc = &qdev->dbc[args->dbc_id];
1681 
1682 	rcu_id = srcu_read_lock(&dbc->ch_lock);
1683 	if (dbc->usr != usr) {
1684 		ret = -EPERM;
1685 		goto unlock_ch_srcu;
1686 	}
1687 
1688 	obj = drm_gem_object_lookup(file_priv, args->handle);
1689 	if (!obj) {
1690 		ret = -ENOENT;
1691 		goto unlock_ch_srcu;
1692 	}
1693 
1694 	bo = to_qaic_bo(obj);
1695 	timeout = args->timeout ? args->timeout : wait_exec_default_timeout_ms;
1696 	timeout = msecs_to_jiffies(timeout);
1697 	ret = wait_for_completion_interruptible_timeout(&bo->xfer_done, timeout);
1698 	if (!ret) {
1699 		ret = -ETIMEDOUT;
1700 		goto put_obj;
1701 	}
1702 	if (ret > 0)
1703 		ret = 0;
1704 
1705 	if (!dbc->usr)
1706 		ret = -EPERM;
1707 
1708 put_obj:
1709 	drm_gem_object_put(obj);
1710 unlock_ch_srcu:
1711 	srcu_read_unlock(&dbc->ch_lock, rcu_id);
1712 unlock_dev_srcu:
1713 	srcu_read_unlock(&qdev->dev_lock, qdev_rcu_id);
1714 unlock_usr_srcu:
1715 	srcu_read_unlock(&usr->qddev_lock, usr_rcu_id);
1716 	return ret;
1717 }
1718 
1719 int qaic_perf_stats_bo_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv)
1720 {
1721 	struct qaic_perf_stats_entry *ent = NULL;
1722 	struct qaic_perf_stats *args = data;
1723 	int usr_rcu_id, qdev_rcu_id;
1724 	struct drm_gem_object *obj;
1725 	struct qaic_device *qdev;
1726 	struct qaic_user *usr;
1727 	struct qaic_bo *bo;
1728 	int ret = 0;
1729 	int i;
1730 
1731 	usr = file_priv->driver_priv;
1732 	usr_rcu_id = srcu_read_lock(&usr->qddev_lock);
1733 	if (!usr->qddev) {
1734 		ret = -ENODEV;
1735 		goto unlock_usr_srcu;
1736 	}
1737 
1738 	qdev = usr->qddev->qdev;
1739 	qdev_rcu_id = srcu_read_lock(&qdev->dev_lock);
1740 	if (qdev->dev_state != QAIC_ONLINE) {
1741 		ret = -ENODEV;
1742 		goto unlock_dev_srcu;
1743 	}
1744 
1745 	if (args->hdr.dbc_id >= qdev->num_dbc) {
1746 		ret = -EINVAL;
1747 		goto unlock_dev_srcu;
1748 	}
1749 
1750 	ent = memdup_array_user(u64_to_user_ptr(args->data), args->hdr.count, sizeof(*ent));
1751 	if (IS_ERR(ent)) {
1752 		ret = PTR_ERR(ent);
1753 		goto unlock_dev_srcu;
1754 	}
1755 
1756 	for (i = 0; i < args->hdr.count; i++) {
1757 		obj = drm_gem_object_lookup(file_priv, ent[i].handle);
1758 		if (!obj) {
1759 			ret = -ENOENT;
1760 			goto free_ent;
1761 		}
1762 		bo = to_qaic_bo(obj);
1763 		/*
1764 		 * perf stats ioctl is called before wait ioctl is complete then
1765 		 * the latency information is invalid.
1766 		 */
1767 		if (bo->perf_stats.req_processed_ts < bo->perf_stats.req_submit_ts) {
1768 			ent[i].device_latency_us = 0;
1769 		} else {
1770 			ent[i].device_latency_us = div_u64((bo->perf_stats.req_processed_ts -
1771 							    bo->perf_stats.req_submit_ts), 1000);
1772 		}
1773 		ent[i].submit_latency_us = div_u64((bo->perf_stats.req_submit_ts -
1774 						    bo->perf_stats.req_received_ts), 1000);
1775 		ent[i].queue_level_before = bo->perf_stats.queue_level_before;
1776 		ent[i].num_queue_element = bo->total_slice_nents;
1777 		drm_gem_object_put(obj);
1778 	}
1779 
1780 	if (copy_to_user(u64_to_user_ptr(args->data), ent, args->hdr.count * sizeof(*ent)))
1781 		ret = -EFAULT;
1782 
1783 free_ent:
1784 	kfree(ent);
1785 unlock_dev_srcu:
1786 	srcu_read_unlock(&qdev->dev_lock, qdev_rcu_id);
1787 unlock_usr_srcu:
1788 	srcu_read_unlock(&usr->qddev_lock, usr_rcu_id);
1789 	return ret;
1790 }
1791 
1792 static void detach_slice_bo(struct qaic_device *qdev, struct qaic_bo *bo)
1793 {
1794 	qaic_free_slices_bo(bo);
1795 	qaic_unprepare_bo(qdev, bo);
1796 	qaic_init_bo(bo, true);
1797 	list_del(&bo->bo_list);
1798 	drm_gem_object_put(&bo->base);
1799 }
1800 
1801 int qaic_detach_slice_bo_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv)
1802 {
1803 	struct qaic_detach_slice *args = data;
1804 	int rcu_id, usr_rcu_id, qdev_rcu_id;
1805 	struct dma_bridge_chan *dbc;
1806 	struct drm_gem_object *obj;
1807 	struct qaic_device *qdev;
1808 	struct qaic_user *usr;
1809 	unsigned long flags;
1810 	struct qaic_bo *bo;
1811 	int ret;
1812 
1813 	if (args->pad != 0)
1814 		return -EINVAL;
1815 
1816 	usr = file_priv->driver_priv;
1817 	usr_rcu_id = srcu_read_lock(&usr->qddev_lock);
1818 	if (!usr->qddev) {
1819 		ret = -ENODEV;
1820 		goto unlock_usr_srcu;
1821 	}
1822 
1823 	qdev = usr->qddev->qdev;
1824 	qdev_rcu_id = srcu_read_lock(&qdev->dev_lock);
1825 	if (qdev->dev_state != QAIC_ONLINE) {
1826 		ret = -ENODEV;
1827 		goto unlock_dev_srcu;
1828 	}
1829 
1830 	obj = drm_gem_object_lookup(file_priv, args->handle);
1831 	if (!obj) {
1832 		ret = -ENOENT;
1833 		goto unlock_dev_srcu;
1834 	}
1835 
1836 	bo = to_qaic_bo(obj);
1837 	ret = mutex_lock_interruptible(&bo->lock);
1838 	if (ret)
1839 		goto put_bo;
1840 
1841 	if (!bo->sliced) {
1842 		ret = -EINVAL;
1843 		goto unlock_bo;
1844 	}
1845 
1846 	dbc = bo->dbc;
1847 	rcu_id = srcu_read_lock(&dbc->ch_lock);
1848 	if (dbc->usr != usr) {
1849 		ret = -EINVAL;
1850 		goto unlock_ch_srcu;
1851 	}
1852 
1853 	/* Check if BO is committed to H/W for DMA */
1854 	spin_lock_irqsave(&dbc->xfer_lock, flags);
1855 	if (bo_queued(bo)) {
1856 		spin_unlock_irqrestore(&dbc->xfer_lock, flags);
1857 		ret = -EBUSY;
1858 		goto unlock_ch_srcu;
1859 	}
1860 	spin_unlock_irqrestore(&dbc->xfer_lock, flags);
1861 
1862 	detach_slice_bo(qdev, bo);
1863 
1864 unlock_ch_srcu:
1865 	srcu_read_unlock(&dbc->ch_lock, rcu_id);
1866 unlock_bo:
1867 	mutex_unlock(&bo->lock);
1868 put_bo:
1869 	drm_gem_object_put(obj);
1870 unlock_dev_srcu:
1871 	srcu_read_unlock(&qdev->dev_lock, qdev_rcu_id);
1872 unlock_usr_srcu:
1873 	srcu_read_unlock(&usr->qddev_lock, usr_rcu_id);
1874 	return ret;
1875 }
1876 
1877 static void empty_xfer_list(struct qaic_device *qdev, struct dma_bridge_chan *dbc)
1878 {
1879 	unsigned long flags;
1880 	struct qaic_bo *bo;
1881 
1882 	spin_lock_irqsave(&dbc->xfer_lock, flags);
1883 	while (!list_empty(&dbc->xfer_list)) {
1884 		bo = list_first_entry(&dbc->xfer_list, typeof(*bo), xfer_list);
1885 		list_del_init(&bo->xfer_list);
1886 		spin_unlock_irqrestore(&dbc->xfer_lock, flags);
1887 		bo->nr_slice_xfer_done = 0;
1888 		bo->req_id = 0;
1889 		bo->perf_stats.req_received_ts = 0;
1890 		bo->perf_stats.req_submit_ts = 0;
1891 		bo->perf_stats.req_processed_ts = 0;
1892 		bo->perf_stats.queue_level_before = 0;
1893 		dma_sync_sgtable_for_cpu(&qdev->pdev->dev, bo->sgt, bo->dir);
1894 		complete_all(&bo->xfer_done);
1895 		drm_gem_object_put(&bo->base);
1896 		spin_lock_irqsave(&dbc->xfer_lock, flags);
1897 	}
1898 	spin_unlock_irqrestore(&dbc->xfer_lock, flags);
1899 }
1900 
1901 int disable_dbc(struct qaic_device *qdev, u32 dbc_id, struct qaic_user *usr)
1902 {
1903 	if (!qdev->dbc[dbc_id].usr || qdev->dbc[dbc_id].usr->handle != usr->handle)
1904 		return -EPERM;
1905 
1906 	qdev->dbc[dbc_id].usr = NULL;
1907 	synchronize_srcu(&qdev->dbc[dbc_id].ch_lock);
1908 	return 0;
1909 }
1910 
1911 /**
1912  * enable_dbc - Enable the DBC. DBCs are disabled by removing the context of
1913  * user. Add user context back to DBC to enable it. This function trusts the
1914  * DBC ID passed and expects the DBC to be disabled.
1915  * @qdev: Qranium device handle
1916  * @dbc_id: ID of the DBC
1917  * @usr: User context
1918  */
1919 void enable_dbc(struct qaic_device *qdev, u32 dbc_id, struct qaic_user *usr)
1920 {
1921 	qdev->dbc[dbc_id].usr = usr;
1922 }
1923 
1924 void wakeup_dbc(struct qaic_device *qdev, u32 dbc_id)
1925 {
1926 	struct dma_bridge_chan *dbc = &qdev->dbc[dbc_id];
1927 
1928 	dbc->usr = NULL;
1929 	empty_xfer_list(qdev, dbc);
1930 	synchronize_srcu(&dbc->ch_lock);
1931 	/*
1932 	 * Threads holding channel lock, may add more elements in the xfer_list.
1933 	 * Flush out these elements from xfer_list.
1934 	 */
1935 	empty_xfer_list(qdev, dbc);
1936 }
1937 
1938 void release_dbc(struct qaic_device *qdev, u32 dbc_id)
1939 {
1940 	struct qaic_bo *bo, *bo_temp;
1941 	struct dma_bridge_chan *dbc;
1942 
1943 	dbc = &qdev->dbc[dbc_id];
1944 	if (!dbc->in_use)
1945 		return;
1946 
1947 	wakeup_dbc(qdev, dbc_id);
1948 
1949 	dma_free_coherent(&qdev->pdev->dev, dbc->total_size, dbc->req_q_base, dbc->dma_addr);
1950 	dbc->total_size = 0;
1951 	dbc->req_q_base = NULL;
1952 	dbc->dma_addr = 0;
1953 	dbc->nelem = 0;
1954 	dbc->usr = NULL;
1955 
1956 	list_for_each_entry_safe(bo, bo_temp, &dbc->bo_lists, bo_list) {
1957 		drm_gem_object_get(&bo->base);
1958 		mutex_lock(&bo->lock);
1959 		detach_slice_bo(qdev, bo);
1960 		mutex_unlock(&bo->lock);
1961 		drm_gem_object_put(&bo->base);
1962 	}
1963 
1964 	dbc->in_use = false;
1965 	wake_up(&dbc->dbc_release);
1966 }
1967 
1968 void qaic_data_get_fifo_info(struct dma_bridge_chan *dbc, u32 *head, u32 *tail)
1969 {
1970 	if (!dbc || !head || !tail)
1971 		return;
1972 
1973 	*head = readl(dbc->dbc_base + REQHP_OFF);
1974 	*tail = readl(dbc->dbc_base + REQTP_OFF);
1975 }
1976