staging: bcm2835-camera: Add sanity checks for queue_setup/CREATE_BUFS
[platform/kernel/linux-rpi.git] / drivers / staging / vc04_services / bcm2835-camera / bcm2835-camera.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Broadcom BM2835 V4L2 driver
4  *
5  * Copyright © 2013 Raspberry Pi (Trading) Ltd.
6  *
7  * Authors: Vincent Sanders @ Collabora
8  *          Dave Stevenson @ Broadcom
9  *              (now dave.stevenson@raspberrypi.org)
10  *          Simon Mellor @ Broadcom
11  *          Luke Diamand @ Broadcom
12  */
13
14 #include <linux/errno.h>
15 #include <linux/kernel.h>
16 #include <linux/module.h>
17 #include <linux/slab.h>
18 #include <media/videobuf2-vmalloc.h>
19 #include <media/videobuf2-dma-contig.h>
20 #include <media/v4l2-device.h>
21 #include <media/v4l2-ioctl.h>
22 #include <media/v4l2-ctrls.h>
23 #include <media/v4l2-fh.h>
24 #include <media/v4l2-event.h>
25 #include <media/v4l2-common.h>
26 #include <linux/delay.h>
27 #include <linux/platform_device.h>
28
29 #include "mmal-common.h"
30 #include "mmal-encodings.h"
31 #include "mmal-vchiq.h"
32 #include "mmal-msg.h"
33 #include "mmal-parameters.h"
34 #include "bcm2835-camera.h"
35
36 #define BM2835_MMAL_VERSION "0.0.2"
37 #define BM2835_MMAL_MODULE_NAME "bcm2835-v4l2"
38 #define MIN_WIDTH 32
39 #define MIN_HEIGHT 32
40 #define MIN_BUFFER_SIZE (80 * 1024)
41
42 #define MAX_VIDEO_MODE_WIDTH 1280
43 #define MAX_VIDEO_MODE_HEIGHT 720
44
45 #define MAX_BCM2835_CAMERAS 2
46
47 int bcm2835_v4l2_debug;
48 module_param_named(debug, bcm2835_v4l2_debug, int, 0644);
49 MODULE_PARM_DESC(bcm2835_v4l2_debug, "Debug level 0-2");
50
51 #define UNSET (-1)
52 static int video_nr[] = {[0 ... (MAX_BCM2835_CAMERAS - 1)] = UNSET };
53 module_param_array(video_nr, int, NULL, 0644);
54 MODULE_PARM_DESC(video_nr, "videoX start numbers, -1 is autodetect");
55
56 static int max_video_width = MAX_VIDEO_MODE_WIDTH;
57 static int max_video_height = MAX_VIDEO_MODE_HEIGHT;
58 module_param(max_video_width, int, 0644);
59 MODULE_PARM_DESC(max_video_width, "Threshold for video mode");
60 module_param(max_video_height, int, 0644);
61 MODULE_PARM_DESC(max_video_height, "Threshold for video mode");
62
63 /* global device data array */
64 static struct bm2835_mmal_dev *gdev[MAX_BCM2835_CAMERAS];
65
66 #define FPS_MIN 1
67 #define FPS_MAX 90
68
69 /* timeperframe: min/max and default */
70 static const struct v4l2_fract
71         tpf_min     = {.numerator = 1,          .denominator = FPS_MAX},
72         tpf_max     = {.numerator = 1,          .denominator = FPS_MIN},
73         tpf_default = {.numerator = 1000,       .denominator = 30000};
74
75 /* Container for MMAL and VB2 buffers*/
76 struct vb2_mmal_buffer {
77         struct vb2_v4l2_buffer  vb;
78         struct mmal_buffer      mmal;
79 };
80
81 /* video formats */
82 static struct mmal_fmt formats[] = {
83         {
84                 .name = "4:2:0, planar, YUV",
85                 .fourcc = V4L2_PIX_FMT_YUV420,
86                 .flags = 0,
87                 .mmal = MMAL_ENCODING_I420,
88                 .depth = 12,
89                 .mmal_component = COMP_CAMERA,
90                 .ybbp = 1,
91                 .remove_padding = 1,
92         }, {
93                 .name = "4:2:2, packed, YUYV",
94                 .fourcc = V4L2_PIX_FMT_YUYV,
95                 .flags = 0,
96                 .mmal = MMAL_ENCODING_YUYV,
97                 .depth = 16,
98                 .mmal_component = COMP_CAMERA,
99                 .ybbp = 2,
100                 .remove_padding = 0,
101         }, {
102                 .name = "RGB24 (LE)",
103                 .fourcc = V4L2_PIX_FMT_RGB24,
104                 .flags = 0,
105                 .mmal = MMAL_ENCODING_RGB24,
106                 .depth = 24,
107                 .mmal_component = COMP_CAMERA,
108                 .ybbp = 3,
109                 .remove_padding = 0,
110         }, {
111                 .name = "JPEG",
112                 .fourcc = V4L2_PIX_FMT_JPEG,
113                 .flags = V4L2_FMT_FLAG_COMPRESSED,
114                 .mmal = MMAL_ENCODING_JPEG,
115                 .depth = 8,
116                 .mmal_component = COMP_IMAGE_ENCODE,
117                 .ybbp = 0,
118                 .remove_padding = 0,
119         }, {
120                 .name = "H264",
121                 .fourcc = V4L2_PIX_FMT_H264,
122                 .flags = V4L2_FMT_FLAG_COMPRESSED,
123                 .mmal = MMAL_ENCODING_H264,
124                 .depth = 8,
125                 .mmal_component = COMP_VIDEO_ENCODE,
126                 .ybbp = 0,
127                 .remove_padding = 0,
128         }, {
129                 .name = "MJPEG",
130                 .fourcc = V4L2_PIX_FMT_MJPEG,
131                 .flags = V4L2_FMT_FLAG_COMPRESSED,
132                 .mmal = MMAL_ENCODING_MJPEG,
133                 .depth = 8,
134                 .mmal_component = COMP_VIDEO_ENCODE,
135                 .ybbp = 0,
136                 .remove_padding = 0,
137         }, {
138                 .name = "4:2:2, packed, YVYU",
139                 .fourcc = V4L2_PIX_FMT_YVYU,
140                 .flags = 0,
141                 .mmal = MMAL_ENCODING_YVYU,
142                 .depth = 16,
143                 .mmal_component = COMP_CAMERA,
144                 .ybbp = 2,
145                 .remove_padding = 0,
146         }, {
147                 .name = "4:2:2, packed, VYUY",
148                 .fourcc = V4L2_PIX_FMT_VYUY,
149                 .flags = 0,
150                 .mmal = MMAL_ENCODING_VYUY,
151                 .depth = 16,
152                 .mmal_component = COMP_CAMERA,
153                 .ybbp = 2,
154                 .remove_padding = 0,
155         }, {
156                 .name = "4:2:2, packed, UYVY",
157                 .fourcc = V4L2_PIX_FMT_UYVY,
158                 .flags = 0,
159                 .mmal = MMAL_ENCODING_UYVY,
160                 .depth = 16,
161                 .mmal_component = COMP_CAMERA,
162                 .ybbp = 2,
163                 .remove_padding = 0,
164         }, {
165                 .name = "4:2:0, planar, NV12",
166                 .fourcc = V4L2_PIX_FMT_NV12,
167                 .flags = 0,
168                 .mmal = MMAL_ENCODING_NV12,
169                 .depth = 12,
170                 .mmal_component = COMP_CAMERA,
171                 .ybbp = 1,
172                 .remove_padding = 1,
173         }, {
174                 .name = "RGB24 (BE)",
175                 .fourcc = V4L2_PIX_FMT_BGR24,
176                 .flags = 0,
177                 .mmal = MMAL_ENCODING_BGR24,
178                 .depth = 24,
179                 .mmal_component = COMP_CAMERA,
180                 .ybbp = 3,
181                 .remove_padding = 0,
182         }, {
183                 .name = "4:2:0, planar, YVU",
184                 .fourcc = V4L2_PIX_FMT_YVU420,
185                 .flags = 0,
186                 .mmal = MMAL_ENCODING_YV12,
187                 .depth = 12,
188                 .mmal_component = COMP_CAMERA,
189                 .ybbp = 1,
190                 .remove_padding = 1,
191         }, {
192                 .name = "4:2:0, planar, NV21",
193                 .fourcc = V4L2_PIX_FMT_NV21,
194                 .flags = 0,
195                 .mmal = MMAL_ENCODING_NV21,
196                 .depth = 12,
197                 .mmal_component = COMP_CAMERA,
198                 .ybbp = 1,
199                 .remove_padding = 1,
200         }, {
201                 .name = "RGB32 (BE)",
202                 .fourcc = V4L2_PIX_FMT_BGR32,
203                 .flags = 0,
204                 .mmal = MMAL_ENCODING_BGRA,
205                 .depth = 32,
206                 .mmal_component = COMP_CAMERA,
207                 .ybbp = 4,
208                 .remove_padding = 0,
209         },
210 };
211
212 static struct mmal_fmt *get_format(struct v4l2_format *f)
213 {
214         struct mmal_fmt *fmt;
215         unsigned int k;
216
217         for (k = 0; k < ARRAY_SIZE(formats); k++) {
218                 fmt = &formats[k];
219                 if (fmt->fourcc == f->fmt.pix.pixelformat)
220                         return fmt;
221         }
222
223         return NULL;
224 }
225
226 /* ------------------------------------------------------------------
227  *      Videobuf queue operations
228  * ------------------------------------------------------------------
229  */
230
231 static int queue_setup(struct vb2_queue *vq,
232                        unsigned int *nbuffers, unsigned int *nplanes,
233                        unsigned int sizes[], struct device *alloc_ctxs[])
234 {
235         struct bm2835_mmal_dev *dev = vb2_get_drv_priv(vq);
236         unsigned long size;
237
238         /* refuse queue setup if port is not configured */
239         if (!dev->capture.port) {
240                 v4l2_err(&dev->v4l2_dev,
241                          "%s: capture port not configured\n", __func__);
242                 return -EINVAL;
243         }
244
245         /* Handle CREATE_BUFS situation - *nplanes != 0 */
246         if (*nplanes) {
247                 if (*nplanes != 1 ||
248                     sizes[0] < dev->capture.port->current_buffer.size) {
249                         v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev,
250                                  "%s: dev:%p Invalid buffer request from CREATE_BUFS, size %u < %u, nplanes %u != 1\n",
251                                  __func__, dev, sizes[0],
252                                  dev->capture.port->current_buffer.size,
253                                  *nplanes);
254                         return -EINVAL;
255                 } else {
256                         return 0;
257                 }
258         }
259
260         /* Handle REQBUFS situation */
261         size = dev->capture.port->current_buffer.size;
262         if (size == 0) {
263                 v4l2_err(&dev->v4l2_dev,
264                          "%s: capture port buffer size is zero\n", __func__);
265                 return -EINVAL;
266         }
267
268         if (*nbuffers < dev->capture.port->minimum_buffer.num)
269                 *nbuffers = dev->capture.port->minimum_buffer.num;
270
271         dev->capture.port->current_buffer.num = *nbuffers;
272
273         *nplanes = 1;
274
275         sizes[0] = size;
276
277         /*
278          * videobuf2-vmalloc allocator is context-less so no need to set
279          * alloc_ctxs array.
280          */
281
282         v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev, "%s: dev:%p\n",
283                  __func__, dev);
284
285         return 0;
286 }
287
288 static int buffer_init(struct vb2_buffer *vb)
289 {
290         struct bm2835_mmal_dev *dev = vb2_get_drv_priv(vb->vb2_queue);
291         struct vb2_v4l2_buffer *vb2 = to_vb2_v4l2_buffer(vb);
292         struct vb2_mmal_buffer *buf =
293                                 container_of(vb2, struct vb2_mmal_buffer, vb);
294
295         v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev, "%s: dev:%p, vb %p\n",
296                  __func__, dev, vb);
297         buf->mmal.buffer = vb2_plane_vaddr(&buf->vb.vb2_buf, 0);
298         buf->mmal.buffer_size = vb2_plane_size(&buf->vb.vb2_buf, 0);
299
300         return mmal_vchi_buffer_init(dev->instance, &buf->mmal);
301 }
302
303 static int buffer_prepare(struct vb2_buffer *vb)
304 {
305         struct bm2835_mmal_dev *dev = vb2_get_drv_priv(vb->vb2_queue);
306         unsigned long size;
307
308         v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev, "%s: dev:%p, vb %p\n",
309                  __func__, dev, vb);
310
311         if (!dev->capture.port || !dev->capture.fmt)
312                 return -ENODEV;
313
314         size = dev->capture.stride * dev->capture.height;
315         if (vb2_plane_size(vb, 0) < size) {
316                 v4l2_err(&dev->v4l2_dev,
317                          "%s data will not fit into plane (%lu < %lu)\n",
318                          __func__, vb2_plane_size(vb, 0), size);
319                 return -EINVAL;
320         }
321
322         return 0;
323 }
324
325 static void buffer_cleanup(struct vb2_buffer *vb)
326 {
327         struct bm2835_mmal_dev *dev = vb2_get_drv_priv(vb->vb2_queue);
328         struct vb2_v4l2_buffer *vb2 = to_vb2_v4l2_buffer(vb);
329         struct vb2_mmal_buffer *buf =
330                                 container_of(vb2, struct vb2_mmal_buffer, vb);
331
332         v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev, "%s: dev:%p, vb %p\n",
333                  __func__, dev, vb);
334
335         mmal_vchi_buffer_cleanup(&buf->mmal);
336 }
337
338 static inline bool is_capturing(struct bm2835_mmal_dev *dev)
339 {
340         return dev->capture.camera_port ==
341             &dev->component[COMP_CAMERA]->output[CAM_PORT_CAPTURE];
342 }
343
344 static void buffer_cb(struct vchiq_mmal_instance *instance,
345                       struct vchiq_mmal_port *port,
346                       int status,
347                       struct mmal_buffer *mmal_buf)
348 {
349         struct bm2835_mmal_dev *dev = port->cb_ctx;
350         struct vb2_mmal_buffer *buf =
351                         container_of(mmal_buf, struct vb2_mmal_buffer, mmal);
352
353         v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev,
354                  "%s: status:%d, buf:%p, length:%lu, flags %u, pts %lld\n",
355                  __func__, status, buf, mmal_buf->length, mmal_buf->mmal_flags,
356                  mmal_buf->pts);
357
358         if (status != 0) {
359                 /* error in transfer */
360                 if (buf) {
361                         /* there was a buffer with the error so return it */
362                         vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
363                 }
364                 return;
365         }
366
367         if (mmal_buf->length == 0) {
368                 /* stream ended */
369                 if (dev->capture.frame_count) {
370                         /* empty buffer whilst capturing - expected to be an
371                          * EOS, so grab another frame
372                          */
373                         if (is_capturing(dev)) {
374                                 v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev,
375                                          "Grab another frame");
376                                 vchiq_mmal_port_parameter_set(
377                                         instance,
378                                         dev->capture.camera_port,
379                                         MMAL_PARAMETER_CAPTURE,
380                                         &dev->capture.frame_count,
381                                         sizeof(dev->capture.frame_count));
382                         }
383                         if (vchiq_mmal_submit_buffer(instance, port,
384                                                      &buf->mmal))
385                                 v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev,
386                                          "Failed to return EOS buffer");
387                 } else {
388                         /* stopping streaming.
389                          * return buffer, and signal frame completion
390                          */
391                         vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
392                         complete(&dev->capture.frame_cmplt);
393                 }
394                 return;
395         }
396
397         if (!dev->capture.frame_count) {
398                 /* signal frame completion */
399                 vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
400                 complete(&dev->capture.frame_cmplt);
401                 return;
402         }
403
404         if (dev->capture.vc_start_timestamp == -1) {
405                 /*
406                  * VPU doesn't support MMAL_PARAMETER_SYSTEM_TIME, rely on
407                  * kernel time, and have no latency compensation.
408                  */
409                 buf->vb.vb2_buf.timestamp = ktime_get_ns();
410                 v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev,
411                          "Buffer time set as current time - %lld",
412                          buf->vb.vb2_buf.timestamp);
413         } else if (mmal_buf->pts != 0) {
414                 ktime_t timestamp;
415                 s64 runtime_us = mmal_buf->pts -
416                     dev->capture.vc_start_timestamp;
417                 timestamp = ktime_add_us(dev->capture.kernel_start_ts,
418                                          runtime_us);
419                 v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev,
420                          "Convert start time %llu and %llu with offset %llu to %llu\n",
421                          ktime_to_ns(dev->capture.kernel_start_ts),
422                          dev->capture.vc_start_timestamp, mmal_buf->pts,
423                          ktime_to_ns(timestamp));
424                 if (timestamp < dev->capture.last_timestamp) {
425                         v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev,
426                                  "Negative delta - using last time\n");
427                         timestamp = dev->capture.last_timestamp;
428                 }
429                 buf->vb.vb2_buf.timestamp = ktime_to_ns(timestamp);
430         } else {
431                 if (dev->capture.last_timestamp) {
432                         buf->vb.vb2_buf.timestamp = dev->capture.last_timestamp;
433                         v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev,
434                                  "Buffer time set as last timestamp - %lld",
435                                  buf->vb.vb2_buf.timestamp);
436                 } else {
437                         buf->vb.vb2_buf.timestamp =
438                                 ktime_to_ns(dev->capture.kernel_start_ts);
439                         v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev,
440                                  "Buffer time set as start timestamp - %lld",
441                                  buf->vb.vb2_buf.timestamp);
442                 }
443         }
444         dev->capture.last_timestamp = buf->vb.vb2_buf.timestamp;
445         buf->vb.sequence = dev->capture.sequence++;
446
447         vb2_set_plane_payload(&buf->vb.vb2_buf, 0, mmal_buf->length);
448         if (mmal_buf->mmal_flags & MMAL_BUFFER_HEADER_FLAG_KEYFRAME)
449                 buf->vb.flags |= V4L2_BUF_FLAG_KEYFRAME;
450
451         v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev,
452                  "Buffer has ts %llu", dev->capture.last_timestamp);
453         vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_DONE);
454
455         if (mmal_buf->mmal_flags & MMAL_BUFFER_HEADER_FLAG_EOS &&
456             is_capturing(dev)) {
457                 v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev,
458                          "Grab another frame as buffer has EOS");
459                 vchiq_mmal_port_parameter_set(instance,
460                                               dev->capture.camera_port,
461                                               MMAL_PARAMETER_CAPTURE,
462                                               &dev->capture.frame_count,
463                                               sizeof(dev->capture.frame_count));
464         }
465 }
466
467 static int enable_camera(struct bm2835_mmal_dev *dev)
468 {
469         int ret;
470
471         if (!dev->camera_use_count) {
472                 ret = vchiq_mmal_port_parameter_set(
473                         dev->instance,
474                         &dev->component[COMP_CAMERA]->control,
475                         MMAL_PARAMETER_CAMERA_NUM, &dev->camera_num,
476                         sizeof(dev->camera_num));
477                 if (ret < 0) {
478                         v4l2_err(&dev->v4l2_dev,
479                                  "Failed setting camera num, ret %d\n", ret);
480                         return -EINVAL;
481                 }
482
483                 ret = vchiq_mmal_component_enable(
484                                 dev->instance,
485                                 dev->component[COMP_CAMERA]);
486                 if (ret < 0) {
487                         v4l2_err(&dev->v4l2_dev,
488                                  "Failed enabling camera, ret %d\n", ret);
489                         return -EINVAL;
490                 }
491         }
492         dev->camera_use_count++;
493         v4l2_dbg(1, bcm2835_v4l2_debug,
494                  &dev->v4l2_dev, "enabled camera (refcount %d)\n",
495                         dev->camera_use_count);
496         return 0;
497 }
498
499 static int disable_camera(struct bm2835_mmal_dev *dev)
500 {
501         int ret;
502
503         if (!dev->camera_use_count) {
504                 v4l2_err(&dev->v4l2_dev,
505                          "Disabled the camera when already disabled\n");
506                 return -EINVAL;
507         }
508         dev->camera_use_count--;
509         if (!dev->camera_use_count) {
510                 unsigned int i = 0xFFFFFFFF;
511
512                 v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev,
513                          "Disabling camera\n");
514                 ret =
515                     vchiq_mmal_component_disable(
516                                 dev->instance,
517                                 dev->component[COMP_CAMERA]);
518                 if (ret < 0) {
519                         v4l2_err(&dev->v4l2_dev,
520                                  "Failed disabling camera, ret %d\n", ret);
521                         return -EINVAL;
522                 }
523                 vchiq_mmal_port_parameter_set(
524                         dev->instance,
525                         &dev->component[COMP_CAMERA]->control,
526                         MMAL_PARAMETER_CAMERA_NUM, &i,
527                         sizeof(i));
528         }
529         v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev,
530                  "Camera refcount now %d\n", dev->camera_use_count);
531         return 0;
532 }
533
534 static void buffer_queue(struct vb2_buffer *vb)
535 {
536         struct bm2835_mmal_dev *dev = vb2_get_drv_priv(vb->vb2_queue);
537         struct vb2_v4l2_buffer *vb2 = to_vb2_v4l2_buffer(vb);
538         struct vb2_mmal_buffer *buf =
539                                 container_of(vb2, struct vb2_mmal_buffer, vb);
540         int ret;
541
542         v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev,
543                  "%s: dev:%p buf:%p, idx %u\n",
544                  __func__, dev, buf, vb2->vb2_buf.index);
545
546         ret = vchiq_mmal_submit_buffer(dev->instance, dev->capture.port,
547                                        &buf->mmal);
548         if (ret < 0)
549                 v4l2_err(&dev->v4l2_dev, "%s: error submitting buffer\n",
550                          __func__);
551 }
552
553 static int start_streaming(struct vb2_queue *vq, unsigned int count)
554 {
555         struct bm2835_mmal_dev *dev = vb2_get_drv_priv(vq);
556         int ret;
557         u32 parameter_size;
558
559         v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev, "%s: dev:%p\n",
560                  __func__, dev);
561
562         /* ensure a format has actually been set */
563         if (!dev->capture.port)
564                 return -EINVAL;
565
566         if (enable_camera(dev) < 0) {
567                 v4l2_err(&dev->v4l2_dev, "Failed to enable camera\n");
568                 return -EINVAL;
569         }
570
571         /*init_completion(&dev->capture.frame_cmplt); */
572
573         /* enable frame capture */
574         dev->capture.frame_count = 1;
575
576         /* reset sequence number */
577         dev->capture.sequence = 0;
578
579         /* if the preview is not already running, wait for a few frames for AGC
580          * to settle down.
581          */
582         if (!dev->component[COMP_PREVIEW]->enabled)
583                 msleep(300);
584
585         /* enable the connection from camera to encoder (if applicable) */
586         if (dev->capture.camera_port != dev->capture.port &&
587             dev->capture.camera_port) {
588                 ret = vchiq_mmal_port_enable(dev->instance,
589                                              dev->capture.camera_port, NULL);
590                 if (ret) {
591                         v4l2_err(&dev->v4l2_dev,
592                                  "Failed to enable encode tunnel - error %d\n",
593                                  ret);
594                         return -1;
595                 }
596         }
597
598         /* Get VC timestamp at this point in time */
599         parameter_size = sizeof(dev->capture.vc_start_timestamp);
600         if (vchiq_mmal_port_parameter_get(dev->instance,
601                                           dev->capture.camera_port,
602                                           MMAL_PARAMETER_SYSTEM_TIME,
603                                           &dev->capture.vc_start_timestamp,
604                                           &parameter_size)) {
605                 v4l2_err(&dev->v4l2_dev,
606                          "Failed to get VC start time - update your VC f/w\n");
607
608                 /* Flag to indicate just to rely on kernel timestamps */
609                 dev->capture.vc_start_timestamp = -1;
610         } else {
611                 v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev,
612                          "Start time %lld size %d\n",
613                          dev->capture.vc_start_timestamp, parameter_size);
614         }
615
616         dev->capture.kernel_start_ts = ktime_get();
617         dev->capture.last_timestamp = 0;
618
619         /* enable the camera port */
620         dev->capture.port->cb_ctx = dev;
621         ret =
622             vchiq_mmal_port_enable(dev->instance, dev->capture.port, buffer_cb);
623         if (ret) {
624                 v4l2_err(&dev->v4l2_dev,
625                          "Failed to enable capture port - error %d. Disabling camera port again\n",
626                          ret);
627
628                 vchiq_mmal_port_disable(dev->instance,
629                                         dev->capture.camera_port);
630                 if (disable_camera(dev) < 0) {
631                         v4l2_err(&dev->v4l2_dev, "Failed to disable camera\n");
632                         return -EINVAL;
633                 }
634                 return -1;
635         }
636
637         /* capture the first frame */
638         vchiq_mmal_port_parameter_set(dev->instance,
639                                       dev->capture.camera_port,
640                                       MMAL_PARAMETER_CAPTURE,
641                                       &dev->capture.frame_count,
642                                       sizeof(dev->capture.frame_count));
643         return 0;
644 }
645
646 /* abort streaming and wait for last buffer */
647 static void stop_streaming(struct vb2_queue *vq)
648 {
649         int ret;
650         unsigned long timeout;
651         struct bm2835_mmal_dev *dev = vb2_get_drv_priv(vq);
652         struct vchiq_mmal_port *port = dev->capture.port;
653
654         v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev, "%s: dev:%p\n",
655                  __func__, dev);
656
657         init_completion(&dev->capture.frame_cmplt);
658         dev->capture.frame_count = 0;
659
660         /* ensure a format has actually been set */
661         if (!port) {
662                 v4l2_err(&dev->v4l2_dev,
663                          "no capture port - stream not started?\n");
664                 return;
665         }
666
667         v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev, "stopping capturing\n");
668
669         /* stop capturing frames */
670         vchiq_mmal_port_parameter_set(dev->instance,
671                                       dev->capture.camera_port,
672                                       MMAL_PARAMETER_CAPTURE,
673                                       &dev->capture.frame_count,
674                                       sizeof(dev->capture.frame_count));
675
676         v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev,
677                  "disabling connection\n");
678
679         /* disable the connection from camera to encoder */
680         ret = vchiq_mmal_port_disable(dev->instance, dev->capture.camera_port);
681         if (!ret && dev->capture.camera_port != port) {
682                 v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev,
683                          "disabling port\n");
684                 ret = vchiq_mmal_port_disable(dev->instance, port);
685         } else if (dev->capture.camera_port != port) {
686                 v4l2_err(&dev->v4l2_dev, "port_disable failed, error %d\n",
687                          ret);
688         }
689
690         /* wait for all buffers to be returned */
691         while (atomic_read(&port->buffers_with_vpu)) {
692                 v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev,
693                          "%s: Waiting for buffers to be returned - %d outstanding\n",
694                          __func__, atomic_read(&port->buffers_with_vpu));
695                 timeout = wait_for_completion_timeout(&dev->capture.frame_cmplt,
696                                                       HZ);
697                 if (timeout == 0) {
698                         v4l2_err(&dev->v4l2_dev, "%s: Timeout waiting for buffers to be returned - %d outstanding\n",
699                                  __func__,
700                                  atomic_read(&port->buffers_with_vpu));
701                         break;
702                 }
703         }
704
705         if (disable_camera(dev) < 0)
706                 v4l2_err(&dev->v4l2_dev, "Failed to disable camera\n");
707 }
708
709 static const struct vb2_ops bm2835_mmal_video_qops = {
710         .queue_setup = queue_setup,
711         .buf_init = buffer_init,
712         .buf_prepare = buffer_prepare,
713         .buf_cleanup = buffer_cleanup,
714         .buf_queue = buffer_queue,
715         .start_streaming = start_streaming,
716         .stop_streaming = stop_streaming,
717         .wait_prepare = vb2_ops_wait_prepare,
718         .wait_finish = vb2_ops_wait_finish,
719 };
720
721 /* ------------------------------------------------------------------
722  *      IOCTL operations
723  * ------------------------------------------------------------------
724  */
725
726 static int set_overlay_params(struct bm2835_mmal_dev *dev,
727                               struct vchiq_mmal_port *port)
728 {
729         struct mmal_parameter_displayregion prev_config = {
730                 .set =  MMAL_DISPLAY_SET_LAYER |
731                         MMAL_DISPLAY_SET_ALPHA |
732                         MMAL_DISPLAY_SET_DEST_RECT |
733                         MMAL_DISPLAY_SET_FULLSCREEN,
734                 .layer = PREVIEW_LAYER,
735                 .alpha = dev->overlay.global_alpha,
736                 .fullscreen = 0,
737                 .dest_rect = {
738                         .x = dev->overlay.w.left,
739                         .y = dev->overlay.w.top,
740                         .width = dev->overlay.w.width,
741                         .height = dev->overlay.w.height,
742                 },
743         };
744         return vchiq_mmal_port_parameter_set(dev->instance, port,
745                                              MMAL_PARAMETER_DISPLAYREGION,
746                                              &prev_config, sizeof(prev_config));
747 }
748
749 /* overlay ioctl */
750 static int vidioc_enum_fmt_vid_overlay(struct file *file, void *priv,
751                                        struct v4l2_fmtdesc *f)
752 {
753         struct mmal_fmt *fmt;
754
755         if (f->index >= ARRAY_SIZE(formats))
756                 return -EINVAL;
757
758         fmt = &formats[f->index];
759
760         strlcpy((char *)f->description, fmt->name, sizeof(f->description));
761         f->pixelformat = fmt->fourcc;
762         f->flags = fmt->flags;
763
764         return 0;
765 }
766
767 static int vidioc_g_fmt_vid_overlay(struct file *file, void *priv,
768                                     struct v4l2_format *f)
769 {
770         struct bm2835_mmal_dev *dev = video_drvdata(file);
771
772         f->fmt.win = dev->overlay;
773
774         return 0;
775 }
776
777 static int vidioc_try_fmt_vid_overlay(struct file *file, void *priv,
778                                       struct v4l2_format *f)
779 {
780         struct bm2835_mmal_dev *dev = video_drvdata(file);
781
782         f->fmt.win.field = V4L2_FIELD_NONE;
783         f->fmt.win.chromakey = 0;
784         f->fmt.win.clips = NULL;
785         f->fmt.win.clipcount = 0;
786         f->fmt.win.bitmap = NULL;
787
788         v4l_bound_align_image(&f->fmt.win.w.width, MIN_WIDTH, dev->max_width, 1,
789                               &f->fmt.win.w.height, MIN_HEIGHT, dev->max_height,
790                               1, 0);
791         v4l_bound_align_image(&f->fmt.win.w.left, MIN_WIDTH, dev->max_width, 1,
792                               &f->fmt.win.w.top, MIN_HEIGHT, dev->max_height,
793                               1, 0);
794
795         v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev,
796                  "Overlay: Now w/h %dx%d l/t %dx%d\n",
797                 f->fmt.win.w.width, f->fmt.win.w.height,
798                 f->fmt.win.w.left, f->fmt.win.w.top);
799
800         v4l2_dump_win_format(1,
801                              bcm2835_v4l2_debug,
802                              &dev->v4l2_dev,
803                              &f->fmt.win,
804                              __func__);
805         return 0;
806 }
807
808 static int vidioc_s_fmt_vid_overlay(struct file *file, void *priv,
809                                     struct v4l2_format *f)
810 {
811         struct bm2835_mmal_dev *dev = video_drvdata(file);
812
813         vidioc_try_fmt_vid_overlay(file, priv, f);
814
815         dev->overlay = f->fmt.win;
816         if (dev->component[COMP_PREVIEW]->enabled) {
817                 set_overlay_params(dev,
818                                    &dev->component[COMP_PREVIEW]->input[0]);
819         }
820
821         return 0;
822 }
823
824 static int vidioc_overlay(struct file *file, void *f, unsigned int on)
825 {
826         int ret;
827         struct bm2835_mmal_dev *dev = video_drvdata(file);
828         struct vchiq_mmal_port *src;
829         struct vchiq_mmal_port *dst;
830
831         if ((on && dev->component[COMP_PREVIEW]->enabled) ||
832             (!on && !dev->component[COMP_PREVIEW]->enabled))
833                 return 0;       /* already in requested state */
834
835         src =
836             &dev->component[COMP_CAMERA]->output[CAM_PORT_PREVIEW];
837
838         if (!on) {
839                 /* disconnect preview ports and disable component */
840                 ret = vchiq_mmal_port_disable(dev->instance, src);
841                 if (!ret)
842                         ret =
843                             vchiq_mmal_port_connect_tunnel(dev->instance, src,
844                                                            NULL);
845                 if (ret >= 0)
846                         ret = vchiq_mmal_component_disable(
847                                         dev->instance,
848                                         dev->component[COMP_PREVIEW]);
849
850                 disable_camera(dev);
851                 return ret;
852         }
853
854         /* set preview port format and connect it to output */
855         dst = &dev->component[COMP_PREVIEW]->input[0];
856
857         ret = vchiq_mmal_port_set_format(dev->instance, src);
858         if (ret < 0)
859                 return ret;
860
861         ret = set_overlay_params(dev, dst);
862         if (ret < 0)
863                 return ret;
864
865         if (enable_camera(dev) < 0) {
866                 ret = -EINVAL;
867                 return ret;
868         }
869
870         ret = vchiq_mmal_component_enable(
871                         dev->instance,
872                         dev->component[COMP_PREVIEW]);
873         if (ret < 0)
874                 return ret;
875
876         v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev, "connecting %p to %p\n",
877                  src, dst);
878         ret = vchiq_mmal_port_connect_tunnel(dev->instance, src, dst);
879         if (!ret)
880                 ret = vchiq_mmal_port_enable(dev->instance, src, NULL);
881
882         return ret;
883 }
884
885 static int vidioc_g_fbuf(struct file *file, void *fh,
886                          struct v4l2_framebuffer *a)
887 {
888         /* The video overlay must stay within the framebuffer and can't be
889          * positioned independently.
890          */
891         struct bm2835_mmal_dev *dev = video_drvdata(file);
892         struct vchiq_mmal_port *preview_port =
893                 &dev->component[COMP_CAMERA]->output[CAM_PORT_PREVIEW];
894
895         a->capability = V4L2_FBUF_CAP_EXTERNOVERLAY |
896                         V4L2_FBUF_CAP_GLOBAL_ALPHA;
897         a->flags = V4L2_FBUF_FLAG_OVERLAY;
898         a->fmt.width = preview_port->es.video.width;
899         a->fmt.height = preview_port->es.video.height;
900         a->fmt.pixelformat = V4L2_PIX_FMT_YUV420;
901         a->fmt.bytesperline = preview_port->es.video.width;
902         a->fmt.sizeimage = (preview_port->es.video.width *
903                                preview_port->es.video.height * 3) >> 1;
904         a->fmt.colorspace = V4L2_COLORSPACE_SMPTE170M;
905
906         return 0;
907 }
908
909 /* input ioctls */
910 static int vidioc_enum_input(struct file *file, void *priv,
911                              struct v4l2_input *inp)
912 {
913         /* only a single camera input */
914         if (inp->index != 0)
915                 return -EINVAL;
916
917         inp->type = V4L2_INPUT_TYPE_CAMERA;
918         sprintf((char *)inp->name, "Camera %u", inp->index);
919         return 0;
920 }
921
922 static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
923 {
924         *i = 0;
925         return 0;
926 }
927
928 static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
929 {
930         if (i != 0)
931                 return -EINVAL;
932
933         return 0;
934 }
935
936 /* capture ioctls */
937 static int vidioc_querycap(struct file *file, void *priv,
938                            struct v4l2_capability *cap)
939 {
940         struct bm2835_mmal_dev *dev = video_drvdata(file);
941         u32 major;
942         u32 minor;
943
944         vchiq_mmal_version(dev->instance, &major, &minor);
945
946         strcpy((char *)cap->driver, "bm2835 mmal");
947         snprintf((char *)cap->card, sizeof(cap->card), "mmal service %d.%d",
948                  major, minor);
949
950         snprintf((char *)cap->bus_info, sizeof(cap->bus_info),
951                  "platform:%s", dev->v4l2_dev.name);
952         cap->device_caps = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_VIDEO_OVERLAY |
953             V4L2_CAP_STREAMING | V4L2_CAP_READWRITE;
954         cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS;
955
956         return 0;
957 }
958
959 static int vidioc_enum_fmt_vid_cap(struct file *file, void *priv,
960                                    struct v4l2_fmtdesc *f)
961 {
962         struct mmal_fmt *fmt;
963
964         if (f->index >= ARRAY_SIZE(formats))
965                 return -EINVAL;
966
967         fmt = &formats[f->index];
968
969         strlcpy((char *)f->description, fmt->name, sizeof(f->description));
970         f->pixelformat = fmt->fourcc;
971         f->flags = fmt->flags;
972
973         return 0;
974 }
975
976 static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
977                                 struct v4l2_format *f)
978 {
979         struct bm2835_mmal_dev *dev = video_drvdata(file);
980
981         f->fmt.pix.width = dev->capture.width;
982         f->fmt.pix.height = dev->capture.height;
983         f->fmt.pix.field = V4L2_FIELD_NONE;
984         f->fmt.pix.pixelformat = dev->capture.fmt->fourcc;
985         f->fmt.pix.bytesperline = dev->capture.stride;
986         f->fmt.pix.sizeimage = dev->capture.buffersize;
987
988         if (dev->capture.fmt->fourcc == V4L2_PIX_FMT_RGB24)
989                 f->fmt.pix.colorspace = V4L2_COLORSPACE_SRGB;
990         else if (dev->capture.fmt->fourcc == V4L2_PIX_FMT_JPEG)
991                 f->fmt.pix.colorspace = V4L2_COLORSPACE_JPEG;
992         else
993                 f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
994         f->fmt.pix.priv = 0;
995
996         v4l2_dump_pix_format(1, bcm2835_v4l2_debug, &dev->v4l2_dev, &f->fmt.pix,
997                              __func__);
998         return 0;
999 }
1000
1001 static int vidioc_try_fmt_vid_cap(struct file *file, void *priv,
1002                                   struct v4l2_format *f)
1003 {
1004         struct bm2835_mmal_dev *dev = video_drvdata(file);
1005         struct mmal_fmt *mfmt;
1006
1007         mfmt = get_format(f);
1008         if (!mfmt) {
1009                 v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev,
1010                          "Fourcc format (0x%08x) unknown.\n",
1011                          f->fmt.pix.pixelformat);
1012                 f->fmt.pix.pixelformat = formats[0].fourcc;
1013                 mfmt = get_format(f);
1014         }
1015
1016         f->fmt.pix.field = V4L2_FIELD_NONE;
1017
1018         v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev,
1019                  "Clipping/aligning %dx%d format %08X\n",
1020                  f->fmt.pix.width, f->fmt.pix.height, f->fmt.pix.pixelformat);
1021
1022         v4l_bound_align_image(&f->fmt.pix.width, MIN_WIDTH, dev->max_width, 1,
1023                               &f->fmt.pix.height, MIN_HEIGHT, dev->max_height,
1024                               1, 0);
1025         f->fmt.pix.bytesperline = f->fmt.pix.width * mfmt->ybbp;
1026         if (!mfmt->remove_padding) {
1027                 if (mfmt->depth == 24) {
1028                         /*
1029                          * 24bpp is a pain as we can't use simple masking.
1030                          * Min stride is width aligned to 16, times 24bpp.
1031                          */
1032                         f->fmt.pix.bytesperline =
1033                                 ((f->fmt.pix.width + 15) & ~15) * 3;
1034                 } else {
1035                         /*
1036                          * GPU isn't removing padding, so stride is aligned to
1037                          * 32
1038                          */
1039                         int align_mask = ((32 * mfmt->depth) >> 3) - 1;
1040
1041                         f->fmt.pix.bytesperline =
1042                                 (f->fmt.pix.bytesperline + align_mask) &
1043                                                         ~align_mask;
1044                 }
1045                 v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev,
1046                          "Not removing padding, so bytes/line = %d\n",
1047                          f->fmt.pix.bytesperline);
1048         }
1049
1050         /* Image buffer has to be padded to allow for alignment, even though
1051          * we sometimes then remove that padding before delivering the buffer.
1052          */
1053         f->fmt.pix.sizeimage = ((f->fmt.pix.height + 15) & ~15) *
1054                         (((f->fmt.pix.width + 31) & ~31) * mfmt->depth) >> 3;
1055
1056         if ((mfmt->flags & V4L2_FMT_FLAG_COMPRESSED) &&
1057             f->fmt.pix.sizeimage < MIN_BUFFER_SIZE)
1058                 f->fmt.pix.sizeimage = MIN_BUFFER_SIZE;
1059
1060         if (f->fmt.pix.pixelformat == V4L2_PIX_FMT_RGB24)
1061                 f->fmt.pix.colorspace = V4L2_COLORSPACE_SRGB;
1062         else if (f->fmt.pix.pixelformat == V4L2_PIX_FMT_JPEG)
1063                 f->fmt.pix.colorspace = V4L2_COLORSPACE_JPEG;
1064         else
1065                 f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
1066         f->fmt.pix.priv = 0;
1067
1068         v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev,
1069                  "Now %dx%d format %08X\n",
1070                 f->fmt.pix.width, f->fmt.pix.height, f->fmt.pix.pixelformat);
1071
1072         v4l2_dump_pix_format(1, bcm2835_v4l2_debug, &dev->v4l2_dev, &f->fmt.pix,
1073                              __func__);
1074         return 0;
1075 }
1076
1077 static int mmal_setup_components(struct bm2835_mmal_dev *dev,
1078                                  struct v4l2_format *f)
1079 {
1080         int ret;
1081         struct vchiq_mmal_port *port = NULL, *camera_port = NULL;
1082         struct vchiq_mmal_component *encode_component = NULL;
1083         struct mmal_fmt *mfmt = get_format(f);
1084         u32 remove_padding;
1085
1086         if (!mfmt)
1087                 return -EINVAL;
1088
1089         if (dev->capture.encode_component) {
1090                 v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev,
1091                          "vid_cap - disconnect previous tunnel\n");
1092
1093                 /* Disconnect any previous connection */
1094                 vchiq_mmal_port_connect_tunnel(dev->instance,
1095                                                dev->capture.camera_port, NULL);
1096                 dev->capture.camera_port = NULL;
1097                 ret = vchiq_mmal_component_disable(dev->instance,
1098                                                    dev->capture.encode_component);
1099                 if (ret)
1100                         v4l2_err(&dev->v4l2_dev,
1101                                  "Failed to disable encode component %d\n",
1102                                  ret);
1103
1104                 dev->capture.encode_component = NULL;
1105         }
1106         /* format dependent port setup */
1107         switch (mfmt->mmal_component) {
1108         case COMP_CAMERA:
1109                 /* Make a further decision on port based on resolution */
1110                 if (f->fmt.pix.width <= max_video_width &&
1111                     f->fmt.pix.height <= max_video_height)
1112                         camera_port =
1113                             &dev->component[COMP_CAMERA]->output[CAM_PORT_VIDEO];
1114                 else
1115                         camera_port =
1116                             &dev->component[COMP_CAMERA]->output[CAM_PORT_CAPTURE];
1117                 port = camera_port;
1118                 break;
1119         case COMP_IMAGE_ENCODE:
1120                 encode_component = dev->component[COMP_IMAGE_ENCODE];
1121                 port = &dev->component[COMP_IMAGE_ENCODE]->output[0];
1122                 camera_port =
1123                     &dev->component[COMP_CAMERA]->output[CAM_PORT_CAPTURE];
1124                 break;
1125         case COMP_VIDEO_ENCODE:
1126                 encode_component = dev->component[COMP_VIDEO_ENCODE];
1127                 port = &dev->component[COMP_VIDEO_ENCODE]->output[0];
1128                 camera_port =
1129                     &dev->component[COMP_CAMERA]->output[CAM_PORT_VIDEO];
1130                 break;
1131         default:
1132                 break;
1133         }
1134
1135         if (!port)
1136                 return -EINVAL;
1137
1138         if (encode_component)
1139                 camera_port->format.encoding = MMAL_ENCODING_OPAQUE;
1140         else
1141                 camera_port->format.encoding = mfmt->mmal;
1142
1143         if (dev->rgb_bgr_swapped) {
1144                 if (camera_port->format.encoding == MMAL_ENCODING_RGB24)
1145                         camera_port->format.encoding = MMAL_ENCODING_BGR24;
1146                 else if (camera_port->format.encoding == MMAL_ENCODING_BGR24)
1147                         camera_port->format.encoding = MMAL_ENCODING_RGB24;
1148         }
1149
1150         remove_padding = mfmt->remove_padding;
1151         vchiq_mmal_port_parameter_set(dev->instance,
1152                                       camera_port,
1153                                       MMAL_PARAMETER_NO_IMAGE_PADDING,
1154                                       &remove_padding, sizeof(remove_padding));
1155
1156         camera_port->format.encoding_variant = 0;
1157         camera_port->es.video.width = f->fmt.pix.width;
1158         camera_port->es.video.height = f->fmt.pix.height;
1159         camera_port->es.video.crop.x = 0;
1160         camera_port->es.video.crop.y = 0;
1161         camera_port->es.video.crop.width = f->fmt.pix.width;
1162         camera_port->es.video.crop.height = f->fmt.pix.height;
1163         camera_port->es.video.frame_rate.num = 0;
1164         camera_port->es.video.frame_rate.den = 1;
1165         camera_port->es.video.color_space = MMAL_COLOR_SPACE_JPEG_JFIF;
1166
1167         ret = vchiq_mmal_port_set_format(dev->instance, camera_port);
1168
1169         if (!ret &&
1170             camera_port ==
1171             &dev->component[COMP_CAMERA]->output[CAM_PORT_VIDEO]) {
1172                 bool overlay_enabled =
1173                     !!dev->component[COMP_PREVIEW]->enabled;
1174                 struct vchiq_mmal_port *preview_port =
1175                     &dev->component[COMP_CAMERA]->output[CAM_PORT_PREVIEW];
1176                 /* Preview and encode ports need to match on resolution */
1177                 if (overlay_enabled) {
1178                         /* Need to disable the overlay before we can update
1179                          * the resolution
1180                          */
1181                         ret =
1182                             vchiq_mmal_port_disable(dev->instance,
1183                                                     preview_port);
1184                         if (!ret)
1185                                 ret =
1186                                     vchiq_mmal_port_connect_tunnel(
1187                                                 dev->instance,
1188                                                 preview_port,
1189                                                 NULL);
1190                 }
1191                 preview_port->es.video.width = f->fmt.pix.width;
1192                 preview_port->es.video.height = f->fmt.pix.height;
1193                 preview_port->es.video.crop.x = 0;
1194                 preview_port->es.video.crop.y = 0;
1195                 preview_port->es.video.crop.width = f->fmt.pix.width;
1196                 preview_port->es.video.crop.height = f->fmt.pix.height;
1197                 preview_port->es.video.frame_rate.num =
1198                                           dev->capture.timeperframe.denominator;
1199                 preview_port->es.video.frame_rate.den =
1200                                           dev->capture.timeperframe.numerator;
1201                 ret = vchiq_mmal_port_set_format(dev->instance, preview_port);
1202                 if (overlay_enabled) {
1203                         ret = vchiq_mmal_port_connect_tunnel(
1204                                 dev->instance,
1205                                 preview_port,
1206                                 &dev->component[COMP_PREVIEW]->input[0]);
1207                         if (!ret)
1208                                 ret = vchiq_mmal_port_enable(dev->instance,
1209                                                              preview_port,
1210                                                              NULL);
1211                 }
1212         }
1213
1214         if (ret) {
1215                 v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev,
1216                          "%s failed to set format %dx%d %08X\n", __func__,
1217                          f->fmt.pix.width, f->fmt.pix.height,
1218                          f->fmt.pix.pixelformat);
1219                 /* ensure capture is not going to be tried */
1220                 dev->capture.port = NULL;
1221         } else {
1222                 if (encode_component) {
1223                         v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev,
1224                                  "vid_cap - set up encode comp\n");
1225
1226                         /* configure buffering */
1227                         camera_port->current_buffer.size =
1228                             camera_port->recommended_buffer.size;
1229                         camera_port->current_buffer.num =
1230                             camera_port->recommended_buffer.num;
1231
1232                         ret =
1233                             vchiq_mmal_port_connect_tunnel(
1234                                         dev->instance,
1235                                         camera_port,
1236                                         &encode_component->input[0]);
1237                         if (ret) {
1238                                 v4l2_dbg(1, bcm2835_v4l2_debug,
1239                                          &dev->v4l2_dev,
1240                                          "%s failed to create connection\n",
1241                                          __func__);
1242                                 /* ensure capture is not going to be tried */
1243                                 dev->capture.port = NULL;
1244                         } else {
1245                                 port->es.video.width = f->fmt.pix.width;
1246                                 port->es.video.height = f->fmt.pix.height;
1247                                 port->es.video.crop.x = 0;
1248                                 port->es.video.crop.y = 0;
1249                                 port->es.video.crop.width = f->fmt.pix.width;
1250                                 port->es.video.crop.height = f->fmt.pix.height;
1251                                 port->es.video.frame_rate.num =
1252                                           dev->capture.timeperframe.denominator;
1253                                 port->es.video.frame_rate.den =
1254                                           dev->capture.timeperframe.numerator;
1255
1256                                 port->format.encoding = mfmt->mmal;
1257                                 port->format.encoding_variant = 0;
1258                                 /* Set any encoding specific parameters */
1259                                 switch (mfmt->mmal_component) {
1260                                 case COMP_VIDEO_ENCODE:
1261                                         port->format.bitrate =
1262                                             dev->capture.encode_bitrate;
1263                                         break;
1264                                 case COMP_IMAGE_ENCODE:
1265                                         /* Could set EXIF parameters here */
1266                                         break;
1267                                 default:
1268                                         break;
1269                                 }
1270                                 ret = vchiq_mmal_port_set_format(dev->instance,
1271                                                                  port);
1272                                 if (ret)
1273                                         v4l2_dbg(1, bcm2835_v4l2_debug,
1274                                                  &dev->v4l2_dev,
1275                                                  "%s failed to set format %dx%d fmt %08X\n",
1276                                                  __func__,
1277                                                  f->fmt.pix.width,
1278                                                  f->fmt.pix.height,
1279                                                  f->fmt.pix.pixelformat
1280                                                  );
1281                         }
1282
1283                         if (!ret) {
1284                                 ret = vchiq_mmal_component_enable(
1285                                                 dev->instance,
1286                                                 encode_component);
1287                                 if (ret) {
1288                                         v4l2_dbg(1, bcm2835_v4l2_debug,
1289                                                  &dev->v4l2_dev,
1290                                                  "%s Failed to enable encode components\n",
1291                                                  __func__);
1292                                 }
1293                         }
1294                         if (!ret) {
1295                                 /* configure buffering */
1296                                 port->current_buffer.num = 1;
1297                                 port->current_buffer.size =
1298                                     f->fmt.pix.sizeimage;
1299                                 if (port->format.encoding ==
1300                                     MMAL_ENCODING_JPEG) {
1301                                         v4l2_dbg(1, bcm2835_v4l2_debug,
1302                                                  &dev->v4l2_dev,
1303                                                  "JPG - buf size now %d was %d\n",
1304                                                  f->fmt.pix.sizeimage,
1305                                                  port->current_buffer.size);
1306                                         port->current_buffer.size =
1307                                             (f->fmt.pix.sizeimage <
1308                                              (100 << 10)) ?
1309                                             (100 << 10) : f->fmt.pix.sizeimage;
1310                                 }
1311                                 v4l2_dbg(1, bcm2835_v4l2_debug,
1312                                          &dev->v4l2_dev,
1313                                          "vid_cap - cur_buf.size set to %d\n",
1314                                          f->fmt.pix.sizeimage);
1315                                 port->current_buffer.alignment = 0;
1316                         }
1317                 } else {
1318                         /* configure buffering */
1319                         camera_port->current_buffer.num = 1;
1320                         camera_port->current_buffer.size = f->fmt.pix.sizeimage;
1321                         camera_port->current_buffer.alignment = 0;
1322                 }
1323
1324                 if (!ret) {
1325                         dev->capture.fmt = mfmt;
1326                         dev->capture.stride = f->fmt.pix.bytesperline;
1327                         dev->capture.width = camera_port->es.video.crop.width;
1328                         dev->capture.height = camera_port->es.video.crop.height;
1329                         dev->capture.buffersize = port->current_buffer.size;
1330
1331                         /* select port for capture */
1332                         dev->capture.port = port;
1333                         dev->capture.camera_port = camera_port;
1334                         dev->capture.encode_component = encode_component;
1335                         v4l2_dbg(1, bcm2835_v4l2_debug,
1336                                  &dev->v4l2_dev,
1337                                 "Set dev->capture.fmt %08X, %dx%d, stride %d, size %d",
1338                                 port->format.encoding,
1339                                 dev->capture.width, dev->capture.height,
1340                                 dev->capture.stride, dev->capture.buffersize);
1341                 }
1342         }
1343
1344         /* todo: Need to convert the vchiq/mmal error into a v4l2 error. */
1345         return ret;
1346 }
1347
1348 static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
1349                                 struct v4l2_format *f)
1350 {
1351         int ret;
1352         struct bm2835_mmal_dev *dev = video_drvdata(file);
1353         struct mmal_fmt *mfmt;
1354
1355         /* try the format to set valid parameters */
1356         ret = vidioc_try_fmt_vid_cap(file, priv, f);
1357         if (ret) {
1358                 v4l2_err(&dev->v4l2_dev,
1359                          "vid_cap - vidioc_try_fmt_vid_cap failed\n");
1360                 return ret;
1361         }
1362
1363         /* if a capture is running refuse to set format */
1364         if (vb2_is_busy(&dev->capture.vb_vidq)) {
1365                 v4l2_info(&dev->v4l2_dev, "%s device busy\n", __func__);
1366                 return -EBUSY;
1367         }
1368
1369         /* If the format is unsupported v4l2 says we should switch to
1370          * a supported one and not return an error.
1371          */
1372         mfmt = get_format(f);
1373         if (!mfmt) {
1374                 v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev,
1375                          "Fourcc format (0x%08x) unknown.\n",
1376                          f->fmt.pix.pixelformat);
1377                 f->fmt.pix.pixelformat = formats[0].fourcc;
1378                 mfmt = get_format(f);
1379         }
1380
1381         ret = mmal_setup_components(dev, f);
1382         if (ret != 0) {
1383                 v4l2_err(&dev->v4l2_dev,
1384                          "%s: failed to setup mmal components: %d\n",
1385                          __func__, ret);
1386                 ret = -EINVAL;
1387         }
1388
1389         return ret;
1390 }
1391
1392 static int vidioc_enum_framesizes(struct file *file, void *fh,
1393                                   struct v4l2_frmsizeenum *fsize)
1394 {
1395         struct bm2835_mmal_dev *dev = video_drvdata(file);
1396         static const struct v4l2_frmsize_stepwise sizes = {
1397                 MIN_WIDTH, 0, 2,
1398                 MIN_HEIGHT, 0, 2
1399         };
1400         int i;
1401
1402         if (fsize->index)
1403                 return -EINVAL;
1404         for (i = 0; i < ARRAY_SIZE(formats); i++)
1405                 if (formats[i].fourcc == fsize->pixel_format)
1406                         break;
1407         if (i == ARRAY_SIZE(formats))
1408                 return -EINVAL;
1409         fsize->type = V4L2_FRMSIZE_TYPE_STEPWISE;
1410         fsize->stepwise = sizes;
1411         fsize->stepwise.max_width = dev->max_width;
1412         fsize->stepwise.max_height = dev->max_height;
1413         return 0;
1414 }
1415
1416 /* timeperframe is arbitrary and continuous */
1417 static int vidioc_enum_frameintervals(struct file *file, void *priv,
1418                                       struct v4l2_frmivalenum *fival)
1419 {
1420         struct bm2835_mmal_dev *dev = video_drvdata(file);
1421         int i;
1422
1423         if (fival->index)
1424                 return -EINVAL;
1425
1426         for (i = 0; i < ARRAY_SIZE(formats); i++)
1427                 if (formats[i].fourcc == fival->pixel_format)
1428                         break;
1429         if (i == ARRAY_SIZE(formats))
1430                 return -EINVAL;
1431
1432         /* regarding width & height - we support any within range */
1433         if (fival->width < MIN_WIDTH || fival->width > dev->max_width ||
1434             fival->height < MIN_HEIGHT || fival->height > dev->max_height)
1435                 return -EINVAL;
1436
1437         fival->type = V4L2_FRMIVAL_TYPE_CONTINUOUS;
1438
1439         /* fill in stepwise (step=1.0 is required by V4L2 spec) */
1440         fival->stepwise.min  = tpf_min;
1441         fival->stepwise.max  = tpf_max;
1442         fival->stepwise.step = (struct v4l2_fract) {1, 1};
1443
1444         return 0;
1445 }
1446
1447 static int vidioc_g_parm(struct file *file, void *priv,
1448                          struct v4l2_streamparm *parm)
1449 {
1450         struct bm2835_mmal_dev *dev = video_drvdata(file);
1451
1452         if (parm->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1453                 return -EINVAL;
1454
1455         parm->parm.capture.capability   = V4L2_CAP_TIMEPERFRAME;
1456         parm->parm.capture.timeperframe = dev->capture.timeperframe;
1457         parm->parm.capture.readbuffers  = 1;
1458         return 0;
1459 }
1460
1461 #define FRACT_CMP(a, OP, b)     \
1462         ((u64)(a).numerator * (b).denominator  OP  \
1463          (u64)(b).numerator * (a).denominator)
1464
1465 static int vidioc_s_parm(struct file *file, void *priv,
1466                          struct v4l2_streamparm *parm)
1467 {
1468         struct bm2835_mmal_dev *dev = video_drvdata(file);
1469         struct v4l2_fract tpf;
1470
1471         if (parm->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1472                 return -EINVAL;
1473
1474         tpf = parm->parm.capture.timeperframe;
1475
1476         /* tpf: {*, 0} resets timing; clip to [min, max]*/
1477         tpf = tpf.denominator ? tpf : tpf_default;
1478         tpf = FRACT_CMP(tpf, <, tpf_min) ? tpf_min : tpf;
1479         tpf = FRACT_CMP(tpf, >, tpf_max) ? tpf_max : tpf;
1480
1481         dev->capture.timeperframe = tpf;
1482         parm->parm.capture.timeperframe = tpf;
1483         parm->parm.capture.readbuffers  = 1;
1484         parm->parm.capture.capability   = V4L2_CAP_TIMEPERFRAME;
1485
1486         set_framerate_params(dev);
1487
1488         return 0;
1489 }
1490
1491 static const struct v4l2_ioctl_ops camera0_ioctl_ops = {
1492         /* overlay */
1493         .vidioc_enum_fmt_vid_overlay = vidioc_enum_fmt_vid_overlay,
1494         .vidioc_g_fmt_vid_overlay = vidioc_g_fmt_vid_overlay,
1495         .vidioc_try_fmt_vid_overlay = vidioc_try_fmt_vid_overlay,
1496         .vidioc_s_fmt_vid_overlay = vidioc_s_fmt_vid_overlay,
1497         .vidioc_overlay = vidioc_overlay,
1498         .vidioc_g_fbuf = vidioc_g_fbuf,
1499
1500         /* inputs */
1501         .vidioc_enum_input = vidioc_enum_input,
1502         .vidioc_g_input = vidioc_g_input,
1503         .vidioc_s_input = vidioc_s_input,
1504
1505         /* capture */
1506         .vidioc_querycap = vidioc_querycap,
1507         .vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap,
1508         .vidioc_g_fmt_vid_cap = vidioc_g_fmt_vid_cap,
1509         .vidioc_try_fmt_vid_cap = vidioc_try_fmt_vid_cap,
1510         .vidioc_s_fmt_vid_cap = vidioc_s_fmt_vid_cap,
1511
1512         /* buffer management */
1513         .vidioc_reqbufs = vb2_ioctl_reqbufs,
1514         .vidioc_create_bufs = vb2_ioctl_create_bufs,
1515         .vidioc_prepare_buf = vb2_ioctl_prepare_buf,
1516         .vidioc_querybuf = vb2_ioctl_querybuf,
1517         .vidioc_qbuf = vb2_ioctl_qbuf,
1518         .vidioc_dqbuf = vb2_ioctl_dqbuf,
1519         .vidioc_enum_framesizes = vidioc_enum_framesizes,
1520         .vidioc_enum_frameintervals = vidioc_enum_frameintervals,
1521         .vidioc_g_parm        = vidioc_g_parm,
1522         .vidioc_s_parm        = vidioc_s_parm,
1523         .vidioc_streamon = vb2_ioctl_streamon,
1524         .vidioc_streamoff = vb2_ioctl_streamoff,
1525
1526         .vidioc_log_status = v4l2_ctrl_log_status,
1527         .vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
1528         .vidioc_unsubscribe_event = v4l2_event_unsubscribe,
1529 };
1530
1531 /* ------------------------------------------------------------------
1532  *      Driver init/finalise
1533  * ------------------------------------------------------------------
1534  */
1535
1536 static const struct v4l2_file_operations camera0_fops = {
1537         .owner = THIS_MODULE,
1538         .open = v4l2_fh_open,
1539         .release = vb2_fop_release,
1540         .read = vb2_fop_read,
1541         .poll = vb2_fop_poll,
1542         .unlocked_ioctl = video_ioctl2, /* V4L2 ioctl handler */
1543         .mmap = vb2_fop_mmap,
1544 };
1545
1546 static const struct video_device vdev_template = {
1547         .name = "camera0",
1548         .fops = &camera0_fops,
1549         .ioctl_ops = &camera0_ioctl_ops,
1550         .release = video_device_release_empty,
1551 };
1552
1553 /* Returns the number of cameras, and also the max resolution supported
1554  * by those cameras.
1555  */
1556 static int get_num_cameras(struct vchiq_mmal_instance *instance,
1557                            unsigned int resolutions[][2], int num_resolutions)
1558 {
1559         int ret;
1560         struct vchiq_mmal_component  *cam_info_component;
1561         struct mmal_parameter_camera_info_t cam_info = {0};
1562         u32 param_size = sizeof(cam_info);
1563         int i;
1564
1565         /* create a camera_info component */
1566         ret = vchiq_mmal_component_init(instance, "camera_info",
1567                                         &cam_info_component);
1568         if (ret < 0)
1569                 /* Unusual failure - let's guess one camera. */
1570                 return 1;
1571
1572         if (vchiq_mmal_port_parameter_get(instance,
1573                                           &cam_info_component->control,
1574                                           MMAL_PARAMETER_CAMERA_INFO,
1575                                           &cam_info,
1576                                           &param_size)) {
1577                 pr_info("Failed to get camera info\n");
1578         }
1579         for (i = 0;
1580              i < min_t(unsigned int, cam_info.num_cameras, num_resolutions);
1581              i++) {
1582                 resolutions[i][0] = cam_info.cameras[i].max_width;
1583                 resolutions[i][1] = cam_info.cameras[i].max_height;
1584         }
1585
1586         vchiq_mmal_component_finalise(instance,
1587                                       cam_info_component);
1588
1589         return cam_info.num_cameras;
1590 }
1591
1592 static int set_camera_parameters(struct vchiq_mmal_instance *instance,
1593                                  struct vchiq_mmal_component *camera,
1594                                  struct bm2835_mmal_dev *dev)
1595 {
1596         int ret;
1597         struct mmal_parameter_camera_config cam_config = {
1598                 .max_stills_w = dev->max_width,
1599                 .max_stills_h = dev->max_height,
1600                 .stills_yuv422 = 1,
1601                 .one_shot_stills = 1,
1602                 .max_preview_video_w = (max_video_width > 1920) ?
1603                                                 max_video_width : 1920,
1604                 .max_preview_video_h = (max_video_height > 1088) ?
1605                                                 max_video_height : 1088,
1606                 .num_preview_video_frames = 3,
1607                 .stills_capture_circular_buffer_height = 0,
1608                 .fast_preview_resume = 0,
1609                 .use_stc_timestamp = MMAL_PARAM_TIMESTAMP_MODE_RAW_STC
1610         };
1611
1612         ret = vchiq_mmal_port_parameter_set(instance, &camera->control,
1613                                             MMAL_PARAMETER_CAMERA_CONFIG,
1614                                             &cam_config, sizeof(cam_config));
1615         return ret;
1616 }
1617
1618 #define MAX_SUPPORTED_ENCODINGS 20
1619
1620 /* MMAL instance and component init */
1621 static int mmal_init(struct bm2835_mmal_dev *dev)
1622 {
1623         int ret;
1624         struct mmal_es_format_local *format;
1625         u32 supported_encodings[MAX_SUPPORTED_ENCODINGS];
1626         u32 param_size;
1627         struct vchiq_mmal_component  *camera;
1628
1629         ret = vchiq_mmal_init(&dev->instance);
1630         if (ret < 0) {
1631                 v4l2_err(&dev->v4l2_dev, "%s: vchiq mmal init failed %d\n",
1632                          __func__, ret);
1633                 return ret;
1634         }
1635
1636         /* get the camera component ready */
1637         ret = vchiq_mmal_component_init(dev->instance, "ril.camera",
1638                                         &dev->component[COMP_CAMERA]);
1639         if (ret < 0)
1640                 goto unreg_mmal;
1641
1642         camera = dev->component[COMP_CAMERA];
1643         if (camera->outputs < CAM_PORT_COUNT) {
1644                 v4l2_err(&dev->v4l2_dev, "%s: too few camera outputs %d needed %d\n",
1645                          __func__, camera->outputs, CAM_PORT_COUNT);
1646                 ret = -EINVAL;
1647                 goto unreg_camera;
1648         }
1649
1650         ret = set_camera_parameters(dev->instance,
1651                                     camera,
1652                                     dev);
1653         if (ret < 0) {
1654                 v4l2_err(&dev->v4l2_dev, "%s: unable to set camera parameters: %d\n",
1655                          __func__, ret);
1656                 goto unreg_camera;
1657         }
1658
1659         /* There was an error in the firmware that meant the camera component
1660          * produced BGR instead of RGB.
1661          * This is now fixed, but in order to support the old firmwares, we
1662          * have to check.
1663          */
1664         dev->rgb_bgr_swapped = true;
1665         param_size = sizeof(supported_encodings);
1666         ret = vchiq_mmal_port_parameter_get(dev->instance,
1667                                             &camera->output[CAM_PORT_CAPTURE],
1668                                             MMAL_PARAMETER_SUPPORTED_ENCODINGS,
1669                                             &supported_encodings,
1670                                             &param_size);
1671         if (ret == 0) {
1672                 int i;
1673
1674                 for (i = 0; i < param_size / sizeof(u32); i++) {
1675                         if (supported_encodings[i] == MMAL_ENCODING_BGR24) {
1676                                 /* Found BGR24 first - old firmware. */
1677                                 break;
1678                         }
1679                         if (supported_encodings[i] == MMAL_ENCODING_RGB24) {
1680                                 /* Found RGB24 first
1681                                  * new firmware, so use RGB24.
1682                                  */
1683                                 dev->rgb_bgr_swapped = false;
1684                         break;
1685                         }
1686                 }
1687         }
1688         format = &camera->output[CAM_PORT_PREVIEW].format;
1689
1690         format->encoding = MMAL_ENCODING_OPAQUE;
1691         format->encoding_variant = MMAL_ENCODING_I420;
1692
1693         format->es->video.width = 1024;
1694         format->es->video.height = 768;
1695         format->es->video.crop.x = 0;
1696         format->es->video.crop.y = 0;
1697         format->es->video.crop.width = 1024;
1698         format->es->video.crop.height = 768;
1699         format->es->video.frame_rate.num = 0; /* Rely on fps_range */
1700         format->es->video.frame_rate.den = 1;
1701
1702         format = &camera->output[CAM_PORT_VIDEO].format;
1703
1704         format->encoding = MMAL_ENCODING_OPAQUE;
1705         format->encoding_variant = MMAL_ENCODING_I420;
1706
1707         format->es->video.width = 1024;
1708         format->es->video.height = 768;
1709         format->es->video.crop.x = 0;
1710         format->es->video.crop.y = 0;
1711         format->es->video.crop.width = 1024;
1712         format->es->video.crop.height = 768;
1713         format->es->video.frame_rate.num = 0; /* Rely on fps_range */
1714         format->es->video.frame_rate.den = 1;
1715
1716         format = &camera->output[CAM_PORT_CAPTURE].format;
1717
1718         format->encoding = MMAL_ENCODING_OPAQUE;
1719
1720         format->es->video.width = 2592;
1721         format->es->video.height = 1944;
1722         format->es->video.crop.x = 0;
1723         format->es->video.crop.y = 0;
1724         format->es->video.crop.width = 2592;
1725         format->es->video.crop.height = 1944;
1726         format->es->video.frame_rate.num = 0; /* Rely on fps_range */
1727         format->es->video.frame_rate.den = 1;
1728
1729         dev->capture.width = format->es->video.width;
1730         dev->capture.height = format->es->video.height;
1731         dev->capture.fmt = &formats[0];
1732         dev->capture.encode_component = NULL;
1733         dev->capture.timeperframe = tpf_default;
1734         dev->capture.enc_profile = V4L2_MPEG_VIDEO_H264_PROFILE_HIGH;
1735         dev->capture.enc_level = V4L2_MPEG_VIDEO_H264_LEVEL_4_0;
1736
1737         /* get the preview component ready */
1738         ret = vchiq_mmal_component_init(
1739                         dev->instance, "ril.video_render",
1740                         &dev->component[COMP_PREVIEW]);
1741         if (ret < 0)
1742                 goto unreg_camera;
1743
1744         if (dev->component[COMP_PREVIEW]->inputs < 1) {
1745                 ret = -EINVAL;
1746                 v4l2_err(&dev->v4l2_dev, "%s: too few input ports %d needed %d\n",
1747                          __func__, dev->component[COMP_PREVIEW]->inputs, 1);
1748                 goto unreg_preview;
1749         }
1750
1751         /* get the image encoder component ready */
1752         ret = vchiq_mmal_component_init(
1753                 dev->instance, "ril.image_encode",
1754                 &dev->component[COMP_IMAGE_ENCODE]);
1755         if (ret < 0)
1756                 goto unreg_preview;
1757
1758         if (dev->component[COMP_IMAGE_ENCODE]->inputs < 1) {
1759                 ret = -EINVAL;
1760                 v4l2_err(&dev->v4l2_dev, "%s: too few input ports %d needed %d\n",
1761                          __func__, dev->component[COMP_IMAGE_ENCODE]->inputs,
1762                          1);
1763                 goto unreg_image_encoder;
1764         }
1765
1766         /* get the video encoder component ready */
1767         ret = vchiq_mmal_component_init(dev->instance, "ril.video_encode",
1768                                         &dev->component[COMP_VIDEO_ENCODE]);
1769         if (ret < 0)
1770                 goto unreg_image_encoder;
1771
1772         if (dev->component[COMP_VIDEO_ENCODE]->inputs < 1) {
1773                 ret = -EINVAL;
1774                 v4l2_err(&dev->v4l2_dev, "%s: too few input ports %d needed %d\n",
1775                          __func__, dev->component[COMP_VIDEO_ENCODE]->inputs,
1776                          1);
1777                 goto unreg_vid_encoder;
1778         }
1779
1780         {
1781                 struct vchiq_mmal_port *encoder_port =
1782                         &dev->component[COMP_VIDEO_ENCODE]->output[0];
1783                 encoder_port->format.encoding = MMAL_ENCODING_H264;
1784                 ret = vchiq_mmal_port_set_format(dev->instance,
1785                                                  encoder_port);
1786         }
1787
1788         {
1789                 unsigned int enable = 1;
1790
1791                 vchiq_mmal_port_parameter_set(
1792                         dev->instance,
1793                         &dev->component[COMP_VIDEO_ENCODE]->control,
1794                         MMAL_PARAMETER_VIDEO_IMMUTABLE_INPUT,
1795                         &enable, sizeof(enable));
1796
1797                 vchiq_mmal_port_parameter_set(dev->instance,
1798                                               &dev->component[COMP_VIDEO_ENCODE]->control,
1799                                               MMAL_PARAMETER_MINIMISE_FRAGMENTATION,
1800                                               &enable,
1801                                               sizeof(enable));
1802         }
1803         ret = bm2835_mmal_set_all_camera_controls(dev);
1804         if (ret < 0) {
1805                 v4l2_err(&dev->v4l2_dev, "%s: failed to set all camera controls: %d\n",
1806                          __func__, ret);
1807                 goto unreg_vid_encoder;
1808         }
1809
1810         return 0;
1811
1812 unreg_vid_encoder:
1813         pr_err("Cleanup: Destroy video encoder\n");
1814         vchiq_mmal_component_finalise(
1815                 dev->instance,
1816                 dev->component[COMP_VIDEO_ENCODE]);
1817
1818 unreg_image_encoder:
1819         pr_err("Cleanup: Destroy image encoder\n");
1820         vchiq_mmal_component_finalise(
1821                 dev->instance,
1822                 dev->component[COMP_IMAGE_ENCODE]);
1823
1824 unreg_preview:
1825         pr_err("Cleanup: Destroy video render\n");
1826         vchiq_mmal_component_finalise(dev->instance,
1827                                       dev->component[COMP_PREVIEW]);
1828
1829 unreg_camera:
1830         pr_err("Cleanup: Destroy camera\n");
1831         vchiq_mmal_component_finalise(dev->instance,
1832                                       dev->component[COMP_CAMERA]);
1833
1834 unreg_mmal:
1835         vchiq_mmal_finalise(dev->instance);
1836         return ret;
1837 }
1838
1839 static int bm2835_mmal_init_device(struct bm2835_mmal_dev *dev,
1840                                    struct video_device *vfd)
1841 {
1842         int ret;
1843
1844         *vfd = vdev_template;
1845
1846         vfd->v4l2_dev = &dev->v4l2_dev;
1847
1848         vfd->lock = &dev->mutex;
1849
1850         vfd->queue = &dev->capture.vb_vidq;
1851
1852         /* video device needs to be able to access instance data */
1853         video_set_drvdata(vfd, dev);
1854
1855         ret = video_register_device(vfd,
1856                                     VFL_TYPE_GRABBER,
1857                                     video_nr[dev->camera_num]);
1858         if (ret < 0)
1859                 return ret;
1860
1861         v4l2_info(vfd->v4l2_dev,
1862                   "V4L2 device registered as %s - stills mode > %dx%d\n",
1863                   video_device_node_name(vfd),
1864                   max_video_width, max_video_height);
1865
1866         return 0;
1867 }
1868
1869 static void bcm2835_cleanup_instance(struct bm2835_mmal_dev *dev)
1870 {
1871         if (!dev)
1872                 return;
1873
1874         v4l2_info(&dev->v4l2_dev, "unregistering %s\n",
1875                   video_device_node_name(&dev->vdev));
1876
1877         video_unregister_device(&dev->vdev);
1878
1879         if (dev->capture.encode_component) {
1880                 v4l2_dbg(1, bcm2835_v4l2_debug, &dev->v4l2_dev,
1881                          "mmal_exit - disconnect tunnel\n");
1882                 vchiq_mmal_port_connect_tunnel(dev->instance,
1883                                                dev->capture.camera_port, NULL);
1884                 vchiq_mmal_component_disable(dev->instance,
1885                                              dev->capture.encode_component);
1886         }
1887         vchiq_mmal_component_disable(dev->instance,
1888                                      dev->component[COMP_CAMERA]);
1889
1890         vchiq_mmal_component_finalise(dev->instance,
1891                                       dev->component[COMP_VIDEO_ENCODE]);
1892
1893         vchiq_mmal_component_finalise(dev->instance,
1894                                       dev->component[COMP_IMAGE_ENCODE]);
1895
1896         vchiq_mmal_component_finalise(dev->instance,
1897                                       dev->component[COMP_PREVIEW]);
1898
1899         vchiq_mmal_component_finalise(dev->instance,
1900                                       dev->component[COMP_CAMERA]);
1901
1902         v4l2_ctrl_handler_free(&dev->ctrl_handler);
1903
1904         v4l2_device_unregister(&dev->v4l2_dev);
1905
1906         kfree(dev);
1907 }
1908
1909 static struct v4l2_format default_v4l2_format = {
1910         .fmt.pix.pixelformat = V4L2_PIX_FMT_JPEG,
1911         .fmt.pix.width = 1024,
1912         .fmt.pix.bytesperline = 0,
1913         .fmt.pix.height = 768,
1914         .fmt.pix.sizeimage = 1024 * 768,
1915 };
1916
1917 static int bcm2835_mmal_probe(struct platform_device *pdev)
1918 {
1919         int ret;
1920         struct bm2835_mmal_dev *dev;
1921         struct vb2_queue *q;
1922         int camera;
1923         unsigned int num_cameras;
1924         struct vchiq_mmal_instance *instance;
1925         unsigned int resolutions[MAX_BCM2835_CAMERAS][2];
1926         int i;
1927
1928         ret = vchiq_mmal_init(&instance);
1929         if (ret < 0)
1930                 return ret;
1931
1932         num_cameras = get_num_cameras(instance,
1933                                       resolutions,
1934                                       MAX_BCM2835_CAMERAS);
1935
1936         if (num_cameras < 1) {
1937                 ret = -ENODEV;
1938                 goto cleanup_mmal;
1939         }
1940
1941         if (num_cameras > MAX_BCM2835_CAMERAS)
1942                 num_cameras = MAX_BCM2835_CAMERAS;
1943
1944         for (camera = 0; camera < num_cameras; camera++) {
1945                 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
1946                 if (!dev) {
1947                         ret = -ENOMEM;
1948                         goto cleanup_gdev;
1949                 }
1950
1951                 /* v4l2 core mutex used to protect all fops and v4l2 ioctls. */
1952                 mutex_init(&dev->mutex);
1953                 dev->camera_num = camera;
1954                 dev->max_width = resolutions[camera][0];
1955                 dev->max_height = resolutions[camera][1];
1956
1957                 /* setup device defaults */
1958                 dev->overlay.w.left = 150;
1959                 dev->overlay.w.top = 50;
1960                 dev->overlay.w.width = 1024;
1961                 dev->overlay.w.height = 768;
1962                 dev->overlay.clipcount = 0;
1963                 dev->overlay.field = V4L2_FIELD_NONE;
1964                 dev->overlay.global_alpha = 255;
1965
1966                 dev->capture.fmt = &formats[3]; /* JPEG */
1967
1968                 /* v4l device registration */
1969                 snprintf(dev->v4l2_dev.name, sizeof(dev->v4l2_dev.name),
1970                          "%s", BM2835_MMAL_MODULE_NAME);
1971                 ret = v4l2_device_register(NULL, &dev->v4l2_dev);
1972                 if (ret) {
1973                         dev_err(&pdev->dev, "%s: could not register V4L2 device: %d\n",
1974                                 __func__, ret);
1975                         goto free_dev;
1976                 }
1977
1978                 /* setup v4l controls */
1979                 ret = bm2835_mmal_init_controls(dev, &dev->ctrl_handler);
1980                 if (ret < 0) {
1981                         v4l2_err(&dev->v4l2_dev, "%s: could not init controls: %d\n",
1982                                  __func__, ret);
1983                         goto unreg_dev;
1984                 }
1985                 dev->v4l2_dev.ctrl_handler = &dev->ctrl_handler;
1986
1987                 /* mmal init */
1988                 dev->instance = instance;
1989                 ret = mmal_init(dev);
1990                 if (ret < 0) {
1991                         v4l2_err(&dev->v4l2_dev, "%s: mmal init failed: %d\n",
1992                                  __func__, ret);
1993                         goto unreg_dev;
1994                 }
1995                 /* initialize queue */
1996                 q = &dev->capture.vb_vidq;
1997                 memset(q, 0, sizeof(*q));
1998                 q->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1999                 q->io_modes = VB2_MMAP | VB2_USERPTR | VB2_READ;
2000                 q->drv_priv = dev;
2001                 q->buf_struct_size = sizeof(struct vb2_mmal_buffer);
2002                 q->ops = &bm2835_mmal_video_qops;
2003                 q->mem_ops = &vb2_vmalloc_memops;
2004                 q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
2005                 q->lock = &dev->mutex;
2006                 ret = vb2_queue_init(q);
2007                 if (ret < 0)
2008                         goto unreg_dev;
2009
2010                 /* initialise video devices */
2011                 ret = bm2835_mmal_init_device(dev, &dev->vdev);
2012                 if (ret < 0) {
2013                         v4l2_err(&dev->v4l2_dev, "%s: could not init device: %d\n",
2014                                  __func__, ret);
2015                         goto unreg_dev;
2016                 }
2017
2018                 /* Really want to call vidioc_s_fmt_vid_cap with the default
2019                  * format, but currently the APIs don't join up.
2020                  */
2021                 ret = mmal_setup_components(dev, &default_v4l2_format);
2022                 if (ret < 0) {
2023                         v4l2_err(&dev->v4l2_dev, "%s: could not setup components: %d\n",
2024                                  __func__, ret);
2025                         goto unreg_dev;
2026                 }
2027
2028                 v4l2_info(&dev->v4l2_dev,
2029                           "Broadcom 2835 MMAL video capture ver %s loaded.\n",
2030                           BM2835_MMAL_VERSION);
2031
2032                 gdev[camera] = dev;
2033         }
2034         return 0;
2035
2036 unreg_dev:
2037         v4l2_ctrl_handler_free(&dev->ctrl_handler);
2038         v4l2_device_unregister(&dev->v4l2_dev);
2039
2040 free_dev:
2041         kfree(dev);
2042
2043 cleanup_gdev:
2044         for (i = 0; i < camera; i++) {
2045                 bcm2835_cleanup_instance(gdev[i]);
2046                 gdev[i] = NULL;
2047         }
2048
2049 cleanup_mmal:
2050         vchiq_mmal_finalise(instance);
2051
2052         return ret;
2053 }
2054
2055 static int bcm2835_mmal_remove(struct platform_device *pdev)
2056 {
2057         int camera;
2058         struct vchiq_mmal_instance *instance = gdev[0]->instance;
2059
2060         for (camera = 0; camera < MAX_BCM2835_CAMERAS; camera++) {
2061                 bcm2835_cleanup_instance(gdev[camera]);
2062                 gdev[camera] = NULL;
2063         }
2064         vchiq_mmal_finalise(instance);
2065
2066         return 0;
2067 }
2068
2069 static struct platform_driver bcm2835_camera_driver = {
2070         .probe          = bcm2835_mmal_probe,
2071         .remove         = bcm2835_mmal_remove,
2072         .driver         = {
2073                 .name   = "bcm2835-camera",
2074         },
2075 };
2076
2077 module_platform_driver(bcm2835_camera_driver)
2078
2079 MODULE_DESCRIPTION("Broadcom 2835 MMAL video capture");
2080 MODULE_AUTHOR("Vincent Sanders");
2081 MODULE_LICENSE("GPL");
2082 MODULE_VERSION(BM2835_MMAL_VERSION);
2083 MODULE_ALIAS("platform:bcm2835-camera");