• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * BCM283x / BCM271x Unicam Capture Driver
4  *
5  * Copyright (C) 2017-2020 - Raspberry Pi (Trading) Ltd.
6  * Copyright (C) 2024 - Ideas on Board
7  *
8  * Dave Stevenson <dave.stevenson@raspberrypi.com>
9  *
10  * Based on TI am437x driver by
11  *   Benoit Parrot <bparrot@ti.com>
12  *   Lad, Prabhakar <prabhakar.csengg@gmail.com>
13  *
14  * and TI CAL camera interface driver by
15  *    Benoit Parrot <bparrot@ti.com>
16  *
17  *
18  * There are two camera drivers in the kernel for BCM283x - this one and
19  * bcm2835-camera (currently in staging).
20  *
21  * This driver directly controls the Unicam peripheral - there is no
22  * involvement with the VideoCore firmware. Unicam receives CSI-2 or CCP2 data
23  * and writes it into SDRAM. The only potential processing options are to
24  * repack Bayer data into an alternate format, and applying windowing. The
25  * repacking does not shift the data, so can repack V4L2_PIX_FMT_Sxxxx10P to
26  * V4L2_PIX_FMT_Sxxxx10, or V4L2_PIX_FMT_Sxxxx12P to V4L2_PIX_FMT_Sxxxx12, but
27  * not generically up to V4L2_PIX_FMT_Sxxxx16. Support for windowing may be
28  * added later.
29  *
30  * It should be possible to connect this driver to any sensor with a suitable
31  * output interface and V4L2 subdevice driver.
32  */
33 
34 #include <linux/clk.h>
35 #include <linux/delay.h>
36 #include <linux/device.h>
37 #include <linux/dma-mapping.h>
38 #include <linux/err.h>
39 #include <linux/interrupt.h>
40 #include <linux/io.h>
41 #include <linux/module.h>
42 #include <linux/of.h>
43 #include <linux/of_device.h>
44 #include <linux/platform_device.h>
45 #include <linux/pm_runtime.h>
46 #include <linux/slab.h>
47 #include <linux/videodev2.h>
48 
49 #include <media/mipi-csi2.h>
50 #include <media/v4l2-async.h>
51 #include <media/v4l2-common.h>
52 #include <media/v4l2-dev.h>
53 #include <media/v4l2-device.h>
54 #include <media/v4l2-event.h>
55 #include <media/v4l2-ioctl.h>
56 #include <media/v4l2-fwnode.h>
57 #include <media/v4l2-mc.h>
58 #include <media/v4l2-subdev.h>
59 #include <media/videobuf2-dma-contig.h>
60 
61 #include "bcm2835-unicam-regs.h"
62 
63 #define UNICAM_MODULE_NAME		"unicam"
64 
65 /*
66  * Unicam must request a minimum of 250Mhz from the VPU clock.
67  * Otherwise the input FIFOs overrun and cause image corruption.
68  */
69 #define UNICAM_MIN_VPU_CLOCK_RATE	(250 * 1000 * 1000)
70 
71 /* Unicam has an internal DMA alignment constraint of 16 bytes for each line. */
72 #define UNICAM_DMA_BPL_ALIGNMENT	16
73 
74 /*
75  * The image stride is stored in a 16 bit register, and needs to be aligned to
76  * the DMA constraint. As the ISP in the same SoC has a 32 bytes alignment
77  * constraint on its input, set the image stride alignment to 32 bytes here as
78  * well to avoid incompatible configurations.
79  */
80 #define UNICAM_IMAGE_BPL_ALIGNMENT	32
81 #define UNICAM_IMAGE_MAX_BPL		((1U << 16) - UNICAM_IMAGE_BPL_ALIGNMENT)
82 
83 /*
84  * Max width is therefore determined by the max stride divided by the number of
85  * bits per pixel. Take 32bpp as a worst case. No imposed limit on the height,
86  * so adopt a square image for want of anything better.
87  */
88 #define UNICAM_IMAGE_MIN_WIDTH		16
89 #define UNICAM_IMAGE_MIN_HEIGHT		16
90 #define UNICAM_IMAGE_MAX_WIDTH		(UNICAM_IMAGE_MAX_BPL / 4)
91 #define UNICAM_IMAGE_MAX_HEIGHT		UNICAM_IMAGE_MAX_WIDTH
92 
93 /*
94  * There's no intrinsic limits on the width and height for embedded data. Use
95  * the same maximum values as for the image, to avoid overflows in the image
96  * size computation.
97  */
98 #define UNICAM_META_MIN_WIDTH		1
99 #define UNICAM_META_MIN_HEIGHT		1
100 #define UNICAM_META_MAX_WIDTH		UNICAM_IMAGE_MAX_WIDTH
101 #define UNICAM_META_MAX_HEIGHT		UNICAM_IMAGE_MAX_HEIGHT
102 
103 /*
104  * Size of the dummy buffer. Can be any size really, but the DMA
105  * allocation works in units of page sizes.
106  */
107 #define UNICAM_DUMMY_BUF_SIZE		PAGE_SIZE
108 
109 enum unicam_pad {
110 	UNICAM_SD_PAD_SINK,
111 	UNICAM_SD_PAD_SOURCE_IMAGE,
112 	UNICAM_SD_PAD_SOURCE_METADATA,
113 	UNICAM_SD_NUM_PADS
114 };
115 
116 enum unicam_node_type {
117 	UNICAM_IMAGE_NODE,
118 	UNICAM_METADATA_NODE,
119 	UNICAM_MAX_NODES
120 };
121 
122 /*
123  * struct unicam_format_info - Unicam media bus format information
124  * @fourcc: V4L2 pixel format FCC identifier. 0 if n/a.
125  * @unpacked_fourcc: V4L2 pixel format FCC identifier if the data is expanded
126  * out to 16bpp. 0 if n/a.
127  * @code: V4L2 media bus format code.
128  * @depth: Bits per pixel as delivered from the source.
129  * @csi_dt: CSI data type.
130  * @unpack: PUM value when unpacking to @unpacked_fourcc
131  */
132 struct unicam_format_info {
133 	u32	fourcc;
134 	u32	unpacked_fourcc;
135 	u32	code;
136 	u8	depth;
137 	u8	csi_dt;
138 	u8	unpack;
139 };
140 
141 struct unicam_buffer {
142 	struct vb2_v4l2_buffer vb;
143 	struct list_head list;
144 	dma_addr_t dma_addr;
145 	unsigned int size;
146 };
147 
to_unicam_buffer(struct vb2_buffer * vb)148 static inline struct unicam_buffer *to_unicam_buffer(struct vb2_buffer *vb)
149 {
150 	return container_of(vb, struct unicam_buffer, vb.vb2_buf);
151 }
152 
153 struct unicam_node {
154 	bool registered;
155 	unsigned int id;
156 
157 	/* Pointer to the current v4l2_buffer */
158 	struct unicam_buffer *cur_frm;
159 	/* Pointer to the next v4l2_buffer */
160 	struct unicam_buffer *next_frm;
161 	/* Used to store current pixel format */
162 	struct v4l2_format fmt;
163 	/* Buffer queue used in video-buf */
164 	struct vb2_queue buffer_queue;
165 	/* Queue of filled frames */
166 	struct list_head dma_queue;
167 	/* IRQ lock for DMA queue */
168 	spinlock_t dma_queue_lock;
169 	/* Identifies video device for this channel */
170 	struct video_device video_dev;
171 	/* Pointer to the parent handle */
172 	struct unicam_device *dev;
173 	struct media_pad pad;
174 	/*
175 	 * Dummy buffer intended to be used by unicam
176 	 * if we have no other queued buffers to swap to.
177 	 */
178 	struct unicam_buffer dummy_buf;
179 	void *dummy_buf_cpu_addr;
180 };
181 
182 struct unicam_device {
183 	struct kref kref;
184 
185 	/* peripheral base address */
186 	void __iomem *base;
187 	/* clock gating base address */
188 	void __iomem *clk_gate_base;
189 	/* lp clock handle */
190 	struct clk *clock;
191 	/* vpu clock handle */
192 	struct clk *vpu_clock;
193 	/* V4l2 device */
194 	struct v4l2_device v4l2_dev;
195 	struct media_device mdev;
196 
197 	/* parent device */
198 	struct device *dev;
199 	/* subdevice async notifier */
200 	struct v4l2_async_notifier notifier;
201 	unsigned int sequence;
202 
203 	/* Sensor node */
204 	struct {
205 		struct v4l2_subdev *subdev;
206 		struct media_pad *pad;
207 	} sensor;
208 
209 	/* Internal subdev */
210 	struct {
211 		struct v4l2_subdev sd;
212 		struct media_pad pads[UNICAM_SD_NUM_PADS];
213 		unsigned int enabled_streams;
214 	} subdev;
215 
216 	enum v4l2_mbus_type bus_type;
217 	/*
218 	 * Stores bus.mipi_csi2.flags for CSI2 sensors, or
219 	 * bus.mipi_csi1.strobe for CCP2.
220 	 */
221 	unsigned int bus_flags;
222 	unsigned int max_data_lanes;
223 
224 	struct {
225 		struct media_pipeline pipe;
226 		unsigned int num_data_lanes;
227 		unsigned int nodes;
228 	} pipe;
229 
230 	/* Lock used for the video devices of both nodes */
231 	struct mutex lock;
232 	struct unicam_node node[UNICAM_MAX_NODES];
233 };
234 
235 static inline struct unicam_device *
notifier_to_unicam_device(struct v4l2_async_notifier * notifier)236 notifier_to_unicam_device(struct v4l2_async_notifier *notifier)
237 {
238 	return container_of(notifier, struct unicam_device, notifier);
239 }
240 
241 static inline struct unicam_device *
sd_to_unicam_device(struct v4l2_subdev * sd)242 sd_to_unicam_device(struct v4l2_subdev *sd)
243 {
244 	return container_of(sd, struct unicam_device, subdev.sd);
245 }
246 
unicam_release(struct kref * kref)247 static void unicam_release(struct kref *kref)
248 {
249 	struct unicam_device *unicam =
250 		container_of(kref, struct unicam_device, kref);
251 
252 	if (unicam->mdev.dev)
253 		media_device_cleanup(&unicam->mdev);
254 
255 	mutex_destroy(&unicam->lock);
256 	kfree(unicam);
257 }
258 
unicam_get(struct unicam_device * unicam)259 static struct unicam_device *unicam_get(struct unicam_device *unicam)
260 {
261 	kref_get(&unicam->kref);
262 
263 	return unicam;
264 }
265 
unicam_put(struct unicam_device * unicam)266 static void unicam_put(struct unicam_device *unicam)
267 {
268 	kref_put(&unicam->kref, unicam_release);
269 }
270 
271 /* -----------------------------------------------------------------------------
272  * Misc helper functions
273  */
274 
unicam_sd_pad_is_source(u32 pad)275 static inline bool unicam_sd_pad_is_source(u32 pad)
276 {
277 	/* Camera RX has 1 sink pad, and N source pads */
278 	return pad != UNICAM_SD_PAD_SINK;
279 }
280 
is_metadata_node(struct unicam_node * node)281 static inline bool is_metadata_node(struct unicam_node *node)
282 {
283 	return node->video_dev.device_caps & V4L2_CAP_META_CAPTURE;
284 }
285 
is_image_node(struct unicam_node * node)286 static inline bool is_image_node(struct unicam_node *node)
287 {
288 	return node->video_dev.device_caps & V4L2_CAP_VIDEO_CAPTURE;
289 }
290 
291 /* -----------------------------------------------------------------------------
292  * Format data table and helper functions
293  */
294 
295 static const struct v4l2_mbus_framefmt unicam_default_image_format = {
296 	.width = 640,
297 	.height = 480,
298 	.code = MEDIA_BUS_FMT_UYVY8_1X16,
299 	.field = V4L2_FIELD_NONE,
300 	.colorspace = V4L2_COLORSPACE_SRGB,
301 	.ycbcr_enc = V4L2_YCBCR_ENC_601,
302 	.quantization = V4L2_QUANTIZATION_LIM_RANGE,
303 	.xfer_func = V4L2_XFER_FUNC_SRGB,
304 	.flags = 0,
305 };
306 
307 static const struct v4l2_mbus_framefmt unicam_default_meta_format = {
308 	.width = 640,
309 	.height = 2,
310 	.code = MEDIA_BUS_FMT_META_8,
311 	.field = V4L2_FIELD_NONE,
312 };
313 
314 static const struct unicam_format_info unicam_image_formats[] = {
315 	/* YUV Formats */
316 	{
317 		.fourcc		= V4L2_PIX_FMT_YUYV,
318 		.code		= MEDIA_BUS_FMT_YUYV8_1X16,
319 		.depth		= 16,
320 		.csi_dt		= MIPI_CSI2_DT_YUV422_8B,
321 	}, {
322 		.fourcc		= V4L2_PIX_FMT_UYVY,
323 		.code		= MEDIA_BUS_FMT_UYVY8_1X16,
324 		.depth		= 16,
325 		.csi_dt		= MIPI_CSI2_DT_YUV422_8B,
326 	}, {
327 		.fourcc		= V4L2_PIX_FMT_YVYU,
328 		.code		= MEDIA_BUS_FMT_YVYU8_1X16,
329 		.depth		= 16,
330 		.csi_dt		= MIPI_CSI2_DT_YUV422_8B,
331 	}, {
332 		.fourcc		= V4L2_PIX_FMT_VYUY,
333 		.code		= MEDIA_BUS_FMT_VYUY8_1X16,
334 		.depth		= 16,
335 		.csi_dt		= MIPI_CSI2_DT_YUV422_8B,
336 	}, {
337 	/* RGB Formats */
338 		.fourcc		= V4L2_PIX_FMT_RGB565, /* gggbbbbb rrrrrggg */
339 		.code		= MEDIA_BUS_FMT_RGB565_1X16,
340 		.depth		= 16,
341 		.csi_dt		= MIPI_CSI2_DT_RGB565,
342 	}, {
343 		.fourcc		= V4L2_PIX_FMT_RGB24, /* rgb */
344 		.code		= MEDIA_BUS_FMT_RGB888_1X24,
345 		.depth		= 24,
346 		.csi_dt		= MIPI_CSI2_DT_RGB888,
347 	}, {
348 		.fourcc		= V4L2_PIX_FMT_BGR24, /* bgr */
349 		.code		= MEDIA_BUS_FMT_BGR888_1X24,
350 		.depth		= 24,
351 		.csi_dt		= MIPI_CSI2_DT_RGB888,
352 	}, {
353 	/* Bayer Formats */
354 		.fourcc		= V4L2_PIX_FMT_SBGGR8,
355 		.code		= MEDIA_BUS_FMT_SBGGR8_1X8,
356 		.depth		= 8,
357 		.csi_dt		= MIPI_CSI2_DT_RAW8,
358 	}, {
359 		.fourcc		= V4L2_PIX_FMT_SGBRG8,
360 		.code		= MEDIA_BUS_FMT_SGBRG8_1X8,
361 		.depth		= 8,
362 		.csi_dt		= MIPI_CSI2_DT_RAW8,
363 	}, {
364 		.fourcc		= V4L2_PIX_FMT_SGRBG8,
365 		.code		= MEDIA_BUS_FMT_SGRBG8_1X8,
366 		.depth		= 8,
367 		.csi_dt		= MIPI_CSI2_DT_RAW8,
368 	}, {
369 		.fourcc		= V4L2_PIX_FMT_SRGGB8,
370 		.code		= MEDIA_BUS_FMT_SRGGB8_1X8,
371 		.depth		= 8,
372 		.csi_dt		= MIPI_CSI2_DT_RAW8,
373 	}, {
374 		.fourcc		= V4L2_PIX_FMT_SBGGR10P,
375 		.unpacked_fourcc = V4L2_PIX_FMT_SBGGR10,
376 		.code		= MEDIA_BUS_FMT_SBGGR10_1X10,
377 		.depth		= 10,
378 		.csi_dt		= MIPI_CSI2_DT_RAW10,
379 		.unpack		= UNICAM_PUM_UNPACK10,
380 	}, {
381 		.fourcc		= V4L2_PIX_FMT_SGBRG10P,
382 		.unpacked_fourcc = V4L2_PIX_FMT_SGBRG10,
383 		.code		= MEDIA_BUS_FMT_SGBRG10_1X10,
384 		.depth		= 10,
385 		.csi_dt		= MIPI_CSI2_DT_RAW10,
386 		.unpack		= UNICAM_PUM_UNPACK10,
387 	}, {
388 		.fourcc		= V4L2_PIX_FMT_SGRBG10P,
389 		.unpacked_fourcc = V4L2_PIX_FMT_SGRBG10,
390 		.code		= MEDIA_BUS_FMT_SGRBG10_1X10,
391 		.depth		= 10,
392 		.csi_dt		= MIPI_CSI2_DT_RAW10,
393 		.unpack		= UNICAM_PUM_UNPACK10,
394 	}, {
395 		.fourcc		= V4L2_PIX_FMT_SRGGB10P,
396 		.unpacked_fourcc = V4L2_PIX_FMT_SRGGB10,
397 		.code		= MEDIA_BUS_FMT_SRGGB10_1X10,
398 		.depth		= 10,
399 		.csi_dt		= MIPI_CSI2_DT_RAW10,
400 		.unpack		= UNICAM_PUM_UNPACK10,
401 	}, {
402 		.fourcc		= V4L2_PIX_FMT_SBGGR12P,
403 		.unpacked_fourcc = V4L2_PIX_FMT_SBGGR12,
404 		.code		= MEDIA_BUS_FMT_SBGGR12_1X12,
405 		.depth		= 12,
406 		.csi_dt		= MIPI_CSI2_DT_RAW12,
407 		.unpack		= UNICAM_PUM_UNPACK12,
408 	}, {
409 		.fourcc		= V4L2_PIX_FMT_SGBRG12P,
410 		.unpacked_fourcc = V4L2_PIX_FMT_SGBRG12,
411 		.code		= MEDIA_BUS_FMT_SGBRG12_1X12,
412 		.depth		= 12,
413 		.csi_dt		= MIPI_CSI2_DT_RAW12,
414 		.unpack		= UNICAM_PUM_UNPACK12,
415 	}, {
416 		.fourcc		= V4L2_PIX_FMT_SGRBG12P,
417 		.unpacked_fourcc = V4L2_PIX_FMT_SGRBG12,
418 		.code		= MEDIA_BUS_FMT_SGRBG12_1X12,
419 		.depth		= 12,
420 		.csi_dt		= MIPI_CSI2_DT_RAW12,
421 		.unpack		= UNICAM_PUM_UNPACK12,
422 	}, {
423 		.fourcc		= V4L2_PIX_FMT_SRGGB12P,
424 		.unpacked_fourcc = V4L2_PIX_FMT_SRGGB12,
425 		.code		= MEDIA_BUS_FMT_SRGGB12_1X12,
426 		.depth		= 12,
427 		.csi_dt		= MIPI_CSI2_DT_RAW12,
428 		.unpack		= UNICAM_PUM_UNPACK12,
429 	}, {
430 		.fourcc		= V4L2_PIX_FMT_SBGGR14P,
431 		.unpacked_fourcc = V4L2_PIX_FMT_SBGGR14,
432 		.code		= MEDIA_BUS_FMT_SBGGR14_1X14,
433 		.depth		= 14,
434 		.csi_dt		= MIPI_CSI2_DT_RAW14,
435 		.unpack		= UNICAM_PUM_UNPACK14,
436 	}, {
437 		.fourcc		= V4L2_PIX_FMT_SGBRG14P,
438 		.unpacked_fourcc = V4L2_PIX_FMT_SGBRG14,
439 		.code		= MEDIA_BUS_FMT_SGBRG14_1X14,
440 		.depth		= 14,
441 		.csi_dt		= MIPI_CSI2_DT_RAW14,
442 		.unpack		= UNICAM_PUM_UNPACK14,
443 	}, {
444 		.fourcc		= V4L2_PIX_FMT_SGRBG14P,
445 		.unpacked_fourcc = V4L2_PIX_FMT_SGRBG14,
446 		.code		= MEDIA_BUS_FMT_SGRBG14_1X14,
447 		.depth		= 14,
448 		.csi_dt		= MIPI_CSI2_DT_RAW14,
449 		.unpack		= UNICAM_PUM_UNPACK14,
450 	}, {
451 		.fourcc		= V4L2_PIX_FMT_SRGGB14P,
452 		.unpacked_fourcc = V4L2_PIX_FMT_SRGGB14,
453 		.code		= MEDIA_BUS_FMT_SRGGB14_1X14,
454 		.depth		= 14,
455 		.csi_dt		= MIPI_CSI2_DT_RAW14,
456 		.unpack		= UNICAM_PUM_UNPACK14,
457 	}, {
458 	/* 16 bit Bayer formats could be supported. */
459 
460 	/* Greyscale formats */
461 		.fourcc		= V4L2_PIX_FMT_GREY,
462 		.code		= MEDIA_BUS_FMT_Y8_1X8,
463 		.depth		= 8,
464 		.csi_dt		= MIPI_CSI2_DT_RAW8,
465 	}, {
466 		.fourcc		= V4L2_PIX_FMT_Y10P,
467 		.unpacked_fourcc = V4L2_PIX_FMT_Y10,
468 		.code		= MEDIA_BUS_FMT_Y10_1X10,
469 		.depth		= 10,
470 		.csi_dt		= MIPI_CSI2_DT_RAW10,
471 		.unpack		= UNICAM_PUM_UNPACK10,
472 	}, {
473 		.fourcc		= V4L2_PIX_FMT_Y12P,
474 		.unpacked_fourcc = V4L2_PIX_FMT_Y12,
475 		.code		= MEDIA_BUS_FMT_Y12_1X12,
476 		.depth		= 12,
477 		.csi_dt		= MIPI_CSI2_DT_RAW12,
478 		.unpack		= UNICAM_PUM_UNPACK12,
479 	}, {
480 		.fourcc		= V4L2_PIX_FMT_Y14P,
481 		.unpacked_fourcc = V4L2_PIX_FMT_Y14,
482 		.code		= MEDIA_BUS_FMT_Y14_1X14,
483 		.depth		= 14,
484 		.csi_dt		= MIPI_CSI2_DT_RAW14,
485 		.unpack		= UNICAM_PUM_UNPACK14,
486 	},
487 };
488 
489 static const struct unicam_format_info unicam_meta_formats[] = {
490 	{
491 		.fourcc		= V4L2_META_FMT_GENERIC_8,
492 		.code		= MEDIA_BUS_FMT_META_8,
493 		.depth		= 8,
494 	}, {
495 		.fourcc		= V4L2_META_FMT_GENERIC_CSI2_10,
496 		.code		= MEDIA_BUS_FMT_META_10,
497 		.depth		= 10,
498 	}, {
499 		.fourcc		= V4L2_META_FMT_GENERIC_CSI2_12,
500 		.code		= MEDIA_BUS_FMT_META_12,
501 		.depth		= 12,
502 	}, {
503 		.fourcc		= V4L2_META_FMT_GENERIC_CSI2_14,
504 		.code		= MEDIA_BUS_FMT_META_14,
505 		.depth		= 14,
506 	},
507 };
508 
509 /* Format setup functions */
510 static const struct unicam_format_info *
unicam_find_format_by_code(u32 code,u32 pad)511 unicam_find_format_by_code(u32 code, u32 pad)
512 {
513 	const struct unicam_format_info *formats;
514 	unsigned int num_formats;
515 	unsigned int i;
516 
517 	if (pad == UNICAM_SD_PAD_SOURCE_IMAGE) {
518 		formats = unicam_image_formats;
519 		num_formats = ARRAY_SIZE(unicam_image_formats);
520 	} else {
521 		formats = unicam_meta_formats;
522 		num_formats = ARRAY_SIZE(unicam_meta_formats);
523 	}
524 
525 	for (i = 0; i < num_formats; i++) {
526 		if (formats[i].code == code)
527 			return &formats[i];
528 	}
529 
530 	return NULL;
531 }
532 
533 static const struct unicam_format_info *
unicam_find_format_by_fourcc(u32 fourcc,u32 pad)534 unicam_find_format_by_fourcc(u32 fourcc, u32 pad)
535 {
536 	const struct unicam_format_info *formats;
537 	unsigned int num_formats;
538 	unsigned int i;
539 
540 	if (pad == UNICAM_SD_PAD_SOURCE_IMAGE) {
541 		formats = unicam_image_formats;
542 		num_formats = ARRAY_SIZE(unicam_image_formats);
543 	} else {
544 		formats = unicam_meta_formats;
545 		num_formats = ARRAY_SIZE(unicam_meta_formats);
546 	}
547 
548 	for (i = 0; i < num_formats; ++i) {
549 		if (formats[i].fourcc == fourcc)
550 			return &formats[i];
551 	}
552 
553 	return NULL;
554 }
555 
unicam_calc_image_size_bpl(struct unicam_device * unicam,const struct unicam_format_info * fmtinfo,struct v4l2_pix_format * pix)556 static void unicam_calc_image_size_bpl(struct unicam_device *unicam,
557 				       const struct unicam_format_info *fmtinfo,
558 				       struct v4l2_pix_format *pix)
559 {
560 	u32 min_bpl;
561 
562 	v4l_bound_align_image(&pix->width, UNICAM_IMAGE_MIN_WIDTH,
563 			      UNICAM_IMAGE_MAX_WIDTH, 2,
564 			      &pix->height, UNICAM_IMAGE_MIN_HEIGHT,
565 			      UNICAM_IMAGE_MAX_HEIGHT, 0, 0);
566 
567 	/* Unpacking always goes to 16bpp */
568 	if (pix->pixelformat == fmtinfo->unpacked_fourcc)
569 		min_bpl = pix->width * 2;
570 	else
571 		min_bpl = pix->width * fmtinfo->depth / 8;
572 	min_bpl = ALIGN(min_bpl, UNICAM_IMAGE_BPL_ALIGNMENT);
573 
574 	pix->bytesperline = ALIGN(pix->bytesperline, UNICAM_IMAGE_BPL_ALIGNMENT);
575 	pix->bytesperline = clamp_t(unsigned int, pix->bytesperline, min_bpl,
576 				    UNICAM_IMAGE_MAX_BPL);
577 
578 	pix->sizeimage = pix->height * pix->bytesperline;
579 }
580 
unicam_calc_meta_size_bpl(struct unicam_device * unicam,const struct unicam_format_info * fmtinfo,struct v4l2_meta_format * meta)581 static void unicam_calc_meta_size_bpl(struct unicam_device *unicam,
582 				      const struct unicam_format_info *fmtinfo,
583 				      struct v4l2_meta_format *meta)
584 {
585 	v4l_bound_align_image(&meta->width, UNICAM_META_MIN_WIDTH,
586 			      UNICAM_META_MAX_WIDTH, 0,
587 			      &meta->height, UNICAM_META_MIN_HEIGHT,
588 			      UNICAM_META_MAX_HEIGHT, 0, 0);
589 
590 	meta->bytesperline = ALIGN(meta->width * fmtinfo->depth / 8,
591 				   UNICAM_DMA_BPL_ALIGNMENT);
592 	meta->buffersize = meta->height * meta->bytesperline;
593 }
594 
595 /* -----------------------------------------------------------------------------
596  * Hardware handling
597  */
598 
unicam_clk_write(struct unicam_device * unicam,u32 val)599 static inline void unicam_clk_write(struct unicam_device *unicam, u32 val)
600 {
601 	/* Pass the CM_PASSWORD along with the value. */
602 	writel(val | 0x5a000000, unicam->clk_gate_base);
603 }
604 
unicam_reg_read(struct unicam_device * unicam,u32 offset)605 static inline u32 unicam_reg_read(struct unicam_device *unicam, u32 offset)
606 {
607 	return readl(unicam->base + offset);
608 }
609 
unicam_reg_write(struct unicam_device * unicam,u32 offset,u32 val)610 static inline void unicam_reg_write(struct unicam_device *unicam, u32 offset, u32 val)
611 {
612 	writel(val, unicam->base + offset);
613 }
614 
unicam_get_field(u32 value,u32 mask)615 static inline int unicam_get_field(u32 value, u32 mask)
616 {
617 	return (value & mask) >> __ffs(mask);
618 }
619 
unicam_set_field(u32 * valp,u32 field,u32 mask)620 static inline void unicam_set_field(u32 *valp, u32 field, u32 mask)
621 {
622 	u32 val = *valp;
623 
624 	val &= ~mask;
625 	val |= (field << __ffs(mask)) & mask;
626 	*valp = val;
627 }
628 
unicam_reg_write_field(struct unicam_device * unicam,u32 offset,u32 field,u32 mask)629 static inline void unicam_reg_write_field(struct unicam_device *unicam, u32 offset,
630 					  u32 field, u32 mask)
631 {
632 	u32 val = unicam_reg_read(unicam, offset);
633 
634 	unicam_set_field(&val, field, mask);
635 	unicam_reg_write(unicam, offset, val);
636 }
637 
unicam_wr_dma_addr(struct unicam_node * node,struct unicam_buffer * buf)638 static void unicam_wr_dma_addr(struct unicam_node *node,
639 			       struct unicam_buffer *buf)
640 {
641 	dma_addr_t endaddr = buf->dma_addr + buf->size;
642 
643 	if (node->id == UNICAM_IMAGE_NODE) {
644 		unicam_reg_write(node->dev, UNICAM_IBSA0, buf->dma_addr);
645 		unicam_reg_write(node->dev, UNICAM_IBEA0, endaddr);
646 	} else {
647 		unicam_reg_write(node->dev, UNICAM_DBSA0, buf->dma_addr);
648 		unicam_reg_write(node->dev, UNICAM_DBEA0, endaddr);
649 	}
650 }
651 
unicam_get_lines_done(struct unicam_device * unicam)652 static unsigned int unicam_get_lines_done(struct unicam_device *unicam)
653 {
654 	struct unicam_node *node = &unicam->node[UNICAM_IMAGE_NODE];
655 	unsigned int stride = node->fmt.fmt.pix.bytesperline;
656 	struct unicam_buffer *frm = node->cur_frm;
657 	dma_addr_t cur_addr;
658 
659 	if (!frm)
660 		return 0;
661 
662 	cur_addr = unicam_reg_read(unicam, UNICAM_IBWP);
663 	return (unsigned int)(cur_addr - frm->dma_addr) / stride;
664 }
665 
unicam_schedule_next_buffer(struct unicam_node * node)666 static void unicam_schedule_next_buffer(struct unicam_node *node)
667 {
668 	struct unicam_buffer *buf;
669 
670 	buf = list_first_entry(&node->dma_queue, struct unicam_buffer, list);
671 	node->next_frm = buf;
672 	list_del(&buf->list);
673 
674 	unicam_wr_dma_addr(node, buf);
675 }
676 
unicam_schedule_dummy_buffer(struct unicam_node * node)677 static void unicam_schedule_dummy_buffer(struct unicam_node *node)
678 {
679 	int node_id = is_image_node(node) ? UNICAM_IMAGE_NODE : UNICAM_METADATA_NODE;
680 
681 	dev_dbg(node->dev->dev, "Scheduling dummy buffer for node %d\n", node_id);
682 
683 	unicam_wr_dma_addr(node, &node->dummy_buf);
684 
685 	node->next_frm = NULL;
686 }
687 
unicam_process_buffer_complete(struct unicam_node * node,unsigned int sequence)688 static void unicam_process_buffer_complete(struct unicam_node *node,
689 					   unsigned int sequence)
690 {
691 	node->cur_frm->vb.field = node->fmt.fmt.pix.field;
692 	node->cur_frm->vb.sequence = sequence;
693 
694 	vb2_buffer_done(&node->cur_frm->vb.vb2_buf, VB2_BUF_STATE_DONE);
695 }
696 
unicam_queue_event_sof(struct unicam_device * unicam)697 static void unicam_queue_event_sof(struct unicam_device *unicam)
698 {
699 	struct unicam_node *node = &unicam->node[UNICAM_IMAGE_NODE];
700 	struct v4l2_event event = {
701 		.type = V4L2_EVENT_FRAME_SYNC,
702 		.u.frame_sync.frame_sequence = unicam->sequence,
703 	};
704 
705 	v4l2_event_queue(&node->video_dev, &event);
706 }
707 
unicam_isr(int irq,void * dev)708 static irqreturn_t unicam_isr(int irq, void *dev)
709 {
710 	struct unicam_device *unicam = dev;
711 	unsigned int lines_done = unicam_get_lines_done(dev);
712 	unsigned int sequence = unicam->sequence;
713 	unsigned int i;
714 	u32 ista, sta;
715 	bool fe;
716 	u64 ts;
717 
718 	sta = unicam_reg_read(unicam, UNICAM_STA);
719 	/* Write value back to clear the interrupts */
720 	unicam_reg_write(unicam, UNICAM_STA, sta);
721 
722 	ista = unicam_reg_read(unicam, UNICAM_ISTA);
723 	/* Write value back to clear the interrupts */
724 	unicam_reg_write(unicam, UNICAM_ISTA, ista);
725 
726 	dev_dbg(unicam->dev, "ISR: ISTA: 0x%X, STA: 0x%X, sequence %d, lines done %d\n",
727 		ista, sta, sequence, lines_done);
728 
729 	if (!(sta & (UNICAM_IS | UNICAM_PI0)))
730 		return IRQ_HANDLED;
731 
732 	/*
733 	 * Look for either the Frame End interrupt or the Packet Capture status
734 	 * to signal a frame end.
735 	 */
736 	fe = ista & UNICAM_FEI || sta & UNICAM_PI0;
737 
738 	/*
739 	 * We must run the frame end handler first. If we have a valid next_frm
740 	 * and we get a simultaneout FE + FS interrupt, running the FS handler
741 	 * first would null out the next_frm ptr and we would have lost the
742 	 * buffer forever.
743 	 */
744 	if (fe) {
745 		/*
746 		 * Ensure we have swapped buffers already as we can't
747 		 * stop the peripheral. If no buffer is available, use a
748 		 * dummy buffer to dump out frames until we get a new buffer
749 		 * to use.
750 		 */
751 		for (i = 0; i < ARRAY_SIZE(unicam->node); i++) {
752 			struct unicam_node *node = &unicam->node[i];
753 
754 			if (!vb2_start_streaming_called(&node->buffer_queue))
755 				continue;
756 
757 			/*
758 			 * If cur_frm == next_frm, it means we have not had
759 			 * a chance to swap buffers, likely due to having
760 			 * multiple interrupts occurring simultaneously (like FE
761 			 * + FS + LS). In this case, we cannot signal the buffer
762 			 * as complete, as the HW will reuse that buffer.
763 			 */
764 			if (node->cur_frm && node->cur_frm != node->next_frm)
765 				unicam_process_buffer_complete(node, sequence);
766 			node->cur_frm = node->next_frm;
767 		}
768 		unicam->sequence++;
769 	}
770 
771 	if (ista & UNICAM_FSI) {
772 		/*
773 		 * Timestamp is to be when the first data byte was captured,
774 		 * aka frame start.
775 		 */
776 		ts = ktime_get_ns();
777 		for (i = 0; i < ARRAY_SIZE(unicam->node); i++) {
778 			struct unicam_node *node = &unicam->node[i];
779 
780 			if (!vb2_start_streaming_called(&node->buffer_queue))
781 				continue;
782 
783 			if (node->cur_frm)
784 				node->cur_frm->vb.vb2_buf.timestamp = ts;
785 			else
786 				dev_dbg(unicam->v4l2_dev.dev,
787 					"ISR: [%d] Dropping frame, buffer not available at FS\n",
788 					i);
789 			/*
790 			 * Set the next frame output to go to a dummy frame
791 			 * if we have not managed to obtain another frame
792 			 * from the queue.
793 			 */
794 			unicam_schedule_dummy_buffer(node);
795 		}
796 
797 		unicam_queue_event_sof(unicam);
798 	}
799 
800 	/*
801 	 * Cannot swap buffer at frame end, there may be a race condition
802 	 * where the HW does not actually swap it if the new frame has
803 	 * already started.
804 	 */
805 	if (ista & (UNICAM_FSI | UNICAM_LCI) && !fe) {
806 		for (i = 0; i < ARRAY_SIZE(unicam->node); i++) {
807 			struct unicam_node *node = &unicam->node[i];
808 
809 			if (!vb2_start_streaming_called(&node->buffer_queue))
810 				continue;
811 
812 			spin_lock(&node->dma_queue_lock);
813 			if (!list_empty(&node->dma_queue) && !node->next_frm)
814 				unicam_schedule_next_buffer(node);
815 			spin_unlock(&node->dma_queue_lock);
816 		}
817 	}
818 
819 	return IRQ_HANDLED;
820 }
821 
unicam_set_packing_config(struct unicam_device * unicam,const struct unicam_format_info * fmtinfo)822 static void unicam_set_packing_config(struct unicam_device *unicam,
823 				      const struct unicam_format_info *fmtinfo)
824 {
825 	struct unicam_node *node = &unicam->node[UNICAM_IMAGE_NODE];
826 	u32 pack, unpack;
827 	u32 val;
828 
829 	if (node->fmt.fmt.pix.pixelformat == fmtinfo->fourcc) {
830 		unpack = UNICAM_PUM_NONE;
831 		pack = UNICAM_PPM_NONE;
832 	} else {
833 		unpack = fmtinfo->unpack;
834 		/* Repacking is always to 16bpp */
835 		pack = UNICAM_PPM_PACK16;
836 	}
837 
838 	val = 0;
839 	unicam_set_field(&val, unpack, UNICAM_PUM_MASK);
840 	unicam_set_field(&val, pack, UNICAM_PPM_MASK);
841 	unicam_reg_write(unicam, UNICAM_IPIPE, val);
842 }
843 
unicam_cfg_image_id(struct unicam_device * unicam,u8 vc,u8 dt)844 static void unicam_cfg_image_id(struct unicam_device *unicam, u8 vc, u8 dt)
845 {
846 	if (unicam->bus_type == V4L2_MBUS_CSI2_DPHY) {
847 		/* CSI2 mode  */
848 		unicam_reg_write(unicam, UNICAM_IDI0, (vc << 6) | dt);
849 	} else {
850 		/* CCP2 mode */
851 		unicam_reg_write(unicam, UNICAM_IDI0, 0x80 | dt);
852 	}
853 }
854 
unicam_enable_ed(struct unicam_device * unicam)855 static void unicam_enable_ed(struct unicam_device *unicam)
856 {
857 	u32 val = unicam_reg_read(unicam, UNICAM_DCS);
858 
859 	unicam_set_field(&val, 2, UNICAM_EDL_MASK);
860 	/* Do not wrap at the end of the embedded data buffer */
861 	unicam_set_field(&val, 0, UNICAM_DBOB);
862 
863 	unicam_reg_write(unicam, UNICAM_DCS, val);
864 }
865 
unicam_get_image_vc_dt(struct unicam_device * unicam,struct v4l2_subdev_state * state,u8 * vc,u8 * dt)866 static int unicam_get_image_vc_dt(struct unicam_device *unicam,
867 				  struct v4l2_subdev_state *state,
868 				  u8 *vc, u8 *dt)
869 {
870 	struct v4l2_mbus_frame_desc fd;
871 	u32 stream;
872 	int ret;
873 
874 	ret = v4l2_subdev_routing_find_opposite_end(&state->routing,
875 						    UNICAM_SD_PAD_SOURCE_IMAGE,
876 						    0, NULL, &stream);
877 	if (ret)
878 		return ret;
879 
880 	ret = v4l2_subdev_call(unicam->sensor.subdev, pad, get_frame_desc,
881 			       unicam->sensor.pad->index, &fd);
882 	if (ret)
883 		return ret;
884 
885 	/* Only CSI-2 supports DTs. */
886 	if (fd.type != V4L2_MBUS_FRAME_DESC_TYPE_CSI2)
887 		return -EINVAL;
888 
889 	for (unsigned int i = 0; i < fd.num_entries; ++i) {
890 		const struct v4l2_mbus_frame_desc_entry *fde = &fd.entry[i];
891 
892 		if (fde->stream == stream) {
893 			*vc = fde->bus.csi2.vc;
894 			*dt = fde->bus.csi2.dt;
895 			return 0;
896 		}
897 	}
898 
899 	return -EINVAL;
900 }
901 
unicam_start_rx(struct unicam_device * unicam,struct v4l2_subdev_state * state)902 static void unicam_start_rx(struct unicam_device *unicam,
903 			    struct v4l2_subdev_state *state)
904 {
905 	struct unicam_node *node = &unicam->node[UNICAM_IMAGE_NODE];
906 	const struct unicam_format_info *fmtinfo;
907 	const struct v4l2_mbus_framefmt *fmt;
908 	unsigned int line_int_freq;
909 	u8 vc, dt;
910 	u32 val;
911 	int ret;
912 
913 	fmt = v4l2_subdev_state_get_format(state, UNICAM_SD_PAD_SOURCE_IMAGE, 0);
914 	fmtinfo = unicam_find_format_by_code(fmt->code,
915 					     UNICAM_SD_PAD_SOURCE_IMAGE);
916 	if (WARN_ON(!fmtinfo))
917 		return;
918 
919 	/*
920 	 * Enable lane clocks. The register is structured as follows:
921 	 *
922 	 * [9:8] - DAT3
923 	 * [7:6] - DAT2
924 	 * [5:4] - DAT1
925 	 * [3:2] - DAT0
926 	 * [1:0] - CLK
927 	 *
928 	 * Enabled lane must be set to b01, and disabled lanes to b00. The clock
929 	 * lane is always enabled.
930 	 */
931 	val = 0x155 & GENMASK(unicam->pipe.num_data_lanes * 2 + 1, 0);
932 	unicam_clk_write(unicam, val);
933 
934 	/* Basic init */
935 	unicam_reg_write(unicam, UNICAM_CTRL, UNICAM_MEM);
936 
937 	/* Enable analogue control, and leave in reset. */
938 	val = UNICAM_AR;
939 	unicam_set_field(&val, 7, UNICAM_CTATADJ_MASK);
940 	unicam_set_field(&val, 7, UNICAM_PTATADJ_MASK);
941 	unicam_reg_write(unicam, UNICAM_ANA, val);
942 	usleep_range(1000, 2000);
943 
944 	/* Come out of reset */
945 	unicam_reg_write_field(unicam, UNICAM_ANA, 0, UNICAM_AR);
946 
947 	/* Peripheral reset */
948 	unicam_reg_write_field(unicam, UNICAM_CTRL, 1, UNICAM_CPR);
949 	unicam_reg_write_field(unicam, UNICAM_CTRL, 0, UNICAM_CPR);
950 
951 	unicam_reg_write_field(unicam, UNICAM_CTRL, 0, UNICAM_CPE);
952 
953 	/* Enable Rx control. */
954 	val = unicam_reg_read(unicam, UNICAM_CTRL);
955 	if (unicam->bus_type == V4L2_MBUS_CSI2_DPHY) {
956 		unicam_set_field(&val, UNICAM_CPM_CSI2, UNICAM_CPM_MASK);
957 		unicam_set_field(&val, UNICAM_DCM_STROBE, UNICAM_DCM_MASK);
958 	} else {
959 		unicam_set_field(&val, UNICAM_CPM_CCP2, UNICAM_CPM_MASK);
960 		unicam_set_field(&val, unicam->bus_flags, UNICAM_DCM_MASK);
961 	}
962 	/* Packet framer timeout */
963 	unicam_set_field(&val, 0xf, UNICAM_PFT_MASK);
964 	unicam_set_field(&val, 128, UNICAM_OET_MASK);
965 	unicam_reg_write(unicam, UNICAM_CTRL, val);
966 
967 	unicam_reg_write(unicam, UNICAM_IHWIN, 0);
968 	unicam_reg_write(unicam, UNICAM_IVWIN, 0);
969 
970 	/* AXI bus access QoS setup */
971 	val = unicam_reg_read(unicam, UNICAM_PRI);
972 	unicam_set_field(&val, 0, UNICAM_BL_MASK);
973 	unicam_set_field(&val, 0, UNICAM_BS_MASK);
974 	unicam_set_field(&val, 0xe, UNICAM_PP_MASK);
975 	unicam_set_field(&val, 8, UNICAM_NP_MASK);
976 	unicam_set_field(&val, 2, UNICAM_PT_MASK);
977 	unicam_set_field(&val, 1, UNICAM_PE);
978 	unicam_reg_write(unicam, UNICAM_PRI, val);
979 
980 	unicam_reg_write_field(unicam, UNICAM_ANA, 0, UNICAM_DDL);
981 
982 	val = UNICAM_FSIE | UNICAM_FEIE | UNICAM_IBOB;
983 	line_int_freq = max(fmt->height >> 2, 128);
984 	unicam_set_field(&val, line_int_freq, UNICAM_LCIE_MASK);
985 	unicam_reg_write(unicam, UNICAM_ICTL, val);
986 	unicam_reg_write(unicam, UNICAM_STA, UNICAM_STA_MASK_ALL);
987 	unicam_reg_write(unicam, UNICAM_ISTA, UNICAM_ISTA_MASK_ALL);
988 
989 	/* tclk_term_en */
990 	unicam_reg_write_field(unicam, UNICAM_CLT, 2, UNICAM_CLT1_MASK);
991 	/* tclk_settle */
992 	unicam_reg_write_field(unicam, UNICAM_CLT, 6, UNICAM_CLT2_MASK);
993 	/* td_term_en */
994 	unicam_reg_write_field(unicam, UNICAM_DLT, 2, UNICAM_DLT1_MASK);
995 	/* ths_settle */
996 	unicam_reg_write_field(unicam, UNICAM_DLT, 6, UNICAM_DLT2_MASK);
997 	/* trx_enable */
998 	unicam_reg_write_field(unicam, UNICAM_DLT, 0, UNICAM_DLT3_MASK);
999 
1000 	unicam_reg_write_field(unicam, UNICAM_CTRL, 0, UNICAM_SOE);
1001 
1002 	/* Packet compare setup - required to avoid missing frame ends */
1003 	val = 0;
1004 	unicam_set_field(&val, 1, UNICAM_PCE);
1005 	unicam_set_field(&val, 1, UNICAM_GI);
1006 	unicam_set_field(&val, 1, UNICAM_CPH);
1007 	unicam_set_field(&val, 0, UNICAM_PCVC_MASK);
1008 	unicam_set_field(&val, 1, UNICAM_PCDT_MASK);
1009 	unicam_reg_write(unicam, UNICAM_CMP0, val);
1010 
1011 	/* Enable clock lane and set up terminations */
1012 	val = 0;
1013 	if (unicam->bus_type == V4L2_MBUS_CSI2_DPHY) {
1014 		/* CSI2 */
1015 		unicam_set_field(&val, 1, UNICAM_CLE);
1016 		unicam_set_field(&val, 1, UNICAM_CLLPE);
1017 		if (!(unicam->bus_flags & V4L2_MBUS_CSI2_NONCONTINUOUS_CLOCK)) {
1018 			unicam_set_field(&val, 1, UNICAM_CLTRE);
1019 			unicam_set_field(&val, 1, UNICAM_CLHSE);
1020 		}
1021 	} else {
1022 		/* CCP2 */
1023 		unicam_set_field(&val, 1, UNICAM_CLE);
1024 		unicam_set_field(&val, 1, UNICAM_CLHSE);
1025 		unicam_set_field(&val, 1, UNICAM_CLTRE);
1026 	}
1027 	unicam_reg_write(unicam, UNICAM_CLK, val);
1028 
1029 	/*
1030 	 * Enable required data lanes with appropriate terminations.
1031 	 * The same value needs to be written to UNICAM_DATn registers for
1032 	 * the active lanes, and 0 for inactive ones.
1033 	 */
1034 	val = 0;
1035 	if (unicam->bus_type == V4L2_MBUS_CSI2_DPHY) {
1036 		/* CSI2 */
1037 		unicam_set_field(&val, 1, UNICAM_DLE);
1038 		unicam_set_field(&val, 1, UNICAM_DLLPE);
1039 		if (!(unicam->bus_flags & V4L2_MBUS_CSI2_NONCONTINUOUS_CLOCK)) {
1040 			unicam_set_field(&val, 1, UNICAM_DLTRE);
1041 			unicam_set_field(&val, 1, UNICAM_DLHSE);
1042 		}
1043 	} else {
1044 		/* CCP2 */
1045 		unicam_set_field(&val, 1, UNICAM_DLE);
1046 		unicam_set_field(&val, 1, UNICAM_DLHSE);
1047 		unicam_set_field(&val, 1, UNICAM_DLTRE);
1048 	}
1049 	unicam_reg_write(unicam, UNICAM_DAT0, val);
1050 
1051 	if (unicam->pipe.num_data_lanes == 1)
1052 		val = 0;
1053 	unicam_reg_write(unicam, UNICAM_DAT1, val);
1054 
1055 	if (unicam->max_data_lanes > 2) {
1056 		/*
1057 		 * Registers UNICAM_DAT2 and UNICAM_DAT3 only valid if the
1058 		 * instance supports more than 2 data lanes.
1059 		 */
1060 		if (unicam->pipe.num_data_lanes == 2)
1061 			val = 0;
1062 		unicam_reg_write(unicam, UNICAM_DAT2, val);
1063 
1064 		if (unicam->pipe.num_data_lanes == 3)
1065 			val = 0;
1066 		unicam_reg_write(unicam, UNICAM_DAT3, val);
1067 	}
1068 
1069 	unicam_reg_write(unicam, UNICAM_IBLS,
1070 			 node->fmt.fmt.pix.bytesperline);
1071 	unicam_wr_dma_addr(node, node->cur_frm);
1072 	unicam_set_packing_config(unicam, fmtinfo);
1073 
1074 	ret = unicam_get_image_vc_dt(unicam, state, &vc, &dt);
1075 	if (ret) {
1076 		/*
1077 		 * If the source doesn't support frame descriptors, default to
1078 		 * VC 0 and use the DT corresponding to the format.
1079 		 */
1080 		vc = 0;
1081 		dt = fmtinfo->csi_dt;
1082 	}
1083 
1084 	unicam_cfg_image_id(unicam, vc, dt);
1085 
1086 	val = unicam_reg_read(unicam, UNICAM_MISC);
1087 	unicam_set_field(&val, 1, UNICAM_FL0);
1088 	unicam_set_field(&val, 1, UNICAM_FL1);
1089 	unicam_reg_write(unicam, UNICAM_MISC, val);
1090 
1091 	/* Enable peripheral */
1092 	unicam_reg_write_field(unicam, UNICAM_CTRL, 1, UNICAM_CPE);
1093 
1094 	/* Load image pointers */
1095 	unicam_reg_write_field(unicam, UNICAM_ICTL, 1, UNICAM_LIP_MASK);
1096 
1097 	/*
1098 	 * Enable trigger only for the first frame to
1099 	 * sync correctly to the FS from the source.
1100 	 */
1101 	unicam_reg_write_field(unicam, UNICAM_ICTL, 1, UNICAM_TFC);
1102 }
1103 
unicam_start_metadata(struct unicam_device * unicam)1104 static void unicam_start_metadata(struct unicam_device *unicam)
1105 {
1106 	struct unicam_node *node = &unicam->node[UNICAM_METADATA_NODE];
1107 
1108 	unicam_enable_ed(unicam);
1109 	unicam_wr_dma_addr(node, node->cur_frm);
1110 	unicam_reg_write_field(unicam, UNICAM_DCS, 1, UNICAM_LDP);
1111 }
1112 
unicam_disable(struct unicam_device * unicam)1113 static void unicam_disable(struct unicam_device *unicam)
1114 {
1115 	/* Analogue lane control disable */
1116 	unicam_reg_write_field(unicam, UNICAM_ANA, 1, UNICAM_DDL);
1117 
1118 	/* Stop the output engine */
1119 	unicam_reg_write_field(unicam, UNICAM_CTRL, 1, UNICAM_SOE);
1120 
1121 	/* Disable the data lanes. */
1122 	unicam_reg_write(unicam, UNICAM_DAT0, 0);
1123 	unicam_reg_write(unicam, UNICAM_DAT1, 0);
1124 
1125 	if (unicam->max_data_lanes > 2) {
1126 		unicam_reg_write(unicam, UNICAM_DAT2, 0);
1127 		unicam_reg_write(unicam, UNICAM_DAT3, 0);
1128 	}
1129 
1130 	/* Peripheral reset */
1131 	unicam_reg_write_field(unicam, UNICAM_CTRL, 1, UNICAM_CPR);
1132 	usleep_range(50, 100);
1133 	unicam_reg_write_field(unicam, UNICAM_CTRL, 0, UNICAM_CPR);
1134 
1135 	/* Disable peripheral */
1136 	unicam_reg_write_field(unicam, UNICAM_CTRL, 0, UNICAM_CPE);
1137 
1138 	/* Clear ED setup */
1139 	unicam_reg_write(unicam, UNICAM_DCS, 0);
1140 
1141 	/* Disable all lane clocks */
1142 	unicam_clk_write(unicam, 0);
1143 }
1144 
1145 /* -----------------------------------------------------------------------------
1146  * V4L2 subdev operations
1147  */
1148 
__unicam_subdev_set_routing(struct v4l2_subdev * sd,struct v4l2_subdev_state * state,struct v4l2_subdev_krouting * routing)1149 static int __unicam_subdev_set_routing(struct v4l2_subdev *sd,
1150 				       struct v4l2_subdev_state *state,
1151 				       struct v4l2_subdev_krouting *routing)
1152 {
1153 	struct v4l2_subdev_route *route;
1154 	int ret;
1155 
1156 	ret = v4l2_subdev_routing_validate(sd, routing,
1157 					   V4L2_SUBDEV_ROUTING_ONLY_1_TO_1);
1158 	if (ret)
1159 		return ret;
1160 
1161 	ret = v4l2_subdev_set_routing(sd, state, routing);
1162 	if (ret)
1163 		return ret;
1164 
1165 	for_each_active_route(&state->routing, route) {
1166 		const struct v4l2_mbus_framefmt *def_fmt;
1167 		struct v4l2_mbus_framefmt *fmt;
1168 
1169 		if (route->source_pad == UNICAM_SD_PAD_SOURCE_IMAGE)
1170 			def_fmt = &unicam_default_image_format;
1171 		else
1172 			def_fmt = &unicam_default_meta_format;
1173 
1174 		fmt = v4l2_subdev_state_get_format(state, route->sink_pad,
1175 						   route->sink_stream);
1176 		*fmt = *def_fmt;
1177 		fmt = v4l2_subdev_state_get_format(state, route->source_pad,
1178 						   route->source_stream);
1179 		*fmt = *def_fmt;
1180 	}
1181 
1182 	return 0;
1183 }
1184 
unicam_subdev_init_state(struct v4l2_subdev * sd,struct v4l2_subdev_state * state)1185 static int unicam_subdev_init_state(struct v4l2_subdev *sd,
1186 				    struct v4l2_subdev_state *state)
1187 {
1188 	struct v4l2_subdev_route routes[] = {
1189 		{
1190 			.sink_pad = UNICAM_SD_PAD_SINK,
1191 			.sink_stream = 0,
1192 			.source_pad = UNICAM_SD_PAD_SOURCE_IMAGE,
1193 			.source_stream = 0,
1194 			.flags = V4L2_SUBDEV_ROUTE_FL_ACTIVE,
1195 		},
1196 	};
1197 
1198 	struct v4l2_subdev_krouting routing = {
1199 		.len_routes = ARRAY_SIZE(routes),
1200 		.num_routes = ARRAY_SIZE(routes),
1201 		.routes = routes,
1202 	};
1203 
1204 	/* Initialize routing to single route to the fist source pad. */
1205 	return __unicam_subdev_set_routing(sd, state, &routing);
1206 }
1207 
unicam_subdev_enum_mbus_code(struct v4l2_subdev * sd,struct v4l2_subdev_state * state,struct v4l2_subdev_mbus_code_enum * code)1208 static int unicam_subdev_enum_mbus_code(struct v4l2_subdev *sd,
1209 					struct v4l2_subdev_state *state,
1210 					struct v4l2_subdev_mbus_code_enum *code)
1211 {
1212 	u32 pad, stream;
1213 	int ret;
1214 
1215 	ret = v4l2_subdev_routing_find_opposite_end(&state->routing,
1216 						    code->pad, code->stream,
1217 						    &pad, &stream);
1218 	if (ret)
1219 		return ret;
1220 
1221 	if (unicam_sd_pad_is_source(code->pad)) {
1222 		/* No transcoding, source and sink codes must match. */
1223 		const struct v4l2_mbus_framefmt *fmt;
1224 
1225 		fmt = v4l2_subdev_state_get_format(state, pad, stream);
1226 		if (!fmt)
1227 			return -EINVAL;
1228 
1229 		if (code->index > 0)
1230 			return -EINVAL;
1231 
1232 		code->code = fmt->code;
1233 	} else {
1234 		const struct unicam_format_info *formats;
1235 		unsigned int num_formats;
1236 
1237 		if (pad == UNICAM_SD_PAD_SOURCE_IMAGE) {
1238 			formats = unicam_image_formats;
1239 			num_formats = ARRAY_SIZE(unicam_image_formats);
1240 		} else {
1241 			formats = unicam_meta_formats;
1242 			num_formats = ARRAY_SIZE(unicam_meta_formats);
1243 		}
1244 
1245 		if (code->index >= num_formats)
1246 			return -EINVAL;
1247 
1248 		code->code = formats[code->index].code;
1249 	}
1250 
1251 	return 0;
1252 }
1253 
unicam_subdev_enum_frame_size(struct v4l2_subdev * sd,struct v4l2_subdev_state * state,struct v4l2_subdev_frame_size_enum * fse)1254 static int unicam_subdev_enum_frame_size(struct v4l2_subdev *sd,
1255 					 struct v4l2_subdev_state *state,
1256 					 struct v4l2_subdev_frame_size_enum *fse)
1257 {
1258 	u32 pad, stream;
1259 	int ret;
1260 
1261 	if (fse->index > 0)
1262 		return -EINVAL;
1263 
1264 	ret = v4l2_subdev_routing_find_opposite_end(&state->routing, fse->pad,
1265 						    fse->stream, &pad,
1266 						    &stream);
1267 	if (ret)
1268 		return ret;
1269 
1270 	if (unicam_sd_pad_is_source(fse->pad)) {
1271 		/* No transcoding, source and sink formats must match. */
1272 		const struct v4l2_mbus_framefmt *fmt;
1273 
1274 		fmt = v4l2_subdev_state_get_format(state, pad, stream);
1275 		if (!fmt)
1276 			return -EINVAL;
1277 
1278 		if (fse->code != fmt->code)
1279 			return -EINVAL;
1280 
1281 		fse->min_width = fmt->width;
1282 		fse->max_width = fmt->width;
1283 		fse->min_height = fmt->height;
1284 		fse->max_height = fmt->height;
1285 	} else {
1286 		const struct unicam_format_info *fmtinfo;
1287 
1288 		fmtinfo = unicam_find_format_by_code(fse->code, pad);
1289 		if (!fmtinfo)
1290 			return -EINVAL;
1291 
1292 		if (pad == UNICAM_SD_PAD_SOURCE_IMAGE) {
1293 			fse->min_width = UNICAM_IMAGE_MIN_WIDTH;
1294 			fse->max_width = UNICAM_IMAGE_MAX_WIDTH;
1295 			fse->min_height = UNICAM_IMAGE_MIN_HEIGHT;
1296 			fse->max_height = UNICAM_IMAGE_MAX_HEIGHT;
1297 		} else {
1298 			fse->min_width = UNICAM_META_MIN_WIDTH;
1299 			fse->max_width = UNICAM_META_MAX_WIDTH;
1300 			fse->min_height = UNICAM_META_MIN_HEIGHT;
1301 			fse->max_height = UNICAM_META_MAX_HEIGHT;
1302 		}
1303 	}
1304 
1305 	return 0;
1306 }
1307 
unicam_subdev_set_format(struct v4l2_subdev * sd,struct v4l2_subdev_state * state,struct v4l2_subdev_format * format)1308 static int unicam_subdev_set_format(struct v4l2_subdev *sd,
1309 				    struct v4l2_subdev_state *state,
1310 				    struct v4l2_subdev_format *format)
1311 {
1312 	struct unicam_device *unicam = sd_to_unicam_device(sd);
1313 	struct v4l2_mbus_framefmt *sink_format, *source_format;
1314 	const struct unicam_format_info *fmtinfo;
1315 	u32 source_pad, source_stream;
1316 	int ret;
1317 
1318 	if (format->which == V4L2_SUBDEV_FORMAT_ACTIVE &&
1319 	    unicam->subdev.enabled_streams)
1320 		return -EBUSY;
1321 
1322 	/* No transcoding, source and sink formats must match. */
1323 	if (unicam_sd_pad_is_source(format->pad))
1324 		return v4l2_subdev_get_fmt(sd, state, format);
1325 
1326 	/*
1327 	 * Allowed formats for the stream on the sink pad depend on what source
1328 	 * pad the stream is routed to. Find the corresponding source pad and
1329 	 * use it to validate the media bus code.
1330 	 */
1331 	ret = v4l2_subdev_routing_find_opposite_end(&state->routing,
1332 						    format->pad, format->stream,
1333 						    &source_pad, &source_stream);
1334 	if (ret)
1335 		return ret;
1336 
1337 	fmtinfo = unicam_find_format_by_code(format->format.code, source_pad);
1338 	if (!fmtinfo) {
1339 		fmtinfo = source_pad == UNICAM_SD_PAD_SOURCE_IMAGE
1340 			? &unicam_image_formats[0] : &unicam_meta_formats[0];
1341 		format->format.code = fmtinfo->code;
1342 	}
1343 
1344 	if (source_pad == UNICAM_SD_PAD_SOURCE_IMAGE) {
1345 		format->format.width = clamp_t(unsigned int,
1346 					       format->format.width,
1347 					       UNICAM_IMAGE_MIN_WIDTH,
1348 					       UNICAM_IMAGE_MAX_WIDTH);
1349 		format->format.height = clamp_t(unsigned int,
1350 						format->format.height,
1351 						UNICAM_IMAGE_MIN_HEIGHT,
1352 						UNICAM_IMAGE_MAX_HEIGHT);
1353 		format->format.field = V4L2_FIELD_NONE;
1354 	} else {
1355 		format->format.width = clamp_t(unsigned int,
1356 					       format->format.width,
1357 					       UNICAM_META_MIN_WIDTH,
1358 					       UNICAM_META_MAX_WIDTH);
1359 		format->format.height = clamp_t(unsigned int,
1360 						format->format.height,
1361 						UNICAM_META_MIN_HEIGHT,
1362 						UNICAM_META_MAX_HEIGHT);
1363 		format->format.field = V4L2_FIELD_NONE;
1364 
1365 		/* Colorspace don't apply to metadata. */
1366 		format->format.colorspace = 0;
1367 		format->format.ycbcr_enc = 0;
1368 		format->format.quantization = 0;
1369 		format->format.xfer_func = 0;
1370 	}
1371 
1372 	sink_format = v4l2_subdev_state_get_format(state, format->pad,
1373 						   format->stream);
1374 	source_format = v4l2_subdev_state_get_format(state, source_pad,
1375 						     source_stream);
1376 	*sink_format = format->format;
1377 	*source_format = format->format;
1378 
1379 	return 0;
1380 }
1381 
unicam_subdev_set_routing(struct v4l2_subdev * sd,struct v4l2_subdev_state * state,enum v4l2_subdev_format_whence which,struct v4l2_subdev_krouting * routing)1382 static int unicam_subdev_set_routing(struct v4l2_subdev *sd,
1383 				     struct v4l2_subdev_state *state,
1384 				     enum v4l2_subdev_format_whence which,
1385 				     struct v4l2_subdev_krouting *routing)
1386 {
1387 	struct unicam_device *unicam = sd_to_unicam_device(sd);
1388 
1389 	if (which == V4L2_SUBDEV_FORMAT_ACTIVE && unicam->subdev.enabled_streams)
1390 		return -EBUSY;
1391 
1392 	return __unicam_subdev_set_routing(sd, state, routing);
1393 }
1394 
unicam_sd_enable_streams(struct v4l2_subdev * sd,struct v4l2_subdev_state * state,u32 pad,u64 streams_mask)1395 static int unicam_sd_enable_streams(struct v4l2_subdev *sd,
1396 				    struct v4l2_subdev_state *state, u32 pad,
1397 				    u64 streams_mask)
1398 {
1399 	struct unicam_device *unicam = sd_to_unicam_device(sd);
1400 	u32 other_pad, other_stream;
1401 	int ret;
1402 
1403 	if (!unicam->subdev.enabled_streams) {
1404 		/* Configure and start Unicam. */
1405 		unicam->sequence = 0;
1406 
1407 		if (unicam->pipe.nodes & BIT(UNICAM_METADATA_NODE))
1408 			unicam_start_metadata(unicam);
1409 
1410 		unicam_start_rx(unicam, state);
1411 	}
1412 
1413 	ret = v4l2_subdev_routing_find_opposite_end(&state->routing, pad, 0,
1414 						    &other_pad, &other_stream);
1415 	if (ret)
1416 		return ret;
1417 
1418 	ret = v4l2_subdev_enable_streams(unicam->sensor.subdev,
1419 					 unicam->sensor.pad->index,
1420 					 BIT(other_stream));
1421 	if (ret) {
1422 		dev_err(unicam->dev, "stream on failed in subdev\n");
1423 		return ret;
1424 	}
1425 
1426 	unicam->subdev.enabled_streams |= BIT(other_stream);
1427 
1428 	return 0;
1429 }
1430 
unicam_sd_disable_streams(struct v4l2_subdev * sd,struct v4l2_subdev_state * state,u32 pad,u64 streams_mask)1431 static int unicam_sd_disable_streams(struct v4l2_subdev *sd,
1432 				     struct v4l2_subdev_state *state, u32 pad,
1433 				     u64 streams_mask)
1434 {
1435 	struct unicam_device *unicam = sd_to_unicam_device(sd);
1436 	u32 other_pad, other_stream;
1437 	int ret;
1438 
1439 	ret = v4l2_subdev_routing_find_opposite_end(&state->routing, pad, 0,
1440 						    &other_pad, &other_stream);
1441 	if (ret)
1442 		return ret;
1443 
1444 	v4l2_subdev_disable_streams(unicam->sensor.subdev,
1445 				    unicam->sensor.pad->index,
1446 				    BIT(other_stream));
1447 
1448 	unicam->subdev.enabled_streams &= ~BIT(other_stream);
1449 
1450 	if (!unicam->subdev.enabled_streams)
1451 		unicam_disable(unicam);
1452 
1453 	return 0;
1454 }
1455 
1456 static const struct v4l2_subdev_pad_ops unicam_subdev_pad_ops = {
1457 	.enum_mbus_code		= unicam_subdev_enum_mbus_code,
1458 	.enum_frame_size	= unicam_subdev_enum_frame_size,
1459 	.get_fmt		= v4l2_subdev_get_fmt,
1460 	.set_fmt		= unicam_subdev_set_format,
1461 	.set_routing		= unicam_subdev_set_routing,
1462 	.enable_streams		= unicam_sd_enable_streams,
1463 	.disable_streams	= unicam_sd_disable_streams,
1464 };
1465 
1466 static const struct v4l2_subdev_ops unicam_subdev_ops = {
1467 	.pad			= &unicam_subdev_pad_ops,
1468 };
1469 
1470 static const struct v4l2_subdev_internal_ops unicam_subdev_internal_ops = {
1471 	.init_state		= unicam_subdev_init_state,
1472 };
1473 
1474 static const struct media_entity_operations unicam_subdev_media_ops = {
1475 	.link_validate		= v4l2_subdev_link_validate,
1476 	.has_pad_interdep	= v4l2_subdev_has_pad_interdep,
1477 };
1478 
unicam_subdev_init(struct unicam_device * unicam)1479 static int unicam_subdev_init(struct unicam_device *unicam)
1480 {
1481 	struct v4l2_subdev *sd = &unicam->subdev.sd;
1482 	int ret;
1483 
1484 	v4l2_subdev_init(sd, &unicam_subdev_ops);
1485 	sd->internal_ops = &unicam_subdev_internal_ops;
1486 	v4l2_set_subdevdata(sd, unicam);
1487 
1488 	sd->entity.function = MEDIA_ENT_F_VID_IF_BRIDGE;
1489 	sd->entity.ops = &unicam_subdev_media_ops;
1490 	sd->dev = unicam->dev;
1491 	sd->owner = THIS_MODULE;
1492 	sd->flags = V4L2_SUBDEV_FL_HAS_DEVNODE | V4L2_SUBDEV_FL_STREAMS;
1493 
1494 	strscpy(sd->name, "unicam", sizeof(sd->name));
1495 
1496 	unicam->subdev.pads[UNICAM_SD_PAD_SINK].flags = MEDIA_PAD_FL_SINK;
1497 	unicam->subdev.pads[UNICAM_SD_PAD_SOURCE_IMAGE].flags = MEDIA_PAD_FL_SOURCE;
1498 	unicam->subdev.pads[UNICAM_SD_PAD_SOURCE_METADATA].flags = MEDIA_PAD_FL_SOURCE;
1499 
1500 	ret = media_entity_pads_init(&sd->entity, ARRAY_SIZE(unicam->subdev.pads),
1501 				     unicam->subdev.pads);
1502 	if (ret) {
1503 		dev_err(unicam->dev, "Failed to initialize media entity: %d\n",
1504 			ret);
1505 		return ret;
1506 	}
1507 
1508 	ret = v4l2_subdev_init_finalize(sd);
1509 	if (ret) {
1510 		dev_err(unicam->dev, "Failed to initialize subdev: %d\n", ret);
1511 		goto err_entity;
1512 	}
1513 
1514 	ret = v4l2_device_register_subdev(&unicam->v4l2_dev, sd);
1515 	if (ret) {
1516 		dev_err(unicam->dev, "Failed to register subdev: %d\n", ret);
1517 		goto err_subdev;
1518 	}
1519 
1520 	return 0;
1521 
1522 err_subdev:
1523 	v4l2_subdev_cleanup(sd);
1524 err_entity:
1525 	media_entity_cleanup(&sd->entity);
1526 	return ret;
1527 }
1528 
unicam_subdev_cleanup(struct unicam_device * unicam)1529 static void unicam_subdev_cleanup(struct unicam_device *unicam)
1530 {
1531 	v4l2_subdev_cleanup(&unicam->subdev.sd);
1532 	media_entity_cleanup(&unicam->subdev.sd.entity);
1533 }
1534 
1535 /* -----------------------------------------------------------------------------
1536  * Videobuf2 queue operations
1537  */
1538 
unicam_queue_setup(struct vb2_queue * vq,unsigned int * nbuffers,unsigned int * nplanes,unsigned int sizes[],struct device * alloc_devs[])1539 static int unicam_queue_setup(struct vb2_queue *vq, unsigned int *nbuffers,
1540 			      unsigned int *nplanes, unsigned int sizes[],
1541 			      struct device *alloc_devs[])
1542 {
1543 	struct unicam_node *node = vb2_get_drv_priv(vq);
1544 	u32 size = is_image_node(node) ? node->fmt.fmt.pix.sizeimage
1545 		 : node->fmt.fmt.meta.buffersize;
1546 
1547 	if (*nplanes) {
1548 		if (sizes[0] < size) {
1549 			dev_dbg(node->dev->dev, "sizes[0] %i < size %u\n",
1550 				sizes[0], size);
1551 			return -EINVAL;
1552 		}
1553 		size = sizes[0];
1554 	}
1555 
1556 	*nplanes = 1;
1557 	sizes[0] = size;
1558 
1559 	return 0;
1560 }
1561 
unicam_buffer_prepare(struct vb2_buffer * vb)1562 static int unicam_buffer_prepare(struct vb2_buffer *vb)
1563 {
1564 	struct unicam_node *node = vb2_get_drv_priv(vb->vb2_queue);
1565 	struct unicam_buffer *buf = to_unicam_buffer(vb);
1566 	u32 size = is_image_node(node) ? node->fmt.fmt.pix.sizeimage
1567 		 : node->fmt.fmt.meta.buffersize;
1568 
1569 	if (vb2_plane_size(vb, 0) < size) {
1570 		dev_dbg(node->dev->dev,
1571 			"data will not fit into plane (%lu < %u)\n",
1572 			vb2_plane_size(vb, 0), size);
1573 		return -EINVAL;
1574 	}
1575 
1576 	buf->dma_addr = vb2_dma_contig_plane_dma_addr(&buf->vb.vb2_buf, 0);
1577 	buf->size = size;
1578 
1579 	vb2_set_plane_payload(&buf->vb.vb2_buf, 0, size);
1580 
1581 	return 0;
1582 }
1583 
unicam_return_buffers(struct unicam_node * node,enum vb2_buffer_state state)1584 static void unicam_return_buffers(struct unicam_node *node,
1585 				  enum vb2_buffer_state state)
1586 {
1587 	struct unicam_buffer *buf, *tmp;
1588 
1589 	list_for_each_entry_safe(buf, tmp, &node->dma_queue, list) {
1590 		list_del(&buf->list);
1591 		vb2_buffer_done(&buf->vb.vb2_buf, state);
1592 	}
1593 
1594 	if (node->cur_frm)
1595 		vb2_buffer_done(&node->cur_frm->vb.vb2_buf,
1596 				state);
1597 	if (node->next_frm && node->cur_frm != node->next_frm)
1598 		vb2_buffer_done(&node->next_frm->vb.vb2_buf,
1599 				state);
1600 
1601 	node->cur_frm = NULL;
1602 	node->next_frm = NULL;
1603 }
1604 
unicam_num_data_lanes(struct unicam_device * unicam)1605 static int unicam_num_data_lanes(struct unicam_device *unicam)
1606 {
1607 	struct v4l2_mbus_config mbus_config = { 0 };
1608 	unsigned int num_data_lanes;
1609 	int ret;
1610 
1611 	if (unicam->bus_type != V4L2_MBUS_CSI2_DPHY)
1612 		return unicam->max_data_lanes;
1613 
1614 	ret = v4l2_subdev_call(unicam->sensor.subdev, pad, get_mbus_config,
1615 			       unicam->sensor.pad->index, &mbus_config);
1616 	if (ret == -ENOIOCTLCMD)
1617 		return unicam->max_data_lanes;
1618 
1619 	if (ret < 0) {
1620 		dev_err(unicam->dev, "Failed to get mbus config: %d\n", ret);
1621 		return ret;
1622 	}
1623 
1624 	num_data_lanes = mbus_config.bus.mipi_csi2.num_data_lanes;
1625 
1626 	if (num_data_lanes != 1 && num_data_lanes != 2 && num_data_lanes != 4) {
1627 		dev_err(unicam->dev,
1628 			"Device %s has requested %u data lanes, invalid\n",
1629 			unicam->sensor.subdev->name, num_data_lanes);
1630 		return -EINVAL;
1631 	}
1632 
1633 	if (num_data_lanes > unicam->max_data_lanes) {
1634 		dev_err(unicam->dev,
1635 			"Device %s has requested %u data lanes, >%u configured in DT\n",
1636 			unicam->sensor.subdev->name, num_data_lanes,
1637 			unicam->max_data_lanes);
1638 		return -EINVAL;
1639 	}
1640 
1641 	return num_data_lanes;
1642 }
1643 
unicam_start_streaming(struct vb2_queue * vq,unsigned int count)1644 static int unicam_start_streaming(struct vb2_queue *vq, unsigned int count)
1645 {
1646 	struct unicam_node *node = vb2_get_drv_priv(vq);
1647 	struct unicam_device *unicam = node->dev;
1648 	struct unicam_buffer *buf;
1649 	struct media_pipeline_pad_iter iter;
1650 	struct media_pad *pad;
1651 	unsigned long flags;
1652 	int ret;
1653 
1654 	dev_dbg(unicam->dev, "Starting stream on %s device\n",
1655 		is_metadata_node(node) ? "metadata" : "image");
1656 
1657 	/*
1658 	 * Start the pipeline. This validates all links, and populates the
1659 	 * pipeline structure.
1660 	 */
1661 	ret = video_device_pipeline_start(&node->video_dev, &unicam->pipe.pipe);
1662 	if (ret < 0) {
1663 		dev_dbg(unicam->dev, "Failed to start media pipeline: %d\n", ret);
1664 		goto err_buffers;
1665 	}
1666 
1667 	/*
1668 	 * Determine which video nodes are included in the pipeline, and get the
1669 	 * number of data lanes.
1670 	 */
1671 	if (unicam->pipe.pipe.start_count == 1) {
1672 		unicam->pipe.nodes = 0;
1673 
1674 		media_pipeline_for_each_pad(&unicam->pipe.pipe, &iter, pad) {
1675 			if (pad->entity != &unicam->subdev.sd.entity)
1676 				continue;
1677 
1678 			if (pad->index == UNICAM_SD_PAD_SOURCE_IMAGE)
1679 				unicam->pipe.nodes |= BIT(UNICAM_IMAGE_NODE);
1680 			else if (pad->index == UNICAM_SD_PAD_SOURCE_METADATA)
1681 				unicam->pipe.nodes |= BIT(UNICAM_METADATA_NODE);
1682 		}
1683 
1684 		if (!(unicam->pipe.nodes & BIT(UNICAM_IMAGE_NODE))) {
1685 			dev_dbg(unicam->dev,
1686 				"Pipeline does not include image node\n");
1687 			ret = -EPIPE;
1688 			goto err_pipeline;
1689 		}
1690 
1691 		ret = unicam_num_data_lanes(unicam);
1692 		if (ret < 0)
1693 			goto err_pipeline;
1694 
1695 		unicam->pipe.num_data_lanes = ret;
1696 
1697 		dev_dbg(unicam->dev, "Running with %u data lanes, nodes %u\n",
1698 			unicam->pipe.num_data_lanes, unicam->pipe.nodes);
1699 	}
1700 
1701 	/* Arm the node with the first buffer from the DMA queue. */
1702 	spin_lock_irqsave(&node->dma_queue_lock, flags);
1703 	buf = list_first_entry(&node->dma_queue, struct unicam_buffer, list);
1704 	node->cur_frm = buf;
1705 	node->next_frm = buf;
1706 	list_del(&buf->list);
1707 	spin_unlock_irqrestore(&node->dma_queue_lock, flags);
1708 
1709 	/*
1710 	 * Wait for all the video devices in the pipeline to have been started
1711 	 * before starting the hardware. In the general case, this would
1712 	 * prevent capturing multiple streams independently. However, the
1713 	 * Unicam DMA engines are not generic, they have been designed to
1714 	 * capture image data and embedded data from the same camera sensor.
1715 	 * Not only does the main use case not benefit from independent
1716 	 * capture, it requires proper synchronization of the streams at start
1717 	 * time.
1718 	 */
1719 	if (unicam->pipe.pipe.start_count < hweight32(unicam->pipe.nodes))
1720 		return 0;
1721 
1722 	ret = pm_runtime_resume_and_get(unicam->dev);
1723 	if (ret < 0) {
1724 		dev_err(unicam->dev, "PM runtime resume failed: %d\n", ret);
1725 		goto err_pipeline;
1726 	}
1727 
1728 	/* Enable the streams on the source. */
1729 	ret = v4l2_subdev_enable_streams(&unicam->subdev.sd,
1730 					 UNICAM_SD_PAD_SOURCE_IMAGE,
1731 					 BIT(0));
1732 	if (ret < 0) {
1733 		dev_err(unicam->dev, "stream on failed in subdev\n");
1734 		goto err_pm_put;
1735 	}
1736 
1737 	if (unicam->pipe.nodes & BIT(UNICAM_METADATA_NODE)) {
1738 		ret = v4l2_subdev_enable_streams(&unicam->subdev.sd,
1739 						 UNICAM_SD_PAD_SOURCE_METADATA,
1740 						 BIT(0));
1741 		if (ret < 0) {
1742 			dev_err(unicam->dev, "stream on failed in subdev\n");
1743 			goto err_disable_streams;
1744 		}
1745 	}
1746 
1747 	return 0;
1748 
1749 err_disable_streams:
1750 	v4l2_subdev_disable_streams(&unicam->subdev.sd,
1751 				    UNICAM_SD_PAD_SOURCE_IMAGE, BIT(0));
1752 err_pm_put:
1753 	pm_runtime_put_sync(unicam->dev);
1754 err_pipeline:
1755 	video_device_pipeline_stop(&node->video_dev);
1756 err_buffers:
1757 	unicam_return_buffers(node, VB2_BUF_STATE_QUEUED);
1758 	return ret;
1759 }
1760 
unicam_stop_streaming(struct vb2_queue * vq)1761 static void unicam_stop_streaming(struct vb2_queue *vq)
1762 {
1763 	struct unicam_node *node = vb2_get_drv_priv(vq);
1764 	struct unicam_device *unicam = node->dev;
1765 
1766 	/* Stop the hardware when the first video device gets stopped. */
1767 	if (unicam->pipe.pipe.start_count == hweight32(unicam->pipe.nodes)) {
1768 		if (unicam->pipe.nodes & BIT(UNICAM_METADATA_NODE))
1769 			v4l2_subdev_disable_streams(&unicam->subdev.sd,
1770 						    UNICAM_SD_PAD_SOURCE_METADATA,
1771 						    BIT(0));
1772 
1773 		v4l2_subdev_disable_streams(&unicam->subdev.sd,
1774 					    UNICAM_SD_PAD_SOURCE_IMAGE,
1775 					    BIT(0));
1776 
1777 		pm_runtime_put(unicam->dev);
1778 	}
1779 
1780 	video_device_pipeline_stop(&node->video_dev);
1781 
1782 	/* Clear all queued buffers for the node */
1783 	unicam_return_buffers(node, VB2_BUF_STATE_ERROR);
1784 }
1785 
unicam_buffer_queue(struct vb2_buffer * vb)1786 static void unicam_buffer_queue(struct vb2_buffer *vb)
1787 {
1788 	struct unicam_node *node = vb2_get_drv_priv(vb->vb2_queue);
1789 	struct unicam_buffer *buf = to_unicam_buffer(vb);
1790 
1791 	spin_lock_irq(&node->dma_queue_lock);
1792 	list_add_tail(&buf->list, &node->dma_queue);
1793 	spin_unlock_irq(&node->dma_queue_lock);
1794 }
1795 
1796 static const struct vb2_ops unicam_video_qops = {
1797 	.queue_setup		= unicam_queue_setup,
1798 	.wait_prepare		= vb2_ops_wait_prepare,
1799 	.wait_finish		= vb2_ops_wait_finish,
1800 	.buf_prepare		= unicam_buffer_prepare,
1801 	.start_streaming	= unicam_start_streaming,
1802 	.stop_streaming		= unicam_stop_streaming,
1803 	.buf_queue		= unicam_buffer_queue,
1804 };
1805 
1806 /* -----------------------------------------------------------------------------
1807  *  V4L2 video device operations
1808  */
1809 
unicam_querycap(struct file * file,void * priv,struct v4l2_capability * cap)1810 static int unicam_querycap(struct file *file, void *priv,
1811 			   struct v4l2_capability *cap)
1812 {
1813 	strscpy(cap->driver, UNICAM_MODULE_NAME, sizeof(cap->driver));
1814 	strscpy(cap->card, UNICAM_MODULE_NAME, sizeof(cap->card));
1815 
1816 	cap->capabilities |= V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_META_CAPTURE;
1817 
1818 	return 0;
1819 }
1820 
unicam_enum_fmt_vid(struct file * file,void * priv,struct v4l2_fmtdesc * f)1821 static int unicam_enum_fmt_vid(struct file *file, void  *priv,
1822 			       struct v4l2_fmtdesc *f)
1823 {
1824 	unsigned int index;
1825 	unsigned int i;
1826 
1827 	for (i = 0, index = 0; i < ARRAY_SIZE(unicam_image_formats); i++) {
1828 		if (f->mbus_code && unicam_image_formats[i].code != f->mbus_code)
1829 			continue;
1830 
1831 		if (index == f->index) {
1832 			f->pixelformat = unicam_image_formats[i].fourcc;
1833 			return 0;
1834 		}
1835 
1836 		index++;
1837 
1838 		if (!unicam_image_formats[i].unpacked_fourcc)
1839 			continue;
1840 
1841 		if (index == f->index) {
1842 			f->pixelformat = unicam_image_formats[i].unpacked_fourcc;
1843 			return 0;
1844 		}
1845 
1846 		index++;
1847 	}
1848 
1849 	return -EINVAL;
1850 }
1851 
unicam_g_fmt_vid(struct file * file,void * priv,struct v4l2_format * f)1852 static int unicam_g_fmt_vid(struct file *file, void *priv,
1853 			    struct v4l2_format *f)
1854 {
1855 	struct unicam_node *node = video_drvdata(file);
1856 
1857 	*f = node->fmt;
1858 
1859 	return 0;
1860 }
1861 
__unicam_try_fmt_vid(struct unicam_node * node,struct v4l2_pix_format * pix)1862 static void __unicam_try_fmt_vid(struct unicam_node *node,
1863 				 struct v4l2_pix_format *pix)
1864 {
1865 	const struct unicam_format_info *fmtinfo;
1866 
1867 	/*
1868 	 * Default to the first format if the requested pixel format code isn't
1869 	 * supported.
1870 	 */
1871 	fmtinfo = unicam_find_format_by_fourcc(pix->pixelformat,
1872 					       UNICAM_SD_PAD_SOURCE_IMAGE);
1873 	if (!fmtinfo) {
1874 		fmtinfo = &unicam_image_formats[0];
1875 		pix->pixelformat = fmtinfo->fourcc;
1876 	}
1877 
1878 	unicam_calc_image_size_bpl(node->dev, fmtinfo, pix);
1879 
1880 	if (pix->field == V4L2_FIELD_ANY)
1881 		pix->field = V4L2_FIELD_NONE;
1882 }
1883 
unicam_try_fmt_vid(struct file * file,void * priv,struct v4l2_format * f)1884 static int unicam_try_fmt_vid(struct file *file, void *priv,
1885 			      struct v4l2_format *f)
1886 {
1887 	struct unicam_node *node = video_drvdata(file);
1888 
1889 	__unicam_try_fmt_vid(node, &f->fmt.pix);
1890 	return 0;
1891 }
1892 
unicam_s_fmt_vid(struct file * file,void * priv,struct v4l2_format * f)1893 static int unicam_s_fmt_vid(struct file *file, void *priv,
1894 			    struct v4l2_format *f)
1895 {
1896 	struct unicam_node *node = video_drvdata(file);
1897 
1898 	if (vb2_is_busy(&node->buffer_queue))
1899 		return -EBUSY;
1900 
1901 	__unicam_try_fmt_vid(node, &f->fmt.pix);
1902 	node->fmt = *f;
1903 
1904 	return 0;
1905 }
1906 
unicam_enum_fmt_meta(struct file * file,void * priv,struct v4l2_fmtdesc * f)1907 static int unicam_enum_fmt_meta(struct file *file, void *priv,
1908 				struct v4l2_fmtdesc *f)
1909 {
1910 	unsigned int i, index;
1911 
1912 	for (i = 0, index = 0; i < ARRAY_SIZE(unicam_meta_formats); i++) {
1913 		if (f->mbus_code && unicam_meta_formats[i].code != f->mbus_code)
1914 			continue;
1915 
1916 		if (index == f->index) {
1917 			f->pixelformat = unicam_meta_formats[i].fourcc;
1918 			f->type = V4L2_BUF_TYPE_META_CAPTURE;
1919 			f->flags = V4L2_FMT_FLAG_META_LINE_BASED;
1920 			return 0;
1921 		}
1922 
1923 		index++;
1924 	}
1925 
1926 	return -EINVAL;
1927 }
1928 
unicam_g_fmt_meta(struct file * file,void * priv,struct v4l2_format * f)1929 static int unicam_g_fmt_meta(struct file *file, void *priv,
1930 			     struct v4l2_format *f)
1931 {
1932 	struct unicam_node *node = video_drvdata(file);
1933 
1934 	f->fmt.meta = node->fmt.fmt.meta;
1935 
1936 	return 0;
1937 }
1938 
1939 static const struct unicam_format_info *
__unicam_try_fmt_meta(struct unicam_node * node,struct v4l2_meta_format * meta)1940 __unicam_try_fmt_meta(struct unicam_node *node, struct v4l2_meta_format *meta)
1941 {
1942 	const struct unicam_format_info *fmtinfo;
1943 
1944 	/*
1945 	 * Default to the first format if the requested pixel format code isn't
1946 	 * supported.
1947 	 */
1948 	fmtinfo = unicam_find_format_by_fourcc(meta->dataformat,
1949 					       UNICAM_SD_PAD_SOURCE_METADATA);
1950 	if (!fmtinfo) {
1951 		fmtinfo = &unicam_meta_formats[0];
1952 		meta->dataformat = fmtinfo->fourcc;
1953 	}
1954 
1955 	unicam_calc_meta_size_bpl(node->dev, fmtinfo, meta);
1956 
1957 	return fmtinfo;
1958 }
1959 
unicam_try_fmt_meta(struct file * file,void * priv,struct v4l2_format * f)1960 static int unicam_try_fmt_meta(struct file *file, void *priv,
1961 			       struct v4l2_format *f)
1962 {
1963 	struct unicam_node *node = video_drvdata(file);
1964 
1965 	__unicam_try_fmt_meta(node, &f->fmt.meta);
1966 	return 0;
1967 }
1968 
unicam_s_fmt_meta(struct file * file,void * priv,struct v4l2_format * f)1969 static int unicam_s_fmt_meta(struct file *file, void *priv,
1970 			     struct v4l2_format *f)
1971 {
1972 	struct unicam_node *node = video_drvdata(file);
1973 
1974 	if (vb2_is_busy(&node->buffer_queue))
1975 		return -EBUSY;
1976 
1977 	__unicam_try_fmt_meta(node, &f->fmt.meta);
1978 	node->fmt = *f;
1979 
1980 	return 0;
1981 }
1982 
unicam_enum_framesizes(struct file * file,void * fh,struct v4l2_frmsizeenum * fsize)1983 static int unicam_enum_framesizes(struct file *file, void *fh,
1984 				  struct v4l2_frmsizeenum *fsize)
1985 {
1986 	struct unicam_node *node = video_drvdata(file);
1987 	int ret = -EINVAL;
1988 
1989 	if (fsize->index > 0)
1990 		return ret;
1991 
1992 	if (is_image_node(node)) {
1993 		if (!unicam_find_format_by_fourcc(fsize->pixel_format,
1994 						  UNICAM_SD_PAD_SOURCE_IMAGE))
1995 			return ret;
1996 
1997 		fsize->type = V4L2_FRMSIZE_TYPE_STEPWISE;
1998 		fsize->stepwise.min_width = UNICAM_IMAGE_MIN_WIDTH;
1999 		fsize->stepwise.max_width = UNICAM_IMAGE_MAX_WIDTH;
2000 		fsize->stepwise.step_width = 1;
2001 		fsize->stepwise.min_height = UNICAM_IMAGE_MIN_HEIGHT;
2002 		fsize->stepwise.max_height = UNICAM_IMAGE_MAX_HEIGHT;
2003 		fsize->stepwise.step_height = 1;
2004 	} else {
2005 		if (!unicam_find_format_by_fourcc(fsize->pixel_format,
2006 						  UNICAM_SD_PAD_SOURCE_METADATA))
2007 			return ret;
2008 
2009 		fsize->type = V4L2_FRMSIZE_TYPE_STEPWISE;
2010 		fsize->stepwise.min_width = UNICAM_META_MIN_WIDTH;
2011 		fsize->stepwise.max_width = UNICAM_META_MAX_WIDTH;
2012 		fsize->stepwise.step_width = 1;
2013 		fsize->stepwise.min_height = UNICAM_META_MIN_HEIGHT;
2014 		fsize->stepwise.max_height = UNICAM_META_MAX_HEIGHT;
2015 		fsize->stepwise.step_height = 1;
2016 	}
2017 
2018 	return 0;
2019 }
2020 
unicam_log_status(struct file * file,void * fh)2021 static int unicam_log_status(struct file *file, void *fh)
2022 {
2023 	struct unicam_node *node = video_drvdata(file);
2024 	struct unicam_device *unicam = node->dev;
2025 	u32 reg;
2026 
2027 	/* status for sub devices */
2028 	v4l2_device_call_all(&unicam->v4l2_dev, 0, core, log_status);
2029 
2030 	dev_info(unicam->dev, "-----Receiver status-----\n");
2031 	dev_info(unicam->dev, "V4L2 width/height:   %ux%u\n",
2032 		 node->fmt.fmt.pix.width, node->fmt.fmt.pix.height);
2033 	dev_info(unicam->dev, "V4L2 format:         %08x\n",
2034 		 node->fmt.fmt.pix.pixelformat);
2035 	reg = unicam_reg_read(unicam, UNICAM_IPIPE);
2036 	dev_info(unicam->dev, "Unpacking/packing:   %u / %u\n",
2037 		 unicam_get_field(reg, UNICAM_PUM_MASK),
2038 		 unicam_get_field(reg, UNICAM_PPM_MASK));
2039 	dev_info(unicam->dev, "----Live data----\n");
2040 	dev_info(unicam->dev, "Programmed stride:   %4u\n",
2041 		 unicam_reg_read(unicam, UNICAM_IBLS));
2042 	dev_info(unicam->dev, "Detected resolution: %ux%u\n",
2043 		 unicam_reg_read(unicam, UNICAM_IHSTA),
2044 		 unicam_reg_read(unicam, UNICAM_IVSTA));
2045 	dev_info(unicam->dev, "Write pointer:       %08x\n",
2046 		 unicam_reg_read(unicam, UNICAM_IBWP));
2047 
2048 	return 0;
2049 }
2050 
unicam_subscribe_event(struct v4l2_fh * fh,const struct v4l2_event_subscription * sub)2051 static int unicam_subscribe_event(struct v4l2_fh *fh,
2052 				  const struct v4l2_event_subscription *sub)
2053 {
2054 	switch (sub->type) {
2055 	case V4L2_EVENT_FRAME_SYNC:
2056 		return v4l2_event_subscribe(fh, sub, 2, NULL);
2057 	default:
2058 		return -EINVAL;
2059 	}
2060 }
2061 
2062 static const struct v4l2_ioctl_ops unicam_ioctl_ops = {
2063 	.vidioc_querycap		= unicam_querycap,
2064 
2065 	.vidioc_enum_fmt_vid_cap	= unicam_enum_fmt_vid,
2066 	.vidioc_g_fmt_vid_cap		= unicam_g_fmt_vid,
2067 	.vidioc_try_fmt_vid_cap		= unicam_try_fmt_vid,
2068 	.vidioc_s_fmt_vid_cap		= unicam_s_fmt_vid,
2069 
2070 	.vidioc_enum_fmt_meta_cap	= unicam_enum_fmt_meta,
2071 	.vidioc_g_fmt_meta_cap		= unicam_g_fmt_meta,
2072 	.vidioc_try_fmt_meta_cap	= unicam_try_fmt_meta,
2073 	.vidioc_s_fmt_meta_cap		= unicam_s_fmt_meta,
2074 
2075 	.vidioc_enum_framesizes		= unicam_enum_framesizes,
2076 
2077 	.vidioc_reqbufs			= vb2_ioctl_reqbufs,
2078 	.vidioc_create_bufs		= vb2_ioctl_create_bufs,
2079 	.vidioc_prepare_buf		= vb2_ioctl_prepare_buf,
2080 	.vidioc_querybuf		= vb2_ioctl_querybuf,
2081 	.vidioc_qbuf			= vb2_ioctl_qbuf,
2082 	.vidioc_dqbuf			= vb2_ioctl_dqbuf,
2083 	.vidioc_expbuf			= vb2_ioctl_expbuf,
2084 	.vidioc_streamon		= vb2_ioctl_streamon,
2085 	.vidioc_streamoff		= vb2_ioctl_streamoff,
2086 
2087 	.vidioc_log_status		= unicam_log_status,
2088 	.vidioc_subscribe_event		= unicam_subscribe_event,
2089 	.vidioc_unsubscribe_event	= v4l2_event_unsubscribe,
2090 };
2091 
2092 /* unicam capture driver file operations */
2093 static const struct v4l2_file_operations unicam_fops = {
2094 	.owner		= THIS_MODULE,
2095 	.open           = v4l2_fh_open,
2096 	.release        = vb2_fop_release,
2097 	.poll		= vb2_fop_poll,
2098 	.unlocked_ioctl = video_ioctl2,
2099 	.mmap           = vb2_fop_mmap,
2100 };
2101 
unicam_video_link_validate(struct media_link * link)2102 static int unicam_video_link_validate(struct media_link *link)
2103 {
2104 	struct video_device *vdev =
2105 		media_entity_to_video_device(link->sink->entity);
2106 	struct v4l2_subdev *sd =
2107 		media_entity_to_v4l2_subdev(link->source->entity);
2108 	struct unicam_node *node = video_get_drvdata(vdev);
2109 	const u32 pad = is_image_node(node) ? UNICAM_SD_PAD_SOURCE_IMAGE
2110 		      : UNICAM_SD_PAD_SOURCE_METADATA;
2111 	const struct v4l2_mbus_framefmt *format;
2112 	struct v4l2_subdev_state *state;
2113 	int ret = 0;
2114 
2115 	state = v4l2_subdev_lock_and_get_active_state(sd);
2116 
2117 	format = v4l2_subdev_state_get_format(state, pad, 0);
2118 	if (!format) {
2119 		ret = -EINVAL;
2120 		goto out;
2121 	}
2122 
2123 	if (is_image_node(node)) {
2124 		const struct v4l2_pix_format *fmt = &node->fmt.fmt.pix;
2125 		const struct unicam_format_info *fmtinfo;
2126 
2127 		fmtinfo = unicam_find_format_by_fourcc(fmt->pixelformat,
2128 						       UNICAM_SD_PAD_SOURCE_IMAGE);
2129 		if (WARN_ON(!fmtinfo)) {
2130 			ret = -EPIPE;
2131 			goto out;
2132 		}
2133 
2134 		if (fmtinfo->code != format->code ||
2135 		    fmt->height != format->height ||
2136 		    fmt->width != format->width ||
2137 		    fmt->field != format->field) {
2138 			dev_dbg(node->dev->dev,
2139 				"image: (%u x %u) 0x%08x %s != (%u x %u) 0x%08x %s\n",
2140 				fmt->width, fmt->height, fmtinfo->code,
2141 				v4l2_field_names[fmt->field],
2142 				format->width, format->height, format->code,
2143 				v4l2_field_names[format->field]);
2144 			ret = -EPIPE;
2145 		}
2146 	} else {
2147 		const struct v4l2_meta_format *fmt = &node->fmt.fmt.meta;
2148 
2149 		const struct unicam_format_info *fmtinfo;
2150 
2151 		fmtinfo = unicam_find_format_by_fourcc(fmt->dataformat,
2152 						       UNICAM_SD_PAD_SOURCE_METADATA);
2153 		if (WARN_ON(!fmtinfo)) {
2154 			ret = -EPIPE;
2155 			goto out;
2156 		}
2157 
2158 		if (fmtinfo->code != format->code ||
2159 		    fmt->height != format->height ||
2160 		    fmt->width != format->width) {
2161 			dev_dbg(node->dev->dev,
2162 				"meta: (%u x %u) 0x%04x != (%u x %u) 0x%04x\n",
2163 				fmt->width, fmt->height, fmtinfo->code,
2164 				format->width, format->height, format->code);
2165 			ret = -EPIPE;
2166 		}
2167 	}
2168 
2169 out:
2170 	v4l2_subdev_unlock_state(state);
2171 	return ret;
2172 }
2173 
2174 static const struct media_entity_operations unicam_video_media_ops = {
2175 	.link_validate = unicam_video_link_validate,
2176 };
2177 
unicam_node_release(struct video_device * vdev)2178 static void unicam_node_release(struct video_device *vdev)
2179 {
2180 	struct unicam_node *node = video_get_drvdata(vdev);
2181 
2182 	unicam_put(node->dev);
2183 }
2184 
unicam_set_default_format(struct unicam_node * node)2185 static void unicam_set_default_format(struct unicam_node *node)
2186 {
2187 	if (is_image_node(node)) {
2188 		struct v4l2_pix_format *fmt = &node->fmt.fmt.pix;
2189 		const struct unicam_format_info *fmtinfo =
2190 			&unicam_image_formats[0];
2191 
2192 		node->fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2193 
2194 		v4l2_fill_pix_format(fmt, &unicam_default_image_format);
2195 		fmt->pixelformat = fmtinfo->fourcc;
2196 		unicam_calc_image_size_bpl(node->dev, fmtinfo, fmt);
2197 	} else {
2198 		struct v4l2_meta_format *fmt = &node->fmt.fmt.meta;
2199 		const struct unicam_format_info *fmtinfo =
2200 			&unicam_meta_formats[0];
2201 
2202 		node->fmt.type = V4L2_BUF_TYPE_META_CAPTURE;
2203 
2204 		fmt->dataformat = fmtinfo->fourcc;
2205 		fmt->width = unicam_default_meta_format.width;
2206 		fmt->height = unicam_default_meta_format.height;
2207 		unicam_calc_meta_size_bpl(node->dev, fmtinfo, fmt);
2208 	}
2209 }
2210 
unicam_register_node(struct unicam_device * unicam,enum unicam_node_type type)2211 static int unicam_register_node(struct unicam_device *unicam,
2212 				enum unicam_node_type type)
2213 {
2214 	const u32 pad_index = type == UNICAM_IMAGE_NODE
2215 			    ? UNICAM_SD_PAD_SOURCE_IMAGE
2216 			    : UNICAM_SD_PAD_SOURCE_METADATA;
2217 	struct unicam_node *node = &unicam->node[type];
2218 	struct video_device *vdev = &node->video_dev;
2219 	struct vb2_queue *q = &node->buffer_queue;
2220 	int ret;
2221 
2222 	node->dev = unicam_get(unicam);
2223 	node->id = type;
2224 
2225 	spin_lock_init(&node->dma_queue_lock);
2226 
2227 	INIT_LIST_HEAD(&node->dma_queue);
2228 
2229 	/* Initialize the videobuf2 queue. */
2230 	q->type = type == UNICAM_IMAGE_NODE ? V4L2_BUF_TYPE_VIDEO_CAPTURE
2231 					    : V4L2_BUF_TYPE_META_CAPTURE;
2232 	q->io_modes = VB2_MMAP | VB2_DMABUF;
2233 	q->drv_priv = node;
2234 	q->ops = &unicam_video_qops;
2235 	q->mem_ops = &vb2_dma_contig_memops;
2236 	q->buf_struct_size = sizeof(struct unicam_buffer);
2237 	q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
2238 	q->lock = &unicam->lock;
2239 	q->min_queued_buffers = 1;
2240 	q->dev = unicam->dev;
2241 
2242 	ret = vb2_queue_init(q);
2243 	if (ret) {
2244 		dev_err(unicam->dev, "vb2_queue_init() failed\n");
2245 		goto err_unicam_put;
2246 	}
2247 
2248 	/* Initialize the video device. */
2249 	vdev->release = unicam_node_release;
2250 	vdev->fops = &unicam_fops;
2251 	vdev->ioctl_ops = &unicam_ioctl_ops;
2252 	vdev->v4l2_dev = &unicam->v4l2_dev;
2253 	vdev->vfl_dir = VFL_DIR_RX;
2254 	vdev->queue = q;
2255 	vdev->lock = &unicam->lock;
2256 	vdev->device_caps = type == UNICAM_IMAGE_NODE
2257 			  ? V4L2_CAP_VIDEO_CAPTURE : V4L2_CAP_META_CAPTURE;
2258 	vdev->device_caps |= V4L2_CAP_STREAMING | V4L2_CAP_IO_MC;
2259 	vdev->entity.ops = &unicam_video_media_ops;
2260 
2261 	snprintf(vdev->name, sizeof(vdev->name), "%s-%s", UNICAM_MODULE_NAME,
2262 		 type == UNICAM_IMAGE_NODE ? "image" : "embedded");
2263 
2264 	video_set_drvdata(vdev, node);
2265 
2266 	if (type == UNICAM_IMAGE_NODE)
2267 		vdev->entity.flags |= MEDIA_ENT_FL_DEFAULT;
2268 
2269 	node->pad.flags = MEDIA_PAD_FL_SINK;
2270 
2271 	ret = media_entity_pads_init(&vdev->entity, 1, &node->pad);
2272 	if (ret)
2273 		goto err_unicam_put;
2274 
2275 	node->dummy_buf.size = UNICAM_DUMMY_BUF_SIZE;
2276 	node->dummy_buf_cpu_addr = dma_alloc_coherent(unicam->dev,
2277 						      node->dummy_buf.size,
2278 						      &node->dummy_buf.dma_addr,
2279 						      GFP_KERNEL);
2280 	if (!node->dummy_buf_cpu_addr) {
2281 		dev_err(unicam->dev, "Unable to allocate dummy buffer.\n");
2282 		ret = -ENOMEM;
2283 		goto err_entity_cleanup;
2284 	}
2285 
2286 	unicam_set_default_format(node);
2287 
2288 	ret = video_register_device(vdev, VFL_TYPE_VIDEO, -1);
2289 	if (ret) {
2290 		dev_err(unicam->dev, "Unable to register video device %s\n",
2291 			vdev->name);
2292 		goto err_dma_free;
2293 	}
2294 
2295 	node->registered = true;
2296 
2297 	ret = media_create_pad_link(&unicam->subdev.sd.entity,
2298 				    pad_index,
2299 				    &node->video_dev.entity,
2300 				    0,
2301 				    MEDIA_LNK_FL_ENABLED |
2302 				    MEDIA_LNK_FL_IMMUTABLE);
2303 	if (ret) {
2304 		/*
2305 		 * No need for cleanup, the caller will unregister the
2306 		 * video device, which will drop the reference on the
2307 		 * device and trigger the cleanup.
2308 		 */
2309 		dev_err(unicam->dev, "Unable to create pad link for %s\n",
2310 			unicam->sensor.subdev->name);
2311 		return ret;
2312 	}
2313 
2314 	return 0;
2315 
2316 err_dma_free:
2317 	dma_free_coherent(unicam->dev, node->dummy_buf.size,
2318 			  node->dummy_buf_cpu_addr,
2319 			  node->dummy_buf.dma_addr);
2320 err_entity_cleanup:
2321 	media_entity_cleanup(&vdev->entity);
2322 err_unicam_put:
2323 	unicam_put(unicam);
2324 	return ret;
2325 }
2326 
unicam_unregister_nodes(struct unicam_device * unicam)2327 static void unicam_unregister_nodes(struct unicam_device *unicam)
2328 {
2329 	unsigned int i;
2330 
2331 	for (i = 0; i < ARRAY_SIZE(unicam->node); i++) {
2332 		struct unicam_node *node = &unicam->node[i];
2333 
2334 		if (node->registered) {
2335 			vb2_video_unregister_device(&node->video_dev);
2336 			node->registered = false;
2337 		}
2338 
2339 		if (node->dummy_buf_cpu_addr)
2340 			dma_free_coherent(unicam->dev, node->dummy_buf.size,
2341 					  node->dummy_buf_cpu_addr,
2342 					  node->dummy_buf.dma_addr);
2343 	}
2344 }
2345 
2346 /* -----------------------------------------------------------------------------
2347  * Power management
2348  */
2349 
unicam_runtime_resume(struct device * dev)2350 static int unicam_runtime_resume(struct device *dev)
2351 {
2352 	struct unicam_device *unicam = dev_get_drvdata(dev);
2353 	int ret;
2354 
2355 	ret = clk_set_min_rate(unicam->vpu_clock, UNICAM_MIN_VPU_CLOCK_RATE);
2356 	if (ret) {
2357 		dev_err(unicam->dev, "failed to set up VPU clock\n");
2358 		return ret;
2359 	}
2360 
2361 	ret = clk_prepare_enable(unicam->vpu_clock);
2362 	if (ret) {
2363 		dev_err(unicam->dev, "Failed to enable VPU clock: %d\n", ret);
2364 		goto err_vpu_clock;
2365 	}
2366 
2367 	ret = clk_set_rate(unicam->clock, 100 * 1000 * 1000);
2368 	if (ret) {
2369 		dev_err(unicam->dev, "failed to set up CSI clock\n");
2370 		goto err_vpu_prepare;
2371 	}
2372 
2373 	ret = clk_prepare_enable(unicam->clock);
2374 	if (ret) {
2375 		dev_err(unicam->dev, "Failed to enable CSI clock: %d\n", ret);
2376 		goto err_vpu_prepare;
2377 	}
2378 
2379 	return 0;
2380 
2381 err_vpu_prepare:
2382 	clk_disable_unprepare(unicam->vpu_clock);
2383 err_vpu_clock:
2384 	if (clk_set_min_rate(unicam->vpu_clock, 0))
2385 		dev_err(unicam->dev, "failed to reset the VPU clock\n");
2386 
2387 	return ret;
2388 }
2389 
unicam_runtime_suspend(struct device * dev)2390 static int unicam_runtime_suspend(struct device *dev)
2391 {
2392 	struct unicam_device *unicam = dev_get_drvdata(dev);
2393 
2394 	clk_disable_unprepare(unicam->clock);
2395 
2396 	if (clk_set_min_rate(unicam->vpu_clock, 0))
2397 		dev_err(unicam->dev, "failed to reset the VPU clock\n");
2398 
2399 	clk_disable_unprepare(unicam->vpu_clock);
2400 
2401 	return 0;
2402 }
2403 
2404 static const struct dev_pm_ops unicam_pm_ops = {
2405 	RUNTIME_PM_OPS(unicam_runtime_suspend, unicam_runtime_resume, NULL)
2406 };
2407 
2408 /* -----------------------------------------------------------------------------
2409  * V4L2 async notifier
2410  */
2411 
unicam_async_bound(struct v4l2_async_notifier * notifier,struct v4l2_subdev * subdev,struct v4l2_async_connection * asc)2412 static int unicam_async_bound(struct v4l2_async_notifier *notifier,
2413 			      struct v4l2_subdev *subdev,
2414 			      struct v4l2_async_connection *asc)
2415 {
2416 	struct unicam_device *unicam = notifier_to_unicam_device(notifier);
2417 	struct media_pad *sink = &unicam->subdev.pads[UNICAM_SD_PAD_SINK];
2418 	struct media_pad *source;
2419 	int ret;
2420 
2421 	dev_dbg(unicam->dev, "Using sensor %s for capture\n",
2422 		subdev->name);
2423 
2424 	ret = v4l2_create_fwnode_links_to_pad(subdev, sink, MEDIA_LNK_FL_ENABLED |
2425 					      MEDIA_LNK_FL_IMMUTABLE);
2426 	if (ret)
2427 		return ret;
2428 
2429 	source = media_pad_remote_pad_unique(sink);
2430 	if (IS_ERR(source)) {
2431 		dev_err(unicam->dev, "No connected sensor pad\n");
2432 		return PTR_ERR(source);
2433 	}
2434 
2435 	unicam->sensor.subdev = subdev;
2436 	unicam->sensor.pad = source;
2437 
2438 	return 0;
2439 }
2440 
unicam_async_complete(struct v4l2_async_notifier * notifier)2441 static int unicam_async_complete(struct v4l2_async_notifier *notifier)
2442 {
2443 	struct unicam_device *unicam = notifier_to_unicam_device(notifier);
2444 	int ret;
2445 
2446 	ret = unicam_register_node(unicam, UNICAM_IMAGE_NODE);
2447 	if (ret) {
2448 		dev_err(unicam->dev, "Unable to register image video device.\n");
2449 		goto unregister;
2450 	}
2451 
2452 	ret = unicam_register_node(unicam, UNICAM_METADATA_NODE);
2453 	if (ret) {
2454 		dev_err(unicam->dev, "Unable to register metadata video device.\n");
2455 		goto unregister;
2456 	}
2457 
2458 	ret = v4l2_device_register_subdev_nodes(&unicam->v4l2_dev);
2459 	if (ret) {
2460 		dev_err(unicam->dev, "Unable to register subdev nodes.\n");
2461 		goto unregister;
2462 	}
2463 
2464 	return 0;
2465 
2466 unregister:
2467 	unicam_unregister_nodes(unicam);
2468 	unicam_put(unicam);
2469 
2470 	return ret;
2471 }
2472 
2473 static const struct v4l2_async_notifier_operations unicam_async_ops = {
2474 	.bound = unicam_async_bound,
2475 	.complete = unicam_async_complete,
2476 };
2477 
unicam_async_nf_init(struct unicam_device * unicam)2478 static int unicam_async_nf_init(struct unicam_device *unicam)
2479 {
2480 	struct v4l2_fwnode_endpoint ep = { };
2481 	struct fwnode_handle *ep_handle;
2482 	struct v4l2_async_connection *asc;
2483 	int ret;
2484 
2485 	ret = of_property_read_u32(unicam->dev->of_node, "brcm,num-data-lanes",
2486 				   &unicam->max_data_lanes);
2487 	if (ret < 0) {
2488 		dev_err(unicam->dev, "Missing %s DT property\n",
2489 			"brcm,num-data-lanes");
2490 		return -EINVAL;
2491 	}
2492 
2493 	/* Get and parse the local endpoint. */
2494 	ep_handle = fwnode_graph_get_endpoint_by_id(dev_fwnode(unicam->dev), 0, 0,
2495 						    FWNODE_GRAPH_ENDPOINT_NEXT);
2496 	if (!ep_handle) {
2497 		dev_err(unicam->dev, "No endpoint found\n");
2498 		return -ENODEV;
2499 	}
2500 
2501 	ret = v4l2_fwnode_endpoint_parse(ep_handle, &ep);
2502 	if (ret) {
2503 		dev_err(unicam->dev, "Failed to parse endpoint: %d\n", ret);
2504 		goto error;
2505 	}
2506 
2507 	unicam->bus_type = ep.bus_type;
2508 
2509 	switch (ep.bus_type) {
2510 	case V4L2_MBUS_CSI2_DPHY: {
2511 		unsigned int num_data_lanes = ep.bus.mipi_csi2.num_data_lanes;
2512 
2513 		if (num_data_lanes != 1 && num_data_lanes != 2 &&
2514 		    num_data_lanes != 4) {
2515 			dev_err(unicam->dev, "%u data lanes not supported\n",
2516 				num_data_lanes);
2517 			ret = -EINVAL;
2518 			goto error;
2519 		}
2520 
2521 		if (num_data_lanes > unicam->max_data_lanes) {
2522 			dev_err(unicam->dev,
2523 				"Endpoint uses %u data lanes when %u are supported\n",
2524 				num_data_lanes, unicam->max_data_lanes);
2525 			ret = -EINVAL;
2526 			goto error;
2527 		}
2528 
2529 		unicam->max_data_lanes = num_data_lanes;
2530 		unicam->bus_flags = ep.bus.mipi_csi2.flags;
2531 		break;
2532 	}
2533 
2534 	case V4L2_MBUS_CCP2:
2535 		unicam->max_data_lanes = 1;
2536 		unicam->bus_flags = ep.bus.mipi_csi1.strobe;
2537 		break;
2538 
2539 	default:
2540 		/* Unsupported bus type */
2541 		dev_err(unicam->dev, "Unsupported bus type %u\n", ep.bus_type);
2542 		ret = -EINVAL;
2543 		goto error;
2544 	}
2545 
2546 	/* Initialize and register the async notifier. */
2547 	v4l2_async_nf_init(&unicam->notifier, &unicam->v4l2_dev);
2548 
2549 	asc = v4l2_async_nf_add_fwnode_remote(&unicam->notifier, ep_handle,
2550 					      struct v4l2_async_connection);
2551 	fwnode_handle_put(ep_handle);
2552 	ep_handle = NULL;
2553 
2554 	if (IS_ERR(asc)) {
2555 		ret = PTR_ERR(asc);
2556 		dev_err(unicam->dev, "Failed to add entry to notifier: %d\n",
2557 			ret);
2558 		goto error;
2559 	}
2560 
2561 	unicam->notifier.ops = &unicam_async_ops;
2562 
2563 	ret = v4l2_async_nf_register(&unicam->notifier);
2564 	if (ret) {
2565 		dev_err(unicam->dev, "Error registering device notifier: %d\n",
2566 			ret);
2567 		goto error;
2568 	}
2569 
2570 	return 0;
2571 
2572 error:
2573 	fwnode_handle_put(ep_handle);
2574 	return ret;
2575 }
2576 
2577 /* -----------------------------------------------------------------------------
2578  * Probe & remove
2579  */
2580 
unicam_media_init(struct unicam_device * unicam)2581 static int unicam_media_init(struct unicam_device *unicam)
2582 {
2583 	int ret;
2584 
2585 	unicam->mdev.dev = unicam->dev;
2586 	strscpy(unicam->mdev.model, UNICAM_MODULE_NAME,
2587 		sizeof(unicam->mdev.model));
2588 	unicam->mdev.hw_revision = 0;
2589 
2590 	media_device_init(&unicam->mdev);
2591 
2592 	unicam->v4l2_dev.mdev = &unicam->mdev;
2593 
2594 	ret = v4l2_device_register(unicam->dev, &unicam->v4l2_dev);
2595 	if (ret < 0) {
2596 		dev_err(unicam->dev, "Unable to register v4l2 device\n");
2597 		goto err_media_cleanup;
2598 	}
2599 
2600 	ret = media_device_register(&unicam->mdev);
2601 	if (ret < 0) {
2602 		dev_err(unicam->dev,
2603 			"Unable to register media-controller device\n");
2604 		goto err_v4l2_unregister;
2605 	}
2606 
2607 	return 0;
2608 
2609 err_v4l2_unregister:
2610 	v4l2_device_unregister(&unicam->v4l2_dev);
2611 err_media_cleanup:
2612 	media_device_cleanup(&unicam->mdev);
2613 	return ret;
2614 }
2615 
unicam_probe(struct platform_device * pdev)2616 static int unicam_probe(struct platform_device *pdev)
2617 {
2618 	struct unicam_device *unicam;
2619 	int ret;
2620 
2621 	unicam = kzalloc(sizeof(*unicam), GFP_KERNEL);
2622 	if (!unicam)
2623 		return -ENOMEM;
2624 
2625 	kref_init(&unicam->kref);
2626 	mutex_init(&unicam->lock);
2627 
2628 	unicam->dev = &pdev->dev;
2629 	platform_set_drvdata(pdev, unicam);
2630 
2631 	unicam->base = devm_platform_ioremap_resource_byname(pdev, "unicam");
2632 	if (IS_ERR(unicam->base)) {
2633 		ret = PTR_ERR(unicam->base);
2634 		goto err_unicam_put;
2635 	}
2636 
2637 	unicam->clk_gate_base = devm_platform_ioremap_resource_byname(pdev, "cmi");
2638 	if (IS_ERR(unicam->clk_gate_base)) {
2639 		ret = PTR_ERR(unicam->clk_gate_base);
2640 		goto err_unicam_put;
2641 	}
2642 
2643 	unicam->clock = devm_clk_get(&pdev->dev, "lp");
2644 	if (IS_ERR(unicam->clock)) {
2645 		dev_err(unicam->dev, "Failed to get lp clock\n");
2646 		ret = PTR_ERR(unicam->clock);
2647 		goto err_unicam_put;
2648 	}
2649 
2650 	unicam->vpu_clock = devm_clk_get(&pdev->dev, "vpu");
2651 	if (IS_ERR(unicam->vpu_clock)) {
2652 		dev_err(unicam->dev, "Failed to get vpu clock\n");
2653 		ret = PTR_ERR(unicam->vpu_clock);
2654 		goto err_unicam_put;
2655 	}
2656 
2657 	ret = platform_get_irq(pdev, 0);
2658 	if (ret < 0)
2659 		goto err_unicam_put;
2660 
2661 	ret = devm_request_irq(&pdev->dev, ret, unicam_isr, 0,
2662 			       "unicam_capture0", unicam);
2663 	if (ret) {
2664 		dev_err(&pdev->dev, "Unable to request interrupt\n");
2665 		goto err_unicam_put;
2666 	}
2667 
2668 	/* Enable the block power domain. */
2669 	pm_runtime_enable(&pdev->dev);
2670 
2671 	ret = unicam_media_init(unicam);
2672 	if (ret)
2673 		goto err_pm_runtime;
2674 
2675 	ret = unicam_subdev_init(unicam);
2676 	if (ret)
2677 		goto err_media_unregister;
2678 
2679 	ret = unicam_async_nf_init(unicam);
2680 	if (ret)
2681 		goto err_subdev_unregister;
2682 
2683 	return 0;
2684 
2685 err_subdev_unregister:
2686 	unicam_subdev_cleanup(unicam);
2687 err_media_unregister:
2688 	media_device_unregister(&unicam->mdev);
2689 err_pm_runtime:
2690 	pm_runtime_disable(&pdev->dev);
2691 err_unicam_put:
2692 	unicam_put(unicam);
2693 
2694 	return ret;
2695 }
2696 
unicam_remove(struct platform_device * pdev)2697 static void unicam_remove(struct platform_device *pdev)
2698 {
2699 	struct unicam_device *unicam = platform_get_drvdata(pdev);
2700 
2701 	unicam_unregister_nodes(unicam);
2702 	v4l2_device_unregister(&unicam->v4l2_dev);
2703 	media_device_unregister(&unicam->mdev);
2704 	v4l2_async_nf_unregister(&unicam->notifier);
2705 
2706 	unicam_subdev_cleanup(unicam);
2707 
2708 	unicam_put(unicam);
2709 
2710 	pm_runtime_disable(&pdev->dev);
2711 }
2712 
2713 static const struct of_device_id unicam_of_match[] = {
2714 	{ .compatible = "brcm,bcm2835-unicam", },
2715 	{ /* sentinel */ },
2716 };
2717 MODULE_DEVICE_TABLE(of, unicam_of_match);
2718 
2719 static struct platform_driver unicam_driver = {
2720 	.probe		= unicam_probe,
2721 	.remove_new	= unicam_remove,
2722 	.driver = {
2723 		.name	= UNICAM_MODULE_NAME,
2724 		.pm	= pm_ptr(&unicam_pm_ops),
2725 		.of_match_table = unicam_of_match,
2726 	},
2727 };
2728 
2729 module_platform_driver(unicam_driver);
2730 
2731 MODULE_AUTHOR("Dave Stevenson <dave.stevenson@raspberrypi.com>");
2732 MODULE_DESCRIPTION("BCM2835 Unicam driver");
2733 MODULE_LICENSE("GPL");
2734