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