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