xref: /linux/drivers/misc/bcm-vk/bcm_vk_msg.c (revision 37bef2170d4c88fc3d708eecf3ef0f4032bc1372)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright 2018-2020 Broadcom.
4  */
5 
6 #include <linux/delay.h>
7 #include <linux/fs.h>
8 #include <linux/hash.h>
9 #include <linux/interrupt.h>
10 #include <linux/list.h>
11 #include <linux/module.h>
12 #include <linux/overflow.h>
13 #include <linux/poll.h>
14 #include <linux/sizes.h>
15 #include <linux/spinlock.h>
16 #include <linux/timer.h>
17 
18 #include "bcm_vk.h"
19 #include "bcm_vk_msg.h"
20 #include "bcm_vk_sg.h"
21 
22 /* functions to manipulate the transport id in msg block */
23 #define BCM_VK_MSG_Q_SHIFT	 4
24 #define BCM_VK_MSG_Q_MASK	 0xF
25 #define BCM_VK_MSG_ID_MASK	 0xFFF
26 
27 #define BCM_VK_DMA_DRAIN_MAX_MS	  2000
28 
29 /* number x q_size will be the max number of msg processed per loop */
30 #define BCM_VK_MSG_PROC_MAX_LOOP 2
31 
32 /* module parameter */
33 static bool hb_mon = true;
34 module_param(hb_mon, bool, 0444);
35 MODULE_PARM_DESC(hb_mon, "Monitoring heartbeat continuously.\n");
36 static int batch_log = 1;
37 module_param(batch_log, int, 0444);
38 MODULE_PARM_DESC(batch_log, "Max num of logs per batch operation.\n");
39 
40 static bool hb_mon_is_on(void)
41 {
42 	return hb_mon;
43 }
44 
45 static u32 get_q_num(const struct vk_msg_blk *msg)
46 {
47 	u32 q_num = msg->trans_id & BCM_VK_MSG_Q_MASK;
48 
49 	if (q_num >= VK_MSGQ_PER_CHAN_MAX)
50 		q_num = VK_MSGQ_NUM_DEFAULT;
51 	return q_num;
52 }
53 
54 static void set_q_num(struct vk_msg_blk *msg, u32 q_num)
55 {
56 	u32 trans_q;
57 
58 	if (q_num >= VK_MSGQ_PER_CHAN_MAX)
59 		trans_q = VK_MSGQ_NUM_DEFAULT;
60 	else
61 		trans_q = q_num;
62 
63 	msg->trans_id = (msg->trans_id & ~BCM_VK_MSG_Q_MASK) | trans_q;
64 }
65 
66 static u32 get_msg_id(const struct vk_msg_blk *msg)
67 {
68 	return ((msg->trans_id >> BCM_VK_MSG_Q_SHIFT) & BCM_VK_MSG_ID_MASK);
69 }
70 
71 static void set_msg_id(struct vk_msg_blk *msg, u32 val)
72 {
73 	msg->trans_id = (val << BCM_VK_MSG_Q_SHIFT) | get_q_num(msg);
74 }
75 
76 static u32 msgq_inc(const struct bcm_vk_sync_qinfo *qinfo, u32 idx, u32 inc)
77 {
78 	return ((idx + inc) & qinfo->q_mask);
79 }
80 
81 static
82 struct vk_msg_blk __iomem *msgq_blk_addr(const struct bcm_vk_sync_qinfo *qinfo,
83 					 u32 idx)
84 {
85 	return qinfo->q_start + (VK_MSGQ_BLK_SIZE * idx);
86 }
87 
88 static u32 msgq_occupied(const struct bcm_vk_msgq __iomem *msgq,
89 			 const struct bcm_vk_sync_qinfo *qinfo)
90 {
91 	u32 wr_idx, rd_idx;
92 
93 	wr_idx = readl_relaxed(&msgq->wr_idx);
94 	rd_idx = readl_relaxed(&msgq->rd_idx);
95 
96 	return ((wr_idx - rd_idx) & qinfo->q_mask);
97 }
98 
99 static
100 u32 msgq_avail_space(const struct bcm_vk_msgq __iomem *msgq,
101 		     const struct bcm_vk_sync_qinfo *qinfo)
102 {
103 	return (qinfo->q_size - msgq_occupied(msgq, qinfo) - 1);
104 }
105 
106 /* number of retries when enqueue message fails before returning EAGAIN */
107 #define BCM_VK_H2VK_ENQ_RETRY 10
108 #define BCM_VK_H2VK_ENQ_RETRY_DELAY_MS 50
109 
110 bool bcm_vk_drv_access_ok(struct bcm_vk *vk)
111 {
112 	/* Pair with the release store after message queue initialization. */
113 	return !!atomic_read_acquire(&vk->msgq_inited);
114 }
115 
116 void bcm_vk_set_host_alert(struct bcm_vk *vk, u32 bit_mask)
117 {
118 	struct bcm_vk_alert *alert = &vk->host_alert;
119 	unsigned long flags;
120 
121 	/* use irqsave version as this maybe called inside timer interrupt */
122 	spin_lock_irqsave(&vk->host_alert_lock, flags);
123 	alert->notfs |= bit_mask;
124 	spin_unlock_irqrestore(&vk->host_alert_lock, flags);
125 
126 	if (test_and_set_bit(BCM_VK_WQ_NOTF_PEND, vk->wq_offload) == 0)
127 		queue_work(vk->wq_thread, &vk->wq_work);
128 }
129 
130 /*
131  * Heartbeat related defines
132  * The heartbeat from host is a last resort.  If stuck condition happens
133  * on the card, firmware is supposed to detect it.  Therefore, the heartbeat
134  * values used will be more relaxed on the driver, which need to be bigger
135  * than the watchdog timeout on the card.  The watchdog timeout on the card
136  * is 20s, with a jitter of 2s => 22s.  We use a value of 27s here.
137  */
138 #define BCM_VK_HB_TIMER_S 3
139 #define BCM_VK_HB_TIMER_VALUE (BCM_VK_HB_TIMER_S * HZ)
140 #define BCM_VK_HB_LOST_MAX (27 / BCM_VK_HB_TIMER_S)
141 
142 static void bcm_vk_hb_poll(struct work_struct *work)
143 {
144 	u32 uptime_s;
145 	struct bcm_vk_hb_ctrl *hb = container_of(to_delayed_work(work), struct bcm_vk_hb_ctrl,
146 						 work);
147 	struct bcm_vk *vk = container_of(hb, struct bcm_vk, hb_ctrl);
148 
149 	if (bcm_vk_drv_access_ok(vk) && hb_mon_is_on()) {
150 		/* read uptime from register and compare */
151 		uptime_s = vkread32(vk, BAR_0, BAR_OS_UPTIME);
152 
153 		if (uptime_s == hb->last_uptime)
154 			hb->lost_cnt++;
155 		else /* reset to avoid accumulation */
156 			hb->lost_cnt = 0;
157 
158 		dev_dbg(&vk->pdev->dev, "Last uptime %d current %d, lost %d\n",
159 			hb->last_uptime, uptime_s, hb->lost_cnt);
160 
161 		/*
162 		 * if the interface goes down without any activity, a value
163 		 * of 0xFFFFFFFF will be continuously read, and the detection
164 		 * will be happened eventually.
165 		 */
166 		hb->last_uptime = uptime_s;
167 	} else {
168 		/* reset heart beat lost cnt */
169 		hb->lost_cnt = 0;
170 	}
171 
172 	/* next, check if heartbeat exceeds limit */
173 	if (hb->lost_cnt > BCM_VK_HB_LOST_MAX) {
174 		dev_err(&vk->pdev->dev, "Heartbeat Misses %d times, %d s!\n",
175 			BCM_VK_HB_LOST_MAX,
176 			BCM_VK_HB_LOST_MAX * BCM_VK_HB_TIMER_S);
177 
178 		bcm_vk_blk_drv_access(vk);
179 		bcm_vk_set_host_alert(vk, ERR_LOG_HOST_HB_FAIL);
180 	}
181 	/* re-arm timer */
182 	schedule_delayed_work(&hb->work, BCM_VK_HB_TIMER_VALUE);
183 }
184 
185 void bcm_vk_hb_init(struct bcm_vk *vk)
186 {
187 	struct bcm_vk_hb_ctrl *hb = &vk->hb_ctrl;
188 
189 	INIT_DELAYED_WORK(&hb->work, bcm_vk_hb_poll);
190 	schedule_delayed_work(&hb->work, BCM_VK_HB_TIMER_VALUE);
191 }
192 
193 void bcm_vk_hb_deinit(struct bcm_vk *vk)
194 {
195 	struct bcm_vk_hb_ctrl *hb = &vk->hb_ctrl;
196 
197 	cancel_delayed_work_sync(&hb->work);
198 }
199 
200 static void bcm_vk_msgid_bitmap_clear(struct bcm_vk *vk,
201 				      unsigned int start,
202 				      unsigned int nbits)
203 {
204 	spin_lock(&vk->msg_id_lock);
205 	bitmap_clear(vk->bmap, start, nbits);
206 	spin_unlock(&vk->msg_id_lock);
207 }
208 
209 /*
210  * allocate a ctx per file struct
211  */
212 static struct bcm_vk_ctx *bcm_vk_get_ctx(struct bcm_vk *vk, const pid_t pid)
213 {
214 	u32 i;
215 	struct bcm_vk_ctx *ctx = NULL;
216 	u32 hash_idx = hash_32(pid, VK_PID_HT_SHIFT_BIT);
217 
218 	spin_lock(&vk->ctx_lock);
219 
220 	/* check if it is in reset, if so, don't allow */
221 	if (vk->reset_pid) {
222 		dev_err(&vk->pdev->dev,
223 			"No context allowed during reset by pid %d\n",
224 			vk->reset_pid);
225 
226 		goto in_reset_exit;
227 	}
228 
229 	for (i = 0; i < ARRAY_SIZE(vk->ctx); i++) {
230 		if (!vk->ctx[i].in_use) {
231 			vk->ctx[i].in_use = true;
232 			ctx = &vk->ctx[i];
233 			break;
234 		}
235 	}
236 
237 	if (!ctx) {
238 		dev_err(&vk->pdev->dev, "All context in use\n");
239 
240 		goto all_in_use_exit;
241 	}
242 
243 	/* set the pid and insert it to hash table */
244 	ctx->pid = pid;
245 	ctx->hash_idx = hash_idx;
246 	list_add_tail(&ctx->node, &vk->pid_ht[hash_idx].head);
247 
248 	/* increase kref */
249 	kref_get(&vk->kref);
250 
251 	/* clear counter */
252 	atomic_set(&ctx->pend_cnt, 0);
253 	atomic_set(&ctx->dma_cnt, 0);
254 	init_waitqueue_head(&ctx->rd_wq);
255 
256 all_in_use_exit:
257 in_reset_exit:
258 	spin_unlock(&vk->ctx_lock);
259 
260 	return ctx;
261 }
262 
263 static u16 bcm_vk_get_msg_id(struct bcm_vk *vk)
264 {
265 	u16 rc = VK_MSG_ID_OVERFLOW;
266 	u16 test_bit_count = 0;
267 
268 	spin_lock(&vk->msg_id_lock);
269 	while (test_bit_count < (VK_MSG_ID_BITMAP_SIZE - 1)) {
270 		/*
271 		 * first time come in this loop, msg_id will be 0
272 		 * and the first one tested will be 1.  We skip
273 		 * VK_SIMPLEX_MSG_ID (0) for one way host2vk
274 		 * communication
275 		 */
276 		vk->msg_id++;
277 		if (vk->msg_id == VK_MSG_ID_BITMAP_SIZE)
278 			vk->msg_id = 1;
279 
280 		if (test_bit(vk->msg_id, vk->bmap)) {
281 			test_bit_count++;
282 			continue;
283 		}
284 		rc = vk->msg_id;
285 		bitmap_set(vk->bmap, vk->msg_id, 1);
286 		break;
287 	}
288 	spin_unlock(&vk->msg_id_lock);
289 
290 	return rc;
291 }
292 
293 static int bcm_vk_free_ctx(struct bcm_vk *vk, struct bcm_vk_ctx *ctx)
294 {
295 	u32 idx;
296 	u32 hash_idx;
297 	pid_t pid;
298 	struct bcm_vk_ctx *entry;
299 	int count = 0;
300 
301 	if (!ctx) {
302 		dev_err(&vk->pdev->dev, "NULL context detected\n");
303 		return -EINVAL;
304 	}
305 	idx = ctx->idx;
306 	pid = ctx->pid;
307 
308 	spin_lock(&vk->ctx_lock);
309 
310 	if (!vk->ctx[idx].in_use) {
311 		dev_err(&vk->pdev->dev, "context[%d] not in use!\n", idx);
312 	} else {
313 		vk->ctx[idx].in_use = false;
314 		vk->ctx[idx].miscdev = NULL;
315 
316 		/* Remove it from hash list and see if it is the last one. */
317 		list_del(&ctx->node);
318 		hash_idx = ctx->hash_idx;
319 		list_for_each_entry(entry, &vk->pid_ht[hash_idx].head, node) {
320 			if (entry->pid == pid)
321 				count++;
322 		}
323 	}
324 
325 	spin_unlock(&vk->ctx_lock);
326 
327 	return count;
328 }
329 
330 static void bcm_vk_free_wkent(struct device *dev, struct bcm_vk_wkent *entry)
331 {
332 	int proc_cnt;
333 
334 	bcm_vk_sg_free(dev, entry->dma, VK_DMA_MAX_ADDRS, &proc_cnt);
335 	if (proc_cnt)
336 		atomic_dec(&entry->ctx->dma_cnt);
337 
338 	kfree(entry->to_h_msg);
339 	kfree(entry);
340 }
341 
342 static void bcm_vk_drain_all_pend(struct device *dev,
343 				  struct bcm_vk_msg_chan *chan,
344 				  struct bcm_vk_ctx *ctx)
345 {
346 	u32 num;
347 	struct bcm_vk_wkent *entry, *tmp;
348 	struct bcm_vk *vk;
349 	struct list_head del_q;
350 
351 	if (ctx)
352 		vk = container_of(ctx->miscdev, struct bcm_vk, miscdev);
353 
354 	INIT_LIST_HEAD(&del_q);
355 	spin_lock(&chan->pendq_lock);
356 	for (num = 0; num < chan->q_nr; num++) {
357 		list_for_each_entry_safe(entry, tmp, &chan->pendq[num], node) {
358 			if ((!ctx) || (entry->ctx->idx == ctx->idx)) {
359 				list_move_tail(&entry->node, &del_q);
360 			}
361 		}
362 	}
363 	spin_unlock(&chan->pendq_lock);
364 
365 	/* batch clean up */
366 	num = 0;
367 	list_for_each_entry_safe(entry, tmp, &del_q, node) {
368 		list_del(&entry->node);
369 		num++;
370 		if (ctx) {
371 			struct vk_msg_blk *msg;
372 			int bit_set;
373 			bool responded;
374 			u32 msg_id;
375 
376 			/* if it is specific ctx, log for any stuck */
377 			msg = entry->to_v_msg;
378 			msg_id = get_msg_id(msg);
379 			bit_set = test_bit(msg_id, vk->bmap);
380 			responded = entry->to_h_msg ? true : false;
381 			if (num <= batch_log)
382 				dev_info(dev,
383 					 "Drained: fid %u size %u msg 0x%x(seq-%x) ctx 0x%x[fd-%d] args:[0x%x 0x%x] resp %s, bmap %d\n",
384 					 msg->function_id, msg->size,
385 					 msg_id, entry->seq_num,
386 					 msg->context_id, entry->ctx->idx,
387 					 msg->cmd, msg->arg,
388 					 responded ? "T" : "F", bit_set);
389 			if (responded)
390 				atomic_dec(&ctx->pend_cnt);
391 			else if (bit_set)
392 				bcm_vk_msgid_bitmap_clear(vk, msg_id, 1);
393 		}
394 		bcm_vk_free_wkent(dev, entry);
395 	}
396 	if (num && ctx)
397 		dev_info(dev, "Total drained items %d [fd-%d]\n",
398 			 num, ctx->idx);
399 }
400 
401 void bcm_vk_drain_msg_on_reset(struct bcm_vk *vk)
402 {
403 	bcm_vk_drain_all_pend(&vk->pdev->dev, &vk->to_v_msg_chan, NULL);
404 	bcm_vk_drain_all_pend(&vk->pdev->dev, &vk->to_h_msg_chan, NULL);
405 }
406 
407 /*
408  * Function to sync up the messages queue info that is provided by BAR1
409  */
410 int bcm_vk_sync_msgq(struct bcm_vk *vk, bool force_sync)
411 {
412 	struct bcm_vk_msgq __iomem *msgq;
413 	struct device *dev = &vk->pdev->dev;
414 	u32 msgq_off;
415 	u32 num_q;
416 	struct bcm_vk_msg_chan *chan_list[] = {&vk->to_v_msg_chan,
417 					       &vk->to_h_msg_chan};
418 	struct bcm_vk_msg_chan *chan;
419 	int i, j;
420 	int ret = 0;
421 
422 	/*
423 	 * If the driver is loaded at startup where vk OS is not up yet,
424 	 * the msgq-info may not be available until a later time.  In
425 	 * this case, we skip and the sync function is supposed to be
426 	 * called again.
427 	 */
428 	if (!bcm_vk_msgq_marker_valid(vk)) {
429 		dev_info(dev, "BAR1 msgq marker not initialized.\n");
430 		return -EAGAIN;
431 	}
432 
433 	msgq_off = vkread32(vk, BAR_1, VK_BAR1_MSGQ_CTRL_OFF);
434 
435 	/* each side is always half the total  */
436 	num_q = vkread32(vk, BAR_1, VK_BAR1_MSGQ_NR) / 2;
437 	if (!num_q || (num_q > VK_MSGQ_PER_CHAN_MAX)) {
438 		dev_err(dev,
439 			"Advertised msgq %d error - max %d allowed\n",
440 			num_q, VK_MSGQ_PER_CHAN_MAX);
441 		return -EINVAL;
442 	}
443 
444 	vk->to_v_msg_chan.q_nr = num_q;
445 	vk->to_h_msg_chan.q_nr = num_q;
446 
447 	/* first msgq location */
448 	msgq = vk->bar[BAR_1] + msgq_off;
449 
450 	/*
451 	 * if this function is called when it is already inited,
452 	 * something is wrong
453 	 */
454 	if (bcm_vk_drv_access_ok(vk) && !force_sync) {
455 		dev_err(dev, "Msgq info already in sync\n");
456 		return -EPERM;
457 	}
458 
459 	for (i = 0; i < ARRAY_SIZE(chan_list); i++) {
460 		chan = chan_list[i];
461 		memset(chan->sync_qinfo, 0, sizeof(chan->sync_qinfo));
462 
463 		for (j = 0; j < num_q; j++) {
464 			struct bcm_vk_sync_qinfo *qinfo;
465 			u32 msgq_start;
466 			u32 msgq_size;
467 			u32 msgq_nxt;
468 			u32 msgq_db_offset, q_db_offset;
469 
470 			chan->msgq[j] = msgq;
471 			msgq_start = readl_relaxed(&msgq->start);
472 			msgq_size = readl_relaxed(&msgq->size);
473 			msgq_nxt = readl_relaxed(&msgq->nxt);
474 			msgq_db_offset = readl_relaxed(&msgq->db_offset);
475 			q_db_offset = (msgq_db_offset & ((1 << DB_SHIFT) - 1));
476 			if (q_db_offset  == (~msgq_db_offset >> DB_SHIFT))
477 				msgq_db_offset = q_db_offset;
478 			else
479 				/* fall back to default */
480 				msgq_db_offset = VK_BAR0_Q_DB_BASE(j);
481 
482 			dev_info(dev,
483 				 "MsgQ[%d] type %d num %d, @ 0x%x, db_offset 0x%x rd_idx %d wr_idx %d, size %d, nxt 0x%x\n",
484 				 j,
485 				 readw_relaxed(&msgq->type),
486 				 readw_relaxed(&msgq->num),
487 				 msgq_start,
488 				 msgq_db_offset,
489 				 readl_relaxed(&msgq->rd_idx),
490 				 readl_relaxed(&msgq->wr_idx),
491 				 msgq_size,
492 				 msgq_nxt);
493 
494 			qinfo = &chan->sync_qinfo[j];
495 			/* formulate and record static info */
496 			qinfo->q_start = vk->bar[BAR_1] + msgq_start;
497 			qinfo->q_size = msgq_size;
498 			/* set low threshold as 50% or 1/2 */
499 			qinfo->q_low = qinfo->q_size >> 1;
500 			qinfo->q_mask = qinfo->q_size - 1;
501 			qinfo->q_db_offset = msgq_db_offset;
502 
503 			msgq++;
504 		}
505 	}
506 	/* Publish message queue info before allowing driver access. */
507 	atomic_set_release(&vk->msgq_inited, 1);
508 
509 	return ret;
510 }
511 
512 static int bcm_vk_msg_chan_init(struct bcm_vk_msg_chan *chan)
513 {
514 	u32 i;
515 
516 	mutex_init(&chan->msgq_mutex);
517 	spin_lock_init(&chan->pendq_lock);
518 	for (i = 0; i < VK_MSGQ_MAX_NR; i++)
519 		INIT_LIST_HEAD(&chan->pendq[i]);
520 
521 	return 0;
522 }
523 
524 static void bcm_vk_append_pendq(struct bcm_vk_msg_chan *chan, u16 q_num,
525 				struct bcm_vk_wkent *entry)
526 {
527 	struct bcm_vk_ctx *ctx;
528 
529 	spin_lock(&chan->pendq_lock);
530 	list_add_tail(&entry->node, &chan->pendq[q_num]);
531 	if (entry->to_h_msg) {
532 		ctx = entry->ctx;
533 		atomic_inc(&ctx->pend_cnt);
534 		wake_up_interruptible(&ctx->rd_wq);
535 	}
536 	spin_unlock(&chan->pendq_lock);
537 }
538 
539 static u32 bcm_vk_append_ib_sgl(struct bcm_vk *vk,
540 				struct bcm_vk_wkent *entry,
541 				struct _vk_data *data,
542 				unsigned int num_planes)
543 {
544 	unsigned int i;
545 	unsigned int item_cnt = 0;
546 	struct device *dev = &vk->pdev->dev;
547 	struct bcm_vk_msg_chan *chan = &vk->to_v_msg_chan;
548 	struct vk_msg_blk *msg = &entry->to_v_msg[0];
549 	struct bcm_vk_msgq __iomem *msgq;
550 	struct bcm_vk_sync_qinfo *qinfo;
551 	u32 ib_sgl_size = 0;
552 	u8 *buf = (u8 *)&entry->to_v_msg[entry->to_v_blks];
553 	u32 avail;
554 	u32 q_num;
555 
556 	/* check if high watermark is hit, and if so, skip */
557 	q_num = get_q_num(msg);
558 	msgq = chan->msgq[q_num];
559 	qinfo = &chan->sync_qinfo[q_num];
560 	avail = msgq_avail_space(msgq, qinfo);
561 	if (avail < qinfo->q_low) {
562 		dev_dbg(dev, "Skip inserting inband SGL, [0x%x/0x%x]\n",
563 			avail, qinfo->q_size);
564 		return 0;
565 	}
566 
567 	for (i = 0; i < num_planes; i++) {
568 		if (data[i].address &&
569 		    (ib_sgl_size + data[i].size) <= vk->ib_sgl_size) {
570 			item_cnt++;
571 			memcpy(buf, entry->dma[i].sglist, data[i].size);
572 			ib_sgl_size += data[i].size;
573 			buf += data[i].size;
574 		}
575 	}
576 
577 	dev_dbg(dev, "Num %u sgl items appended, size 0x%x, room 0x%x\n",
578 		item_cnt, ib_sgl_size, vk->ib_sgl_size);
579 
580 	/* round up size */
581 	ib_sgl_size = (ib_sgl_size + VK_MSGQ_BLK_SIZE - 1)
582 		       >> VK_MSGQ_BLK_SZ_SHIFT;
583 
584 	return ib_sgl_size;
585 }
586 
587 void bcm_to_v_q_doorbell(struct bcm_vk *vk, u32 q_num, u32 db_val)
588 {
589 	struct bcm_vk_msg_chan *chan = &vk->to_v_msg_chan;
590 	struct bcm_vk_sync_qinfo *qinfo = &chan->sync_qinfo[q_num];
591 
592 	vkwrite32(vk, db_val, BAR_0, qinfo->q_db_offset);
593 }
594 
595 static int bcm_to_v_msg_enqueue(struct bcm_vk *vk, struct bcm_vk_wkent *entry)
596 {
597 	static u32 seq_num;
598 	struct bcm_vk_msg_chan *chan = &vk->to_v_msg_chan;
599 	struct device *dev = &vk->pdev->dev;
600 	struct vk_msg_blk *src = &entry->to_v_msg[0];
601 
602 	struct vk_msg_blk __iomem *dst;
603 	struct bcm_vk_msgq __iomem *msgq;
604 	struct bcm_vk_sync_qinfo *qinfo;
605 	u32 q_num = get_q_num(src);
606 	u32 wr_idx; /* local copy */
607 	u32 i;
608 	u32 avail;
609 	u32 retry;
610 
611 	if (entry->to_v_blks != src->size + 1) {
612 		dev_err(dev, "number of blks %d not matching %d MsgId[0x%x]: func %d ctx 0x%x\n",
613 			entry->to_v_blks,
614 			src->size + 1,
615 			get_msg_id(src),
616 			src->function_id,
617 			src->context_id);
618 		return -EMSGSIZE;
619 	}
620 
621 	msgq = chan->msgq[q_num];
622 	qinfo = &chan->sync_qinfo[q_num];
623 
624 	mutex_lock(&chan->msgq_mutex);
625 
626 	avail = msgq_avail_space(msgq, qinfo);
627 
628 	/* if not enough space, return EAGAIN and let app handles it */
629 	retry = 0;
630 	while ((avail < entry->to_v_blks) &&
631 	       (retry++ < BCM_VK_H2VK_ENQ_RETRY)) {
632 		mutex_unlock(&chan->msgq_mutex);
633 
634 		msleep(BCM_VK_H2VK_ENQ_RETRY_DELAY_MS);
635 		mutex_lock(&chan->msgq_mutex);
636 		avail = msgq_avail_space(msgq, qinfo);
637 	}
638 	if (retry > BCM_VK_H2VK_ENQ_RETRY) {
639 		mutex_unlock(&chan->msgq_mutex);
640 		return -EAGAIN;
641 	}
642 
643 	/* at this point, mutex is taken and there is enough space */
644 	entry->seq_num = seq_num++; /* update debug seq number */
645 	wr_idx = readl_relaxed(&msgq->wr_idx);
646 
647 	if (wr_idx >= qinfo->q_size) {
648 		dev_crit(dev, "Invalid wr_idx 0x%x => max 0x%x!",
649 			 wr_idx, qinfo->q_size);
650 		bcm_vk_blk_drv_access(vk);
651 		bcm_vk_set_host_alert(vk, ERR_LOG_HOST_PCIE_DWN);
652 		goto idx_err;
653 	}
654 
655 	dst = msgq_blk_addr(qinfo, wr_idx);
656 	for (i = 0; i < entry->to_v_blks; i++) {
657 		memcpy_toio(dst, src, sizeof(*dst));
658 
659 		src++;
660 		wr_idx = msgq_inc(qinfo, wr_idx, 1);
661 		dst = msgq_blk_addr(qinfo, wr_idx);
662 	}
663 
664 	/* flush the write pointer */
665 	writel(wr_idx, &msgq->wr_idx);
666 
667 	/* log new info for debugging */
668 	dev_dbg(dev,
669 		"MsgQ[%d] [Rd Wr] = [%d %d] blks inserted %d - Q = [u-%d a-%d]/%d\n",
670 		readl_relaxed(&msgq->num),
671 		readl_relaxed(&msgq->rd_idx),
672 		wr_idx,
673 		entry->to_v_blks,
674 		msgq_occupied(msgq, qinfo),
675 		msgq_avail_space(msgq, qinfo),
676 		readl_relaxed(&msgq->size));
677 	/*
678 	 * press door bell based on queue number. 1 is added to the wr_idx
679 	 * to avoid the value of 0 appearing on the VK side to distinguish
680 	 * from initial value.
681 	 */
682 	bcm_to_v_q_doorbell(vk, q_num, wr_idx + 1);
683 idx_err:
684 	mutex_unlock(&chan->msgq_mutex);
685 	return 0;
686 }
687 
688 int bcm_vk_send_shutdown_msg(struct bcm_vk *vk, u32 shut_type,
689 			     const pid_t pid, const u32 q_num)
690 {
691 	int rc = 0;
692 	struct bcm_vk_wkent *entry;
693 	struct device *dev = &vk->pdev->dev;
694 
695 	/*
696 	 * check if the marker is still good.  Sometimes, the PCIe interface may
697 	 * have gone done, and if so and we ship down thing based on broken
698 	 * values, kernel may panic.
699 	 */
700 	if (!bcm_vk_msgq_marker_valid(vk)) {
701 		dev_info(dev, "PCIe comm chan - invalid marker (0x%x)!\n",
702 			 vkread32(vk, BAR_1, VK_BAR1_MSGQ_DEF_RDY));
703 		return -EINVAL;
704 	}
705 
706 	entry = kzalloc_flex(*entry, to_v_msg, 1);
707 	if (!entry)
708 		return -ENOMEM;
709 	entry->to_v_blks = 1;	/* always 1 block */
710 
711 	/* fill up necessary data */
712 	entry->to_v_msg[0].function_id = VK_FID_SHUTDOWN;
713 	set_q_num(&entry->to_v_msg[0], q_num);
714 	set_msg_id(&entry->to_v_msg[0], VK_SIMPLEX_MSG_ID);
715 
716 	entry->to_v_msg[0].cmd = shut_type;
717 	entry->to_v_msg[0].arg = pid;
718 
719 	rc = bcm_to_v_msg_enqueue(vk, entry);
720 	if (rc)
721 		dev_err(dev,
722 			"Sending shutdown message to q %d for pid %d fails.\n",
723 			get_q_num(&entry->to_v_msg[0]), pid);
724 
725 	kfree(entry);
726 
727 	return rc;
728 }
729 
730 static int bcm_vk_handle_last_sess(struct bcm_vk *vk, const pid_t pid,
731 				   const u32 q_num)
732 {
733 	int rc = 0;
734 	struct device *dev = &vk->pdev->dev;
735 
736 	/*
737 	 * don't send down or do anything if message queue is not initialized
738 	 * and if it is the reset session, clear it.
739 	 */
740 	if (!bcm_vk_drv_access_ok(vk)) {
741 		if (vk->reset_pid == pid)
742 			vk->reset_pid = 0;
743 		return -EPERM;
744 	}
745 
746 	dev_dbg(dev, "No more sessions, shut down pid %d\n", pid);
747 
748 	/* only need to do it if it is not the reset process */
749 	if (vk->reset_pid != pid)
750 		rc = bcm_vk_send_shutdown_msg(vk, VK_SHUTDOWN_PID, pid, q_num);
751 	else
752 		/* put reset_pid to 0 if it is exiting last session */
753 		vk->reset_pid = 0;
754 
755 	return rc;
756 }
757 
758 static struct bcm_vk_wkent *bcm_vk_dequeue_pending(struct bcm_vk *vk,
759 						   struct bcm_vk_msg_chan *chan,
760 						   u16 q_num,
761 						   u16 msg_id)
762 {
763 	struct bcm_vk_wkent *entry = NULL, *iter;
764 
765 	spin_lock(&chan->pendq_lock);
766 	list_for_each_entry(iter, &chan->pendq[q_num], node) {
767 		if (get_msg_id(&iter->to_v_msg[0]) == msg_id) {
768 			list_del(&iter->node);
769 			entry = iter;
770 			bcm_vk_msgid_bitmap_clear(vk, msg_id, 1);
771 			break;
772 		}
773 	}
774 	spin_unlock(&chan->pendq_lock);
775 	return entry;
776 }
777 
778 s32 bcm_to_h_msg_dequeue(struct bcm_vk *vk)
779 {
780 	struct device *dev = &vk->pdev->dev;
781 	struct bcm_vk_msg_chan *chan = &vk->to_h_msg_chan;
782 	struct vk_msg_blk *data;
783 	struct vk_msg_blk __iomem *src;
784 	struct vk_msg_blk *dst;
785 	struct bcm_vk_msgq __iomem *msgq;
786 	struct bcm_vk_sync_qinfo *qinfo;
787 	struct bcm_vk_wkent *entry;
788 	u32 rd_idx, wr_idx;
789 	u32 q_num, msg_id, j;
790 	u32 num_blks;
791 	s32 total = 0;
792 	int cnt = 0;
793 	int msg_processed = 0;
794 	int max_msg_to_process;
795 	bool exit_loop;
796 
797 	/*
798 	 * drain all the messages from the queues, and find its pending
799 	 * entry in the to_v queue, based on msg_id & q_num, and move the
800 	 * entry to the to_h pending queue, waiting for user space
801 	 * program to extract
802 	 */
803 	mutex_lock(&chan->msgq_mutex);
804 
805 	for (q_num = 0; q_num < chan->q_nr; q_num++) {
806 		msgq = chan->msgq[q_num];
807 		qinfo = &chan->sync_qinfo[q_num];
808 		max_msg_to_process = BCM_VK_MSG_PROC_MAX_LOOP * qinfo->q_size;
809 
810 		rd_idx = readl_relaxed(&msgq->rd_idx);
811 		wr_idx = readl_relaxed(&msgq->wr_idx);
812 		msg_processed = 0;
813 		exit_loop = false;
814 		while ((rd_idx != wr_idx) && !exit_loop) {
815 			u8 src_size;
816 
817 			/*
818 			 * Make a local copy and get pointer to src blk
819 			 * The rd_idx is masked before getting the pointer to
820 			 * avoid out of bound access in case the interface goes
821 			 * down.  It will end up pointing to the last block in
822 			 * the buffer, but subsequent src->size check would be
823 			 * able to catch this.
824 			 */
825 			src = msgq_blk_addr(qinfo, rd_idx & qinfo->q_mask);
826 			src_size = readb(&src->size);
827 
828 			if ((rd_idx >= qinfo->q_size) ||
829 			    (src_size > (qinfo->q_size - 1))) {
830 				dev_crit(dev,
831 					 "Invalid rd_idx 0x%x or size 0x%x => max 0x%x!",
832 					 rd_idx, src_size, qinfo->q_size);
833 				bcm_vk_blk_drv_access(vk);
834 				bcm_vk_set_host_alert(vk,
835 						      ERR_LOG_HOST_PCIE_DWN);
836 				goto idx_err;
837 			}
838 
839 			num_blks = src_size + 1;
840 			data = kzalloc(num_blks * VK_MSGQ_BLK_SIZE, GFP_KERNEL);
841 			if (data) {
842 				/* copy messages and linearize it */
843 				dst = data;
844 				for (j = 0; j < num_blks; j++) {
845 					memcpy_fromio(dst, src, sizeof(*dst));
846 
847 					dst++;
848 					rd_idx = msgq_inc(qinfo, rd_idx, 1);
849 					src = msgq_blk_addr(qinfo, rd_idx);
850 				}
851 				total++;
852 			} else {
853 				/*
854 				 * if we could not allocate memory in kernel,
855 				 * that is fatal.
856 				 */
857 				dev_crit(dev, "Kernel mem allocation failure.\n");
858 				total = -ENOMEM;
859 				goto idx_err;
860 			}
861 
862 			/* flush rd pointer after a message is dequeued */
863 			writel(rd_idx, &msgq->rd_idx);
864 
865 			/* log new info for debugging */
866 			dev_dbg(dev,
867 				"MsgQ[%d] [Rd Wr] = [%d %d] blks extracted %d - Q = [u-%d a-%d]/%d\n",
868 				readl_relaxed(&msgq->num),
869 				rd_idx,
870 				wr_idx,
871 				num_blks,
872 				msgq_occupied(msgq, qinfo),
873 				msgq_avail_space(msgq, qinfo),
874 				readl_relaxed(&msgq->size));
875 
876 			/*
877 			 * No need to search if it is an autonomous one-way
878 			 * message from driver, as these messages do not bear
879 			 * a to_v pending item. Currently, only the shutdown
880 			 * message falls into this category.
881 			 */
882 			if (data->function_id == VK_FID_SHUTDOWN) {
883 				kfree(data);
884 				continue;
885 			}
886 
887 			msg_id = get_msg_id(data);
888 			/* lookup original message in to_v direction */
889 			entry = bcm_vk_dequeue_pending(vk,
890 						       &vk->to_v_msg_chan,
891 						       q_num,
892 						       msg_id);
893 
894 			/*
895 			 * if there is message to does not have prior send,
896 			 * this is the location to add here
897 			 */
898 			if (entry) {
899 				entry->to_h_blks = num_blks;
900 				entry->to_h_msg = data;
901 				bcm_vk_append_pendq(&vk->to_h_msg_chan,
902 						    q_num, entry);
903 
904 			} else {
905 				if (cnt++ < batch_log)
906 					dev_info(dev,
907 						 "Could not find MsgId[0x%x] for resp func %d bmap %d\n",
908 						 msg_id, data->function_id,
909 						 test_bit(msg_id, vk->bmap));
910 				kfree(data);
911 			}
912 			/* Fetch wr_idx to handle more back-to-back events */
913 			wr_idx = readl(&msgq->wr_idx);
914 
915 			/*
916 			 * cap the max so that even we try to handle more back-to-back events,
917 			 * so that it won't hold CPU too long or in case rd/wr idexes are
918 			 * corrupted which triggers infinite looping.
919 			 */
920 			if (++msg_processed >= max_msg_to_process) {
921 				dev_warn(dev, "Q[%d] Per loop processing exceeds %d\n",
922 					 q_num, max_msg_to_process);
923 				exit_loop = true;
924 			}
925 		}
926 	}
927 idx_err:
928 	mutex_unlock(&chan->msgq_mutex);
929 	dev_dbg(dev, "total %d drained from queues\n", total);
930 
931 	return total;
932 }
933 
934 /*
935  * init routine for all required data structures
936  */
937 static int bcm_vk_data_init(struct bcm_vk *vk)
938 {
939 	int i;
940 
941 	spin_lock_init(&vk->ctx_lock);
942 	for (i = 0; i < ARRAY_SIZE(vk->ctx); i++) {
943 		vk->ctx[i].in_use = false;
944 		vk->ctx[i].idx = i;	/* self identity */
945 		vk->ctx[i].miscdev = NULL;
946 	}
947 	spin_lock_init(&vk->msg_id_lock);
948 	spin_lock_init(&vk->host_alert_lock);
949 	vk->msg_id = 0;
950 
951 	/* initialize hash table */
952 	for (i = 0; i < VK_PID_HT_SZ; i++)
953 		INIT_LIST_HEAD(&vk->pid_ht[i].head);
954 
955 	return 0;
956 }
957 
958 irqreturn_t bcm_vk_msgq_irqhandler(int irq, void *dev_id)
959 {
960 	struct bcm_vk *vk = dev_id;
961 
962 	if (!bcm_vk_drv_access_ok(vk)) {
963 		dev_err(&vk->pdev->dev,
964 			"Interrupt %d received when msgq not inited\n", irq);
965 		goto skip_schedule_work;
966 	}
967 
968 	queue_work(vk->wq_thread, &vk->wq_work);
969 
970 skip_schedule_work:
971 	return IRQ_HANDLED;
972 }
973 
974 int bcm_vk_open(struct inode *inode, struct file *p_file)
975 {
976 	struct bcm_vk_ctx *ctx;
977 	struct miscdevice *miscdev = (struct miscdevice *)p_file->private_data;
978 	struct bcm_vk *vk = container_of(miscdev, struct bcm_vk, miscdev);
979 	struct device *dev = &vk->pdev->dev;
980 	int rc = 0;
981 
982 	/* get a context and set it up for file */
983 	ctx = bcm_vk_get_ctx(vk, task_tgid_nr(current));
984 	if (!ctx) {
985 		dev_err(dev, "Error allocating context\n");
986 		rc = -ENOMEM;
987 	} else {
988 		/*
989 		 * set up context and replace private data with context for
990 		 * other methods to use.  Reason for the context is because
991 		 * it is allowed for multiple sessions to open the sysfs, and
992 		 * for each file open, when upper layer query the response,
993 		 * only those that are tied to a specific open should be
994 		 * returned.  The context->idx will be used for such binding
995 		 */
996 		ctx->miscdev = miscdev;
997 		p_file->private_data = ctx;
998 		dev_dbg(dev, "ctx_returned with idx %d, pid %d\n",
999 			ctx->idx, ctx->pid);
1000 	}
1001 	return rc;
1002 }
1003 
1004 ssize_t bcm_vk_read(struct file *p_file,
1005 		    char __user *buf,
1006 		    size_t count,
1007 		    loff_t *f_pos)
1008 {
1009 	ssize_t rc = -ENOMSG;
1010 	struct bcm_vk_ctx *ctx = p_file->private_data;
1011 	struct bcm_vk *vk = container_of(ctx->miscdev, struct bcm_vk,
1012 					 miscdev);
1013 	struct device *dev = &vk->pdev->dev;
1014 	struct bcm_vk_msg_chan *chan = &vk->to_h_msg_chan;
1015 	struct bcm_vk_wkent *entry = NULL, *iter;
1016 	struct vk_msg_blk tmp_msg;
1017 	u32 tmp_usr_msg_id;
1018 	u32 tmp_blks;
1019 	u32 q_num;
1020 	u32 rsp_length;
1021 
1022 	if (!bcm_vk_drv_access_ok(vk))
1023 		return -EPERM;
1024 
1025 	dev_dbg(dev, "Buf count %zu\n", count);
1026 
1027 	/*
1028 	 * search through the pendq on the to_h chan, and return only those
1029 	 * that belongs to the same context.  Search is always from the high to
1030 	 * the low priority queues
1031 	 */
1032 	spin_lock(&chan->pendq_lock);
1033 	for (q_num = 0; q_num < chan->q_nr; q_num++) {
1034 		list_for_each_entry(iter, &chan->pendq[q_num], node) {
1035 			if (iter->ctx->idx == ctx->idx) {
1036 				if (count >=
1037 				    (iter->to_h_blks * VK_MSGQ_BLK_SIZE)) {
1038 					list_del(&iter->node);
1039 					atomic_dec(&ctx->pend_cnt);
1040 					entry = iter;
1041 				} else {
1042 					/* buffer not big enough */
1043 					tmp_msg = iter->to_h_msg[0];
1044 					tmp_usr_msg_id = iter->usr_msg_id;
1045 					tmp_blks = iter->to_h_blks;
1046 					rc = -EMSGSIZE;
1047 				}
1048 				goto read_loop_exit;
1049 			}
1050 		}
1051 	}
1052 read_loop_exit:
1053 	spin_unlock(&chan->pendq_lock);
1054 
1055 	if (entry) {
1056 		/* retrieve the passed down msg_id */
1057 		set_msg_id(&entry->to_h_msg[0], entry->usr_msg_id);
1058 		rsp_length = entry->to_h_blks * VK_MSGQ_BLK_SIZE;
1059 		if (copy_to_user(buf, entry->to_h_msg, rsp_length) == 0)
1060 			rc = rsp_length;
1061 
1062 		bcm_vk_free_wkent(dev, entry);
1063 	} else if (rc == -EMSGSIZE) {
1064 		/*
1065 		 * in this case, return just the first block, so
1066 		 * that app knows what size it is looking for.
1067 		 */
1068 		set_msg_id(&tmp_msg, tmp_usr_msg_id);
1069 		tmp_msg.size = tmp_blks - 1;
1070 		if (copy_to_user(buf, &tmp_msg, VK_MSGQ_BLK_SIZE) != 0) {
1071 			dev_err(dev, "Error return 1st block in -EMSGSIZE\n");
1072 			rc = -EFAULT;
1073 		}
1074 	}
1075 	return rc;
1076 }
1077 
1078 ssize_t bcm_vk_write(struct file *p_file,
1079 		     const char __user *buf,
1080 		     size_t count,
1081 		     loff_t *f_pos)
1082 {
1083 	ssize_t rc;
1084 	struct bcm_vk_ctx *ctx = p_file->private_data;
1085 	struct bcm_vk *vk = container_of(ctx->miscdev, struct bcm_vk,
1086 					 miscdev);
1087 	struct bcm_vk_msgq __iomem *msgq;
1088 	struct device *dev = &vk->pdev->dev;
1089 	struct bcm_vk_wkent *entry;
1090 	u32 sgl_extra_blks;
1091 	u32 q_num;
1092 	u32 msg_size;
1093 	u32 msgq_size;
1094 	size_t entry_size;
1095 
1096 	if (!bcm_vk_drv_access_ok(vk))
1097 		return -EPERM;
1098 
1099 	dev_dbg(dev, "Msg count %zu\n", count);
1100 
1101 	/* first, do sanity check where count should be multiple of basic blk */
1102 	if (!count || count & (VK_MSGQ_BLK_SIZE - 1)) {
1103 		dev_err(dev, "Failure with size %zu not a positive multiple of %zu\n",
1104 			count, VK_MSGQ_BLK_SIZE);
1105 		rc = -EINVAL;
1106 		goto write_err;
1107 	}
1108 
1109 	if (check_add_overflow(sizeof(*entry), count, &entry_size) ||
1110 	    check_add_overflow(entry_size, vk->ib_sgl_size, &entry_size)) {
1111 		rc = -EOVERFLOW;
1112 		goto write_err;
1113 	}
1114 
1115 	/* allocate the work entry + buffer for size count and inband sgl */
1116 	entry = kzalloc(entry_size, GFP_KERNEL);
1117 	if (!entry) {
1118 		rc = -ENOMEM;
1119 		goto write_err;
1120 	}
1121 	entry->to_v_blks = count >> VK_MSGQ_BLK_SZ_SHIFT;
1122 
1123 	/* now copy msg from user space, and then formulate the work entry */
1124 	if (copy_from_user(&entry->to_v_msg[0], buf, count)) {
1125 		rc = -EFAULT;
1126 		goto write_free_ent;
1127 	}
1128 
1129 	entry->ctx = ctx;
1130 
1131 	/* do a check on the blk size which could not exceed queue space */
1132 	q_num = get_q_num(&entry->to_v_msg[0]);
1133 	msgq = vk->to_v_msg_chan.msgq[q_num];
1134 	msgq_size = readl_relaxed(&msgq->size);
1135 	if (entry->to_v_blks + (vk->ib_sgl_size >> VK_MSGQ_BLK_SZ_SHIFT)
1136 	    > (msgq_size - 1)) {
1137 		dev_err(dev, "Blk size %d exceed max queue size allowed %d\n",
1138 			entry->to_v_blks, msgq_size - 1);
1139 		rc = -EINVAL;
1140 		goto write_free_ent;
1141 	}
1142 
1143 	/* Use internal message id */
1144 	entry->usr_msg_id = get_msg_id(&entry->to_v_msg[0]);
1145 	rc = bcm_vk_get_msg_id(vk);
1146 	if (rc == VK_MSG_ID_OVERFLOW) {
1147 		dev_err(dev, "msg_id overflow\n");
1148 		rc = -EOVERFLOW;
1149 		goto write_free_ent;
1150 	}
1151 	set_msg_id(&entry->to_v_msg[0], rc);
1152 	ctx->q_num = q_num;
1153 
1154 	dev_dbg(dev,
1155 		"[Q-%d]Message ctx id %d, usr_msg_id 0x%x sent msg_id 0x%x\n",
1156 		ctx->q_num, ctx->idx, entry->usr_msg_id,
1157 		get_msg_id(&entry->to_v_msg[0]));
1158 
1159 	if (entry->to_v_msg[0].function_id == VK_FID_TRANS_BUF) {
1160 		/* Convert any pointers to sg list */
1161 		unsigned int num_planes;
1162 		int dir;
1163 		struct _vk_data *data;
1164 
1165 		/*
1166 		 * check if we are in reset, if so, no buffer transfer is
1167 		 * allowed and return error.
1168 		 */
1169 		if (vk->reset_pid) {
1170 			dev_dbg(dev, "No Transfer allowed during reset, pid %d.\n",
1171 				ctx->pid);
1172 			rc = -EACCES;
1173 			goto write_free_msgid;
1174 		}
1175 
1176 		num_planes = entry->to_v_msg[0].cmd & VK_CMD_PLANES_MASK;
1177 		if ((entry->to_v_msg[0].cmd & VK_CMD_MASK) == VK_CMD_DOWNLOAD)
1178 			dir = DMA_FROM_DEVICE;
1179 		else
1180 			dir = DMA_TO_DEVICE;
1181 
1182 		/* Calculate vk_data location */
1183 		/* Go to end of the message */
1184 		msg_size = entry->to_v_msg[0].size;
1185 		if (msg_size > entry->to_v_blks) {
1186 			rc = -EMSGSIZE;
1187 			goto write_free_msgid;
1188 		}
1189 
1190 		data = (struct _vk_data *)&entry->to_v_msg[msg_size + 1];
1191 
1192 		/* Now back up to the start of the pointers */
1193 		data -= num_planes;
1194 
1195 		/* Convert user addresses to DMA SG List */
1196 		rc = bcm_vk_sg_alloc(dev, entry->dma, dir, data, num_planes);
1197 		if (rc)
1198 			goto write_free_msgid;
1199 
1200 		atomic_inc(&ctx->dma_cnt);
1201 		/* try to embed inband sgl */
1202 		sgl_extra_blks = bcm_vk_append_ib_sgl(vk, entry, data,
1203 						      num_planes);
1204 		entry->to_v_blks += sgl_extra_blks;
1205 		entry->to_v_msg[0].size += sgl_extra_blks;
1206 	} else if (entry->to_v_msg[0].function_id == VK_FID_INIT &&
1207 		   entry->to_v_msg[0].context_id == VK_NEW_CTX) {
1208 		/*
1209 		 * Init happens in 2 stages, only the first stage contains the
1210 		 * pid that needs translating.
1211 		 */
1212 		pid_t org_pid, pid;
1213 
1214 		/*
1215 		 * translate the pid into the unique host space as user
1216 		 * may run sessions inside containers or process
1217 		 * namespaces.
1218 		 */
1219 #define VK_MSG_PID_MASK 0xffffff00
1220 #define VK_MSG_PID_SH   8
1221 		org_pid = (entry->to_v_msg[0].arg & VK_MSG_PID_MASK)
1222 			   >> VK_MSG_PID_SH;
1223 
1224 		pid = task_tgid_nr(current);
1225 		entry->to_v_msg[0].arg =
1226 			(entry->to_v_msg[0].arg & ~VK_MSG_PID_MASK) |
1227 			(pid << VK_MSG_PID_SH);
1228 		if (org_pid != pid)
1229 			dev_dbg(dev, "In PID 0x%x(%d), converted PID 0x%x(%d)\n",
1230 				org_pid, org_pid, pid, pid);
1231 	}
1232 
1233 	/*
1234 	 * store work entry to pending queue until a response is received.
1235 	 * This needs to be done before enqueuing the message
1236 	 */
1237 	bcm_vk_append_pendq(&vk->to_v_msg_chan, q_num, entry);
1238 
1239 	rc = bcm_to_v_msg_enqueue(vk, entry);
1240 	if (rc) {
1241 		dev_err(dev, "Fail to enqueue msg to to_v queue\n");
1242 
1243 		/* remove message from pending list */
1244 		entry = bcm_vk_dequeue_pending
1245 			       (vk,
1246 				&vk->to_v_msg_chan,
1247 				q_num,
1248 				get_msg_id(&entry->to_v_msg[0]));
1249 		goto write_free_ent;
1250 	}
1251 
1252 	return count;
1253 
1254 write_free_msgid:
1255 	bcm_vk_msgid_bitmap_clear(vk, get_msg_id(&entry->to_v_msg[0]), 1);
1256 write_free_ent:
1257 	kfree(entry);
1258 write_err:
1259 	return rc;
1260 }
1261 
1262 __poll_t bcm_vk_poll(struct file *p_file, struct poll_table_struct *wait)
1263 {
1264 	__poll_t ret = 0;
1265 	int cnt;
1266 	struct bcm_vk_ctx *ctx = p_file->private_data;
1267 	struct bcm_vk *vk = container_of(ctx->miscdev, struct bcm_vk, miscdev);
1268 	struct device *dev = &vk->pdev->dev;
1269 
1270 	poll_wait(p_file, &ctx->rd_wq, wait);
1271 
1272 	cnt = atomic_read(&ctx->pend_cnt);
1273 	if (cnt) {
1274 		ret = (__force __poll_t)(POLLIN | POLLRDNORM);
1275 		if (cnt < 0) {
1276 			dev_err(dev, "Error cnt %d, setting back to 0", cnt);
1277 			atomic_set(&ctx->pend_cnt, 0);
1278 		}
1279 	}
1280 
1281 	return ret;
1282 }
1283 
1284 int bcm_vk_release(struct inode *inode, struct file *p_file)
1285 {
1286 	int ret;
1287 	struct bcm_vk_ctx *ctx = p_file->private_data;
1288 	struct bcm_vk *vk = container_of(ctx->miscdev, struct bcm_vk, miscdev);
1289 	struct device *dev = &vk->pdev->dev;
1290 	pid_t pid = ctx->pid;
1291 	int dma_cnt;
1292 	unsigned long timeout, start_time;
1293 
1294 	/*
1295 	 * if there are outstanding DMA transactions, need to delay long enough
1296 	 * to ensure that the card side would have stopped touching the host buffer
1297 	 * and its SGL list.  A race condition could happen if the host app is killed
1298 	 * abruptly, eg kill -9, while some DMA transfer orders are still inflight.
1299 	 * Nothing could be done except for a delay as host side is running in a
1300 	 * completely async fashion.
1301 	 */
1302 	start_time = jiffies;
1303 	timeout = start_time + msecs_to_jiffies(BCM_VK_DMA_DRAIN_MAX_MS);
1304 	do {
1305 		if (time_after(jiffies, timeout)) {
1306 			dev_warn(dev, "%d dma still pending for [fd-%d] pid %d\n",
1307 				 dma_cnt, ctx->idx, pid);
1308 			break;
1309 		}
1310 		dma_cnt = atomic_read(&ctx->dma_cnt);
1311 		cpu_relax();
1312 		cond_resched();
1313 	} while (dma_cnt);
1314 	dev_dbg(dev, "Draining for [fd-%d] pid %d - delay %d ms\n",
1315 		ctx->idx, pid, jiffies_to_msecs(jiffies - start_time));
1316 
1317 	bcm_vk_drain_all_pend(&vk->pdev->dev, &vk->to_v_msg_chan, ctx);
1318 	bcm_vk_drain_all_pend(&vk->pdev->dev, &vk->to_h_msg_chan, ctx);
1319 
1320 	ret = bcm_vk_free_ctx(vk, ctx);
1321 	if (ret == 0)
1322 		ret = bcm_vk_handle_last_sess(vk, pid, ctx->q_num);
1323 	else
1324 		ret = 0;
1325 
1326 	kref_put(&vk->kref, bcm_vk_release_data);
1327 
1328 	return ret;
1329 }
1330 
1331 int bcm_vk_msg_init(struct bcm_vk *vk)
1332 {
1333 	struct device *dev = &vk->pdev->dev;
1334 	int ret;
1335 
1336 	if (bcm_vk_data_init(vk)) {
1337 		dev_err(dev, "Error initializing internal data structures\n");
1338 		return -EINVAL;
1339 	}
1340 
1341 	if (bcm_vk_msg_chan_init(&vk->to_v_msg_chan) ||
1342 	    bcm_vk_msg_chan_init(&vk->to_h_msg_chan)) {
1343 		dev_err(dev, "Error initializing communication channel\n");
1344 		return -EIO;
1345 	}
1346 
1347 	/* read msgq info if ready */
1348 	ret = bcm_vk_sync_msgq(vk, false);
1349 	if (ret && (ret != -EAGAIN)) {
1350 		dev_err(dev, "Error reading comm msg Q info\n");
1351 		return -EIO;
1352 	}
1353 
1354 	return 0;
1355 }
1356 
1357 void bcm_vk_msg_remove(struct bcm_vk *vk)
1358 {
1359 	bcm_vk_blk_drv_access(vk);
1360 
1361 	/* drain all pending items */
1362 	bcm_vk_drain_all_pend(&vk->pdev->dev, &vk->to_v_msg_chan, NULL);
1363 	bcm_vk_drain_all_pend(&vk->pdev->dev, &vk->to_h_msg_chan, NULL);
1364 }
1365