1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2019 Pengutronix, Michael Tretter <kernel@pengutronix.de>
4  *
5  * Allegro DVT video encoder driver
6  */
7 
8 #include <linux/bits.h>
9 #include <linux/firmware.h>
10 #include <linux/gcd.h>
11 #include <linux/interrupt.h>
12 #include <linux/io.h>
13 #include <linux/kernel.h>
14 #include <linux/log2.h>
15 #include <linux/module.h>
16 #include <linux/of.h>
17 #include <linux/of_device.h>
18 #include <linux/platform_device.h>
19 #include <linux/regmap.h>
20 #include <linux/sizes.h>
21 #include <linux/slab.h>
22 #include <linux/videodev2.h>
23 #include <media/v4l2-ctrls.h>
24 #include <media/v4l2-device.h>
25 #include <media/v4l2-event.h>
26 #include <media/v4l2-ioctl.h>
27 #include <media/v4l2-mem2mem.h>
28 #include <media/videobuf2-dma-contig.h>
29 #include <media/videobuf2-v4l2.h>
30 
31 #include "allegro-mail.h"
32 #include "nal-h264.h"
33 #include "nal-hevc.h"
34 
35 /*
36  * Support up to 4k video streams. The hardware actually supports higher
37  * resolutions, which are specified in PG252 June 6, 2018 (H.264/H.265 Video
38  * Codec Unit v1.1) Chapter 3.
39  */
40 #define ALLEGRO_WIDTH_MIN 128
41 #define ALLEGRO_WIDTH_DEFAULT 1920
42 #define ALLEGRO_WIDTH_MAX 3840
43 #define ALLEGRO_HEIGHT_MIN 64
44 #define ALLEGRO_HEIGHT_DEFAULT 1080
45 #define ALLEGRO_HEIGHT_MAX 2160
46 
47 #define ALLEGRO_FRAMERATE_DEFAULT ((struct v4l2_fract) { 30, 1 })
48 
49 #define ALLEGRO_GOP_SIZE_DEFAULT 25
50 #define ALLEGRO_GOP_SIZE_MAX 1000
51 
52 /*
53  * MCU Control Registers
54  *
55  * The Zynq UltraScale+ Devices Register Reference documents the registers
56  * with an offset of 0x9000, which equals the size of the SRAM and one page
57  * gap. The driver handles SRAM and registers separately and, therefore, is
58  * oblivious of the offset.
59  */
60 #define AL5_MCU_RESET                   0x0000
61 #define AL5_MCU_RESET_SOFT              BIT(0)
62 #define AL5_MCU_RESET_REGS              BIT(1)
63 #define AL5_MCU_RESET_MODE              0x0004
64 #define AL5_MCU_RESET_MODE_SLEEP        BIT(0)
65 #define AL5_MCU_RESET_MODE_HALT         BIT(1)
66 #define AL5_MCU_STA                     0x0008
67 #define AL5_MCU_STA_SLEEP               BIT(0)
68 #define AL5_MCU_WAKEUP                  0x000c
69 
70 #define AL5_ICACHE_ADDR_OFFSET_MSB      0x0010
71 #define AL5_ICACHE_ADDR_OFFSET_LSB      0x0014
72 #define AL5_DCACHE_ADDR_OFFSET_MSB      0x0018
73 #define AL5_DCACHE_ADDR_OFFSET_LSB      0x001c
74 
75 #define AL5_MCU_INTERRUPT               0x0100
76 #define AL5_ITC_CPU_IRQ_MSK             0x0104
77 #define AL5_ITC_CPU_IRQ_CLR             0x0108
78 #define AL5_ITC_CPU_IRQ_STA             0x010C
79 #define AL5_ITC_CPU_IRQ_STA_TRIGGERED   BIT(0)
80 
81 #define AXI_ADDR_OFFSET_IP              0x0208
82 
83 /*
84  * The MCU accesses the system memory with a 2G offset compared to CPU
85  * physical addresses.
86  */
87 #define MCU_CACHE_OFFSET SZ_2G
88 
89 /*
90  * The driver needs to reserve some space at the beginning of capture buffers,
91  * because it needs to write SPS/PPS NAL units. The encoder writes the actual
92  * frame data after the offset.
93  */
94 #define ENCODER_STREAM_OFFSET SZ_128
95 
96 #define SIZE_MACROBLOCK 16
97 
98 /* Encoding options */
99 #define LOG2_MAX_FRAME_NUM		4
100 #define LOG2_MAX_PIC_ORDER_CNT		10
101 #define BETA_OFFSET_DIV_2		-1
102 #define TC_OFFSET_DIV_2			-1
103 
104 static int debug;
105 module_param(debug, int, 0644);
106 MODULE_PARM_DESC(debug, "Debug level (0-2)");
107 
108 struct allegro_buffer {
109 	void *vaddr;
110 	dma_addr_t paddr;
111 	size_t size;
112 	struct list_head head;
113 };
114 
115 struct allegro_dev;
116 struct allegro_channel;
117 
118 struct allegro_mbox {
119 	struct allegro_dev *dev;
120 	unsigned int head;
121 	unsigned int tail;
122 	unsigned int data;
123 	size_t size;
124 	/* protect mailbox from simultaneous accesses */
125 	struct mutex lock;
126 };
127 
128 struct allegro_dev {
129 	struct v4l2_device v4l2_dev;
130 	struct video_device video_dev;
131 	struct v4l2_m2m_dev *m2m_dev;
132 	struct platform_device *plat_dev;
133 
134 	/* mutex protecting vb2_queue structure */
135 	struct mutex lock;
136 
137 	struct regmap *regmap;
138 	struct regmap *sram;
139 
140 	const struct fw_info *fw_info;
141 	struct allegro_buffer firmware;
142 	struct allegro_buffer suballocator;
143 
144 	struct completion init_complete;
145 
146 	/* The mailbox interface */
147 	struct allegro_mbox *mbox_command;
148 	struct allegro_mbox *mbox_status;
149 
150 	/*
151 	 * The downstream driver limits the users to 64 users, thus I can use
152 	 * a bitfield for the user_ids that are in use. See also user_id in
153 	 * struct allegro_channel.
154 	 */
155 	unsigned long channel_user_ids;
156 	struct list_head channels;
157 };
158 
159 static struct regmap_config allegro_regmap_config = {
160 	.name = "regmap",
161 	.reg_bits = 32,
162 	.val_bits = 32,
163 	.reg_stride = 4,
164 	.max_register = 0xfff,
165 	.cache_type = REGCACHE_NONE,
166 };
167 
168 static struct regmap_config allegro_sram_config = {
169 	.name = "sram",
170 	.reg_bits = 32,
171 	.val_bits = 32,
172 	.reg_stride = 4,
173 	.max_register = 0x7fff,
174 	.cache_type = REGCACHE_NONE,
175 };
176 
177 #define fh_to_channel(__fh) container_of(__fh, struct allegro_channel, fh)
178 
179 struct allegro_channel {
180 	struct allegro_dev *dev;
181 	struct v4l2_fh fh;
182 	struct v4l2_ctrl_handler ctrl_handler;
183 
184 	unsigned int width;
185 	unsigned int height;
186 	unsigned int stride;
187 	struct v4l2_fract framerate;
188 
189 	enum v4l2_colorspace colorspace;
190 	enum v4l2_ycbcr_encoding ycbcr_enc;
191 	enum v4l2_quantization quantization;
192 	enum v4l2_xfer_func xfer_func;
193 
194 	u32 pixelformat;
195 	unsigned int sizeimage_raw;
196 	unsigned int osequence;
197 
198 	u32 codec;
199 	unsigned int sizeimage_encoded;
200 	unsigned int csequence;
201 
202 	bool frame_rc_enable;
203 	unsigned int bitrate;
204 	unsigned int bitrate_peak;
205 
206 	struct allegro_buffer config_blob;
207 
208 	unsigned int log2_max_frame_num;
209 	bool temporal_mvp_enable;
210 
211 	bool enable_loop_filter_across_tiles;
212 	bool enable_loop_filter_across_slices;
213 	bool enable_deblocking_filter_override;
214 	bool enable_reordering;
215 	bool dbf_ovr_en;
216 
217 	unsigned int num_ref_idx_l0;
218 	unsigned int num_ref_idx_l1;
219 
220 	/* Maximum range for motion estimation */
221 	int b_hrz_me_range;
222 	int b_vrt_me_range;
223 	int p_hrz_me_range;
224 	int p_vrt_me_range;
225 	/* Size limits of coding unit */
226 	int min_cu_size;
227 	int max_cu_size;
228 	/* Size limits of transform unit */
229 	int min_tu_size;
230 	int max_tu_size;
231 	int max_transfo_depth_intra;
232 	int max_transfo_depth_inter;
233 
234 	struct v4l2_ctrl *mpeg_video_h264_profile;
235 	struct v4l2_ctrl *mpeg_video_h264_level;
236 	struct v4l2_ctrl *mpeg_video_h264_i_frame_qp;
237 	struct v4l2_ctrl *mpeg_video_h264_max_qp;
238 	struct v4l2_ctrl *mpeg_video_h264_min_qp;
239 	struct v4l2_ctrl *mpeg_video_h264_p_frame_qp;
240 	struct v4l2_ctrl *mpeg_video_h264_b_frame_qp;
241 
242 	struct v4l2_ctrl *mpeg_video_hevc_profile;
243 	struct v4l2_ctrl *mpeg_video_hevc_level;
244 	struct v4l2_ctrl *mpeg_video_hevc_tier;
245 	struct v4l2_ctrl *mpeg_video_hevc_i_frame_qp;
246 	struct v4l2_ctrl *mpeg_video_hevc_max_qp;
247 	struct v4l2_ctrl *mpeg_video_hevc_min_qp;
248 	struct v4l2_ctrl *mpeg_video_hevc_p_frame_qp;
249 	struct v4l2_ctrl *mpeg_video_hevc_b_frame_qp;
250 
251 	struct v4l2_ctrl *mpeg_video_frame_rc_enable;
252 	struct { /* video bitrate mode control cluster */
253 		struct v4l2_ctrl *mpeg_video_bitrate_mode;
254 		struct v4l2_ctrl *mpeg_video_bitrate;
255 		struct v4l2_ctrl *mpeg_video_bitrate_peak;
256 	};
257 	struct v4l2_ctrl *mpeg_video_cpb_size;
258 	struct v4l2_ctrl *mpeg_video_gop_size;
259 
260 	/* user_id is used to identify the channel during CREATE_CHANNEL */
261 	/* not sure, what to set here and if this is actually required */
262 	int user_id;
263 	/* channel_id is set by the mcu and used by all later commands */
264 	int mcu_channel_id;
265 
266 	struct list_head buffers_reference;
267 	struct list_head buffers_intermediate;
268 
269 	struct list_head source_shadow_list;
270 	struct list_head stream_shadow_list;
271 	/* protect shadow lists of buffers passed to firmware */
272 	struct mutex shadow_list_lock;
273 
274 	struct list_head list;
275 	struct completion completion;
276 
277 	unsigned int error;
278 };
279 
280 static inline int
281 allegro_channel_get_i_frame_qp(struct allegro_channel *channel)
282 {
283 	if (channel->codec == V4L2_PIX_FMT_HEVC)
284 		return v4l2_ctrl_g_ctrl(channel->mpeg_video_hevc_i_frame_qp);
285 	else
286 		return v4l2_ctrl_g_ctrl(channel->mpeg_video_h264_i_frame_qp);
287 }
288 
289 static inline int
290 allegro_channel_get_p_frame_qp(struct allegro_channel *channel)
291 {
292 	if (channel->codec == V4L2_PIX_FMT_HEVC)
293 		return v4l2_ctrl_g_ctrl(channel->mpeg_video_hevc_p_frame_qp);
294 	else
295 		return v4l2_ctrl_g_ctrl(channel->mpeg_video_h264_p_frame_qp);
296 }
297 
298 static inline int
299 allegro_channel_get_b_frame_qp(struct allegro_channel *channel)
300 {
301 	if (channel->codec == V4L2_PIX_FMT_HEVC)
302 		return v4l2_ctrl_g_ctrl(channel->mpeg_video_hevc_b_frame_qp);
303 	else
304 		return v4l2_ctrl_g_ctrl(channel->mpeg_video_h264_b_frame_qp);
305 }
306 
307 static inline int
308 allegro_channel_get_min_qp(struct allegro_channel *channel)
309 {
310 	if (channel->codec == V4L2_PIX_FMT_HEVC)
311 		return v4l2_ctrl_g_ctrl(channel->mpeg_video_hevc_min_qp);
312 	else
313 		return v4l2_ctrl_g_ctrl(channel->mpeg_video_h264_min_qp);
314 }
315 
316 static inline int
317 allegro_channel_get_max_qp(struct allegro_channel *channel)
318 {
319 	if (channel->codec == V4L2_PIX_FMT_HEVC)
320 		return v4l2_ctrl_g_ctrl(channel->mpeg_video_hevc_max_qp);
321 	else
322 		return v4l2_ctrl_g_ctrl(channel->mpeg_video_h264_max_qp);
323 }
324 
325 struct allegro_m2m_buffer {
326 	struct v4l2_m2m_buffer buf;
327 	struct list_head head;
328 };
329 
330 #define to_allegro_m2m_buffer(__buf) \
331 	container_of(__buf, struct allegro_m2m_buffer, buf)
332 
333 struct fw_info {
334 	unsigned int id;
335 	unsigned int id_codec;
336 	char *version;
337 	unsigned int mailbox_cmd;
338 	unsigned int mailbox_status;
339 	size_t mailbox_size;
340 	enum mcu_msg_version mailbox_version;
341 	size_t suballocator_size;
342 };
343 
344 static const struct fw_info supported_firmware[] = {
345 	{
346 		.id = 18296,
347 		.id_codec = 96272,
348 		.version = "v2018.2",
349 		.mailbox_cmd = 0x7800,
350 		.mailbox_status = 0x7c00,
351 		.mailbox_size = 0x400 - 0x8,
352 		.mailbox_version = MCU_MSG_VERSION_2018_2,
353 		.suballocator_size = SZ_16M,
354 	}, {
355 		.id = 14680,
356 		.id_codec = 126572,
357 		.version = "v2019.2",
358 		.mailbox_cmd = 0x7000,
359 		.mailbox_status = 0x7800,
360 		.mailbox_size = 0x800 - 0x8,
361 		.mailbox_version = MCU_MSG_VERSION_2019_2,
362 		.suballocator_size = SZ_32M,
363 	},
364 };
365 
366 static inline u32 to_mcu_addr(struct allegro_dev *dev, dma_addr_t phys)
367 {
368 	if (upper_32_bits(phys) || (lower_32_bits(phys) & MCU_CACHE_OFFSET))
369 		v4l2_warn(&dev->v4l2_dev,
370 			  "address %pad is outside mcu window\n", &phys);
371 
372 	return lower_32_bits(phys) | MCU_CACHE_OFFSET;
373 }
374 
375 static inline u32 to_mcu_size(struct allegro_dev *dev, size_t size)
376 {
377 	return lower_32_bits(size);
378 }
379 
380 static inline u32 to_codec_addr(struct allegro_dev *dev, dma_addr_t phys)
381 {
382 	if (upper_32_bits(phys))
383 		v4l2_warn(&dev->v4l2_dev,
384 			  "address %pad cannot be used by codec\n", &phys);
385 
386 	return lower_32_bits(phys);
387 }
388 
389 static inline u64 ptr_to_u64(const void *ptr)
390 {
391 	return (uintptr_t)ptr;
392 }
393 
394 /* Helper functions for channel and user operations */
395 
396 static unsigned long allegro_next_user_id(struct allegro_dev *dev)
397 {
398 	if (dev->channel_user_ids == ~0UL)
399 		return -EBUSY;
400 
401 	return ffz(dev->channel_user_ids);
402 }
403 
404 static struct allegro_channel *
405 allegro_find_channel_by_user_id(struct allegro_dev *dev,
406 				unsigned int user_id)
407 {
408 	struct allegro_channel *channel;
409 
410 	list_for_each_entry(channel, &dev->channels, list) {
411 		if (channel->user_id == user_id)
412 			return channel;
413 	}
414 
415 	return ERR_PTR(-EINVAL);
416 }
417 
418 static struct allegro_channel *
419 allegro_find_channel_by_channel_id(struct allegro_dev *dev,
420 				   unsigned int channel_id)
421 {
422 	struct allegro_channel *channel;
423 
424 	list_for_each_entry(channel, &dev->channels, list) {
425 		if (channel->mcu_channel_id == channel_id)
426 			return channel;
427 	}
428 
429 	return ERR_PTR(-EINVAL);
430 }
431 
432 static inline bool channel_exists(struct allegro_channel *channel)
433 {
434 	return channel->mcu_channel_id != -1;
435 }
436 
437 #define AL_ERROR			0x80
438 #define AL_ERR_INIT_FAILED		0x81
439 #define AL_ERR_NO_FRAME_DECODED		0x82
440 #define AL_ERR_RESOLUTION_CHANGE	0x85
441 #define AL_ERR_NO_MEMORY		0x87
442 #define AL_ERR_STREAM_OVERFLOW		0x88
443 #define AL_ERR_TOO_MANY_SLICES		0x89
444 #define AL_ERR_BUF_NOT_READY		0x8c
445 #define AL_ERR_NO_CHANNEL_AVAILABLE	0x8d
446 #define AL_ERR_RESOURCE_UNAVAILABLE	0x8e
447 #define AL_ERR_NOT_ENOUGH_CORES		0x8f
448 #define AL_ERR_REQUEST_MALFORMED	0x90
449 #define AL_ERR_CMD_NOT_ALLOWED		0x91
450 #define AL_ERR_INVALID_CMD_VALUE	0x92
451 
452 static inline const char *allegro_err_to_string(unsigned int err)
453 {
454 	switch (err) {
455 	case AL_ERR_INIT_FAILED:
456 		return "initialization failed";
457 	case AL_ERR_NO_FRAME_DECODED:
458 		return "no frame decoded";
459 	case AL_ERR_RESOLUTION_CHANGE:
460 		return "resolution change";
461 	case AL_ERR_NO_MEMORY:
462 		return "out of memory";
463 	case AL_ERR_STREAM_OVERFLOW:
464 		return "stream buffer overflow";
465 	case AL_ERR_TOO_MANY_SLICES:
466 		return "too many slices";
467 	case AL_ERR_BUF_NOT_READY:
468 		return "buffer not ready";
469 	case AL_ERR_NO_CHANNEL_AVAILABLE:
470 		return "no channel available";
471 	case AL_ERR_RESOURCE_UNAVAILABLE:
472 		return "resource unavailable";
473 	case AL_ERR_NOT_ENOUGH_CORES:
474 		return "not enough cores";
475 	case AL_ERR_REQUEST_MALFORMED:
476 		return "request malformed";
477 	case AL_ERR_CMD_NOT_ALLOWED:
478 		return "command not allowed";
479 	case AL_ERR_INVALID_CMD_VALUE:
480 		return "invalid command value";
481 	case AL_ERROR:
482 	default:
483 		return "unknown error";
484 	}
485 }
486 
487 static unsigned int estimate_stream_size(unsigned int width,
488 					 unsigned int height)
489 {
490 	unsigned int offset = ENCODER_STREAM_OFFSET;
491 	unsigned int num_blocks = DIV_ROUND_UP(width, SIZE_MACROBLOCK) *
492 					DIV_ROUND_UP(height, SIZE_MACROBLOCK);
493 	unsigned int pcm_size = SZ_256;
494 	unsigned int partition_table = SZ_256;
495 
496 	return round_up(offset + num_blocks * pcm_size + partition_table, 32);
497 }
498 
499 static enum v4l2_mpeg_video_h264_level
500 select_minimum_h264_level(unsigned int width, unsigned int height)
501 {
502 	unsigned int pic_width_in_mb = DIV_ROUND_UP(width, SIZE_MACROBLOCK);
503 	unsigned int frame_height_in_mb = DIV_ROUND_UP(height, SIZE_MACROBLOCK);
504 	unsigned int frame_size_in_mb = pic_width_in_mb * frame_height_in_mb;
505 	enum v4l2_mpeg_video_h264_level level = V4L2_MPEG_VIDEO_H264_LEVEL_4_0;
506 
507 	/*
508 	 * The level limits are specified in Rec. ITU-T H.264 Annex A.3.1 and
509 	 * also specify limits regarding bit rate and CBP size. Only approximate
510 	 * the levels using the frame size.
511 	 *
512 	 * Level 5.1 allows up to 4k video resolution.
513 	 */
514 	if (frame_size_in_mb <= 99)
515 		level = V4L2_MPEG_VIDEO_H264_LEVEL_1_0;
516 	else if (frame_size_in_mb <= 396)
517 		level = V4L2_MPEG_VIDEO_H264_LEVEL_1_1;
518 	else if (frame_size_in_mb <= 792)
519 		level = V4L2_MPEG_VIDEO_H264_LEVEL_2_1;
520 	else if (frame_size_in_mb <= 1620)
521 		level = V4L2_MPEG_VIDEO_H264_LEVEL_2_2;
522 	else if (frame_size_in_mb <= 3600)
523 		level = V4L2_MPEG_VIDEO_H264_LEVEL_3_1;
524 	else if (frame_size_in_mb <= 5120)
525 		level = V4L2_MPEG_VIDEO_H264_LEVEL_3_2;
526 	else if (frame_size_in_mb <= 8192)
527 		level = V4L2_MPEG_VIDEO_H264_LEVEL_4_0;
528 	else if (frame_size_in_mb <= 8704)
529 		level = V4L2_MPEG_VIDEO_H264_LEVEL_4_2;
530 	else if (frame_size_in_mb <= 22080)
531 		level = V4L2_MPEG_VIDEO_H264_LEVEL_5_0;
532 	else
533 		level = V4L2_MPEG_VIDEO_H264_LEVEL_5_1;
534 
535 	return level;
536 }
537 
538 static unsigned int h264_maximum_bitrate(enum v4l2_mpeg_video_h264_level level)
539 {
540 	switch (level) {
541 	case V4L2_MPEG_VIDEO_H264_LEVEL_1_0:
542 		return 64000;
543 	case V4L2_MPEG_VIDEO_H264_LEVEL_1B:
544 		return 128000;
545 	case V4L2_MPEG_VIDEO_H264_LEVEL_1_1:
546 		return 192000;
547 	case V4L2_MPEG_VIDEO_H264_LEVEL_1_2:
548 		return 384000;
549 	case V4L2_MPEG_VIDEO_H264_LEVEL_1_3:
550 		return 768000;
551 	case V4L2_MPEG_VIDEO_H264_LEVEL_2_0:
552 		return 2000000;
553 	case V4L2_MPEG_VIDEO_H264_LEVEL_2_1:
554 		return 4000000;
555 	case V4L2_MPEG_VIDEO_H264_LEVEL_2_2:
556 		return 4000000;
557 	case V4L2_MPEG_VIDEO_H264_LEVEL_3_0:
558 		return 10000000;
559 	case V4L2_MPEG_VIDEO_H264_LEVEL_3_1:
560 		return 14000000;
561 	case V4L2_MPEG_VIDEO_H264_LEVEL_3_2:
562 		return 20000000;
563 	case V4L2_MPEG_VIDEO_H264_LEVEL_4_0:
564 		return 20000000;
565 	case V4L2_MPEG_VIDEO_H264_LEVEL_4_1:
566 		return 50000000;
567 	case V4L2_MPEG_VIDEO_H264_LEVEL_4_2:
568 		return 50000000;
569 	case V4L2_MPEG_VIDEO_H264_LEVEL_5_0:
570 		return 135000000;
571 	case V4L2_MPEG_VIDEO_H264_LEVEL_5_1:
572 	default:
573 		return 240000000;
574 	}
575 }
576 
577 static unsigned int h264_maximum_cpb_size(enum v4l2_mpeg_video_h264_level level)
578 {
579 	switch (level) {
580 	case V4L2_MPEG_VIDEO_H264_LEVEL_1_0:
581 		return 175;
582 	case V4L2_MPEG_VIDEO_H264_LEVEL_1B:
583 		return 350;
584 	case V4L2_MPEG_VIDEO_H264_LEVEL_1_1:
585 		return 500;
586 	case V4L2_MPEG_VIDEO_H264_LEVEL_1_2:
587 		return 1000;
588 	case V4L2_MPEG_VIDEO_H264_LEVEL_1_3:
589 		return 2000;
590 	case V4L2_MPEG_VIDEO_H264_LEVEL_2_0:
591 		return 2000;
592 	case V4L2_MPEG_VIDEO_H264_LEVEL_2_1:
593 		return 4000;
594 	case V4L2_MPEG_VIDEO_H264_LEVEL_2_2:
595 		return 4000;
596 	case V4L2_MPEG_VIDEO_H264_LEVEL_3_0:
597 		return 10000;
598 	case V4L2_MPEG_VIDEO_H264_LEVEL_3_1:
599 		return 14000;
600 	case V4L2_MPEG_VIDEO_H264_LEVEL_3_2:
601 		return 20000;
602 	case V4L2_MPEG_VIDEO_H264_LEVEL_4_0:
603 		return 25000;
604 	case V4L2_MPEG_VIDEO_H264_LEVEL_4_1:
605 		return 62500;
606 	case V4L2_MPEG_VIDEO_H264_LEVEL_4_2:
607 		return 62500;
608 	case V4L2_MPEG_VIDEO_H264_LEVEL_5_0:
609 		return 135000;
610 	case V4L2_MPEG_VIDEO_H264_LEVEL_5_1:
611 	default:
612 		return 240000;
613 	}
614 }
615 
616 static enum v4l2_mpeg_video_hevc_level
617 select_minimum_hevc_level(unsigned int width, unsigned int height)
618 {
619 	unsigned int luma_picture_size = width * height;
620 	enum v4l2_mpeg_video_hevc_level level;
621 
622 	if (luma_picture_size <= 36864)
623 		level = V4L2_MPEG_VIDEO_HEVC_LEVEL_1;
624 	else if (luma_picture_size <= 122880)
625 		level = V4L2_MPEG_VIDEO_HEVC_LEVEL_2;
626 	else if (luma_picture_size <= 245760)
627 		level = V4L2_MPEG_VIDEO_HEVC_LEVEL_2_1;
628 	else if (luma_picture_size <= 552960)
629 		level = V4L2_MPEG_VIDEO_HEVC_LEVEL_3;
630 	else if (luma_picture_size <= 983040)
631 		level = V4L2_MPEG_VIDEO_HEVC_LEVEL_3_1;
632 	else if (luma_picture_size <= 2228224)
633 		level = V4L2_MPEG_VIDEO_HEVC_LEVEL_4;
634 	else if (luma_picture_size <= 8912896)
635 		level = V4L2_MPEG_VIDEO_HEVC_LEVEL_5;
636 	else
637 		level = V4L2_MPEG_VIDEO_HEVC_LEVEL_6;
638 
639 	return level;
640 }
641 
642 static unsigned int hevc_maximum_bitrate(enum v4l2_mpeg_video_hevc_level level)
643 {
644 	/*
645 	 * See Rec. ITU-T H.265 v5 (02/2018), A.4.2 Profile-specific level
646 	 * limits for the video profiles.
647 	 */
648 	switch (level) {
649 	case V4L2_MPEG_VIDEO_HEVC_LEVEL_1:
650 		return 128;
651 	case V4L2_MPEG_VIDEO_HEVC_LEVEL_2:
652 		return 1500;
653 	case V4L2_MPEG_VIDEO_HEVC_LEVEL_2_1:
654 		return 3000;
655 	case V4L2_MPEG_VIDEO_HEVC_LEVEL_3:
656 		return 6000;
657 	case V4L2_MPEG_VIDEO_HEVC_LEVEL_3_1:
658 		return 10000;
659 	case V4L2_MPEG_VIDEO_HEVC_LEVEL_4:
660 		return 12000;
661 	case V4L2_MPEG_VIDEO_HEVC_LEVEL_4_1:
662 		return 20000;
663 	case V4L2_MPEG_VIDEO_HEVC_LEVEL_5:
664 		return 25000;
665 	default:
666 	case V4L2_MPEG_VIDEO_HEVC_LEVEL_5_1:
667 		return 40000;
668 	}
669 }
670 
671 static unsigned int hevc_maximum_cpb_size(enum v4l2_mpeg_video_hevc_level level)
672 {
673 	switch (level) {
674 	case V4L2_MPEG_VIDEO_HEVC_LEVEL_1:
675 		return 350;
676 	case V4L2_MPEG_VIDEO_HEVC_LEVEL_2:
677 		return 1500;
678 	case V4L2_MPEG_VIDEO_HEVC_LEVEL_2_1:
679 		return 3000;
680 	case V4L2_MPEG_VIDEO_HEVC_LEVEL_3:
681 		return 6000;
682 	case V4L2_MPEG_VIDEO_HEVC_LEVEL_3_1:
683 		return 10000;
684 	case V4L2_MPEG_VIDEO_HEVC_LEVEL_4:
685 		return 12000;
686 	case V4L2_MPEG_VIDEO_HEVC_LEVEL_4_1:
687 		return 20000;
688 	case V4L2_MPEG_VIDEO_HEVC_LEVEL_5:
689 		return 25000;
690 	default:
691 	case V4L2_MPEG_VIDEO_HEVC_LEVEL_5_1:
692 		return 40000;
693 	}
694 }
695 
696 static const struct fw_info *
697 allegro_get_firmware_info(struct allegro_dev *dev,
698 			  const struct firmware *fw,
699 			  const struct firmware *fw_codec)
700 {
701 	int i;
702 	unsigned int id = fw->size;
703 	unsigned int id_codec = fw_codec->size;
704 
705 	for (i = 0; i < ARRAY_SIZE(supported_firmware); i++)
706 		if (supported_firmware[i].id == id &&
707 		    supported_firmware[i].id_codec == id_codec)
708 			return &supported_firmware[i];
709 
710 	return NULL;
711 }
712 
713 /*
714  * Buffers that are used internally by the MCU.
715  */
716 
717 static int allegro_alloc_buffer(struct allegro_dev *dev,
718 				struct allegro_buffer *buffer, size_t size)
719 {
720 	buffer->vaddr = dma_alloc_coherent(&dev->plat_dev->dev, size,
721 					   &buffer->paddr, GFP_KERNEL);
722 	if (!buffer->vaddr)
723 		return -ENOMEM;
724 	buffer->size = size;
725 
726 	return 0;
727 }
728 
729 static void allegro_free_buffer(struct allegro_dev *dev,
730 				struct allegro_buffer *buffer)
731 {
732 	if (buffer->vaddr) {
733 		dma_free_coherent(&dev->plat_dev->dev, buffer->size,
734 				  buffer->vaddr, buffer->paddr);
735 		buffer->vaddr = NULL;
736 		buffer->size = 0;
737 	}
738 }
739 
740 /*
741  * Mailbox interface to send messages to the MCU.
742  */
743 
744 static void allegro_mcu_interrupt(struct allegro_dev *dev);
745 static void allegro_handle_message(struct allegro_dev *dev,
746 				   union mcu_msg_response *msg);
747 
748 static struct allegro_mbox *allegro_mbox_init(struct allegro_dev *dev,
749 					      unsigned int base, size_t size)
750 {
751 	struct allegro_mbox *mbox;
752 
753 	mbox = devm_kmalloc(&dev->plat_dev->dev, sizeof(*mbox), GFP_KERNEL);
754 	if (!mbox)
755 		return ERR_PTR(-ENOMEM);
756 
757 	mbox->dev = dev;
758 
759 	mbox->head = base;
760 	mbox->tail = base + 0x4;
761 	mbox->data = base + 0x8;
762 	mbox->size = size;
763 	mutex_init(&mbox->lock);
764 
765 	regmap_write(dev->sram, mbox->head, 0);
766 	regmap_write(dev->sram, mbox->tail, 0);
767 
768 	return mbox;
769 }
770 
771 static int allegro_mbox_write(struct allegro_mbox *mbox,
772 			      const u32 *src, size_t size)
773 {
774 	struct regmap *sram = mbox->dev->sram;
775 	unsigned int tail;
776 	size_t size_no_wrap;
777 	int err = 0;
778 	int stride = regmap_get_reg_stride(sram);
779 
780 	if (!src)
781 		return -EINVAL;
782 
783 	if (size > mbox->size)
784 		return -EINVAL;
785 
786 	mutex_lock(&mbox->lock);
787 	regmap_read(sram, mbox->tail, &tail);
788 	if (tail > mbox->size) {
789 		err = -EIO;
790 		goto out;
791 	}
792 	size_no_wrap = min(size, mbox->size - (size_t)tail);
793 	regmap_bulk_write(sram, mbox->data + tail,
794 			  src, size_no_wrap / stride);
795 	regmap_bulk_write(sram, mbox->data,
796 			  src + (size_no_wrap / sizeof(*src)),
797 			  (size - size_no_wrap) / stride);
798 	regmap_write(sram, mbox->tail, (tail + size) % mbox->size);
799 
800 out:
801 	mutex_unlock(&mbox->lock);
802 
803 	return err;
804 }
805 
806 static ssize_t allegro_mbox_read(struct allegro_mbox *mbox,
807 				 u32 *dst, size_t nbyte)
808 {
809 	struct {
810 		u16 length;
811 		u16 type;
812 	} __attribute__ ((__packed__)) *header;
813 	struct regmap *sram = mbox->dev->sram;
814 	unsigned int head;
815 	ssize_t size;
816 	size_t body_no_wrap;
817 	int stride = regmap_get_reg_stride(sram);
818 
819 	regmap_read(sram, mbox->head, &head);
820 	if (head > mbox->size)
821 		return -EIO;
822 
823 	/* Assume that the header does not wrap. */
824 	regmap_bulk_read(sram, mbox->data + head,
825 			 dst, sizeof(*header) / stride);
826 	header = (void *)dst;
827 	size = header->length + sizeof(*header);
828 	if (size > mbox->size || size & 0x3)
829 		return -EIO;
830 	if (size > nbyte)
831 		return -EINVAL;
832 
833 	/*
834 	 * The message might wrap within the mailbox. If the message does not
835 	 * wrap, the first read will read the entire message, otherwise the
836 	 * first read will read message until the end of the mailbox and the
837 	 * second read will read the remaining bytes from the beginning of the
838 	 * mailbox.
839 	 *
840 	 * Skip the header, as was already read to get the size of the body.
841 	 */
842 	body_no_wrap = min((size_t)header->length,
843 			   (size_t)(mbox->size - (head + sizeof(*header))));
844 	regmap_bulk_read(sram, mbox->data + head + sizeof(*header),
845 			 dst + (sizeof(*header) / sizeof(*dst)),
846 			 body_no_wrap / stride);
847 	regmap_bulk_read(sram, mbox->data,
848 			 dst + (sizeof(*header) + body_no_wrap) / sizeof(*dst),
849 			 (header->length - body_no_wrap) / stride);
850 
851 	regmap_write(sram, mbox->head, (head + size) % mbox->size);
852 
853 	return size;
854 }
855 
856 /**
857  * allegro_mbox_send() - Send a message via the mailbox
858  * @mbox: the mailbox which is used to send the message
859  * @msg: the message to send
860  */
861 static int allegro_mbox_send(struct allegro_mbox *mbox, void *msg)
862 {
863 	struct allegro_dev *dev = mbox->dev;
864 	ssize_t size;
865 	int err;
866 	u32 *tmp;
867 
868 	tmp = kzalloc(mbox->size, GFP_KERNEL);
869 	if (!tmp) {
870 		err = -ENOMEM;
871 		goto out;
872 	}
873 
874 	size = allegro_encode_mail(tmp, msg);
875 
876 	err = allegro_mbox_write(mbox, tmp, size);
877 	kfree(tmp);
878 	if (err)
879 		goto out;
880 
881 	allegro_mcu_interrupt(dev);
882 
883 out:
884 	return err;
885 }
886 
887 /**
888  * allegro_mbox_notify() - Notify the mailbox about a new message
889  * @mbox: The allegro_mbox to notify
890  */
891 static void allegro_mbox_notify(struct allegro_mbox *mbox)
892 {
893 	struct allegro_dev *dev = mbox->dev;
894 	union mcu_msg_response *msg;
895 	ssize_t size;
896 	u32 *tmp;
897 	int err;
898 
899 	msg = kmalloc(sizeof(*msg), GFP_KERNEL);
900 	if (!msg)
901 		return;
902 
903 	msg->header.version = dev->fw_info->mailbox_version;
904 
905 	tmp = kmalloc(mbox->size, GFP_KERNEL);
906 	if (!tmp)
907 		goto out;
908 
909 	size = allegro_mbox_read(mbox, tmp, mbox->size);
910 	if (size < 0)
911 		goto out;
912 
913 	err = allegro_decode_mail(msg, tmp);
914 	if (err)
915 		goto out;
916 
917 	allegro_handle_message(dev, msg);
918 
919 out:
920 	kfree(tmp);
921 	kfree(msg);
922 }
923 
924 static void allegro_mcu_send_init(struct allegro_dev *dev,
925 				  dma_addr_t suballoc_dma, size_t suballoc_size)
926 {
927 	struct mcu_msg_init_request msg;
928 
929 	memset(&msg, 0, sizeof(msg));
930 
931 	msg.header.type = MCU_MSG_TYPE_INIT;
932 	msg.header.version = dev->fw_info->mailbox_version;
933 
934 	msg.suballoc_dma = to_mcu_addr(dev, suballoc_dma);
935 	msg.suballoc_size = to_mcu_size(dev, suballoc_size);
936 
937 	/* disable L2 cache */
938 	msg.l2_cache[0] = -1;
939 	msg.l2_cache[1] = -1;
940 	msg.l2_cache[2] = -1;
941 
942 	allegro_mbox_send(dev->mbox_command, &msg);
943 }
944 
945 static u32 v4l2_pixelformat_to_mcu_format(u32 pixelformat)
946 {
947 	switch (pixelformat) {
948 	case V4L2_PIX_FMT_NV12:
949 		/* AL_420_8BITS: 0x100 -> NV12, 0x88 -> 8 bit */
950 		return 0x100 | 0x88;
951 	default:
952 		return -EINVAL;
953 	}
954 }
955 
956 static u32 v4l2_colorspace_to_mcu_colorspace(enum v4l2_colorspace colorspace)
957 {
958 	switch (colorspace) {
959 	case V4L2_COLORSPACE_REC709:
960 		return 2;
961 	case V4L2_COLORSPACE_SMPTE170M:
962 		return 3;
963 	case V4L2_COLORSPACE_SMPTE240M:
964 		return 4;
965 	case V4L2_COLORSPACE_SRGB:
966 		return 7;
967 	default:
968 		/* UNKNOWN */
969 		return 0;
970 	}
971 }
972 
973 static u8 v4l2_profile_to_mcu_profile(enum v4l2_mpeg_video_h264_profile profile)
974 {
975 	switch (profile) {
976 	case V4L2_MPEG_VIDEO_H264_PROFILE_BASELINE:
977 	default:
978 		return 66;
979 	}
980 }
981 
982 static u16 v4l2_level_to_mcu_level(enum v4l2_mpeg_video_h264_level level)
983 {
984 	switch (level) {
985 	case V4L2_MPEG_VIDEO_H264_LEVEL_1_0:
986 		return 10;
987 	case V4L2_MPEG_VIDEO_H264_LEVEL_1_1:
988 		return 11;
989 	case V4L2_MPEG_VIDEO_H264_LEVEL_1_2:
990 		return 12;
991 	case V4L2_MPEG_VIDEO_H264_LEVEL_1_3:
992 		return 13;
993 	case V4L2_MPEG_VIDEO_H264_LEVEL_2_0:
994 		return 20;
995 	case V4L2_MPEG_VIDEO_H264_LEVEL_2_1:
996 		return 21;
997 	case V4L2_MPEG_VIDEO_H264_LEVEL_2_2:
998 		return 22;
999 	case V4L2_MPEG_VIDEO_H264_LEVEL_3_0:
1000 		return 30;
1001 	case V4L2_MPEG_VIDEO_H264_LEVEL_3_1:
1002 		return 31;
1003 	case V4L2_MPEG_VIDEO_H264_LEVEL_3_2:
1004 		return 32;
1005 	case V4L2_MPEG_VIDEO_H264_LEVEL_4_0:
1006 		return 40;
1007 	case V4L2_MPEG_VIDEO_H264_LEVEL_4_1:
1008 		return 41;
1009 	case V4L2_MPEG_VIDEO_H264_LEVEL_4_2:
1010 		return 42;
1011 	case V4L2_MPEG_VIDEO_H264_LEVEL_5_0:
1012 		return 50;
1013 	case V4L2_MPEG_VIDEO_H264_LEVEL_5_1:
1014 	default:
1015 		return 51;
1016 	}
1017 }
1018 
1019 static u8 hevc_profile_to_mcu_profile(enum v4l2_mpeg_video_hevc_profile profile)
1020 {
1021 	switch (profile) {
1022 	default:
1023 	case V4L2_MPEG_VIDEO_HEVC_PROFILE_MAIN:
1024 		return 1;
1025 	case V4L2_MPEG_VIDEO_HEVC_PROFILE_MAIN_10:
1026 		return 2;
1027 	case V4L2_MPEG_VIDEO_HEVC_PROFILE_MAIN_STILL_PICTURE:
1028 		return 3;
1029 	}
1030 }
1031 
1032 static u16 hevc_level_to_mcu_level(enum v4l2_mpeg_video_hevc_level level)
1033 {
1034 	switch (level) {
1035 	case V4L2_MPEG_VIDEO_HEVC_LEVEL_1:
1036 		return 10;
1037 	case V4L2_MPEG_VIDEO_HEVC_LEVEL_2:
1038 		return 20;
1039 	case V4L2_MPEG_VIDEO_HEVC_LEVEL_2_1:
1040 		return 21;
1041 	case V4L2_MPEG_VIDEO_HEVC_LEVEL_3:
1042 		return 30;
1043 	case V4L2_MPEG_VIDEO_HEVC_LEVEL_3_1:
1044 		return 31;
1045 	case V4L2_MPEG_VIDEO_HEVC_LEVEL_4:
1046 		return 40;
1047 	case V4L2_MPEG_VIDEO_HEVC_LEVEL_4_1:
1048 		return 41;
1049 	case V4L2_MPEG_VIDEO_HEVC_LEVEL_5:
1050 		return 50;
1051 	default:
1052 	case V4L2_MPEG_VIDEO_HEVC_LEVEL_5_1:
1053 		return 51;
1054 	}
1055 }
1056 
1057 static u8 hevc_tier_to_mcu_tier(enum v4l2_mpeg_video_hevc_tier tier)
1058 {
1059 	switch (tier) {
1060 	default:
1061 	case V4L2_MPEG_VIDEO_HEVC_TIER_MAIN:
1062 		return 0;
1063 	case V4L2_MPEG_VIDEO_HEVC_TIER_HIGH:
1064 		return 1;
1065 	}
1066 }
1067 
1068 static u32
1069 v4l2_bitrate_mode_to_mcu_mode(enum v4l2_mpeg_video_bitrate_mode mode)
1070 {
1071 	switch (mode) {
1072 	case V4L2_MPEG_VIDEO_BITRATE_MODE_VBR:
1073 		return 2;
1074 	case V4L2_MPEG_VIDEO_BITRATE_MODE_CBR:
1075 	default:
1076 		return 1;
1077 	}
1078 }
1079 
1080 static u32 v4l2_cpb_size_to_mcu(unsigned int cpb_size, unsigned int bitrate)
1081 {
1082 	unsigned int cpb_size_kbit;
1083 	unsigned int bitrate_kbps;
1084 
1085 	/*
1086 	 * The mcu expects the CPB size in units of a 90 kHz clock, but the
1087 	 * channel follows the V4L2_CID_MPEG_VIDEO_H264_CPB_SIZE and stores
1088 	 * the CPB size in kilobytes.
1089 	 */
1090 	cpb_size_kbit = cpb_size * BITS_PER_BYTE;
1091 	bitrate_kbps = bitrate / 1000;
1092 
1093 	return (cpb_size_kbit * 90000) / bitrate_kbps;
1094 }
1095 
1096 static s16 get_qp_delta(int minuend, int subtrahend)
1097 {
1098 	if (minuend == subtrahend)
1099 		return -1;
1100 	else
1101 		return minuend - subtrahend;
1102 }
1103 
1104 static u32 allegro_channel_get_entropy_mode(struct allegro_channel *channel)
1105 {
1106 #define ALLEGRO_ENTROPY_MODE_CAVLC 0
1107 #define ALLEGRO_ENTROPY_MODE_CABAC 1
1108 
1109 	/* HEVC always uses CABAC, but this has to be explicitly set */
1110 	if (channel->codec == V4L2_PIX_FMT_HEVC)
1111 		return ALLEGRO_ENTROPY_MODE_CABAC;
1112 
1113 	return ALLEGRO_ENTROPY_MODE_CAVLC;
1114 }
1115 
1116 static int fill_create_channel_param(struct allegro_channel *channel,
1117 				     struct create_channel_param *param)
1118 {
1119 	int i_frame_qp = allegro_channel_get_i_frame_qp(channel);
1120 	int p_frame_qp = allegro_channel_get_p_frame_qp(channel);
1121 	int b_frame_qp = allegro_channel_get_b_frame_qp(channel);
1122 	int bitrate_mode = v4l2_ctrl_g_ctrl(channel->mpeg_video_bitrate_mode);
1123 	unsigned int cpb_size = v4l2_ctrl_g_ctrl(channel->mpeg_video_cpb_size);
1124 
1125 	param->width = channel->width;
1126 	param->height = channel->height;
1127 	param->format = v4l2_pixelformat_to_mcu_format(channel->pixelformat);
1128 	param->colorspace =
1129 		v4l2_colorspace_to_mcu_colorspace(channel->colorspace);
1130 	param->src_mode = 0x0;
1131 
1132 	param->codec = channel->codec;
1133 	if (channel->codec == V4L2_PIX_FMT_H264) {
1134 		enum v4l2_mpeg_video_h264_profile profile;
1135 		enum v4l2_mpeg_video_h264_level level;
1136 
1137 		profile = v4l2_ctrl_g_ctrl(channel->mpeg_video_h264_profile);
1138 		level = v4l2_ctrl_g_ctrl(channel->mpeg_video_h264_level);
1139 
1140 		param->profile = v4l2_profile_to_mcu_profile(profile);
1141 		param->constraint_set_flags = BIT(1);
1142 		param->level = v4l2_level_to_mcu_level(level);
1143 	} else {
1144 		enum v4l2_mpeg_video_hevc_profile profile;
1145 		enum v4l2_mpeg_video_hevc_level level;
1146 		enum v4l2_mpeg_video_hevc_tier tier;
1147 
1148 		profile = v4l2_ctrl_g_ctrl(channel->mpeg_video_hevc_profile);
1149 		level = v4l2_ctrl_g_ctrl(channel->mpeg_video_hevc_level);
1150 		tier = v4l2_ctrl_g_ctrl(channel->mpeg_video_hevc_tier);
1151 
1152 		param->profile = hevc_profile_to_mcu_profile(profile);
1153 		param->level = hevc_level_to_mcu_level(level);
1154 		param->tier = hevc_tier_to_mcu_tier(tier);
1155 	}
1156 
1157 	param->log2_max_poc = LOG2_MAX_PIC_ORDER_CNT;
1158 	param->log2_max_frame_num = channel->log2_max_frame_num;
1159 	param->temporal_mvp_enable = channel->temporal_mvp_enable;
1160 
1161 	param->dbf_ovr_en = channel->dbf_ovr_en;
1162 	param->override_lf = channel->enable_deblocking_filter_override;
1163 	param->enable_reordering = channel->enable_reordering;
1164 	param->entropy_mode = allegro_channel_get_entropy_mode(channel);
1165 	param->rdo_cost_mode = 1;
1166 	param->custom_lda = 1;
1167 	param->lf = 1;
1168 	param->lf_x_tile = channel->enable_loop_filter_across_tiles;
1169 	param->lf_x_slice = channel->enable_loop_filter_across_slices;
1170 
1171 	param->src_bit_depth = 8;
1172 
1173 	param->beta_offset = BETA_OFFSET_DIV_2;
1174 	param->tc_offset = TC_OFFSET_DIV_2;
1175 	param->num_slices = 1;
1176 	param->me_range[0] = channel->b_hrz_me_range;
1177 	param->me_range[1] = channel->b_vrt_me_range;
1178 	param->me_range[2] = channel->p_hrz_me_range;
1179 	param->me_range[3] = channel->p_vrt_me_range;
1180 	param->max_cu_size = channel->max_cu_size;
1181 	param->min_cu_size = channel->min_cu_size;
1182 	param->max_tu_size = channel->max_tu_size;
1183 	param->min_tu_size = channel->min_tu_size;
1184 	param->max_transfo_depth_intra = channel->max_transfo_depth_intra;
1185 	param->max_transfo_depth_inter = channel->max_transfo_depth_inter;
1186 
1187 	param->prefetch_auto = 0;
1188 	param->prefetch_mem_offset = 0;
1189 	param->prefetch_mem_size = 0;
1190 
1191 	param->rate_control_mode = channel->frame_rc_enable ?
1192 		v4l2_bitrate_mode_to_mcu_mode(bitrate_mode) : 0;
1193 
1194 	param->cpb_size = v4l2_cpb_size_to_mcu(cpb_size, channel->bitrate_peak);
1195 	/* Shall be ]0;cpb_size in 90 kHz units]. Use maximum value. */
1196 	param->initial_rem_delay = param->cpb_size;
1197 	param->framerate = DIV_ROUND_UP(channel->framerate.numerator,
1198 					channel->framerate.denominator);
1199 	param->clk_ratio = channel->framerate.denominator == 1001 ? 1001 : 1000;
1200 	param->target_bitrate = channel->bitrate;
1201 	param->max_bitrate = channel->bitrate_peak;
1202 	param->initial_qp = i_frame_qp;
1203 	param->min_qp = allegro_channel_get_min_qp(channel);
1204 	param->max_qp = allegro_channel_get_max_qp(channel);
1205 	param->ip_delta = get_qp_delta(i_frame_qp, p_frame_qp);
1206 	param->pb_delta = get_qp_delta(p_frame_qp, b_frame_qp);
1207 	param->golden_ref = 0;
1208 	param->golden_delta = 2;
1209 	param->golden_ref_frequency = 10;
1210 	param->rate_control_option = 0x00000000;
1211 
1212 	param->num_pixel = channel->width + channel->height;
1213 	param->max_psnr = 4200;
1214 	param->max_pixel_value = 255;
1215 
1216 	param->gop_ctrl_mode = 0x00000002;
1217 	param->freq_idr = v4l2_ctrl_g_ctrl(channel->mpeg_video_gop_size);
1218 	param->freq_lt = 0;
1219 	param->gdr_mode = 0x00000000;
1220 	param->gop_length = v4l2_ctrl_g_ctrl(channel->mpeg_video_gop_size);
1221 	param->subframe_latency = 0x00000000;
1222 
1223 	param->lda_factors[0] = 51;
1224 	param->lda_factors[1] = 90;
1225 	param->lda_factors[2] = 151;
1226 	param->lda_factors[3] = 151;
1227 	param->lda_factors[4] = 151;
1228 	param->lda_factors[5] = 151;
1229 
1230 	param->max_num_merge_cand = 5;
1231 
1232 	return 0;
1233 }
1234 
1235 static int allegro_mcu_send_create_channel(struct allegro_dev *dev,
1236 					   struct allegro_channel *channel)
1237 {
1238 	struct mcu_msg_create_channel msg;
1239 	struct allegro_buffer *blob = &channel->config_blob;
1240 	struct create_channel_param param;
1241 	size_t size;
1242 
1243 	memset(&param, 0, sizeof(param));
1244 	fill_create_channel_param(channel, &param);
1245 	allegro_alloc_buffer(dev, blob, sizeof(struct create_channel_param));
1246 	param.version = dev->fw_info->mailbox_version;
1247 	size = allegro_encode_config_blob(blob->vaddr, &param);
1248 
1249 	memset(&msg, 0, sizeof(msg));
1250 
1251 	msg.header.type = MCU_MSG_TYPE_CREATE_CHANNEL;
1252 	msg.header.version = dev->fw_info->mailbox_version;
1253 
1254 	msg.user_id = channel->user_id;
1255 
1256 	msg.blob = blob->vaddr;
1257 	msg.blob_size = size;
1258 	msg.blob_mcu_addr = to_mcu_addr(dev, blob->paddr);
1259 
1260 	allegro_mbox_send(dev->mbox_command, &msg);
1261 
1262 	return 0;
1263 }
1264 
1265 static int allegro_mcu_send_destroy_channel(struct allegro_dev *dev,
1266 					    struct allegro_channel *channel)
1267 {
1268 	struct mcu_msg_destroy_channel msg;
1269 
1270 	memset(&msg, 0, sizeof(msg));
1271 
1272 	msg.header.type = MCU_MSG_TYPE_DESTROY_CHANNEL;
1273 	msg.header.version = dev->fw_info->mailbox_version;
1274 
1275 	msg.channel_id = channel->mcu_channel_id;
1276 
1277 	allegro_mbox_send(dev->mbox_command, &msg);
1278 
1279 	return 0;
1280 }
1281 
1282 static int allegro_mcu_send_put_stream_buffer(struct allegro_dev *dev,
1283 					      struct allegro_channel *channel,
1284 					      dma_addr_t paddr,
1285 					      unsigned long size,
1286 					      u64 dst_handle)
1287 {
1288 	struct mcu_msg_put_stream_buffer msg;
1289 
1290 	memset(&msg, 0, sizeof(msg));
1291 
1292 	msg.header.type = MCU_MSG_TYPE_PUT_STREAM_BUFFER;
1293 	msg.header.version = dev->fw_info->mailbox_version;
1294 
1295 	msg.channel_id = channel->mcu_channel_id;
1296 	msg.dma_addr = to_codec_addr(dev, paddr);
1297 	msg.mcu_addr = to_mcu_addr(dev, paddr);
1298 	msg.size = size;
1299 	msg.offset = ENCODER_STREAM_OFFSET;
1300 	/* copied to mcu_msg_encode_frame_response */
1301 	msg.dst_handle = dst_handle;
1302 
1303 	allegro_mbox_send(dev->mbox_command, &msg);
1304 
1305 	return 0;
1306 }
1307 
1308 static int allegro_mcu_send_encode_frame(struct allegro_dev *dev,
1309 					 struct allegro_channel *channel,
1310 					 dma_addr_t src_y, dma_addr_t src_uv,
1311 					 u64 src_handle)
1312 {
1313 	struct mcu_msg_encode_frame msg;
1314 
1315 	memset(&msg, 0, sizeof(msg));
1316 
1317 	msg.header.type = MCU_MSG_TYPE_ENCODE_FRAME;
1318 	msg.header.version = dev->fw_info->mailbox_version;
1319 
1320 	msg.channel_id = channel->mcu_channel_id;
1321 	msg.encoding_options = AL_OPT_FORCE_LOAD;
1322 	msg.pps_qp = 26; /* qp are relative to 26 */
1323 	msg.user_param = 0; /* copied to mcu_msg_encode_frame_response */
1324 	/* src_handle is copied to mcu_msg_encode_frame_response */
1325 	msg.src_handle = src_handle;
1326 	msg.src_y = to_codec_addr(dev, src_y);
1327 	msg.src_uv = to_codec_addr(dev, src_uv);
1328 	msg.stride = channel->stride;
1329 	msg.ep2 = 0x0;
1330 	msg.ep2_v = to_mcu_addr(dev, msg.ep2);
1331 
1332 	allegro_mbox_send(dev->mbox_command, &msg);
1333 
1334 	return 0;
1335 }
1336 
1337 static int allegro_mcu_wait_for_init_timeout(struct allegro_dev *dev,
1338 					     unsigned long timeout_ms)
1339 {
1340 	unsigned long tmo;
1341 
1342 	tmo = wait_for_completion_timeout(&dev->init_complete,
1343 					  msecs_to_jiffies(timeout_ms));
1344 	if (tmo == 0)
1345 		return -ETIMEDOUT;
1346 
1347 	reinit_completion(&dev->init_complete);
1348 	return 0;
1349 }
1350 
1351 static int allegro_mcu_push_buffer_internal(struct allegro_channel *channel,
1352 					    enum mcu_msg_type type)
1353 {
1354 	struct allegro_dev *dev = channel->dev;
1355 	struct mcu_msg_push_buffers_internal *msg;
1356 	struct mcu_msg_push_buffers_internal_buffer *buffer;
1357 	unsigned int num_buffers = 0;
1358 	size_t size;
1359 	struct allegro_buffer *al_buffer;
1360 	struct list_head *list;
1361 	int err;
1362 
1363 	switch (type) {
1364 	case MCU_MSG_TYPE_PUSH_BUFFER_REFERENCE:
1365 		list = &channel->buffers_reference;
1366 		break;
1367 	case MCU_MSG_TYPE_PUSH_BUFFER_INTERMEDIATE:
1368 		list = &channel->buffers_intermediate;
1369 		break;
1370 	default:
1371 		return -EINVAL;
1372 	}
1373 
1374 	list_for_each_entry(al_buffer, list, head)
1375 		num_buffers++;
1376 	size = struct_size(msg, buffer, num_buffers);
1377 
1378 	msg = kmalloc(size, GFP_KERNEL);
1379 	if (!msg)
1380 		return -ENOMEM;
1381 
1382 	msg->header.type = type;
1383 	msg->header.version = dev->fw_info->mailbox_version;
1384 
1385 	msg->channel_id = channel->mcu_channel_id;
1386 	msg->num_buffers = num_buffers;
1387 
1388 	buffer = msg->buffer;
1389 	list_for_each_entry(al_buffer, list, head) {
1390 		buffer->dma_addr = to_codec_addr(dev, al_buffer->paddr);
1391 		buffer->mcu_addr = to_mcu_addr(dev, al_buffer->paddr);
1392 		buffer->size = to_mcu_size(dev, al_buffer->size);
1393 		buffer++;
1394 	}
1395 
1396 	err = allegro_mbox_send(dev->mbox_command, msg);
1397 
1398 	kfree(msg);
1399 	return err;
1400 }
1401 
1402 static int allegro_mcu_push_buffer_intermediate(struct allegro_channel *channel)
1403 {
1404 	enum mcu_msg_type type = MCU_MSG_TYPE_PUSH_BUFFER_INTERMEDIATE;
1405 
1406 	return allegro_mcu_push_buffer_internal(channel, type);
1407 }
1408 
1409 static int allegro_mcu_push_buffer_reference(struct allegro_channel *channel)
1410 {
1411 	enum mcu_msg_type type = MCU_MSG_TYPE_PUSH_BUFFER_REFERENCE;
1412 
1413 	return allegro_mcu_push_buffer_internal(channel, type);
1414 }
1415 
1416 static int allocate_buffers_internal(struct allegro_channel *channel,
1417 				     struct list_head *list,
1418 				     size_t n, size_t size)
1419 {
1420 	struct allegro_dev *dev = channel->dev;
1421 	unsigned int i;
1422 	int err;
1423 	struct allegro_buffer *buffer, *tmp;
1424 
1425 	for (i = 0; i < n; i++) {
1426 		buffer = kmalloc(sizeof(*buffer), GFP_KERNEL);
1427 		if (!buffer) {
1428 			err = -ENOMEM;
1429 			goto err;
1430 		}
1431 		INIT_LIST_HEAD(&buffer->head);
1432 
1433 		err = allegro_alloc_buffer(dev, buffer, size);
1434 		if (err)
1435 			goto err;
1436 		list_add(&buffer->head, list);
1437 	}
1438 
1439 	return 0;
1440 
1441 err:
1442 	list_for_each_entry_safe(buffer, tmp, list, head) {
1443 		list_del(&buffer->head);
1444 		allegro_free_buffer(dev, buffer);
1445 		kfree(buffer);
1446 	}
1447 	return err;
1448 }
1449 
1450 static void destroy_buffers_internal(struct allegro_channel *channel,
1451 				     struct list_head *list)
1452 {
1453 	struct allegro_dev *dev = channel->dev;
1454 	struct allegro_buffer *buffer, *tmp;
1455 
1456 	list_for_each_entry_safe(buffer, tmp, list, head) {
1457 		list_del(&buffer->head);
1458 		allegro_free_buffer(dev, buffer);
1459 		kfree(buffer);
1460 	}
1461 }
1462 
1463 static void destroy_reference_buffers(struct allegro_channel *channel)
1464 {
1465 	return destroy_buffers_internal(channel, &channel->buffers_reference);
1466 }
1467 
1468 static void destroy_intermediate_buffers(struct allegro_channel *channel)
1469 {
1470 	return destroy_buffers_internal(channel,
1471 					&channel->buffers_intermediate);
1472 }
1473 
1474 static int allocate_intermediate_buffers(struct allegro_channel *channel,
1475 					 size_t n, size_t size)
1476 {
1477 	return allocate_buffers_internal(channel,
1478 					 &channel->buffers_intermediate,
1479 					 n, size);
1480 }
1481 
1482 static int allocate_reference_buffers(struct allegro_channel *channel,
1483 				      size_t n, size_t size)
1484 {
1485 	return allocate_buffers_internal(channel,
1486 					 &channel->buffers_reference,
1487 					 n, PAGE_ALIGN(size));
1488 }
1489 
1490 static ssize_t allegro_h264_write_sps(struct allegro_channel *channel,
1491 				      void *dest, size_t n)
1492 {
1493 	struct allegro_dev *dev = channel->dev;
1494 	struct nal_h264_sps *sps;
1495 	ssize_t size;
1496 	unsigned int size_mb = SIZE_MACROBLOCK;
1497 	/* Calculation of crop units in Rec. ITU-T H.264 (04/2017) p. 76 */
1498 	unsigned int crop_unit_x = 2;
1499 	unsigned int crop_unit_y = 2;
1500 	enum v4l2_mpeg_video_h264_profile profile;
1501 	enum v4l2_mpeg_video_h264_level level;
1502 	unsigned int cpb_size;
1503 	unsigned int cpb_size_scale;
1504 
1505 	sps = kzalloc(sizeof(*sps), GFP_KERNEL);
1506 	if (!sps)
1507 		return -ENOMEM;
1508 
1509 	profile = v4l2_ctrl_g_ctrl(channel->mpeg_video_h264_profile);
1510 	level = v4l2_ctrl_g_ctrl(channel->mpeg_video_h264_level);
1511 
1512 	sps->profile_idc = nal_h264_profile_from_v4l2(profile);
1513 	sps->constraint_set0_flag = 0;
1514 	sps->constraint_set1_flag = 1;
1515 	sps->constraint_set2_flag = 0;
1516 	sps->constraint_set3_flag = 0;
1517 	sps->constraint_set4_flag = 0;
1518 	sps->constraint_set5_flag = 0;
1519 	sps->level_idc = nal_h264_level_from_v4l2(level);
1520 	sps->seq_parameter_set_id = 0;
1521 	sps->log2_max_frame_num_minus4 = LOG2_MAX_FRAME_NUM - 4;
1522 	sps->pic_order_cnt_type = 0;
1523 	sps->log2_max_pic_order_cnt_lsb_minus4 = LOG2_MAX_PIC_ORDER_CNT - 4;
1524 	sps->max_num_ref_frames = 3;
1525 	sps->gaps_in_frame_num_value_allowed_flag = 0;
1526 	sps->pic_width_in_mbs_minus1 =
1527 		DIV_ROUND_UP(channel->width, size_mb) - 1;
1528 	sps->pic_height_in_map_units_minus1 =
1529 		DIV_ROUND_UP(channel->height, size_mb) - 1;
1530 	sps->frame_mbs_only_flag = 1;
1531 	sps->mb_adaptive_frame_field_flag = 0;
1532 	sps->direct_8x8_inference_flag = 1;
1533 	sps->frame_cropping_flag =
1534 		(channel->width % size_mb) || (channel->height % size_mb);
1535 	if (sps->frame_cropping_flag) {
1536 		sps->crop_left = 0;
1537 		sps->crop_right = (round_up(channel->width, size_mb) - channel->width) / crop_unit_x;
1538 		sps->crop_top = 0;
1539 		sps->crop_bottom = (round_up(channel->height, size_mb) - channel->height) / crop_unit_y;
1540 	}
1541 	sps->vui_parameters_present_flag = 1;
1542 	sps->vui.aspect_ratio_info_present_flag = 0;
1543 	sps->vui.overscan_info_present_flag = 0;
1544 	sps->vui.video_signal_type_present_flag = 1;
1545 	sps->vui.video_format = 1;
1546 	sps->vui.video_full_range_flag = 0;
1547 	sps->vui.colour_description_present_flag = 1;
1548 	sps->vui.colour_primaries = 5;
1549 	sps->vui.transfer_characteristics = 5;
1550 	sps->vui.matrix_coefficients = 5;
1551 	sps->vui.chroma_loc_info_present_flag = 1;
1552 	sps->vui.chroma_sample_loc_type_top_field = 0;
1553 	sps->vui.chroma_sample_loc_type_bottom_field = 0;
1554 
1555 	sps->vui.timing_info_present_flag = 1;
1556 	sps->vui.num_units_in_tick = channel->framerate.denominator;
1557 	sps->vui.time_scale = 2 * channel->framerate.numerator;
1558 
1559 	sps->vui.fixed_frame_rate_flag = 1;
1560 	sps->vui.nal_hrd_parameters_present_flag = 0;
1561 	sps->vui.vcl_hrd_parameters_present_flag = 1;
1562 	sps->vui.vcl_hrd_parameters.cpb_cnt_minus1 = 0;
1563 	sps->vui.vcl_hrd_parameters.bit_rate_scale = 0;
1564 	/* See Rec. ITU-T H.264 (04/2017) p. 410 E-53 */
1565 	sps->vui.vcl_hrd_parameters.bit_rate_value_minus1[0] =
1566 		channel->bitrate_peak / (1 << (6 + sps->vui.vcl_hrd_parameters.bit_rate_scale)) - 1;
1567 	/* See Rec. ITU-T H.264 (04/2017) p. 410 E-54 */
1568 	cpb_size = v4l2_ctrl_g_ctrl(channel->mpeg_video_cpb_size);
1569 	cpb_size_scale = ffs(cpb_size) - 4;
1570 	sps->vui.vcl_hrd_parameters.cpb_size_scale = cpb_size_scale;
1571 	sps->vui.vcl_hrd_parameters.cpb_size_value_minus1[0] =
1572 		(cpb_size * 1000) / (1 << (4 + cpb_size_scale)) - 1;
1573 	sps->vui.vcl_hrd_parameters.cbr_flag[0] =
1574 		!v4l2_ctrl_g_ctrl(channel->mpeg_video_frame_rc_enable);
1575 	sps->vui.vcl_hrd_parameters.initial_cpb_removal_delay_length_minus1 = 31;
1576 	sps->vui.vcl_hrd_parameters.cpb_removal_delay_length_minus1 = 31;
1577 	sps->vui.vcl_hrd_parameters.dpb_output_delay_length_minus1 = 31;
1578 	sps->vui.vcl_hrd_parameters.time_offset_length = 0;
1579 	sps->vui.low_delay_hrd_flag = 0;
1580 	sps->vui.pic_struct_present_flag = 1;
1581 	sps->vui.bitstream_restriction_flag = 0;
1582 
1583 	size = nal_h264_write_sps(&dev->plat_dev->dev, dest, n, sps);
1584 
1585 	kfree(sps);
1586 
1587 	return size;
1588 }
1589 
1590 static ssize_t allegro_h264_write_pps(struct allegro_channel *channel,
1591 				      void *dest, size_t n)
1592 {
1593 	struct allegro_dev *dev = channel->dev;
1594 	struct nal_h264_pps *pps;
1595 	ssize_t size;
1596 
1597 	pps = kzalloc(sizeof(*pps), GFP_KERNEL);
1598 	if (!pps)
1599 		return -ENOMEM;
1600 
1601 	pps->pic_parameter_set_id = 0;
1602 	pps->seq_parameter_set_id = 0;
1603 	pps->entropy_coding_mode_flag = 0;
1604 	pps->bottom_field_pic_order_in_frame_present_flag = 0;
1605 	pps->num_slice_groups_minus1 = 0;
1606 	pps->num_ref_idx_l0_default_active_minus1 = channel->num_ref_idx_l0 - 1;
1607 	pps->num_ref_idx_l1_default_active_minus1 = channel->num_ref_idx_l1 - 1;
1608 	pps->weighted_pred_flag = 0;
1609 	pps->weighted_bipred_idc = 0;
1610 	pps->pic_init_qp_minus26 = 0;
1611 	pps->pic_init_qs_minus26 = 0;
1612 	pps->chroma_qp_index_offset = 0;
1613 	pps->deblocking_filter_control_present_flag = 1;
1614 	pps->constrained_intra_pred_flag = 0;
1615 	pps->redundant_pic_cnt_present_flag = 0;
1616 	pps->transform_8x8_mode_flag = 0;
1617 	pps->pic_scaling_matrix_present_flag = 0;
1618 	pps->second_chroma_qp_index_offset = 0;
1619 
1620 	size = nal_h264_write_pps(&dev->plat_dev->dev, dest, n, pps);
1621 
1622 	kfree(pps);
1623 
1624 	return size;
1625 }
1626 
1627 static void allegro_channel_eos_event(struct allegro_channel *channel)
1628 {
1629 	const struct v4l2_event eos_event = {
1630 		.type = V4L2_EVENT_EOS
1631 	};
1632 
1633 	v4l2_event_queue_fh(&channel->fh, &eos_event);
1634 }
1635 
1636 static ssize_t allegro_hevc_write_vps(struct allegro_channel *channel,
1637 				      void *dest, size_t n)
1638 {
1639 	struct allegro_dev *dev = channel->dev;
1640 	struct nal_hevc_vps *vps;
1641 	struct nal_hevc_profile_tier_level *ptl;
1642 	ssize_t size;
1643 	unsigned int num_ref_frames = channel->num_ref_idx_l0;
1644 	s32 profile = v4l2_ctrl_g_ctrl(channel->mpeg_video_hevc_profile);
1645 	s32 level = v4l2_ctrl_g_ctrl(channel->mpeg_video_hevc_level);
1646 	s32 tier = v4l2_ctrl_g_ctrl(channel->mpeg_video_hevc_tier);
1647 
1648 	vps = kzalloc(sizeof(*vps), GFP_KERNEL);
1649 	if (!vps)
1650 		return -ENOMEM;
1651 
1652 	vps->base_layer_internal_flag = 1;
1653 	vps->base_layer_available_flag = 1;
1654 	vps->temporal_id_nesting_flag = 1;
1655 
1656 	ptl = &vps->profile_tier_level;
1657 	ptl->general_profile_idc = nal_hevc_profile_from_v4l2(profile);
1658 	ptl->general_profile_compatibility_flag[ptl->general_profile_idc] = 1;
1659 	ptl->general_tier_flag = nal_hevc_tier_from_v4l2(tier);
1660 	ptl->general_progressive_source_flag = 1;
1661 	ptl->general_frame_only_constraint_flag = 1;
1662 	ptl->general_level_idc = nal_hevc_level_from_v4l2(level);
1663 
1664 	vps->sub_layer_ordering_info_present_flag = 0;
1665 	vps->max_dec_pic_buffering_minus1[0] = num_ref_frames;
1666 	vps->max_num_reorder_pics[0] = num_ref_frames;
1667 
1668 	size = nal_hevc_write_vps(&dev->plat_dev->dev, dest, n, vps);
1669 
1670 	kfree(vps);
1671 
1672 	return size;
1673 }
1674 
1675 static ssize_t allegro_hevc_write_sps(struct allegro_channel *channel,
1676 				      void *dest, size_t n)
1677 {
1678 	struct allegro_dev *dev = channel->dev;
1679 	struct nal_hevc_sps *sps;
1680 	struct nal_hevc_profile_tier_level *ptl;
1681 	ssize_t size;
1682 	unsigned int num_ref_frames = channel->num_ref_idx_l0;
1683 	s32 profile = v4l2_ctrl_g_ctrl(channel->mpeg_video_hevc_profile);
1684 	s32 level = v4l2_ctrl_g_ctrl(channel->mpeg_video_hevc_level);
1685 	s32 tier = v4l2_ctrl_g_ctrl(channel->mpeg_video_hevc_tier);
1686 
1687 	sps = kzalloc(sizeof(*sps), GFP_KERNEL);
1688 	if (!sps)
1689 		return -ENOMEM;
1690 
1691 	sps->temporal_id_nesting_flag = 1;
1692 
1693 	ptl = &sps->profile_tier_level;
1694 	ptl->general_profile_idc = nal_hevc_profile_from_v4l2(profile);
1695 	ptl->general_profile_compatibility_flag[ptl->general_profile_idc] = 1;
1696 	ptl->general_tier_flag = nal_hevc_tier_from_v4l2(tier);
1697 	ptl->general_progressive_source_flag = 1;
1698 	ptl->general_frame_only_constraint_flag = 1;
1699 	ptl->general_level_idc = nal_hevc_level_from_v4l2(level);
1700 
1701 	sps->seq_parameter_set_id = 0;
1702 	sps->chroma_format_idc = 1; /* Only 4:2:0 sampling supported */
1703 	sps->pic_width_in_luma_samples = round_up(channel->width, 8);
1704 	sps->pic_height_in_luma_samples = round_up(channel->height, 8);
1705 	sps->conf_win_right_offset =
1706 		sps->pic_width_in_luma_samples - channel->width;
1707 	sps->conf_win_bottom_offset =
1708 		sps->pic_height_in_luma_samples - channel->height;
1709 	sps->conformance_window_flag =
1710 		sps->conf_win_right_offset || sps->conf_win_bottom_offset;
1711 
1712 	sps->log2_max_pic_order_cnt_lsb_minus4 = LOG2_MAX_PIC_ORDER_CNT - 4;
1713 
1714 	sps->sub_layer_ordering_info_present_flag = 1;
1715 	sps->max_dec_pic_buffering_minus1[0] = num_ref_frames;
1716 	sps->max_num_reorder_pics[0] = num_ref_frames;
1717 
1718 	sps->log2_min_luma_coding_block_size_minus3 =
1719 		channel->min_cu_size - 3;
1720 	sps->log2_diff_max_min_luma_coding_block_size =
1721 		channel->max_cu_size - channel->min_cu_size;
1722 	sps->log2_min_luma_transform_block_size_minus2 =
1723 		channel->min_tu_size - 2;
1724 	sps->log2_diff_max_min_luma_transform_block_size =
1725 		channel->max_tu_size - channel->min_tu_size;
1726 	sps->max_transform_hierarchy_depth_intra =
1727 		channel->max_transfo_depth_intra;
1728 	sps->max_transform_hierarchy_depth_inter =
1729 		channel->max_transfo_depth_inter;
1730 
1731 	sps->sps_temporal_mvp_enabled_flag = channel->temporal_mvp_enable;
1732 	sps->strong_intra_smoothing_enabled_flag = channel->max_cu_size > 4;
1733 
1734 	size = nal_hevc_write_sps(&dev->plat_dev->dev, dest, n, sps);
1735 
1736 	kfree(sps);
1737 
1738 	return size;
1739 }
1740 
1741 static ssize_t allegro_hevc_write_pps(struct allegro_channel *channel,
1742 				      struct mcu_msg_encode_frame_response *msg,
1743 				      void *dest, size_t n)
1744 {
1745 	struct allegro_dev *dev = channel->dev;
1746 	struct nal_hevc_pps *pps;
1747 	ssize_t size;
1748 	int i;
1749 
1750 	pps = kzalloc(sizeof(*pps), GFP_KERNEL);
1751 	if (!pps)
1752 		return -ENOMEM;
1753 
1754 	pps->pps_pic_parameter_set_id = 0;
1755 	pps->pps_seq_parameter_set_id = 0;
1756 
1757 	if (msg->num_column > 1 || msg->num_row > 1) {
1758 		pps->tiles_enabled_flag = 1;
1759 		pps->num_tile_columns_minus1 = msg->num_column - 1;
1760 		pps->num_tile_rows_minus1 = msg->num_row - 1;
1761 
1762 		for (i = 0; i < msg->num_column; i++)
1763 			pps->column_width_minus1[i] = msg->tile_width[i] - 1;
1764 
1765 		for (i = 0; i < msg->num_row; i++)
1766 			pps->row_height_minus1[i] = msg->tile_height[i] - 1;
1767 	}
1768 
1769 	pps->loop_filter_across_tiles_enabled_flag =
1770 		channel->enable_loop_filter_across_tiles;
1771 	pps->pps_loop_filter_across_slices_enabled_flag =
1772 		channel->enable_loop_filter_across_slices;
1773 	pps->deblocking_filter_control_present_flag = 1;
1774 	pps->deblocking_filter_override_enabled_flag =
1775 		channel->enable_deblocking_filter_override;
1776 	pps->pps_beta_offset_div2 = BETA_OFFSET_DIV_2;
1777 	pps->pps_tc_offset_div2 = TC_OFFSET_DIV_2;
1778 
1779 	pps->lists_modification_present_flag = channel->enable_reordering;
1780 
1781 	size = nal_hevc_write_pps(&dev->plat_dev->dev, dest, n, pps);
1782 
1783 	kfree(pps);
1784 
1785 	return size;
1786 }
1787 
1788 static u64 allegro_put_buffer(struct allegro_channel *channel,
1789 			      struct list_head *list,
1790 			      struct vb2_v4l2_buffer *buffer)
1791 {
1792 	struct v4l2_m2m_buffer *b = container_of(buffer,
1793 						 struct v4l2_m2m_buffer, vb);
1794 	struct allegro_m2m_buffer *shadow = to_allegro_m2m_buffer(b);
1795 
1796 	mutex_lock(&channel->shadow_list_lock);
1797 	list_add_tail(&shadow->head, list);
1798 	mutex_unlock(&channel->shadow_list_lock);
1799 
1800 	return ptr_to_u64(buffer);
1801 }
1802 
1803 static struct vb2_v4l2_buffer *
1804 allegro_get_buffer(struct allegro_channel *channel,
1805 		   struct list_head *list, u64 handle)
1806 {
1807 	struct allegro_m2m_buffer *shadow, *tmp;
1808 	struct vb2_v4l2_buffer *buffer = NULL;
1809 
1810 	mutex_lock(&channel->shadow_list_lock);
1811 	list_for_each_entry_safe(shadow, tmp, list, head) {
1812 		if (handle == ptr_to_u64(&shadow->buf.vb)) {
1813 			buffer = &shadow->buf.vb;
1814 			list_del_init(&shadow->head);
1815 			break;
1816 		}
1817 	}
1818 	mutex_unlock(&channel->shadow_list_lock);
1819 
1820 	return buffer;
1821 }
1822 
1823 static void allegro_channel_finish_frame(struct allegro_channel *channel,
1824 		struct mcu_msg_encode_frame_response *msg)
1825 {
1826 	struct allegro_dev *dev = channel->dev;
1827 	struct vb2_v4l2_buffer *src_buf;
1828 	struct vb2_v4l2_buffer *dst_buf;
1829 	struct {
1830 		u32 offset;
1831 		u32 size;
1832 	} *partition;
1833 	enum vb2_buffer_state state = VB2_BUF_STATE_ERROR;
1834 	char *curr;
1835 	ssize_t len;
1836 	ssize_t free;
1837 
1838 	src_buf = allegro_get_buffer(channel, &channel->source_shadow_list,
1839 				     msg->src_handle);
1840 	if (!src_buf)
1841 		v4l2_warn(&dev->v4l2_dev,
1842 			  "channel %d: invalid source buffer\n",
1843 			  channel->mcu_channel_id);
1844 
1845 	dst_buf = allegro_get_buffer(channel, &channel->stream_shadow_list,
1846 				     msg->dst_handle);
1847 	if (!dst_buf)
1848 		v4l2_warn(&dev->v4l2_dev,
1849 			  "channel %d: invalid stream buffer\n",
1850 			  channel->mcu_channel_id);
1851 
1852 	if (!src_buf || !dst_buf)
1853 		goto err;
1854 
1855 	if (v4l2_m2m_is_last_draining_src_buf(channel->fh.m2m_ctx, src_buf)) {
1856 		dst_buf->flags |= V4L2_BUF_FLAG_LAST;
1857 		allegro_channel_eos_event(channel);
1858 		v4l2_m2m_mark_stopped(channel->fh.m2m_ctx);
1859 	}
1860 
1861 	dst_buf->sequence = channel->csequence++;
1862 
1863 	if (msg->error_code & AL_ERROR) {
1864 		v4l2_err(&dev->v4l2_dev,
1865 			 "channel %d: failed to encode frame: %s (%x)\n",
1866 			 channel->mcu_channel_id,
1867 			 allegro_err_to_string(msg->error_code),
1868 			 msg->error_code);
1869 		goto err;
1870 	}
1871 
1872 	if (msg->partition_table_size != 1) {
1873 		v4l2_warn(&dev->v4l2_dev,
1874 			  "channel %d: only handling first partition table entry (%d entries)\n",
1875 			  channel->mcu_channel_id, msg->partition_table_size);
1876 	}
1877 
1878 	if (msg->partition_table_offset +
1879 	    msg->partition_table_size * sizeof(*partition) >
1880 	    vb2_plane_size(&dst_buf->vb2_buf, 0)) {
1881 		v4l2_err(&dev->v4l2_dev,
1882 			 "channel %d: partition table outside of dst_buf\n",
1883 			 channel->mcu_channel_id);
1884 		goto err;
1885 	}
1886 
1887 	partition =
1888 	    vb2_plane_vaddr(&dst_buf->vb2_buf, 0) + msg->partition_table_offset;
1889 	if (partition->offset + partition->size >
1890 	    vb2_plane_size(&dst_buf->vb2_buf, 0)) {
1891 		v4l2_err(&dev->v4l2_dev,
1892 			 "channel %d: encoded frame is outside of dst_buf (offset 0x%x, size 0x%x)\n",
1893 			 channel->mcu_channel_id, partition->offset,
1894 			 partition->size);
1895 		goto err;
1896 	}
1897 
1898 	v4l2_dbg(2, debug, &dev->v4l2_dev,
1899 		 "channel %d: encoded frame of size %d is at offset 0x%x\n",
1900 		 channel->mcu_channel_id, partition->size, partition->offset);
1901 
1902 	/*
1903 	 * The payload must include the data before the partition offset,
1904 	 * because we will put the sps and pps data there.
1905 	 */
1906 	vb2_set_plane_payload(&dst_buf->vb2_buf, 0,
1907 			      partition->offset + partition->size);
1908 
1909 	curr = vb2_plane_vaddr(&dst_buf->vb2_buf, 0);
1910 	free = partition->offset;
1911 
1912 	if (channel->codec == V4L2_PIX_FMT_HEVC && msg->is_idr) {
1913 		len = allegro_hevc_write_vps(channel, curr, free);
1914 		if (len < 0) {
1915 			v4l2_err(&dev->v4l2_dev,
1916 				 "not enough space for video parameter set: %zd left\n",
1917 				 free);
1918 			goto err;
1919 		}
1920 		curr += len;
1921 		free -= len;
1922 		v4l2_dbg(1, debug, &dev->v4l2_dev,
1923 			 "channel %d: wrote %zd byte VPS nal unit\n",
1924 			 channel->mcu_channel_id, len);
1925 	}
1926 
1927 	if (msg->is_idr) {
1928 		if (channel->codec == V4L2_PIX_FMT_H264)
1929 			len = allegro_h264_write_sps(channel, curr, free);
1930 		else
1931 			len = allegro_hevc_write_sps(channel, curr, free);
1932 		if (len < 0) {
1933 			v4l2_err(&dev->v4l2_dev,
1934 				 "not enough space for sequence parameter set: %zd left\n",
1935 				 free);
1936 			goto err;
1937 		}
1938 		curr += len;
1939 		free -= len;
1940 		v4l2_dbg(1, debug, &dev->v4l2_dev,
1941 			 "channel %d: wrote %zd byte SPS nal unit\n",
1942 			 channel->mcu_channel_id, len);
1943 	}
1944 
1945 	if (msg->slice_type == AL_ENC_SLICE_TYPE_I) {
1946 		if (channel->codec == V4L2_PIX_FMT_H264)
1947 			len = allegro_h264_write_pps(channel, curr, free);
1948 		else
1949 			len = allegro_hevc_write_pps(channel, msg, curr, free);
1950 		if (len < 0) {
1951 			v4l2_err(&dev->v4l2_dev,
1952 				 "not enough space for picture parameter set: %zd left\n",
1953 				 free);
1954 			goto err;
1955 		}
1956 		curr += len;
1957 		free -= len;
1958 		v4l2_dbg(1, debug, &dev->v4l2_dev,
1959 			 "channel %d: wrote %zd byte PPS nal unit\n",
1960 			 channel->mcu_channel_id, len);
1961 	}
1962 
1963 	if (msg->slice_type != AL_ENC_SLICE_TYPE_I && !msg->is_idr) {
1964 		dst_buf->vb2_buf.planes[0].data_offset = free;
1965 		free = 0;
1966 	} else {
1967 		if (channel->codec == V4L2_PIX_FMT_H264)
1968 			len = nal_h264_write_filler(&dev->plat_dev->dev, curr, free);
1969 		else
1970 			len = nal_hevc_write_filler(&dev->plat_dev->dev, curr, free);
1971 		if (len < 0) {
1972 			v4l2_err(&dev->v4l2_dev,
1973 				 "failed to write %zd filler data\n", free);
1974 			goto err;
1975 		}
1976 		curr += len;
1977 		free -= len;
1978 		v4l2_dbg(2, debug, &dev->v4l2_dev,
1979 			 "channel %d: wrote %zd bytes filler nal unit\n",
1980 			 channel->mcu_channel_id, len);
1981 	}
1982 
1983 	if (free != 0) {
1984 		v4l2_err(&dev->v4l2_dev,
1985 			 "non-VCL NAL units do not fill space until VCL NAL unit: %zd bytes left\n",
1986 			 free);
1987 		goto err;
1988 	}
1989 
1990 	state = VB2_BUF_STATE_DONE;
1991 
1992 	v4l2_m2m_buf_copy_metadata(src_buf, dst_buf, false);
1993 	if (msg->is_idr)
1994 		dst_buf->flags |= V4L2_BUF_FLAG_KEYFRAME;
1995 	else
1996 		dst_buf->flags |= V4L2_BUF_FLAG_PFRAME;
1997 
1998 	v4l2_dbg(1, debug, &dev->v4l2_dev,
1999 		 "channel %d: encoded frame #%03d (%s%s, QP %d, %d bytes)\n",
2000 		 channel->mcu_channel_id,
2001 		 dst_buf->sequence,
2002 		 msg->is_idr ? "IDR, " : "",
2003 		 msg->slice_type == AL_ENC_SLICE_TYPE_I ? "I slice" :
2004 		 msg->slice_type == AL_ENC_SLICE_TYPE_P ? "P slice" : "unknown",
2005 		 msg->qp, partition->size);
2006 
2007 err:
2008 	if (src_buf)
2009 		v4l2_m2m_buf_done(src_buf, VB2_BUF_STATE_DONE);
2010 
2011 	if (dst_buf)
2012 		v4l2_m2m_buf_done(dst_buf, state);
2013 }
2014 
2015 static int allegro_handle_init(struct allegro_dev *dev,
2016 			       struct mcu_msg_init_response *msg)
2017 {
2018 	complete(&dev->init_complete);
2019 
2020 	return 0;
2021 }
2022 
2023 static int
2024 allegro_handle_create_channel(struct allegro_dev *dev,
2025 			      struct mcu_msg_create_channel_response *msg)
2026 {
2027 	struct allegro_channel *channel;
2028 	int err = 0;
2029 	struct create_channel_param param;
2030 
2031 	channel = allegro_find_channel_by_user_id(dev, msg->user_id);
2032 	if (IS_ERR(channel)) {
2033 		v4l2_warn(&dev->v4l2_dev,
2034 			  "received %s for unknown user %d\n",
2035 			  msg_type_name(msg->header.type),
2036 			  msg->user_id);
2037 		return -EINVAL;
2038 	}
2039 
2040 	if (msg->error_code) {
2041 		v4l2_err(&dev->v4l2_dev,
2042 			 "user %d: mcu failed to create channel: %s (%x)\n",
2043 			 channel->user_id,
2044 			 allegro_err_to_string(msg->error_code),
2045 			 msg->error_code);
2046 		err = -EIO;
2047 		goto out;
2048 	}
2049 
2050 	channel->mcu_channel_id = msg->channel_id;
2051 	v4l2_dbg(1, debug, &dev->v4l2_dev,
2052 		 "user %d: channel has channel id %d\n",
2053 		 channel->user_id, channel->mcu_channel_id);
2054 
2055 	err = allegro_decode_config_blob(&param, msg, channel->config_blob.vaddr);
2056 	allegro_free_buffer(channel->dev, &channel->config_blob);
2057 	if (err)
2058 		goto out;
2059 
2060 	channel->num_ref_idx_l0 = param.num_ref_idx_l0;
2061 	channel->num_ref_idx_l1 = param.num_ref_idx_l1;
2062 
2063 	v4l2_dbg(1, debug, &dev->v4l2_dev,
2064 		 "channel %d: intermediate buffers: %d x %d bytes\n",
2065 		 channel->mcu_channel_id,
2066 		 msg->int_buffers_count, msg->int_buffers_size);
2067 	err = allocate_intermediate_buffers(channel, msg->int_buffers_count,
2068 					    msg->int_buffers_size);
2069 	if (err) {
2070 		v4l2_err(&dev->v4l2_dev,
2071 			 "channel %d: failed to allocate intermediate buffers\n",
2072 			 channel->mcu_channel_id);
2073 		goto out;
2074 	}
2075 	err = allegro_mcu_push_buffer_intermediate(channel);
2076 	if (err)
2077 		goto out;
2078 
2079 	v4l2_dbg(1, debug, &dev->v4l2_dev,
2080 		 "channel %d: reference buffers: %d x %d bytes\n",
2081 		 channel->mcu_channel_id,
2082 		 msg->rec_buffers_count, msg->rec_buffers_size);
2083 	err = allocate_reference_buffers(channel, msg->rec_buffers_count,
2084 					 msg->rec_buffers_size);
2085 	if (err) {
2086 		v4l2_err(&dev->v4l2_dev,
2087 			 "channel %d: failed to allocate reference buffers\n",
2088 			 channel->mcu_channel_id);
2089 		goto out;
2090 	}
2091 	err = allegro_mcu_push_buffer_reference(channel);
2092 	if (err)
2093 		goto out;
2094 
2095 out:
2096 	channel->error = err;
2097 	complete(&channel->completion);
2098 
2099 	/* Handled successfully, error is passed via channel->error */
2100 	return 0;
2101 }
2102 
2103 static int
2104 allegro_handle_destroy_channel(struct allegro_dev *dev,
2105 			       struct mcu_msg_destroy_channel_response *msg)
2106 {
2107 	struct allegro_channel *channel;
2108 
2109 	channel = allegro_find_channel_by_channel_id(dev, msg->channel_id);
2110 	if (IS_ERR(channel)) {
2111 		v4l2_err(&dev->v4l2_dev,
2112 			 "received %s for unknown channel %d\n",
2113 			 msg_type_name(msg->header.type),
2114 			 msg->channel_id);
2115 		return -EINVAL;
2116 	}
2117 
2118 	v4l2_dbg(2, debug, &dev->v4l2_dev,
2119 		 "user %d: vcu destroyed channel %d\n",
2120 		 channel->user_id, channel->mcu_channel_id);
2121 	complete(&channel->completion);
2122 
2123 	return 0;
2124 }
2125 
2126 static int
2127 allegro_handle_encode_frame(struct allegro_dev *dev,
2128 			    struct mcu_msg_encode_frame_response *msg)
2129 {
2130 	struct allegro_channel *channel;
2131 
2132 	channel = allegro_find_channel_by_channel_id(dev, msg->channel_id);
2133 	if (IS_ERR(channel)) {
2134 		v4l2_err(&dev->v4l2_dev,
2135 			 "received %s for unknown channel %d\n",
2136 			 msg_type_name(msg->header.type),
2137 			 msg->channel_id);
2138 		return -EINVAL;
2139 	}
2140 
2141 	allegro_channel_finish_frame(channel, msg);
2142 
2143 	return 0;
2144 }
2145 
2146 static void allegro_handle_message(struct allegro_dev *dev,
2147 				   union mcu_msg_response *msg)
2148 {
2149 	switch (msg->header.type) {
2150 	case MCU_MSG_TYPE_INIT:
2151 		allegro_handle_init(dev, &msg->init);
2152 		break;
2153 	case MCU_MSG_TYPE_CREATE_CHANNEL:
2154 		allegro_handle_create_channel(dev, &msg->create_channel);
2155 		break;
2156 	case MCU_MSG_TYPE_DESTROY_CHANNEL:
2157 		allegro_handle_destroy_channel(dev, &msg->destroy_channel);
2158 		break;
2159 	case MCU_MSG_TYPE_ENCODE_FRAME:
2160 		allegro_handle_encode_frame(dev, &msg->encode_frame);
2161 		break;
2162 	default:
2163 		v4l2_warn(&dev->v4l2_dev,
2164 			  "%s: unknown message %s\n",
2165 			  __func__, msg_type_name(msg->header.type));
2166 		break;
2167 	}
2168 }
2169 
2170 static irqreturn_t allegro_hardirq(int irq, void *data)
2171 {
2172 	struct allegro_dev *dev = data;
2173 	unsigned int status;
2174 
2175 	regmap_read(dev->regmap, AL5_ITC_CPU_IRQ_STA, &status);
2176 	if (!(status & AL5_ITC_CPU_IRQ_STA_TRIGGERED))
2177 		return IRQ_NONE;
2178 
2179 	regmap_write(dev->regmap, AL5_ITC_CPU_IRQ_CLR, status);
2180 
2181 	return IRQ_WAKE_THREAD;
2182 }
2183 
2184 static irqreturn_t allegro_irq_thread(int irq, void *data)
2185 {
2186 	struct allegro_dev *dev = data;
2187 
2188 	allegro_mbox_notify(dev->mbox_status);
2189 
2190 	return IRQ_HANDLED;
2191 }
2192 
2193 static void allegro_copy_firmware(struct allegro_dev *dev,
2194 				  const u8 * const buf, size_t size)
2195 {
2196 	int err = 0;
2197 
2198 	v4l2_dbg(1, debug, &dev->v4l2_dev,
2199 		 "copy mcu firmware (%zu B) to SRAM\n", size);
2200 	err = regmap_bulk_write(dev->sram, 0x0, buf, size / 4);
2201 	if (err)
2202 		v4l2_err(&dev->v4l2_dev,
2203 			 "failed to copy firmware: %d\n", err);
2204 }
2205 
2206 static void allegro_copy_fw_codec(struct allegro_dev *dev,
2207 				  const u8 * const buf, size_t size)
2208 {
2209 	int err;
2210 	dma_addr_t icache_offset, dcache_offset;
2211 
2212 	/*
2213 	 * The downstream allocates 600 KB for the codec firmware to have some
2214 	 * extra space for "possible extensions." My tests were fine with
2215 	 * allocating just enough memory for the actual firmware, but I am not
2216 	 * sure that the firmware really does not use the remaining space.
2217 	 */
2218 	err = allegro_alloc_buffer(dev, &dev->firmware, size);
2219 	if (err) {
2220 		v4l2_err(&dev->v4l2_dev,
2221 			 "failed to allocate %zu bytes for firmware\n", size);
2222 		return;
2223 	}
2224 
2225 	v4l2_dbg(1, debug, &dev->v4l2_dev,
2226 		 "copy codec firmware (%zd B) to phys %pad\n",
2227 		 size, &dev->firmware.paddr);
2228 	memcpy(dev->firmware.vaddr, buf, size);
2229 
2230 	regmap_write(dev->regmap, AXI_ADDR_OFFSET_IP,
2231 		     upper_32_bits(dev->firmware.paddr));
2232 
2233 	icache_offset = dev->firmware.paddr - MCU_CACHE_OFFSET;
2234 	v4l2_dbg(2, debug, &dev->v4l2_dev,
2235 		 "icache_offset: msb = 0x%x, lsb = 0x%x\n",
2236 		 upper_32_bits(icache_offset), lower_32_bits(icache_offset));
2237 	regmap_write(dev->regmap, AL5_ICACHE_ADDR_OFFSET_MSB,
2238 		     upper_32_bits(icache_offset));
2239 	regmap_write(dev->regmap, AL5_ICACHE_ADDR_OFFSET_LSB,
2240 		     lower_32_bits(icache_offset));
2241 
2242 	dcache_offset =
2243 	    (dev->firmware.paddr & 0xffffffff00000000ULL) - MCU_CACHE_OFFSET;
2244 	v4l2_dbg(2, debug, &dev->v4l2_dev,
2245 		 "dcache_offset: msb = 0x%x, lsb = 0x%x\n",
2246 		 upper_32_bits(dcache_offset), lower_32_bits(dcache_offset));
2247 	regmap_write(dev->regmap, AL5_DCACHE_ADDR_OFFSET_MSB,
2248 		     upper_32_bits(dcache_offset));
2249 	regmap_write(dev->regmap, AL5_DCACHE_ADDR_OFFSET_LSB,
2250 		     lower_32_bits(dcache_offset));
2251 }
2252 
2253 static void allegro_free_fw_codec(struct allegro_dev *dev)
2254 {
2255 	allegro_free_buffer(dev, &dev->firmware);
2256 }
2257 
2258 /*
2259  * Control functions for the MCU
2260  */
2261 
2262 static int allegro_mcu_enable_interrupts(struct allegro_dev *dev)
2263 {
2264 	return regmap_write(dev->regmap, AL5_ITC_CPU_IRQ_MSK, BIT(0));
2265 }
2266 
2267 static int allegro_mcu_disable_interrupts(struct allegro_dev *dev)
2268 {
2269 	return regmap_write(dev->regmap, AL5_ITC_CPU_IRQ_MSK, 0);
2270 }
2271 
2272 static int allegro_mcu_wait_for_sleep(struct allegro_dev *dev)
2273 {
2274 	unsigned long timeout;
2275 	unsigned int status;
2276 
2277 	timeout = jiffies + msecs_to_jiffies(100);
2278 	while (regmap_read(dev->regmap, AL5_MCU_STA, &status) == 0 &&
2279 	       status != AL5_MCU_STA_SLEEP) {
2280 		if (time_after(jiffies, timeout))
2281 			return -ETIMEDOUT;
2282 		cpu_relax();
2283 	}
2284 
2285 	return 0;
2286 }
2287 
2288 static int allegro_mcu_start(struct allegro_dev *dev)
2289 {
2290 	unsigned long timeout;
2291 	unsigned int status;
2292 	int err;
2293 
2294 	err = regmap_write(dev->regmap, AL5_MCU_WAKEUP, BIT(0));
2295 	if (err)
2296 		return err;
2297 
2298 	timeout = jiffies + msecs_to_jiffies(100);
2299 	while (regmap_read(dev->regmap, AL5_MCU_STA, &status) == 0 &&
2300 	       status == AL5_MCU_STA_SLEEP) {
2301 		if (time_after(jiffies, timeout))
2302 			return -ETIMEDOUT;
2303 		cpu_relax();
2304 	}
2305 
2306 	err = regmap_write(dev->regmap, AL5_MCU_WAKEUP, 0);
2307 	if (err)
2308 		return err;
2309 
2310 	return 0;
2311 }
2312 
2313 static int allegro_mcu_reset(struct allegro_dev *dev)
2314 {
2315 	int err;
2316 
2317 	/*
2318 	 * Ensure that the AL5_MCU_WAKEUP bit is set to 0 otherwise the mcu
2319 	 * does not go to sleep after the reset.
2320 	 */
2321 	err = regmap_write(dev->regmap, AL5_MCU_WAKEUP, 0);
2322 	if (err)
2323 		return err;
2324 
2325 	err = regmap_write(dev->regmap,
2326 			   AL5_MCU_RESET_MODE, AL5_MCU_RESET_MODE_SLEEP);
2327 	if (err < 0)
2328 		return err;
2329 
2330 	err = regmap_write(dev->regmap, AL5_MCU_RESET, AL5_MCU_RESET_SOFT);
2331 	if (err < 0)
2332 		return err;
2333 
2334 	return allegro_mcu_wait_for_sleep(dev);
2335 }
2336 
2337 static void allegro_mcu_interrupt(struct allegro_dev *dev)
2338 {
2339 	regmap_write(dev->regmap, AL5_MCU_INTERRUPT, BIT(0));
2340 }
2341 
2342 static void allegro_destroy_channel(struct allegro_channel *channel)
2343 {
2344 	struct allegro_dev *dev = channel->dev;
2345 	unsigned long timeout;
2346 
2347 	if (channel_exists(channel)) {
2348 		reinit_completion(&channel->completion);
2349 		allegro_mcu_send_destroy_channel(dev, channel);
2350 		timeout = wait_for_completion_timeout(&channel->completion,
2351 						      msecs_to_jiffies(5000));
2352 		if (timeout == 0)
2353 			v4l2_warn(&dev->v4l2_dev,
2354 				  "channel %d: timeout while destroying\n",
2355 				  channel->mcu_channel_id);
2356 
2357 		channel->mcu_channel_id = -1;
2358 	}
2359 
2360 	destroy_intermediate_buffers(channel);
2361 	destroy_reference_buffers(channel);
2362 
2363 	v4l2_ctrl_grab(channel->mpeg_video_h264_profile, false);
2364 	v4l2_ctrl_grab(channel->mpeg_video_h264_level, false);
2365 	v4l2_ctrl_grab(channel->mpeg_video_h264_i_frame_qp, false);
2366 	v4l2_ctrl_grab(channel->mpeg_video_h264_max_qp, false);
2367 	v4l2_ctrl_grab(channel->mpeg_video_h264_min_qp, false);
2368 	v4l2_ctrl_grab(channel->mpeg_video_h264_p_frame_qp, false);
2369 	v4l2_ctrl_grab(channel->mpeg_video_h264_b_frame_qp, false);
2370 
2371 	v4l2_ctrl_grab(channel->mpeg_video_hevc_profile, false);
2372 	v4l2_ctrl_grab(channel->mpeg_video_hevc_level, false);
2373 	v4l2_ctrl_grab(channel->mpeg_video_hevc_tier, false);
2374 	v4l2_ctrl_grab(channel->mpeg_video_hevc_i_frame_qp, false);
2375 	v4l2_ctrl_grab(channel->mpeg_video_hevc_max_qp, false);
2376 	v4l2_ctrl_grab(channel->mpeg_video_hevc_min_qp, false);
2377 	v4l2_ctrl_grab(channel->mpeg_video_hevc_p_frame_qp, false);
2378 	v4l2_ctrl_grab(channel->mpeg_video_hevc_b_frame_qp, false);
2379 
2380 	v4l2_ctrl_grab(channel->mpeg_video_frame_rc_enable, false);
2381 	v4l2_ctrl_grab(channel->mpeg_video_bitrate_mode, false);
2382 	v4l2_ctrl_grab(channel->mpeg_video_bitrate, false);
2383 	v4l2_ctrl_grab(channel->mpeg_video_bitrate_peak, false);
2384 	v4l2_ctrl_grab(channel->mpeg_video_cpb_size, false);
2385 	v4l2_ctrl_grab(channel->mpeg_video_gop_size, false);
2386 
2387 	if (channel->user_id != -1) {
2388 		clear_bit(channel->user_id, &dev->channel_user_ids);
2389 		channel->user_id = -1;
2390 	}
2391 }
2392 
2393 /*
2394  * Create the MCU channel
2395  *
2396  * After the channel has been created, the picture size, format, colorspace
2397  * and framerate are fixed. Also the codec, profile, bitrate, etc. cannot be
2398  * changed anymore.
2399  *
2400  * The channel can be created only once. The MCU will accept source buffers
2401  * and stream buffers only after a channel has been created.
2402  */
2403 static int allegro_create_channel(struct allegro_channel *channel)
2404 {
2405 	struct allegro_dev *dev = channel->dev;
2406 	unsigned long timeout;
2407 
2408 	if (channel_exists(channel)) {
2409 		v4l2_warn(&dev->v4l2_dev,
2410 			  "channel already exists\n");
2411 		return 0;
2412 	}
2413 
2414 	channel->user_id = allegro_next_user_id(dev);
2415 	if (channel->user_id < 0) {
2416 		v4l2_err(&dev->v4l2_dev,
2417 			 "no free channels available\n");
2418 		return -EBUSY;
2419 	}
2420 	set_bit(channel->user_id, &dev->channel_user_ids);
2421 
2422 	v4l2_dbg(1, debug, &dev->v4l2_dev,
2423 		 "user %d: creating channel (%4.4s, %dx%d@%d)\n",
2424 		 channel->user_id,
2425 		 (char *)&channel->codec, channel->width, channel->height,
2426 		 DIV_ROUND_UP(channel->framerate.numerator,
2427 			      channel->framerate.denominator));
2428 
2429 	v4l2_ctrl_grab(channel->mpeg_video_h264_profile, true);
2430 	v4l2_ctrl_grab(channel->mpeg_video_h264_level, true);
2431 	v4l2_ctrl_grab(channel->mpeg_video_h264_i_frame_qp, true);
2432 	v4l2_ctrl_grab(channel->mpeg_video_h264_max_qp, true);
2433 	v4l2_ctrl_grab(channel->mpeg_video_h264_min_qp, true);
2434 	v4l2_ctrl_grab(channel->mpeg_video_h264_p_frame_qp, true);
2435 	v4l2_ctrl_grab(channel->mpeg_video_h264_b_frame_qp, true);
2436 
2437 	v4l2_ctrl_grab(channel->mpeg_video_hevc_profile, true);
2438 	v4l2_ctrl_grab(channel->mpeg_video_hevc_level, true);
2439 	v4l2_ctrl_grab(channel->mpeg_video_hevc_tier, true);
2440 	v4l2_ctrl_grab(channel->mpeg_video_hevc_i_frame_qp, true);
2441 	v4l2_ctrl_grab(channel->mpeg_video_hevc_max_qp, true);
2442 	v4l2_ctrl_grab(channel->mpeg_video_hevc_min_qp, true);
2443 	v4l2_ctrl_grab(channel->mpeg_video_hevc_p_frame_qp, true);
2444 	v4l2_ctrl_grab(channel->mpeg_video_hevc_b_frame_qp, true);
2445 
2446 	v4l2_ctrl_grab(channel->mpeg_video_frame_rc_enable, true);
2447 	v4l2_ctrl_grab(channel->mpeg_video_bitrate_mode, true);
2448 	v4l2_ctrl_grab(channel->mpeg_video_bitrate, true);
2449 	v4l2_ctrl_grab(channel->mpeg_video_bitrate_peak, true);
2450 	v4l2_ctrl_grab(channel->mpeg_video_cpb_size, true);
2451 	v4l2_ctrl_grab(channel->mpeg_video_gop_size, true);
2452 
2453 	reinit_completion(&channel->completion);
2454 	allegro_mcu_send_create_channel(dev, channel);
2455 	timeout = wait_for_completion_timeout(&channel->completion,
2456 					      msecs_to_jiffies(5000));
2457 	if (timeout == 0)
2458 		channel->error = -ETIMEDOUT;
2459 	if (channel->error)
2460 		goto err;
2461 
2462 	v4l2_dbg(1, debug, &dev->v4l2_dev,
2463 		 "channel %d: accepting buffers\n",
2464 		 channel->mcu_channel_id);
2465 
2466 	return 0;
2467 
2468 err:
2469 	allegro_destroy_channel(channel);
2470 
2471 	return channel->error;
2472 }
2473 
2474 /**
2475  * allegro_channel_adjust() - Adjust channel parameters to current format
2476  * @channel: the channel to adjust
2477  *
2478  * Various parameters of a channel and their limits depend on the currently
2479  * set format. Adjust the parameters after a format change in one go.
2480  */
2481 static void allegro_channel_adjust(struct allegro_channel *channel)
2482 {
2483 	struct allegro_dev *dev = channel->dev;
2484 	u32 codec = channel->codec;
2485 	struct v4l2_ctrl *ctrl;
2486 	s64 min;
2487 	s64 max;
2488 
2489 	channel->sizeimage_encoded =
2490 		estimate_stream_size(channel->width, channel->height);
2491 
2492 	if (codec == V4L2_PIX_FMT_H264) {
2493 		ctrl = channel->mpeg_video_h264_level;
2494 		min = select_minimum_h264_level(channel->width, channel->height);
2495 	} else {
2496 		ctrl = channel->mpeg_video_hevc_level;
2497 		min = select_minimum_hevc_level(channel->width, channel->height);
2498 	}
2499 	if (ctrl->minimum > min)
2500 		v4l2_dbg(1, debug, &dev->v4l2_dev,
2501 			 "%s.minimum: %lld -> %lld\n",
2502 			 v4l2_ctrl_get_name(ctrl->id), ctrl->minimum, min);
2503 	v4l2_ctrl_lock(ctrl);
2504 	__v4l2_ctrl_modify_range(ctrl, min, ctrl->maximum,
2505 				 ctrl->step, ctrl->default_value);
2506 	v4l2_ctrl_unlock(ctrl);
2507 
2508 	ctrl = channel->mpeg_video_bitrate;
2509 	if (codec == V4L2_PIX_FMT_H264)
2510 		max = h264_maximum_bitrate(v4l2_ctrl_g_ctrl(channel->mpeg_video_h264_level));
2511 	else
2512 		max = hevc_maximum_bitrate(v4l2_ctrl_g_ctrl(channel->mpeg_video_hevc_level));
2513 	if (ctrl->maximum < max)
2514 		v4l2_dbg(1, debug, &dev->v4l2_dev,
2515 			 "%s: maximum: %lld -> %lld\n",
2516 			 v4l2_ctrl_get_name(ctrl->id), ctrl->maximum, max);
2517 	v4l2_ctrl_lock(ctrl);
2518 	__v4l2_ctrl_modify_range(ctrl, ctrl->minimum, max,
2519 				 ctrl->step, ctrl->default_value);
2520 	v4l2_ctrl_unlock(ctrl);
2521 
2522 	ctrl = channel->mpeg_video_bitrate_peak;
2523 	v4l2_ctrl_lock(ctrl);
2524 	__v4l2_ctrl_modify_range(ctrl, ctrl->minimum, max,
2525 				 ctrl->step, ctrl->default_value);
2526 	v4l2_ctrl_unlock(ctrl);
2527 
2528 	v4l2_ctrl_activate(channel->mpeg_video_h264_profile,
2529 			   codec == V4L2_PIX_FMT_H264);
2530 	v4l2_ctrl_activate(channel->mpeg_video_h264_level,
2531 			   codec == V4L2_PIX_FMT_H264);
2532 	v4l2_ctrl_activate(channel->mpeg_video_h264_i_frame_qp,
2533 			   codec == V4L2_PIX_FMT_H264);
2534 	v4l2_ctrl_activate(channel->mpeg_video_h264_max_qp,
2535 			   codec == V4L2_PIX_FMT_H264);
2536 	v4l2_ctrl_activate(channel->mpeg_video_h264_min_qp,
2537 			   codec == V4L2_PIX_FMT_H264);
2538 	v4l2_ctrl_activate(channel->mpeg_video_h264_p_frame_qp,
2539 			   codec == V4L2_PIX_FMT_H264);
2540 	v4l2_ctrl_activate(channel->mpeg_video_h264_b_frame_qp,
2541 			   codec == V4L2_PIX_FMT_H264);
2542 
2543 	v4l2_ctrl_activate(channel->mpeg_video_hevc_profile,
2544 			   codec == V4L2_PIX_FMT_HEVC);
2545 	v4l2_ctrl_activate(channel->mpeg_video_hevc_level,
2546 			   codec == V4L2_PIX_FMT_HEVC);
2547 	v4l2_ctrl_activate(channel->mpeg_video_hevc_tier,
2548 			   codec == V4L2_PIX_FMT_HEVC);
2549 	v4l2_ctrl_activate(channel->mpeg_video_hevc_i_frame_qp,
2550 			   codec == V4L2_PIX_FMT_HEVC);
2551 	v4l2_ctrl_activate(channel->mpeg_video_hevc_max_qp,
2552 			   codec == V4L2_PIX_FMT_HEVC);
2553 	v4l2_ctrl_activate(channel->mpeg_video_hevc_min_qp,
2554 			   codec == V4L2_PIX_FMT_HEVC);
2555 	v4l2_ctrl_activate(channel->mpeg_video_hevc_p_frame_qp,
2556 			   codec == V4L2_PIX_FMT_HEVC);
2557 	v4l2_ctrl_activate(channel->mpeg_video_hevc_b_frame_qp,
2558 			   codec == V4L2_PIX_FMT_HEVC);
2559 
2560 	if (codec == V4L2_PIX_FMT_H264)
2561 		channel->log2_max_frame_num = LOG2_MAX_FRAME_NUM;
2562 	channel->temporal_mvp_enable = true;
2563 	channel->dbf_ovr_en = (codec == V4L2_PIX_FMT_H264);
2564 	channel->enable_deblocking_filter_override = (codec == V4L2_PIX_FMT_HEVC);
2565 	channel->enable_reordering = (codec == V4L2_PIX_FMT_HEVC);
2566 	channel->enable_loop_filter_across_tiles = true;
2567 	channel->enable_loop_filter_across_slices = true;
2568 
2569 	if (codec == V4L2_PIX_FMT_H264) {
2570 		channel->b_hrz_me_range = 8;
2571 		channel->b_vrt_me_range = 8;
2572 		channel->p_hrz_me_range = 16;
2573 		channel->p_vrt_me_range = 16;
2574 		channel->max_cu_size = ilog2(16);
2575 		channel->min_cu_size = ilog2(8);
2576 		channel->max_tu_size = ilog2(4);
2577 		channel->min_tu_size = ilog2(4);
2578 	} else {
2579 		channel->b_hrz_me_range = 16;
2580 		channel->b_vrt_me_range = 16;
2581 		channel->p_hrz_me_range = 32;
2582 		channel->p_vrt_me_range = 32;
2583 		channel->max_cu_size = ilog2(32);
2584 		channel->min_cu_size = ilog2(8);
2585 		channel->max_tu_size = ilog2(32);
2586 		channel->min_tu_size = ilog2(4);
2587 	}
2588 	channel->max_transfo_depth_intra = 1;
2589 	channel->max_transfo_depth_inter = 1;
2590 }
2591 
2592 static void allegro_set_default_params(struct allegro_channel *channel)
2593 {
2594 	channel->width = ALLEGRO_WIDTH_DEFAULT;
2595 	channel->height = ALLEGRO_HEIGHT_DEFAULT;
2596 	channel->stride = round_up(channel->width, 32);
2597 	channel->framerate = ALLEGRO_FRAMERATE_DEFAULT;
2598 
2599 	channel->colorspace = V4L2_COLORSPACE_REC709;
2600 	channel->ycbcr_enc = V4L2_YCBCR_ENC_DEFAULT;
2601 	channel->quantization = V4L2_QUANTIZATION_DEFAULT;
2602 	channel->xfer_func = V4L2_XFER_FUNC_DEFAULT;
2603 
2604 	channel->pixelformat = V4L2_PIX_FMT_NV12;
2605 	channel->sizeimage_raw = channel->stride * channel->height * 3 / 2;
2606 
2607 	channel->codec = V4L2_PIX_FMT_H264;
2608 }
2609 
2610 static int allegro_queue_setup(struct vb2_queue *vq,
2611 			       unsigned int *nbuffers, unsigned int *nplanes,
2612 			       unsigned int sizes[],
2613 			       struct device *alloc_devs[])
2614 {
2615 	struct allegro_channel *channel = vb2_get_drv_priv(vq);
2616 	struct allegro_dev *dev = channel->dev;
2617 
2618 	v4l2_dbg(2, debug, &dev->v4l2_dev,
2619 		 "%s: queue setup[%s]: nplanes = %d\n",
2620 		 V4L2_TYPE_IS_OUTPUT(vq->type) ? "output" : "capture",
2621 		 *nplanes == 0 ? "REQBUFS" : "CREATE_BUFS", *nplanes);
2622 
2623 	if (*nplanes != 0) {
2624 		if (V4L2_TYPE_IS_OUTPUT(vq->type)) {
2625 			if (sizes[0] < channel->sizeimage_raw)
2626 				return -EINVAL;
2627 		} else {
2628 			if (sizes[0] < channel->sizeimage_encoded)
2629 				return -EINVAL;
2630 		}
2631 	} else {
2632 		*nplanes = 1;
2633 		if (V4L2_TYPE_IS_OUTPUT(vq->type))
2634 			sizes[0] = channel->sizeimage_raw;
2635 		else
2636 			sizes[0] = channel->sizeimage_encoded;
2637 	}
2638 
2639 	return 0;
2640 }
2641 
2642 static int allegro_buf_prepare(struct vb2_buffer *vb)
2643 {
2644 	struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
2645 	struct allegro_channel *channel = vb2_get_drv_priv(vb->vb2_queue);
2646 	struct allegro_dev *dev = channel->dev;
2647 
2648 	if (V4L2_TYPE_IS_OUTPUT(vb->vb2_queue->type)) {
2649 		if (vbuf->field == V4L2_FIELD_ANY)
2650 			vbuf->field = V4L2_FIELD_NONE;
2651 		if (vbuf->field != V4L2_FIELD_NONE) {
2652 			v4l2_err(&dev->v4l2_dev,
2653 				 "channel %d: unsupported field\n",
2654 				 channel->mcu_channel_id);
2655 			return -EINVAL;
2656 		}
2657 	}
2658 
2659 	return 0;
2660 }
2661 
2662 static void allegro_buf_queue(struct vb2_buffer *vb)
2663 {
2664 	struct allegro_channel *channel = vb2_get_drv_priv(vb->vb2_queue);
2665 	struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
2666 	struct vb2_queue *q = vb->vb2_queue;
2667 
2668 	if (V4L2_TYPE_IS_CAPTURE(q->type) &&
2669 	    vb2_is_streaming(q) &&
2670 	    v4l2_m2m_dst_buf_is_last(channel->fh.m2m_ctx)) {
2671 		unsigned int i;
2672 
2673 		for (i = 0; i < vb->num_planes; i++)
2674 			vb->planes[i].bytesused = 0;
2675 
2676 		vbuf->field = V4L2_FIELD_NONE;
2677 		vbuf->sequence = channel->csequence++;
2678 
2679 		v4l2_m2m_last_buffer_done(channel->fh.m2m_ctx, vbuf);
2680 		allegro_channel_eos_event(channel);
2681 		return;
2682 	}
2683 
2684 	v4l2_m2m_buf_queue(channel->fh.m2m_ctx, vbuf);
2685 }
2686 
2687 static int allegro_start_streaming(struct vb2_queue *q, unsigned int count)
2688 {
2689 	struct allegro_channel *channel = vb2_get_drv_priv(q);
2690 	struct allegro_dev *dev = channel->dev;
2691 
2692 	v4l2_dbg(2, debug, &dev->v4l2_dev,
2693 		 "%s: start streaming\n",
2694 		 V4L2_TYPE_IS_OUTPUT(q->type) ? "output" : "capture");
2695 
2696 	v4l2_m2m_update_start_streaming_state(channel->fh.m2m_ctx, q);
2697 
2698 	if (V4L2_TYPE_IS_OUTPUT(q->type))
2699 		channel->osequence = 0;
2700 	else
2701 		channel->csequence = 0;
2702 
2703 	return 0;
2704 }
2705 
2706 static void allegro_stop_streaming(struct vb2_queue *q)
2707 {
2708 	struct allegro_channel *channel = vb2_get_drv_priv(q);
2709 	struct allegro_dev *dev = channel->dev;
2710 	struct vb2_v4l2_buffer *buffer;
2711 	struct allegro_m2m_buffer *shadow, *tmp;
2712 
2713 	v4l2_dbg(2, debug, &dev->v4l2_dev,
2714 		 "%s: stop streaming\n",
2715 		 V4L2_TYPE_IS_OUTPUT(q->type) ? "output" : "capture");
2716 
2717 	if (V4L2_TYPE_IS_OUTPUT(q->type)) {
2718 		mutex_lock(&channel->shadow_list_lock);
2719 		list_for_each_entry_safe(shadow, tmp,
2720 					 &channel->source_shadow_list, head) {
2721 			list_del(&shadow->head);
2722 			v4l2_m2m_buf_done(&shadow->buf.vb, VB2_BUF_STATE_ERROR);
2723 		}
2724 		mutex_unlock(&channel->shadow_list_lock);
2725 
2726 		while ((buffer = v4l2_m2m_src_buf_remove(channel->fh.m2m_ctx)))
2727 			v4l2_m2m_buf_done(buffer, VB2_BUF_STATE_ERROR);
2728 	} else {
2729 		mutex_lock(&channel->shadow_list_lock);
2730 		list_for_each_entry_safe(shadow, tmp,
2731 					 &channel->stream_shadow_list, head) {
2732 			list_del(&shadow->head);
2733 			v4l2_m2m_buf_done(&shadow->buf.vb, VB2_BUF_STATE_ERROR);
2734 		}
2735 		mutex_unlock(&channel->shadow_list_lock);
2736 
2737 		allegro_destroy_channel(channel);
2738 		while ((buffer = v4l2_m2m_dst_buf_remove(channel->fh.m2m_ctx)))
2739 			v4l2_m2m_buf_done(buffer, VB2_BUF_STATE_ERROR);
2740 	}
2741 
2742 	v4l2_m2m_update_stop_streaming_state(channel->fh.m2m_ctx, q);
2743 
2744 	if (V4L2_TYPE_IS_OUTPUT(q->type) &&
2745 	    v4l2_m2m_has_stopped(channel->fh.m2m_ctx))
2746 		allegro_channel_eos_event(channel);
2747 }
2748 
2749 static const struct vb2_ops allegro_queue_ops = {
2750 	.queue_setup = allegro_queue_setup,
2751 	.buf_prepare = allegro_buf_prepare,
2752 	.buf_queue = allegro_buf_queue,
2753 	.start_streaming = allegro_start_streaming,
2754 	.stop_streaming = allegro_stop_streaming,
2755 	.wait_prepare = vb2_ops_wait_prepare,
2756 	.wait_finish = vb2_ops_wait_finish,
2757 };
2758 
2759 static int allegro_queue_init(void *priv,
2760 			      struct vb2_queue *src_vq,
2761 			      struct vb2_queue *dst_vq)
2762 {
2763 	int err;
2764 	struct allegro_channel *channel = priv;
2765 
2766 	src_vq->dev = &channel->dev->plat_dev->dev;
2767 	src_vq->type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
2768 	src_vq->io_modes = VB2_DMABUF | VB2_MMAP;
2769 	src_vq->mem_ops = &vb2_dma_contig_memops;
2770 	src_vq->drv_priv = channel;
2771 	src_vq->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_COPY;
2772 	src_vq->ops = &allegro_queue_ops;
2773 	src_vq->buf_struct_size = sizeof(struct allegro_m2m_buffer);
2774 	src_vq->lock = &channel->dev->lock;
2775 	err = vb2_queue_init(src_vq);
2776 	if (err)
2777 		return err;
2778 
2779 	dst_vq->dev = &channel->dev->plat_dev->dev;
2780 	dst_vq->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2781 	dst_vq->io_modes = VB2_DMABUF | VB2_MMAP;
2782 	dst_vq->mem_ops = &vb2_dma_contig_memops;
2783 	dst_vq->drv_priv = channel;
2784 	dst_vq->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_COPY;
2785 	dst_vq->ops = &allegro_queue_ops;
2786 	dst_vq->buf_struct_size = sizeof(struct allegro_m2m_buffer);
2787 	dst_vq->lock = &channel->dev->lock;
2788 	err = vb2_queue_init(dst_vq);
2789 	if (err)
2790 		return err;
2791 
2792 	return 0;
2793 }
2794 
2795 static int allegro_clamp_qp(struct allegro_channel *channel,
2796 			    struct v4l2_ctrl *ctrl)
2797 {
2798 	struct v4l2_ctrl *next_ctrl;
2799 
2800 	if (ctrl->id == V4L2_CID_MPEG_VIDEO_H264_I_FRAME_QP)
2801 		next_ctrl = channel->mpeg_video_h264_p_frame_qp;
2802 	else if (ctrl->id == V4L2_CID_MPEG_VIDEO_H264_P_FRAME_QP)
2803 		next_ctrl = channel->mpeg_video_h264_b_frame_qp;
2804 	else
2805 		return 0;
2806 
2807 	/* Modify range automatically updates the value */
2808 	__v4l2_ctrl_modify_range(next_ctrl, ctrl->val, 51, 1, ctrl->val);
2809 
2810 	return allegro_clamp_qp(channel, next_ctrl);
2811 }
2812 
2813 static int allegro_clamp_bitrate(struct allegro_channel *channel,
2814 				 struct v4l2_ctrl *ctrl)
2815 {
2816 	struct v4l2_ctrl *ctrl_bitrate = channel->mpeg_video_bitrate;
2817 	struct v4l2_ctrl *ctrl_bitrate_peak = channel->mpeg_video_bitrate_peak;
2818 
2819 	if (ctrl->val == V4L2_MPEG_VIDEO_BITRATE_MODE_VBR &&
2820 	    ctrl_bitrate_peak->val < ctrl_bitrate->val)
2821 		ctrl_bitrate_peak->val = ctrl_bitrate->val;
2822 
2823 	return 0;
2824 }
2825 
2826 static int allegro_try_ctrl(struct v4l2_ctrl *ctrl)
2827 {
2828 	struct allegro_channel *channel = container_of(ctrl->handler,
2829 						       struct allegro_channel,
2830 						       ctrl_handler);
2831 
2832 	switch (ctrl->id) {
2833 	case V4L2_CID_MPEG_VIDEO_BITRATE_MODE:
2834 		allegro_clamp_bitrate(channel, ctrl);
2835 		break;
2836 	}
2837 
2838 	return 0;
2839 }
2840 
2841 static int allegro_s_ctrl(struct v4l2_ctrl *ctrl)
2842 {
2843 	struct allegro_channel *channel = container_of(ctrl->handler,
2844 						       struct allegro_channel,
2845 						       ctrl_handler);
2846 	struct allegro_dev *dev = channel->dev;
2847 
2848 	v4l2_dbg(1, debug, &dev->v4l2_dev,
2849 		 "s_ctrl: %s = %d\n", v4l2_ctrl_get_name(ctrl->id), ctrl->val);
2850 
2851 	switch (ctrl->id) {
2852 	case V4L2_CID_MPEG_VIDEO_FRAME_RC_ENABLE:
2853 		channel->frame_rc_enable = ctrl->val;
2854 		break;
2855 	case V4L2_CID_MPEG_VIDEO_BITRATE_MODE:
2856 		channel->bitrate = channel->mpeg_video_bitrate->val;
2857 		channel->bitrate_peak = channel->mpeg_video_bitrate_peak->val;
2858 		v4l2_ctrl_activate(channel->mpeg_video_bitrate_peak,
2859 				   ctrl->val == V4L2_MPEG_VIDEO_BITRATE_MODE_VBR);
2860 		break;
2861 	case V4L2_CID_MPEG_VIDEO_H264_I_FRAME_QP:
2862 	case V4L2_CID_MPEG_VIDEO_H264_P_FRAME_QP:
2863 	case V4L2_CID_MPEG_VIDEO_H264_B_FRAME_QP:
2864 		allegro_clamp_qp(channel, ctrl);
2865 		break;
2866 	}
2867 
2868 	return 0;
2869 }
2870 
2871 static const struct v4l2_ctrl_ops allegro_ctrl_ops = {
2872 	.try_ctrl = allegro_try_ctrl,
2873 	.s_ctrl = allegro_s_ctrl,
2874 };
2875 
2876 static int allegro_open(struct file *file)
2877 {
2878 	struct video_device *vdev = video_devdata(file);
2879 	struct allegro_dev *dev = video_get_drvdata(vdev);
2880 	struct allegro_channel *channel = NULL;
2881 	struct v4l2_ctrl_handler *handler;
2882 	u64 mask;
2883 	int ret;
2884 	unsigned int bitrate_max;
2885 	unsigned int bitrate_def;
2886 	unsigned int cpb_size_max;
2887 	unsigned int cpb_size_def;
2888 
2889 	channel = kzalloc(sizeof(*channel), GFP_KERNEL);
2890 	if (!channel)
2891 		return -ENOMEM;
2892 
2893 	v4l2_fh_init(&channel->fh, vdev);
2894 
2895 	init_completion(&channel->completion);
2896 	INIT_LIST_HEAD(&channel->source_shadow_list);
2897 	INIT_LIST_HEAD(&channel->stream_shadow_list);
2898 	mutex_init(&channel->shadow_list_lock);
2899 
2900 	channel->dev = dev;
2901 
2902 	allegro_set_default_params(channel);
2903 
2904 	handler = &channel->ctrl_handler;
2905 	v4l2_ctrl_handler_init(handler, 0);
2906 	channel->mpeg_video_h264_profile = v4l2_ctrl_new_std_menu(handler,
2907 			&allegro_ctrl_ops,
2908 			V4L2_CID_MPEG_VIDEO_H264_PROFILE,
2909 			V4L2_MPEG_VIDEO_H264_PROFILE_BASELINE, 0x0,
2910 			V4L2_MPEG_VIDEO_H264_PROFILE_BASELINE);
2911 	mask = 1 << V4L2_MPEG_VIDEO_H264_LEVEL_1B;
2912 	channel->mpeg_video_h264_level = v4l2_ctrl_new_std_menu(handler,
2913 			&allegro_ctrl_ops,
2914 			V4L2_CID_MPEG_VIDEO_H264_LEVEL,
2915 			V4L2_MPEG_VIDEO_H264_LEVEL_5_1, mask,
2916 			V4L2_MPEG_VIDEO_H264_LEVEL_5_1);
2917 	channel->mpeg_video_h264_i_frame_qp =
2918 		v4l2_ctrl_new_std(handler,
2919 				  &allegro_ctrl_ops,
2920 				  V4L2_CID_MPEG_VIDEO_H264_I_FRAME_QP,
2921 				  0, 51, 1, 30);
2922 	channel->mpeg_video_h264_max_qp =
2923 		v4l2_ctrl_new_std(handler,
2924 				  &allegro_ctrl_ops,
2925 				  V4L2_CID_MPEG_VIDEO_H264_MAX_QP,
2926 				  0, 51, 1, 51);
2927 	channel->mpeg_video_h264_min_qp =
2928 		v4l2_ctrl_new_std(handler,
2929 				  &allegro_ctrl_ops,
2930 				  V4L2_CID_MPEG_VIDEO_H264_MIN_QP,
2931 				  0, 51, 1, 0);
2932 	channel->mpeg_video_h264_p_frame_qp =
2933 		v4l2_ctrl_new_std(handler,
2934 				  &allegro_ctrl_ops,
2935 				  V4L2_CID_MPEG_VIDEO_H264_P_FRAME_QP,
2936 				  0, 51, 1, 30);
2937 	channel->mpeg_video_h264_b_frame_qp =
2938 		v4l2_ctrl_new_std(handler,
2939 				  &allegro_ctrl_ops,
2940 				  V4L2_CID_MPEG_VIDEO_H264_B_FRAME_QP,
2941 				  0, 51, 1, 30);
2942 
2943 	channel->mpeg_video_hevc_profile =
2944 		v4l2_ctrl_new_std_menu(handler,
2945 				       &allegro_ctrl_ops,
2946 				       V4L2_CID_MPEG_VIDEO_HEVC_PROFILE,
2947 				       V4L2_MPEG_VIDEO_HEVC_PROFILE_MAIN, 0x0,
2948 				       V4L2_MPEG_VIDEO_HEVC_PROFILE_MAIN);
2949 	channel->mpeg_video_hevc_level =
2950 		v4l2_ctrl_new_std_menu(handler,
2951 				       &allegro_ctrl_ops,
2952 				       V4L2_CID_MPEG_VIDEO_HEVC_LEVEL,
2953 				       V4L2_MPEG_VIDEO_HEVC_LEVEL_5_1, 0x0,
2954 				       V4L2_MPEG_VIDEO_HEVC_LEVEL_5_1);
2955 	channel->mpeg_video_hevc_tier =
2956 		v4l2_ctrl_new_std_menu(handler,
2957 				       &allegro_ctrl_ops,
2958 				       V4L2_CID_MPEG_VIDEO_HEVC_TIER,
2959 				       V4L2_MPEG_VIDEO_HEVC_TIER_HIGH, 0x0,
2960 				       V4L2_MPEG_VIDEO_HEVC_TIER_MAIN);
2961 	channel->mpeg_video_hevc_i_frame_qp =
2962 		v4l2_ctrl_new_std(handler,
2963 				  &allegro_ctrl_ops,
2964 				  V4L2_CID_MPEG_VIDEO_HEVC_I_FRAME_QP,
2965 				  0, 51, 1, 30);
2966 	channel->mpeg_video_hevc_max_qp =
2967 		v4l2_ctrl_new_std(handler,
2968 				  &allegro_ctrl_ops,
2969 				  V4L2_CID_MPEG_VIDEO_HEVC_MAX_QP,
2970 				  0, 51, 1, 51);
2971 	channel->mpeg_video_hevc_min_qp =
2972 		v4l2_ctrl_new_std(handler,
2973 				  &allegro_ctrl_ops,
2974 				  V4L2_CID_MPEG_VIDEO_HEVC_MIN_QP,
2975 				  0, 51, 1, 0);
2976 	channel->mpeg_video_hevc_p_frame_qp =
2977 		v4l2_ctrl_new_std(handler,
2978 				  &allegro_ctrl_ops,
2979 				  V4L2_CID_MPEG_VIDEO_HEVC_P_FRAME_QP,
2980 				  0, 51, 1, 30);
2981 	channel->mpeg_video_hevc_b_frame_qp =
2982 		v4l2_ctrl_new_std(handler,
2983 				  &allegro_ctrl_ops,
2984 				  V4L2_CID_MPEG_VIDEO_HEVC_B_FRAME_QP,
2985 				  0, 51, 1, 30);
2986 
2987 	channel->mpeg_video_frame_rc_enable =
2988 		v4l2_ctrl_new_std(handler,
2989 				  &allegro_ctrl_ops,
2990 				  V4L2_CID_MPEG_VIDEO_FRAME_RC_ENABLE,
2991 				  false, 0x1,
2992 				  true, false);
2993 	channel->mpeg_video_bitrate_mode = v4l2_ctrl_new_std_menu(handler,
2994 			&allegro_ctrl_ops,
2995 			V4L2_CID_MPEG_VIDEO_BITRATE_MODE,
2996 			V4L2_MPEG_VIDEO_BITRATE_MODE_CBR, 0,
2997 			V4L2_MPEG_VIDEO_BITRATE_MODE_CBR);
2998 
2999 	if (channel->codec == V4L2_PIX_FMT_H264) {
3000 		bitrate_max = h264_maximum_bitrate(V4L2_MPEG_VIDEO_H264_LEVEL_5_1);
3001 		bitrate_def = h264_maximum_bitrate(V4L2_MPEG_VIDEO_H264_LEVEL_5_1);
3002 		cpb_size_max = h264_maximum_cpb_size(V4L2_MPEG_VIDEO_H264_LEVEL_5_1);
3003 		cpb_size_def = h264_maximum_cpb_size(V4L2_MPEG_VIDEO_H264_LEVEL_5_1);
3004 	} else {
3005 		bitrate_max = hevc_maximum_bitrate(V4L2_MPEG_VIDEO_HEVC_LEVEL_5_1);
3006 		bitrate_def = hevc_maximum_bitrate(V4L2_MPEG_VIDEO_HEVC_LEVEL_5_1);
3007 		cpb_size_max = hevc_maximum_cpb_size(V4L2_MPEG_VIDEO_HEVC_LEVEL_5_1);
3008 		cpb_size_def = hevc_maximum_cpb_size(V4L2_MPEG_VIDEO_HEVC_LEVEL_5_1);
3009 	}
3010 	channel->mpeg_video_bitrate = v4l2_ctrl_new_std(handler,
3011 			&allegro_ctrl_ops,
3012 			V4L2_CID_MPEG_VIDEO_BITRATE,
3013 			0, bitrate_max, 1, bitrate_def);
3014 	channel->mpeg_video_bitrate_peak = v4l2_ctrl_new_std(handler,
3015 			&allegro_ctrl_ops,
3016 			V4L2_CID_MPEG_VIDEO_BITRATE_PEAK,
3017 			0, bitrate_max, 1, bitrate_def);
3018 	channel->mpeg_video_cpb_size = v4l2_ctrl_new_std(handler,
3019 			&allegro_ctrl_ops,
3020 			V4L2_CID_MPEG_VIDEO_H264_CPB_SIZE,
3021 			0, cpb_size_max, 1, cpb_size_def);
3022 	channel->mpeg_video_gop_size = v4l2_ctrl_new_std(handler,
3023 			&allegro_ctrl_ops,
3024 			V4L2_CID_MPEG_VIDEO_GOP_SIZE,
3025 			0, ALLEGRO_GOP_SIZE_MAX,
3026 			1, ALLEGRO_GOP_SIZE_DEFAULT);
3027 	v4l2_ctrl_new_std(handler,
3028 			  &allegro_ctrl_ops,
3029 			  V4L2_CID_MIN_BUFFERS_FOR_OUTPUT,
3030 			  1, 32,
3031 			  1, 1);
3032 	if (handler->error != 0) {
3033 		ret = handler->error;
3034 		goto error;
3035 	}
3036 
3037 	channel->fh.ctrl_handler = handler;
3038 
3039 	v4l2_ctrl_cluster(3, &channel->mpeg_video_bitrate_mode);
3040 
3041 	v4l2_ctrl_handler_setup(handler);
3042 
3043 	channel->mcu_channel_id = -1;
3044 	channel->user_id = -1;
3045 
3046 	INIT_LIST_HEAD(&channel->buffers_reference);
3047 	INIT_LIST_HEAD(&channel->buffers_intermediate);
3048 
3049 	channel->fh.m2m_ctx = v4l2_m2m_ctx_init(dev->m2m_dev, channel,
3050 						allegro_queue_init);
3051 
3052 	if (IS_ERR(channel->fh.m2m_ctx)) {
3053 		ret = PTR_ERR(channel->fh.m2m_ctx);
3054 		goto error;
3055 	}
3056 
3057 	list_add(&channel->list, &dev->channels);
3058 	file->private_data = &channel->fh;
3059 	v4l2_fh_add(&channel->fh);
3060 
3061 	allegro_channel_adjust(channel);
3062 
3063 	return 0;
3064 
3065 error:
3066 	v4l2_ctrl_handler_free(handler);
3067 	kfree(channel);
3068 	return ret;
3069 }
3070 
3071 static int allegro_release(struct file *file)
3072 {
3073 	struct allegro_channel *channel = fh_to_channel(file->private_data);
3074 
3075 	v4l2_m2m_ctx_release(channel->fh.m2m_ctx);
3076 
3077 	list_del(&channel->list);
3078 
3079 	v4l2_ctrl_handler_free(&channel->ctrl_handler);
3080 
3081 	v4l2_fh_del(&channel->fh);
3082 	v4l2_fh_exit(&channel->fh);
3083 
3084 	kfree(channel);
3085 
3086 	return 0;
3087 }
3088 
3089 static int allegro_querycap(struct file *file, void *fh,
3090 			    struct v4l2_capability *cap)
3091 {
3092 	struct video_device *vdev = video_devdata(file);
3093 	struct allegro_dev *dev = video_get_drvdata(vdev);
3094 
3095 	strscpy(cap->driver, KBUILD_MODNAME, sizeof(cap->driver));
3096 	strscpy(cap->card, "Allegro DVT Video Encoder", sizeof(cap->card));
3097 	snprintf(cap->bus_info, sizeof(cap->bus_info), "platform:%s",
3098 		 dev_name(&dev->plat_dev->dev));
3099 
3100 	return 0;
3101 }
3102 
3103 static int allegro_enum_fmt_vid(struct file *file, void *fh,
3104 				struct v4l2_fmtdesc *f)
3105 {
3106 	switch (f->type) {
3107 	case V4L2_BUF_TYPE_VIDEO_OUTPUT:
3108 		if (f->index >= 1)
3109 			return -EINVAL;
3110 		f->pixelformat = V4L2_PIX_FMT_NV12;
3111 		break;
3112 	case V4L2_BUF_TYPE_VIDEO_CAPTURE:
3113 		if (f->index >= 2)
3114 			return -EINVAL;
3115 		if (f->index == 0)
3116 			f->pixelformat = V4L2_PIX_FMT_H264;
3117 		if (f->index == 1)
3118 			f->pixelformat = V4L2_PIX_FMT_HEVC;
3119 		break;
3120 	default:
3121 		return -EINVAL;
3122 	}
3123 	return 0;
3124 }
3125 
3126 static int allegro_g_fmt_vid_cap(struct file *file, void *fh,
3127 				 struct v4l2_format *f)
3128 {
3129 	struct allegro_channel *channel = fh_to_channel(fh);
3130 
3131 	f->fmt.pix.field = V4L2_FIELD_NONE;
3132 	f->fmt.pix.width = channel->width;
3133 	f->fmt.pix.height = channel->height;
3134 
3135 	f->fmt.pix.colorspace = channel->colorspace;
3136 	f->fmt.pix.ycbcr_enc = channel->ycbcr_enc;
3137 	f->fmt.pix.quantization = channel->quantization;
3138 	f->fmt.pix.xfer_func = channel->xfer_func;
3139 
3140 	f->fmt.pix.pixelformat = channel->codec;
3141 	f->fmt.pix.bytesperline = 0;
3142 	f->fmt.pix.sizeimage = channel->sizeimage_encoded;
3143 
3144 	return 0;
3145 }
3146 
3147 static int allegro_try_fmt_vid_cap(struct file *file, void *fh,
3148 				   struct v4l2_format *f)
3149 {
3150 	f->fmt.pix.field = V4L2_FIELD_NONE;
3151 
3152 	f->fmt.pix.width = clamp_t(__u32, f->fmt.pix.width,
3153 				   ALLEGRO_WIDTH_MIN, ALLEGRO_WIDTH_MAX);
3154 	f->fmt.pix.height = clamp_t(__u32, f->fmt.pix.height,
3155 				    ALLEGRO_HEIGHT_MIN, ALLEGRO_HEIGHT_MAX);
3156 
3157 	if (f->fmt.pix.pixelformat != V4L2_PIX_FMT_HEVC &&
3158 	    f->fmt.pix.pixelformat != V4L2_PIX_FMT_H264)
3159 		f->fmt.pix.pixelformat = V4L2_PIX_FMT_H264;
3160 
3161 	f->fmt.pix.bytesperline = 0;
3162 	f->fmt.pix.sizeimage =
3163 		estimate_stream_size(f->fmt.pix.width, f->fmt.pix.height);
3164 
3165 	return 0;
3166 }
3167 
3168 static int allegro_s_fmt_vid_cap(struct file *file, void *fh,
3169 				 struct v4l2_format *f)
3170 {
3171 	struct allegro_channel *channel = fh_to_channel(fh);
3172 	struct vb2_queue *vq;
3173 	int err;
3174 
3175 	err = allegro_try_fmt_vid_cap(file, fh, f);
3176 	if (err)
3177 		return err;
3178 
3179 	vq = v4l2_m2m_get_vq(channel->fh.m2m_ctx, f->type);
3180 	if (!vq)
3181 		return -EINVAL;
3182 	if (vb2_is_busy(vq))
3183 		return -EBUSY;
3184 
3185 	channel->codec = f->fmt.pix.pixelformat;
3186 
3187 	allegro_channel_adjust(channel);
3188 
3189 	return 0;
3190 }
3191 
3192 static int allegro_g_fmt_vid_out(struct file *file, void *fh,
3193 				 struct v4l2_format *f)
3194 {
3195 	struct allegro_channel *channel = fh_to_channel(fh);
3196 
3197 	f->fmt.pix.field = V4L2_FIELD_NONE;
3198 
3199 	f->fmt.pix.width = channel->width;
3200 	f->fmt.pix.height = channel->height;
3201 
3202 	f->fmt.pix.colorspace = channel->colorspace;
3203 	f->fmt.pix.ycbcr_enc = channel->ycbcr_enc;
3204 	f->fmt.pix.quantization = channel->quantization;
3205 	f->fmt.pix.xfer_func = channel->xfer_func;
3206 
3207 	f->fmt.pix.pixelformat = channel->pixelformat;
3208 	f->fmt.pix.bytesperline = channel->stride;
3209 	f->fmt.pix.sizeimage = channel->sizeimage_raw;
3210 
3211 	return 0;
3212 }
3213 
3214 static int allegro_try_fmt_vid_out(struct file *file, void *fh,
3215 				   struct v4l2_format *f)
3216 {
3217 	f->fmt.pix.field = V4L2_FIELD_NONE;
3218 
3219 	/*
3220 	 * The firmware of the Allegro codec handles the padding internally
3221 	 * and expects the visual frame size when configuring a channel.
3222 	 * Therefore, unlike other encoder drivers, this driver does not round
3223 	 * up the width and height to macroblock alignment and does not
3224 	 * implement the selection api.
3225 	 */
3226 	f->fmt.pix.width = clamp_t(__u32, f->fmt.pix.width,
3227 				   ALLEGRO_WIDTH_MIN, ALLEGRO_WIDTH_MAX);
3228 	f->fmt.pix.height = clamp_t(__u32, f->fmt.pix.height,
3229 				    ALLEGRO_HEIGHT_MIN, ALLEGRO_HEIGHT_MAX);
3230 
3231 	f->fmt.pix.pixelformat = V4L2_PIX_FMT_NV12;
3232 	f->fmt.pix.bytesperline = round_up(f->fmt.pix.width, 32);
3233 	f->fmt.pix.sizeimage =
3234 		f->fmt.pix.bytesperline * f->fmt.pix.height * 3 / 2;
3235 
3236 	return 0;
3237 }
3238 
3239 static int allegro_s_fmt_vid_out(struct file *file, void *fh,
3240 				 struct v4l2_format *f)
3241 {
3242 	struct allegro_channel *channel = fh_to_channel(fh);
3243 	int err;
3244 
3245 	err = allegro_try_fmt_vid_out(file, fh, f);
3246 	if (err)
3247 		return err;
3248 
3249 	channel->width = f->fmt.pix.width;
3250 	channel->height = f->fmt.pix.height;
3251 	channel->stride = f->fmt.pix.bytesperline;
3252 	channel->sizeimage_raw = f->fmt.pix.sizeimage;
3253 
3254 	channel->colorspace = f->fmt.pix.colorspace;
3255 	channel->ycbcr_enc = f->fmt.pix.ycbcr_enc;
3256 	channel->quantization = f->fmt.pix.quantization;
3257 	channel->xfer_func = f->fmt.pix.xfer_func;
3258 
3259 	allegro_channel_adjust(channel);
3260 
3261 	return 0;
3262 }
3263 
3264 static int allegro_channel_cmd_stop(struct allegro_channel *channel)
3265 {
3266 	if (v4l2_m2m_has_stopped(channel->fh.m2m_ctx))
3267 		allegro_channel_eos_event(channel);
3268 
3269 	return 0;
3270 }
3271 
3272 static int allegro_channel_cmd_start(struct allegro_channel *channel)
3273 {
3274 	if (v4l2_m2m_has_stopped(channel->fh.m2m_ctx))
3275 		vb2_clear_last_buffer_dequeued(&channel->fh.m2m_ctx->cap_q_ctx.q);
3276 
3277 	return 0;
3278 }
3279 
3280 static int allegro_encoder_cmd(struct file *file, void *fh,
3281 			       struct v4l2_encoder_cmd *cmd)
3282 {
3283 	struct allegro_channel *channel = fh_to_channel(fh);
3284 	int err;
3285 
3286 	err = v4l2_m2m_ioctl_try_encoder_cmd(file, fh, cmd);
3287 	if (err)
3288 		return err;
3289 
3290 	err = v4l2_m2m_ioctl_encoder_cmd(file, fh, cmd);
3291 	if (err)
3292 		return err;
3293 
3294 	if (cmd->cmd == V4L2_ENC_CMD_STOP)
3295 		err = allegro_channel_cmd_stop(channel);
3296 
3297 	if (cmd->cmd == V4L2_ENC_CMD_START)
3298 		err = allegro_channel_cmd_start(channel);
3299 
3300 	return err;
3301 }
3302 
3303 static int allegro_enum_framesizes(struct file *file, void *fh,
3304 				   struct v4l2_frmsizeenum *fsize)
3305 {
3306 	switch (fsize->pixel_format) {
3307 	case V4L2_PIX_FMT_HEVC:
3308 	case V4L2_PIX_FMT_H264:
3309 	case V4L2_PIX_FMT_NV12:
3310 		break;
3311 	default:
3312 		return -EINVAL;
3313 	}
3314 
3315 	if (fsize->index)
3316 		return -EINVAL;
3317 
3318 	fsize->type = V4L2_FRMSIZE_TYPE_CONTINUOUS;
3319 	fsize->stepwise.min_width = ALLEGRO_WIDTH_MIN;
3320 	fsize->stepwise.max_width = ALLEGRO_WIDTH_MAX;
3321 	fsize->stepwise.step_width = 1;
3322 	fsize->stepwise.min_height = ALLEGRO_HEIGHT_MIN;
3323 	fsize->stepwise.max_height = ALLEGRO_HEIGHT_MAX;
3324 	fsize->stepwise.step_height = 1;
3325 
3326 	return 0;
3327 }
3328 
3329 static int allegro_ioctl_streamon(struct file *file, void *priv,
3330 				  enum v4l2_buf_type type)
3331 {
3332 	struct v4l2_fh *fh = file->private_data;
3333 	struct allegro_channel *channel = fh_to_channel(fh);
3334 	int err;
3335 
3336 	if (type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
3337 		err = allegro_create_channel(channel);
3338 		if (err)
3339 			return err;
3340 	}
3341 
3342 	return v4l2_m2m_streamon(file, fh->m2m_ctx, type);
3343 }
3344 
3345 static int allegro_g_parm(struct file *file, void *fh,
3346 			  struct v4l2_streamparm *a)
3347 {
3348 	struct allegro_channel *channel = fh_to_channel(fh);
3349 	struct v4l2_fract *timeperframe;
3350 
3351 	if (a->type != V4L2_BUF_TYPE_VIDEO_OUTPUT)
3352 		return -EINVAL;
3353 
3354 	a->parm.output.capability = V4L2_CAP_TIMEPERFRAME;
3355 	timeperframe = &a->parm.output.timeperframe;
3356 	timeperframe->numerator = channel->framerate.denominator;
3357 	timeperframe->denominator = channel->framerate.numerator;
3358 
3359 	return 0;
3360 }
3361 
3362 static int allegro_s_parm(struct file *file, void *fh,
3363 			  struct v4l2_streamparm *a)
3364 {
3365 	struct allegro_channel *channel = fh_to_channel(fh);
3366 	struct v4l2_fract *timeperframe;
3367 	int div;
3368 
3369 	if (a->type != V4L2_BUF_TYPE_VIDEO_OUTPUT)
3370 		return -EINVAL;
3371 
3372 	a->parm.output.capability = V4L2_CAP_TIMEPERFRAME;
3373 	timeperframe = &a->parm.output.timeperframe;
3374 
3375 	if (timeperframe->numerator == 0 || timeperframe->denominator == 0)
3376 		return allegro_g_parm(file, fh, a);
3377 
3378 	div = gcd(timeperframe->denominator, timeperframe->numerator);
3379 	channel->framerate.numerator = timeperframe->denominator / div;
3380 	channel->framerate.denominator = timeperframe->numerator / div;
3381 
3382 	return 0;
3383 }
3384 
3385 static int allegro_subscribe_event(struct v4l2_fh *fh,
3386 				   const struct v4l2_event_subscription *sub)
3387 {
3388 	switch (sub->type) {
3389 	case V4L2_EVENT_EOS:
3390 		return v4l2_event_subscribe(fh, sub, 0, NULL);
3391 	default:
3392 		return v4l2_ctrl_subscribe_event(fh, sub);
3393 	}
3394 }
3395 
3396 static const struct v4l2_ioctl_ops allegro_ioctl_ops = {
3397 	.vidioc_querycap = allegro_querycap,
3398 	.vidioc_enum_fmt_vid_cap = allegro_enum_fmt_vid,
3399 	.vidioc_enum_fmt_vid_out = allegro_enum_fmt_vid,
3400 	.vidioc_g_fmt_vid_cap = allegro_g_fmt_vid_cap,
3401 	.vidioc_try_fmt_vid_cap = allegro_try_fmt_vid_cap,
3402 	.vidioc_s_fmt_vid_cap = allegro_s_fmt_vid_cap,
3403 	.vidioc_g_fmt_vid_out = allegro_g_fmt_vid_out,
3404 	.vidioc_try_fmt_vid_out = allegro_try_fmt_vid_out,
3405 	.vidioc_s_fmt_vid_out = allegro_s_fmt_vid_out,
3406 
3407 	.vidioc_create_bufs = v4l2_m2m_ioctl_create_bufs,
3408 	.vidioc_reqbufs = v4l2_m2m_ioctl_reqbufs,
3409 
3410 	.vidioc_expbuf = v4l2_m2m_ioctl_expbuf,
3411 	.vidioc_querybuf = v4l2_m2m_ioctl_querybuf,
3412 	.vidioc_qbuf = v4l2_m2m_ioctl_qbuf,
3413 	.vidioc_dqbuf = v4l2_m2m_ioctl_dqbuf,
3414 	.vidioc_prepare_buf = v4l2_m2m_ioctl_prepare_buf,
3415 
3416 	.vidioc_streamon = allegro_ioctl_streamon,
3417 	.vidioc_streamoff = v4l2_m2m_ioctl_streamoff,
3418 
3419 	.vidioc_try_encoder_cmd = v4l2_m2m_ioctl_try_encoder_cmd,
3420 	.vidioc_encoder_cmd = allegro_encoder_cmd,
3421 	.vidioc_enum_framesizes = allegro_enum_framesizes,
3422 
3423 	.vidioc_g_parm		= allegro_g_parm,
3424 	.vidioc_s_parm		= allegro_s_parm,
3425 
3426 	.vidioc_subscribe_event = allegro_subscribe_event,
3427 	.vidioc_unsubscribe_event = v4l2_event_unsubscribe,
3428 };
3429 
3430 static const struct v4l2_file_operations allegro_fops = {
3431 	.owner = THIS_MODULE,
3432 	.open = allegro_open,
3433 	.release = allegro_release,
3434 	.poll = v4l2_m2m_fop_poll,
3435 	.unlocked_ioctl = video_ioctl2,
3436 	.mmap = v4l2_m2m_fop_mmap,
3437 };
3438 
3439 static int allegro_register_device(struct allegro_dev *dev)
3440 {
3441 	struct video_device *video_dev = &dev->video_dev;
3442 
3443 	strscpy(video_dev->name, "allegro", sizeof(video_dev->name));
3444 	video_dev->fops = &allegro_fops;
3445 	video_dev->ioctl_ops = &allegro_ioctl_ops;
3446 	video_dev->release = video_device_release_empty;
3447 	video_dev->lock = &dev->lock;
3448 	video_dev->v4l2_dev = &dev->v4l2_dev;
3449 	video_dev->vfl_dir = VFL_DIR_M2M;
3450 	video_dev->device_caps = V4L2_CAP_VIDEO_M2M | V4L2_CAP_STREAMING;
3451 	video_set_drvdata(video_dev, dev);
3452 
3453 	return video_register_device(video_dev, VFL_TYPE_VIDEO, 0);
3454 }
3455 
3456 static void allegro_device_run(void *priv)
3457 {
3458 	struct allegro_channel *channel = priv;
3459 	struct allegro_dev *dev = channel->dev;
3460 	struct vb2_v4l2_buffer *src_buf;
3461 	struct vb2_v4l2_buffer *dst_buf;
3462 	dma_addr_t src_y;
3463 	dma_addr_t src_uv;
3464 	dma_addr_t dst_addr;
3465 	unsigned long dst_size;
3466 	u64 src_handle;
3467 	u64 dst_handle;
3468 
3469 	dst_buf = v4l2_m2m_dst_buf_remove(channel->fh.m2m_ctx);
3470 	dst_addr = vb2_dma_contig_plane_dma_addr(&dst_buf->vb2_buf, 0);
3471 	dst_size = vb2_plane_size(&dst_buf->vb2_buf, 0);
3472 	dst_handle = allegro_put_buffer(channel, &channel->stream_shadow_list,
3473 					dst_buf);
3474 	allegro_mcu_send_put_stream_buffer(dev, channel, dst_addr, dst_size,
3475 					   dst_handle);
3476 
3477 	src_buf = v4l2_m2m_src_buf_remove(channel->fh.m2m_ctx);
3478 	src_buf->sequence = channel->osequence++;
3479 	src_y = vb2_dma_contig_plane_dma_addr(&src_buf->vb2_buf, 0);
3480 	src_uv = src_y + (channel->stride * channel->height);
3481 	src_handle = allegro_put_buffer(channel, &channel->source_shadow_list,
3482 					src_buf);
3483 	allegro_mcu_send_encode_frame(dev, channel, src_y, src_uv, src_handle);
3484 
3485 	v4l2_m2m_job_finish(dev->m2m_dev, channel->fh.m2m_ctx);
3486 }
3487 
3488 static const struct v4l2_m2m_ops allegro_m2m_ops = {
3489 	.device_run = allegro_device_run,
3490 };
3491 
3492 static int allegro_mcu_hw_init(struct allegro_dev *dev,
3493 			       const struct fw_info *info)
3494 {
3495 	int err;
3496 
3497 	dev->mbox_command = allegro_mbox_init(dev, info->mailbox_cmd,
3498 					      info->mailbox_size);
3499 	dev->mbox_status = allegro_mbox_init(dev, info->mailbox_status,
3500 					     info->mailbox_size);
3501 	if (IS_ERR(dev->mbox_command) || IS_ERR(dev->mbox_status)) {
3502 		v4l2_err(&dev->v4l2_dev,
3503 			 "failed to initialize mailboxes\n");
3504 		return -EIO;
3505 	}
3506 
3507 	allegro_mcu_enable_interrupts(dev);
3508 
3509 	/* The mcu sends INIT after reset. */
3510 	allegro_mcu_start(dev);
3511 	err = allegro_mcu_wait_for_init_timeout(dev, 5000);
3512 	if (err < 0) {
3513 		v4l2_err(&dev->v4l2_dev,
3514 			 "mcu did not send INIT after reset\n");
3515 		err = -EIO;
3516 		goto err_disable_interrupts;
3517 	}
3518 
3519 	err = allegro_alloc_buffer(dev, &dev->suballocator,
3520 				   info->suballocator_size);
3521 	if (err) {
3522 		v4l2_err(&dev->v4l2_dev,
3523 			 "failed to allocate %zu bytes for suballocator\n",
3524 			 info->suballocator_size);
3525 		goto err_reset_mcu;
3526 	}
3527 
3528 	allegro_mcu_send_init(dev, dev->suballocator.paddr,
3529 			      dev->suballocator.size);
3530 	err = allegro_mcu_wait_for_init_timeout(dev, 5000);
3531 	if (err < 0) {
3532 		v4l2_err(&dev->v4l2_dev,
3533 			 "mcu failed to configure sub-allocator\n");
3534 		err = -EIO;
3535 		goto err_free_suballocator;
3536 	}
3537 
3538 	return 0;
3539 
3540 err_free_suballocator:
3541 	allegro_free_buffer(dev, &dev->suballocator);
3542 err_reset_mcu:
3543 	allegro_mcu_reset(dev);
3544 err_disable_interrupts:
3545 	allegro_mcu_disable_interrupts(dev);
3546 
3547 	return err;
3548 }
3549 
3550 static int allegro_mcu_hw_deinit(struct allegro_dev *dev)
3551 {
3552 	int err;
3553 
3554 	err = allegro_mcu_reset(dev);
3555 	if (err)
3556 		v4l2_warn(&dev->v4l2_dev,
3557 			  "mcu failed to enter sleep state\n");
3558 
3559 	err = allegro_mcu_disable_interrupts(dev);
3560 	if (err)
3561 		v4l2_warn(&dev->v4l2_dev,
3562 			  "failed to disable interrupts\n");
3563 
3564 	allegro_free_buffer(dev, &dev->suballocator);
3565 
3566 	return 0;
3567 }
3568 
3569 static void allegro_fw_callback(const struct firmware *fw, void *context)
3570 {
3571 	struct allegro_dev *dev = context;
3572 	const char *fw_codec_name = "al5e.fw";
3573 	const struct firmware *fw_codec;
3574 	int err;
3575 
3576 	if (!fw)
3577 		return;
3578 
3579 	v4l2_dbg(1, debug, &dev->v4l2_dev,
3580 		 "requesting codec firmware '%s'\n", fw_codec_name);
3581 	err = request_firmware(&fw_codec, fw_codec_name, &dev->plat_dev->dev);
3582 	if (err)
3583 		goto err_release_firmware;
3584 
3585 	dev->fw_info = allegro_get_firmware_info(dev, fw, fw_codec);
3586 	if (!dev->fw_info) {
3587 		v4l2_err(&dev->v4l2_dev, "firmware is not supported\n");
3588 		goto err_release_firmware_codec;
3589 	}
3590 
3591 	v4l2_info(&dev->v4l2_dev,
3592 		  "using mcu firmware version '%s'\n", dev->fw_info->version);
3593 
3594 	/* Ensure that the mcu is sleeping at the reset vector */
3595 	err = allegro_mcu_reset(dev);
3596 	if (err) {
3597 		v4l2_err(&dev->v4l2_dev, "failed to reset mcu\n");
3598 		goto err_release_firmware_codec;
3599 	}
3600 
3601 	allegro_copy_firmware(dev, fw->data, fw->size);
3602 	allegro_copy_fw_codec(dev, fw_codec->data, fw_codec->size);
3603 
3604 	err = allegro_mcu_hw_init(dev, dev->fw_info);
3605 	if (err) {
3606 		v4l2_err(&dev->v4l2_dev, "failed to initialize mcu\n");
3607 		goto err_free_fw_codec;
3608 	}
3609 
3610 	dev->m2m_dev = v4l2_m2m_init(&allegro_m2m_ops);
3611 	if (IS_ERR(dev->m2m_dev)) {
3612 		v4l2_err(&dev->v4l2_dev, "failed to init mem2mem device\n");
3613 		goto err_mcu_hw_deinit;
3614 	}
3615 
3616 	err = allegro_register_device(dev);
3617 	if (err) {
3618 		v4l2_err(&dev->v4l2_dev, "failed to register video device\n");
3619 		goto err_m2m_release;
3620 	}
3621 
3622 	v4l2_dbg(1, debug, &dev->v4l2_dev,
3623 		 "allegro codec registered as /dev/video%d\n",
3624 		 dev->video_dev.num);
3625 
3626 	release_firmware(fw_codec);
3627 	release_firmware(fw);
3628 
3629 	return;
3630 
3631 err_m2m_release:
3632 	v4l2_m2m_release(dev->m2m_dev);
3633 	dev->m2m_dev = NULL;
3634 err_mcu_hw_deinit:
3635 	allegro_mcu_hw_deinit(dev);
3636 err_free_fw_codec:
3637 	allegro_free_fw_codec(dev);
3638 err_release_firmware_codec:
3639 	release_firmware(fw_codec);
3640 err_release_firmware:
3641 	release_firmware(fw);
3642 }
3643 
3644 static int allegro_firmware_request_nowait(struct allegro_dev *dev)
3645 {
3646 	const char *fw = "al5e_b.fw";
3647 
3648 	v4l2_dbg(1, debug, &dev->v4l2_dev,
3649 		 "requesting firmware '%s'\n", fw);
3650 	return request_firmware_nowait(THIS_MODULE, true, fw,
3651 				       &dev->plat_dev->dev, GFP_KERNEL, dev,
3652 				       allegro_fw_callback);
3653 }
3654 
3655 static int allegro_probe(struct platform_device *pdev)
3656 {
3657 	struct allegro_dev *dev;
3658 	struct resource *res, *sram_res;
3659 	int ret;
3660 	int irq;
3661 	void __iomem *regs, *sram_regs;
3662 
3663 	dev = devm_kzalloc(&pdev->dev, sizeof(*dev), GFP_KERNEL);
3664 	if (!dev)
3665 		return -ENOMEM;
3666 	dev->plat_dev = pdev;
3667 	init_completion(&dev->init_complete);
3668 	INIT_LIST_HEAD(&dev->channels);
3669 
3670 	mutex_init(&dev->lock);
3671 
3672 	res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "regs");
3673 	if (!res) {
3674 		dev_err(&pdev->dev,
3675 			"regs resource missing from device tree\n");
3676 		return -EINVAL;
3677 	}
3678 	regs = devm_ioremap(&pdev->dev, res->start, resource_size(res));
3679 	if (!regs) {
3680 		dev_err(&pdev->dev, "failed to map registers\n");
3681 		return -ENOMEM;
3682 	}
3683 	dev->regmap = devm_regmap_init_mmio(&pdev->dev, regs,
3684 					    &allegro_regmap_config);
3685 	if (IS_ERR(dev->regmap)) {
3686 		dev_err(&pdev->dev, "failed to init regmap\n");
3687 		return PTR_ERR(dev->regmap);
3688 	}
3689 
3690 	sram_res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "sram");
3691 	if (!sram_res) {
3692 		dev_err(&pdev->dev,
3693 			"sram resource missing from device tree\n");
3694 		return -EINVAL;
3695 	}
3696 	sram_regs = devm_ioremap(&pdev->dev,
3697 				 sram_res->start,
3698 				 resource_size(sram_res));
3699 	if (!sram_regs) {
3700 		dev_err(&pdev->dev, "failed to map sram\n");
3701 		return -ENOMEM;
3702 	}
3703 	dev->sram = devm_regmap_init_mmio(&pdev->dev, sram_regs,
3704 					  &allegro_sram_config);
3705 	if (IS_ERR(dev->sram)) {
3706 		dev_err(&pdev->dev, "failed to init sram\n");
3707 		return PTR_ERR(dev->sram);
3708 	}
3709 
3710 	irq = platform_get_irq(pdev, 0);
3711 	if (irq < 0)
3712 		return irq;
3713 	ret = devm_request_threaded_irq(&pdev->dev, irq,
3714 					allegro_hardirq,
3715 					allegro_irq_thread,
3716 					IRQF_SHARED, dev_name(&pdev->dev), dev);
3717 	if (ret < 0) {
3718 		dev_err(&pdev->dev, "failed to request irq: %d\n", ret);
3719 		return ret;
3720 	}
3721 
3722 	ret = v4l2_device_register(&pdev->dev, &dev->v4l2_dev);
3723 	if (ret)
3724 		return ret;
3725 
3726 	platform_set_drvdata(pdev, dev);
3727 
3728 	ret = allegro_firmware_request_nowait(dev);
3729 	if (ret < 0) {
3730 		v4l2_err(&dev->v4l2_dev,
3731 			 "failed to request firmware: %d\n", ret);
3732 		return ret;
3733 	}
3734 
3735 	return 0;
3736 }
3737 
3738 static int allegro_remove(struct platform_device *pdev)
3739 {
3740 	struct allegro_dev *dev = platform_get_drvdata(pdev);
3741 
3742 	video_unregister_device(&dev->video_dev);
3743 	if (dev->m2m_dev)
3744 		v4l2_m2m_release(dev->m2m_dev);
3745 	allegro_mcu_hw_deinit(dev);
3746 	allegro_free_fw_codec(dev);
3747 
3748 	v4l2_device_unregister(&dev->v4l2_dev);
3749 
3750 	return 0;
3751 }
3752 
3753 static const struct of_device_id allegro_dt_ids[] = {
3754 	{ .compatible = "allegro,al5e-1.1" },
3755 	{ /* sentinel */ }
3756 };
3757 
3758 MODULE_DEVICE_TABLE(of, allegro_dt_ids);
3759 
3760 static struct platform_driver allegro_driver = {
3761 	.probe = allegro_probe,
3762 	.remove = allegro_remove,
3763 	.driver = {
3764 		.name = "allegro",
3765 		.of_match_table = of_match_ptr(allegro_dt_ids),
3766 	},
3767 };
3768 
3769 module_platform_driver(allegro_driver);
3770 
3771 MODULE_LICENSE("GPL");
3772 MODULE_AUTHOR("Michael Tretter <kernel@pengutronix.de>");
3773 MODULE_DESCRIPTION("Allegro DVT encoder driver");
3774