]> asedeno.scripts.mit.edu Git - linux.git/blob - drivers/media/platform/vim2m.c
media: vim2m: fix driver for it to handle different fourcc formats
[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         spinlock_t              irqlock;
150
151         struct delayed_work     work_run;
152
153         struct v4l2_m2m_dev     *m2m_dev;
154 };
155
156 struct vim2m_ctx {
157         struct v4l2_fh          fh;
158         struct vim2m_dev        *dev;
159
160         struct v4l2_ctrl_handler hdl;
161
162         /* Processed buffers in this transaction */
163         u8                      num_processed;
164
165         /* Transaction length (i.e. how many buffers per transaction) */
166         u32                     translen;
167         /* Transaction time (i.e. simulated processing time) in milliseconds */
168         u32                     transtime;
169
170         /* Abort requested by m2m */
171         int                     aborting;
172
173         /* Processing mode */
174         int                     mode;
175
176         enum v4l2_colorspace    colorspace;
177         enum v4l2_ycbcr_encoding ycbcr_enc;
178         enum v4l2_xfer_func     xfer_func;
179         enum v4l2_quantization  quant;
180
181         /* Source and destination queue data */
182         struct vim2m_q_data   q_data[2];
183 };
184
185 static inline struct vim2m_ctx *file2ctx(struct file *file)
186 {
187         return container_of(file->private_data, struct vim2m_ctx, fh);
188 }
189
190 static struct vim2m_q_data *get_q_data(struct vim2m_ctx *ctx,
191                                          enum v4l2_buf_type type)
192 {
193         switch (type) {
194         case V4L2_BUF_TYPE_VIDEO_OUTPUT:
195                 return &ctx->q_data[V4L2_M2M_SRC];
196         case V4L2_BUF_TYPE_VIDEO_CAPTURE:
197                 return &ctx->q_data[V4L2_M2M_DST];
198         default:
199                 BUG();
200         }
201         return NULL;
202 }
203
204 #define CLIP(__color) \
205         (u8)(((__color) > 0xff) ? 0xff : (((__color) < 0) ? 0 : (__color)))
206
207 static void copy_two_pixels(struct vim2m_fmt *in, struct vim2m_fmt *out,
208                             u8 **src, u8 **dst, bool reverse)
209 {
210         u8 _r[2], _g[2], _b[2], *r, *g, *b;
211         int i, step;
212
213         // If format is the same just copy the data, respecting the width
214         if (in->fourcc == out->fourcc) {
215                 int depth = out->depth >> 3;
216
217                 if (reverse) {
218                         if (in->fourcc == V4L2_PIX_FMT_YUYV) {
219                                 int u, v, y, y1;
220
221                                 *src -= 2;
222
223                                 y1 = (*src)[0]; /* copy as second point */
224                                 u  = (*src)[1];
225                                 y  = (*src)[2]; /* copy as first point */
226                                 v  = (*src)[3];
227
228                                 *src -= 2;
229
230                                 *(*dst)++ = y;
231                                 *(*dst)++ = u;
232                                 *(*dst)++ = y1;
233                                 *(*dst)++ = v;
234                                 return;
235                         }
236
237                         memcpy(*dst, *src, depth);
238                         memcpy(*dst + depth, *src - depth, depth);
239                         *src -= depth << 1;
240                 } else {
241                         memcpy(*dst, *src, depth << 1);
242                         *src += depth << 1;
243                 }
244                 *dst += depth << 1;
245                 return;
246         }
247
248         /* Step 1: read two consecutive pixels from src pointer */
249
250         r = _r;
251         g = _g;
252         b = _b;
253
254         if (reverse)
255                 step = -1;
256         else
257                 step = 1;
258
259         switch (in->fourcc) {
260         case V4L2_PIX_FMT_RGB565: /* rrrrrggg gggbbbbb */
261                 for (i = 0; i < 2; i++) {
262                         u16 pix = *(u16 *)*src;
263
264                         *r++ = (u8)(((pix & 0xf800) >> 11) << 3) | 0x07;
265                         *g++ = (u8)((((pix & 0x07e0) >> 5)) << 2) | 0x03;
266                         *b++ = (u8)((pix & 0x1f) << 3) | 0x07;
267
268                         *src += step << 1;
269                 }
270                 break;
271         case V4L2_PIX_FMT_RGB565X: /* gggbbbbb rrrrrggg */
272                 for (i = 0; i < 2; i++) {
273                         u16 pix = *(u16 *)*src;
274
275                         *r++ = (u8)(((0x00f8 & pix) >> 3) << 3) | 0x07;
276                         *g++ = (u8)(((pix & 0x7) << 2) |
277                                     ((pix & 0xe000) >> 5)) | 0x03;
278                         *b++ = (u8)(((pix & 0x1f00) >> 8) << 3) | 0x07;
279
280                         *src += step << 1;
281                 }
282                 break;
283         case V4L2_PIX_FMT_RGB24:
284                 for (i = 0; i < 2; i++) {
285                         *r++ = (*src)[0];
286                         *g++ = (*src)[1];
287                         *b++ = (*src)[2];
288
289                         *src += step * 3;
290                 }
291                 break;
292         case V4L2_PIX_FMT_BGR24:
293                 for (i = 0; i < 2; i++) {
294                         *b++ = (*src)[0];
295                         *g++ = (*src)[1];
296                         *r++ = (*src)[2];
297
298                         *src += step * 3;
299                 }
300                 break;
301         default: /* V4L2_PIX_FMT_YUYV */
302         {
303                 int u, v, y, y1, u1, v1, tmp;
304
305                 if (reverse) {
306                         *src -= 2;
307
308                         y1 = (*src)[0]; /* copy as second point */
309                         u  = (*src)[1];
310                         y  = (*src)[2]; /* copy as first point */
311                         v  = (*src)[3];
312
313                         *src -= 2;
314                 } else {
315                         y  = *(*src)++;
316                         u  = *(*src)++;
317                         y1 = *(*src)++;
318                         v  = *(*src)++;
319                 }
320
321                 u1 = (((u - 128) << 7) +  (u - 128)) >> 6;
322                 tmp = (((u - 128) << 1) + (u - 128) +
323                        ((v - 128) << 2) + ((v - 128) << 1)) >> 3;
324                 v1 = (((v - 128) << 1) +  (v - 128)) >> 1;
325
326                 *r++ = CLIP(y + v1);
327                 *g++ = CLIP(y - tmp);
328                 *b++ = CLIP(y + u1);
329
330                 *r = CLIP(y1 + v1);
331                 *g = CLIP(y1 - tmp);
332                 *b = CLIP(y1 + u1);
333                 break;
334         }
335         }
336
337         /* Step 2: store two consecutive points, reversing them if needed */
338
339         r = _r;
340         g = _g;
341         b = _b;
342
343         switch (out->fourcc) {
344         case V4L2_PIX_FMT_RGB565: /* rrrrrggg gggbbbbb */
345                 for (i = 0; i < 2; i++) {
346                         u16 *pix = (u16 *)*dst;
347
348                         *pix = ((*r << 8) & 0xf800) | ((*g << 3) & 0x07e0) |
349                                (*b >> 3);
350
351                         *dst += 2;
352                 }
353                 return;
354         case V4L2_PIX_FMT_RGB565X: /* gggbbbbb rrrrrggg */
355                 for (i = 0; i < 2; i++) {
356                         u16 *pix = (u16 *)*dst;
357                         u8 green = *g++ >> 2;
358
359                         *pix = ((green << 8) & 0xe000) | (green & 0x07) |
360                                ((*b++ << 5) & 0x1f00) | ((*r++ & 0xf8));
361
362                         *dst += 2;
363                 }
364                 return;
365         case V4L2_PIX_FMT_RGB24:
366                 for (i = 0; i < 2; i++) {
367                         *(*dst)++ = *r++;
368                         *(*dst)++ = *g++;
369                         *(*dst)++ = *b++;
370                 }
371                 return;
372         case V4L2_PIX_FMT_BGR24:
373                 for (i = 0; i < 2; i++) {
374                         *(*dst)++ = *b++;
375                         *(*dst)++ = *g++;
376                         *(*dst)++ = *r++;
377                 }
378                 return;
379         default: /* V4L2_PIX_FMT_YUYV */
380         {
381                 u8 y, y1, u, v;
382
383                 y = ((8453  * (*r) + 16594 * (*g) +  3223 * (*b)
384                      + 524288) >> 15);
385                 u = ((-4878 * (*r) - 9578  * (*g) + 14456 * (*b)
386                      + 4210688) >> 15);
387                 v = ((14456 * (*r++) - 12105 * (*g++) - 2351 * (*b++)
388                      + 4210688) >> 15);
389                 y1 = ((8453 * (*r) + 16594 * (*g) +  3223 * (*b)
390                      + 524288) >> 15);
391
392                 *(*dst)++ = y;
393                 *(*dst)++ = u;
394
395                 *(*dst)++ = y1;
396                 *(*dst)++ = v;
397                 return;
398         }
399         }
400 }
401
402 static int device_process(struct vim2m_ctx *ctx,
403                           struct vb2_v4l2_buffer *in_vb,
404                           struct vb2_v4l2_buffer *out_vb)
405 {
406         struct vim2m_dev *dev = ctx->dev;
407         struct vim2m_q_data *q_data_in, *q_data_out;
408         u8 *p_in, *p, *p_out;
409         int width, height, bytesperline, x, y, start, end, step;
410         struct vim2m_fmt *in, *out;
411
412         q_data_in = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_OUTPUT);
413         in = q_data_in->fmt;
414         width = q_data_in->width;
415         height = q_data_in->height;
416         bytesperline = (q_data_in->width * q_data_in->fmt->depth) >> 3;
417
418         q_data_out = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_CAPTURE);
419         out = q_data_out->fmt;
420
421         p_in = vb2_plane_vaddr(&in_vb->vb2_buf, 0);
422         p_out = vb2_plane_vaddr(&out_vb->vb2_buf, 0);
423         if (!p_in || !p_out) {
424                 v4l2_err(&dev->v4l2_dev,
425                          "Acquiring kernel pointers to buffers failed\n");
426                 return -EFAULT;
427         }
428
429         out_vb->sequence = get_q_data(ctx,
430                                       V4L2_BUF_TYPE_VIDEO_CAPTURE)->sequence++;
431         in_vb->sequence = q_data_in->sequence++;
432         v4l2_m2m_buf_copy_data(in_vb, out_vb, true);
433
434         if (ctx->mode & MEM2MEM_VFLIP) {
435                 start = height - 1;
436                 end = -1;
437                 step = -1;
438         } else {
439                 start = 0;
440                 end = height;
441                 step = 1;
442         }
443         for (y = start; y != end; y += step) {
444                 p = p_in + (y * bytesperline);
445                 if (ctx->mode & MEM2MEM_HFLIP)
446                         p += bytesperline - (q_data_in->fmt->depth >> 3);
447
448                 for (x = 0; x < width >> 1; x++)
449                         copy_two_pixels(in, out, &p, &p_out,
450                                         ctx->mode & MEM2MEM_HFLIP);
451         }
452
453         return 0;
454 }
455
456 /*
457  * mem2mem callbacks
458  */
459
460 /*
461  * job_ready() - check whether an instance is ready to be scheduled to run
462  */
463 static int job_ready(void *priv)
464 {
465         struct vim2m_ctx *ctx = priv;
466
467         if (v4l2_m2m_num_src_bufs_ready(ctx->fh.m2m_ctx) < ctx->translen
468             || v4l2_m2m_num_dst_bufs_ready(ctx->fh.m2m_ctx) < ctx->translen) {
469                 dprintk(ctx->dev, "Not enough buffers available\n");
470                 return 0;
471         }
472
473         return 1;
474 }
475
476 static void job_abort(void *priv)
477 {
478         struct vim2m_ctx *ctx = priv;
479
480         /* Will cancel the transaction in the next interrupt handler */
481         ctx->aborting = 1;
482 }
483
484 /* device_run() - prepares and starts the device
485  *
486  * This simulates all the immediate preparations required before starting
487  * a device. This will be called by the framework when it decides to schedule
488  * a particular instance.
489  */
490 static void device_run(void *priv)
491 {
492         struct vim2m_ctx *ctx = priv;
493         struct vim2m_dev *dev = ctx->dev;
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(&dev->work_run, msecs_to_jiffies(ctx->transtime));
511 }
512
513 static void device_work(struct work_struct *w)
514 {
515         struct vim2m_dev *vim2m_dev =
516                 container_of(w, struct vim2m_dev, work_run.work);
517         struct vim2m_ctx *curr_ctx;
518         struct vb2_v4l2_buffer *src_vb, *dst_vb;
519         unsigned long flags;
520
521         curr_ctx = v4l2_m2m_get_curr_priv(vim2m_dev->m2m_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(&vim2m_dev->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(&vim2m_dev->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 vim2m_dev *dev = ctx->dev;
901         struct vb2_v4l2_buffer *vbuf;
902         unsigned long flags;
903
904         cancel_delayed_work_sync(&dev->work_run);
905         for (;;) {
906                 if (V4L2_TYPE_IS_OUTPUT(q->type))
907                         vbuf = v4l2_m2m_src_buf_remove(ctx->fh.m2m_ctx);
908                 else
909                         vbuf = v4l2_m2m_dst_buf_remove(ctx->fh.m2m_ctx);
910                 if (vbuf == NULL)
911                         return;
912                 v4l2_ctrl_request_complete(vbuf->vb2_buf.req_obj.req,
913                                            &ctx->hdl);
914                 spin_lock_irqsave(&ctx->dev->irqlock, flags);
915                 v4l2_m2m_buf_done(vbuf, VB2_BUF_STATE_ERROR);
916                 spin_unlock_irqrestore(&ctx->dev->irqlock, flags);
917         }
918 }
919
920 static void vim2m_buf_request_complete(struct vb2_buffer *vb)
921 {
922         struct vim2m_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue);
923
924         v4l2_ctrl_request_complete(vb->req_obj.req, &ctx->hdl);
925 }
926
927 static const struct vb2_ops vim2m_qops = {
928         .queue_setup     = vim2m_queue_setup,
929         .buf_out_validate        = vim2m_buf_out_validate,
930         .buf_prepare     = vim2m_buf_prepare,
931         .buf_queue       = vim2m_buf_queue,
932         .start_streaming = vim2m_start_streaming,
933         .stop_streaming  = vim2m_stop_streaming,
934         .wait_prepare    = vb2_ops_wait_prepare,
935         .wait_finish     = vb2_ops_wait_finish,
936         .buf_request_complete = vim2m_buf_request_complete,
937 };
938
939 static int queue_init(void *priv, struct vb2_queue *src_vq, struct vb2_queue *dst_vq)
940 {
941         struct vim2m_ctx *ctx = priv;
942         int ret;
943
944         src_vq->type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
945         src_vq->io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF;
946         src_vq->drv_priv = ctx;
947         src_vq->buf_struct_size = sizeof(struct v4l2_m2m_buffer);
948         src_vq->ops = &vim2m_qops;
949         src_vq->mem_ops = &vb2_vmalloc_memops;
950         src_vq->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_COPY;
951         src_vq->lock = &ctx->dev->dev_mutex;
952         src_vq->supports_requests = true;
953
954         ret = vb2_queue_init(src_vq);
955         if (ret)
956                 return ret;
957
958         dst_vq->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
959         dst_vq->io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF;
960         dst_vq->drv_priv = ctx;
961         dst_vq->buf_struct_size = sizeof(struct v4l2_m2m_buffer);
962         dst_vq->ops = &vim2m_qops;
963         dst_vq->mem_ops = &vb2_vmalloc_memops;
964         dst_vq->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_COPY;
965         dst_vq->lock = &ctx->dev->dev_mutex;
966
967         return vb2_queue_init(dst_vq);
968 }
969
970 static const struct v4l2_ctrl_config vim2m_ctrl_trans_time_msec = {
971         .ops = &vim2m_ctrl_ops,
972         .id = V4L2_CID_TRANS_TIME_MSEC,
973         .name = "Transaction Time (msec)",
974         .type = V4L2_CTRL_TYPE_INTEGER,
975         .def = MEM2MEM_DEF_TRANSTIME,
976         .min = 1,
977         .max = 10001,
978         .step = 1,
979 };
980
981 static const struct v4l2_ctrl_config vim2m_ctrl_trans_num_bufs = {
982         .ops = &vim2m_ctrl_ops,
983         .id = V4L2_CID_TRANS_NUM_BUFS,
984         .name = "Buffers Per Transaction",
985         .type = V4L2_CTRL_TYPE_INTEGER,
986         .def = 1,
987         .min = 1,
988         .max = MEM2MEM_DEF_NUM_BUFS,
989         .step = 1,
990 };
991
992 /*
993  * File operations
994  */
995 static int vim2m_open(struct file *file)
996 {
997         struct vim2m_dev *dev = video_drvdata(file);
998         struct vim2m_ctx *ctx = NULL;
999         struct v4l2_ctrl_handler *hdl;
1000         int rc = 0;
1001
1002         if (mutex_lock_interruptible(&dev->dev_mutex))
1003                 return -ERESTARTSYS;
1004         ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1005         if (!ctx) {
1006                 rc = -ENOMEM;
1007                 goto open_unlock;
1008         }
1009
1010         v4l2_fh_init(&ctx->fh, video_devdata(file));
1011         file->private_data = &ctx->fh;
1012         ctx->dev = dev;
1013         hdl = &ctx->hdl;
1014         v4l2_ctrl_handler_init(hdl, 4);
1015         v4l2_ctrl_new_std(hdl, &vim2m_ctrl_ops, V4L2_CID_HFLIP, 0, 1, 1, 0);
1016         v4l2_ctrl_new_std(hdl, &vim2m_ctrl_ops, V4L2_CID_VFLIP, 0, 1, 1, 0);
1017         v4l2_ctrl_new_custom(hdl, &vim2m_ctrl_trans_time_msec, NULL);
1018         v4l2_ctrl_new_custom(hdl, &vim2m_ctrl_trans_num_bufs, NULL);
1019         if (hdl->error) {
1020                 rc = hdl->error;
1021                 v4l2_ctrl_handler_free(hdl);
1022                 kfree(ctx);
1023                 goto open_unlock;
1024         }
1025         ctx->fh.ctrl_handler = hdl;
1026         v4l2_ctrl_handler_setup(hdl);
1027
1028         ctx->q_data[V4L2_M2M_SRC].fmt = &formats[0];
1029         ctx->q_data[V4L2_M2M_SRC].width = 640;
1030         ctx->q_data[V4L2_M2M_SRC].height = 480;
1031         ctx->q_data[V4L2_M2M_SRC].sizeimage =
1032                 ctx->q_data[V4L2_M2M_SRC].width *
1033                 ctx->q_data[V4L2_M2M_SRC].height *
1034                 (ctx->q_data[V4L2_M2M_SRC].fmt->depth >> 3);
1035         ctx->q_data[V4L2_M2M_DST] = ctx->q_data[V4L2_M2M_SRC];
1036         ctx->colorspace = V4L2_COLORSPACE_REC709;
1037
1038         ctx->fh.m2m_ctx = v4l2_m2m_ctx_init(dev->m2m_dev, ctx, &queue_init);
1039
1040         if (IS_ERR(ctx->fh.m2m_ctx)) {
1041                 rc = PTR_ERR(ctx->fh.m2m_ctx);
1042
1043                 v4l2_ctrl_handler_free(hdl);
1044                 v4l2_fh_exit(&ctx->fh);
1045                 kfree(ctx);
1046                 goto open_unlock;
1047         }
1048
1049         v4l2_fh_add(&ctx->fh);
1050         atomic_inc(&dev->num_inst);
1051
1052         dprintk(dev, "Created instance: %p, m2m_ctx: %p\n",
1053                 ctx, ctx->fh.m2m_ctx);
1054
1055 open_unlock:
1056         mutex_unlock(&dev->dev_mutex);
1057         return rc;
1058 }
1059
1060 static int vim2m_release(struct file *file)
1061 {
1062         struct vim2m_dev *dev = video_drvdata(file);
1063         struct vim2m_ctx *ctx = file2ctx(file);
1064
1065         dprintk(dev, "Releasing instance %p\n", ctx);
1066
1067         v4l2_fh_del(&ctx->fh);
1068         v4l2_fh_exit(&ctx->fh);
1069         v4l2_ctrl_handler_free(&ctx->hdl);
1070         mutex_lock(&dev->dev_mutex);
1071         v4l2_m2m_ctx_release(ctx->fh.m2m_ctx);
1072         mutex_unlock(&dev->dev_mutex);
1073         kfree(ctx);
1074
1075         atomic_dec(&dev->num_inst);
1076
1077         return 0;
1078 }
1079
1080 static const struct v4l2_file_operations vim2m_fops = {
1081         .owner          = THIS_MODULE,
1082         .open           = vim2m_open,
1083         .release        = vim2m_release,
1084         .poll           = v4l2_m2m_fop_poll,
1085         .unlocked_ioctl = video_ioctl2,
1086         .mmap           = v4l2_m2m_fop_mmap,
1087 };
1088
1089 static const struct video_device vim2m_videodev = {
1090         .name           = MEM2MEM_NAME,
1091         .vfl_dir        = VFL_DIR_M2M,
1092         .fops           = &vim2m_fops,
1093         .ioctl_ops      = &vim2m_ioctl_ops,
1094         .minor          = -1,
1095         .release        = video_device_release_empty,
1096         .device_caps    = V4L2_CAP_VIDEO_M2M | V4L2_CAP_STREAMING,
1097 };
1098
1099 static const struct v4l2_m2m_ops m2m_ops = {
1100         .device_run     = device_run,
1101         .job_ready      = job_ready,
1102         .job_abort      = job_abort,
1103 };
1104
1105 static const struct media_device_ops m2m_media_ops = {
1106         .req_validate = vb2_request_validate,
1107         .req_queue = v4l2_m2m_request_queue,
1108 };
1109
1110 static int vim2m_probe(struct platform_device *pdev)
1111 {
1112         struct vim2m_dev *dev;
1113         struct video_device *vfd;
1114         int ret;
1115
1116         dev = devm_kzalloc(&pdev->dev, sizeof(*dev), GFP_KERNEL);
1117         if (!dev)
1118                 return -ENOMEM;
1119
1120         spin_lock_init(&dev->irqlock);
1121
1122         ret = v4l2_device_register(&pdev->dev, &dev->v4l2_dev);
1123         if (ret)
1124                 return ret;
1125
1126         atomic_set(&dev->num_inst, 0);
1127         mutex_init(&dev->dev_mutex);
1128
1129         dev->vfd = vim2m_videodev;
1130         vfd = &dev->vfd;
1131         vfd->lock = &dev->dev_mutex;
1132         vfd->v4l2_dev = &dev->v4l2_dev;
1133         INIT_DELAYED_WORK(&dev->work_run, device_work);
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);