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_CAPTURE_MPLANE &&
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_CAPTURE_MPLANE &&
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 const struct v4l2_ioctl_ops venc_ioctl_ops = {
524 	.vidioc_querycap = venc_querycap,
525 	.vidioc_enum_fmt_vid_cap = venc_enum_fmt,
526 	.vidioc_enum_fmt_vid_out = venc_enum_fmt,
527 	.vidioc_s_fmt_vid_cap_mplane = venc_s_fmt,
528 	.vidioc_s_fmt_vid_out_mplane = venc_s_fmt,
529 	.vidioc_g_fmt_vid_cap_mplane = venc_g_fmt,
530 	.vidioc_g_fmt_vid_out_mplane = venc_g_fmt,
531 	.vidioc_try_fmt_vid_cap_mplane = venc_try_fmt,
532 	.vidioc_try_fmt_vid_out_mplane = venc_try_fmt,
533 	.vidioc_g_selection = venc_g_selection,
534 	.vidioc_s_selection = venc_s_selection,
535 	.vidioc_reqbufs = v4l2_m2m_ioctl_reqbufs,
536 	.vidioc_querybuf = v4l2_m2m_ioctl_querybuf,
537 	.vidioc_create_bufs = v4l2_m2m_ioctl_create_bufs,
538 	.vidioc_prepare_buf = v4l2_m2m_ioctl_prepare_buf,
539 	.vidioc_qbuf = v4l2_m2m_ioctl_qbuf,
540 	.vidioc_expbuf = v4l2_m2m_ioctl_expbuf,
541 	.vidioc_dqbuf = v4l2_m2m_ioctl_dqbuf,
542 	.vidioc_streamon = v4l2_m2m_ioctl_streamon,
543 	.vidioc_streamoff = v4l2_m2m_ioctl_streamoff,
544 	.vidioc_s_parm = venc_s_parm,
545 	.vidioc_g_parm = venc_g_parm,
546 	.vidioc_enum_framesizes = venc_enum_framesizes,
547 	.vidioc_enum_frameintervals = venc_enum_frameintervals,
548 	.vidioc_subscribe_event = venc_subscribe_event,
549 	.vidioc_unsubscribe_event = v4l2_event_unsubscribe,
550 	.vidioc_try_encoder_cmd = v4l2_m2m_ioctl_try_encoder_cmd,
551 };
552 
553 static int venc_pm_get(struct venus_inst *inst)
554 {
555 	struct venus_core *core = inst->core;
556 	struct device *dev = core->dev_enc;
557 	int ret;
558 
559 	mutex_lock(&core->pm_lock);
560 	ret = pm_runtime_resume_and_get(dev);
561 	mutex_unlock(&core->pm_lock);
562 
563 	return ret < 0 ? ret : 0;
564 }
565 
566 static int venc_pm_put(struct venus_inst *inst, bool autosuspend)
567 {
568 	struct venus_core *core = inst->core;
569 	struct device *dev = core->dev_enc;
570 	int ret;
571 
572 	mutex_lock(&core->pm_lock);
573 
574 	if (autosuspend)
575 		ret = pm_runtime_put_autosuspend(dev);
576 	else
577 		ret = pm_runtime_put_sync(dev);
578 
579 	mutex_unlock(&core->pm_lock);
580 
581 	return ret < 0 ? ret : 0;
582 }
583 
584 static int venc_pm_get_put(struct venus_inst *inst)
585 {
586 	struct venus_core *core = inst->core;
587 	struct device *dev = core->dev_enc;
588 	int ret = 0;
589 
590 	mutex_lock(&core->pm_lock);
591 
592 	if (pm_runtime_suspended(dev)) {
593 		ret = pm_runtime_resume_and_get(dev);
594 		if (ret < 0)
595 			goto error;
596 
597 		ret = pm_runtime_put_autosuspend(dev);
598 	}
599 
600 error:
601 	mutex_unlock(&core->pm_lock);
602 
603 	return ret < 0 ? ret : 0;
604 }
605 
606 static void venc_pm_touch(struct venus_inst *inst)
607 {
608 	pm_runtime_mark_last_busy(inst->core->dev_enc);
609 }
610 
611 static int venc_set_properties(struct venus_inst *inst)
612 {
613 	struct venc_controls *ctr = &inst->controls.enc;
614 	struct hfi_intra_period intra_period;
615 	struct hfi_framerate frate;
616 	struct hfi_bitrate brate;
617 	struct hfi_idr_period idrp;
618 	struct hfi_quantization quant;
619 	struct hfi_quantization_range quant_range;
620 	struct hfi_enable en;
621 	struct hfi_ltr_mode ltr_mode;
622 	struct hfi_intra_refresh intra_refresh = {};
623 	u32 ptype, rate_control, bitrate;
624 	u32 profile, level;
625 	int ret;
626 
627 	ret = venus_helper_set_work_mode(inst);
628 	if (ret)
629 		return ret;
630 
631 	ptype = HFI_PROPERTY_CONFIG_FRAME_RATE;
632 	frate.buffer_type = HFI_BUFFER_OUTPUT;
633 	frate.framerate = inst->fps * (1 << 16);
634 
635 	ret = hfi_session_set_property(inst, ptype, &frate);
636 	if (ret)
637 		return ret;
638 
639 	if (inst->fmt_cap->pixfmt == V4L2_PIX_FMT_H264) {
640 		struct hfi_h264_vui_timing_info info;
641 		struct hfi_h264_entropy_control entropy;
642 		struct hfi_h264_db_control deblock;
643 		struct hfi_h264_8x8_transform h264_transform;
644 
645 		ptype = HFI_PROPERTY_PARAM_VENC_H264_VUI_TIMING_INFO;
646 		info.enable = 1;
647 		info.fixed_framerate = 1;
648 		info.time_scale = NSEC_PER_SEC;
649 
650 		ret = hfi_session_set_property(inst, ptype, &info);
651 		if (ret)
652 			return ret;
653 
654 		ptype = HFI_PROPERTY_PARAM_VENC_H264_ENTROPY_CONTROL;
655 		entropy.entropy_mode = venc_v4l2_to_hfi(
656 					  V4L2_CID_MPEG_VIDEO_H264_ENTROPY_MODE,
657 					  ctr->h264_entropy_mode);
658 		entropy.cabac_model = HFI_H264_CABAC_MODEL_0;
659 
660 		ret = hfi_session_set_property(inst, ptype, &entropy);
661 		if (ret)
662 			return ret;
663 
664 		ptype = HFI_PROPERTY_PARAM_VENC_H264_DEBLOCK_CONTROL;
665 		deblock.mode = venc_v4l2_to_hfi(
666 				      V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_MODE,
667 				      ctr->h264_loop_filter_mode);
668 		deblock.slice_alpha_offset = ctr->h264_loop_filter_alpha;
669 		deblock.slice_beta_offset = ctr->h264_loop_filter_beta;
670 
671 		ret = hfi_session_set_property(inst, ptype, &deblock);
672 		if (ret)
673 			return ret;
674 
675 		ptype = HFI_PROPERTY_PARAM_VENC_H264_TRANSFORM_8X8;
676 		h264_transform.enable_type = 0;
677 		if (ctr->profile.h264 == V4L2_MPEG_VIDEO_H264_PROFILE_HIGH ||
678 		    ctr->profile.h264 == V4L2_MPEG_VIDEO_H264_PROFILE_CONSTRAINED_HIGH)
679 			h264_transform.enable_type = ctr->h264_8x8_transform;
680 
681 		ret = hfi_session_set_property(inst, ptype, &h264_transform);
682 		if (ret)
683 			return ret;
684 
685 	}
686 
687 	if (inst->fmt_cap->pixfmt == V4L2_PIX_FMT_H264 ||
688 	    inst->fmt_cap->pixfmt == V4L2_PIX_FMT_HEVC) {
689 		/* IDR periodicity, n:
690 		 * n = 0 - only the first I-frame is IDR frame
691 		 * n = 1 - all I-frames will be IDR frames
692 		 * n > 1 - every n-th I-frame will be IDR frame
693 		 */
694 		ptype = HFI_PROPERTY_CONFIG_VENC_IDR_PERIOD;
695 		idrp.idr_period = 0;
696 		ret = hfi_session_set_property(inst, ptype, &idrp);
697 		if (ret)
698 			return ret;
699 	}
700 
701 	if (inst->fmt_cap->pixfmt == V4L2_PIX_FMT_HEVC) {
702 		struct hfi_hdr10_pq_sei hdr10;
703 		unsigned int c;
704 
705 		ptype = HFI_PROPERTY_PARAM_VENC_HDR10_PQ_SEI;
706 
707 		for (c = 0; c < 3; c++) {
708 			hdr10.mastering.display_primaries_x[c] =
709 				ctr->mastering.display_primaries_x[c];
710 			hdr10.mastering.display_primaries_y[c] =
711 				ctr->mastering.display_primaries_y[c];
712 		}
713 
714 		hdr10.mastering.white_point_x = ctr->mastering.white_point_x;
715 		hdr10.mastering.white_point_y = ctr->mastering.white_point_y;
716 		hdr10.mastering.max_display_mastering_luminance =
717 			ctr->mastering.max_display_mastering_luminance;
718 		hdr10.mastering.min_display_mastering_luminance =
719 			ctr->mastering.min_display_mastering_luminance;
720 
721 		hdr10.cll.max_content_light = ctr->cll.max_content_light_level;
722 		hdr10.cll.max_pic_average_light =
723 			ctr->cll.max_pic_average_light_level;
724 
725 		ret = hfi_session_set_property(inst, ptype, &hdr10);
726 		if (ret)
727 			return ret;
728 	}
729 
730 	if (ctr->num_b_frames) {
731 		u32 max_num_b_frames = NUM_B_FRAMES_MAX;
732 
733 		ptype = HFI_PROPERTY_PARAM_VENC_MAX_NUM_B_FRAMES;
734 		ret = hfi_session_set_property(inst, ptype, &max_num_b_frames);
735 		if (ret)
736 			return ret;
737 	}
738 
739 	ptype = HFI_PROPERTY_CONFIG_VENC_INTRA_PERIOD;
740 	intra_period.pframes = ctr->num_p_frames;
741 	intra_period.bframes = ctr->num_b_frames;
742 
743 	ret = hfi_session_set_property(inst, ptype, &intra_period);
744 	if (ret)
745 		return ret;
746 
747 	if (!ctr->rc_enable)
748 		rate_control = HFI_RATE_CONTROL_OFF;
749 	else if (ctr->bitrate_mode == V4L2_MPEG_VIDEO_BITRATE_MODE_VBR)
750 		rate_control = ctr->frame_skip_mode ? HFI_RATE_CONTROL_VBR_VFR :
751 						      HFI_RATE_CONTROL_VBR_CFR;
752 	else if (ctr->bitrate_mode == V4L2_MPEG_VIDEO_BITRATE_MODE_CBR)
753 		rate_control = ctr->frame_skip_mode ? HFI_RATE_CONTROL_CBR_VFR :
754 						      HFI_RATE_CONTROL_CBR_CFR;
755 	else if (ctr->bitrate_mode == V4L2_MPEG_VIDEO_BITRATE_MODE_CQ)
756 		rate_control = HFI_RATE_CONTROL_CQ;
757 
758 	ptype = HFI_PROPERTY_PARAM_VENC_RATE_CONTROL;
759 	ret = hfi_session_set_property(inst, ptype, &rate_control);
760 	if (ret)
761 		return ret;
762 
763 	if (rate_control == HFI_RATE_CONTROL_CQ && ctr->const_quality) {
764 		struct hfi_heic_frame_quality quality = {};
765 
766 		ptype = HFI_PROPERTY_CONFIG_HEIC_FRAME_QUALITY;
767 		quality.frame_quality = ctr->const_quality;
768 		ret = hfi_session_set_property(inst, ptype, &quality);
769 		if (ret)
770 			return ret;
771 	}
772 
773 	if (!ctr->bitrate)
774 		bitrate = 64000;
775 	else
776 		bitrate = ctr->bitrate;
777 
778 	ptype = HFI_PROPERTY_CONFIG_VENC_TARGET_BITRATE;
779 	brate.bitrate = bitrate;
780 	brate.layer_id = 0;
781 
782 	ret = hfi_session_set_property(inst, ptype, &brate);
783 	if (ret)
784 		return ret;
785 
786 	if (inst->fmt_cap->pixfmt == V4L2_PIX_FMT_H264 ||
787 	    inst->fmt_cap->pixfmt == V4L2_PIX_FMT_HEVC) {
788 		ptype = HFI_PROPERTY_CONFIG_VENC_SYNC_FRAME_SEQUENCE_HEADER;
789 		if (ctr->header_mode == V4L2_MPEG_VIDEO_HEADER_MODE_SEPARATE)
790 			en.enable = 0;
791 		else
792 			en.enable = 1;
793 
794 		ret = hfi_session_set_property(inst, ptype, &en);
795 		if (ret)
796 			return ret;
797 	}
798 
799 	if (!ctr->bitrate_peak)
800 		bitrate *= 2;
801 	else
802 		bitrate = ctr->bitrate_peak;
803 
804 	ptype = HFI_PROPERTY_CONFIG_VENC_MAX_BITRATE;
805 	brate.bitrate = bitrate;
806 	brate.layer_id = 0;
807 
808 	ret = hfi_session_set_property(inst, ptype, &brate);
809 	if (ret)
810 		return ret;
811 
812 	ptype = HFI_PROPERTY_PARAM_VENC_SESSION_QP;
813 	if (inst->fmt_cap->pixfmt == V4L2_PIX_FMT_HEVC) {
814 		quant.qp_i = ctr->hevc_i_qp;
815 		quant.qp_p = ctr->hevc_p_qp;
816 		quant.qp_b = ctr->hevc_b_qp;
817 	} else {
818 		quant.qp_i = ctr->h264_i_qp;
819 		quant.qp_p = ctr->h264_p_qp;
820 		quant.qp_b = ctr->h264_b_qp;
821 	}
822 	quant.layer_id = 0;
823 	ret = hfi_session_set_property(inst, ptype, &quant);
824 	if (ret)
825 		return ret;
826 
827 	ptype = HFI_PROPERTY_PARAM_VENC_SESSION_QP_RANGE;
828 	if (inst->fmt_cap->pixfmt == V4L2_PIX_FMT_HEVC) {
829 		quant_range.min_qp = ctr->hevc_min_qp;
830 		quant_range.max_qp = ctr->hevc_max_qp;
831 	} else {
832 		quant_range.min_qp = ctr->h264_min_qp;
833 		quant_range.max_qp = ctr->h264_max_qp;
834 	}
835 	quant_range.layer_id = 0;
836 	ret = hfi_session_set_property(inst, ptype, &quant_range);
837 	if (ret)
838 		return ret;
839 
840 	ptype = HFI_PROPERTY_PARAM_VENC_LTRMODE;
841 	ltr_mode.ltr_count = ctr->ltr_count;
842 	ltr_mode.ltr_mode = HFI_LTR_MODE_MANUAL;
843 	ltr_mode.trust_mode = 1;
844 	ret = hfi_session_set_property(inst, ptype, &ltr_mode);
845 	if (ret)
846 		return ret;
847 
848 	switch (inst->hfi_codec) {
849 	case HFI_VIDEO_CODEC_H264:
850 		profile = ctr->profile.h264;
851 		level = ctr->level.h264;
852 		break;
853 	case HFI_VIDEO_CODEC_MPEG4:
854 		profile = ctr->profile.mpeg4;
855 		level = ctr->level.mpeg4;
856 		break;
857 	case HFI_VIDEO_CODEC_VP8:
858 		profile = ctr->profile.vp8;
859 		level = 0;
860 		break;
861 	case HFI_VIDEO_CODEC_VP9:
862 		profile = ctr->profile.vp9;
863 		level = ctr->level.vp9;
864 		break;
865 	case HFI_VIDEO_CODEC_HEVC:
866 		profile = ctr->profile.hevc;
867 		level = ctr->level.hevc;
868 		break;
869 	case HFI_VIDEO_CODEC_MPEG2:
870 	default:
871 		profile = 0;
872 		level = 0;
873 		break;
874 	}
875 
876 	ret = venus_helper_set_profile_level(inst, profile, level);
877 	if (ret)
878 		return ret;
879 
880 	if (inst->fmt_cap->pixfmt == V4L2_PIX_FMT_H264 ||
881 	    inst->fmt_cap->pixfmt == V4L2_PIX_FMT_HEVC) {
882 		struct hfi_enable en = {};
883 
884 		ptype = HFI_PROPERTY_PARAM_VENC_H264_GENERATE_AUDNAL;
885 
886 		if (ctr->aud_enable)
887 			en.enable = 1;
888 
889 		ret = hfi_session_set_property(inst, ptype, &en);
890 	}
891 
892 	if ((inst->fmt_cap->pixfmt == V4L2_PIX_FMT_H264 ||
893 	     inst->fmt_cap->pixfmt == V4L2_PIX_FMT_HEVC) &&
894 	    (rate_control == HFI_RATE_CONTROL_CBR_VFR ||
895 	     rate_control == HFI_RATE_CONTROL_CBR_CFR)) {
896 		intra_refresh.mode = HFI_INTRA_REFRESH_NONE;
897 		intra_refresh.cir_mbs = 0;
898 
899 		if (ctr->intra_refresh_period) {
900 			u32 mbs;
901 
902 			mbs = ALIGN(inst->width, 16) * ALIGN(inst->height, 16);
903 			mbs /= 16 * 16;
904 			if (mbs % ctr->intra_refresh_period)
905 				mbs++;
906 			mbs /= ctr->intra_refresh_period;
907 
908 			intra_refresh.cir_mbs = mbs;
909 			if (ctr->intra_refresh_type ==
910 			    V4L2_CID_MPEG_VIDEO_INTRA_REFRESH_PERIOD_TYPE_CYCLIC)
911 				intra_refresh.mode = HFI_INTRA_REFRESH_CYCLIC;
912 			else
913 				intra_refresh.mode = HFI_INTRA_REFRESH_RANDOM;
914 		}
915 
916 		ptype = HFI_PROPERTY_PARAM_VENC_INTRA_REFRESH;
917 
918 		ret = hfi_session_set_property(inst, ptype, &intra_refresh);
919 		if (ret)
920 			return ret;
921 	}
922 
923 	return 0;
924 }
925 
926 static int venc_init_session(struct venus_inst *inst)
927 {
928 	int ret;
929 
930 	ret = venus_helper_session_init(inst);
931 	if (ret == -EALREADY)
932 		return 0;
933 	else if (ret)
934 		return ret;
935 
936 	ret = venus_helper_set_stride(inst, inst->out_width,
937 				      inst->out_height);
938 	if (ret)
939 		goto deinit;
940 
941 	ret = venus_helper_set_input_resolution(inst, inst->width,
942 						inst->height);
943 	if (ret)
944 		goto deinit;
945 
946 	ret = venus_helper_set_output_resolution(inst, inst->width,
947 						 inst->height,
948 						 HFI_BUFFER_OUTPUT);
949 	if (ret)
950 		goto deinit;
951 
952 	ret = venus_helper_set_color_format(inst, inst->fmt_out->pixfmt);
953 	if (ret)
954 		goto deinit;
955 
956 	ret = venc_set_properties(inst);
957 	if (ret)
958 		goto deinit;
959 
960 	return 0;
961 deinit:
962 	hfi_session_deinit(inst);
963 	return ret;
964 }
965 
966 static int venc_out_num_buffers(struct venus_inst *inst, unsigned int *num)
967 {
968 	struct hfi_buffer_requirements bufreq;
969 	int ret;
970 
971 	ret = venus_helper_get_bufreq(inst, HFI_BUFFER_INPUT, &bufreq);
972 	if (ret)
973 		return ret;
974 
975 	*num = bufreq.count_actual;
976 
977 	return 0;
978 }
979 
980 static int venc_queue_setup(struct vb2_queue *q,
981 			    unsigned int *num_buffers, unsigned int *num_planes,
982 			    unsigned int sizes[], struct device *alloc_devs[])
983 {
984 	struct venus_inst *inst = vb2_get_drv_priv(q);
985 	struct venus_core *core = inst->core;
986 	unsigned int num, min = 4;
987 	int ret;
988 
989 	if (*num_planes) {
990 		if (q->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE &&
991 		    *num_planes != inst->fmt_out->num_planes)
992 			return -EINVAL;
993 
994 		if (q->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE &&
995 		    *num_planes != inst->fmt_cap->num_planes)
996 			return -EINVAL;
997 
998 		if (q->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE &&
999 		    sizes[0] < inst->input_buf_size)
1000 			return -EINVAL;
1001 
1002 		if (q->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE &&
1003 		    sizes[0] < inst->output_buf_size)
1004 			return -EINVAL;
1005 
1006 		return 0;
1007 	}
1008 
1009 	if (test_bit(0, &core->sys_error)) {
1010 		if (inst->nonblock)
1011 			return -EAGAIN;
1012 
1013 		ret = wait_event_interruptible(core->sys_err_done,
1014 					       !test_bit(0, &core->sys_error));
1015 		if (ret)
1016 			return ret;
1017 	}
1018 
1019 	ret = venc_pm_get(inst);
1020 	if (ret)
1021 		return ret;
1022 
1023 	mutex_lock(&inst->lock);
1024 	ret = venc_init_session(inst);
1025 	mutex_unlock(&inst->lock);
1026 
1027 	if (ret)
1028 		goto put_power;
1029 
1030 	ret = venc_pm_put(inst, false);
1031 	if (ret)
1032 		return ret;
1033 
1034 	switch (q->type) {
1035 	case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:
1036 		*num_planes = inst->fmt_out->num_planes;
1037 
1038 		ret = venc_out_num_buffers(inst, &num);
1039 		if (ret)
1040 			break;
1041 
1042 		num = max(num, min);
1043 		*num_buffers = max(*num_buffers, num);
1044 		inst->num_input_bufs = *num_buffers;
1045 
1046 		sizes[0] = venus_helper_get_framesz(inst->fmt_out->pixfmt,
1047 						    inst->out_width,
1048 						    inst->out_height);
1049 		inst->input_buf_size = sizes[0];
1050 		break;
1051 	case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
1052 		*num_planes = inst->fmt_cap->num_planes;
1053 		*num_buffers = max(*num_buffers, min);
1054 		inst->num_output_bufs = *num_buffers;
1055 		sizes[0] = venus_helper_get_framesz(inst->fmt_cap->pixfmt,
1056 						    inst->width,
1057 						    inst->height);
1058 		sizes[0] = max(sizes[0], inst->output_buf_size);
1059 		inst->output_buf_size = sizes[0];
1060 		break;
1061 	default:
1062 		ret = -EINVAL;
1063 		break;
1064 	}
1065 
1066 	return ret;
1067 put_power:
1068 	venc_pm_put(inst, false);
1069 	return ret;
1070 }
1071 
1072 static int venc_buf_init(struct vb2_buffer *vb)
1073 {
1074 	struct venus_inst *inst = vb2_get_drv_priv(vb->vb2_queue);
1075 
1076 	inst->buf_count++;
1077 
1078 	return venus_helper_vb2_buf_init(vb);
1079 }
1080 
1081 static void venc_release_session(struct venus_inst *inst)
1082 {
1083 	int ret;
1084 
1085 	venc_pm_get(inst);
1086 
1087 	mutex_lock(&inst->lock);
1088 
1089 	ret = hfi_session_deinit(inst);
1090 	if (ret || inst->session_error)
1091 		hfi_session_abort(inst);
1092 
1093 	mutex_unlock(&inst->lock);
1094 
1095 	venus_pm_load_scale(inst);
1096 	INIT_LIST_HEAD(&inst->registeredbufs);
1097 	venus_pm_release_core(inst);
1098 
1099 	venc_pm_put(inst, false);
1100 }
1101 
1102 static void venc_buf_cleanup(struct vb2_buffer *vb)
1103 {
1104 	struct venus_inst *inst = vb2_get_drv_priv(vb->vb2_queue);
1105 	struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
1106 	struct venus_buffer *buf = to_venus_buffer(vbuf);
1107 
1108 	mutex_lock(&inst->lock);
1109 	if (vb->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE)
1110 		if (!list_empty(&inst->registeredbufs))
1111 			list_del_init(&buf->reg_list);
1112 	mutex_unlock(&inst->lock);
1113 
1114 	inst->buf_count--;
1115 	if (!inst->buf_count)
1116 		venc_release_session(inst);
1117 }
1118 
1119 static int venc_verify_conf(struct venus_inst *inst)
1120 {
1121 	enum hfi_version ver = inst->core->res->hfi_version;
1122 	struct hfi_buffer_requirements bufreq;
1123 	int ret;
1124 
1125 	if (!inst->num_input_bufs || !inst->num_output_bufs)
1126 		return -EINVAL;
1127 
1128 	ret = venus_helper_get_bufreq(inst, HFI_BUFFER_OUTPUT, &bufreq);
1129 	if (ret)
1130 		return ret;
1131 
1132 	if (inst->num_output_bufs < bufreq.count_actual ||
1133 	    inst->num_output_bufs < HFI_BUFREQ_COUNT_MIN(&bufreq, ver))
1134 		return -EINVAL;
1135 
1136 	ret = venus_helper_get_bufreq(inst, HFI_BUFFER_INPUT, &bufreq);
1137 	if (ret)
1138 		return ret;
1139 
1140 	if (inst->num_input_bufs < bufreq.count_actual ||
1141 	    inst->num_input_bufs < HFI_BUFREQ_COUNT_MIN(&bufreq, ver))
1142 		return -EINVAL;
1143 
1144 	return 0;
1145 }
1146 
1147 static int venc_start_streaming(struct vb2_queue *q, unsigned int count)
1148 {
1149 	struct venus_inst *inst = vb2_get_drv_priv(q);
1150 	int ret;
1151 
1152 	mutex_lock(&inst->lock);
1153 
1154 	if (q->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE)
1155 		inst->streamon_out = 1;
1156 	else
1157 		inst->streamon_cap = 1;
1158 
1159 	if (!(inst->streamon_out & inst->streamon_cap)) {
1160 		mutex_unlock(&inst->lock);
1161 		return 0;
1162 	}
1163 
1164 	venus_helper_init_instance(inst);
1165 
1166 	inst->sequence_cap = 0;
1167 	inst->sequence_out = 0;
1168 
1169 	ret = venc_pm_get(inst);
1170 	if (ret)
1171 		goto error;
1172 
1173 	ret = venus_pm_acquire_core(inst);
1174 	if (ret)
1175 		goto put_power;
1176 
1177 	ret = venc_pm_put(inst, true);
1178 	if (ret)
1179 		goto error;
1180 
1181 	ret = venc_set_properties(inst);
1182 	if (ret)
1183 		goto error;
1184 
1185 	ret = venc_verify_conf(inst);
1186 	if (ret)
1187 		goto error;
1188 
1189 	ret = venus_helper_set_num_bufs(inst, inst->num_input_bufs,
1190 					inst->num_output_bufs, 0);
1191 	if (ret)
1192 		goto error;
1193 
1194 	ret = venus_helper_vb2_start_streaming(inst);
1195 	if (ret)
1196 		goto error;
1197 
1198 	mutex_unlock(&inst->lock);
1199 
1200 	return 0;
1201 
1202 put_power:
1203 	venc_pm_put(inst, false);
1204 error:
1205 	venus_helper_buffers_done(inst, q->type, VB2_BUF_STATE_QUEUED);
1206 	if (q->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE)
1207 		inst->streamon_out = 0;
1208 	else
1209 		inst->streamon_cap = 0;
1210 	mutex_unlock(&inst->lock);
1211 	return ret;
1212 }
1213 
1214 static void venc_vb2_buf_queue(struct vb2_buffer *vb)
1215 {
1216 	struct venus_inst *inst = vb2_get_drv_priv(vb->vb2_queue);
1217 
1218 	venc_pm_get_put(inst);
1219 
1220 	mutex_lock(&inst->lock);
1221 	venus_helper_vb2_buf_queue(vb);
1222 	mutex_unlock(&inst->lock);
1223 }
1224 
1225 static const struct vb2_ops venc_vb2_ops = {
1226 	.queue_setup = venc_queue_setup,
1227 	.buf_init = venc_buf_init,
1228 	.buf_cleanup = venc_buf_cleanup,
1229 	.buf_prepare = venus_helper_vb2_buf_prepare,
1230 	.start_streaming = venc_start_streaming,
1231 	.stop_streaming = venus_helper_vb2_stop_streaming,
1232 	.buf_queue = venc_vb2_buf_queue,
1233 };
1234 
1235 static void venc_buf_done(struct venus_inst *inst, unsigned int buf_type,
1236 			  u32 tag, u32 bytesused, u32 data_offset, u32 flags,
1237 			  u32 hfi_flags, u64 timestamp_us)
1238 {
1239 	struct vb2_v4l2_buffer *vbuf;
1240 	struct vb2_buffer *vb;
1241 	unsigned int type;
1242 
1243 	venc_pm_touch(inst);
1244 
1245 	if (buf_type == HFI_BUFFER_INPUT)
1246 		type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
1247 	else
1248 		type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
1249 
1250 	vbuf = venus_helper_find_buf(inst, type, tag);
1251 	if (!vbuf)
1252 		return;
1253 
1254 	vbuf->flags = flags;
1255 
1256 	if (type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
1257 		vb = &vbuf->vb2_buf;
1258 		vb2_set_plane_payload(vb, 0, bytesused + data_offset);
1259 		vb->planes[0].data_offset = data_offset;
1260 		vb->timestamp = timestamp_us * NSEC_PER_USEC;
1261 		vbuf->sequence = inst->sequence_cap++;
1262 	} else {
1263 		vbuf->sequence = inst->sequence_out++;
1264 	}
1265 
1266 	v4l2_m2m_buf_done(vbuf, VB2_BUF_STATE_DONE);
1267 }
1268 
1269 static void venc_event_notify(struct venus_inst *inst, u32 event,
1270 			      struct hfi_event_data *data)
1271 {
1272 	struct device *dev = inst->core->dev_enc;
1273 
1274 	venc_pm_touch(inst);
1275 
1276 	if (event == EVT_SESSION_ERROR) {
1277 		inst->session_error = true;
1278 		venus_helper_vb2_queue_error(inst);
1279 		dev_err(dev, "enc: event session error %x\n", inst->error);
1280 	}
1281 }
1282 
1283 static const struct hfi_inst_ops venc_hfi_ops = {
1284 	.buf_done = venc_buf_done,
1285 	.event_notify = venc_event_notify,
1286 };
1287 
1288 static const struct v4l2_m2m_ops venc_m2m_ops = {
1289 	.device_run = venus_helper_m2m_device_run,
1290 	.job_abort = venus_helper_m2m_job_abort,
1291 };
1292 
1293 static int m2m_queue_init(void *priv, struct vb2_queue *src_vq,
1294 			  struct vb2_queue *dst_vq)
1295 {
1296 	struct venus_inst *inst = priv;
1297 	int ret;
1298 
1299 	src_vq->type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
1300 	src_vq->io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF;
1301 	src_vq->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_COPY;
1302 	src_vq->ops = &venc_vb2_ops;
1303 	src_vq->mem_ops = &vb2_dma_contig_memops;
1304 	src_vq->drv_priv = inst;
1305 	src_vq->buf_struct_size = sizeof(struct venus_buffer);
1306 	src_vq->allow_zero_bytesused = 1;
1307 	src_vq->min_buffers_needed = 1;
1308 	src_vq->dev = inst->core->dev;
1309 	if (inst->core->res->hfi_version == HFI_VERSION_1XX)
1310 		src_vq->bidirectional = 1;
1311 	ret = vb2_queue_init(src_vq);
1312 	if (ret)
1313 		return ret;
1314 
1315 	dst_vq->type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
1316 	dst_vq->io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF;
1317 	dst_vq->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_COPY;
1318 	dst_vq->ops = &venc_vb2_ops;
1319 	dst_vq->mem_ops = &vb2_dma_contig_memops;
1320 	dst_vq->drv_priv = inst;
1321 	dst_vq->buf_struct_size = sizeof(struct venus_buffer);
1322 	dst_vq->allow_zero_bytesused = 1;
1323 	dst_vq->min_buffers_needed = 1;
1324 	dst_vq->dev = inst->core->dev;
1325 	return vb2_queue_init(dst_vq);
1326 }
1327 
1328 static void venc_inst_init(struct venus_inst *inst)
1329 {
1330 	inst->fmt_cap = &venc_formats[3];
1331 	inst->fmt_out = &venc_formats[0];
1332 	inst->width = 1280;
1333 	inst->height = ALIGN(720, 32);
1334 	inst->out_width = 1280;
1335 	inst->out_height = 720;
1336 	inst->fps = 15;
1337 	inst->timeperframe.numerator = 1;
1338 	inst->timeperframe.denominator = 15;
1339 	inst->hfi_codec = HFI_VIDEO_CODEC_H264;
1340 }
1341 
1342 static int venc_open(struct file *file)
1343 {
1344 	struct venus_core *core = video_drvdata(file);
1345 	struct venus_inst *inst;
1346 	int ret;
1347 
1348 	inst = kzalloc(sizeof(*inst), GFP_KERNEL);
1349 	if (!inst)
1350 		return -ENOMEM;
1351 
1352 	INIT_LIST_HEAD(&inst->dpbbufs);
1353 	INIT_LIST_HEAD(&inst->registeredbufs);
1354 	INIT_LIST_HEAD(&inst->internalbufs);
1355 	INIT_LIST_HEAD(&inst->list);
1356 	mutex_init(&inst->lock);
1357 
1358 	inst->core = core;
1359 	inst->session_type = VIDC_SESSION_TYPE_ENC;
1360 	inst->clk_data.core_id = VIDC_CORE_ID_DEFAULT;
1361 	inst->core_acquired = false;
1362 	inst->nonblock = file->f_flags & O_NONBLOCK;
1363 
1364 	venus_helper_init_instance(inst);
1365 
1366 	ret = venc_ctrl_init(inst);
1367 	if (ret)
1368 		goto err_free;
1369 
1370 	ret = hfi_session_create(inst, &venc_hfi_ops);
1371 	if (ret)
1372 		goto err_ctrl_deinit;
1373 
1374 	venc_inst_init(inst);
1375 
1376 	/*
1377 	 * create m2m device for every instance, the m2m context scheduling
1378 	 * is made by firmware side so we do not need to care about.
1379 	 */
1380 	inst->m2m_dev = v4l2_m2m_init(&venc_m2m_ops);
1381 	if (IS_ERR(inst->m2m_dev)) {
1382 		ret = PTR_ERR(inst->m2m_dev);
1383 		goto err_session_destroy;
1384 	}
1385 
1386 	inst->m2m_ctx = v4l2_m2m_ctx_init(inst->m2m_dev, inst, m2m_queue_init);
1387 	if (IS_ERR(inst->m2m_ctx)) {
1388 		ret = PTR_ERR(inst->m2m_ctx);
1389 		goto err_m2m_release;
1390 	}
1391 
1392 	v4l2_fh_init(&inst->fh, core->vdev_enc);
1393 
1394 	inst->fh.ctrl_handler = &inst->ctrl_handler;
1395 	v4l2_fh_add(&inst->fh);
1396 	inst->fh.m2m_ctx = inst->m2m_ctx;
1397 	file->private_data = &inst->fh;
1398 
1399 	return 0;
1400 
1401 err_m2m_release:
1402 	v4l2_m2m_release(inst->m2m_dev);
1403 err_session_destroy:
1404 	hfi_session_destroy(inst);
1405 err_ctrl_deinit:
1406 	venc_ctrl_deinit(inst);
1407 err_free:
1408 	kfree(inst);
1409 	return ret;
1410 }
1411 
1412 static int venc_close(struct file *file)
1413 {
1414 	struct venus_inst *inst = to_inst(file);
1415 
1416 	venc_pm_get(inst);
1417 
1418 	v4l2_m2m_ctx_release(inst->m2m_ctx);
1419 	v4l2_m2m_release(inst->m2m_dev);
1420 	venc_ctrl_deinit(inst);
1421 	hfi_session_destroy(inst);
1422 	mutex_destroy(&inst->lock);
1423 	v4l2_fh_del(&inst->fh);
1424 	v4l2_fh_exit(&inst->fh);
1425 
1426 	venc_pm_put(inst, false);
1427 
1428 	kfree(inst);
1429 	return 0;
1430 }
1431 
1432 static const struct v4l2_file_operations venc_fops = {
1433 	.owner = THIS_MODULE,
1434 	.open = venc_open,
1435 	.release = venc_close,
1436 	.unlocked_ioctl = video_ioctl2,
1437 	.poll = v4l2_m2m_fop_poll,
1438 	.mmap = v4l2_m2m_fop_mmap,
1439 };
1440 
1441 static int venc_probe(struct platform_device *pdev)
1442 {
1443 	struct device *dev = &pdev->dev;
1444 	struct video_device *vdev;
1445 	struct venus_core *core;
1446 	int ret;
1447 
1448 	if (!dev->parent)
1449 		return -EPROBE_DEFER;
1450 
1451 	core = dev_get_drvdata(dev->parent);
1452 	if (!core)
1453 		return -EPROBE_DEFER;
1454 
1455 	platform_set_drvdata(pdev, core);
1456 
1457 	if (core->pm_ops->venc_get) {
1458 		ret = core->pm_ops->venc_get(dev);
1459 		if (ret)
1460 			return ret;
1461 	}
1462 
1463 	vdev = video_device_alloc();
1464 	if (!vdev)
1465 		return -ENOMEM;
1466 
1467 	strscpy(vdev->name, "qcom-venus-encoder", sizeof(vdev->name));
1468 	vdev->release = video_device_release;
1469 	vdev->fops = &venc_fops;
1470 	vdev->ioctl_ops = &venc_ioctl_ops;
1471 	vdev->vfl_dir = VFL_DIR_M2M;
1472 	vdev->v4l2_dev = &core->v4l2_dev;
1473 	vdev->device_caps = V4L2_CAP_VIDEO_M2M_MPLANE | V4L2_CAP_STREAMING;
1474 
1475 	ret = video_register_device(vdev, VFL_TYPE_VIDEO, -1);
1476 	if (ret)
1477 		goto err_vdev_release;
1478 
1479 	core->vdev_enc = vdev;
1480 	core->dev_enc = dev;
1481 
1482 	video_set_drvdata(vdev, core);
1483 	pm_runtime_set_autosuspend_delay(dev, 2000);
1484 	pm_runtime_use_autosuspend(dev);
1485 	pm_runtime_enable(dev);
1486 
1487 	return 0;
1488 
1489 err_vdev_release:
1490 	video_device_release(vdev);
1491 	return ret;
1492 }
1493 
1494 static int venc_remove(struct platform_device *pdev)
1495 {
1496 	struct venus_core *core = dev_get_drvdata(pdev->dev.parent);
1497 
1498 	video_unregister_device(core->vdev_enc);
1499 	pm_runtime_disable(core->dev_enc);
1500 
1501 	if (core->pm_ops->venc_put)
1502 		core->pm_ops->venc_put(core->dev_enc);
1503 
1504 	return 0;
1505 }
1506 
1507 static __maybe_unused int venc_runtime_suspend(struct device *dev)
1508 {
1509 	struct venus_core *core = dev_get_drvdata(dev);
1510 	const struct venus_pm_ops *pm_ops = core->pm_ops;
1511 	int ret = 0;
1512 
1513 	if (pm_ops->venc_power)
1514 		ret = pm_ops->venc_power(dev, POWER_OFF);
1515 
1516 	return ret;
1517 }
1518 
1519 static __maybe_unused int venc_runtime_resume(struct device *dev)
1520 {
1521 	struct venus_core *core = dev_get_drvdata(dev);
1522 	const struct venus_pm_ops *pm_ops = core->pm_ops;
1523 	int ret = 0;
1524 
1525 	if (pm_ops->venc_power)
1526 		ret = pm_ops->venc_power(dev, POWER_ON);
1527 
1528 	return ret;
1529 }
1530 
1531 static const struct dev_pm_ops venc_pm_ops = {
1532 	SET_SYSTEM_SLEEP_PM_OPS(pm_runtime_force_suspend,
1533 				pm_runtime_force_resume)
1534 	SET_RUNTIME_PM_OPS(venc_runtime_suspend, venc_runtime_resume, NULL)
1535 };
1536 
1537 static const struct of_device_id venc_dt_match[] = {
1538 	{ .compatible = "venus-encoder" },
1539 	{ }
1540 };
1541 MODULE_DEVICE_TABLE(of, venc_dt_match);
1542 
1543 static struct platform_driver qcom_venus_enc_driver = {
1544 	.probe = venc_probe,
1545 	.remove = venc_remove,
1546 	.driver = {
1547 		.name = "qcom-venus-encoder",
1548 		.of_match_table = venc_dt_match,
1549 		.pm = &venc_pm_ops,
1550 	},
1551 };
1552 module_platform_driver(qcom_venus_enc_driver);
1553 
1554 MODULE_ALIAS("platform:qcom-venus-encoder");
1555 MODULE_DESCRIPTION("Qualcomm Venus video encoder driver");
1556 MODULE_LICENSE("GPL v2");
1557