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