1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (c) 2012-2016, The Linux Foundation. All rights reserved.
4  * Copyright (C) 2017 Linaro Ltd.
5  */
6 #include <linux/clk.h>
7 #include <linux/module.h>
8 #include <linux/mod_devicetable.h>
9 #include <linux/platform_device.h>
10 #include <linux/pm_runtime.h>
11 #include <linux/slab.h>
12 #include <media/v4l2-mem2mem.h>
13 #include <media/videobuf2-dma-contig.h>
14 #include <media/v4l2-ioctl.h>
15 #include <media/v4l2-event.h>
16 #include <media/v4l2-ctrls.h>
17 
18 #include "hfi_venus_io.h"
19 #include "hfi_parser.h"
20 #include "core.h"
21 #include "helpers.h"
22 #include "venc.h"
23 #include "pm_helpers.h"
24 
25 #define NUM_B_FRAMES_MAX	4
26 
27 /*
28  * Three resons to keep MPLANE formats (despite that the number of planes
29  * currently is one):
30  * - the MPLANE formats allow only one plane to be used
31  * - the downstream driver use MPLANE formats too
32  * - future firmware versions could add support for >1 planes
33  */
34 static const struct venus_format venc_formats[] = {
35 	{
36 		.pixfmt = V4L2_PIX_FMT_NV12,
37 		.num_planes = 1,
38 		.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE,
39 	}, {
40 		.pixfmt = V4L2_PIX_FMT_MPEG4,
41 		.num_planes = 1,
42 		.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE,
43 	}, {
44 		.pixfmt = V4L2_PIX_FMT_H263,
45 		.num_planes = 1,
46 		.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE,
47 	}, {
48 		.pixfmt = V4L2_PIX_FMT_H264,
49 		.num_planes = 1,
50 		.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE,
51 	}, {
52 		.pixfmt = V4L2_PIX_FMT_VP8,
53 		.num_planes = 1,
54 		.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE,
55 	}, {
56 		.pixfmt = V4L2_PIX_FMT_HEVC,
57 		.num_planes = 1,
58 		.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE,
59 	},
60 };
61 
62 static const struct venus_format *
63 find_format(struct venus_inst *inst, u32 pixfmt, u32 type)
64 {
65 	const struct venus_format *fmt = venc_formats;
66 	unsigned int size = ARRAY_SIZE(venc_formats);
67 	unsigned int i;
68 
69 	for (i = 0; i < size; i++) {
70 		if (fmt[i].pixfmt == pixfmt)
71 			break;
72 	}
73 
74 	if (i == size || fmt[i].type != type)
75 		return NULL;
76 
77 	if (type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE &&
78 	    !venus_helper_check_codec(inst, fmt[i].pixfmt))
79 		return NULL;
80 
81 	return &fmt[i];
82 }
83 
84 static const struct venus_format *
85 find_format_by_index(struct venus_inst *inst, unsigned int index, u32 type)
86 {
87 	const struct venus_format *fmt = venc_formats;
88 	unsigned int size = ARRAY_SIZE(venc_formats);
89 	unsigned int i, k = 0;
90 
91 	if (index > size)
92 		return NULL;
93 
94 	for (i = 0; i < size; i++) {
95 		bool valid;
96 
97 		if (fmt[i].type != type)
98 			continue;
99 		valid = type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE ||
100 			venus_helper_check_codec(inst, fmt[i].pixfmt);
101 		if (k == index && valid)
102 			break;
103 		if (valid)
104 			k++;
105 	}
106 
107 	if (i == size)
108 		return NULL;
109 
110 	return &fmt[i];
111 }
112 
113 static int venc_v4l2_to_hfi(int id, int value)
114 {
115 	switch (id) {
116 	case V4L2_CID_MPEG_VIDEO_H264_ENTROPY_MODE:
117 		switch (value) {
118 		case V4L2_MPEG_VIDEO_H264_ENTROPY_MODE_CAVLC:
119 		default:
120 			return HFI_H264_ENTROPY_CAVLC;
121 		case V4L2_MPEG_VIDEO_H264_ENTROPY_MODE_CABAC:
122 			return HFI_H264_ENTROPY_CABAC;
123 		}
124 	case V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_MODE:
125 		switch (value) {
126 		case V4L2_MPEG_VIDEO_H264_LOOP_FILTER_MODE_ENABLED:
127 		default:
128 			return HFI_H264_DB_MODE_ALL_BOUNDARY;
129 		case V4L2_MPEG_VIDEO_H264_LOOP_FILTER_MODE_DISABLED:
130 			return HFI_H264_DB_MODE_DISABLE;
131 		case V4L2_MPEG_VIDEO_H264_LOOP_FILTER_MODE_DISABLED_AT_SLICE_BOUNDARY:
132 			return HFI_H264_DB_MODE_SKIP_SLICE_BOUNDARY;
133 		}
134 	}
135 
136 	return 0;
137 }
138 
139 static int
140 venc_querycap(struct file *file, void *fh, struct v4l2_capability *cap)
141 {
142 	strscpy(cap->driver, "qcom-venus", sizeof(cap->driver));
143 	strscpy(cap->card, "Qualcomm Venus video encoder", sizeof(cap->card));
144 	strscpy(cap->bus_info, "platform:qcom-venus", sizeof(cap->bus_info));
145 
146 	return 0;
147 }
148 
149 static int venc_enum_fmt(struct file *file, void *fh, struct v4l2_fmtdesc *f)
150 {
151 	struct venus_inst *inst = to_inst(file);
152 	const struct venus_format *fmt;
153 
154 	fmt = find_format_by_index(inst, f->index, f->type);
155 
156 	memset(f->reserved, 0, sizeof(f->reserved));
157 
158 	if (!fmt)
159 		return -EINVAL;
160 
161 	f->pixelformat = fmt->pixfmt;
162 
163 	return 0;
164 }
165 
166 static const struct venus_format *
167 venc_try_fmt_common(struct venus_inst *inst, struct v4l2_format *f)
168 {
169 	struct v4l2_pix_format_mplane *pixmp = &f->fmt.pix_mp;
170 	struct v4l2_plane_pix_format *pfmt = pixmp->plane_fmt;
171 	const struct venus_format *fmt;
172 	u32 sizeimage;
173 
174 	memset(pfmt[0].reserved, 0, sizeof(pfmt[0].reserved));
175 	memset(pixmp->reserved, 0, sizeof(pixmp->reserved));
176 
177 	fmt = find_format(inst, pixmp->pixelformat, f->type);
178 	if (!fmt) {
179 		if (f->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE)
180 			pixmp->pixelformat = V4L2_PIX_FMT_H264;
181 		else if (f->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE)
182 			pixmp->pixelformat = V4L2_PIX_FMT_NV12;
183 		else
184 			return NULL;
185 		fmt = find_format(inst, pixmp->pixelformat, f->type);
186 		if (!fmt)
187 			return NULL;
188 	}
189 
190 	pixmp->width = clamp(pixmp->width, frame_width_min(inst),
191 			     frame_width_max(inst));
192 	pixmp->height = clamp(pixmp->height, frame_height_min(inst),
193 			      frame_height_max(inst));
194 
195 	pixmp->width = ALIGN(pixmp->width, 128);
196 	pixmp->height = ALIGN(pixmp->height, 32);
197 
198 	pixmp->width = ALIGN(pixmp->width, 2);
199 	pixmp->height = ALIGN(pixmp->height, 2);
200 
201 	if (pixmp->field == V4L2_FIELD_ANY)
202 		pixmp->field = V4L2_FIELD_NONE;
203 	pixmp->num_planes = fmt->num_planes;
204 	pixmp->flags = 0;
205 
206 	sizeimage = venus_helper_get_framesz(pixmp->pixelformat,
207 					     pixmp->width,
208 					     pixmp->height);
209 	pfmt[0].sizeimage = max(ALIGN(pfmt[0].sizeimage, SZ_4K), sizeimage);
210 
211 	if (f->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE)
212 		pfmt[0].bytesperline = ALIGN(pixmp->width, 128);
213 	else
214 		pfmt[0].bytesperline = 0;
215 
216 	return fmt;
217 }
218 
219 static int venc_try_fmt(struct file *file, void *fh, struct v4l2_format *f)
220 {
221 	struct venus_inst *inst = to_inst(file);
222 
223 	venc_try_fmt_common(inst, f);
224 
225 	return 0;
226 }
227 
228 static int venc_s_fmt(struct file *file, void *fh, struct v4l2_format *f)
229 {
230 	struct venus_inst *inst = to_inst(file);
231 	struct v4l2_pix_format_mplane *pixmp = &f->fmt.pix_mp;
232 	struct v4l2_pix_format_mplane orig_pixmp;
233 	const struct venus_format *fmt;
234 	struct v4l2_format format;
235 	u32 pixfmt_out = 0, pixfmt_cap = 0;
236 	struct vb2_queue *q;
237 
238 	q = v4l2_m2m_get_vq(inst->m2m_ctx, f->type);
239 	if (!q)
240 		return -EINVAL;
241 
242 	if (vb2_is_busy(q))
243 		return -EBUSY;
244 
245 	orig_pixmp = *pixmp;
246 
247 	fmt = venc_try_fmt_common(inst, f);
248 	if (!fmt)
249 		return -EINVAL;
250 
251 	if (f->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
252 		pixfmt_out = pixmp->pixelformat;
253 		pixfmt_cap = inst->fmt_cap->pixfmt;
254 	} else if (f->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
255 		pixfmt_cap = pixmp->pixelformat;
256 		pixfmt_out = inst->fmt_out->pixfmt;
257 	}
258 
259 	memset(&format, 0, sizeof(format));
260 
261 	format.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
262 	format.fmt.pix_mp.pixelformat = pixfmt_out;
263 	format.fmt.pix_mp.width = orig_pixmp.width;
264 	format.fmt.pix_mp.height = orig_pixmp.height;
265 	venc_try_fmt_common(inst, &format);
266 
267 	if (f->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
268 		inst->out_width = format.fmt.pix_mp.width;
269 		inst->out_height = format.fmt.pix_mp.height;
270 		inst->colorspace = pixmp->colorspace;
271 		inst->ycbcr_enc = pixmp->ycbcr_enc;
272 		inst->quantization = pixmp->quantization;
273 		inst->xfer_func = pixmp->xfer_func;
274 	}
275 
276 	memset(&format, 0, sizeof(format));
277 
278 	format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
279 	format.fmt.pix_mp.pixelformat = pixfmt_cap;
280 	format.fmt.pix_mp.width = orig_pixmp.width;
281 	format.fmt.pix_mp.height = orig_pixmp.height;
282 	venc_try_fmt_common(inst, &format);
283 
284 	inst->width = format.fmt.pix_mp.width;
285 	inst->height = format.fmt.pix_mp.height;
286 
287 	if (f->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE)
288 		inst->fmt_out = fmt;
289 	else if (f->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
290 		inst->fmt_cap = fmt;
291 		inst->output_buf_size = pixmp->plane_fmt[0].sizeimage;
292 	}
293 
294 	return 0;
295 }
296 
297 static int venc_g_fmt(struct file *file, void *fh, struct v4l2_format *f)
298 {
299 	struct v4l2_pix_format_mplane *pixmp = &f->fmt.pix_mp;
300 	struct venus_inst *inst = to_inst(file);
301 	const struct venus_format *fmt;
302 
303 	if (f->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE)
304 		fmt = inst->fmt_cap;
305 	else if (f->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE)
306 		fmt = inst->fmt_out;
307 	else
308 		return -EINVAL;
309 
310 	pixmp->pixelformat = fmt->pixfmt;
311 
312 	if (f->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
313 		pixmp->width = inst->width;
314 		pixmp->height = inst->height;
315 		pixmp->colorspace = inst->colorspace;
316 		pixmp->ycbcr_enc = inst->ycbcr_enc;
317 		pixmp->quantization = inst->quantization;
318 		pixmp->xfer_func = inst->xfer_func;
319 	} else if (f->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
320 		pixmp->width = inst->out_width;
321 		pixmp->height = inst->out_height;
322 	}
323 
324 	venc_try_fmt_common(inst, f);
325 
326 	return 0;
327 }
328 
329 static int
330 venc_g_selection(struct file *file, void *fh, struct v4l2_selection *s)
331 {
332 	struct venus_inst *inst = to_inst(file);
333 
334 	if (s->type != V4L2_BUF_TYPE_VIDEO_OUTPUT)
335 		return -EINVAL;
336 
337 	switch (s->target) {
338 	case V4L2_SEL_TGT_CROP_DEFAULT:
339 	case V4L2_SEL_TGT_CROP_BOUNDS:
340 		s->r.width = inst->out_width;
341 		s->r.height = inst->out_height;
342 		break;
343 	case V4L2_SEL_TGT_CROP:
344 		s->r.width = inst->width;
345 		s->r.height = inst->height;
346 		break;
347 	default:
348 		return -EINVAL;
349 	}
350 
351 	s->r.top = 0;
352 	s->r.left = 0;
353 
354 	return 0;
355 }
356 
357 static int
358 venc_s_selection(struct file *file, void *fh, struct v4l2_selection *s)
359 {
360 	struct venus_inst *inst = to_inst(file);
361 
362 	if (s->type != V4L2_BUF_TYPE_VIDEO_OUTPUT)
363 		return -EINVAL;
364 
365 	if (s->r.width > inst->out_width ||
366 	    s->r.height > inst->out_height)
367 		return -EINVAL;
368 
369 	s->r.width = ALIGN(s->r.width, 2);
370 	s->r.height = ALIGN(s->r.height, 2);
371 
372 	switch (s->target) {
373 	case V4L2_SEL_TGT_CROP:
374 		s->r.top = 0;
375 		s->r.left = 0;
376 		inst->width = s->r.width;
377 		inst->height = s->r.height;
378 		break;
379 	default:
380 		return -EINVAL;
381 	}
382 
383 	return 0;
384 }
385 
386 static int venc_s_parm(struct file *file, void *fh, struct v4l2_streamparm *a)
387 {
388 	struct venus_inst *inst = to_inst(file);
389 	struct v4l2_outputparm *out = &a->parm.output;
390 	struct v4l2_fract *timeperframe = &out->timeperframe;
391 	u64 us_per_frame, fps;
392 
393 	if (a->type != V4L2_BUF_TYPE_VIDEO_OUTPUT &&
394 	    a->type != V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE)
395 		return -EINVAL;
396 
397 	memset(out->reserved, 0, sizeof(out->reserved));
398 
399 	if (!timeperframe->denominator)
400 		timeperframe->denominator = inst->timeperframe.denominator;
401 	if (!timeperframe->numerator)
402 		timeperframe->numerator = inst->timeperframe.numerator;
403 
404 	out->capability = V4L2_CAP_TIMEPERFRAME;
405 
406 	us_per_frame = timeperframe->numerator * (u64)USEC_PER_SEC;
407 	do_div(us_per_frame, timeperframe->denominator);
408 
409 	if (!us_per_frame)
410 		return -EINVAL;
411 
412 	fps = (u64)USEC_PER_SEC;
413 	do_div(fps, us_per_frame);
414 
415 	inst->timeperframe = *timeperframe;
416 	inst->fps = fps;
417 
418 	return 0;
419 }
420 
421 static int venc_g_parm(struct file *file, void *fh, struct v4l2_streamparm *a)
422 {
423 	struct venus_inst *inst = to_inst(file);
424 
425 	if (a->type != V4L2_BUF_TYPE_VIDEO_OUTPUT &&
426 	    a->type != V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE)
427 		return -EINVAL;
428 
429 	a->parm.output.capability |= V4L2_CAP_TIMEPERFRAME;
430 	a->parm.output.timeperframe = inst->timeperframe;
431 
432 	return 0;
433 }
434 
435 static int venc_enum_framesizes(struct file *file, void *fh,
436 				struct v4l2_frmsizeenum *fsize)
437 {
438 	struct venus_inst *inst = to_inst(file);
439 	const struct venus_format *fmt;
440 
441 	fsize->type = V4L2_FRMSIZE_TYPE_STEPWISE;
442 
443 	fmt = find_format(inst, fsize->pixel_format,
444 			  V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE);
445 	if (!fmt) {
446 		fmt = find_format(inst, fsize->pixel_format,
447 				  V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE);
448 		if (!fmt)
449 			return -EINVAL;
450 	}
451 
452 	if (fsize->index)
453 		return -EINVAL;
454 
455 	fsize->stepwise.min_width = frame_width_min(inst);
456 	fsize->stepwise.max_width = frame_width_max(inst);
457 	fsize->stepwise.step_width = frame_width_step(inst);
458 	fsize->stepwise.min_height = frame_height_min(inst);
459 	fsize->stepwise.max_height = frame_height_max(inst);
460 	fsize->stepwise.step_height = frame_height_step(inst);
461 
462 	return 0;
463 }
464 
465 static int venc_enum_frameintervals(struct file *file, void *fh,
466 				    struct v4l2_frmivalenum *fival)
467 {
468 	struct venus_inst *inst = to_inst(file);
469 	const struct venus_format *fmt;
470 	unsigned int framerate_factor = 1;
471 
472 	fival->type = V4L2_FRMIVAL_TYPE_STEPWISE;
473 
474 	fmt = find_format(inst, fival->pixel_format,
475 			  V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE);
476 	if (!fmt) {
477 		fmt = find_format(inst, fival->pixel_format,
478 				  V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE);
479 		if (!fmt)
480 			return -EINVAL;
481 	}
482 
483 	if (fival->index)
484 		return -EINVAL;
485 
486 	if (!fival->width || !fival->height)
487 		return -EINVAL;
488 
489 	if (fival->width > frame_width_max(inst) ||
490 	    fival->width < frame_width_min(inst) ||
491 	    fival->height > frame_height_max(inst) ||
492 	    fival->height < frame_height_min(inst))
493 		return -EINVAL;
494 
495 	if (IS_V1(inst->core)) {
496 		/* framerate is reported in 1/65535 fps unit */
497 		framerate_factor = (1 << 16);
498 	}
499 
500 	fival->stepwise.min.numerator = 1;
501 	fival->stepwise.min.denominator = frate_max(inst) / framerate_factor;
502 	fival->stepwise.max.numerator = 1;
503 	fival->stepwise.max.denominator = frate_min(inst) / framerate_factor;
504 	fival->stepwise.step.numerator = 1;
505 	fival->stepwise.step.denominator = frate_max(inst) / framerate_factor;
506 
507 	return 0;
508 }
509 
510 static int venc_subscribe_event(struct v4l2_fh *fh,
511 				const struct v4l2_event_subscription *sub)
512 {
513 	switch (sub->type) {
514 	case V4L2_EVENT_EOS:
515 		return v4l2_event_subscribe(fh, sub, 2, NULL);
516 	case V4L2_EVENT_CTRL:
517 		return v4l2_ctrl_subscribe_event(fh, sub);
518 	default:
519 		return -EINVAL;
520 	}
521 }
522 
523 static int
524 venc_encoder_cmd(struct file *file, void *fh, struct v4l2_encoder_cmd *cmd)
525 {
526 	struct venus_inst *inst = to_inst(file);
527 	struct hfi_frame_data fdata = {0};
528 	int ret = 0;
529 
530 	ret = v4l2_m2m_ioctl_try_encoder_cmd(file, fh, cmd);
531 	if (ret)
532 		return ret;
533 
534 	mutex_lock(&inst->lock);
535 
536 	if (cmd->cmd == V4L2_ENC_CMD_STOP &&
537 	    inst->enc_state == VENUS_ENC_STATE_ENCODING) {
538 		/*
539 		 * Implement V4L2_ENC_CMD_STOP by enqueue an empty buffer on
540 		 * encoder input to signal EOS.
541 		 */
542 		if (!(inst->streamon_out && inst->streamon_cap))
543 			goto unlock;
544 
545 		fdata.buffer_type = HFI_BUFFER_INPUT;
546 		fdata.flags |= HFI_BUFFERFLAG_EOS;
547 		fdata.device_addr = 0xdeadb000;
548 
549 		ret = hfi_session_process_buf(inst, &fdata);
550 
551 		inst->enc_state = VENUS_ENC_STATE_DRAIN;
552 	} else if (cmd->cmd == V4L2_ENC_CMD_START) {
553 		if (inst->enc_state == VENUS_ENC_STATE_DRAIN) {
554 			ret = -EBUSY;
555 			goto unlock;
556 		}
557 		if (inst->enc_state == VENUS_ENC_STATE_STOPPED) {
558 			vb2_clear_last_buffer_dequeued(&inst->fh.m2m_ctx->cap_q_ctx.q);
559 			inst->enc_state = VENUS_ENC_STATE_ENCODING;
560 		}
561 	}
562 
563 unlock:
564 	mutex_unlock(&inst->lock);
565 	return ret;
566 }
567 
568 static const struct v4l2_ioctl_ops venc_ioctl_ops = {
569 	.vidioc_querycap = venc_querycap,
570 	.vidioc_enum_fmt_vid_cap = venc_enum_fmt,
571 	.vidioc_enum_fmt_vid_out = venc_enum_fmt,
572 	.vidioc_s_fmt_vid_cap_mplane = venc_s_fmt,
573 	.vidioc_s_fmt_vid_out_mplane = venc_s_fmt,
574 	.vidioc_g_fmt_vid_cap_mplane = venc_g_fmt,
575 	.vidioc_g_fmt_vid_out_mplane = venc_g_fmt,
576 	.vidioc_try_fmt_vid_cap_mplane = venc_try_fmt,
577 	.vidioc_try_fmt_vid_out_mplane = venc_try_fmt,
578 	.vidioc_g_selection = venc_g_selection,
579 	.vidioc_s_selection = venc_s_selection,
580 	.vidioc_reqbufs = v4l2_m2m_ioctl_reqbufs,
581 	.vidioc_querybuf = v4l2_m2m_ioctl_querybuf,
582 	.vidioc_create_bufs = v4l2_m2m_ioctl_create_bufs,
583 	.vidioc_prepare_buf = v4l2_m2m_ioctl_prepare_buf,
584 	.vidioc_qbuf = v4l2_m2m_ioctl_qbuf,
585 	.vidioc_expbuf = v4l2_m2m_ioctl_expbuf,
586 	.vidioc_dqbuf = v4l2_m2m_ioctl_dqbuf,
587 	.vidioc_streamon = v4l2_m2m_ioctl_streamon,
588 	.vidioc_streamoff = v4l2_m2m_ioctl_streamoff,
589 	.vidioc_s_parm = venc_s_parm,
590 	.vidioc_g_parm = venc_g_parm,
591 	.vidioc_enum_framesizes = venc_enum_framesizes,
592 	.vidioc_enum_frameintervals = venc_enum_frameintervals,
593 	.vidioc_subscribe_event = venc_subscribe_event,
594 	.vidioc_unsubscribe_event = v4l2_event_unsubscribe,
595 	.vidioc_try_encoder_cmd = v4l2_m2m_ioctl_try_encoder_cmd,
596 	.vidioc_encoder_cmd = venc_encoder_cmd,
597 };
598 
599 static int venc_pm_get(struct venus_inst *inst)
600 {
601 	struct venus_core *core = inst->core;
602 	struct device *dev = core->dev_enc;
603 	int ret;
604 
605 	mutex_lock(&core->pm_lock);
606 	ret = pm_runtime_resume_and_get(dev);
607 	mutex_unlock(&core->pm_lock);
608 
609 	return ret < 0 ? ret : 0;
610 }
611 
612 static int venc_pm_put(struct venus_inst *inst, bool autosuspend)
613 {
614 	struct venus_core *core = inst->core;
615 	struct device *dev = core->dev_enc;
616 	int ret;
617 
618 	mutex_lock(&core->pm_lock);
619 
620 	if (autosuspend)
621 		ret = pm_runtime_put_autosuspend(dev);
622 	else
623 		ret = pm_runtime_put_sync(dev);
624 
625 	mutex_unlock(&core->pm_lock);
626 
627 	return ret < 0 ? ret : 0;
628 }
629 
630 static int venc_pm_get_put(struct venus_inst *inst)
631 {
632 	struct venus_core *core = inst->core;
633 	struct device *dev = core->dev_enc;
634 	int ret = 0;
635 
636 	mutex_lock(&core->pm_lock);
637 
638 	if (pm_runtime_suspended(dev)) {
639 		ret = pm_runtime_resume_and_get(dev);
640 		if (ret < 0)
641 			goto error;
642 
643 		ret = pm_runtime_put_autosuspend(dev);
644 	}
645 
646 error:
647 	mutex_unlock(&core->pm_lock);
648 
649 	return ret < 0 ? ret : 0;
650 }
651 
652 static void venc_pm_touch(struct venus_inst *inst)
653 {
654 	pm_runtime_mark_last_busy(inst->core->dev_enc);
655 }
656 
657 static int venc_set_properties(struct venus_inst *inst)
658 {
659 	struct venc_controls *ctr = &inst->controls.enc;
660 	struct hfi_intra_period intra_period;
661 	struct hfi_framerate frate;
662 	struct hfi_bitrate brate;
663 	struct hfi_idr_period idrp;
664 	struct hfi_quantization quant;
665 	struct hfi_quantization_range quant_range;
666 	struct hfi_quantization_range_v2 quant_range_v2;
667 	struct hfi_enable en;
668 	struct hfi_ltr_mode ltr_mode;
669 	struct hfi_intra_refresh intra_refresh = {};
670 	u32 ptype, rate_control, bitrate;
671 	u32 profile, level;
672 	int ret;
673 
674 	ret = venus_helper_set_work_mode(inst);
675 	if (ret)
676 		return ret;
677 
678 	ptype = HFI_PROPERTY_CONFIG_FRAME_RATE;
679 	frate.buffer_type = HFI_BUFFER_OUTPUT;
680 	frate.framerate = inst->fps * (1 << 16);
681 
682 	ret = hfi_session_set_property(inst, ptype, &frate);
683 	if (ret)
684 		return ret;
685 
686 	if (inst->fmt_cap->pixfmt == V4L2_PIX_FMT_H264) {
687 		struct hfi_h264_vui_timing_info info;
688 		struct hfi_h264_entropy_control entropy;
689 		struct hfi_h264_db_control deblock;
690 		struct hfi_h264_8x8_transform h264_transform;
691 
692 		ptype = HFI_PROPERTY_PARAM_VENC_H264_VUI_TIMING_INFO;
693 		info.enable = 1;
694 		info.fixed_framerate = 1;
695 		info.time_scale = NSEC_PER_SEC;
696 
697 		ret = hfi_session_set_property(inst, ptype, &info);
698 		if (ret)
699 			return ret;
700 
701 		ptype = HFI_PROPERTY_PARAM_VENC_H264_ENTROPY_CONTROL;
702 		entropy.entropy_mode = venc_v4l2_to_hfi(
703 					  V4L2_CID_MPEG_VIDEO_H264_ENTROPY_MODE,
704 					  ctr->h264_entropy_mode);
705 		entropy.cabac_model = HFI_H264_CABAC_MODEL_0;
706 
707 		ret = hfi_session_set_property(inst, ptype, &entropy);
708 		if (ret)
709 			return ret;
710 
711 		ptype = HFI_PROPERTY_PARAM_VENC_H264_DEBLOCK_CONTROL;
712 		deblock.mode = venc_v4l2_to_hfi(
713 				      V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_MODE,
714 				      ctr->h264_loop_filter_mode);
715 		deblock.slice_alpha_offset = ctr->h264_loop_filter_alpha;
716 		deblock.slice_beta_offset = ctr->h264_loop_filter_beta;
717 
718 		ret = hfi_session_set_property(inst, ptype, &deblock);
719 		if (ret)
720 			return ret;
721 
722 		ptype = HFI_PROPERTY_PARAM_VENC_H264_TRANSFORM_8X8;
723 		h264_transform.enable_type = 0;
724 		if (ctr->profile.h264 == V4L2_MPEG_VIDEO_H264_PROFILE_HIGH ||
725 		    ctr->profile.h264 == V4L2_MPEG_VIDEO_H264_PROFILE_CONSTRAINED_HIGH)
726 			h264_transform.enable_type = ctr->h264_8x8_transform;
727 
728 		ret = hfi_session_set_property(inst, ptype, &h264_transform);
729 		if (ret)
730 			return ret;
731 
732 	}
733 
734 	if (inst->fmt_cap->pixfmt == V4L2_PIX_FMT_H264 ||
735 	    inst->fmt_cap->pixfmt == V4L2_PIX_FMT_HEVC) {
736 		/* IDR periodicity, n:
737 		 * n = 0 - only the first I-frame is IDR frame
738 		 * n = 1 - all I-frames will be IDR frames
739 		 * n > 1 - every n-th I-frame will be IDR frame
740 		 */
741 		ptype = HFI_PROPERTY_CONFIG_VENC_IDR_PERIOD;
742 		idrp.idr_period = 0;
743 		ret = hfi_session_set_property(inst, ptype, &idrp);
744 		if (ret)
745 			return ret;
746 	}
747 
748 	if (inst->fmt_cap->pixfmt == V4L2_PIX_FMT_HEVC &&
749 	    ctr->profile.hevc == V4L2_MPEG_VIDEO_HEVC_PROFILE_MAIN_10) {
750 		struct hfi_hdr10_pq_sei hdr10;
751 		unsigned int c;
752 
753 		ptype = HFI_PROPERTY_PARAM_VENC_HDR10_PQ_SEI;
754 
755 		for (c = 0; c < 3; c++) {
756 			hdr10.mastering.display_primaries_x[c] =
757 				ctr->mastering.display_primaries_x[c];
758 			hdr10.mastering.display_primaries_y[c] =
759 				ctr->mastering.display_primaries_y[c];
760 		}
761 
762 		hdr10.mastering.white_point_x = ctr->mastering.white_point_x;
763 		hdr10.mastering.white_point_y = ctr->mastering.white_point_y;
764 		hdr10.mastering.max_display_mastering_luminance =
765 			ctr->mastering.max_display_mastering_luminance;
766 		hdr10.mastering.min_display_mastering_luminance =
767 			ctr->mastering.min_display_mastering_luminance;
768 
769 		hdr10.cll.max_content_light = ctr->cll.max_content_light_level;
770 		hdr10.cll.max_pic_average_light =
771 			ctr->cll.max_pic_average_light_level;
772 
773 		ret = hfi_session_set_property(inst, ptype, &hdr10);
774 		if (ret)
775 			return ret;
776 	}
777 
778 	if (ctr->num_b_frames) {
779 		u32 max_num_b_frames = NUM_B_FRAMES_MAX;
780 
781 		ptype = HFI_PROPERTY_PARAM_VENC_MAX_NUM_B_FRAMES;
782 		ret = hfi_session_set_property(inst, ptype, &max_num_b_frames);
783 		if (ret)
784 			return ret;
785 	}
786 
787 	ptype = HFI_PROPERTY_CONFIG_VENC_INTRA_PERIOD;
788 	intra_period.pframes = ctr->num_p_frames;
789 	intra_period.bframes = ctr->num_b_frames;
790 
791 	ret = hfi_session_set_property(inst, ptype, &intra_period);
792 	if (ret)
793 		return ret;
794 
795 	if (!ctr->rc_enable)
796 		rate_control = HFI_RATE_CONTROL_OFF;
797 	else if (ctr->bitrate_mode == V4L2_MPEG_VIDEO_BITRATE_MODE_VBR)
798 		rate_control = ctr->frame_skip_mode ? HFI_RATE_CONTROL_VBR_VFR :
799 						      HFI_RATE_CONTROL_VBR_CFR;
800 	else if (ctr->bitrate_mode == V4L2_MPEG_VIDEO_BITRATE_MODE_CBR)
801 		rate_control = ctr->frame_skip_mode ? HFI_RATE_CONTROL_CBR_VFR :
802 						      HFI_RATE_CONTROL_CBR_CFR;
803 	else if (ctr->bitrate_mode == V4L2_MPEG_VIDEO_BITRATE_MODE_CQ)
804 		rate_control = HFI_RATE_CONTROL_CQ;
805 
806 	ptype = HFI_PROPERTY_PARAM_VENC_RATE_CONTROL;
807 	ret = hfi_session_set_property(inst, ptype, &rate_control);
808 	if (ret)
809 		return ret;
810 
811 	if (rate_control == HFI_RATE_CONTROL_CQ && ctr->const_quality) {
812 		struct hfi_heic_frame_quality quality = {};
813 
814 		ptype = HFI_PROPERTY_CONFIG_HEIC_FRAME_QUALITY;
815 		quality.frame_quality = ctr->const_quality;
816 		ret = hfi_session_set_property(inst, ptype, &quality);
817 		if (ret)
818 			return ret;
819 	}
820 
821 	if (!ctr->bitrate)
822 		bitrate = 64000;
823 	else
824 		bitrate = ctr->bitrate;
825 
826 	ptype = HFI_PROPERTY_CONFIG_VENC_TARGET_BITRATE;
827 	brate.bitrate = bitrate;
828 	brate.layer_id = 0;
829 
830 	ret = hfi_session_set_property(inst, ptype, &brate);
831 	if (ret)
832 		return ret;
833 
834 	if (inst->fmt_cap->pixfmt == V4L2_PIX_FMT_H264 ||
835 	    inst->fmt_cap->pixfmt == V4L2_PIX_FMT_HEVC) {
836 		ptype = HFI_PROPERTY_CONFIG_VENC_SYNC_FRAME_SEQUENCE_HEADER;
837 		if (ctr->header_mode == V4L2_MPEG_VIDEO_HEADER_MODE_SEPARATE)
838 			en.enable = 0;
839 		else
840 			en.enable = 1;
841 
842 		ret = hfi_session_set_property(inst, ptype, &en);
843 		if (ret)
844 			return ret;
845 	}
846 
847 	if (!ctr->bitrate_peak)
848 		bitrate *= 2;
849 	else
850 		bitrate = ctr->bitrate_peak;
851 
852 	ptype = HFI_PROPERTY_CONFIG_VENC_MAX_BITRATE;
853 	brate.bitrate = bitrate;
854 	brate.layer_id = 0;
855 
856 	ret = hfi_session_set_property(inst, ptype, &brate);
857 	if (ret)
858 		return ret;
859 
860 	ptype = HFI_PROPERTY_PARAM_VENC_SESSION_QP;
861 	if (inst->fmt_cap->pixfmt == V4L2_PIX_FMT_HEVC) {
862 		quant.qp_i = ctr->hevc_i_qp;
863 		quant.qp_p = ctr->hevc_p_qp;
864 		quant.qp_b = ctr->hevc_b_qp;
865 	} else {
866 		quant.qp_i = ctr->h264_i_qp;
867 		quant.qp_p = ctr->h264_p_qp;
868 		quant.qp_b = ctr->h264_b_qp;
869 	}
870 	quant.layer_id = 0;
871 	ret = hfi_session_set_property(inst, ptype, &quant);
872 	if (ret)
873 		return ret;
874 
875 	if (inst->core->res->hfi_version == HFI_VERSION_4XX ||
876 	    inst->core->res->hfi_version == HFI_VERSION_6XX) {
877 		ptype = HFI_PROPERTY_PARAM_VENC_SESSION_QP_RANGE_V2;
878 
879 		if (inst->fmt_cap->pixfmt == V4L2_PIX_FMT_HEVC) {
880 			quant_range_v2.min_qp.qp_packed = ctr->hevc_min_qp;
881 			quant_range_v2.max_qp.qp_packed = ctr->hevc_max_qp;
882 		} else if (inst->fmt_cap->pixfmt == V4L2_PIX_FMT_VP8) {
883 			quant_range_v2.min_qp.qp_packed = ctr->vp8_min_qp;
884 			quant_range_v2.max_qp.qp_packed = ctr->vp8_max_qp;
885 		} else {
886 			quant_range_v2.min_qp.qp_packed = ctr->h264_min_qp;
887 			quant_range_v2.max_qp.qp_packed = ctr->h264_max_qp;
888 		}
889 
890 		ret = hfi_session_set_property(inst, ptype, &quant_range_v2);
891 	} else {
892 		ptype = HFI_PROPERTY_PARAM_VENC_SESSION_QP_RANGE;
893 
894 		if (inst->fmt_cap->pixfmt == V4L2_PIX_FMT_HEVC) {
895 			quant_range.min_qp = ctr->hevc_min_qp;
896 			quant_range.max_qp = ctr->hevc_max_qp;
897 		} else if (inst->fmt_cap->pixfmt == V4L2_PIX_FMT_VP8) {
898 			quant_range.min_qp = ctr->vp8_min_qp;
899 			quant_range.max_qp = ctr->vp8_max_qp;
900 		} else {
901 			quant_range.min_qp = ctr->h264_min_qp;
902 			quant_range.max_qp = ctr->h264_max_qp;
903 		}
904 
905 		quant_range.layer_id = 0;
906 		ret = hfi_session_set_property(inst, ptype, &quant_range);
907 	}
908 
909 	if (ret)
910 		return ret;
911 
912 	ptype = HFI_PROPERTY_PARAM_VENC_LTRMODE;
913 	ltr_mode.ltr_count = ctr->ltr_count;
914 	ltr_mode.ltr_mode = HFI_LTR_MODE_MANUAL;
915 	ltr_mode.trust_mode = 1;
916 	ret = hfi_session_set_property(inst, ptype, &ltr_mode);
917 	if (ret)
918 		return ret;
919 
920 	switch (inst->hfi_codec) {
921 	case HFI_VIDEO_CODEC_H264:
922 		profile = ctr->profile.h264;
923 		level = ctr->level.h264;
924 		break;
925 	case HFI_VIDEO_CODEC_MPEG4:
926 		profile = ctr->profile.mpeg4;
927 		level = ctr->level.mpeg4;
928 		break;
929 	case HFI_VIDEO_CODEC_VP8:
930 		profile = ctr->profile.vp8;
931 		level = 0;
932 		break;
933 	case HFI_VIDEO_CODEC_VP9:
934 		profile = ctr->profile.vp9;
935 		level = ctr->level.vp9;
936 		break;
937 	case HFI_VIDEO_CODEC_HEVC:
938 		profile = ctr->profile.hevc;
939 		level = ctr->level.hevc;
940 		break;
941 	case HFI_VIDEO_CODEC_MPEG2:
942 	default:
943 		profile = 0;
944 		level = 0;
945 		break;
946 	}
947 
948 	ret = venus_helper_set_profile_level(inst, profile, level);
949 	if (ret)
950 		return ret;
951 
952 	if (inst->fmt_cap->pixfmt == V4L2_PIX_FMT_H264 ||
953 	    inst->fmt_cap->pixfmt == V4L2_PIX_FMT_HEVC) {
954 		struct hfi_enable en = {};
955 
956 		ptype = HFI_PROPERTY_PARAM_VENC_H264_GENERATE_AUDNAL;
957 
958 		if (ctr->aud_enable)
959 			en.enable = 1;
960 
961 		ret = hfi_session_set_property(inst, ptype, &en);
962 	}
963 
964 	if ((inst->fmt_cap->pixfmt == V4L2_PIX_FMT_H264 ||
965 	     inst->fmt_cap->pixfmt == V4L2_PIX_FMT_HEVC) &&
966 	    (rate_control == HFI_RATE_CONTROL_CBR_VFR ||
967 	     rate_control == HFI_RATE_CONTROL_CBR_CFR)) {
968 		intra_refresh.mode = HFI_INTRA_REFRESH_NONE;
969 		intra_refresh.cir_mbs = 0;
970 
971 		if (ctr->intra_refresh_period) {
972 			u32 mbs;
973 
974 			mbs = ALIGN(inst->width, 16) * ALIGN(inst->height, 16);
975 			mbs /= 16 * 16;
976 			if (mbs % ctr->intra_refresh_period)
977 				mbs++;
978 			mbs /= ctr->intra_refresh_period;
979 
980 			intra_refresh.cir_mbs = mbs;
981 			if (ctr->intra_refresh_type ==
982 			    V4L2_CID_MPEG_VIDEO_INTRA_REFRESH_PERIOD_TYPE_CYCLIC)
983 				intra_refresh.mode = HFI_INTRA_REFRESH_CYCLIC;
984 			else
985 				intra_refresh.mode = HFI_INTRA_REFRESH_RANDOM;
986 		}
987 
988 		ptype = HFI_PROPERTY_PARAM_VENC_INTRA_REFRESH;
989 
990 		ret = hfi_session_set_property(inst, ptype, &intra_refresh);
991 		if (ret)
992 			return ret;
993 	}
994 
995 	return 0;
996 }
997 
998 static int venc_init_session(struct venus_inst *inst)
999 {
1000 	int ret;
1001 
1002 	ret = venus_helper_session_init(inst);
1003 	if (ret == -EALREADY)
1004 		return 0;
1005 	else if (ret)
1006 		return ret;
1007 
1008 	ret = venus_helper_set_stride(inst, inst->out_width,
1009 				      inst->out_height);
1010 	if (ret)
1011 		goto deinit;
1012 
1013 	ret = venus_helper_set_input_resolution(inst, inst->width,
1014 						inst->height);
1015 	if (ret)
1016 		goto deinit;
1017 
1018 	ret = venus_helper_set_output_resolution(inst, inst->width,
1019 						 inst->height,
1020 						 HFI_BUFFER_OUTPUT);
1021 	if (ret)
1022 		goto deinit;
1023 
1024 	ret = venus_helper_set_color_format(inst, inst->fmt_out->pixfmt);
1025 	if (ret)
1026 		goto deinit;
1027 
1028 	ret = venc_set_properties(inst);
1029 	if (ret)
1030 		goto deinit;
1031 
1032 	return 0;
1033 deinit:
1034 	hfi_session_deinit(inst);
1035 	return ret;
1036 }
1037 
1038 static int venc_out_num_buffers(struct venus_inst *inst, unsigned int *num)
1039 {
1040 	struct hfi_buffer_requirements bufreq;
1041 	int ret;
1042 
1043 	ret = venus_helper_get_bufreq(inst, HFI_BUFFER_INPUT, &bufreq);
1044 	if (ret)
1045 		return ret;
1046 
1047 	*num = bufreq.count_actual;
1048 
1049 	return 0;
1050 }
1051 
1052 static int venc_queue_setup(struct vb2_queue *q,
1053 			    unsigned int *num_buffers, unsigned int *num_planes,
1054 			    unsigned int sizes[], struct device *alloc_devs[])
1055 {
1056 	struct venus_inst *inst = vb2_get_drv_priv(q);
1057 	struct venus_core *core = inst->core;
1058 	unsigned int num, min = 4;
1059 	int ret;
1060 
1061 	if (*num_planes) {
1062 		if (q->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE &&
1063 		    *num_planes != inst->fmt_out->num_planes)
1064 			return -EINVAL;
1065 
1066 		if (q->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE &&
1067 		    *num_planes != inst->fmt_cap->num_planes)
1068 			return -EINVAL;
1069 
1070 		if (q->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE &&
1071 		    sizes[0] < inst->input_buf_size)
1072 			return -EINVAL;
1073 
1074 		if (q->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE &&
1075 		    sizes[0] < inst->output_buf_size)
1076 			return -EINVAL;
1077 
1078 		return 0;
1079 	}
1080 
1081 	if (test_bit(0, &core->sys_error)) {
1082 		if (inst->nonblock)
1083 			return -EAGAIN;
1084 
1085 		ret = wait_event_interruptible(core->sys_err_done,
1086 					       !test_bit(0, &core->sys_error));
1087 		if (ret)
1088 			return ret;
1089 	}
1090 
1091 	ret = venc_pm_get(inst);
1092 	if (ret)
1093 		return ret;
1094 
1095 	mutex_lock(&inst->lock);
1096 	ret = venc_init_session(inst);
1097 	mutex_unlock(&inst->lock);
1098 
1099 	if (ret)
1100 		goto put_power;
1101 
1102 	ret = venc_pm_put(inst, false);
1103 	if (ret)
1104 		return ret;
1105 
1106 	switch (q->type) {
1107 	case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:
1108 		*num_planes = inst->fmt_out->num_planes;
1109 
1110 		ret = venc_out_num_buffers(inst, &num);
1111 		if (ret)
1112 			break;
1113 
1114 		num = max(num, min);
1115 		*num_buffers = max(*num_buffers, num);
1116 		inst->num_input_bufs = *num_buffers;
1117 
1118 		sizes[0] = venus_helper_get_framesz(inst->fmt_out->pixfmt,
1119 						    inst->out_width,
1120 						    inst->out_height);
1121 		inst->input_buf_size = sizes[0];
1122 		break;
1123 	case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
1124 		*num_planes = inst->fmt_cap->num_planes;
1125 		*num_buffers = max(*num_buffers, min);
1126 		inst->num_output_bufs = *num_buffers;
1127 		sizes[0] = venus_helper_get_framesz(inst->fmt_cap->pixfmt,
1128 						    inst->width,
1129 						    inst->height);
1130 		sizes[0] = max(sizes[0], inst->output_buf_size);
1131 		inst->output_buf_size = sizes[0];
1132 		break;
1133 	default:
1134 		ret = -EINVAL;
1135 		break;
1136 	}
1137 
1138 	return ret;
1139 put_power:
1140 	venc_pm_put(inst, false);
1141 	return ret;
1142 }
1143 
1144 static int venc_buf_init(struct vb2_buffer *vb)
1145 {
1146 	struct venus_inst *inst = vb2_get_drv_priv(vb->vb2_queue);
1147 
1148 	inst->buf_count++;
1149 
1150 	return venus_helper_vb2_buf_init(vb);
1151 }
1152 
1153 static void venc_release_session(struct venus_inst *inst)
1154 {
1155 	int ret;
1156 
1157 	venc_pm_get(inst);
1158 
1159 	mutex_lock(&inst->lock);
1160 
1161 	ret = hfi_session_deinit(inst);
1162 	if (ret || inst->session_error)
1163 		hfi_session_abort(inst);
1164 
1165 	mutex_unlock(&inst->lock);
1166 
1167 	venus_pm_load_scale(inst);
1168 	INIT_LIST_HEAD(&inst->registeredbufs);
1169 	venus_pm_release_core(inst);
1170 
1171 	venc_pm_put(inst, false);
1172 }
1173 
1174 static void venc_buf_cleanup(struct vb2_buffer *vb)
1175 {
1176 	struct venus_inst *inst = vb2_get_drv_priv(vb->vb2_queue);
1177 	struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
1178 	struct venus_buffer *buf = to_venus_buffer(vbuf);
1179 
1180 	mutex_lock(&inst->lock);
1181 	if (vb->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE)
1182 		if (!list_empty(&inst->registeredbufs))
1183 			list_del_init(&buf->reg_list);
1184 	mutex_unlock(&inst->lock);
1185 
1186 	inst->buf_count--;
1187 	if (!inst->buf_count)
1188 		venc_release_session(inst);
1189 }
1190 
1191 static int venc_verify_conf(struct venus_inst *inst)
1192 {
1193 	enum hfi_version ver = inst->core->res->hfi_version;
1194 	struct hfi_buffer_requirements bufreq;
1195 	int ret;
1196 
1197 	if (!inst->num_input_bufs || !inst->num_output_bufs)
1198 		return -EINVAL;
1199 
1200 	ret = venus_helper_get_bufreq(inst, HFI_BUFFER_OUTPUT, &bufreq);
1201 	if (ret)
1202 		return ret;
1203 
1204 	if (inst->num_output_bufs < bufreq.count_actual ||
1205 	    inst->num_output_bufs < HFI_BUFREQ_COUNT_MIN(&bufreq, ver))
1206 		return -EINVAL;
1207 
1208 	ret = venus_helper_get_bufreq(inst, HFI_BUFFER_INPUT, &bufreq);
1209 	if (ret)
1210 		return ret;
1211 
1212 	if (inst->num_input_bufs < bufreq.count_actual ||
1213 	    inst->num_input_bufs < HFI_BUFREQ_COUNT_MIN(&bufreq, ver))
1214 		return -EINVAL;
1215 
1216 	return 0;
1217 }
1218 
1219 static int venc_start_streaming(struct vb2_queue *q, unsigned int count)
1220 {
1221 	struct venus_inst *inst = vb2_get_drv_priv(q);
1222 	int ret;
1223 
1224 	mutex_lock(&inst->lock);
1225 
1226 	if (q->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE)
1227 		inst->streamon_out = 1;
1228 	else
1229 		inst->streamon_cap = 1;
1230 
1231 	if (!(inst->streamon_out & inst->streamon_cap)) {
1232 		mutex_unlock(&inst->lock);
1233 		return 0;
1234 	}
1235 
1236 	venus_helper_init_instance(inst);
1237 
1238 	inst->sequence_cap = 0;
1239 	inst->sequence_out = 0;
1240 
1241 	ret = venc_pm_get(inst);
1242 	if (ret)
1243 		goto error;
1244 
1245 	ret = venus_pm_acquire_core(inst);
1246 	if (ret)
1247 		goto put_power;
1248 
1249 	ret = venc_pm_put(inst, true);
1250 	if (ret)
1251 		goto error;
1252 
1253 	ret = venc_set_properties(inst);
1254 	if (ret)
1255 		goto error;
1256 
1257 	ret = venc_verify_conf(inst);
1258 	if (ret)
1259 		goto error;
1260 
1261 	ret = venus_helper_set_num_bufs(inst, inst->num_input_bufs,
1262 					inst->num_output_bufs, 0);
1263 	if (ret)
1264 		goto error;
1265 
1266 	ret = venus_helper_vb2_start_streaming(inst);
1267 	if (ret)
1268 		goto error;
1269 
1270 	inst->enc_state = VENUS_ENC_STATE_ENCODING;
1271 
1272 	mutex_unlock(&inst->lock);
1273 
1274 	return 0;
1275 
1276 put_power:
1277 	venc_pm_put(inst, false);
1278 error:
1279 	venus_helper_buffers_done(inst, q->type, VB2_BUF_STATE_QUEUED);
1280 	if (q->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE)
1281 		inst->streamon_out = 0;
1282 	else
1283 		inst->streamon_cap = 0;
1284 	mutex_unlock(&inst->lock);
1285 	return ret;
1286 }
1287 
1288 static void venc_vb2_buf_queue(struct vb2_buffer *vb)
1289 {
1290 	struct venus_inst *inst = vb2_get_drv_priv(vb->vb2_queue);
1291 	struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
1292 
1293 	venc_pm_get_put(inst);
1294 
1295 	mutex_lock(&inst->lock);
1296 
1297 	if (inst->enc_state == VENUS_ENC_STATE_STOPPED) {
1298 		vbuf->sequence = inst->sequence_cap++;
1299 		vbuf->field = V4L2_FIELD_NONE;
1300 		vb2_set_plane_payload(vb, 0, 0);
1301 		v4l2_m2m_buf_done(vbuf, VB2_BUF_STATE_DONE);
1302 		mutex_unlock(&inst->lock);
1303 		return;
1304 	}
1305 
1306 	venus_helper_vb2_buf_queue(vb);
1307 	mutex_unlock(&inst->lock);
1308 }
1309 
1310 static const struct vb2_ops venc_vb2_ops = {
1311 	.queue_setup = venc_queue_setup,
1312 	.buf_init = venc_buf_init,
1313 	.buf_cleanup = venc_buf_cleanup,
1314 	.buf_prepare = venus_helper_vb2_buf_prepare,
1315 	.start_streaming = venc_start_streaming,
1316 	.stop_streaming = venus_helper_vb2_stop_streaming,
1317 	.buf_queue = venc_vb2_buf_queue,
1318 };
1319 
1320 static void venc_buf_done(struct venus_inst *inst, unsigned int buf_type,
1321 			  u32 tag, u32 bytesused, u32 data_offset, u32 flags,
1322 			  u32 hfi_flags, u64 timestamp_us)
1323 {
1324 	struct vb2_v4l2_buffer *vbuf;
1325 	struct vb2_buffer *vb;
1326 	unsigned int type;
1327 
1328 	venc_pm_touch(inst);
1329 
1330 	if (buf_type == HFI_BUFFER_INPUT)
1331 		type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
1332 	else
1333 		type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
1334 
1335 	vbuf = venus_helper_find_buf(inst, type, tag);
1336 	if (!vbuf)
1337 		return;
1338 
1339 	vbuf->flags = flags;
1340 
1341 	if (type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
1342 		vb = &vbuf->vb2_buf;
1343 		vb2_set_plane_payload(vb, 0, bytesused + data_offset);
1344 		vb->planes[0].data_offset = data_offset;
1345 		vb->timestamp = timestamp_us * NSEC_PER_USEC;
1346 		vbuf->sequence = inst->sequence_cap++;
1347 		if ((vbuf->flags & V4L2_BUF_FLAG_LAST) &&
1348 		    inst->enc_state == VENUS_ENC_STATE_DRAIN) {
1349 			inst->enc_state = VENUS_ENC_STATE_STOPPED;
1350 		}
1351 	} else {
1352 		vbuf->sequence = inst->sequence_out++;
1353 	}
1354 
1355 	v4l2_m2m_buf_done(vbuf, VB2_BUF_STATE_DONE);
1356 }
1357 
1358 static void venc_event_notify(struct venus_inst *inst, u32 event,
1359 			      struct hfi_event_data *data)
1360 {
1361 	struct device *dev = inst->core->dev_enc;
1362 
1363 	venc_pm_touch(inst);
1364 
1365 	if (event == EVT_SESSION_ERROR) {
1366 		inst->session_error = true;
1367 		venus_helper_vb2_queue_error(inst);
1368 		dev_err(dev, "enc: event session error %x\n", inst->error);
1369 	}
1370 }
1371 
1372 static const struct hfi_inst_ops venc_hfi_ops = {
1373 	.buf_done = venc_buf_done,
1374 	.event_notify = venc_event_notify,
1375 };
1376 
1377 static const struct v4l2_m2m_ops venc_m2m_ops = {
1378 	.device_run = venus_helper_m2m_device_run,
1379 	.job_abort = venus_helper_m2m_job_abort,
1380 };
1381 
1382 static int m2m_queue_init(void *priv, struct vb2_queue *src_vq,
1383 			  struct vb2_queue *dst_vq)
1384 {
1385 	struct venus_inst *inst = priv;
1386 	int ret;
1387 
1388 	src_vq->type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
1389 	src_vq->io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF;
1390 	src_vq->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_COPY;
1391 	src_vq->ops = &venc_vb2_ops;
1392 	src_vq->mem_ops = &vb2_dma_contig_memops;
1393 	src_vq->drv_priv = inst;
1394 	src_vq->buf_struct_size = sizeof(struct venus_buffer);
1395 	src_vq->allow_zero_bytesused = 1;
1396 	src_vq->min_buffers_needed = 1;
1397 	src_vq->dev = inst->core->dev;
1398 	if (inst->core->res->hfi_version == HFI_VERSION_1XX)
1399 		src_vq->bidirectional = 1;
1400 	ret = vb2_queue_init(src_vq);
1401 	if (ret)
1402 		return ret;
1403 
1404 	dst_vq->type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
1405 	dst_vq->io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF;
1406 	dst_vq->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_COPY;
1407 	dst_vq->ops = &venc_vb2_ops;
1408 	dst_vq->mem_ops = &vb2_dma_contig_memops;
1409 	dst_vq->drv_priv = inst;
1410 	dst_vq->buf_struct_size = sizeof(struct venus_buffer);
1411 	dst_vq->allow_zero_bytesused = 1;
1412 	dst_vq->min_buffers_needed = 1;
1413 	dst_vq->dev = inst->core->dev;
1414 	return vb2_queue_init(dst_vq);
1415 }
1416 
1417 static void venc_inst_init(struct venus_inst *inst)
1418 {
1419 	inst->fmt_cap = &venc_formats[3];
1420 	inst->fmt_out = &venc_formats[0];
1421 	inst->width = 1280;
1422 	inst->height = ALIGN(720, 32);
1423 	inst->out_width = 1280;
1424 	inst->out_height = 720;
1425 	inst->fps = 15;
1426 	inst->timeperframe.numerator = 1;
1427 	inst->timeperframe.denominator = 15;
1428 	inst->hfi_codec = HFI_VIDEO_CODEC_H264;
1429 }
1430 
1431 static int venc_open(struct file *file)
1432 {
1433 	struct venus_core *core = video_drvdata(file);
1434 	struct venus_inst *inst;
1435 	int ret;
1436 
1437 	inst = kzalloc(sizeof(*inst), GFP_KERNEL);
1438 	if (!inst)
1439 		return -ENOMEM;
1440 
1441 	INIT_LIST_HEAD(&inst->dpbbufs);
1442 	INIT_LIST_HEAD(&inst->registeredbufs);
1443 	INIT_LIST_HEAD(&inst->internalbufs);
1444 	INIT_LIST_HEAD(&inst->list);
1445 	mutex_init(&inst->lock);
1446 
1447 	inst->core = core;
1448 	inst->session_type = VIDC_SESSION_TYPE_ENC;
1449 	inst->clk_data.core_id = VIDC_CORE_ID_DEFAULT;
1450 	inst->core_acquired = false;
1451 	inst->nonblock = file->f_flags & O_NONBLOCK;
1452 
1453 	if (inst->enc_state == VENUS_ENC_STATE_DEINIT)
1454 		inst->enc_state = VENUS_ENC_STATE_INIT;
1455 
1456 	venus_helper_init_instance(inst);
1457 
1458 	ret = venc_ctrl_init(inst);
1459 	if (ret)
1460 		goto err_free;
1461 
1462 	ret = hfi_session_create(inst, &venc_hfi_ops);
1463 	if (ret)
1464 		goto err_ctrl_deinit;
1465 
1466 	venc_inst_init(inst);
1467 
1468 	/*
1469 	 * create m2m device for every instance, the m2m context scheduling
1470 	 * is made by firmware side so we do not need to care about.
1471 	 */
1472 	inst->m2m_dev = v4l2_m2m_init(&venc_m2m_ops);
1473 	if (IS_ERR(inst->m2m_dev)) {
1474 		ret = PTR_ERR(inst->m2m_dev);
1475 		goto err_session_destroy;
1476 	}
1477 
1478 	inst->m2m_ctx = v4l2_m2m_ctx_init(inst->m2m_dev, inst, m2m_queue_init);
1479 	if (IS_ERR(inst->m2m_ctx)) {
1480 		ret = PTR_ERR(inst->m2m_ctx);
1481 		goto err_m2m_release;
1482 	}
1483 
1484 	v4l2_fh_init(&inst->fh, core->vdev_enc);
1485 
1486 	inst->fh.ctrl_handler = &inst->ctrl_handler;
1487 	v4l2_fh_add(&inst->fh);
1488 	inst->fh.m2m_ctx = inst->m2m_ctx;
1489 	file->private_data = &inst->fh;
1490 
1491 	return 0;
1492 
1493 err_m2m_release:
1494 	v4l2_m2m_release(inst->m2m_dev);
1495 err_session_destroy:
1496 	hfi_session_destroy(inst);
1497 err_ctrl_deinit:
1498 	venc_ctrl_deinit(inst);
1499 err_free:
1500 	kfree(inst);
1501 	return ret;
1502 }
1503 
1504 static int venc_close(struct file *file)
1505 {
1506 	struct venus_inst *inst = to_inst(file);
1507 
1508 	venc_pm_get(inst);
1509 
1510 	v4l2_m2m_ctx_release(inst->m2m_ctx);
1511 	v4l2_m2m_release(inst->m2m_dev);
1512 	venc_ctrl_deinit(inst);
1513 	hfi_session_destroy(inst);
1514 	mutex_destroy(&inst->lock);
1515 	v4l2_fh_del(&inst->fh);
1516 	v4l2_fh_exit(&inst->fh);
1517 
1518 	inst->enc_state = VENUS_ENC_STATE_DEINIT;
1519 
1520 	venc_pm_put(inst, false);
1521 
1522 	kfree(inst);
1523 	return 0;
1524 }
1525 
1526 static const struct v4l2_file_operations venc_fops = {
1527 	.owner = THIS_MODULE,
1528 	.open = venc_open,
1529 	.release = venc_close,
1530 	.unlocked_ioctl = video_ioctl2,
1531 	.poll = v4l2_m2m_fop_poll,
1532 	.mmap = v4l2_m2m_fop_mmap,
1533 };
1534 
1535 static int venc_probe(struct platform_device *pdev)
1536 {
1537 	struct device *dev = &pdev->dev;
1538 	struct video_device *vdev;
1539 	struct venus_core *core;
1540 	int ret;
1541 
1542 	if (!dev->parent)
1543 		return -EPROBE_DEFER;
1544 
1545 	core = dev_get_drvdata(dev->parent);
1546 	if (!core)
1547 		return -EPROBE_DEFER;
1548 
1549 	platform_set_drvdata(pdev, core);
1550 
1551 	if (core->pm_ops->venc_get) {
1552 		ret = core->pm_ops->venc_get(dev);
1553 		if (ret)
1554 			return ret;
1555 	}
1556 
1557 	vdev = video_device_alloc();
1558 	if (!vdev)
1559 		return -ENOMEM;
1560 
1561 	strscpy(vdev->name, "qcom-venus-encoder", sizeof(vdev->name));
1562 	vdev->release = video_device_release;
1563 	vdev->fops = &venc_fops;
1564 	vdev->ioctl_ops = &venc_ioctl_ops;
1565 	vdev->vfl_dir = VFL_DIR_M2M;
1566 	vdev->v4l2_dev = &core->v4l2_dev;
1567 	vdev->device_caps = V4L2_CAP_VIDEO_M2M_MPLANE | V4L2_CAP_STREAMING;
1568 
1569 	ret = video_register_device(vdev, VFL_TYPE_VIDEO, -1);
1570 	if (ret)
1571 		goto err_vdev_release;
1572 
1573 	core->vdev_enc = vdev;
1574 	core->dev_enc = dev;
1575 
1576 	video_set_drvdata(vdev, core);
1577 	pm_runtime_set_autosuspend_delay(dev, 2000);
1578 	pm_runtime_use_autosuspend(dev);
1579 	pm_runtime_enable(dev);
1580 
1581 	return 0;
1582 
1583 err_vdev_release:
1584 	video_device_release(vdev);
1585 	return ret;
1586 }
1587 
1588 static void venc_remove(struct platform_device *pdev)
1589 {
1590 	struct venus_core *core = dev_get_drvdata(pdev->dev.parent);
1591 
1592 	video_unregister_device(core->vdev_enc);
1593 	pm_runtime_disable(core->dev_enc);
1594 
1595 	if (core->pm_ops->venc_put)
1596 		core->pm_ops->venc_put(core->dev_enc);
1597 }
1598 
1599 static __maybe_unused int venc_runtime_suspend(struct device *dev)
1600 {
1601 	struct venus_core *core = dev_get_drvdata(dev);
1602 	const struct venus_pm_ops *pm_ops = core->pm_ops;
1603 	int ret = 0;
1604 
1605 	if (pm_ops->venc_power)
1606 		ret = pm_ops->venc_power(dev, POWER_OFF);
1607 
1608 	return ret;
1609 }
1610 
1611 static __maybe_unused int venc_runtime_resume(struct device *dev)
1612 {
1613 	struct venus_core *core = dev_get_drvdata(dev);
1614 	const struct venus_pm_ops *pm_ops = core->pm_ops;
1615 	int ret = 0;
1616 
1617 	if (pm_ops->venc_power)
1618 		ret = pm_ops->venc_power(dev, POWER_ON);
1619 
1620 	return ret;
1621 }
1622 
1623 static const struct dev_pm_ops venc_pm_ops = {
1624 	SET_SYSTEM_SLEEP_PM_OPS(pm_runtime_force_suspend,
1625 				pm_runtime_force_resume)
1626 	SET_RUNTIME_PM_OPS(venc_runtime_suspend, venc_runtime_resume, NULL)
1627 };
1628 
1629 static const struct of_device_id venc_dt_match[] = {
1630 	{ .compatible = "venus-encoder" },
1631 	{ }
1632 };
1633 MODULE_DEVICE_TABLE(of, venc_dt_match);
1634 
1635 static struct platform_driver qcom_venus_enc_driver = {
1636 	.probe = venc_probe,
1637 	.remove_new = venc_remove,
1638 	.driver = {
1639 		.name = "qcom-venus-encoder",
1640 		.of_match_table = venc_dt_match,
1641 		.pm = &venc_pm_ops,
1642 	},
1643 };
1644 module_platform_driver(qcom_venus_enc_driver);
1645 
1646 MODULE_ALIAS("platform:qcom-venus-encoder");
1647 MODULE_DESCRIPTION("Qualcomm Venus video encoder driver");
1648 MODULE_LICENSE("GPL v2");
1649