ca8b133e2e46e357628bf722ac03416a495a001d
[linux-2.6-microblaze.git] / drivers / staging / media / hantro / hantro_drv.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Hantro VPU codec driver
4  *
5  * Copyright (C) 2018 Collabora, Ltd.
6  * Copyright 2018 Google LLC.
7  *      Tomasz Figa <tfiga@chromium.org>
8  *
9  * Based on s5p-mfc driver by Samsung Electronics Co., Ltd.
10  * Copyright (C) 2011 Samsung Electronics Co., Ltd.
11  */
12
13 #include <linux/clk.h>
14 #include <linux/module.h>
15 #include <linux/of.h>
16 #include <linux/platform_device.h>
17 #include <linux/pm.h>
18 #include <linux/pm_runtime.h>
19 #include <linux/slab.h>
20 #include <linux/videodev2.h>
21 #include <linux/workqueue.h>
22 #include <media/v4l2-event.h>
23 #include <media/v4l2-mem2mem.h>
24 #include <media/videobuf2-core.h>
25 #include <media/videobuf2-vmalloc.h>
26
27 #include "hantro_v4l2.h"
28 #include "hantro.h"
29 #include "hantro_hw.h"
30
31 #define DRIVER_NAME "hantro-vpu"
32
33 int hantro_debug;
34 module_param_named(debug, hantro_debug, int, 0644);
35 MODULE_PARM_DESC(debug,
36                  "Debug level - higher value produces more verbose messages");
37
38 void *hantro_get_ctrl(struct hantro_ctx *ctx, u32 id)
39 {
40         struct v4l2_ctrl *ctrl;
41
42         ctrl = v4l2_ctrl_find(&ctx->ctrl_handler, id);
43         return ctrl ? ctrl->p_cur.p : NULL;
44 }
45
46 dma_addr_t hantro_get_ref(struct hantro_ctx *ctx, u64 ts)
47 {
48         struct vb2_queue *q = v4l2_m2m_get_dst_vq(ctx->fh.m2m_ctx);
49         struct vb2_buffer *buf;
50         int index;
51
52         index = vb2_find_timestamp(q, ts, 0);
53         if (index < 0)
54                 return 0;
55         buf = vb2_get_buffer(q, index);
56         return hantro_get_dec_buf_addr(ctx, buf);
57 }
58
59 static int
60 hantro_enc_buf_finish(struct hantro_ctx *ctx, struct vb2_buffer *buf,
61                       unsigned int bytesused)
62 {
63         size_t avail_size;
64
65         avail_size = vb2_plane_size(buf, 0) - ctx->vpu_dst_fmt->header_size;
66         if (bytesused > avail_size)
67                 return -EINVAL;
68         /*
69          * The bounce buffer is only for the JPEG encoder.
70          * TODO: Rework the JPEG encoder to eliminate the need
71          * for a bounce buffer.
72          */
73         if (ctx->jpeg_enc.bounce_buffer.cpu) {
74                 memcpy(vb2_plane_vaddr(buf, 0) +
75                        ctx->vpu_dst_fmt->header_size,
76                        ctx->jpeg_enc.bounce_buffer.cpu, bytesused);
77         }
78         buf->planes[0].bytesused =
79                 ctx->vpu_dst_fmt->header_size + bytesused;
80         return 0;
81 }
82
83 static int
84 hantro_dec_buf_finish(struct hantro_ctx *ctx, struct vb2_buffer *buf,
85                       unsigned int bytesused)
86 {
87         /* For decoders set bytesused as per the output picture. */
88         buf->planes[0].bytesused = ctx->dst_fmt.plane_fmt[0].sizeimage;
89         return 0;
90 }
91
92 static void hantro_job_finish(struct hantro_dev *vpu,
93                               struct hantro_ctx *ctx,
94                               unsigned int bytesused,
95                               enum vb2_buffer_state result)
96 {
97         struct vb2_v4l2_buffer *src, *dst;
98         int ret;
99
100         pm_runtime_mark_last_busy(vpu->dev);
101         pm_runtime_put_autosuspend(vpu->dev);
102         clk_bulk_disable(vpu->variant->num_clocks, vpu->clocks);
103
104         src = v4l2_m2m_src_buf_remove(ctx->fh.m2m_ctx);
105         dst = v4l2_m2m_dst_buf_remove(ctx->fh.m2m_ctx);
106
107         if (WARN_ON(!src))
108                 return;
109         if (WARN_ON(!dst))
110                 return;
111
112         src->sequence = ctx->sequence_out++;
113         dst->sequence = ctx->sequence_cap++;
114
115         ret = ctx->buf_finish(ctx, &dst->vb2_buf, bytesused);
116         if (ret)
117                 result = VB2_BUF_STATE_ERROR;
118
119         v4l2_m2m_buf_done(src, result);
120         v4l2_m2m_buf_done(dst, result);
121
122         v4l2_m2m_job_finish(vpu->m2m_dev, ctx->fh.m2m_ctx);
123 }
124
125 void hantro_irq_done(struct hantro_dev *vpu, unsigned int bytesused,
126                      enum vb2_buffer_state result)
127 {
128         struct hantro_ctx *ctx =
129                 v4l2_m2m_get_curr_priv(vpu->m2m_dev);
130
131         /*
132          * If cancel_delayed_work returns false
133          * the timeout expired. The watchdog is running,
134          * and will take care of finishing the job.
135          */
136         if (cancel_delayed_work(&vpu->watchdog_work))
137                 hantro_job_finish(vpu, ctx, bytesused, result);
138 }
139
140 void hantro_watchdog(struct work_struct *work)
141 {
142         struct hantro_dev *vpu;
143         struct hantro_ctx *ctx;
144
145         vpu = container_of(to_delayed_work(work),
146                            struct hantro_dev, watchdog_work);
147         ctx = v4l2_m2m_get_curr_priv(vpu->m2m_dev);
148         if (ctx) {
149                 vpu_err("frame processing timed out!\n");
150                 ctx->codec_ops->reset(ctx);
151                 hantro_job_finish(vpu, ctx, 0, VB2_BUF_STATE_ERROR);
152         }
153 }
154
155 void hantro_start_prepare_run(struct hantro_ctx *ctx)
156 {
157         struct vb2_v4l2_buffer *src_buf;
158
159         src_buf = hantro_get_src_buf(ctx);
160         v4l2_ctrl_request_setup(src_buf->vb2_buf.req_obj.req,
161                                 &ctx->ctrl_handler);
162
163         if (hantro_needs_postproc(ctx, ctx->vpu_dst_fmt))
164                 hantro_postproc_enable(ctx);
165         else
166                 hantro_postproc_disable(ctx);
167 }
168
169 void hantro_end_prepare_run(struct hantro_ctx *ctx)
170 {
171         struct vb2_v4l2_buffer *src_buf;
172
173         src_buf = hantro_get_src_buf(ctx);
174         v4l2_ctrl_request_complete(src_buf->vb2_buf.req_obj.req,
175                                    &ctx->ctrl_handler);
176
177         /* Kick the watchdog. */
178         schedule_delayed_work(&ctx->dev->watchdog_work,
179                               msecs_to_jiffies(2000));
180 }
181
182 static void device_run(void *priv)
183 {
184         struct hantro_ctx *ctx = priv;
185         struct vb2_v4l2_buffer *src, *dst;
186         int ret;
187
188         src = hantro_get_src_buf(ctx);
189         dst = hantro_get_dst_buf(ctx);
190
191         ret = clk_bulk_enable(ctx->dev->variant->num_clocks, ctx->dev->clocks);
192         if (ret)
193                 goto err_cancel_job;
194         ret = pm_runtime_get_sync(ctx->dev->dev);
195         if (ret < 0)
196                 goto err_cancel_job;
197
198         v4l2_m2m_buf_copy_metadata(src, dst, true);
199
200         ctx->codec_ops->run(ctx);
201         return;
202
203 err_cancel_job:
204         hantro_job_finish(ctx->dev, ctx, 0, VB2_BUF_STATE_ERROR);
205 }
206
207 bool hantro_is_encoder_ctx(const struct hantro_ctx *ctx)
208 {
209         return ctx->buf_finish == hantro_enc_buf_finish;
210 }
211
212 static struct v4l2_m2m_ops vpu_m2m_ops = {
213         .device_run = device_run,
214 };
215
216 static int
217 queue_init(void *priv, struct vb2_queue *src_vq, struct vb2_queue *dst_vq)
218 {
219         struct hantro_ctx *ctx = priv;
220         int ret;
221
222         src_vq->type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
223         src_vq->io_modes = VB2_MMAP | VB2_DMABUF;
224         src_vq->drv_priv = ctx;
225         src_vq->ops = &hantro_queue_ops;
226         src_vq->mem_ops = &vb2_dma_contig_memops;
227
228         /*
229          * Driver does mostly sequential access, so sacrifice TLB efficiency
230          * for faster allocation. Also, no CPU access on the source queue,
231          * so no kernel mapping needed.
232          */
233         src_vq->dma_attrs = DMA_ATTR_ALLOC_SINGLE_PAGES |
234                             DMA_ATTR_NO_KERNEL_MAPPING;
235         src_vq->buf_struct_size = sizeof(struct v4l2_m2m_buffer);
236         src_vq->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_COPY;
237         src_vq->lock = &ctx->dev->vpu_mutex;
238         src_vq->dev = ctx->dev->v4l2_dev.dev;
239         src_vq->supports_requests = true;
240
241         ret = vb2_queue_init(src_vq);
242         if (ret)
243                 return ret;
244
245         /*
246          * When encoding, the CAPTURE queue doesn't need dma memory,
247          * as the CPU needs to create the JPEG frames, from the
248          * hardware-produced JPEG payload.
249          *
250          * For the DMA destination buffer, we use a bounce buffer.
251          */
252         if (hantro_is_encoder_ctx(ctx)) {
253                 dst_vq->mem_ops = &vb2_vmalloc_memops;
254         } else {
255                 dst_vq->bidirectional = true;
256                 dst_vq->mem_ops = &vb2_dma_contig_memops;
257                 dst_vq->dma_attrs = DMA_ATTR_ALLOC_SINGLE_PAGES |
258                                     DMA_ATTR_NO_KERNEL_MAPPING;
259         }
260
261         dst_vq->type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
262         dst_vq->io_modes = VB2_MMAP | VB2_DMABUF;
263         dst_vq->drv_priv = ctx;
264         dst_vq->ops = &hantro_queue_ops;
265         dst_vq->buf_struct_size = sizeof(struct v4l2_m2m_buffer);
266         dst_vq->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_COPY;
267         dst_vq->lock = &ctx->dev->vpu_mutex;
268         dst_vq->dev = ctx->dev->v4l2_dev.dev;
269
270         return vb2_queue_init(dst_vq);
271 }
272
273 static int hantro_s_ctrl(struct v4l2_ctrl *ctrl)
274 {
275         struct hantro_ctx *ctx;
276
277         ctx = container_of(ctrl->handler,
278                            struct hantro_ctx, ctrl_handler);
279
280         vpu_debug(1, "s_ctrl: id = %d, val = %d\n", ctrl->id, ctrl->val);
281
282         switch (ctrl->id) {
283         case V4L2_CID_JPEG_COMPRESSION_QUALITY:
284                 ctx->jpeg_quality = ctrl->val;
285                 break;
286         default:
287                 return -EINVAL;
288         }
289
290         return 0;
291 }
292
293 static const struct v4l2_ctrl_ops hantro_ctrl_ops = {
294         .s_ctrl = hantro_s_ctrl,
295 };
296
297 static const struct hantro_ctrl controls[] = {
298         {
299                 .codec = HANTRO_JPEG_ENCODER,
300                 .cfg = {
301                         .id = V4L2_CID_JPEG_COMPRESSION_QUALITY,
302                         .min = 5,
303                         .max = 100,
304                         .step = 1,
305                         .def = 50,
306                         .ops = &hantro_ctrl_ops,
307                 },
308         }, {
309                 .codec = HANTRO_MPEG2_DECODER,
310                 .cfg = {
311                         .id = V4L2_CID_MPEG_VIDEO_MPEG2_SLICE_PARAMS,
312                 },
313         }, {
314                 .codec = HANTRO_MPEG2_DECODER,
315                 .cfg = {
316                         .id = V4L2_CID_MPEG_VIDEO_MPEG2_QUANTIZATION,
317                 },
318         }, {
319                 .codec = HANTRO_VP8_DECODER,
320                 .cfg = {
321                         .id = V4L2_CID_MPEG_VIDEO_VP8_FRAME_HEADER,
322                 },
323         }, {
324                 .codec = HANTRO_H264_DECODER,
325                 .cfg = {
326                         .id = V4L2_CID_MPEG_VIDEO_H264_DECODE_PARAMS,
327                 },
328         }, {
329                 .codec = HANTRO_H264_DECODER,
330                 .cfg = {
331                         .id = V4L2_CID_MPEG_VIDEO_H264_SLICE_PARAMS,
332                 },
333         }, {
334                 .codec = HANTRO_H264_DECODER,
335                 .cfg = {
336                         .id = V4L2_CID_MPEG_VIDEO_H264_SPS,
337                 },
338         }, {
339                 .codec = HANTRO_H264_DECODER,
340                 .cfg = {
341                         .id = V4L2_CID_MPEG_VIDEO_H264_PPS,
342                 },
343         }, {
344                 .codec = HANTRO_H264_DECODER,
345                 .cfg = {
346                         .id = V4L2_CID_MPEG_VIDEO_H264_SCALING_MATRIX,
347                 },
348         }, {
349                 .codec = HANTRO_H264_DECODER,
350                 .cfg = {
351                         .id = V4L2_CID_MPEG_VIDEO_H264_DECODE_MODE,
352                         .min = V4L2_MPEG_VIDEO_H264_DECODE_MODE_FRAME_BASED,
353                         .def = V4L2_MPEG_VIDEO_H264_DECODE_MODE_FRAME_BASED,
354                         .max = V4L2_MPEG_VIDEO_H264_DECODE_MODE_FRAME_BASED,
355                 },
356         }, {
357                 .codec = HANTRO_H264_DECODER,
358                 .cfg = {
359                         .id = V4L2_CID_MPEG_VIDEO_H264_START_CODE,
360                         .min = V4L2_MPEG_VIDEO_H264_START_CODE_ANNEX_B,
361                         .def = V4L2_MPEG_VIDEO_H264_START_CODE_ANNEX_B,
362                         .max = V4L2_MPEG_VIDEO_H264_START_CODE_ANNEX_B,
363                 },
364         }, {
365                 .codec = HANTRO_H264_DECODER,
366                 .cfg = {
367                         .id = V4L2_CID_MPEG_VIDEO_H264_PROFILE,
368                         .min = V4L2_MPEG_VIDEO_H264_PROFILE_BASELINE,
369                         .max = V4L2_MPEG_VIDEO_H264_PROFILE_HIGH,
370                         .menu_skip_mask =
371                         BIT(V4L2_MPEG_VIDEO_H264_PROFILE_EXTENDED),
372                         .def = V4L2_MPEG_VIDEO_H264_PROFILE_MAIN,
373                 }
374         }, {
375         },
376 };
377
378 static int hantro_ctrls_setup(struct hantro_dev *vpu,
379                               struct hantro_ctx *ctx,
380                               int allowed_codecs)
381 {
382         int i, num_ctrls = ARRAY_SIZE(controls);
383
384         v4l2_ctrl_handler_init(&ctx->ctrl_handler, num_ctrls);
385
386         for (i = 0; i < num_ctrls; i++) {
387                 if (!(allowed_codecs & controls[i].codec))
388                         continue;
389
390                 v4l2_ctrl_new_custom(&ctx->ctrl_handler,
391                                      &controls[i].cfg, NULL);
392                 if (ctx->ctrl_handler.error) {
393                         vpu_err("Adding control (%d) failed %d\n",
394                                 controls[i].cfg.id,
395                                 ctx->ctrl_handler.error);
396                         v4l2_ctrl_handler_free(&ctx->ctrl_handler);
397                         return ctx->ctrl_handler.error;
398                 }
399         }
400         return v4l2_ctrl_handler_setup(&ctx->ctrl_handler);
401 }
402
403 /*
404  * V4L2 file operations.
405  */
406
407 static int hantro_open(struct file *filp)
408 {
409         struct hantro_dev *vpu = video_drvdata(filp);
410         struct video_device *vdev = video_devdata(filp);
411         struct hantro_func *func = hantro_vdev_to_func(vdev);
412         struct hantro_ctx *ctx;
413         int allowed_codecs, ret;
414
415         /*
416          * We do not need any extra locking here, because we operate only
417          * on local data here, except reading few fields from dev, which
418          * do not change through device's lifetime (which is guaranteed by
419          * reference on module from open()) and V4L2 internal objects (such
420          * as vdev and ctx->fh), which have proper locking done in respective
421          * helper functions used here.
422          */
423
424         ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
425         if (!ctx)
426                 return -ENOMEM;
427
428         ctx->dev = vpu;
429         if (func->id == MEDIA_ENT_F_PROC_VIDEO_ENCODER) {
430                 allowed_codecs = vpu->variant->codec & HANTRO_ENCODERS;
431                 ctx->buf_finish = hantro_enc_buf_finish;
432         } else if (func->id == MEDIA_ENT_F_PROC_VIDEO_DECODER) {
433                 allowed_codecs = vpu->variant->codec & HANTRO_DECODERS;
434                 ctx->buf_finish = hantro_dec_buf_finish;
435         } else {
436                 ret = -ENODEV;
437                 goto err_ctx_free;
438         }
439
440         ctx->fh.m2m_ctx = v4l2_m2m_ctx_init(vpu->m2m_dev, ctx, queue_init);
441         if (IS_ERR(ctx->fh.m2m_ctx)) {
442                 ret = PTR_ERR(ctx->fh.m2m_ctx);
443                 goto err_ctx_free;
444         }
445
446         v4l2_fh_init(&ctx->fh, vdev);
447         filp->private_data = &ctx->fh;
448         v4l2_fh_add(&ctx->fh);
449
450         hantro_reset_fmts(ctx);
451
452         ret = hantro_ctrls_setup(vpu, ctx, allowed_codecs);
453         if (ret) {
454                 vpu_err("Failed to set up controls\n");
455                 goto err_fh_free;
456         }
457         ctx->fh.ctrl_handler = &ctx->ctrl_handler;
458
459         return 0;
460
461 err_fh_free:
462         v4l2_fh_del(&ctx->fh);
463         v4l2_fh_exit(&ctx->fh);
464 err_ctx_free:
465         kfree(ctx);
466         return ret;
467 }
468
469 static int hantro_release(struct file *filp)
470 {
471         struct hantro_ctx *ctx =
472                 container_of(filp->private_data, struct hantro_ctx, fh);
473
474         /*
475          * No need for extra locking because this was the last reference
476          * to this file.
477          */
478         v4l2_m2m_ctx_release(ctx->fh.m2m_ctx);
479         v4l2_fh_del(&ctx->fh);
480         v4l2_fh_exit(&ctx->fh);
481         v4l2_ctrl_handler_free(&ctx->ctrl_handler);
482         kfree(ctx);
483
484         return 0;
485 }
486
487 static const struct v4l2_file_operations hantro_fops = {
488         .owner = THIS_MODULE,
489         .open = hantro_open,
490         .release = hantro_release,
491         .poll = v4l2_m2m_fop_poll,
492         .unlocked_ioctl = video_ioctl2,
493         .mmap = v4l2_m2m_fop_mmap,
494 };
495
496 static const struct of_device_id of_hantro_match[] = {
497 #ifdef CONFIG_VIDEO_HANTRO_ROCKCHIP
498         { .compatible = "rockchip,rk3399-vpu", .data = &rk3399_vpu_variant, },
499         { .compatible = "rockchip,rk3328-vpu", .data = &rk3328_vpu_variant, },
500         { .compatible = "rockchip,rk3288-vpu", .data = &rk3288_vpu_variant, },
501 #endif
502         { /* sentinel */ }
503 };
504 MODULE_DEVICE_TABLE(of, of_hantro_match);
505
506 static int hantro_register_entity(struct media_device *mdev,
507                                   struct media_entity *entity,
508                                   const char *entity_name,
509                                   struct media_pad *pads, int num_pads,
510                                   int function, struct video_device *vdev)
511 {
512         char *name;
513         int ret;
514
515         entity->obj_type = MEDIA_ENTITY_TYPE_BASE;
516         if (function == MEDIA_ENT_F_IO_V4L) {
517                 entity->info.dev.major = VIDEO_MAJOR;
518                 entity->info.dev.minor = vdev->minor;
519         }
520
521         name = devm_kasprintf(mdev->dev, GFP_KERNEL, "%s-%s", vdev->name,
522                               entity_name);
523         if (!name)
524                 return -ENOMEM;
525
526         entity->name = name;
527         entity->function = function;
528
529         ret = media_entity_pads_init(entity, num_pads, pads);
530         if (ret)
531                 return ret;
532
533         ret = media_device_register_entity(mdev, entity);
534         if (ret)
535                 return ret;
536
537         return 0;
538 }
539
540 static int hantro_attach_func(struct hantro_dev *vpu,
541                               struct hantro_func *func)
542 {
543         struct media_device *mdev = &vpu->mdev;
544         struct media_link *link;
545         int ret;
546
547         /* Create the three encoder entities with their pads */
548         func->source_pad.flags = MEDIA_PAD_FL_SOURCE;
549         ret = hantro_register_entity(mdev, &func->vdev.entity, "source",
550                                      &func->source_pad, 1, MEDIA_ENT_F_IO_V4L,
551                                      &func->vdev);
552         if (ret)
553                 return ret;
554
555         func->proc_pads[0].flags = MEDIA_PAD_FL_SINK;
556         func->proc_pads[1].flags = MEDIA_PAD_FL_SOURCE;
557         ret = hantro_register_entity(mdev, &func->proc, "proc",
558                                      func->proc_pads, 2, func->id,
559                                      &func->vdev);
560         if (ret)
561                 goto err_rel_entity0;
562
563         func->sink_pad.flags = MEDIA_PAD_FL_SINK;
564         ret = hantro_register_entity(mdev, &func->sink, "sink",
565                                      &func->sink_pad, 1, MEDIA_ENT_F_IO_V4L,
566                                      &func->vdev);
567         if (ret)
568                 goto err_rel_entity1;
569
570         /* Connect the three entities */
571         ret = media_create_pad_link(&func->vdev.entity, 0, &func->proc, 0,
572                                     MEDIA_LNK_FL_IMMUTABLE |
573                                     MEDIA_LNK_FL_ENABLED);
574         if (ret)
575                 goto err_rel_entity2;
576
577         ret = media_create_pad_link(&func->proc, 1, &func->sink, 0,
578                                     MEDIA_LNK_FL_IMMUTABLE |
579                                     MEDIA_LNK_FL_ENABLED);
580         if (ret)
581                 goto err_rm_links0;
582
583         /* Create video interface */
584         func->intf_devnode = media_devnode_create(mdev, MEDIA_INTF_T_V4L_VIDEO,
585                                                   0, VIDEO_MAJOR,
586                                                   func->vdev.minor);
587         if (!func->intf_devnode) {
588                 ret = -ENOMEM;
589                 goto err_rm_links1;
590         }
591
592         /* Connect the two DMA engines to the interface */
593         link = media_create_intf_link(&func->vdev.entity,
594                                       &func->intf_devnode->intf,
595                                       MEDIA_LNK_FL_IMMUTABLE |
596                                       MEDIA_LNK_FL_ENABLED);
597         if (!link) {
598                 ret = -ENOMEM;
599                 goto err_rm_devnode;
600         }
601
602         link = media_create_intf_link(&func->sink, &func->intf_devnode->intf,
603                                       MEDIA_LNK_FL_IMMUTABLE |
604                                       MEDIA_LNK_FL_ENABLED);
605         if (!link) {
606                 ret = -ENOMEM;
607                 goto err_rm_devnode;
608         }
609         return 0;
610
611 err_rm_devnode:
612         media_devnode_remove(func->intf_devnode);
613
614 err_rm_links1:
615         media_entity_remove_links(&func->sink);
616
617 err_rm_links0:
618         media_entity_remove_links(&func->proc);
619         media_entity_remove_links(&func->vdev.entity);
620
621 err_rel_entity2:
622         media_device_unregister_entity(&func->sink);
623
624 err_rel_entity1:
625         media_device_unregister_entity(&func->proc);
626
627 err_rel_entity0:
628         media_device_unregister_entity(&func->vdev.entity);
629         return ret;
630 }
631
632 static void hantro_detach_func(struct hantro_func *func)
633 {
634         media_devnode_remove(func->intf_devnode);
635         media_entity_remove_links(&func->sink);
636         media_entity_remove_links(&func->proc);
637         media_entity_remove_links(&func->vdev.entity);
638         media_device_unregister_entity(&func->sink);
639         media_device_unregister_entity(&func->proc);
640         media_device_unregister_entity(&func->vdev.entity);
641 }
642
643 static int hantro_add_func(struct hantro_dev *vpu, unsigned int funcid)
644 {
645         const struct of_device_id *match;
646         struct hantro_func *func;
647         struct video_device *vfd;
648         int ret;
649
650         match = of_match_node(of_hantro_match, vpu->dev->of_node);
651         func = devm_kzalloc(vpu->dev, sizeof(*func), GFP_KERNEL);
652         if (!func) {
653                 v4l2_err(&vpu->v4l2_dev, "Failed to allocate video device\n");
654                 return -ENOMEM;
655         }
656
657         func->id = funcid;
658
659         vfd = &func->vdev;
660         vfd->fops = &hantro_fops;
661         vfd->release = video_device_release_empty;
662         vfd->lock = &vpu->vpu_mutex;
663         vfd->v4l2_dev = &vpu->v4l2_dev;
664         vfd->vfl_dir = VFL_DIR_M2M;
665         vfd->device_caps = V4L2_CAP_STREAMING | V4L2_CAP_VIDEO_M2M_MPLANE;
666         vfd->ioctl_ops = &hantro_ioctl_ops;
667         snprintf(vfd->name, sizeof(vfd->name), "%s-%s", match->compatible,
668                  funcid == MEDIA_ENT_F_PROC_VIDEO_ENCODER ? "enc" : "dec");
669
670         if (funcid == MEDIA_ENT_F_PROC_VIDEO_ENCODER)
671                 vpu->encoder = func;
672         else
673                 vpu->decoder = func;
674
675         video_set_drvdata(vfd, vpu);
676
677         ret = video_register_device(vfd, VFL_TYPE_GRABBER, -1);
678         if (ret) {
679                 v4l2_err(&vpu->v4l2_dev, "Failed to register video device\n");
680                 return ret;
681         }
682
683         ret = hantro_attach_func(vpu, func);
684         if (ret) {
685                 v4l2_err(&vpu->v4l2_dev,
686                          "Failed to attach functionality to the media device\n");
687                 goto err_unreg_dev;
688         }
689
690         v4l2_info(&vpu->v4l2_dev, "registered %s as /dev/video%d\n", vfd->name,
691                   vfd->num);
692
693         return 0;
694
695 err_unreg_dev:
696         video_unregister_device(vfd);
697         return ret;
698 }
699
700 static int hantro_add_enc_func(struct hantro_dev *vpu)
701 {
702         if (!vpu->variant->enc_fmts)
703                 return 0;
704
705         return hantro_add_func(vpu, MEDIA_ENT_F_PROC_VIDEO_ENCODER);
706 }
707
708 static int hantro_add_dec_func(struct hantro_dev *vpu)
709 {
710         if (!vpu->variant->dec_fmts)
711                 return 0;
712
713         return hantro_add_func(vpu, MEDIA_ENT_F_PROC_VIDEO_DECODER);
714 }
715
716 static void hantro_remove_func(struct hantro_dev *vpu,
717                                unsigned int funcid)
718 {
719         struct hantro_func *func;
720
721         if (funcid == MEDIA_ENT_F_PROC_VIDEO_ENCODER)
722                 func = vpu->encoder;
723         else
724                 func = vpu->decoder;
725
726         if (!func)
727                 return;
728
729         hantro_detach_func(func);
730         video_unregister_device(&func->vdev);
731 }
732
733 static void hantro_remove_enc_func(struct hantro_dev *vpu)
734 {
735         hantro_remove_func(vpu, MEDIA_ENT_F_PROC_VIDEO_ENCODER);
736 }
737
738 static void hantro_remove_dec_func(struct hantro_dev *vpu)
739 {
740         hantro_remove_func(vpu, MEDIA_ENT_F_PROC_VIDEO_DECODER);
741 }
742
743 static const struct media_device_ops hantro_m2m_media_ops = {
744         .req_validate = vb2_request_validate,
745         .req_queue = v4l2_m2m_request_queue,
746 };
747
748 static int hantro_probe(struct platform_device *pdev)
749 {
750         const struct of_device_id *match;
751         struct hantro_dev *vpu;
752         struct resource *res;
753         int num_bases;
754         int i, ret;
755
756         vpu = devm_kzalloc(&pdev->dev, sizeof(*vpu), GFP_KERNEL);
757         if (!vpu)
758                 return -ENOMEM;
759
760         vpu->dev = &pdev->dev;
761         vpu->pdev = pdev;
762         mutex_init(&vpu->vpu_mutex);
763         spin_lock_init(&vpu->irqlock);
764
765         match = of_match_node(of_hantro_match, pdev->dev.of_node);
766         vpu->variant = match->data;
767
768         INIT_DELAYED_WORK(&vpu->watchdog_work, hantro_watchdog);
769
770         vpu->clocks = devm_kcalloc(&pdev->dev, vpu->variant->num_clocks,
771                                    sizeof(*vpu->clocks), GFP_KERNEL);
772         if (!vpu->clocks)
773                 return -ENOMEM;
774
775         for (i = 0; i < vpu->variant->num_clocks; i++)
776                 vpu->clocks[i].id = vpu->variant->clk_names[i];
777         ret = devm_clk_bulk_get(&pdev->dev, vpu->variant->num_clocks,
778                                 vpu->clocks);
779         if (ret)
780                 return ret;
781
782         num_bases = vpu->variant->num_regs ?: 1;
783         vpu->reg_bases = devm_kcalloc(&pdev->dev, num_bases,
784                                       sizeof(*vpu->reg_bases), GFP_KERNEL);
785         if (!vpu->reg_bases)
786                 return -ENOMEM;
787
788         for (i = 0; i < num_bases; i++) {
789                 res = vpu->variant->reg_names ?
790                       platform_get_resource_byname(vpu->pdev, IORESOURCE_MEM,
791                                                    vpu->variant->reg_names[i]) :
792                       platform_get_resource(vpu->pdev, IORESOURCE_MEM, 0);
793                 vpu->reg_bases[i] = devm_ioremap_resource(vpu->dev, res);
794                 if (IS_ERR(vpu->reg_bases[i]))
795                         return PTR_ERR(vpu->reg_bases[i]);
796         }
797         vpu->enc_base = vpu->reg_bases[0] + vpu->variant->enc_offset;
798         vpu->dec_base = vpu->reg_bases[0] + vpu->variant->dec_offset;
799
800         ret = dma_set_coherent_mask(vpu->dev, DMA_BIT_MASK(32));
801         if (ret) {
802                 dev_err(vpu->dev, "Could not set DMA coherent mask.\n");
803                 return ret;
804         }
805         vb2_dma_contig_set_max_seg_size(&pdev->dev, DMA_BIT_MASK(32));
806
807         for (i = 0; i < vpu->variant->num_irqs; i++) {
808                 const char *irq_name = vpu->variant->irqs[i].name;
809                 int irq;
810
811                 if (!vpu->variant->irqs[i].handler)
812                         continue;
813
814                 irq = platform_get_irq_byname(vpu->pdev, irq_name);
815                 if (irq <= 0)
816                         return -ENXIO;
817
818                 ret = devm_request_irq(vpu->dev, irq,
819                                        vpu->variant->irqs[i].handler, 0,
820                                        dev_name(vpu->dev), vpu);
821                 if (ret) {
822                         dev_err(vpu->dev, "Could not request %s IRQ.\n",
823                                 irq_name);
824                         return ret;
825                 }
826         }
827
828         ret = vpu->variant->init(vpu);
829         if (ret) {
830                 dev_err(&pdev->dev, "Failed to init VPU hardware\n");
831                 return ret;
832         }
833
834         pm_runtime_set_autosuspend_delay(vpu->dev, 100);
835         pm_runtime_use_autosuspend(vpu->dev);
836         pm_runtime_enable(vpu->dev);
837
838         ret = clk_bulk_prepare(vpu->variant->num_clocks, vpu->clocks);
839         if (ret) {
840                 dev_err(&pdev->dev, "Failed to prepare clocks\n");
841                 return ret;
842         }
843
844         ret = v4l2_device_register(&pdev->dev, &vpu->v4l2_dev);
845         if (ret) {
846                 dev_err(&pdev->dev, "Failed to register v4l2 device\n");
847                 goto err_clk_unprepare;
848         }
849         platform_set_drvdata(pdev, vpu);
850
851         vpu->m2m_dev = v4l2_m2m_init(&vpu_m2m_ops);
852         if (IS_ERR(vpu->m2m_dev)) {
853                 v4l2_err(&vpu->v4l2_dev, "Failed to init mem2mem device\n");
854                 ret = PTR_ERR(vpu->m2m_dev);
855                 goto err_v4l2_unreg;
856         }
857
858         vpu->mdev.dev = vpu->dev;
859         strscpy(vpu->mdev.model, DRIVER_NAME, sizeof(vpu->mdev.model));
860         strscpy(vpu->mdev.bus_info, "platform: " DRIVER_NAME,
861                 sizeof(vpu->mdev.model));
862         media_device_init(&vpu->mdev);
863         vpu->mdev.ops = &hantro_m2m_media_ops;
864         vpu->v4l2_dev.mdev = &vpu->mdev;
865
866         ret = hantro_add_enc_func(vpu);
867         if (ret) {
868                 dev_err(&pdev->dev, "Failed to register encoder\n");
869                 goto err_m2m_rel;
870         }
871
872         ret = hantro_add_dec_func(vpu);
873         if (ret) {
874                 dev_err(&pdev->dev, "Failed to register decoder\n");
875                 goto err_rm_enc_func;
876         }
877
878         ret = media_device_register(&vpu->mdev);
879         if (ret) {
880                 v4l2_err(&vpu->v4l2_dev, "Failed to register mem2mem media device\n");
881                 goto err_rm_dec_func;
882         }
883
884         return 0;
885
886 err_rm_dec_func:
887         hantro_remove_dec_func(vpu);
888 err_rm_enc_func:
889         hantro_remove_enc_func(vpu);
890 err_m2m_rel:
891         media_device_cleanup(&vpu->mdev);
892         v4l2_m2m_release(vpu->m2m_dev);
893 err_v4l2_unreg:
894         v4l2_device_unregister(&vpu->v4l2_dev);
895 err_clk_unprepare:
896         clk_bulk_unprepare(vpu->variant->num_clocks, vpu->clocks);
897         pm_runtime_dont_use_autosuspend(vpu->dev);
898         pm_runtime_disable(vpu->dev);
899         return ret;
900 }
901
902 static int hantro_remove(struct platform_device *pdev)
903 {
904         struct hantro_dev *vpu = platform_get_drvdata(pdev);
905
906         v4l2_info(&vpu->v4l2_dev, "Removing %s\n", pdev->name);
907
908         media_device_unregister(&vpu->mdev);
909         hantro_remove_dec_func(vpu);
910         hantro_remove_enc_func(vpu);
911         media_device_cleanup(&vpu->mdev);
912         v4l2_m2m_release(vpu->m2m_dev);
913         v4l2_device_unregister(&vpu->v4l2_dev);
914         clk_bulk_unprepare(vpu->variant->num_clocks, vpu->clocks);
915         pm_runtime_dont_use_autosuspend(vpu->dev);
916         pm_runtime_disable(vpu->dev);
917         return 0;
918 }
919
920 #ifdef CONFIG_PM
921 static int hantro_runtime_resume(struct device *dev)
922 {
923         struct hantro_dev *vpu = dev_get_drvdata(dev);
924
925         if (vpu->variant->runtime_resume)
926                 return vpu->variant->runtime_resume(vpu);
927
928         return 0;
929 }
930 #endif
931
932 static const struct dev_pm_ops hantro_pm_ops = {
933         SET_SYSTEM_SLEEP_PM_OPS(pm_runtime_force_suspend,
934                                 pm_runtime_force_resume)
935         SET_RUNTIME_PM_OPS(NULL, hantro_runtime_resume, NULL)
936 };
937
938 static struct platform_driver hantro_driver = {
939         .probe = hantro_probe,
940         .remove = hantro_remove,
941         .driver = {
942                    .name = DRIVER_NAME,
943                    .of_match_table = of_match_ptr(of_hantro_match),
944                    .pm = &hantro_pm_ops,
945         },
946 };
947 module_platform_driver(hantro_driver);
948
949 MODULE_LICENSE("GPL v2");
950 MODULE_AUTHOR("Alpha Lin <Alpha.Lin@Rock-Chips.com>");
951 MODULE_AUTHOR("Tomasz Figa <tfiga@chromium.org>");
952 MODULE_AUTHOR("Ezequiel Garcia <ezequiel@collabora.com>");
953 MODULE_DESCRIPTION("Hantro VPU codec driver");