]> asedeno.scripts.mit.edu Git - linux.git/blob - drivers/media/platform/vim2m.c
921d656cf988e87feb8fa4c4a31af2b5f671cb6c
[linux.git] / drivers / media / platform / vim2m.c
1 /*
2  * A virtual v4l2-mem2mem example device.
3  *
4  * This is a virtual device driver for testing mem-to-mem videobuf framework.
5  * It simulates a device that uses memory buffers for both source and
6  * destination, processes the data and issues an "irq" (simulated by a delayed
7  * workqueue).
8  * The device is capable of multi-instance, multi-buffer-per-transaction
9  * operation (via the mem2mem framework).
10  *
11  * Copyright (c) 2009-2010 Samsung Electronics Co., Ltd.
12  * Pawel Osciak, <pawel@osciak.com>
13  * Marek Szyprowski, <m.szyprowski@samsung.com>
14  *
15  * This program is free software; you can redistribute it and/or modify
16  * it under the terms of the GNU General Public License as published by the
17  * Free Software Foundation; either version 2 of the
18  * License, or (at your option) any later version
19  */
20 #include <linux/module.h>
21 #include <linux/delay.h>
22 #include <linux/fs.h>
23 #include <linux/sched.h>
24 #include <linux/slab.h>
25
26 #include <linux/platform_device.h>
27 #include <media/v4l2-mem2mem.h>
28 #include <media/v4l2-device.h>
29 #include <media/v4l2-ioctl.h>
30 #include <media/v4l2-ctrls.h>
31 #include <media/v4l2-event.h>
32 #include <media/videobuf2-vmalloc.h>
33
34 MODULE_DESCRIPTION("Virtual device for mem2mem framework testing");
35 MODULE_AUTHOR("Pawel Osciak, <pawel@osciak.com>");
36 MODULE_LICENSE("GPL");
37 MODULE_VERSION("0.1.1");
38 MODULE_ALIAS("mem2mem_testdev");
39
40 static unsigned debug;
41 module_param(debug, uint, 0644);
42 MODULE_PARM_DESC(debug, "activates debug info");
43
44 #define MIN_W 32
45 #define MIN_H 32
46 #define MAX_W 640
47 #define MAX_H 480
48 #define DIM_ALIGN_MASK 7 /* 8-byte alignment for line length */
49
50 /* Flags that indicate a format can be used for capture/output */
51 #define MEM2MEM_CAPTURE (1 << 0)
52 #define MEM2MEM_OUTPUT  (1 << 1)
53
54 #define MEM2MEM_NAME            "vim2m"
55
56 /* Per queue */
57 #define MEM2MEM_DEF_NUM_BUFS    VIDEO_MAX_FRAME
58 /* In bytes, per queue */
59 #define MEM2MEM_VID_MEM_LIMIT   (16 * 1024 * 1024)
60
61 /* Default transaction time in msec */
62 #define MEM2MEM_DEF_TRANSTIME   40
63
64 /* Flags that indicate processing mode */
65 #define MEM2MEM_HFLIP   (1 << 0)
66 #define MEM2MEM_VFLIP   (1 << 1)
67
68 #define dprintk(dev, fmt, arg...) \
69         v4l2_dbg(1, debug, &dev->v4l2_dev, "%s: " fmt, __func__, ## arg)
70
71
72 static void vim2m_dev_release(struct device *dev)
73 {}
74
75 static struct platform_device vim2m_pdev = {
76         .name           = MEM2MEM_NAME,
77         .dev.release    = vim2m_dev_release,
78 };
79
80 struct vim2m_fmt {
81         u32     fourcc;
82         int     depth;
83 };
84
85 static struct vim2m_fmt formats[] = {
86         {
87                 .fourcc = V4L2_PIX_FMT_RGB565,  /* rrrrrggg gggbbbbb */
88                 .depth  = 16,
89         }, {
90                 .fourcc = V4L2_PIX_FMT_RGB565X, /* gggbbbbb rrrrrggg */
91                 .depth  = 16,
92         }, {
93                 .fourcc = V4L2_PIX_FMT_RGB24,
94                 .depth  = 24,
95         }, {
96                 .fourcc = V4L2_PIX_FMT_BGR24,
97                 .depth  = 24,
98         }, {
99                 .fourcc = V4L2_PIX_FMT_YUYV,
100                 .depth  = 16,
101         },
102 };
103
104 #define NUM_FORMATS ARRAY_SIZE(formats)
105
106 /* Per-queue, driver-specific private data */
107 struct vim2m_q_data {
108         unsigned int            width;
109         unsigned int            height;
110         unsigned int            sizeimage;
111         unsigned int            sequence;
112         struct vim2m_fmt        *fmt;
113 };
114
115 enum {
116         V4L2_M2M_SRC = 0,
117         V4L2_M2M_DST = 1,
118 };
119
120 #define V4L2_CID_TRANS_TIME_MSEC        (V4L2_CID_USER_BASE + 0x1000)
121 #define V4L2_CID_TRANS_NUM_BUFS         (V4L2_CID_USER_BASE + 0x1001)
122
123 static struct vim2m_fmt *find_format(struct v4l2_format *f)
124 {
125         struct vim2m_fmt *fmt;
126         unsigned int k;
127
128         for (k = 0; k < NUM_FORMATS; k++) {
129                 fmt = &formats[k];
130                 if (fmt->fourcc == f->fmt.pix.pixelformat)
131                         break;
132         }
133
134         if (k == NUM_FORMATS)
135                 return NULL;
136
137         return &formats[k];
138 }
139
140 struct vim2m_dev {
141         struct v4l2_device      v4l2_dev;
142         struct video_device     vfd;
143 #ifdef CONFIG_MEDIA_CONTROLLER
144         struct media_device     mdev;
145 #endif
146
147         atomic_t                num_inst;
148         struct mutex            dev_mutex;
149
150         struct v4l2_m2m_dev     *m2m_dev;
151 };
152
153 struct vim2m_ctx {
154         struct v4l2_fh          fh;
155         struct vim2m_dev        *dev;
156
157         struct v4l2_ctrl_handler hdl;
158
159         /* Processed buffers in this transaction */
160         u8                      num_processed;
161
162         /* Transaction length (i.e. how many buffers per transaction) */
163         u32                     translen;
164         /* Transaction time (i.e. simulated processing time) in milliseconds */
165         u32                     transtime;
166
167         struct mutex            vb_mutex;
168         struct delayed_work     work_run;
169         spinlock_t              irqlock;
170
171         /* Abort requested by m2m */
172         int                     aborting;
173
174         /* Processing mode */
175         int                     mode;
176
177         enum v4l2_colorspace    colorspace;
178         enum v4l2_ycbcr_encoding ycbcr_enc;
179         enum v4l2_xfer_func     xfer_func;
180         enum v4l2_quantization  quant;
181
182         /* Source and destination queue data */
183         struct vim2m_q_data   q_data[2];
184 };
185
186 static inline struct vim2m_ctx *file2ctx(struct file *file)
187 {
188         return container_of(file->private_data, struct vim2m_ctx, fh);
189 }
190
191 static struct vim2m_q_data *get_q_data(struct vim2m_ctx *ctx,
192                                          enum v4l2_buf_type type)
193 {
194         switch (type) {
195         case V4L2_BUF_TYPE_VIDEO_OUTPUT:
196                 return &ctx->q_data[V4L2_M2M_SRC];
197         case V4L2_BUF_TYPE_VIDEO_CAPTURE:
198                 return &ctx->q_data[V4L2_M2M_DST];
199         default:
200                 BUG();
201         }
202         return NULL;
203 }
204
205 #define CLIP(__color) \
206         (u8)(((__color) > 0xff) ? 0xff : (((__color) < 0) ? 0 : (__color)))
207
208 static void copy_two_pixels(struct vim2m_fmt *in, struct vim2m_fmt *out,
209                             u8 **src, u8 **dst, bool reverse)
210 {
211         u8 _r[2], _g[2], _b[2], *r, *g, *b;
212         int i, step;
213
214         // If format is the same just copy the data, respecting the width
215         if (in->fourcc == out->fourcc) {
216                 int depth = out->depth >> 3;
217
218                 if (reverse) {
219                         if (in->fourcc == V4L2_PIX_FMT_YUYV) {
220                                 int u, v, y, y1;
221
222                                 *src -= 2;
223
224                                 y1 = (*src)[0]; /* copy as second point */
225                                 u  = (*src)[1];
226                                 y  = (*src)[2]; /* copy as first point */
227                                 v  = (*src)[3];
228
229                                 *src -= 2;
230
231                                 *(*dst)++ = y;
232                                 *(*dst)++ = u;
233                                 *(*dst)++ = y1;
234                                 *(*dst)++ = v;
235                                 return;
236                         }
237
238                         memcpy(*dst, *src, depth);
239                         memcpy(*dst + depth, *src - depth, depth);
240                         *src -= depth << 1;
241                 } else {
242                         memcpy(*dst, *src, depth << 1);
243                         *src += depth << 1;
244                 }
245                 *dst += depth << 1;
246                 return;
247         }
248
249         /* Step 1: read two consecutive pixels from src pointer */
250
251         r = _r;
252         g = _g;
253         b = _b;
254
255         if (reverse)
256                 step = -1;
257         else
258                 step = 1;
259
260         switch (in->fourcc) {
261         case V4L2_PIX_FMT_RGB565: /* rrrrrggg gggbbbbb */
262                 for (i = 0; i < 2; i++) {
263                         u16 pix = *(u16 *)*src;
264
265                         *r++ = (u8)(((pix & 0xf800) >> 11) << 3) | 0x07;
266                         *g++ = (u8)((((pix & 0x07e0) >> 5)) << 2) | 0x03;
267                         *b++ = (u8)((pix & 0x1f) << 3) | 0x07;
268
269                         *src += step << 1;
270                 }
271                 break;
272         case V4L2_PIX_FMT_RGB565X: /* gggbbbbb rrrrrggg */
273                 for (i = 0; i < 2; i++) {
274                         u16 pix = *(u16 *)*src;
275
276                         *r++ = (u8)(((0x00f8 & pix) >> 3) << 3) | 0x07;
277                         *g++ = (u8)(((pix & 0x7) << 2) |
278                                     ((pix & 0xe000) >> 5)) | 0x03;
279                         *b++ = (u8)(((pix & 0x1f00) >> 8) << 3) | 0x07;
280
281                         *src += step << 1;
282                 }
283                 break;
284         case V4L2_PIX_FMT_RGB24:
285                 for (i = 0; i < 2; i++) {
286                         *r++ = (*src)[0];
287                         *g++ = (*src)[1];
288                         *b++ = (*src)[2];
289
290                         *src += step * 3;
291                 }
292                 break;
293         case V4L2_PIX_FMT_BGR24:
294                 for (i = 0; i < 2; i++) {
295                         *b++ = (*src)[0];
296                         *g++ = (*src)[1];
297                         *r++ = (*src)[2];
298
299                         *src += step * 3;
300                 }
301                 break;
302         default: /* V4L2_PIX_FMT_YUYV */
303         {
304                 int u, v, y, y1, u1, v1, tmp;
305
306                 if (reverse) {
307                         *src -= 2;
308
309                         y1 = (*src)[0]; /* copy as second point */
310                         u  = (*src)[1];
311                         y  = (*src)[2]; /* copy as first point */
312                         v  = (*src)[3];
313
314                         *src -= 2;
315                 } else {
316                         y  = *(*src)++;
317                         u  = *(*src)++;
318                         y1 = *(*src)++;
319                         v  = *(*src)++;
320                 }
321
322                 u1 = (((u - 128) << 7) +  (u - 128)) >> 6;
323                 tmp = (((u - 128) << 1) + (u - 128) +
324                        ((v - 128) << 2) + ((v - 128) << 1)) >> 3;
325                 v1 = (((v - 128) << 1) +  (v - 128)) >> 1;
326
327                 *r++ = CLIP(y + v1);
328                 *g++ = CLIP(y - tmp);
329                 *b++ = CLIP(y + u1);
330
331                 *r = CLIP(y1 + v1);
332                 *g = CLIP(y1 - tmp);
333                 *b = CLIP(y1 + u1);
334                 break;
335         }
336         }
337
338         /* Step 2: store two consecutive points, reversing them if needed */
339
340         r = _r;
341         g = _g;
342         b = _b;
343
344         switch (out->fourcc) {
345         case V4L2_PIX_FMT_RGB565: /* rrrrrggg gggbbbbb */
346                 for (i = 0; i < 2; i++) {
347                         u16 *pix = (u16 *)*dst;
348
349                         *pix = ((*r << 8) & 0xf800) | ((*g << 3) & 0x07e0) |
350                                (*b >> 3);
351
352                         *dst += 2;
353                 }
354                 return;
355         case V4L2_PIX_FMT_RGB565X: /* gggbbbbb rrrrrggg */
356                 for (i = 0; i < 2; i++) {
357                         u16 *pix = (u16 *)*dst;
358                         u8 green = *g++ >> 2;
359
360                         *pix = ((green << 8) & 0xe000) | (green & 0x07) |
361                                ((*b++ << 5) & 0x1f00) | ((*r++ & 0xf8));
362
363                         *dst += 2;
364                 }
365                 return;
366         case V4L2_PIX_FMT_RGB24:
367                 for (i = 0; i < 2; i++) {
368                         *(*dst)++ = *r++;
369                         *(*dst)++ = *g++;
370                         *(*dst)++ = *b++;
371                 }
372                 return;
373         case V4L2_PIX_FMT_BGR24:
374                 for (i = 0; i < 2; i++) {
375                         *(*dst)++ = *b++;
376                         *(*dst)++ = *g++;
377                         *(*dst)++ = *r++;
378                 }
379                 return;
380         default: /* V4L2_PIX_FMT_YUYV */
381         {
382                 u8 y, y1, u, v;
383
384                 y = ((8453  * (*r) + 16594 * (*g) +  3223 * (*b)
385                      + 524288) >> 15);
386                 u = ((-4878 * (*r) - 9578  * (*g) + 14456 * (*b)
387                      + 4210688) >> 15);
388                 v = ((14456 * (*r++) - 12105 * (*g++) - 2351 * (*b++)
389                      + 4210688) >> 15);
390                 y1 = ((8453 * (*r) + 16594 * (*g) +  3223 * (*b)
391                      + 524288) >> 15);
392
393                 *(*dst)++ = y;
394                 *(*dst)++ = u;
395
396                 *(*dst)++ = y1;
397                 *(*dst)++ = v;
398                 return;
399         }
400         }
401 }
402
403 static int device_process(struct vim2m_ctx *ctx,
404                           struct vb2_v4l2_buffer *in_vb,
405                           struct vb2_v4l2_buffer *out_vb)
406 {
407         struct vim2m_dev *dev = ctx->dev;
408         struct vim2m_q_data *q_data_in, *q_data_out;
409         u8 *p_in, *p, *p_out;
410         int width, height, bytesperline, x, y, start, end, step;
411         struct vim2m_fmt *in, *out;
412
413         q_data_in = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_OUTPUT);
414         in = q_data_in->fmt;
415         width = q_data_in->width;
416         height = q_data_in->height;
417         bytesperline = (q_data_in->width * q_data_in->fmt->depth) >> 3;
418
419         q_data_out = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_CAPTURE);
420         out = q_data_out->fmt;
421
422         p_in = vb2_plane_vaddr(&in_vb->vb2_buf, 0);
423         p_out = vb2_plane_vaddr(&out_vb->vb2_buf, 0);
424         if (!p_in || !p_out) {
425                 v4l2_err(&dev->v4l2_dev,
426                          "Acquiring kernel pointers to buffers failed\n");
427                 return -EFAULT;
428         }
429
430         out_vb->sequence = get_q_data(ctx,
431                                       V4L2_BUF_TYPE_VIDEO_CAPTURE)->sequence++;
432         in_vb->sequence = q_data_in->sequence++;
433         v4l2_m2m_buf_copy_data(in_vb, out_vb, true);
434
435         if (ctx->mode & MEM2MEM_VFLIP) {
436                 start = height - 1;
437                 end = -1;
438                 step = -1;
439         } else {
440                 start = 0;
441                 end = height;
442                 step = 1;
443         }
444         for (y = start; y != end; y += step) {
445                 p = p_in + (y * bytesperline);
446                 if (ctx->mode & MEM2MEM_HFLIP)
447                         p += bytesperline - (q_data_in->fmt->depth >> 3);
448
449                 for (x = 0; x < width >> 1; x++)
450                         copy_two_pixels(in, out, &p, &p_out,
451                                         ctx->mode & MEM2MEM_HFLIP);
452         }
453
454         return 0;
455 }
456
457 /*
458  * mem2mem callbacks
459  */
460
461 /*
462  * job_ready() - check whether an instance is ready to be scheduled to run
463  */
464 static int job_ready(void *priv)
465 {
466         struct vim2m_ctx *ctx = priv;
467
468         if (v4l2_m2m_num_src_bufs_ready(ctx->fh.m2m_ctx) < ctx->translen
469             || v4l2_m2m_num_dst_bufs_ready(ctx->fh.m2m_ctx) < ctx->translen) {
470                 dprintk(ctx->dev, "Not enough buffers available\n");
471                 return 0;
472         }
473
474         return 1;
475 }
476
477 static void job_abort(void *priv)
478 {
479         struct vim2m_ctx *ctx = priv;
480
481         /* Will cancel the transaction in the next interrupt handler */
482         ctx->aborting = 1;
483 }
484
485 /* device_run() - prepares and starts the device
486  *
487  * This simulates all the immediate preparations required before starting
488  * a device. This will be called by the framework when it decides to schedule
489  * a particular instance.
490  */
491 static void device_run(void *priv)
492 {
493         struct vim2m_ctx *ctx = priv;
494         struct vb2_v4l2_buffer *src_buf, *dst_buf;
495
496         src_buf = v4l2_m2m_next_src_buf(ctx->fh.m2m_ctx);
497         dst_buf = v4l2_m2m_next_dst_buf(ctx->fh.m2m_ctx);
498
499         /* Apply request controls if any */
500         v4l2_ctrl_request_setup(src_buf->vb2_buf.req_obj.req,
501                                 &ctx->hdl);
502
503         device_process(ctx, src_buf, dst_buf);
504
505         /* Complete request controls if any */
506         v4l2_ctrl_request_complete(src_buf->vb2_buf.req_obj.req,
507                                    &ctx->hdl);
508
509         /* Run delayed work, which simulates a hardware irq  */
510         schedule_delayed_work(&ctx->work_run, msecs_to_jiffies(ctx->transtime));
511 }
512
513 static void device_work(struct work_struct *w)
514 {
515         struct vim2m_ctx *curr_ctx;
516         struct vim2m_dev *vim2m_dev;
517         struct vb2_v4l2_buffer *src_vb, *dst_vb;
518         unsigned long flags;
519
520         curr_ctx = container_of(w, struct vim2m_ctx, work_run.work);
521         vim2m_dev = curr_ctx->dev;
522
523         if (NULL == curr_ctx) {
524                 pr_err("Instance released before the end of transaction\n");
525                 return;
526         }
527
528         src_vb = v4l2_m2m_src_buf_remove(curr_ctx->fh.m2m_ctx);
529         dst_vb = v4l2_m2m_dst_buf_remove(curr_ctx->fh.m2m_ctx);
530
531         curr_ctx->num_processed++;
532
533         spin_lock_irqsave(&curr_ctx->irqlock, flags);
534         v4l2_m2m_buf_done(src_vb, VB2_BUF_STATE_DONE);
535         v4l2_m2m_buf_done(dst_vb, VB2_BUF_STATE_DONE);
536         spin_unlock_irqrestore(&curr_ctx->irqlock, flags);
537
538         if (curr_ctx->num_processed == curr_ctx->translen
539             || curr_ctx->aborting) {
540                 dprintk(curr_ctx->dev, "Finishing transaction\n");
541                 curr_ctx->num_processed = 0;
542                 v4l2_m2m_job_finish(vim2m_dev->m2m_dev, curr_ctx->fh.m2m_ctx);
543         } else {
544                 device_run(curr_ctx);
545         }
546 }
547
548 /*
549  * video ioctls
550  */
551 static int vidioc_querycap(struct file *file, void *priv,
552                            struct v4l2_capability *cap)
553 {
554         strncpy(cap->driver, MEM2MEM_NAME, sizeof(cap->driver) - 1);
555         strncpy(cap->card, MEM2MEM_NAME, sizeof(cap->card) - 1);
556         snprintf(cap->bus_info, sizeof(cap->bus_info),
557                         "platform:%s", MEM2MEM_NAME);
558         return 0;
559 }
560
561 static int enum_fmt(struct v4l2_fmtdesc *f, u32 type)
562 {
563         struct vim2m_fmt *fmt;
564
565         if (f->index < NUM_FORMATS) {
566                 /* Format found */
567                 fmt = &formats[f->index];
568                 f->pixelformat = fmt->fourcc;
569                 return 0;
570         }
571
572         /* Format not found */
573         return -EINVAL;
574 }
575
576 static int vidioc_enum_fmt_vid_cap(struct file *file, void *priv,
577                                    struct v4l2_fmtdesc *f)
578 {
579         return enum_fmt(f, MEM2MEM_CAPTURE);
580 }
581
582 static int vidioc_enum_fmt_vid_out(struct file *file, void *priv,
583                                    struct v4l2_fmtdesc *f)
584 {
585         return enum_fmt(f, MEM2MEM_OUTPUT);
586 }
587
588 static int vidioc_g_fmt(struct vim2m_ctx *ctx, struct v4l2_format *f)
589 {
590         struct vb2_queue *vq;
591         struct vim2m_q_data *q_data;
592
593         vq = v4l2_m2m_get_vq(ctx->fh.m2m_ctx, f->type);
594         if (!vq)
595                 return -EINVAL;
596
597         q_data = get_q_data(ctx, f->type);
598
599         f->fmt.pix.width        = q_data->width;
600         f->fmt.pix.height       = q_data->height;
601         f->fmt.pix.field        = V4L2_FIELD_NONE;
602         f->fmt.pix.pixelformat  = q_data->fmt->fourcc;
603         f->fmt.pix.bytesperline = (q_data->width * q_data->fmt->depth) >> 3;
604         f->fmt.pix.sizeimage    = q_data->sizeimage;
605         f->fmt.pix.colorspace   = ctx->colorspace;
606         f->fmt.pix.xfer_func    = ctx->xfer_func;
607         f->fmt.pix.ycbcr_enc    = ctx->ycbcr_enc;
608         f->fmt.pix.quantization = ctx->quant;
609
610         return 0;
611 }
612
613 static int vidioc_g_fmt_vid_out(struct file *file, void *priv,
614                                 struct v4l2_format *f)
615 {
616         return vidioc_g_fmt(file2ctx(file), f);
617 }
618
619 static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
620                                 struct v4l2_format *f)
621 {
622         return vidioc_g_fmt(file2ctx(file), f);
623 }
624
625 static int vidioc_try_fmt(struct v4l2_format *f, struct vim2m_fmt *fmt)
626 {
627         /* V4L2 specification suggests the driver corrects the format struct
628          * if any of the dimensions is unsupported */
629         if (f->fmt.pix.height < MIN_H)
630                 f->fmt.pix.height = MIN_H;
631         else if (f->fmt.pix.height > MAX_H)
632                 f->fmt.pix.height = MAX_H;
633
634         if (f->fmt.pix.width < MIN_W)
635                 f->fmt.pix.width = MIN_W;
636         else if (f->fmt.pix.width > MAX_W)
637                 f->fmt.pix.width = MAX_W;
638
639         f->fmt.pix.width &= ~DIM_ALIGN_MASK;
640         f->fmt.pix.bytesperline = (f->fmt.pix.width * fmt->depth) >> 3;
641         f->fmt.pix.sizeimage = f->fmt.pix.height * f->fmt.pix.bytesperline;
642         f->fmt.pix.field = V4L2_FIELD_NONE;
643
644         return 0;
645 }
646
647 static int vidioc_try_fmt_vid_cap(struct file *file, void *priv,
648                                   struct v4l2_format *f)
649 {
650         struct vim2m_fmt *fmt;
651         struct vim2m_ctx *ctx = file2ctx(file);
652
653         fmt = find_format(f);
654         if (!fmt) {
655                 f->fmt.pix.pixelformat = formats[0].fourcc;
656                 fmt = find_format(f);
657         }
658         f->fmt.pix.colorspace = ctx->colorspace;
659         f->fmt.pix.xfer_func = ctx->xfer_func;
660         f->fmt.pix.ycbcr_enc = ctx->ycbcr_enc;
661         f->fmt.pix.quantization = ctx->quant;
662
663         return vidioc_try_fmt(f, fmt);
664 }
665
666 static int vidioc_try_fmt_vid_out(struct file *file, void *priv,
667                                   struct v4l2_format *f)
668 {
669         struct vim2m_fmt *fmt;
670
671         fmt = find_format(f);
672         if (!fmt) {
673                 f->fmt.pix.pixelformat = formats[0].fourcc;
674                 fmt = find_format(f);
675         }
676         if (!f->fmt.pix.colorspace)
677                 f->fmt.pix.colorspace = V4L2_COLORSPACE_REC709;
678
679         return vidioc_try_fmt(f, fmt);
680 }
681
682 static int vidioc_s_fmt(struct vim2m_ctx *ctx, struct v4l2_format *f)
683 {
684         struct vim2m_q_data *q_data;
685         struct vb2_queue *vq;
686
687         vq = v4l2_m2m_get_vq(ctx->fh.m2m_ctx, f->type);
688         if (!vq)
689                 return -EINVAL;
690
691         q_data = get_q_data(ctx, f->type);
692         if (!q_data)
693                 return -EINVAL;
694
695         if (vb2_is_busy(vq)) {
696                 v4l2_err(&ctx->dev->v4l2_dev, "%s queue busy\n", __func__);
697                 return -EBUSY;
698         }
699
700         q_data->fmt             = find_format(f);
701         q_data->width           = f->fmt.pix.width;
702         q_data->height          = f->fmt.pix.height;
703         q_data->sizeimage       = q_data->width * q_data->height
704                                 * q_data->fmt->depth >> 3;
705
706         dprintk(ctx->dev,
707                 "Setting format for type %d, wxh: %dx%d, fmt: %d\n",
708                 f->type, q_data->width, q_data->height, q_data->fmt->fourcc);
709
710         return 0;
711 }
712
713 static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
714                                 struct v4l2_format *f)
715 {
716         int ret;
717
718         ret = vidioc_try_fmt_vid_cap(file, priv, f);
719         if (ret)
720                 return ret;
721
722         return vidioc_s_fmt(file2ctx(file), f);
723 }
724
725 static int vidioc_s_fmt_vid_out(struct file *file, void *priv,
726                                 struct v4l2_format *f)
727 {
728         struct vim2m_ctx *ctx = file2ctx(file);
729         int ret;
730
731         ret = vidioc_try_fmt_vid_out(file, priv, f);
732         if (ret)
733                 return ret;
734
735         ret = vidioc_s_fmt(file2ctx(file), f);
736         if (!ret) {
737                 ctx->colorspace = f->fmt.pix.colorspace;
738                 ctx->xfer_func = f->fmt.pix.xfer_func;
739                 ctx->ycbcr_enc = f->fmt.pix.ycbcr_enc;
740                 ctx->quant = f->fmt.pix.quantization;
741         }
742         return ret;
743 }
744
745 static int vim2m_s_ctrl(struct v4l2_ctrl *ctrl)
746 {
747         struct vim2m_ctx *ctx =
748                 container_of(ctrl->handler, struct vim2m_ctx, hdl);
749
750         switch (ctrl->id) {
751         case V4L2_CID_HFLIP:
752                 if (ctrl->val)
753                         ctx->mode |= MEM2MEM_HFLIP;
754                 else
755                         ctx->mode &= ~MEM2MEM_HFLIP;
756                 break;
757
758         case V4L2_CID_VFLIP:
759                 if (ctrl->val)
760                         ctx->mode |= MEM2MEM_VFLIP;
761                 else
762                         ctx->mode &= ~MEM2MEM_VFLIP;
763                 break;
764
765         case V4L2_CID_TRANS_TIME_MSEC:
766                 ctx->transtime = ctrl->val;
767                 break;
768
769         case V4L2_CID_TRANS_NUM_BUFS:
770                 ctx->translen = ctrl->val;
771                 break;
772
773         default:
774                 v4l2_err(&ctx->dev->v4l2_dev, "Invalid control\n");
775                 return -EINVAL;
776         }
777
778         return 0;
779 }
780
781 static const struct v4l2_ctrl_ops vim2m_ctrl_ops = {
782         .s_ctrl = vim2m_s_ctrl,
783 };
784
785
786 static const struct v4l2_ioctl_ops vim2m_ioctl_ops = {
787         .vidioc_querycap        = vidioc_querycap,
788
789         .vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap,
790         .vidioc_g_fmt_vid_cap   = vidioc_g_fmt_vid_cap,
791         .vidioc_try_fmt_vid_cap = vidioc_try_fmt_vid_cap,
792         .vidioc_s_fmt_vid_cap   = vidioc_s_fmt_vid_cap,
793
794         .vidioc_enum_fmt_vid_out = vidioc_enum_fmt_vid_out,
795         .vidioc_g_fmt_vid_out   = vidioc_g_fmt_vid_out,
796         .vidioc_try_fmt_vid_out = vidioc_try_fmt_vid_out,
797         .vidioc_s_fmt_vid_out   = vidioc_s_fmt_vid_out,
798
799         .vidioc_reqbufs         = v4l2_m2m_ioctl_reqbufs,
800         .vidioc_querybuf        = v4l2_m2m_ioctl_querybuf,
801         .vidioc_qbuf            = v4l2_m2m_ioctl_qbuf,
802         .vidioc_dqbuf           = v4l2_m2m_ioctl_dqbuf,
803         .vidioc_prepare_buf     = v4l2_m2m_ioctl_prepare_buf,
804         .vidioc_create_bufs     = v4l2_m2m_ioctl_create_bufs,
805         .vidioc_expbuf          = v4l2_m2m_ioctl_expbuf,
806
807         .vidioc_streamon        = v4l2_m2m_ioctl_streamon,
808         .vidioc_streamoff       = v4l2_m2m_ioctl_streamoff,
809
810         .vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
811         .vidioc_unsubscribe_event = v4l2_event_unsubscribe,
812 };
813
814
815 /*
816  * Queue operations
817  */
818
819 static int vim2m_queue_setup(struct vb2_queue *vq,
820                                 unsigned int *nbuffers, unsigned int *nplanes,
821                                 unsigned int sizes[], struct device *alloc_devs[])
822 {
823         struct vim2m_ctx *ctx = vb2_get_drv_priv(vq);
824         struct vim2m_q_data *q_data;
825         unsigned int size, count = *nbuffers;
826
827         q_data = get_q_data(ctx, vq->type);
828
829         size = q_data->width * q_data->height * q_data->fmt->depth >> 3;
830
831         while (size * count > MEM2MEM_VID_MEM_LIMIT)
832                 (count)--;
833         *nbuffers = count;
834
835         if (*nplanes)
836                 return sizes[0] < size ? -EINVAL : 0;
837
838         *nplanes = 1;
839         sizes[0] = size;
840
841         dprintk(ctx->dev, "get %d buffer(s) of size %d each.\n", count, size);
842
843         return 0;
844 }
845
846 static int vim2m_buf_out_validate(struct vb2_buffer *vb)
847 {
848         struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
849         struct vim2m_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue);
850
851         if (vbuf->field == V4L2_FIELD_ANY)
852                 vbuf->field = V4L2_FIELD_NONE;
853         if (vbuf->field != V4L2_FIELD_NONE) {
854                 dprintk(ctx->dev, "%s field isn't supported\n", __func__);
855                 return -EINVAL;
856         }
857
858         return 0;
859 }
860
861 static int vim2m_buf_prepare(struct vb2_buffer *vb)
862 {
863         struct vim2m_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue);
864         struct vim2m_q_data *q_data;
865
866         dprintk(ctx->dev, "type: %d\n", vb->vb2_queue->type);
867
868         q_data = get_q_data(ctx, vb->vb2_queue->type);
869         if (vb2_plane_size(vb, 0) < q_data->sizeimage) {
870                 dprintk(ctx->dev, "%s data will not fit into plane (%lu < %lu)\n",
871                                 __func__, vb2_plane_size(vb, 0), (long)q_data->sizeimage);
872                 return -EINVAL;
873         }
874
875         vb2_set_plane_payload(vb, 0, q_data->sizeimage);
876
877         return 0;
878 }
879
880 static void vim2m_buf_queue(struct vb2_buffer *vb)
881 {
882         struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
883         struct vim2m_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue);
884
885         v4l2_m2m_buf_queue(ctx->fh.m2m_ctx, vbuf);
886 }
887
888 static int vim2m_start_streaming(struct vb2_queue *q, unsigned count)
889 {
890         struct vim2m_ctx *ctx = vb2_get_drv_priv(q);
891         struct vim2m_q_data *q_data = get_q_data(ctx, q->type);
892
893         q_data->sequence = 0;
894         return 0;
895 }
896
897 static void vim2m_stop_streaming(struct vb2_queue *q)
898 {
899         struct vim2m_ctx *ctx = vb2_get_drv_priv(q);
900         struct vb2_v4l2_buffer *vbuf;
901         unsigned long flags;
902
903         cancel_delayed_work_sync(&ctx->work_run);
904         for (;;) {
905                 if (V4L2_TYPE_IS_OUTPUT(q->type))
906                         vbuf = v4l2_m2m_src_buf_remove(ctx->fh.m2m_ctx);
907                 else
908                         vbuf = v4l2_m2m_dst_buf_remove(ctx->fh.m2m_ctx);
909                 if (vbuf == NULL)
910                         return;
911                 v4l2_ctrl_request_complete(vbuf->vb2_buf.req_obj.req,
912                                            &ctx->hdl);
913                 spin_lock_irqsave(&ctx->irqlock, flags);
914                 v4l2_m2m_buf_done(vbuf, VB2_BUF_STATE_ERROR);
915                 spin_unlock_irqrestore(&ctx->irqlock, flags);
916         }
917 }
918
919 static void vim2m_buf_request_complete(struct vb2_buffer *vb)
920 {
921         struct vim2m_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue);
922
923         v4l2_ctrl_request_complete(vb->req_obj.req, &ctx->hdl);
924 }
925
926 static const struct vb2_ops vim2m_qops = {
927         .queue_setup     = vim2m_queue_setup,
928         .buf_out_validate        = vim2m_buf_out_validate,
929         .buf_prepare     = vim2m_buf_prepare,
930         .buf_queue       = vim2m_buf_queue,
931         .start_streaming = vim2m_start_streaming,
932         .stop_streaming  = vim2m_stop_streaming,
933         .wait_prepare    = vb2_ops_wait_prepare,
934         .wait_finish     = vb2_ops_wait_finish,
935         .buf_request_complete = vim2m_buf_request_complete,
936 };
937
938 static int queue_init(void *priv, struct vb2_queue *src_vq, struct vb2_queue *dst_vq)
939 {
940         struct vim2m_ctx *ctx = priv;
941         int ret;
942
943         src_vq->type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
944         src_vq->io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF;
945         src_vq->drv_priv = ctx;
946         src_vq->buf_struct_size = sizeof(struct v4l2_m2m_buffer);
947         src_vq->ops = &vim2m_qops;
948         src_vq->mem_ops = &vb2_vmalloc_memops;
949         src_vq->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_COPY;
950         src_vq->lock = &ctx->vb_mutex;
951         src_vq->supports_requests = true;
952
953         ret = vb2_queue_init(src_vq);
954         if (ret)
955                 return ret;
956
957         dst_vq->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
958         dst_vq->io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF;
959         dst_vq->drv_priv = ctx;
960         dst_vq->buf_struct_size = sizeof(struct v4l2_m2m_buffer);
961         dst_vq->ops = &vim2m_qops;
962         dst_vq->mem_ops = &vb2_vmalloc_memops;
963         dst_vq->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_COPY;
964         dst_vq->lock = &ctx->vb_mutex;
965
966         return vb2_queue_init(dst_vq);
967 }
968
969 static const struct v4l2_ctrl_config vim2m_ctrl_trans_time_msec = {
970         .ops = &vim2m_ctrl_ops,
971         .id = V4L2_CID_TRANS_TIME_MSEC,
972         .name = "Transaction Time (msec)",
973         .type = V4L2_CTRL_TYPE_INTEGER,
974         .def = MEM2MEM_DEF_TRANSTIME,
975         .min = 1,
976         .max = 10001,
977         .step = 1,
978 };
979
980 static const struct v4l2_ctrl_config vim2m_ctrl_trans_num_bufs = {
981         .ops = &vim2m_ctrl_ops,
982         .id = V4L2_CID_TRANS_NUM_BUFS,
983         .name = "Buffers Per Transaction",
984         .type = V4L2_CTRL_TYPE_INTEGER,
985         .def = 1,
986         .min = 1,
987         .max = MEM2MEM_DEF_NUM_BUFS,
988         .step = 1,
989 };
990
991 /*
992  * File operations
993  */
994 static int vim2m_open(struct file *file)
995 {
996         struct vim2m_dev *dev = video_drvdata(file);
997         struct vim2m_ctx *ctx = NULL;
998         struct v4l2_ctrl_handler *hdl;
999         int rc = 0;
1000
1001         if (mutex_lock_interruptible(&dev->dev_mutex))
1002                 return -ERESTARTSYS;
1003         ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1004         if (!ctx) {
1005                 rc = -ENOMEM;
1006                 goto open_unlock;
1007         }
1008
1009         v4l2_fh_init(&ctx->fh, video_devdata(file));
1010         file->private_data = &ctx->fh;
1011         ctx->dev = dev;
1012         hdl = &ctx->hdl;
1013         v4l2_ctrl_handler_init(hdl, 4);
1014         v4l2_ctrl_new_std(hdl, &vim2m_ctrl_ops, V4L2_CID_HFLIP, 0, 1, 1, 0);
1015         v4l2_ctrl_new_std(hdl, &vim2m_ctrl_ops, V4L2_CID_VFLIP, 0, 1, 1, 0);
1016         v4l2_ctrl_new_custom(hdl, &vim2m_ctrl_trans_time_msec, NULL);
1017         v4l2_ctrl_new_custom(hdl, &vim2m_ctrl_trans_num_bufs, NULL);
1018         if (hdl->error) {
1019                 rc = hdl->error;
1020                 v4l2_ctrl_handler_free(hdl);
1021                 kfree(ctx);
1022                 goto open_unlock;
1023         }
1024         ctx->fh.ctrl_handler = hdl;
1025         v4l2_ctrl_handler_setup(hdl);
1026
1027         ctx->q_data[V4L2_M2M_SRC].fmt = &formats[0];
1028         ctx->q_data[V4L2_M2M_SRC].width = 640;
1029         ctx->q_data[V4L2_M2M_SRC].height = 480;
1030         ctx->q_data[V4L2_M2M_SRC].sizeimage =
1031                 ctx->q_data[V4L2_M2M_SRC].width *
1032                 ctx->q_data[V4L2_M2M_SRC].height *
1033                 (ctx->q_data[V4L2_M2M_SRC].fmt->depth >> 3);
1034         ctx->q_data[V4L2_M2M_DST] = ctx->q_data[V4L2_M2M_SRC];
1035         ctx->colorspace = V4L2_COLORSPACE_REC709;
1036
1037         ctx->fh.m2m_ctx = v4l2_m2m_ctx_init(dev->m2m_dev, ctx, &queue_init);
1038
1039         mutex_init(&ctx->vb_mutex);
1040         spin_lock_init(&ctx->irqlock);
1041         INIT_DELAYED_WORK(&ctx->work_run, device_work);
1042
1043         if (IS_ERR(ctx->fh.m2m_ctx)) {
1044                 rc = PTR_ERR(ctx->fh.m2m_ctx);
1045
1046                 v4l2_ctrl_handler_free(hdl);
1047                 v4l2_fh_exit(&ctx->fh);
1048                 kfree(ctx);
1049                 goto open_unlock;
1050         }
1051
1052         v4l2_fh_add(&ctx->fh);
1053         atomic_inc(&dev->num_inst);
1054
1055         dprintk(dev, "Created instance: %p, m2m_ctx: %p\n",
1056                 ctx, ctx->fh.m2m_ctx);
1057
1058 open_unlock:
1059         mutex_unlock(&dev->dev_mutex);
1060         return rc;
1061 }
1062
1063 static int vim2m_release(struct file *file)
1064 {
1065         struct vim2m_dev *dev = video_drvdata(file);
1066         struct vim2m_ctx *ctx = file2ctx(file);
1067
1068         dprintk(dev, "Releasing instance %p\n", ctx);
1069
1070         v4l2_fh_del(&ctx->fh);
1071         v4l2_fh_exit(&ctx->fh);
1072         v4l2_ctrl_handler_free(&ctx->hdl);
1073         mutex_lock(&dev->dev_mutex);
1074         v4l2_m2m_ctx_release(ctx->fh.m2m_ctx);
1075         mutex_unlock(&dev->dev_mutex);
1076         kfree(ctx);
1077
1078         atomic_dec(&dev->num_inst);
1079
1080         return 0;
1081 }
1082
1083 static const struct v4l2_file_operations vim2m_fops = {
1084         .owner          = THIS_MODULE,
1085         .open           = vim2m_open,
1086         .release        = vim2m_release,
1087         .poll           = v4l2_m2m_fop_poll,
1088         .unlocked_ioctl = video_ioctl2,
1089         .mmap           = v4l2_m2m_fop_mmap,
1090 };
1091
1092 static const struct video_device vim2m_videodev = {
1093         .name           = MEM2MEM_NAME,
1094         .vfl_dir        = VFL_DIR_M2M,
1095         .fops           = &vim2m_fops,
1096         .ioctl_ops      = &vim2m_ioctl_ops,
1097         .minor          = -1,
1098         .release        = video_device_release_empty,
1099         .device_caps    = V4L2_CAP_VIDEO_M2M | V4L2_CAP_STREAMING,
1100 };
1101
1102 static const struct v4l2_m2m_ops m2m_ops = {
1103         .device_run     = device_run,
1104         .job_ready      = job_ready,
1105         .job_abort      = job_abort,
1106 };
1107
1108 static const struct media_device_ops m2m_media_ops = {
1109         .req_validate = vb2_request_validate,
1110         .req_queue = v4l2_m2m_request_queue,
1111 };
1112
1113 static int vim2m_probe(struct platform_device *pdev)
1114 {
1115         struct vim2m_dev *dev;
1116         struct video_device *vfd;
1117         int ret;
1118
1119         dev = devm_kzalloc(&pdev->dev, sizeof(*dev), GFP_KERNEL);
1120         if (!dev)
1121                 return -ENOMEM;
1122
1123         ret = v4l2_device_register(&pdev->dev, &dev->v4l2_dev);
1124         if (ret)
1125                 return ret;
1126
1127         atomic_set(&dev->num_inst, 0);
1128         mutex_init(&dev->dev_mutex);
1129
1130         dev->vfd = vim2m_videodev;
1131         vfd = &dev->vfd;
1132         vfd->lock = &dev->dev_mutex;
1133         vfd->v4l2_dev = &dev->v4l2_dev;
1134
1135         ret = video_register_device(vfd, VFL_TYPE_GRABBER, 0);
1136         if (ret) {
1137                 v4l2_err(&dev->v4l2_dev, "Failed to register video device\n");
1138                 goto unreg_v4l2;
1139         }
1140
1141         video_set_drvdata(vfd, dev);
1142         v4l2_info(&dev->v4l2_dev,
1143                         "Device registered as /dev/video%d\n", vfd->num);
1144
1145         platform_set_drvdata(pdev, dev);
1146
1147         dev->m2m_dev = v4l2_m2m_init(&m2m_ops);
1148         if (IS_ERR(dev->m2m_dev)) {
1149                 v4l2_err(&dev->v4l2_dev, "Failed to init mem2mem device\n");
1150                 ret = PTR_ERR(dev->m2m_dev);
1151                 goto unreg_dev;
1152         }
1153
1154 #ifdef CONFIG_MEDIA_CONTROLLER
1155         dev->mdev.dev = &pdev->dev;
1156         strscpy(dev->mdev.model, "vim2m", sizeof(dev->mdev.model));
1157         media_device_init(&dev->mdev);
1158         dev->mdev.ops = &m2m_media_ops;
1159         dev->v4l2_dev.mdev = &dev->mdev;
1160
1161         ret = v4l2_m2m_register_media_controller(dev->m2m_dev,
1162                         vfd, MEDIA_ENT_F_PROC_VIDEO_SCALER);
1163         if (ret) {
1164                 v4l2_err(&dev->v4l2_dev, "Failed to init mem2mem media controller\n");
1165                 goto unreg_m2m;
1166         }
1167
1168         ret = media_device_register(&dev->mdev);
1169         if (ret) {
1170                 v4l2_err(&dev->v4l2_dev, "Failed to register mem2mem media device\n");
1171                 goto unreg_m2m_mc;
1172         }
1173 #endif
1174         return 0;
1175
1176 #ifdef CONFIG_MEDIA_CONTROLLER
1177 unreg_m2m_mc:
1178         v4l2_m2m_unregister_media_controller(dev->m2m_dev);
1179 unreg_m2m:
1180         v4l2_m2m_release(dev->m2m_dev);
1181 #endif
1182 unreg_dev:
1183         video_unregister_device(&dev->vfd);
1184 unreg_v4l2:
1185         v4l2_device_unregister(&dev->v4l2_dev);
1186
1187         return ret;
1188 }
1189
1190 static int vim2m_remove(struct platform_device *pdev)
1191 {
1192         struct vim2m_dev *dev = platform_get_drvdata(pdev);
1193
1194         v4l2_info(&dev->v4l2_dev, "Removing " MEM2MEM_NAME);
1195
1196 #ifdef CONFIG_MEDIA_CONTROLLER
1197         media_device_unregister(&dev->mdev);
1198         v4l2_m2m_unregister_media_controller(dev->m2m_dev);
1199         media_device_cleanup(&dev->mdev);
1200 #endif
1201         v4l2_m2m_release(dev->m2m_dev);
1202         video_unregister_device(&dev->vfd);
1203         v4l2_device_unregister(&dev->v4l2_dev);
1204
1205         return 0;
1206 }
1207
1208 static struct platform_driver vim2m_pdrv = {
1209         .probe          = vim2m_probe,
1210         .remove         = vim2m_remove,
1211         .driver         = {
1212                 .name   = MEM2MEM_NAME,
1213         },
1214 };
1215
1216 static void __exit vim2m_exit(void)
1217 {
1218         platform_driver_unregister(&vim2m_pdrv);
1219         platform_device_unregister(&vim2m_pdev);
1220 }
1221
1222 static int __init vim2m_init(void)
1223 {
1224         int ret;
1225
1226         ret = platform_device_register(&vim2m_pdev);
1227         if (ret)
1228                 return ret;
1229
1230         ret = platform_driver_register(&vim2m_pdrv);
1231         if (ret)
1232                 platform_device_unregister(&vim2m_pdev);
1233
1234         return ret;
1235 }
1236
1237 module_init(vim2m_init);
1238 module_exit(vim2m_exit);