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