python_code
stringlengths
0
1.8M
repo_name
stringclasses
7 values
file_path
stringlengths
5
99
// SPDX-License-Identifier: GPL-2.0+ /* * IMI RDACM20 GMSL Camera Driver * * Copyright (C) 2017-2020 Jacopo Mondi * Copyright (C) 2017-2020 Kieran Bingham * Copyright (C) 2017-2019 Laurent Pinchart * Copyright (C) 2017-2019 Niklas Söderlund * Copyright (C) 2016 Renesas Electronics Corporation * Copyright (C) 2015 Cogent Embedded, Inc. */ /* * The camera is made of an Omnivision OV10635 sensor connected to a Maxim * MAX9271 GMSL serializer. */ #include <linux/delay.h> #include <linux/fwnode.h> #include <linux/init.h> #include <linux/i2c.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/videodev2.h> #include <media/v4l2-async.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-subdev.h> #include "max9271.h" #define OV10635_I2C_ADDRESS 0x30 #define OV10635_SOFTWARE_RESET 0x0103 #define OV10635_PID 0x300a #define OV10635_VER 0x300b #define OV10635_SC_CMMN_SCCB_ID 0x300c #define OV10635_SC_CMMN_SCCB_ID_SELECT BIT(0) #define OV10635_VERSION 0xa635 #define OV10635_WIDTH 1280 #define OV10635_HEIGHT 800 /* VTS = PCLK / FPS / HTS / 2 (= 88MHz / 1572 / 30 / 2) */ #define OV10635_HTS 1572 /* FPS = 29,9998 */ #define OV10635_VTS 933 /* * As the drivers supports a single MEDIA_BUS_FMT_UYVY8_1X16 format we * can harcode the pixel rate. * * PCLK is fed through the system clock, programmed @88MHz. * MEDIA_BUS_FMT_UYVY8_1X16 format = 2 samples per pixel. * * Pixelrate = PCLK / 2 * FPS = (OV10635_VTS * OV10635_HTS) / PixelRate * = 29,9998 */ #define OV10635_PIXEL_RATE (44000000) static const struct ov10635_reg { u16 reg; u8 val; } ov10635_regs_wizard[] = { { 0x301b, 0xff }, { 0x301c, 0xff }, { 0x301a, 0xff }, { 0x3011, 0x42 }, { 0x6900, 0x0c }, { 0x6901, 0x19 }, { 0x3503, 0x10 }, { 0x3025, 0x03 }, { 0x3003, 0x16 }, { 0x3004, 0x30 }, { 0x3005, 0x40 }, { 0x3006, 0x91 }, { 0x3600, 0x74 }, { 0x3601, 0x2b }, { 0x3612, 0x00 }, { 0x3611, 0x67 }, { 0x3633, 0xca }, { 0x3602, 0xaf }, { 0x3603, 0x04 }, { 0x3630, 0x28 }, { 0x3631, 0x16 }, { 0x3714, 0x10 }, { 0x371d, 0x01 }, { 0x4300, 0x3a }, { 0x3007, 0x01 }, { 0x3024, 0x03 }, { 0x3020, 0x0a }, { 0x3702, 0x0d }, { 0x3703, 0x20 }, { 0x3704, 0x15 }, { 0x3709, 0xa8 }, { 0x370c, 0xc7 }, { 0x370d, 0x80 }, { 0x3712, 0x00 }, { 0x3713, 0x20 }, { 0x3715, 0x04 }, { 0x381d, 0x40 }, { 0x381c, 0x00 }, { 0x3822, 0x50 }, { 0x3824, 0x10 }, { 0x3815, 0x8c }, { 0x3804, 0x05 }, { 0x3805, 0x1f }, { 0x3800, 0x00 }, { 0x3801, 0x00 }, { 0x3806, 0x03 }, { 0x3807, 0x28 }, { 0x3802, 0x00 }, { 0x3803, 0x07 }, { 0x3808, 0x05 }, { 0x3809, 0x00 }, { 0x380a, 0x03 }, { 0x380b, 0x20 }, { 0x380c, OV10635_HTS >> 8 }, { 0x380d, OV10635_HTS & 0xff }, { 0x380e, OV10635_VTS >> 8 }, { 0x380f, OV10635_VTS & 0xff }, { 0x3813, 0x02 }, { 0x3811, 0x08 }, { 0x381f, 0x0c }, { 0x3819, 0x04 }, { 0x3804, 0x01 }, { 0x3805, 0x00 }, { 0x3828, 0x03 }, { 0x3829, 0x10 }, { 0x382a, 0x10 }, { 0x3621, 0x63 }, { 0x5005, 0x08 }, { 0x56d5, 0x00 }, { 0x56d6, 0x80 }, { 0x56d7, 0x00 }, { 0x56d8, 0x00 }, { 0x56d9, 0x00 }, { 0x56da, 0x80 }, { 0x56db, 0x00 }, { 0x56dc, 0x00 }, { 0x56e8, 0x00 }, { 0x56e9, 0x7f }, { 0x56ea, 0x00 }, { 0x56eb, 0x7f }, { 0x5100, 0x00 }, { 0x5101, 0x80 }, { 0x5102, 0x00 }, { 0x5103, 0x80 }, { 0x5104, 0x00 }, { 0x5105, 0x80 }, { 0x5106, 0x00 }, { 0x5107, 0x80 }, { 0x5108, 0x00 }, { 0x5109, 0x00 }, { 0x510a, 0x00 }, { 0x510b, 0x00 }, { 0x510c, 0x00 }, { 0x510d, 0x00 }, { 0x510e, 0x00 }, { 0x510f, 0x00 }, { 0x5110, 0x00 }, { 0x5111, 0x80 }, { 0x5112, 0x00 }, { 0x5113, 0x80 }, { 0x5114, 0x00 }, { 0x5115, 0x80 }, { 0x5116, 0x00 }, { 0x5117, 0x80 }, { 0x5118, 0x00 }, { 0x5119, 0x00 }, { 0x511a, 0x00 }, { 0x511b, 0x00 }, { 0x511c, 0x00 }, { 0x511d, 0x00 }, { 0x511e, 0x00 }, { 0x511f, 0x00 }, { 0x56d0, 0x00 }, { 0x5006, 0x04 }, { 0x5608, 0x05 }, { 0x52d7, 0x06 }, { 0x528d, 0x08 }, { 0x5293, 0x12 }, { 0x52d3, 0x12 }, { 0x5288, 0x06 }, { 0x5289, 0x20 }, { 0x52c8, 0x06 }, { 0x52c9, 0x20 }, { 0x52cd, 0x04 }, { 0x5381, 0x00 }, { 0x5382, 0xff }, { 0x5589, 0x76 }, { 0x558a, 0x47 }, { 0x558b, 0xef }, { 0x558c, 0xc9 }, { 0x558d, 0x49 }, { 0x558e, 0x30 }, { 0x558f, 0x67 }, { 0x5590, 0x3f }, { 0x5591, 0xf0 }, { 0x5592, 0x10 }, { 0x55a2, 0x6d }, { 0x55a3, 0x55 }, { 0x55a4, 0xc3 }, { 0x55a5, 0xb5 }, { 0x55a6, 0x43 }, { 0x55a7, 0x38 }, { 0x55a8, 0x5f }, { 0x55a9, 0x4b }, { 0x55aa, 0xf0 }, { 0x55ab, 0x10 }, { 0x5581, 0x52 }, { 0x5300, 0x01 }, { 0x5301, 0x00 }, { 0x5302, 0x00 }, { 0x5303, 0x0e }, { 0x5304, 0x00 }, { 0x5305, 0x0e }, { 0x5306, 0x00 }, { 0x5307, 0x36 }, { 0x5308, 0x00 }, { 0x5309, 0xd9 }, { 0x530a, 0x00 }, { 0x530b, 0x0f }, { 0x530c, 0x00 }, { 0x530d, 0x2c }, { 0x530e, 0x00 }, { 0x530f, 0x59 }, { 0x5310, 0x00 }, { 0x5311, 0x7b }, { 0x5312, 0x00 }, { 0x5313, 0x22 }, { 0x5314, 0x00 }, { 0x5315, 0xd5 }, { 0x5316, 0x00 }, { 0x5317, 0x13 }, { 0x5318, 0x00 }, { 0x5319, 0x18 }, { 0x531a, 0x00 }, { 0x531b, 0x26 }, { 0x531c, 0x00 }, { 0x531d, 0xdc }, { 0x531e, 0x00 }, { 0x531f, 0x02 }, { 0x5320, 0x00 }, { 0x5321, 0x24 }, { 0x5322, 0x00 }, { 0x5323, 0x56 }, { 0x5324, 0x00 }, { 0x5325, 0x85 }, { 0x5326, 0x00 }, { 0x5327, 0x20 }, { 0x5609, 0x01 }, { 0x560a, 0x40 }, { 0x560b, 0x01 }, { 0x560c, 0x40 }, { 0x560d, 0x00 }, { 0x560e, 0xfa }, { 0x560f, 0x00 }, { 0x5610, 0xfa }, { 0x5611, 0x02 }, { 0x5612, 0x80 }, { 0x5613, 0x02 }, { 0x5614, 0x80 }, { 0x5615, 0x01 }, { 0x5616, 0x2c }, { 0x5617, 0x01 }, { 0x5618, 0x2c }, { 0x563b, 0x01 }, { 0x563c, 0x01 }, { 0x563d, 0x01 }, { 0x563e, 0x01 }, { 0x563f, 0x03 }, { 0x5640, 0x03 }, { 0x5641, 0x03 }, { 0x5642, 0x05 }, { 0x5643, 0x09 }, { 0x5644, 0x05 }, { 0x5645, 0x05 }, { 0x5646, 0x05 }, { 0x5647, 0x05 }, { 0x5651, 0x00 }, { 0x5652, 0x80 }, { 0x521a, 0x01 }, { 0x521b, 0x03 }, { 0x521c, 0x06 }, { 0x521d, 0x0a }, { 0x521e, 0x0e }, { 0x521f, 0x12 }, { 0x5220, 0x16 }, { 0x5223, 0x02 }, { 0x5225, 0x04 }, { 0x5227, 0x08 }, { 0x5229, 0x0c }, { 0x522b, 0x12 }, { 0x522d, 0x18 }, { 0x522f, 0x1e }, { 0x5241, 0x04 }, { 0x5242, 0x01 }, { 0x5243, 0x03 }, { 0x5244, 0x06 }, { 0x5245, 0x0a }, { 0x5246, 0x0e }, { 0x5247, 0x12 }, { 0x5248, 0x16 }, { 0x524a, 0x03 }, { 0x524c, 0x04 }, { 0x524e, 0x08 }, { 0x5250, 0x0c }, { 0x5252, 0x12 }, { 0x5254, 0x18 }, { 0x5256, 0x1e }, /* fifo_line_length = 2*hts */ { 0x4606, (2 * OV10635_HTS) >> 8 }, { 0x4607, (2 * OV10635_HTS) & 0xff }, /* fifo_hsync_start = 2*(hts - xres) */ { 0x460a, (2 * (OV10635_HTS - OV10635_WIDTH)) >> 8 }, { 0x460b, (2 * (OV10635_HTS - OV10635_WIDTH)) & 0xff }, { 0x460c, 0x00 }, { 0x4620, 0x0e }, /* BT601: 0x08 is also acceptable as HS/VS mode */ { 0x4700, 0x04 }, { 0x4701, 0x00 }, { 0x4702, 0x01 }, { 0x4004, 0x04 }, { 0x4005, 0x18 }, { 0x4001, 0x06 }, { 0x4050, 0x22 }, { 0x4051, 0x24 }, { 0x4052, 0x02 }, { 0x4057, 0x9c }, { 0x405a, 0x00 }, { 0x4202, 0x02 }, { 0x3023, 0x10 }, { 0x0100, 0x01 }, { 0x0100, 0x01 }, { 0x6f10, 0x07 }, { 0x6f11, 0x82 }, { 0x6f12, 0x04 }, { 0x6f13, 0x00 }, { 0xd000, 0x19 }, { 0xd001, 0xa0 }, { 0xd002, 0x00 }, { 0xd003, 0x01 }, { 0xd004, 0xa9 }, { 0xd005, 0xad }, { 0xd006, 0x10 }, { 0xd007, 0x40 }, { 0xd008, 0x44 }, { 0xd009, 0x00 }, { 0xd00a, 0x68 }, { 0xd00b, 0x00 }, { 0xd00c, 0x15 }, { 0xd00d, 0x00 }, { 0xd00e, 0x00 }, { 0xd00f, 0x00 }, { 0xd040, 0x9c }, { 0xd041, 0x21 }, { 0xd042, 0xff }, { 0xd043, 0xf8 }, { 0xd044, 0xd4 }, { 0xd045, 0x01 }, { 0xd046, 0x48 }, { 0xd047, 0x00 }, { 0xd048, 0xd4 }, { 0xd049, 0x01 }, { 0xd04a, 0x50 }, { 0xd04b, 0x04 }, { 0xd04c, 0x18 }, { 0xd04d, 0x60 }, { 0xd04e, 0x00 }, { 0xd04f, 0x01 }, { 0xd050, 0xa8 }, { 0xd051, 0x63 }, { 0xd052, 0x02 }, { 0xd053, 0xa4 }, { 0xd054, 0x85 }, { 0xd055, 0x43 }, { 0xd056, 0x00 }, { 0xd057, 0x00 }, { 0xd058, 0x18 }, { 0xd059, 0x60 }, { 0xd05a, 0x00 }, { 0xd05b, 0x01 }, { 0xd05c, 0xa8 }, { 0xd05d, 0x63 }, { 0xd05e, 0x03 }, { 0xd05f, 0xf0 }, { 0xd060, 0x98 }, { 0xd061, 0xa3 }, { 0xd062, 0x00 }, { 0xd063, 0x00 }, { 0xd064, 0x8c }, { 0xd065, 0x6a }, { 0xd066, 0x00 }, { 0xd067, 0x6e }, { 0xd068, 0xe5 }, { 0xd069, 0x85 }, { 0xd06a, 0x18 }, { 0xd06b, 0x00 }, { 0xd06c, 0x10 }, { 0xd06d, 0x00 }, { 0xd06e, 0x00 }, { 0xd06f, 0x10 }, { 0xd070, 0x9c }, { 0xd071, 0x80 }, { 0xd072, 0x00 }, { 0xd073, 0x03 }, { 0xd074, 0x18 }, { 0xd075, 0x60 }, { 0xd076, 0x00 }, { 0xd077, 0x01 }, { 0xd078, 0xa8 }, { 0xd079, 0x63 }, { 0xd07a, 0x07 }, { 0xd07b, 0x80 }, { 0xd07c, 0x07 }, { 0xd07d, 0xff }, { 0xd07e, 0xf9 }, { 0xd07f, 0x03 }, { 0xd080, 0x8c }, { 0xd081, 0x63 }, { 0xd082, 0x00 }, { 0xd083, 0x00 }, { 0xd084, 0xa5 }, { 0xd085, 0x6b }, { 0xd086, 0x00 }, { 0xd087, 0xff }, { 0xd088, 0x18 }, { 0xd089, 0x80 }, { 0xd08a, 0x00 }, { 0xd08b, 0x01 }, { 0xd08c, 0xa8 }, { 0xd08d, 0x84 }, { 0xd08e, 0x01 }, { 0xd08f, 0x04 }, { 0xd090, 0xe1 }, { 0xd091, 0x6b }, { 0xd092, 0x58 }, { 0xd093, 0x00 }, { 0xd094, 0x94 }, { 0xd095, 0x6a }, { 0xd096, 0x00 }, { 0xd097, 0x70 }, { 0xd098, 0xe1 }, { 0xd099, 0x6b }, { 0xd09a, 0x20 }, { 0xd09b, 0x00 }, { 0xd09c, 0x95 }, { 0xd09d, 0x6b }, { 0xd09e, 0x00 }, { 0xd09f, 0x00 }, { 0xd0a0, 0xe4 }, { 0xd0a1, 0x8b }, { 0xd0a2, 0x18 }, { 0xd0a3, 0x00 }, { 0xd0a4, 0x0c }, { 0xd0a5, 0x00 }, { 0xd0a6, 0x00 }, { 0xd0a7, 0x23 }, { 0xd0a8, 0x15 }, { 0xd0a9, 0x00 }, { 0xd0aa, 0x00 }, { 0xd0ab, 0x00 }, { 0xd0ac, 0x18 }, { 0xd0ad, 0x60 }, { 0xd0ae, 0x80 }, { 0xd0af, 0x06 }, { 0xd0b0, 0xa8 }, { 0xd0b1, 0x83 }, { 0xd0b2, 0x40 }, { 0xd0b3, 0x08 }, { 0xd0b4, 0xa8 }, { 0xd0b5, 0xe3 }, { 0xd0b6, 0x38 }, { 0xd0b7, 0x2a }, { 0xd0b8, 0xa8 }, { 0xd0b9, 0xc3 }, { 0xd0ba, 0x40 }, { 0xd0bb, 0x09 }, { 0xd0bc, 0xa8 }, { 0xd0bd, 0xa3 }, { 0xd0be, 0x38 }, { 0xd0bf, 0x29 }, { 0xd0c0, 0x8c }, { 0xd0c1, 0x65 }, { 0xd0c2, 0x00 }, { 0xd0c3, 0x00 }, { 0xd0c4, 0xd8 }, { 0xd0c5, 0x04 }, { 0xd0c6, 0x18 }, { 0xd0c7, 0x00 }, { 0xd0c8, 0x8c }, { 0xd0c9, 0x67 }, { 0xd0ca, 0x00 }, { 0xd0cb, 0x00 }, { 0xd0cc, 0xd8 }, { 0xd0cd, 0x06 }, { 0xd0ce, 0x18 }, { 0xd0cf, 0x00 }, { 0xd0d0, 0x18 }, { 0xd0d1, 0x60 }, { 0xd0d2, 0x80 }, { 0xd0d3, 0x06 }, { 0xd0d4, 0xa8 }, { 0xd0d5, 0xe3 }, { 0xd0d6, 0x67 }, { 0xd0d7, 0x02 }, { 0xd0d8, 0xa9 }, { 0xd0d9, 0x03 }, { 0xd0da, 0x67 }, { 0xd0db, 0x03 }, { 0xd0dc, 0xa8 }, { 0xd0dd, 0xc3 }, { 0xd0de, 0x3d }, { 0xd0df, 0x05 }, { 0xd0e0, 0x8c }, { 0xd0e1, 0x66 }, { 0xd0e2, 0x00 }, { 0xd0e3, 0x00 }, { 0xd0e4, 0xb8 }, { 0xd0e5, 0x63 }, { 0xd0e6, 0x00 }, { 0xd0e7, 0x18 }, { 0xd0e8, 0xb8 }, { 0xd0e9, 0x63 }, { 0xd0ea, 0x00 }, { 0xd0eb, 0x98 }, { 0xd0ec, 0xbc }, { 0xd0ed, 0x03 }, { 0xd0ee, 0x00 }, { 0xd0ef, 0x00 }, { 0xd0f0, 0x10 }, { 0xd0f1, 0x00 }, { 0xd0f2, 0x00 }, { 0xd0f3, 0x16 }, { 0xd0f4, 0xb8 }, { 0xd0f5, 0x83 }, { 0xd0f6, 0x00 }, { 0xd0f7, 0x19 }, { 0xd0f8, 0x8c }, { 0xd0f9, 0x67 }, { 0xd0fa, 0x00 }, { 0xd0fb, 0x00 }, { 0xd0fc, 0xb8 }, { 0xd0fd, 0xa4 }, { 0xd0fe, 0x00 }, { 0xd0ff, 0x98 }, { 0xd100, 0xb8 }, { 0xd101, 0x83 }, { 0xd102, 0x00 }, { 0xd103, 0x08 }, { 0xd104, 0x8c }, { 0xd105, 0x68 }, { 0xd106, 0x00 }, { 0xd107, 0x00 }, { 0xd108, 0xe0 }, { 0xd109, 0x63 }, { 0xd10a, 0x20 }, { 0xd10b, 0x04 }, { 0xd10c, 0xe0 }, { 0xd10d, 0x65 }, { 0xd10e, 0x18 }, { 0xd10f, 0x00 }, { 0xd110, 0xa4 }, { 0xd111, 0x83 }, { 0xd112, 0xff }, { 0xd113, 0xff }, { 0xd114, 0xb8 }, { 0xd115, 0x64 }, { 0xd116, 0x00 }, { 0xd117, 0x48 }, { 0xd118, 0xd8 }, { 0xd119, 0x07 }, { 0xd11a, 0x18 }, { 0xd11b, 0x00 }, { 0xd11c, 0xd8 }, { 0xd11d, 0x08 }, { 0xd11e, 0x20 }, { 0xd11f, 0x00 }, { 0xd120, 0x9c }, { 0xd121, 0x60 }, { 0xd122, 0x00 }, { 0xd123, 0x00 }, { 0xd124, 0xd8 }, { 0xd125, 0x06 }, { 0xd126, 0x18 }, { 0xd127, 0x00 }, { 0xd128, 0x00 }, { 0xd129, 0x00 }, { 0xd12a, 0x00 }, { 0xd12b, 0x08 }, { 0xd12c, 0x15 }, { 0xd12d, 0x00 }, { 0xd12e, 0x00 }, { 0xd12f, 0x00 }, { 0xd130, 0x8c }, { 0xd131, 0x6a }, { 0xd132, 0x00 }, { 0xd133, 0x76 }, { 0xd134, 0xbc }, { 0xd135, 0x23 }, { 0xd136, 0x00 }, { 0xd137, 0x00 }, { 0xd138, 0x13 }, { 0xd139, 0xff }, { 0xd13a, 0xff }, { 0xd13b, 0xe6 }, { 0xd13c, 0x18 }, { 0xd13d, 0x60 }, { 0xd13e, 0x80 }, { 0xd13f, 0x06 }, { 0xd140, 0x03 }, { 0xd141, 0xff }, { 0xd142, 0xff }, { 0xd143, 0xdd }, { 0xd144, 0xa8 }, { 0xd145, 0x83 }, { 0xd146, 0x40 }, { 0xd147, 0x08 }, { 0xd148, 0x85 }, { 0xd149, 0x21 }, { 0xd14a, 0x00 }, { 0xd14b, 0x00 }, { 0xd14c, 0x85 }, { 0xd14d, 0x41 }, { 0xd14e, 0x00 }, { 0xd14f, 0x04 }, { 0xd150, 0x44 }, { 0xd151, 0x00 }, { 0xd152, 0x48 }, { 0xd153, 0x00 }, { 0xd154, 0x9c }, { 0xd155, 0x21 }, { 0xd156, 0x00 }, { 0xd157, 0x08 }, { 0x6f0e, 0x03 }, { 0x6f0f, 0x00 }, { 0x460e, 0x08 }, { 0x460f, 0x01 }, { 0x4610, 0x00 }, { 0x4611, 0x01 }, { 0x4612, 0x00 }, { 0x4613, 0x01 }, /* 8 bits */ { 0x4605, 0x08 }, /* Swap data bits order [9:0] -> [0:9] */ { 0x4709, 0x10 }, { 0x4608, 0x00 }, { 0x4609, 0x08 }, { 0x6804, 0x00 }, { 0x6805, 0x06 }, { 0x6806, 0x00 }, { 0x5120, 0x00 }, { 0x3510, 0x00 }, { 0x3504, 0x00 }, { 0x6800, 0x00 }, { 0x6f0d, 0x01 }, /* PCLK falling edge */ { 0x4708, 0x01 }, { 0x5000, 0xff }, { 0x5001, 0xbf }, { 0x5002, 0x7e }, { 0x503d, 0x00 }, { 0xc450, 0x01 }, { 0xc452, 0x04 }, { 0xc453, 0x00 }, { 0xc454, 0x00 }, { 0xc455, 0x01 }, { 0xc456, 0x01 }, { 0xc457, 0x00 }, { 0xc458, 0x00 }, { 0xc459, 0x00 }, { 0xc45b, 0x00 }, { 0xc45c, 0x01 }, { 0xc45d, 0x00 }, { 0xc45e, 0x00 }, { 0xc45f, 0x00 }, { 0xc460, 0x00 }, { 0xc461, 0x01 }, { 0xc462, 0x01 }, { 0xc464, 0x03 }, { 0xc465, 0x00 }, { 0xc466, 0x8a }, { 0xc467, 0x00 }, { 0xc468, 0x86 }, { 0xc469, 0x00 }, { 0xc46a, 0x40 }, { 0xc46b, 0x50 }, { 0xc46c, 0x30 }, { 0xc46d, 0x28 }, { 0xc46e, 0x60 }, { 0xc46f, 0x40 }, { 0xc47c, 0x01 }, { 0xc47d, 0x38 }, { 0xc47e, 0x00 }, { 0xc47f, 0x00 }, { 0xc480, 0x00 }, { 0xc481, 0xff }, { 0xc482, 0x00 }, { 0xc483, 0x40 }, { 0xc484, 0x00 }, { 0xc485, 0x18 }, { 0xc486, 0x00 }, { 0xc487, 0x18 }, { 0xc488, (OV10635_VTS - 8) * 16 >> 8}, { 0xc489, (OV10635_VTS - 8) * 16 & 0xff}, { 0xc48a, (OV10635_VTS - 8) * 16 >> 8}, { 0xc48b, (OV10635_VTS - 8) * 16 & 0xff}, { 0xc48c, 0x00 }, { 0xc48d, 0x04 }, { 0xc48e, 0x00 }, { 0xc48f, 0x04 }, { 0xc490, 0x03 }, { 0xc492, 0x20 }, { 0xc493, 0x08 }, { 0xc498, 0x02 }, { 0xc499, 0x00 }, { 0xc49a, 0x02 }, { 0xc49b, 0x00 }, { 0xc49c, 0x02 }, { 0xc49d, 0x00 }, { 0xc49e, 0x02 }, { 0xc49f, 0x60 }, { 0xc4a0, 0x03 }, { 0xc4a1, 0x00 }, { 0xc4a2, 0x04 }, { 0xc4a3, 0x00 }, { 0xc4a4, 0x00 }, { 0xc4a5, 0x10 }, { 0xc4a6, 0x00 }, { 0xc4a7, 0x40 }, { 0xc4a8, 0x00 }, { 0xc4a9, 0x80 }, { 0xc4aa, 0x0d }, { 0xc4ab, 0x00 }, { 0xc4ac, 0x0f }, { 0xc4ad, 0xc0 }, { 0xc4b4, 0x01 }, { 0xc4b5, 0x01 }, { 0xc4b6, 0x00 }, { 0xc4b7, 0x01 }, { 0xc4b8, 0x00 }, { 0xc4b9, 0x01 }, { 0xc4ba, 0x01 }, { 0xc4bb, 0x00 }, { 0xc4bc, 0x01 }, { 0xc4bd, 0x60 }, { 0xc4be, 0x02 }, { 0xc4bf, 0x33 }, { 0xc4c8, 0x03 }, { 0xc4c9, 0xd0 }, { 0xc4ca, 0x0e }, { 0xc4cb, 0x00 }, { 0xc4cc, 0x0e }, { 0xc4cd, 0x51 }, { 0xc4ce, 0x0e }, { 0xc4cf, 0x51 }, { 0xc4d0, 0x04 }, { 0xc4d1, 0x80 }, { 0xc4e0, 0x04 }, { 0xc4e1, 0x02 }, { 0xc4e2, 0x01 }, { 0xc4e4, 0x10 }, { 0xc4e5, 0x20 }, { 0xc4e6, 0x30 }, { 0xc4e7, 0x40 }, { 0xc4e8, 0x50 }, { 0xc4e9, 0x60 }, { 0xc4ea, 0x70 }, { 0xc4eb, 0x80 }, { 0xc4ec, 0x90 }, { 0xc4ed, 0xa0 }, { 0xc4ee, 0xb0 }, { 0xc4ef, 0xc0 }, { 0xc4f0, 0xd0 }, { 0xc4f1, 0xe0 }, { 0xc4f2, 0xf0 }, { 0xc4f3, 0x80 }, { 0xc4f4, 0x00 }, { 0xc4f5, 0x20 }, { 0xc4f6, 0x02 }, { 0xc4f7, 0x00 }, { 0xc4f8, 0x00 }, { 0xc4f9, 0x00 }, { 0xc4fa, 0x00 }, { 0xc4fb, 0x01 }, { 0xc4fc, 0x01 }, { 0xc4fd, 0x00 }, { 0xc4fe, 0x04 }, { 0xc4ff, 0x02 }, { 0xc500, 0x48 }, { 0xc501, 0x74 }, { 0xc502, 0x58 }, { 0xc503, 0x80 }, { 0xc504, 0x05 }, { 0xc505, 0x80 }, { 0xc506, 0x03 }, { 0xc507, 0x80 }, { 0xc508, 0x01 }, { 0xc509, 0xc0 }, { 0xc50a, 0x01 }, { 0xc50b, 0xa0 }, { 0xc50c, 0x01 }, { 0xc50d, 0x2c }, { 0xc50e, 0x01 }, { 0xc50f, 0x0a }, { 0xc510, 0x00 }, { 0xc511, 0x00 }, { 0xc512, 0xe5 }, { 0xc513, 0x14 }, { 0xc514, 0x04 }, { 0xc515, 0x00 }, { 0xc518, OV10635_VTS >> 8}, { 0xc519, OV10635_VTS & 0xff}, { 0xc51a, OV10635_HTS >> 8}, { 0xc51b, OV10635_HTS & 0xff}, { 0xc2e0, 0x00 }, { 0xc2e1, 0x51 }, { 0xc2e2, 0x00 }, { 0xc2e3, 0xd6 }, { 0xc2e4, 0x01 }, { 0xc2e5, 0x5e }, { 0xc2e9, 0x01 }, { 0xc2ea, 0x7a }, { 0xc2eb, 0x90 }, { 0xc2ed, 0x00 }, { 0xc2ee, 0x7a }, { 0xc2ef, 0x64 }, { 0xc308, 0x00 }, { 0xc309, 0x00 }, { 0xc30a, 0x00 }, { 0xc30c, 0x00 }, { 0xc30d, 0x01 }, { 0xc30e, 0x00 }, { 0xc30f, 0x00 }, { 0xc310, 0x01 }, { 0xc311, 0x60 }, { 0xc312, 0xff }, { 0xc313, 0x08 }, { 0xc314, 0x01 }, { 0xc315, 0x00 }, { 0xc316, 0xff }, { 0xc317, 0x0b }, { 0xc318, 0x00 }, { 0xc319, 0x0c }, { 0xc31a, 0x00 }, { 0xc31b, 0xe0 }, { 0xc31c, 0x00 }, { 0xc31d, 0x14 }, { 0xc31e, 0x00 }, { 0xc31f, 0xc5 }, { 0xc320, 0xff }, { 0xc321, 0x4b }, { 0xc322, 0xff }, { 0xc323, 0xf0 }, { 0xc324, 0xff }, { 0xc325, 0xe8 }, { 0xc326, 0x00 }, { 0xc327, 0x46 }, { 0xc328, 0xff }, { 0xc329, 0xd2 }, { 0xc32a, 0xff }, { 0xc32b, 0xe4 }, { 0xc32c, 0xff }, { 0xc32d, 0xbb }, { 0xc32e, 0x00 }, { 0xc32f, 0x61 }, { 0xc330, 0xff }, { 0xc331, 0xf9 }, { 0xc332, 0x00 }, { 0xc333, 0xd9 }, { 0xc334, 0x00 }, { 0xc335, 0x2e }, { 0xc336, 0x00 }, { 0xc337, 0xb1 }, { 0xc338, 0xff }, { 0xc339, 0x64 }, { 0xc33a, 0xff }, { 0xc33b, 0xeb }, { 0xc33c, 0xff }, { 0xc33d, 0xe8 }, { 0xc33e, 0x00 }, { 0xc33f, 0x48 }, { 0xc340, 0xff }, { 0xc341, 0xd0 }, { 0xc342, 0xff }, { 0xc343, 0xed }, { 0xc344, 0xff }, { 0xc345, 0xad }, { 0xc346, 0x00 }, { 0xc347, 0x66 }, { 0xc348, 0x01 }, { 0xc349, 0x00 }, { 0x6700, 0x04 }, { 0x6701, 0x7b }, { 0x6702, 0xfd }, { 0x6703, 0xf9 }, { 0x6704, 0x3d }, { 0x6705, 0x71 }, { 0x6706, 0x78 }, { 0x6708, 0x05 }, { 0x6f06, 0x6f }, { 0x6f07, 0x00 }, { 0x6f0a, 0x6f }, { 0x6f0b, 0x00 }, { 0x6f00, 0x03 }, { 0xc34c, 0x01 }, { 0xc34d, 0x00 }, { 0xc34e, 0x46 }, { 0xc34f, 0x55 }, { 0xc350, 0x00 }, { 0xc351, 0x40 }, { 0xc352, 0x00 }, { 0xc353, 0xff }, { 0xc354, 0x04 }, { 0xc355, 0x08 }, { 0xc356, 0x01 }, { 0xc357, 0xef }, { 0xc358, 0x30 }, { 0xc359, 0x01 }, { 0xc35a, 0x64 }, { 0xc35b, 0x46 }, { 0xc35c, 0x00 }, { 0x3042, 0xf0 }, { 0x3042, 0xf0 }, { 0x3042, 0xf0 }, { 0x3042, 0xf0 }, { 0x3042, 0xf0 }, { 0x3042, 0xf0 }, { 0x3042, 0xf0 }, { 0x3042, 0xf0 }, { 0x3042, 0xf0 }, { 0x3042, 0xf0 }, { 0x3042, 0xf0 }, { 0x3042, 0xf0 }, { 0x3042, 0xf0 }, { 0x3042, 0xf0 }, { 0x3042, 0xf0 }, { 0x3042, 0xf0 }, { 0x3042, 0xf0 }, { 0x3042, 0xf0 }, { 0x3042, 0xf0 }, { 0x3042, 0xf0 }, { 0x3042, 0xf0 }, { 0x3042, 0xf0 }, { 0x3042, 0xf0 }, { 0x3042, 0xf0 }, { 0x3042, 0xf0 }, { 0x3042, 0xf0 }, { 0xc261, 0x01 }, { 0x301b, 0xf0 }, { 0x301c, 0xf0 }, { 0x301a, 0xf0 }, { 0x6f00, 0xc3 }, { 0xc46a, 0x30 }, { 0xc46d, 0x20 }, { 0xc464, 0x84 }, { 0xc465, 0x00 }, { 0x6f00, 0x03 }, { 0x6f00, 0x43 }, { 0x381c, 0x00 }, { 0x381d, 0x40 }, { 0xc454, 0x01 }, { 0x6f00, 0xc3 }, { 0xc454, 0x00 }, { 0xc4b1, 0x02 }, { 0xc4b2, 0x01 }, { 0xc4b3, 0x03 }, { 0x6f00, 0x03 }, { 0x6f00, 0x43 }, /* enable FSIN (FRAMESYNC input) functionality */ { 0x3832, (0x0d + 2 * 0x20 + 0x15 + 38) >> 8 }, { 0x3833, (0x0d + 2 * 0x20 + 0x15 + 38) & 0xff }, { 0x3834, OV10635_VTS >> 8 }, { 0x3835, OV10635_VTS & 0xff }, { 0x302e, 0x01 }, }; struct rdacm20_device { struct device *dev; struct max9271_device serializer; struct i2c_client *sensor; struct v4l2_subdev sd; struct media_pad pad; struct v4l2_ctrl_handler ctrls; u32 addrs[2]; }; static inline struct rdacm20_device *sd_to_rdacm20(struct v4l2_subdev *sd) { return container_of(sd, struct rdacm20_device, sd); } static inline struct rdacm20_device *i2c_to_rdacm20(struct i2c_client *client) { return sd_to_rdacm20(i2c_get_clientdata(client)); } static int ov10635_read16(struct rdacm20_device *dev, u16 reg) { u8 buf[2] = { reg >> 8, reg & 0xff }; int ret; ret = i2c_master_send(dev->sensor, buf, 2); if (ret != 2) { dev_dbg(dev->dev, "%s: register 0x%04x write failed (%d)\n", __func__, reg, ret); return ret; } ret = i2c_master_recv(dev->sensor, buf, 2); if (ret < 0) { dev_dbg(dev->dev, "%s: register 0x%04x read failed (%d)\n", __func__, reg, ret); return ret; } return (buf[0] << 8) | buf[1]; } static int __ov10635_write(struct rdacm20_device *dev, u16 reg, u8 val) { u8 buf[3] = { reg >> 8, reg & 0xff, val }; int ret; dev_dbg(dev->dev, "%s(0x%04x, 0x%02x)\n", __func__, reg, val); ret = i2c_master_send(dev->sensor, buf, 3); return ret < 0 ? ret : 0; } static int ov10635_write(struct rdacm20_device *dev, u16 reg, u8 val) { int ret; ret = __ov10635_write(dev, reg, val); if (ret < 0) dev_err(dev->dev, "%s: register 0x%04x write failed (%d)\n", __func__, reg, ret); return ret; } static int ov10635_set_regs(struct rdacm20_device *dev, const struct ov10635_reg *regs, unsigned int nr_regs) { unsigned int i; int ret; for (i = 0; i < nr_regs; i++) { ret = __ov10635_write(dev, regs[i].reg, regs[i].val); if (ret) { dev_err(dev->dev, "%s: register %u (0x%04x) write failed (%d)\n", __func__, i, regs[i].reg, ret); return ret; } } return 0; } static int rdacm20_s_stream(struct v4l2_subdev *sd, int enable) { struct rdacm20_device *dev = sd_to_rdacm20(sd); return max9271_set_serial_link(&dev->serializer, enable); } static int rdacm20_enum_mbus_code(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_mbus_code_enum *code) { if (code->pad || code->index > 0) return -EINVAL; code->code = MEDIA_BUS_FMT_UYVY8_1X16; return 0; } static int rdacm20_get_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *format) { struct v4l2_mbus_framefmt *mf = &format->format; if (format->pad) return -EINVAL; mf->width = OV10635_WIDTH; mf->height = OV10635_HEIGHT; mf->code = MEDIA_BUS_FMT_UYVY8_1X16; mf->colorspace = V4L2_COLORSPACE_RAW; mf->field = V4L2_FIELD_NONE; mf->ycbcr_enc = V4L2_YCBCR_ENC_601; mf->quantization = V4L2_QUANTIZATION_FULL_RANGE; mf->xfer_func = V4L2_XFER_FUNC_NONE; return 0; } static const struct v4l2_subdev_video_ops rdacm20_video_ops = { .s_stream = rdacm20_s_stream, }; static const struct v4l2_subdev_pad_ops rdacm20_subdev_pad_ops = { .enum_mbus_code = rdacm20_enum_mbus_code, .get_fmt = rdacm20_get_fmt, .set_fmt = rdacm20_get_fmt, }; static const struct v4l2_subdev_ops rdacm20_subdev_ops = { .video = &rdacm20_video_ops, .pad = &rdacm20_subdev_pad_ops, }; static int rdacm20_initialize(struct rdacm20_device *dev) { unsigned int retry = 3; int ret; max9271_wake_up(&dev->serializer); /* Serial link disabled during config as it needs a valid pixel clock. */ ret = max9271_set_serial_link(&dev->serializer, false); if (ret) return ret; /* * Ensure that we have a good link configuration before attempting to * identify the device. */ ret = max9271_configure_i2c(&dev->serializer, MAX9271_I2CSLVSH_469NS_234NS | MAX9271_I2CSLVTO_1024US | MAX9271_I2CMSTBT_105KBPS); if (ret) return ret; /* * Hold OV10635 in reset during max9271 configuration. The reset signal * has to be asserted for at least 200 microseconds. */ ret = max9271_enable_gpios(&dev->serializer, MAX9271_GPIO1OUT); if (ret) return ret; ret = max9271_clear_gpios(&dev->serializer, MAX9271_GPIO1OUT); if (ret) return ret; usleep_range(200, 500); ret = max9271_configure_gmsl_link(&dev->serializer); if (ret) return ret; ret = max9271_verify_id(&dev->serializer); if (ret < 0) return ret; ret = max9271_set_address(&dev->serializer, dev->addrs[0]); if (ret < 0) return ret; dev->serializer.client->addr = dev->addrs[0]; /* * Release ov10635 from reset and initialize it. The image sensor * requires at least 2048 XVCLK cycles (85 micro-seconds at 24MHz) * before being available. Stay safe and wait up to 500 micro-seconds. */ ret = max9271_set_gpios(&dev->serializer, MAX9271_GPIO1OUT); if (ret) return ret; usleep_range(100, 500); again: ret = ov10635_read16(dev, OV10635_PID); if (ret < 0) { if (retry--) goto again; dev_err(dev->dev, "OV10635 ID read failed (%d)\n", ret); return -ENXIO; } if (ret != OV10635_VERSION) { if (retry--) goto again; dev_err(dev->dev, "OV10635 ID mismatch (0x%04x)\n", ret); return -ENXIO; } /* Change the sensor I2C address. */ ret = ov10635_write(dev, OV10635_SC_CMMN_SCCB_ID, (dev->addrs[1] << 1) | OV10635_SC_CMMN_SCCB_ID_SELECT); if (ret < 0) { dev_err(dev->dev, "OV10635 I2C address change failed (%d)\n", ret); return ret; } dev->sensor->addr = dev->addrs[1]; usleep_range(3500, 5000); /* Program the 0V10635 initial configuration. */ ret = ov10635_set_regs(dev, ov10635_regs_wizard, ARRAY_SIZE(ov10635_regs_wizard)); if (ret) return ret; dev_info(dev->dev, "Identified RDACM20 camera module\n"); /* * Set reverse channel high threshold to increase noise immunity. * * This should be compensated by increasing the reverse channel * amplitude on the remote deserializer side. * * TODO Inspect the embedded MCU programming sequence to make sure * there are no conflicts with the configuration applied here. * * TODO Clarify the embedded MCU startup delay to avoid write * collisions on the I2C bus. */ return max9271_set_high_threshold(&dev->serializer, true); } static int rdacm20_probe(struct i2c_client *client) { struct rdacm20_device *dev; int ret; dev = devm_kzalloc(&client->dev, sizeof(*dev), GFP_KERNEL); if (!dev) return -ENOMEM; dev->dev = &client->dev; dev->serializer.client = client; ret = of_property_read_u32_array(client->dev.of_node, "reg", dev->addrs, 2); if (ret < 0) { dev_err(dev->dev, "Invalid DT reg property: %d\n", ret); return -EINVAL; } /* Create the dummy I2C client for the sensor. */ dev->sensor = i2c_new_dummy_device(client->adapter, OV10635_I2C_ADDRESS); if (IS_ERR(dev->sensor)) { ret = PTR_ERR(dev->sensor); goto error; } /* Initialize the hardware. */ ret = rdacm20_initialize(dev); if (ret < 0) goto error; /* Initialize and register the subdevice. */ v4l2_i2c_subdev_init(&dev->sd, client, &rdacm20_subdev_ops); dev->sd.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE; v4l2_ctrl_handler_init(&dev->ctrls, 1); v4l2_ctrl_new_std(&dev->ctrls, NULL, V4L2_CID_PIXEL_RATE, OV10635_PIXEL_RATE, OV10635_PIXEL_RATE, 1, OV10635_PIXEL_RATE); dev->sd.ctrl_handler = &dev->ctrls; ret = dev->ctrls.error; if (ret) goto error_free_ctrls; dev->pad.flags = MEDIA_PAD_FL_SOURCE; dev->sd.entity.function = MEDIA_ENT_F_CAM_SENSOR; ret = media_entity_pads_init(&dev->sd.entity, 1, &dev->pad); if (ret < 0) goto error_free_ctrls; ret = v4l2_async_register_subdev(&dev->sd); if (ret) goto error_free_ctrls; return 0; error_free_ctrls: v4l2_ctrl_handler_free(&dev->ctrls); error: media_entity_cleanup(&dev->sd.entity); if (dev->sensor) i2c_unregister_device(dev->sensor); dev_err(&client->dev, "probe failed\n"); return ret; } static void rdacm20_remove(struct i2c_client *client) { struct rdacm20_device *dev = i2c_to_rdacm20(client); v4l2_async_unregister_subdev(&dev->sd); v4l2_ctrl_handler_free(&dev->ctrls); media_entity_cleanup(&dev->sd.entity); i2c_unregister_device(dev->sensor); } static void rdacm20_shutdown(struct i2c_client *client) { struct rdacm20_device *dev = i2c_to_rdacm20(client); /* make sure stream off during shutdown (reset/reboot) */ rdacm20_s_stream(&dev->sd, 0); } static const struct of_device_id rdacm20_of_ids[] = { { .compatible = "imi,rdacm20", }, { } }; MODULE_DEVICE_TABLE(of, rdacm20_of_ids); static struct i2c_driver rdacm20_i2c_driver = { .driver = { .name = "rdacm20", .of_match_table = rdacm20_of_ids, }, .probe = rdacm20_probe, .remove = rdacm20_remove, .shutdown = rdacm20_shutdown, }; module_i2c_driver(rdacm20_i2c_driver); MODULE_DESCRIPTION("GMSL Camera driver for RDACM20"); MODULE_AUTHOR("Vladimir Barinov"); MODULE_LICENSE("GPL");
linux-master
drivers/media/i2c/rdacm20.c
// SPDX-License-Identifier: GPL-2.0 // Copyright (c) 2019 Intel Corporation. #include <asm/unaligned.h> #include <linux/acpi.h> #include <linux/clk.h> #include <linux/delay.h> #include <linux/gpio/consumer.h> #include <linux/i2c.h> #include <linux/module.h> #include <linux/pm_runtime.h> #include <linux/regulator/consumer.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-device.h> #include <media/v4l2-fwnode.h> #define OV8856_REG_VALUE_08BIT 1 #define OV8856_REG_VALUE_16BIT 2 #define OV8856_REG_VALUE_24BIT 3 #define OV8856_SCLK 144000000ULL #define OV8856_XVCLK_19_2 19200000 #define OV8856_DATA_LANES 4 #define OV8856_RGB_DEPTH 10 #define OV8856_REG_CHIP_ID 0x300a #define OV8856_CHIP_ID 0x00885a #define OV8856_REG_MODE_SELECT 0x0100 #define OV8856_MODE_STANDBY 0x00 #define OV8856_MODE_STREAMING 0x01 /* module revisions */ #define OV8856_2A_MODULE 0x01 #define OV8856_1B_MODULE 0x02 /* the OTP read-out buffer is at 0x7000 and 0xf is the offset * of the byte in the OTP that means the module revision */ #define OV8856_MODULE_REVISION 0x700f #define OV8856_OTP_MODE_CTRL 0x3d84 #define OV8856_OTP_LOAD_CTRL 0x3d81 #define OV8856_OTP_MODE_AUTO 0x00 #define OV8856_OTP_LOAD_CTRL_ENABLE BIT(0) /* vertical-timings from sensor */ #define OV8856_REG_VTS 0x380e #define OV8856_VTS_MAX 0x7fff /* horizontal-timings from sensor */ #define OV8856_REG_HTS 0x380c /* Exposure controls from sensor */ #define OV8856_REG_EXPOSURE 0x3500 #define OV8856_EXPOSURE_MIN 6 #define OV8856_EXPOSURE_MAX_MARGIN 6 #define OV8856_EXPOSURE_STEP 1 /* Analog gain controls from sensor */ #define OV8856_REG_ANALOG_GAIN 0x3508 #define OV8856_ANAL_GAIN_MIN 128 #define OV8856_ANAL_GAIN_MAX 2047 #define OV8856_ANAL_GAIN_STEP 1 /* Digital gain controls from sensor */ #define OV8856_REG_DIGITAL_GAIN 0x350a #define OV8856_REG_MWB_R_GAIN 0x5019 #define OV8856_REG_MWB_G_GAIN 0x501b #define OV8856_REG_MWB_B_GAIN 0x501d #define OV8856_DGTL_GAIN_MIN 0 #define OV8856_DGTL_GAIN_MAX 4095 #define OV8856_DGTL_GAIN_STEP 1 #define OV8856_DGTL_GAIN_DEFAULT 1024 /* Test Pattern Control */ #define OV8856_REG_TEST_PATTERN 0x5e00 #define OV8856_TEST_PATTERN_ENABLE BIT(7) #define OV8856_TEST_PATTERN_BAR_SHIFT 2 #define NUM_REGS 7 #define NUM_MODE_REGS 187 #define NUM_MODE_REGS_2 200 /* Flip Mirror Controls from sensor */ #define OV8856_REG_FORMAT1 0x3820 #define OV8856_REG_FORMAT2 0x3821 #define OV8856_REG_FORMAT1_OP_1 BIT(1) #define OV8856_REG_FORMAT1_OP_2 BIT(2) #define OV8856_REG_FORMAT1_OP_3 BIT(6) #define OV8856_REG_FORMAT2_OP_1 BIT(1) #define OV8856_REG_FORMAT2_OP_2 BIT(2) #define OV8856_REG_FORMAT2_OP_3 BIT(6) #define OV8856_REG_FLIP_OPT_1 0x376b #define OV8856_REG_FLIP_OPT_2 0x5001 #define OV8856_REG_FLIP_OPT_3 0x502e #define OV8856_REG_MIRROR_OPT_1 0x5004 #define OV8856_REG_FLIP_OP_0 BIT(0) #define OV8856_REG_FLIP_OP_1 BIT(1) #define OV8856_REG_FLIP_OP_2 BIT(2) #define OV8856_REG_MIRROR_OP_1 BIT(1) #define OV8856_REG_MIRROR_OP_2 BIT(2) #define to_ov8856(_sd) container_of(_sd, struct ov8856, sd) static const char * const ov8856_supply_names[] = { "dovdd", /* Digital I/O power */ "avdd", /* Analog power */ "dvdd", /* Digital core power */ }; enum { OV8856_MEDIA_BUS_FMT_SBGGR10_1X10, OV8856_MEDIA_BUS_FMT_SGRBG10_1X10, }; struct ov8856_reg { u16 address; u8 val; }; struct ov8856_reg_list { u32 num_of_regs; const struct ov8856_reg *regs; }; struct ov8856_link_freq_config { const struct ov8856_reg_list reg_list; }; struct ov8856_mode { /* Frame width in pixels */ u32 width; /* Frame height in pixels */ u32 height; /* Horizontal timining size */ u32 hts; /* Default vertical timining size */ u32 vts_def; /* Min vertical timining size */ u32 vts_min; /* Link frequency needed for this resolution */ u32 link_freq_index; /* Sensor register settings for this resolution */ const struct ov8856_reg_list reg_list; /* Number of data lanes */ u8 data_lanes; /* Default MEDIA_BUS_FMT for this mode */ u32 default_mbus_index; }; struct ov8856_mipi_data_rates { const struct ov8856_reg regs_0[NUM_REGS]; const struct ov8856_reg regs_1[NUM_REGS]; }; static const struct ov8856_mipi_data_rates mipi_data_rate_lane_2 = { //mipi_data_rate_1440mbps { {0x0103, 0x01}, {0x0100, 0x00}, {0x0302, 0x43}, {0x0303, 0x00}, {0x030b, 0x02}, {0x030d, 0x4b}, {0x031e, 0x0c} }, //mipi_data_rate_720mbps { {0x0103, 0x01}, {0x0100, 0x00}, {0x0302, 0x4b}, {0x0303, 0x01}, {0x030b, 0x02}, {0x030d, 0x4b}, {0x031e, 0x0c} } }; static const struct ov8856_mipi_data_rates mipi_data_rate_lane_4 = { //mipi_data_rate_720mbps { {0x0103, 0x01}, {0x0100, 0x00}, {0x0302, 0x4b}, {0x0303, 0x01}, {0x030b, 0x02}, {0x030d, 0x4b}, {0x031e, 0x0c} }, //mipi_data_rate_360mbps { {0x0103, 0x01}, {0x0100, 0x00}, {0x0302, 0x4b}, {0x0303, 0x03}, {0x030b, 0x02}, {0x030d, 0x4b}, {0x031e, 0x0c} } }; static const struct ov8856_reg lane_2_mode_3280x2464[] = { /* 3280x2464 resolution */ {0x3000, 0x20}, {0x3003, 0x08}, {0x300e, 0x20}, {0x3010, 0x00}, {0x3015, 0x84}, {0x3018, 0x32}, {0x3021, 0x23}, {0x3033, 0x24}, {0x3500, 0x00}, {0x3501, 0x9a}, {0x3502, 0x20}, {0x3503, 0x08}, {0x3505, 0x83}, {0x3508, 0x01}, {0x3509, 0x80}, {0x350c, 0x00}, {0x350d, 0x80}, {0x350e, 0x04}, {0x350f, 0x00}, {0x3510, 0x00}, {0x3511, 0x02}, {0x3512, 0x00}, {0x3600, 0x72}, {0x3601, 0x40}, {0x3602, 0x30}, {0x3610, 0xc5}, {0x3611, 0x58}, {0x3612, 0x5c}, {0x3613, 0xca}, {0x3614, 0x50}, {0x3628, 0xff}, {0x3629, 0xff}, {0x362a, 0xff}, {0x3633, 0x10}, {0x3634, 0x10}, {0x3635, 0x10}, {0x3636, 0x10}, {0x3663, 0x08}, {0x3669, 0x34}, {0x366e, 0x10}, {0x3706, 0x86}, {0x370b, 0x7e}, {0x3714, 0x23}, {0x3730, 0x12}, {0x3733, 0x10}, {0x3764, 0x00}, {0x3765, 0x00}, {0x3769, 0x62}, {0x376a, 0x2a}, {0x376b, 0x30}, {0x3780, 0x00}, {0x3781, 0x24}, {0x3782, 0x00}, {0x3783, 0x23}, {0x3798, 0x2f}, {0x37a1, 0x60}, {0x37a8, 0x6a}, {0x37ab, 0x3f}, {0x37c2, 0x04}, {0x37c3, 0xf1}, {0x37c9, 0x80}, {0x37cb, 0x16}, {0x37cc, 0x16}, {0x37cd, 0x16}, {0x37ce, 0x16}, {0x3800, 0x00}, {0x3801, 0x00}, {0x3802, 0x00}, {0x3803, 0x06}, {0x3804, 0x0c}, {0x3805, 0xdf}, {0x3806, 0x09}, {0x3807, 0xa7}, {0x3808, 0x0c}, {0x3809, 0xd0}, {0x380a, 0x09}, {0x380b, 0xa0}, {0x380c, 0x07}, {0x380d, 0x88}, {0x380e, 0x09}, {0x380f, 0xb8}, {0x3810, 0x00}, {0x3811, 0x00}, {0x3812, 0x00}, {0x3813, 0x01}, {0x3814, 0x01}, {0x3815, 0x01}, {0x3816, 0x00}, {0x3817, 0x00}, {0x3818, 0x00}, {0x3819, 0x00}, {0x3820, 0x80}, {0x3821, 0x46}, {0x382a, 0x01}, {0x382b, 0x01}, {0x3830, 0x06}, {0x3836, 0x02}, {0x3837, 0x10}, {0x3862, 0x04}, {0x3863, 0x08}, {0x3cc0, 0x33}, {0x3d85, 0x14}, {0x3d8c, 0x73}, {0x3d8d, 0xde}, {0x4001, 0xe0}, {0x4003, 0x40}, {0x4008, 0x00}, {0x4009, 0x0b}, {0x400a, 0x00}, {0x400b, 0x84}, {0x400f, 0x80}, {0x4010, 0xf0}, {0x4011, 0xff}, {0x4012, 0x02}, {0x4013, 0x01}, {0x4014, 0x01}, {0x4015, 0x01}, {0x4042, 0x00}, {0x4043, 0x80}, {0x4044, 0x00}, {0x4045, 0x80}, {0x4046, 0x00}, {0x4047, 0x80}, {0x4048, 0x00}, {0x4049, 0x80}, {0x4041, 0x03}, {0x404c, 0x20}, {0x404d, 0x00}, {0x404e, 0x20}, {0x4203, 0x80}, {0x4307, 0x30}, {0x4317, 0x00}, {0x4503, 0x08}, {0x4601, 0x80}, {0x4800, 0x44}, {0x4816, 0x53}, {0x481b, 0x58}, {0x481f, 0x27}, {0x4837, 0x0c}, {0x483c, 0x0f}, {0x484b, 0x05}, {0x5000, 0x57}, {0x5001, 0x0a}, {0x5004, 0x06}, {0x502e, 0x03}, {0x5030, 0x41}, {0x5795, 0x02}, {0x5796, 0x20}, {0x5797, 0x20}, {0x5798, 0xd5}, {0x5799, 0xd5}, {0x579a, 0x00}, {0x579b, 0x50}, {0x579c, 0x00}, {0x579d, 0x2c}, {0x579e, 0x0c}, {0x579f, 0x40}, {0x57a0, 0x09}, {0x57a1, 0x40}, {0x5780, 0x14}, {0x5781, 0x0f}, {0x5782, 0x44}, {0x5783, 0x02}, {0x5784, 0x01}, {0x5785, 0x01}, {0x5786, 0x00}, {0x5787, 0x04}, {0x5788, 0x02}, {0x5789, 0x0f}, {0x578a, 0xfd}, {0x578b, 0xf5}, {0x578c, 0xf5}, {0x578d, 0x03}, {0x578e, 0x08}, {0x578f, 0x0c}, {0x5790, 0x08}, {0x5791, 0x04}, {0x5792, 0x00}, {0x5793, 0x52}, {0x5794, 0xa3}, {0x59f8, 0x3d}, {0x5a08, 0x02}, {0x5b00, 0x02}, {0x5b01, 0x10}, {0x5b02, 0x03}, {0x5b03, 0xcf}, {0x5b05, 0x6c}, {0x5e00, 0x00} }; static const struct ov8856_reg lane_2_mode_1640x1232[] = { /* 1640x1232 resolution */ {0x3000, 0x20}, {0x3003, 0x08}, {0x300e, 0x20}, {0x3010, 0x00}, {0x3015, 0x84}, {0x3018, 0x32}, {0x3021, 0x23}, {0x3033, 0x24}, {0x3500, 0x00}, {0x3501, 0x4c}, {0x3502, 0xe0}, {0x3503, 0x08}, {0x3505, 0x83}, {0x3508, 0x01}, {0x3509, 0x80}, {0x350c, 0x00}, {0x350d, 0x80}, {0x350e, 0x04}, {0x350f, 0x00}, {0x3510, 0x00}, {0x3511, 0x02}, {0x3512, 0x00}, {0x3600, 0x72}, {0x3601, 0x40}, {0x3602, 0x30}, {0x3610, 0xc5}, {0x3611, 0x58}, {0x3612, 0x5c}, {0x3613, 0xca}, {0x3614, 0x50}, {0x3628, 0xff}, {0x3629, 0xff}, {0x362a, 0xff}, {0x3633, 0x10}, {0x3634, 0x10}, {0x3635, 0x10}, {0x3636, 0x10}, {0x3663, 0x08}, {0x3669, 0x34}, {0x366e, 0x08}, {0x3706, 0x86}, {0x370b, 0x7e}, {0x3714, 0x27}, {0x3730, 0x12}, {0x3733, 0x10}, {0x3764, 0x00}, {0x3765, 0x00}, {0x3769, 0x62}, {0x376a, 0x2a}, {0x376b, 0x30}, {0x3780, 0x00}, {0x3781, 0x24}, {0x3782, 0x00}, {0x3783, 0x23}, {0x3798, 0x2f}, {0x37a1, 0x60}, {0x37a8, 0x6a}, {0x37ab, 0x3f}, {0x37c2, 0x14}, {0x37c3, 0xf1}, {0x37c9, 0x80}, {0x37cb, 0x16}, {0x37cc, 0x16}, {0x37cd, 0x16}, {0x37ce, 0x16}, {0x3800, 0x00}, {0x3801, 0x00}, {0x3802, 0x00}, {0x3803, 0x00}, {0x3804, 0x0c}, {0x3805, 0xdf}, {0x3806, 0x09}, {0x3807, 0xaf}, {0x3808, 0x06}, {0x3809, 0x68}, {0x380a, 0x04}, {0x380b, 0xd0}, {0x380c, 0x0c}, {0x380d, 0x60}, {0x380e, 0x05}, {0x380f, 0xea}, {0x3810, 0x00}, {0x3811, 0x04}, {0x3812, 0x00}, {0x3813, 0x05}, {0x3814, 0x03}, {0x3815, 0x01}, {0x3816, 0x00}, {0x3817, 0x00}, {0x3818, 0x00}, {0x3819, 0x00}, {0x3820, 0x90}, {0x3821, 0x67}, {0x382a, 0x03}, {0x382b, 0x01}, {0x3830, 0x06}, {0x3836, 0x02}, {0x3837, 0x10}, {0x3862, 0x04}, {0x3863, 0x08}, {0x3cc0, 0x33}, {0x3d85, 0x14}, {0x3d8c, 0x73}, {0x3d8d, 0xde}, {0x4001, 0xe0}, {0x4003, 0x40}, {0x4008, 0x00}, {0x4009, 0x05}, {0x400a, 0x00}, {0x400b, 0x84}, {0x400f, 0x80}, {0x4010, 0xf0}, {0x4011, 0xff}, {0x4012, 0x02}, {0x4013, 0x01}, {0x4014, 0x01}, {0x4015, 0x01}, {0x4042, 0x00}, {0x4043, 0x80}, {0x4044, 0x00}, {0x4045, 0x80}, {0x4046, 0x00}, {0x4047, 0x80}, {0x4048, 0x00}, {0x4049, 0x80}, {0x4041, 0x03}, {0x404c, 0x20}, {0x404d, 0x00}, {0x404e, 0x20}, {0x4203, 0x80}, {0x4307, 0x30}, {0x4317, 0x00}, {0x4503, 0x08}, {0x4601, 0x80}, {0x4800, 0x44}, {0x4816, 0x53}, {0x481b, 0x58}, {0x481f, 0x27}, {0x4837, 0x16}, {0x483c, 0x0f}, {0x484b, 0x05}, {0x5000, 0x57}, {0x5001, 0x0a}, {0x5004, 0x06}, {0x502e, 0x03}, {0x5030, 0x41}, {0x5795, 0x00}, {0x5796, 0x10}, {0x5797, 0x10}, {0x5798, 0x73}, {0x5799, 0x73}, {0x579a, 0x00}, {0x579b, 0x28}, {0x579c, 0x00}, {0x579d, 0x16}, {0x579e, 0x06}, {0x579f, 0x20}, {0x57a0, 0x04}, {0x57a1, 0xa0}, {0x5780, 0x14}, {0x5781, 0x0f}, {0x5782, 0x44}, {0x5783, 0x02}, {0x5784, 0x01}, {0x5785, 0x01}, {0x5786, 0x00}, {0x5787, 0x04}, {0x5788, 0x02}, {0x5789, 0x0f}, {0x578a, 0xfd}, {0x578b, 0xf5}, {0x578c, 0xf5}, {0x578d, 0x03}, {0x578e, 0x08}, {0x578f, 0x0c}, {0x5790, 0x08}, {0x5791, 0x04}, {0x5792, 0x00}, {0x5793, 0x52}, {0x5794, 0xa3}, {0x59f8, 0x3d}, {0x5a08, 0x02}, {0x5b00, 0x02}, {0x5b01, 0x10}, {0x5b02, 0x03}, {0x5b03, 0xcf}, {0x5b05, 0x6c}, {0x5e00, 0x00} }; static const struct ov8856_reg lane_4_mode_3280x2464[] = { /* 3280x2464 resolution */ {0x3000, 0x20}, {0x3003, 0x08}, {0x300e, 0x20}, {0x3010, 0x00}, {0x3015, 0x84}, {0x3018, 0x72}, {0x3021, 0x23}, {0x3033, 0x24}, {0x3500, 0x00}, {0x3501, 0x9a}, {0x3502, 0x20}, {0x3503, 0x08}, {0x3505, 0x83}, {0x3508, 0x01}, {0x3509, 0x80}, {0x350c, 0x00}, {0x350d, 0x80}, {0x350e, 0x04}, {0x350f, 0x00}, {0x3510, 0x00}, {0x3511, 0x02}, {0x3512, 0x00}, {0x3600, 0x72}, {0x3601, 0x40}, {0x3602, 0x30}, {0x3610, 0xc5}, {0x3611, 0x58}, {0x3612, 0x5c}, {0x3613, 0xca}, {0x3614, 0x20}, {0x3628, 0xff}, {0x3629, 0xff}, {0x362a, 0xff}, {0x3633, 0x10}, {0x3634, 0x10}, {0x3635, 0x10}, {0x3636, 0x10}, {0x3663, 0x08}, {0x3669, 0x34}, {0x366e, 0x10}, {0x3706, 0x86}, {0x370b, 0x7e}, {0x3714, 0x23}, {0x3730, 0x12}, {0x3733, 0x10}, {0x3764, 0x00}, {0x3765, 0x00}, {0x3769, 0x62}, {0x376a, 0x2a}, {0x376b, 0x30}, {0x3780, 0x00}, {0x3781, 0x24}, {0x3782, 0x00}, {0x3783, 0x23}, {0x3798, 0x2f}, {0x37a1, 0x60}, {0x37a8, 0x6a}, {0x37ab, 0x3f}, {0x37c2, 0x04}, {0x37c3, 0xf1}, {0x37c9, 0x80}, {0x37cb, 0x16}, {0x37cc, 0x16}, {0x37cd, 0x16}, {0x37ce, 0x16}, {0x3800, 0x00}, {0x3801, 0x00}, {0x3802, 0x00}, {0x3803, 0x06}, {0x3804, 0x0c}, {0x3805, 0xdf}, {0x3806, 0x09}, {0x3807, 0xa7}, {0x3808, 0x0c}, {0x3809, 0xd0}, {0x380a, 0x09}, {0x380b, 0xa0}, {0x380c, 0x07}, {0x380d, 0x88}, {0x380e, 0x09}, {0x380f, 0xb8}, {0x3810, 0x00}, {0x3811, 0x00}, {0x3812, 0x00}, {0x3813, 0x01}, {0x3814, 0x01}, {0x3815, 0x01}, {0x3816, 0x00}, {0x3817, 0x00}, {0x3818, 0x00}, {0x3819, 0x10}, {0x3820, 0x80}, {0x3821, 0x46}, {0x382a, 0x01}, {0x382b, 0x01}, {0x3830, 0x06}, {0x3836, 0x02}, {0x3862, 0x04}, {0x3863, 0x08}, {0x3cc0, 0x33}, {0x3d85, 0x17}, {0x3d8c, 0x73}, {0x3d8d, 0xde}, {0x4001, 0xe0}, {0x4003, 0x40}, {0x4008, 0x00}, {0x4009, 0x0b}, {0x400a, 0x00}, {0x400b, 0x84}, {0x400f, 0x80}, {0x4010, 0xf0}, {0x4011, 0xff}, {0x4012, 0x02}, {0x4013, 0x01}, {0x4014, 0x01}, {0x4015, 0x01}, {0x4042, 0x00}, {0x4043, 0x80}, {0x4044, 0x00}, {0x4045, 0x80}, {0x4046, 0x00}, {0x4047, 0x80}, {0x4048, 0x00}, {0x4049, 0x80}, {0x4041, 0x03}, {0x404c, 0x20}, {0x404d, 0x00}, {0x404e, 0x20}, {0x4203, 0x80}, {0x4307, 0x30}, {0x4317, 0x00}, {0x4503, 0x08}, {0x4601, 0x80}, {0x4800, 0x44}, {0x4816, 0x53}, {0x481b, 0x58}, {0x481f, 0x27}, {0x4837, 0x16}, {0x483c, 0x0f}, {0x484b, 0x05}, {0x5000, 0x57}, {0x5001, 0x0a}, {0x5004, 0x06}, {0x502e, 0x03}, {0x5030, 0x41}, {0x5780, 0x14}, {0x5781, 0x0f}, {0x5782, 0x44}, {0x5783, 0x02}, {0x5784, 0x01}, {0x5785, 0x01}, {0x5786, 0x00}, {0x5787, 0x04}, {0x5788, 0x02}, {0x5789, 0x0f}, {0x578a, 0xfd}, {0x578b, 0xf5}, {0x578c, 0xf5}, {0x578d, 0x03}, {0x578e, 0x08}, {0x578f, 0x0c}, {0x5790, 0x08}, {0x5791, 0x04}, {0x5792, 0x00}, {0x5793, 0x52}, {0x5794, 0xa3}, {0x5795, 0x02}, {0x5796, 0x20}, {0x5797, 0x20}, {0x5798, 0xd5}, {0x5799, 0xd5}, {0x579a, 0x00}, {0x579b, 0x50}, {0x579c, 0x00}, {0x579d, 0x2c}, {0x579e, 0x0c}, {0x579f, 0x40}, {0x57a0, 0x09}, {0x57a1, 0x40}, {0x59f8, 0x3d}, {0x5a08, 0x02}, {0x5b00, 0x02}, {0x5b01, 0x10}, {0x5b02, 0x03}, {0x5b03, 0xcf}, {0x5b05, 0x6c}, {0x5e00, 0x00} }; static const struct ov8856_reg lane_4_mode_1640x1232[] = { /* 1640x1232 resolution */ {0x3000, 0x20}, {0x3003, 0x08}, {0x300e, 0x20}, {0x3010, 0x00}, {0x3015, 0x84}, {0x3018, 0x72}, {0x3021, 0x23}, {0x3033, 0x24}, {0x3500, 0x00}, {0x3501, 0x4c}, {0x3502, 0xe0}, {0x3503, 0x08}, {0x3505, 0x83}, {0x3508, 0x01}, {0x3509, 0x80}, {0x350c, 0x00}, {0x350d, 0x80}, {0x350e, 0x04}, {0x350f, 0x00}, {0x3510, 0x00}, {0x3511, 0x02}, {0x3512, 0x00}, {0x3600, 0x72}, {0x3601, 0x40}, {0x3602, 0x30}, {0x3610, 0xc5}, {0x3611, 0x58}, {0x3612, 0x5c}, {0x3613, 0xca}, {0x3614, 0x20}, {0x3628, 0xff}, {0x3629, 0xff}, {0x362a, 0xff}, {0x3633, 0x10}, {0x3634, 0x10}, {0x3635, 0x10}, {0x3636, 0x10}, {0x3663, 0x08}, {0x3669, 0x34}, {0x366e, 0x08}, {0x3706, 0x86}, {0x370b, 0x7e}, {0x3714, 0x27}, {0x3730, 0x12}, {0x3733, 0x10}, {0x3764, 0x00}, {0x3765, 0x00}, {0x3769, 0x62}, {0x376a, 0x2a}, {0x376b, 0x30}, {0x3780, 0x00}, {0x3781, 0x24}, {0x3782, 0x00}, {0x3783, 0x23}, {0x3798, 0x2f}, {0x37a1, 0x60}, {0x37a8, 0x6a}, {0x37ab, 0x3f}, {0x37c2, 0x14}, {0x37c3, 0xf1}, {0x37c9, 0x80}, {0x37cb, 0x16}, {0x37cc, 0x16}, {0x37cd, 0x16}, {0x37ce, 0x16}, {0x3800, 0x00}, {0x3801, 0x00}, {0x3802, 0x00}, {0x3803, 0x00}, {0x3804, 0x0c}, {0x3805, 0xdf}, {0x3806, 0x09}, {0x3807, 0xaf}, {0x3808, 0x06}, {0x3809, 0x68}, {0x380a, 0x04}, {0x380b, 0xd0}, {0x380c, 0x0e}, {0x380d, 0xec}, {0x380e, 0x04}, {0x380f, 0xe8}, {0x3810, 0x00}, {0x3811, 0x04}, {0x3812, 0x00}, {0x3813, 0x05}, {0x3814, 0x03}, {0x3815, 0x01}, {0x3816, 0x00}, {0x3817, 0x00}, {0x3818, 0x00}, {0x3819, 0x10}, {0x3820, 0x90}, {0x3821, 0x67}, {0x382a, 0x03}, {0x382b, 0x01}, {0x3830, 0x06}, {0x3836, 0x02}, {0x3862, 0x04}, {0x3863, 0x08}, {0x3cc0, 0x33}, {0x3d85, 0x17}, {0x3d8c, 0x73}, {0x3d8d, 0xde}, {0x4001, 0xe0}, {0x4003, 0x40}, {0x4008, 0x00}, {0x4009, 0x05}, {0x400a, 0x00}, {0x400b, 0x84}, {0x400f, 0x80}, {0x4010, 0xf0}, {0x4011, 0xff}, {0x4012, 0x02}, {0x4013, 0x01}, {0x4014, 0x01}, {0x4015, 0x01}, {0x4042, 0x00}, {0x4043, 0x80}, {0x4044, 0x00}, {0x4045, 0x80}, {0x4046, 0x00}, {0x4047, 0x80}, {0x4048, 0x00}, {0x4049, 0x80}, {0x4041, 0x03}, {0x404c, 0x20}, {0x404d, 0x00}, {0x404e, 0x20}, {0x4203, 0x80}, {0x4307, 0x30}, {0x4317, 0x00}, {0x4503, 0x08}, {0x4601, 0x80}, {0x4800, 0x44}, {0x4816, 0x53}, {0x481b, 0x58}, {0x481f, 0x27}, {0x4837, 0x16}, {0x483c, 0x0f}, {0x484b, 0x05}, {0x5000, 0x57}, {0x5001, 0x0a}, {0x5004, 0x06}, {0x502e, 0x03}, {0x5030, 0x41}, {0x5780, 0x14}, {0x5781, 0x0f}, {0x5782, 0x44}, {0x5783, 0x02}, {0x5784, 0x01}, {0x5785, 0x01}, {0x5786, 0x00}, {0x5787, 0x04}, {0x5788, 0x02}, {0x5789, 0x0f}, {0x578a, 0xfd}, {0x578b, 0xf5}, {0x578c, 0xf5}, {0x578d, 0x03}, {0x578e, 0x08}, {0x578f, 0x0c}, {0x5790, 0x08}, {0x5791, 0x04}, {0x5792, 0x00}, {0x5793, 0x52}, {0x5794, 0xa3}, {0x5795, 0x00}, {0x5796, 0x10}, {0x5797, 0x10}, {0x5798, 0x73}, {0x5799, 0x73}, {0x579a, 0x00}, {0x579b, 0x28}, {0x579c, 0x00}, {0x579d, 0x16}, {0x579e, 0x06}, {0x579f, 0x20}, {0x57a0, 0x04}, {0x57a1, 0xa0}, {0x59f8, 0x3d}, {0x5a08, 0x02}, {0x5b00, 0x02}, {0x5b01, 0x10}, {0x5b02, 0x03}, {0x5b03, 0xcf}, {0x5b05, 0x6c}, {0x5e00, 0x00} }; static const struct ov8856_reg lane_4_mode_3264x2448[] = { /* 3264x2448 resolution */ {0x0103, 0x01}, {0x0302, 0x3c}, {0x0303, 0x01}, {0x031e, 0x0c}, {0x3000, 0x20}, {0x3003, 0x08}, {0x300e, 0x20}, {0x3010, 0x00}, {0x3015, 0x84}, {0x3018, 0x72}, {0x3021, 0x23}, {0x3033, 0x24}, {0x3500, 0x00}, {0x3501, 0x9a}, {0x3502, 0x20}, {0x3503, 0x08}, {0x3505, 0x83}, {0x3508, 0x01}, {0x3509, 0x80}, {0x350c, 0x00}, {0x350d, 0x80}, {0x350e, 0x04}, {0x350f, 0x00}, {0x3510, 0x00}, {0x3511, 0x02}, {0x3512, 0x00}, {0x3600, 0x72}, {0x3601, 0x40}, {0x3602, 0x30}, {0x3610, 0xc5}, {0x3611, 0x58}, {0x3612, 0x5c}, {0x3613, 0xca}, {0x3614, 0x60}, {0x3628, 0xff}, {0x3629, 0xff}, {0x362a, 0xff}, {0x3633, 0x10}, {0x3634, 0x10}, {0x3635, 0x10}, {0x3636, 0x10}, {0x3663, 0x08}, {0x3669, 0x34}, {0x366d, 0x00}, {0x366e, 0x10}, {0x3706, 0x86}, {0x370b, 0x7e}, {0x3714, 0x23}, {0x3730, 0x12}, {0x3733, 0x10}, {0x3764, 0x00}, {0x3765, 0x00}, {0x3769, 0x62}, {0x376a, 0x2a}, {0x376b, 0x30}, {0x3780, 0x00}, {0x3781, 0x24}, {0x3782, 0x00}, {0x3783, 0x23}, {0x3798, 0x2f}, {0x37a1, 0x60}, {0x37a8, 0x6a}, {0x37ab, 0x3f}, {0x37c2, 0x04}, {0x37c3, 0xf1}, {0x37c9, 0x80}, {0x37cb, 0x16}, {0x37cc, 0x16}, {0x37cd, 0x16}, {0x37ce, 0x16}, {0x3800, 0x00}, {0x3801, 0x00}, {0x3802, 0x00}, {0x3803, 0x0c}, {0x3804, 0x0c}, {0x3805, 0xdf}, {0x3806, 0x09}, {0x3807, 0xa3}, {0x3808, 0x0c}, {0x3809, 0xc0}, {0x380a, 0x09}, {0x380b, 0x90}, {0x380c, 0x07}, {0x380d, 0x8c}, {0x380e, 0x09}, {0x380f, 0xb2}, {0x3810, 0x00}, {0x3811, 0x04}, {0x3812, 0x00}, {0x3813, 0x02}, {0x3814, 0x01}, {0x3815, 0x01}, {0x3816, 0x00}, {0x3817, 0x00}, {0x3818, 0x00}, {0x3819, 0x10}, {0x3820, 0x80}, {0x3821, 0x46}, {0x382a, 0x01}, {0x382b, 0x01}, {0x3830, 0x06}, {0x3836, 0x02}, {0x3862, 0x04}, {0x3863, 0x08}, {0x3cc0, 0x33}, {0x3d85, 0x17}, {0x3d8c, 0x73}, {0x3d8d, 0xde}, {0x4001, 0xe0}, {0x4003, 0x40}, {0x4008, 0x00}, {0x4009, 0x0b}, {0x400a, 0x00}, {0x400b, 0x84}, {0x400f, 0x80}, {0x4010, 0xf0}, {0x4011, 0xff}, {0x4012, 0x02}, {0x4013, 0x01}, {0x4014, 0x01}, {0x4015, 0x01}, {0x4042, 0x00}, {0x4043, 0x80}, {0x4044, 0x00}, {0x4045, 0x80}, {0x4046, 0x00}, {0x4047, 0x80}, {0x4048, 0x00}, {0x4049, 0x80}, {0x4041, 0x03}, {0x404c, 0x20}, {0x404d, 0x00}, {0x404e, 0x20}, {0x4203, 0x80}, {0x4307, 0x30}, {0x4317, 0x00}, {0x4502, 0x50}, {0x4503, 0x08}, {0x4601, 0x80}, {0x4800, 0x44}, {0x4816, 0x53}, {0x481b, 0x50}, {0x481f, 0x27}, {0x4823, 0x3c}, {0x482b, 0x00}, {0x4831, 0x66}, {0x4837, 0x16}, {0x483c, 0x0f}, {0x484b, 0x05}, {0x5000, 0x77}, {0x5001, 0x0a}, {0x5003, 0xc8}, {0x5004, 0x04}, {0x5006, 0x00}, {0x5007, 0x00}, {0x502e, 0x03}, {0x5030, 0x41}, {0x5780, 0x14}, {0x5781, 0x0f}, {0x5782, 0x44}, {0x5783, 0x02}, {0x5784, 0x01}, {0x5785, 0x01}, {0x5786, 0x00}, {0x5787, 0x04}, {0x5788, 0x02}, {0x5789, 0x0f}, {0x578a, 0xfd}, {0x578b, 0xf5}, {0x578c, 0xf5}, {0x578d, 0x03}, {0x578e, 0x08}, {0x578f, 0x0c}, {0x5790, 0x08}, {0x5791, 0x04}, {0x5792, 0x00}, {0x5793, 0x52}, {0x5794, 0xa3}, {0x5795, 0x02}, {0x5796, 0x20}, {0x5797, 0x20}, {0x5798, 0xd5}, {0x5799, 0xd5}, {0x579a, 0x00}, {0x579b, 0x50}, {0x579c, 0x00}, {0x579d, 0x2c}, {0x579e, 0x0c}, {0x579f, 0x40}, {0x57a0, 0x09}, {0x57a1, 0x40}, {0x59f8, 0x3d}, {0x5a08, 0x02}, {0x5b00, 0x02}, {0x5b01, 0x10}, {0x5b02, 0x03}, {0x5b03, 0xcf}, {0x5b05, 0x6c}, {0x5e00, 0x00}, {0x5e10, 0xfc} }; static const struct ov8856_reg lane_4_mode_1632x1224[] = { /* 1632x1224 resolution */ {0x0103, 0x01}, {0x0302, 0x3c}, {0x0303, 0x01}, {0x031e, 0x0c}, {0x3000, 0x20}, {0x3003, 0x08}, {0x300e, 0x20}, {0x3010, 0x00}, {0x3015, 0x84}, {0x3018, 0x72}, {0x3021, 0x23}, {0x3033, 0x24}, {0x3500, 0x00}, {0x3501, 0x4c}, {0x3502, 0xe0}, {0x3503, 0x08}, {0x3505, 0x83}, {0x3508, 0x01}, {0x3509, 0x80}, {0x350c, 0x00}, {0x350d, 0x80}, {0x350e, 0x04}, {0x350f, 0x00}, {0x3510, 0x00}, {0x3511, 0x02}, {0x3512, 0x00}, {0x3600, 0x72}, {0x3601, 0x40}, {0x3602, 0x30}, {0x3610, 0xc5}, {0x3611, 0x58}, {0x3612, 0x5c}, {0x3613, 0xca}, {0x3614, 0x60}, {0x3628, 0xff}, {0x3629, 0xff}, {0x362a, 0xff}, {0x3633, 0x10}, {0x3634, 0x10}, {0x3635, 0x10}, {0x3636, 0x10}, {0x3663, 0x08}, {0x3669, 0x34}, {0x366d, 0x00}, {0x366e, 0x08}, {0x3706, 0x86}, {0x370b, 0x7e}, {0x3714, 0x27}, {0x3730, 0x12}, {0x3733, 0x10}, {0x3764, 0x00}, {0x3765, 0x00}, {0x3769, 0x62}, {0x376a, 0x2a}, {0x376b, 0x30}, {0x3780, 0x00}, {0x3781, 0x24}, {0x3782, 0x00}, {0x3783, 0x23}, {0x3798, 0x2f}, {0x37a1, 0x60}, {0x37a8, 0x6a}, {0x37ab, 0x3f}, {0x37c2, 0x14}, {0x37c3, 0xf1}, {0x37c9, 0x80}, {0x37cb, 0x16}, {0x37cc, 0x16}, {0x37cd, 0x16}, {0x37ce, 0x16}, {0x3800, 0x00}, {0x3801, 0x00}, {0x3802, 0x00}, {0x3803, 0x0c}, {0x3804, 0x0c}, {0x3805, 0xdf}, {0x3806, 0x09}, {0x3807, 0xa3}, {0x3808, 0x06}, {0x3809, 0x60}, {0x380a, 0x04}, {0x380b, 0xc8}, {0x380c, 0x07}, {0x380d, 0x8c}, {0x380e, 0x09}, {0x380f, 0xb2}, {0x3810, 0x00}, {0x3811, 0x02}, {0x3812, 0x00}, {0x3813, 0x02}, {0x3814, 0x03}, {0x3815, 0x01}, {0x3816, 0x00}, {0x3817, 0x00}, {0x3818, 0x00}, {0x3819, 0x10}, {0x3820, 0x80}, {0x3821, 0x47}, {0x382a, 0x03}, {0x382b, 0x01}, {0x3830, 0x06}, {0x3836, 0x02}, {0x3862, 0x04}, {0x3863, 0x08}, {0x3cc0, 0x33}, {0x3d85, 0x17}, {0x3d8c, 0x73}, {0x3d8d, 0xde}, {0x4001, 0xe0}, {0x4003, 0x40}, {0x4008, 0x00}, {0x4009, 0x05}, {0x400a, 0x00}, {0x400b, 0x84}, {0x400f, 0x80}, {0x4010, 0xf0}, {0x4011, 0xff}, {0x4012, 0x02}, {0x4013, 0x01}, {0x4014, 0x01}, {0x4015, 0x01}, {0x4042, 0x00}, {0x4043, 0x80}, {0x4044, 0x00}, {0x4045, 0x80}, {0x4046, 0x00}, {0x4047, 0x80}, {0x4048, 0x00}, {0x4049, 0x80}, {0x4041, 0x03}, {0x404c, 0x20}, {0x404d, 0x00}, {0x404e, 0x20}, {0x4203, 0x80}, {0x4307, 0x30}, {0x4317, 0x00}, {0x4502, 0x50}, {0x4503, 0x08}, {0x4601, 0x80}, {0x4800, 0x44}, {0x4816, 0x53}, {0x481b, 0x50}, {0x481f, 0x27}, {0x4823, 0x3c}, {0x482b, 0x00}, {0x4831, 0x66}, {0x4837, 0x16}, {0x483c, 0x0f}, {0x484b, 0x05}, {0x5000, 0x77}, {0x5001, 0x0a}, {0x5003, 0xc8}, {0x5004, 0x04}, {0x5006, 0x00}, {0x5007, 0x00}, {0x502e, 0x03}, {0x5030, 0x41}, {0x5795, 0x00}, {0x5796, 0x10}, {0x5797, 0x10}, {0x5798, 0x73}, {0x5799, 0x73}, {0x579a, 0x00}, {0x579b, 0x28}, {0x579c, 0x00}, {0x579d, 0x16}, {0x579e, 0x06}, {0x579f, 0x20}, {0x57a0, 0x04}, {0x57a1, 0xa0}, {0x5780, 0x14}, {0x5781, 0x0f}, {0x5782, 0x44}, {0x5783, 0x02}, {0x5784, 0x01}, {0x5785, 0x01}, {0x5786, 0x00}, {0x5787, 0x04}, {0x5788, 0x02}, {0x5789, 0x0f}, {0x578a, 0xfd}, {0x578b, 0xf5}, {0x578c, 0xf5}, {0x578d, 0x03}, {0x578e, 0x08}, {0x578f, 0x0c}, {0x5790, 0x08}, {0x5791, 0x04}, {0x5792, 0x00}, {0x5793, 0x52}, {0x5794, 0xa3}, {0x59f8, 0x3d}, {0x5a08, 0x02}, {0x5b00, 0x02}, {0x5b01, 0x10}, {0x5b02, 0x03}, {0x5b03, 0xcf}, {0x5b05, 0x6c}, {0x5e00, 0x00}, {0x5e10, 0xfc} }; static const struct ov8856_reg mipi_data_mbus_sbggr10_1x10[] = { {0x3813, 0x02}, }; static const struct ov8856_reg mipi_data_mbus_sgrbg10_1x10[] = { {0x3813, 0x01}, }; static const u32 ov8856_mbus_codes[] = { MEDIA_BUS_FMT_SBGGR10_1X10, MEDIA_BUS_FMT_SGRBG10_1X10 }; static const char * const ov8856_test_pattern_menu[] = { "Disabled", "Standard Color Bar", "Top-Bottom Darker Color Bar", "Right-Left Darker Color Bar", "Bottom-Top Darker Color Bar" }; static const struct ov8856_reg_list bayer_offset_configs[] = { [OV8856_MEDIA_BUS_FMT_SBGGR10_1X10] = { .num_of_regs = ARRAY_SIZE(mipi_data_mbus_sbggr10_1x10), .regs = mipi_data_mbus_sbggr10_1x10, }, [OV8856_MEDIA_BUS_FMT_SGRBG10_1X10] = { .num_of_regs = ARRAY_SIZE(mipi_data_mbus_sgrbg10_1x10), .regs = mipi_data_mbus_sgrbg10_1x10, } }; struct ov8856 { struct v4l2_subdev sd; struct media_pad pad; struct v4l2_ctrl_handler ctrl_handler; struct clk *xvclk; struct gpio_desc *reset_gpio; struct regulator_bulk_data supplies[ARRAY_SIZE(ov8856_supply_names)]; /* V4L2 Controls */ struct v4l2_ctrl *link_freq; struct v4l2_ctrl *pixel_rate; struct v4l2_ctrl *vblank; struct v4l2_ctrl *hblank; struct v4l2_ctrl *exposure; /* Current mode */ const struct ov8856_mode *cur_mode; /* Application specified mbus format */ u32 cur_mbus_index; /* To serialize asynchronus callbacks */ struct mutex mutex; /* Streaming on/off */ bool streaming; /* lanes index */ u8 nlanes; const struct ov8856_lane_cfg *priv_lane; u8 modes_size; /* True if the device has been identified */ bool identified; }; struct ov8856_lane_cfg { const s64 link_freq_menu_items[2]; const struct ov8856_link_freq_config link_freq_configs[2]; const struct ov8856_mode supported_modes[4]; }; static const struct ov8856_lane_cfg lane_cfg_2 = { { 720000000, 360000000, }, {{ .reg_list = { .num_of_regs = ARRAY_SIZE(mipi_data_rate_lane_2.regs_0), .regs = mipi_data_rate_lane_2.regs_0, } }, { .reg_list = { .num_of_regs = ARRAY_SIZE(mipi_data_rate_lane_2.regs_1), .regs = mipi_data_rate_lane_2.regs_1, } }}, {{ .width = 3280, .height = 2464, .hts = 1928, .vts_def = 2488, .vts_min = 2488, .reg_list = { .num_of_regs = ARRAY_SIZE(lane_2_mode_3280x2464), .regs = lane_2_mode_3280x2464, }, .link_freq_index = 0, .data_lanes = 2, .default_mbus_index = OV8856_MEDIA_BUS_FMT_SGRBG10_1X10, }, { .width = 1640, .height = 1232, .hts = 3168, .vts_def = 1514, .vts_min = 1514, .reg_list = { .num_of_regs = ARRAY_SIZE(lane_2_mode_1640x1232), .regs = lane_2_mode_1640x1232, }, .link_freq_index = 1, .data_lanes = 2, .default_mbus_index = OV8856_MEDIA_BUS_FMT_SGRBG10_1X10, }} }; static const struct ov8856_lane_cfg lane_cfg_4 = { { 360000000, 180000000, }, {{ .reg_list = { .num_of_regs = ARRAY_SIZE(mipi_data_rate_lane_4.regs_0), .regs = mipi_data_rate_lane_4.regs_0, } }, { .reg_list = { .num_of_regs = ARRAY_SIZE(mipi_data_rate_lane_4.regs_1), .regs = mipi_data_rate_lane_4.regs_1, } }}, {{ .width = 3280, .height = 2464, .hts = 1928, .vts_def = 2488, .vts_min = 2488, .reg_list = { .num_of_regs = ARRAY_SIZE(lane_4_mode_3280x2464), .regs = lane_4_mode_3280x2464, }, .link_freq_index = 0, .data_lanes = 4, .default_mbus_index = OV8856_MEDIA_BUS_FMT_SGRBG10_1X10, }, { .width = 1640, .height = 1232, .hts = 3820, .vts_def = 1256, .vts_min = 1256, .reg_list = { .num_of_regs = ARRAY_SIZE(lane_4_mode_1640x1232), .regs = lane_4_mode_1640x1232, }, .link_freq_index = 1, .data_lanes = 4, .default_mbus_index = OV8856_MEDIA_BUS_FMT_SGRBG10_1X10, }, { .width = 3264, .height = 2448, .hts = 1932, .vts_def = 2482, .vts_min = 2482, .reg_list = { .num_of_regs = ARRAY_SIZE(lane_4_mode_3264x2448), .regs = lane_4_mode_3264x2448, }, .link_freq_index = 0, .data_lanes = 4, .default_mbus_index = OV8856_MEDIA_BUS_FMT_SBGGR10_1X10, }, { .width = 1632, .height = 1224, .hts = 1932, .vts_def = 2482, .vts_min = 2482, .reg_list = { .num_of_regs = ARRAY_SIZE(lane_4_mode_1632x1224), .regs = lane_4_mode_1632x1224, }, .link_freq_index = 1, .data_lanes = 4, .default_mbus_index = OV8856_MEDIA_BUS_FMT_SBGGR10_1X10, }} }; static unsigned int ov8856_modes_num(const struct ov8856 *ov8856) { unsigned int i, count = 0; for (i = 0; i < ARRAY_SIZE(ov8856->priv_lane->supported_modes); i++) { if (ov8856->priv_lane->supported_modes[i].width == 0) break; count++; } return count; } static u64 to_rate(const s64 *link_freq_menu_items, u32 f_index, u8 nlanes) { u64 pixel_rate = link_freq_menu_items[f_index] * 2 * nlanes; do_div(pixel_rate, OV8856_RGB_DEPTH); return pixel_rate; } static u64 to_pixels_per_line(const s64 *link_freq_menu_items, u32 hts, u32 f_index, u8 nlanes) { u64 ppl = hts * to_rate(link_freq_menu_items, f_index, nlanes); do_div(ppl, OV8856_SCLK); return ppl; } static int ov8856_read_reg(struct ov8856 *ov8856, u16 reg, u16 len, u32 *val) { struct i2c_client *client = v4l2_get_subdevdata(&ov8856->sd); struct i2c_msg msgs[2]; u8 addr_buf[2]; u8 data_buf[4] = {0}; int ret; if (len > 4) return -EINVAL; put_unaligned_be16(reg, addr_buf); msgs[0].addr = client->addr; msgs[0].flags = 0; msgs[0].len = sizeof(addr_buf); msgs[0].buf = addr_buf; msgs[1].addr = client->addr; msgs[1].flags = I2C_M_RD; msgs[1].len = len; msgs[1].buf = &data_buf[4 - len]; ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs)); if (ret != ARRAY_SIZE(msgs)) return -EIO; *val = get_unaligned_be32(data_buf); return 0; } static int ov8856_write_reg(struct ov8856 *ov8856, u16 reg, u16 len, u32 val) { struct i2c_client *client = v4l2_get_subdevdata(&ov8856->sd); u8 buf[6]; if (len > 4) return -EINVAL; put_unaligned_be16(reg, buf); put_unaligned_be32(val << 8 * (4 - len), buf + 2); if (i2c_master_send(client, buf, len + 2) != len + 2) return -EIO; return 0; } static int ov8856_write_reg_list(struct ov8856 *ov8856, const struct ov8856_reg_list *r_list) { struct i2c_client *client = v4l2_get_subdevdata(&ov8856->sd); unsigned int i; int ret; for (i = 0; i < r_list->num_of_regs; i++) { ret = ov8856_write_reg(ov8856, r_list->regs[i].address, 1, r_list->regs[i].val); if (ret) { dev_err_ratelimited(&client->dev, "failed to write reg 0x%4.4x. error = %d", r_list->regs[i].address, ret); return ret; } } return 0; } static int ov8856_identify_module(struct ov8856 *ov8856) { struct i2c_client *client = v4l2_get_subdevdata(&ov8856->sd); int ret; u32 val; if (ov8856->identified) return 0; ret = ov8856_read_reg(ov8856, OV8856_REG_CHIP_ID, OV8856_REG_VALUE_24BIT, &val); if (ret) return ret; if (val != OV8856_CHIP_ID) { dev_err(&client->dev, "chip id mismatch: %x!=%x", OV8856_CHIP_ID, val); return -ENXIO; } ov8856->identified = true; return 0; } static int ov8856_update_digital_gain(struct ov8856 *ov8856, u32 d_gain) { return ov8856_write_reg(ov8856, OV8856_REG_DIGITAL_GAIN, OV8856_REG_VALUE_16BIT, d_gain); } static int ov8856_test_pattern(struct ov8856 *ov8856, u32 pattern) { if (pattern) pattern = (pattern - 1) << OV8856_TEST_PATTERN_BAR_SHIFT | OV8856_TEST_PATTERN_ENABLE; return ov8856_write_reg(ov8856, OV8856_REG_TEST_PATTERN, OV8856_REG_VALUE_08BIT, pattern); } static int ov8856_set_ctrl_hflip(struct ov8856 *ov8856, u32 ctrl_val) { int ret; u32 val; ret = ov8856_read_reg(ov8856, OV8856_REG_MIRROR_OPT_1, OV8856_REG_VALUE_08BIT, &val); if (ret) return ret; ret = ov8856_write_reg(ov8856, OV8856_REG_MIRROR_OPT_1, OV8856_REG_VALUE_08BIT, ctrl_val ? val & ~OV8856_REG_MIRROR_OP_2 : val | OV8856_REG_MIRROR_OP_2); if (ret) return ret; ret = ov8856_read_reg(ov8856, OV8856_REG_FORMAT2, OV8856_REG_VALUE_08BIT, &val); if (ret) return ret; return ov8856_write_reg(ov8856, OV8856_REG_FORMAT2, OV8856_REG_VALUE_08BIT, ctrl_val ? val & ~OV8856_REG_FORMAT2_OP_1 & ~OV8856_REG_FORMAT2_OP_2 & ~OV8856_REG_FORMAT2_OP_3 : val | OV8856_REG_FORMAT2_OP_1 | OV8856_REG_FORMAT2_OP_2 | OV8856_REG_FORMAT2_OP_3); } static int ov8856_set_ctrl_vflip(struct ov8856 *ov8856, u8 ctrl_val) { int ret; u32 val; ret = ov8856_read_reg(ov8856, OV8856_REG_FLIP_OPT_1, OV8856_REG_VALUE_08BIT, &val); if (ret) return ret; ret = ov8856_write_reg(ov8856, OV8856_REG_FLIP_OPT_1, OV8856_REG_VALUE_08BIT, ctrl_val ? val | OV8856_REG_FLIP_OP_1 | OV8856_REG_FLIP_OP_2 : val & ~OV8856_REG_FLIP_OP_1 & ~OV8856_REG_FLIP_OP_2); ret = ov8856_read_reg(ov8856, OV8856_REG_FLIP_OPT_2, OV8856_REG_VALUE_08BIT, &val); if (ret) return ret; ret = ov8856_write_reg(ov8856, OV8856_REG_FLIP_OPT_2, OV8856_REG_VALUE_08BIT, ctrl_val ? val | OV8856_REG_FLIP_OP_2 : val & ~OV8856_REG_FLIP_OP_2); ret = ov8856_read_reg(ov8856, OV8856_REG_FLIP_OPT_3, OV8856_REG_VALUE_08BIT, &val); if (ret) return ret; ret = ov8856_write_reg(ov8856, OV8856_REG_FLIP_OPT_3, OV8856_REG_VALUE_08BIT, ctrl_val ? val & ~OV8856_REG_FLIP_OP_0 & ~OV8856_REG_FLIP_OP_1 : val | OV8856_REG_FLIP_OP_0 | OV8856_REG_FLIP_OP_1); ret = ov8856_read_reg(ov8856, OV8856_REG_FORMAT1, OV8856_REG_VALUE_08BIT, &val); if (ret) return ret; return ov8856_write_reg(ov8856, OV8856_REG_FORMAT1, OV8856_REG_VALUE_08BIT, ctrl_val ? val | OV8856_REG_FORMAT1_OP_1 | OV8856_REG_FORMAT1_OP_3 | OV8856_REG_FORMAT1_OP_2 : val & ~OV8856_REG_FORMAT1_OP_1 & ~OV8856_REG_FORMAT1_OP_3 & ~OV8856_REG_FORMAT1_OP_2); } static int ov8856_set_ctrl(struct v4l2_ctrl *ctrl) { struct ov8856 *ov8856 = container_of(ctrl->handler, struct ov8856, ctrl_handler); struct i2c_client *client = v4l2_get_subdevdata(&ov8856->sd); s64 exposure_max; int ret = 0; /* Propagate change of current control to all related controls */ if (ctrl->id == V4L2_CID_VBLANK) { /* Update max exposure while meeting expected vblanking */ exposure_max = ov8856->cur_mode->height + ctrl->val - OV8856_EXPOSURE_MAX_MARGIN; __v4l2_ctrl_modify_range(ov8856->exposure, ov8856->exposure->minimum, exposure_max, ov8856->exposure->step, exposure_max); } /* V4L2 controls values will be applied only when power is already up */ if (!pm_runtime_get_if_in_use(&client->dev)) return 0; switch (ctrl->id) { case V4L2_CID_ANALOGUE_GAIN: ret = ov8856_write_reg(ov8856, OV8856_REG_ANALOG_GAIN, OV8856_REG_VALUE_16BIT, ctrl->val); break; case V4L2_CID_DIGITAL_GAIN: ret = ov8856_update_digital_gain(ov8856, ctrl->val); break; case V4L2_CID_EXPOSURE: /* 4 least significant bits of expsoure are fractional part */ ret = ov8856_write_reg(ov8856, OV8856_REG_EXPOSURE, OV8856_REG_VALUE_24BIT, ctrl->val << 4); break; case V4L2_CID_VBLANK: ret = ov8856_write_reg(ov8856, OV8856_REG_VTS, OV8856_REG_VALUE_16BIT, ov8856->cur_mode->height + ctrl->val); break; case V4L2_CID_TEST_PATTERN: ret = ov8856_test_pattern(ov8856, ctrl->val); break; case V4L2_CID_HFLIP: ret = ov8856_set_ctrl_hflip(ov8856, ctrl->val); break; case V4L2_CID_VFLIP: ret = ov8856_set_ctrl_vflip(ov8856, ctrl->val); break; default: ret = -EINVAL; break; } pm_runtime_put(&client->dev); return ret; } static const struct v4l2_ctrl_ops ov8856_ctrl_ops = { .s_ctrl = ov8856_set_ctrl, }; static int ov8856_init_controls(struct ov8856 *ov8856) { struct v4l2_ctrl_handler *ctrl_hdlr; s64 exposure_max, h_blank; int ret; ctrl_hdlr = &ov8856->ctrl_handler; ret = v4l2_ctrl_handler_init(ctrl_hdlr, 8); if (ret) return ret; ctrl_hdlr->lock = &ov8856->mutex; ov8856->link_freq = v4l2_ctrl_new_int_menu(ctrl_hdlr, &ov8856_ctrl_ops, V4L2_CID_LINK_FREQ, ARRAY_SIZE (ov8856->priv_lane->link_freq_menu_items) - 1, 0, ov8856->priv_lane->link_freq_menu_items); if (ov8856->link_freq) ov8856->link_freq->flags |= V4L2_CTRL_FLAG_READ_ONLY; ov8856->pixel_rate = v4l2_ctrl_new_std(ctrl_hdlr, &ov8856_ctrl_ops, V4L2_CID_PIXEL_RATE, 0, to_rate(ov8856->priv_lane->link_freq_menu_items, 0, ov8856->cur_mode->data_lanes), 1, to_rate(ov8856->priv_lane->link_freq_menu_items, 0, ov8856->cur_mode->data_lanes)); ov8856->vblank = v4l2_ctrl_new_std(ctrl_hdlr, &ov8856_ctrl_ops, V4L2_CID_VBLANK, ov8856->cur_mode->vts_min - ov8856->cur_mode->height, OV8856_VTS_MAX - ov8856->cur_mode->height, 1, ov8856->cur_mode->vts_def - ov8856->cur_mode->height); h_blank = to_pixels_per_line(ov8856->priv_lane->link_freq_menu_items, ov8856->cur_mode->hts, ov8856->cur_mode->link_freq_index, ov8856->cur_mode->data_lanes) - ov8856->cur_mode->width; ov8856->hblank = v4l2_ctrl_new_std(ctrl_hdlr, &ov8856_ctrl_ops, V4L2_CID_HBLANK, h_blank, h_blank, 1, h_blank); if (ov8856->hblank) ov8856->hblank->flags |= V4L2_CTRL_FLAG_READ_ONLY; v4l2_ctrl_new_std(ctrl_hdlr, &ov8856_ctrl_ops, V4L2_CID_ANALOGUE_GAIN, OV8856_ANAL_GAIN_MIN, OV8856_ANAL_GAIN_MAX, OV8856_ANAL_GAIN_STEP, OV8856_ANAL_GAIN_MIN); v4l2_ctrl_new_std(ctrl_hdlr, &ov8856_ctrl_ops, V4L2_CID_DIGITAL_GAIN, OV8856_DGTL_GAIN_MIN, OV8856_DGTL_GAIN_MAX, OV8856_DGTL_GAIN_STEP, OV8856_DGTL_GAIN_DEFAULT); exposure_max = ov8856->cur_mode->vts_def - OV8856_EXPOSURE_MAX_MARGIN; ov8856->exposure = v4l2_ctrl_new_std(ctrl_hdlr, &ov8856_ctrl_ops, V4L2_CID_EXPOSURE, OV8856_EXPOSURE_MIN, exposure_max, OV8856_EXPOSURE_STEP, exposure_max); v4l2_ctrl_new_std_menu_items(ctrl_hdlr, &ov8856_ctrl_ops, V4L2_CID_TEST_PATTERN, ARRAY_SIZE(ov8856_test_pattern_menu) - 1, 0, 0, ov8856_test_pattern_menu); v4l2_ctrl_new_std(ctrl_hdlr, &ov8856_ctrl_ops, V4L2_CID_HFLIP, 0, 1, 1, 0); v4l2_ctrl_new_std(ctrl_hdlr, &ov8856_ctrl_ops, V4L2_CID_VFLIP, 0, 1, 1, 0); if (ctrl_hdlr->error) return ctrl_hdlr->error; ov8856->sd.ctrl_handler = ctrl_hdlr; return 0; } static void ov8856_update_pad_format(struct ov8856 *ov8856, const struct ov8856_mode *mode, struct v4l2_mbus_framefmt *fmt) { int index; fmt->width = mode->width; fmt->height = mode->height; for (index = 0; index < ARRAY_SIZE(ov8856_mbus_codes); ++index) if (ov8856_mbus_codes[index] == fmt->code) break; if (index == ARRAY_SIZE(ov8856_mbus_codes)) index = mode->default_mbus_index; fmt->code = ov8856_mbus_codes[index]; ov8856->cur_mbus_index = index; fmt->field = V4L2_FIELD_NONE; } static int ov8856_start_streaming(struct ov8856 *ov8856) { struct i2c_client *client = v4l2_get_subdevdata(&ov8856->sd); const struct ov8856_reg_list *reg_list; int link_freq_index, ret; ret = ov8856_identify_module(ov8856); if (ret) return ret; link_freq_index = ov8856->cur_mode->link_freq_index; reg_list = &ov8856->priv_lane->link_freq_configs[link_freq_index].reg_list; ret = ov8856_write_reg_list(ov8856, reg_list); if (ret) { dev_err(&client->dev, "failed to set plls"); return ret; } reg_list = &ov8856->cur_mode->reg_list; ret = ov8856_write_reg_list(ov8856, reg_list); if (ret) { dev_err(&client->dev, "failed to set mode"); return ret; } reg_list = &bayer_offset_configs[ov8856->cur_mbus_index]; ret = ov8856_write_reg_list(ov8856, reg_list); if (ret) { dev_err(&client->dev, "failed to set mbus format"); return ret; } ret = __v4l2_ctrl_handler_setup(ov8856->sd.ctrl_handler); if (ret) return ret; ret = ov8856_write_reg(ov8856, OV8856_REG_MODE_SELECT, OV8856_REG_VALUE_08BIT, OV8856_MODE_STREAMING); if (ret) { dev_err(&client->dev, "failed to set stream"); return ret; } return 0; } static void ov8856_stop_streaming(struct ov8856 *ov8856) { struct i2c_client *client = v4l2_get_subdevdata(&ov8856->sd); if (ov8856_write_reg(ov8856, OV8856_REG_MODE_SELECT, OV8856_REG_VALUE_08BIT, OV8856_MODE_STANDBY)) dev_err(&client->dev, "failed to set stream"); } static int ov8856_set_stream(struct v4l2_subdev *sd, int enable) { struct ov8856 *ov8856 = to_ov8856(sd); struct i2c_client *client = v4l2_get_subdevdata(sd); int ret = 0; if (ov8856->streaming == enable) return 0; mutex_lock(&ov8856->mutex); if (enable) { ret = pm_runtime_resume_and_get(&client->dev); if (ret < 0) { mutex_unlock(&ov8856->mutex); return ret; } ret = ov8856_start_streaming(ov8856); if (ret) { enable = 0; ov8856_stop_streaming(ov8856); pm_runtime_put(&client->dev); } } else { ov8856_stop_streaming(ov8856); pm_runtime_put(&client->dev); } ov8856->streaming = enable; mutex_unlock(&ov8856->mutex); return ret; } static int ov8856_power_on(struct device *dev) { struct v4l2_subdev *sd = dev_get_drvdata(dev); struct ov8856 *ov8856 = to_ov8856(sd); int ret; if (is_acpi_node(dev_fwnode(dev))) return 0; ret = clk_prepare_enable(ov8856->xvclk); if (ret < 0) { dev_err(dev, "failed to enable xvclk\n"); return ret; } if (ov8856->reset_gpio) { gpiod_set_value_cansleep(ov8856->reset_gpio, 1); usleep_range(1000, 2000); } ret = regulator_bulk_enable(ARRAY_SIZE(ov8856_supply_names), ov8856->supplies); if (ret < 0) { dev_err(dev, "failed to enable regulators\n"); goto disable_clk; } gpiod_set_value_cansleep(ov8856->reset_gpio, 0); usleep_range(1500, 1800); return 0; disable_clk: gpiod_set_value_cansleep(ov8856->reset_gpio, 1); clk_disable_unprepare(ov8856->xvclk); return ret; } static int ov8856_power_off(struct device *dev) { struct v4l2_subdev *sd = dev_get_drvdata(dev); struct ov8856 *ov8856 = to_ov8856(sd); if (is_acpi_node(dev_fwnode(dev))) return 0; gpiod_set_value_cansleep(ov8856->reset_gpio, 1); regulator_bulk_disable(ARRAY_SIZE(ov8856_supply_names), ov8856->supplies); clk_disable_unprepare(ov8856->xvclk); return 0; } static int __maybe_unused ov8856_suspend(struct device *dev) { struct v4l2_subdev *sd = dev_get_drvdata(dev); struct ov8856 *ov8856 = to_ov8856(sd); mutex_lock(&ov8856->mutex); if (ov8856->streaming) ov8856_stop_streaming(ov8856); ov8856_power_off(dev); mutex_unlock(&ov8856->mutex); return 0; } static int __maybe_unused ov8856_resume(struct device *dev) { struct v4l2_subdev *sd = dev_get_drvdata(dev); struct ov8856 *ov8856 = to_ov8856(sd); int ret; mutex_lock(&ov8856->mutex); ov8856_power_on(dev); if (ov8856->streaming) { ret = ov8856_start_streaming(ov8856); if (ret) { ov8856->streaming = false; ov8856_stop_streaming(ov8856); mutex_unlock(&ov8856->mutex); return ret; } } mutex_unlock(&ov8856->mutex); return 0; } static int ov8856_set_format(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *fmt) { struct ov8856 *ov8856 = to_ov8856(sd); const struct ov8856_mode *mode; s32 vblank_def, h_blank; mode = v4l2_find_nearest_size(ov8856->priv_lane->supported_modes, ov8856->modes_size, width, height, fmt->format.width, fmt->format.height); mutex_lock(&ov8856->mutex); ov8856_update_pad_format(ov8856, mode, &fmt->format); if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) { *v4l2_subdev_get_try_format(sd, sd_state, fmt->pad) = fmt->format; } else { ov8856->cur_mode = mode; __v4l2_ctrl_s_ctrl(ov8856->link_freq, mode->link_freq_index); __v4l2_ctrl_s_ctrl_int64(ov8856->pixel_rate, to_rate(ov8856->priv_lane->link_freq_menu_items, mode->link_freq_index, ov8856->cur_mode->data_lanes)); /* Update limits and set FPS to default */ vblank_def = mode->vts_def - mode->height; __v4l2_ctrl_modify_range(ov8856->vblank, mode->vts_min - mode->height, OV8856_VTS_MAX - mode->height, 1, vblank_def); __v4l2_ctrl_s_ctrl(ov8856->vblank, vblank_def); h_blank = to_pixels_per_line(ov8856->priv_lane->link_freq_menu_items, mode->hts, mode->link_freq_index, ov8856->cur_mode->data_lanes) - mode->width; __v4l2_ctrl_modify_range(ov8856->hblank, h_blank, h_blank, 1, h_blank); } mutex_unlock(&ov8856->mutex); return 0; } static int ov8856_get_format(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *fmt) { struct ov8856 *ov8856 = to_ov8856(sd); mutex_lock(&ov8856->mutex); if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) fmt->format = *v4l2_subdev_get_try_format(&ov8856->sd, sd_state, fmt->pad); else ov8856_update_pad_format(ov8856, ov8856->cur_mode, &fmt->format); mutex_unlock(&ov8856->mutex); return 0; } static int ov8856_enum_mbus_code(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_mbus_code_enum *code) { if (code->index >= ARRAY_SIZE(ov8856_mbus_codes)) return -EINVAL; code->code = ov8856_mbus_codes[code->index]; return 0; } static int ov8856_enum_frame_size(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_frame_size_enum *fse) { struct ov8856 *ov8856 = to_ov8856(sd); int index; if (fse->index >= ov8856->modes_size) return -EINVAL; for (index = 0; index < ARRAY_SIZE(ov8856_mbus_codes); ++index) if (fse->code == ov8856_mbus_codes[index]) break; if (index == ARRAY_SIZE(ov8856_mbus_codes)) return -EINVAL; fse->min_width = ov8856->priv_lane->supported_modes[fse->index].width; fse->max_width = fse->min_width; fse->min_height = ov8856->priv_lane->supported_modes[fse->index].height; fse->max_height = fse->min_height; return 0; } static int ov8856_open(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh) { struct ov8856 *ov8856 = to_ov8856(sd); mutex_lock(&ov8856->mutex); ov8856_update_pad_format(ov8856, &ov8856->priv_lane->supported_modes[0], v4l2_subdev_get_try_format(sd, fh->state, 0)); mutex_unlock(&ov8856->mutex); return 0; } static const struct v4l2_subdev_video_ops ov8856_video_ops = { .s_stream = ov8856_set_stream, }; static const struct v4l2_subdev_pad_ops ov8856_pad_ops = { .set_fmt = ov8856_set_format, .get_fmt = ov8856_get_format, .enum_mbus_code = ov8856_enum_mbus_code, .enum_frame_size = ov8856_enum_frame_size, }; static const struct v4l2_subdev_ops ov8856_subdev_ops = { .video = &ov8856_video_ops, .pad = &ov8856_pad_ops, }; static const struct media_entity_operations ov8856_subdev_entity_ops = { .link_validate = v4l2_subdev_link_validate, }; static const struct v4l2_subdev_internal_ops ov8856_internal_ops = { .open = ov8856_open, }; static int ov8856_get_hwcfg(struct ov8856 *ov8856, struct device *dev) { struct fwnode_handle *ep; struct fwnode_handle *fwnode = dev_fwnode(dev); struct v4l2_fwnode_endpoint bus_cfg = { .bus_type = V4L2_MBUS_CSI2_DPHY }; u32 xvclk_rate; int ret; unsigned int i, j; if (!fwnode) return -ENXIO; ret = fwnode_property_read_u32(fwnode, "clock-frequency", &xvclk_rate); if (ret) return ret; if (!is_acpi_node(fwnode)) { ov8856->xvclk = devm_clk_get(dev, "xvclk"); if (IS_ERR(ov8856->xvclk)) { dev_err(dev, "could not get xvclk clock (%pe)\n", ov8856->xvclk); return PTR_ERR(ov8856->xvclk); } clk_set_rate(ov8856->xvclk, xvclk_rate); xvclk_rate = clk_get_rate(ov8856->xvclk); ov8856->reset_gpio = devm_gpiod_get_optional(dev, "reset", GPIOD_OUT_LOW); if (IS_ERR(ov8856->reset_gpio)) return PTR_ERR(ov8856->reset_gpio); for (i = 0; i < ARRAY_SIZE(ov8856_supply_names); i++) ov8856->supplies[i].supply = ov8856_supply_names[i]; ret = devm_regulator_bulk_get(dev, ARRAY_SIZE(ov8856_supply_names), ov8856->supplies); if (ret) return ret; } if (xvclk_rate != OV8856_XVCLK_19_2) dev_warn(dev, "external clock rate %u is unsupported", xvclk_rate); ep = fwnode_graph_get_next_endpoint(fwnode, NULL); if (!ep) return -ENXIO; ret = v4l2_fwnode_endpoint_alloc_parse(ep, &bus_cfg); fwnode_handle_put(ep); if (ret) return ret; /* Get number of data lanes */ if (bus_cfg.bus.mipi_csi2.num_data_lanes != 2 && bus_cfg.bus.mipi_csi2.num_data_lanes != 4) { dev_err(dev, "number of CSI2 data lanes %d is not supported", bus_cfg.bus.mipi_csi2.num_data_lanes); ret = -EINVAL; goto check_hwcfg_error; } dev_dbg(dev, "Using %u data lanes\n", ov8856->cur_mode->data_lanes); if (bus_cfg.bus.mipi_csi2.num_data_lanes == 2) ov8856->priv_lane = &lane_cfg_2; else ov8856->priv_lane = &lane_cfg_4; ov8856->modes_size = ov8856_modes_num(ov8856); if (!bus_cfg.nr_of_link_frequencies) { dev_err(dev, "no link frequencies defined"); ret = -EINVAL; goto check_hwcfg_error; } for (i = 0; i < ARRAY_SIZE(ov8856->priv_lane->link_freq_menu_items); i++) { for (j = 0; j < bus_cfg.nr_of_link_frequencies; j++) { if (ov8856->priv_lane->link_freq_menu_items[i] == bus_cfg.link_frequencies[j]) break; } if (j == bus_cfg.nr_of_link_frequencies) { dev_err(dev, "no link frequency %lld supported", ov8856->priv_lane->link_freq_menu_items[i]); ret = -EINVAL; goto check_hwcfg_error; } } check_hwcfg_error: v4l2_fwnode_endpoint_free(&bus_cfg); return ret; } static void ov8856_remove(struct i2c_client *client) { struct v4l2_subdev *sd = i2c_get_clientdata(client); struct ov8856 *ov8856 = to_ov8856(sd); v4l2_async_unregister_subdev(sd); media_entity_cleanup(&sd->entity); v4l2_ctrl_handler_free(sd->ctrl_handler); pm_runtime_disable(&client->dev); mutex_destroy(&ov8856->mutex); ov8856_power_off(&client->dev); } static int ov8856_probe(struct i2c_client *client) { struct ov8856 *ov8856; int ret; bool full_power; ov8856 = devm_kzalloc(&client->dev, sizeof(*ov8856), GFP_KERNEL); if (!ov8856) return -ENOMEM; ret = ov8856_get_hwcfg(ov8856, &client->dev); if (ret) { dev_err(&client->dev, "failed to get HW configuration: %d", ret); return ret; } v4l2_i2c_subdev_init(&ov8856->sd, client, &ov8856_subdev_ops); full_power = acpi_dev_state_d0(&client->dev); if (full_power) { ret = ov8856_power_on(&client->dev); if (ret) { dev_err(&client->dev, "failed to power on\n"); return ret; } ret = ov8856_identify_module(ov8856); if (ret) { dev_err(&client->dev, "failed to find sensor: %d", ret); goto probe_power_off; } } mutex_init(&ov8856->mutex); ov8856->cur_mode = &ov8856->priv_lane->supported_modes[0]; ov8856->cur_mbus_index = ov8856->cur_mode->default_mbus_index; ret = ov8856_init_controls(ov8856); if (ret) { dev_err(&client->dev, "failed to init controls: %d", ret); goto probe_error_v4l2_ctrl_handler_free; } ov8856->sd.internal_ops = &ov8856_internal_ops; ov8856->sd.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE; ov8856->sd.entity.ops = &ov8856_subdev_entity_ops; ov8856->sd.entity.function = MEDIA_ENT_F_CAM_SENSOR; ov8856->pad.flags = MEDIA_PAD_FL_SOURCE; ret = media_entity_pads_init(&ov8856->sd.entity, 1, &ov8856->pad); if (ret) { dev_err(&client->dev, "failed to init entity pads: %d", ret); goto probe_error_v4l2_ctrl_handler_free; } ret = v4l2_async_register_subdev_sensor(&ov8856->sd); if (ret < 0) { dev_err(&client->dev, "failed to register V4L2 subdev: %d", ret); goto probe_error_media_entity_cleanup; } /* Set the device's state to active if it's in D0 state. */ if (full_power) pm_runtime_set_active(&client->dev); pm_runtime_enable(&client->dev); pm_runtime_idle(&client->dev); return 0; probe_error_media_entity_cleanup: media_entity_cleanup(&ov8856->sd.entity); probe_error_v4l2_ctrl_handler_free: v4l2_ctrl_handler_free(ov8856->sd.ctrl_handler); mutex_destroy(&ov8856->mutex); probe_power_off: ov8856_power_off(&client->dev); return ret; } static const struct dev_pm_ops ov8856_pm_ops = { SET_SYSTEM_SLEEP_PM_OPS(ov8856_suspend, ov8856_resume) SET_RUNTIME_PM_OPS(ov8856_power_off, ov8856_power_on, NULL) }; #ifdef CONFIG_ACPI static const struct acpi_device_id ov8856_acpi_ids[] = { {"OVTI8856"}, {} }; MODULE_DEVICE_TABLE(acpi, ov8856_acpi_ids); #endif static const struct of_device_id ov8856_of_match[] = { { .compatible = "ovti,ov8856" }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(of, ov8856_of_match); static struct i2c_driver ov8856_i2c_driver = { .driver = { .name = "ov8856", .pm = &ov8856_pm_ops, .acpi_match_table = ACPI_PTR(ov8856_acpi_ids), .of_match_table = ov8856_of_match, }, .probe = ov8856_probe, .remove = ov8856_remove, .flags = I2C_DRV_ACPI_WAIVE_D0_PROBE, }; module_i2c_driver(ov8856_i2c_driver); MODULE_AUTHOR("Ben Kao <[email protected]>"); MODULE_DESCRIPTION("OmniVision OV8856 sensor driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/media/i2c/ov8856.c
// SPDX-License-Identifier: GPL-2.0 // Copyright (c) 2020 Intel Corporation. #include <asm/unaligned.h> #include <linux/acpi.h> #include <linux/delay.h> #include <linux/i2c.h> #include <linux/module.h> #include <linux/pm_runtime.h> #include <linux/nvmem-provider.h> #include <linux/regmap.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-device.h> #include <media/v4l2-fwnode.h> #define OV2740_LINK_FREQ_360MHZ 360000000ULL #define OV2740_SCLK 72000000LL #define OV2740_MCLK 19200000 #define OV2740_DATA_LANES 2 #define OV2740_RGB_DEPTH 10 #define OV2740_REG_CHIP_ID 0x300a #define OV2740_CHIP_ID 0x2740 #define OV2740_REG_MODE_SELECT 0x0100 #define OV2740_MODE_STANDBY 0x00 #define OV2740_MODE_STREAMING 0x01 /* vertical-timings from sensor */ #define OV2740_REG_VTS 0x380e #define OV2740_VTS_DEF 0x088a #define OV2740_VTS_MIN 0x0460 #define OV2740_VTS_MAX 0x7fff /* horizontal-timings from sensor */ #define OV2740_REG_HTS 0x380c /* Exposure controls from sensor */ #define OV2740_REG_EXPOSURE 0x3500 #define OV2740_EXPOSURE_MIN 4 #define OV2740_EXPOSURE_MAX_MARGIN 8 #define OV2740_EXPOSURE_STEP 1 /* Analog gain controls from sensor */ #define OV2740_REG_ANALOG_GAIN 0x3508 #define OV2740_ANAL_GAIN_MIN 128 #define OV2740_ANAL_GAIN_MAX 1983 #define OV2740_ANAL_GAIN_STEP 1 /* Digital gain controls from sensor */ #define OV2740_REG_MWB_R_GAIN 0x500a #define OV2740_REG_MWB_G_GAIN 0x500c #define OV2740_REG_MWB_B_GAIN 0x500e #define OV2740_DGTL_GAIN_MIN 1024 #define OV2740_DGTL_GAIN_MAX 4095 #define OV2740_DGTL_GAIN_STEP 1 #define OV2740_DGTL_GAIN_DEFAULT 1024 /* Test Pattern Control */ #define OV2740_REG_TEST_PATTERN 0x5040 #define OV2740_TEST_PATTERN_ENABLE BIT(7) #define OV2740_TEST_PATTERN_BAR_SHIFT 2 /* Group Access */ #define OV2740_REG_GROUP_ACCESS 0x3208 #define OV2740_GROUP_HOLD_START 0x0 #define OV2740_GROUP_HOLD_END 0x10 #define OV2740_GROUP_HOLD_LAUNCH 0xa0 /* ISP CTRL00 */ #define OV2740_REG_ISP_CTRL00 0x5000 /* ISP CTRL01 */ #define OV2740_REG_ISP_CTRL01 0x5001 /* Customer Addresses: 0x7010 - 0x710F */ #define CUSTOMER_USE_OTP_SIZE 0x100 /* OTP registers from sensor */ #define OV2740_REG_OTP_CUSTOMER 0x7010 struct nvm_data { struct nvmem_device *nvmem; struct regmap *regmap; char *nvm_buffer; }; enum { OV2740_LINK_FREQ_360MHZ_INDEX, }; struct ov2740_reg { u16 address; u8 val; }; struct ov2740_reg_list { u32 num_of_regs; const struct ov2740_reg *regs; }; struct ov2740_link_freq_config { const struct ov2740_reg_list reg_list; }; struct ov2740_mode { /* Frame width in pixels */ u32 width; /* Frame height in pixels */ u32 height; /* Horizontal timining size */ u32 hts; /* Default vertical timining size */ u32 vts_def; /* Min vertical timining size */ u32 vts_min; /* Link frequency needed for this resolution */ u32 link_freq_index; /* Sensor register settings for this resolution */ const struct ov2740_reg_list reg_list; }; static const struct ov2740_reg mipi_data_rate_720mbps[] = { {0x0103, 0x01}, {0x0302, 0x4b}, {0x030d, 0x4b}, {0x030e, 0x02}, {0x030a, 0x01}, {0x0312, 0x11}, }; static const struct ov2740_reg mode_1932x1092_regs[] = { {0x3000, 0x00}, {0x3018, 0x32}, {0x3031, 0x0a}, {0x3080, 0x08}, {0x3083, 0xB4}, {0x3103, 0x00}, {0x3104, 0x01}, {0x3106, 0x01}, {0x3500, 0x00}, {0x3501, 0x44}, {0x3502, 0x40}, {0x3503, 0x88}, {0x3507, 0x00}, {0x3508, 0x00}, {0x3509, 0x80}, {0x350c, 0x00}, {0x350d, 0x80}, {0x3510, 0x00}, {0x3511, 0x00}, {0x3512, 0x20}, {0x3632, 0x00}, {0x3633, 0x10}, {0x3634, 0x10}, {0x3635, 0x10}, {0x3645, 0x13}, {0x3646, 0x81}, {0x3636, 0x10}, {0x3651, 0x0a}, {0x3656, 0x02}, {0x3659, 0x04}, {0x365a, 0xda}, {0x365b, 0xa2}, {0x365c, 0x04}, {0x365d, 0x1d}, {0x365e, 0x1a}, {0x3662, 0xd7}, {0x3667, 0x78}, {0x3669, 0x0a}, {0x366a, 0x92}, {0x3700, 0x54}, {0x3702, 0x10}, {0x3706, 0x42}, {0x3709, 0x30}, {0x370b, 0xc2}, {0x3714, 0x63}, {0x3715, 0x01}, {0x3716, 0x00}, {0x371a, 0x3e}, {0x3732, 0x0e}, {0x3733, 0x10}, {0x375f, 0x0e}, {0x3768, 0x30}, {0x3769, 0x44}, {0x376a, 0x22}, {0x377b, 0x20}, {0x377c, 0x00}, {0x377d, 0x0c}, {0x3798, 0x00}, {0x37a1, 0x55}, {0x37a8, 0x6d}, {0x37c2, 0x04}, {0x37c5, 0x00}, {0x37c8, 0x00}, {0x3800, 0x00}, {0x3801, 0x00}, {0x3802, 0x00}, {0x3803, 0x00}, {0x3804, 0x07}, {0x3805, 0x8f}, {0x3806, 0x04}, {0x3807, 0x47}, {0x3808, 0x07}, {0x3809, 0x88}, {0x380a, 0x04}, {0x380b, 0x40}, {0x380c, 0x04}, {0x380d, 0x38}, {0x380e, 0x04}, {0x380f, 0x60}, {0x3810, 0x00}, {0x3811, 0x04}, {0x3812, 0x00}, {0x3813, 0x04}, {0x3814, 0x01}, {0x3815, 0x01}, {0x3820, 0x80}, {0x3821, 0x46}, {0x3822, 0x84}, {0x3829, 0x00}, {0x382a, 0x01}, {0x382b, 0x01}, {0x3830, 0x04}, {0x3836, 0x01}, {0x3837, 0x08}, {0x3839, 0x01}, {0x383a, 0x00}, {0x383b, 0x08}, {0x383c, 0x00}, {0x3f0b, 0x00}, {0x4001, 0x20}, {0x4009, 0x07}, {0x4003, 0x10}, {0x4010, 0xe0}, {0x4016, 0x00}, {0x4017, 0x10}, {0x4044, 0x02}, {0x4304, 0x08}, {0x4307, 0x30}, {0x4320, 0x80}, {0x4322, 0x00}, {0x4323, 0x00}, {0x4324, 0x00}, {0x4325, 0x00}, {0x4326, 0x00}, {0x4327, 0x00}, {0x4328, 0x00}, {0x4329, 0x00}, {0x432c, 0x03}, {0x432d, 0x81}, {0x4501, 0x84}, {0x4502, 0x40}, {0x4503, 0x18}, {0x4504, 0x04}, {0x4508, 0x02}, {0x4601, 0x10}, {0x4800, 0x00}, {0x4816, 0x52}, {0x4837, 0x16}, {0x5000, 0x7f}, {0x5001, 0x00}, {0x5005, 0x38}, {0x501e, 0x0d}, {0x5040, 0x00}, {0x5901, 0x00}, {0x3800, 0x00}, {0x3801, 0x00}, {0x3802, 0x00}, {0x3803, 0x00}, {0x3804, 0x07}, {0x3805, 0x8f}, {0x3806, 0x04}, {0x3807, 0x47}, {0x3808, 0x07}, {0x3809, 0x8c}, {0x380a, 0x04}, {0x380b, 0x44}, {0x3810, 0x00}, {0x3811, 0x00}, {0x3812, 0x00}, {0x3813, 0x01}, }; static const char * const ov2740_test_pattern_menu[] = { "Disabled", "Color Bar", "Top-Bottom Darker Color Bar", "Right-Left Darker Color Bar", "Bottom-Top Darker Color Bar", }; static const s64 link_freq_menu_items[] = { OV2740_LINK_FREQ_360MHZ, }; static const struct ov2740_link_freq_config link_freq_configs[] = { [OV2740_LINK_FREQ_360MHZ_INDEX] = { .reg_list = { .num_of_regs = ARRAY_SIZE(mipi_data_rate_720mbps), .regs = mipi_data_rate_720mbps, } }, }; static const struct ov2740_mode supported_modes[] = { { .width = 1932, .height = 1092, .hts = 1080, .vts_def = OV2740_VTS_DEF, .vts_min = OV2740_VTS_MIN, .reg_list = { .num_of_regs = ARRAY_SIZE(mode_1932x1092_regs), .regs = mode_1932x1092_regs, }, .link_freq_index = OV2740_LINK_FREQ_360MHZ_INDEX, }, }; struct ov2740 { struct v4l2_subdev sd; struct media_pad pad; struct v4l2_ctrl_handler ctrl_handler; /* V4L2 Controls */ struct v4l2_ctrl *link_freq; struct v4l2_ctrl *pixel_rate; struct v4l2_ctrl *vblank; struct v4l2_ctrl *hblank; struct v4l2_ctrl *exposure; /* Current mode */ const struct ov2740_mode *cur_mode; /* To serialize asynchronus callbacks */ struct mutex mutex; /* Streaming on/off */ bool streaming; /* NVM data inforamtion */ struct nvm_data *nvm; /* True if the device has been identified */ bool identified; }; static inline struct ov2740 *to_ov2740(struct v4l2_subdev *subdev) { return container_of(subdev, struct ov2740, sd); } static u64 to_pixel_rate(u32 f_index) { u64 pixel_rate = link_freq_menu_items[f_index] * 2 * OV2740_DATA_LANES; do_div(pixel_rate, OV2740_RGB_DEPTH); return pixel_rate; } static u64 to_pixels_per_line(u32 hts, u32 f_index) { u64 ppl = hts * to_pixel_rate(f_index); do_div(ppl, OV2740_SCLK); return ppl; } static int ov2740_read_reg(struct ov2740 *ov2740, u16 reg, u16 len, u32 *val) { struct i2c_client *client = v4l2_get_subdevdata(&ov2740->sd); struct i2c_msg msgs[2]; u8 addr_buf[2]; u8 data_buf[4] = {0}; int ret; if (len > sizeof(data_buf)) return -EINVAL; put_unaligned_be16(reg, addr_buf); msgs[0].addr = client->addr; msgs[0].flags = 0; msgs[0].len = sizeof(addr_buf); msgs[0].buf = addr_buf; msgs[1].addr = client->addr; msgs[1].flags = I2C_M_RD; msgs[1].len = len; msgs[1].buf = &data_buf[sizeof(data_buf) - len]; ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs)); if (ret != ARRAY_SIZE(msgs)) return ret < 0 ? ret : -EIO; *val = get_unaligned_be32(data_buf); return 0; } static int ov2740_write_reg(struct ov2740 *ov2740, u16 reg, u16 len, u32 val) { struct i2c_client *client = v4l2_get_subdevdata(&ov2740->sd); u8 buf[6]; int ret; if (len > 4) return -EINVAL; put_unaligned_be16(reg, buf); put_unaligned_be32(val << 8 * (4 - len), buf + 2); ret = i2c_master_send(client, buf, len + 2); if (ret != len + 2) return ret < 0 ? ret : -EIO; return 0; } static int ov2740_write_reg_list(struct ov2740 *ov2740, const struct ov2740_reg_list *r_list) { struct i2c_client *client = v4l2_get_subdevdata(&ov2740->sd); unsigned int i; int ret; for (i = 0; i < r_list->num_of_regs; i++) { ret = ov2740_write_reg(ov2740, r_list->regs[i].address, 1, r_list->regs[i].val); if (ret) { dev_err_ratelimited(&client->dev, "write reg 0x%4.4x return err = %d\n", r_list->regs[i].address, ret); return ret; } } return 0; } static int ov2740_identify_module(struct ov2740 *ov2740) { struct i2c_client *client = v4l2_get_subdevdata(&ov2740->sd); int ret; u32 val; if (ov2740->identified) return 0; ret = ov2740_read_reg(ov2740, OV2740_REG_CHIP_ID, 3, &val); if (ret) return ret; if (val != OV2740_CHIP_ID) { dev_err(&client->dev, "chip id mismatch: %x != %x\n", OV2740_CHIP_ID, val); return -ENXIO; } ov2740->identified = true; return 0; } static int ov2740_update_digital_gain(struct ov2740 *ov2740, u32 d_gain) { int ret; ret = ov2740_write_reg(ov2740, OV2740_REG_GROUP_ACCESS, 1, OV2740_GROUP_HOLD_START); if (ret) return ret; ret = ov2740_write_reg(ov2740, OV2740_REG_MWB_R_GAIN, 2, d_gain); if (ret) return ret; ret = ov2740_write_reg(ov2740, OV2740_REG_MWB_G_GAIN, 2, d_gain); if (ret) return ret; ret = ov2740_write_reg(ov2740, OV2740_REG_MWB_B_GAIN, 2, d_gain); if (ret) return ret; ret = ov2740_write_reg(ov2740, OV2740_REG_GROUP_ACCESS, 1, OV2740_GROUP_HOLD_END); if (ret) return ret; ret = ov2740_write_reg(ov2740, OV2740_REG_GROUP_ACCESS, 1, OV2740_GROUP_HOLD_LAUNCH); return ret; } static int ov2740_test_pattern(struct ov2740 *ov2740, u32 pattern) { if (pattern) pattern = (pattern - 1) << OV2740_TEST_PATTERN_BAR_SHIFT | OV2740_TEST_PATTERN_ENABLE; return ov2740_write_reg(ov2740, OV2740_REG_TEST_PATTERN, 1, pattern); } static int ov2740_set_ctrl(struct v4l2_ctrl *ctrl) { struct ov2740 *ov2740 = container_of(ctrl->handler, struct ov2740, ctrl_handler); struct i2c_client *client = v4l2_get_subdevdata(&ov2740->sd); s64 exposure_max; int ret; /* Propagate change of current control to all related controls */ if (ctrl->id == V4L2_CID_VBLANK) { /* Update max exposure while meeting expected vblanking */ exposure_max = ov2740->cur_mode->height + ctrl->val - OV2740_EXPOSURE_MAX_MARGIN; __v4l2_ctrl_modify_range(ov2740->exposure, ov2740->exposure->minimum, exposure_max, ov2740->exposure->step, exposure_max); } /* V4L2 controls values will be applied only when power is already up */ if (!pm_runtime_get_if_in_use(&client->dev)) return 0; switch (ctrl->id) { case V4L2_CID_ANALOGUE_GAIN: ret = ov2740_write_reg(ov2740, OV2740_REG_ANALOG_GAIN, 2, ctrl->val); break; case V4L2_CID_DIGITAL_GAIN: ret = ov2740_update_digital_gain(ov2740, ctrl->val); break; case V4L2_CID_EXPOSURE: /* 4 least significant bits of expsoure are fractional part */ ret = ov2740_write_reg(ov2740, OV2740_REG_EXPOSURE, 3, ctrl->val << 4); break; case V4L2_CID_VBLANK: ret = ov2740_write_reg(ov2740, OV2740_REG_VTS, 2, ov2740->cur_mode->height + ctrl->val); break; case V4L2_CID_TEST_PATTERN: ret = ov2740_test_pattern(ov2740, ctrl->val); break; default: ret = -EINVAL; break; } pm_runtime_put(&client->dev); return ret; } static const struct v4l2_ctrl_ops ov2740_ctrl_ops = { .s_ctrl = ov2740_set_ctrl, }; static int ov2740_init_controls(struct ov2740 *ov2740) { struct v4l2_ctrl_handler *ctrl_hdlr; const struct ov2740_mode *cur_mode; s64 exposure_max, h_blank, pixel_rate; u32 vblank_min, vblank_max, vblank_default; int size; int ret; ctrl_hdlr = &ov2740->ctrl_handler; ret = v4l2_ctrl_handler_init(ctrl_hdlr, 8); if (ret) return ret; ctrl_hdlr->lock = &ov2740->mutex; cur_mode = ov2740->cur_mode; size = ARRAY_SIZE(link_freq_menu_items); ov2740->link_freq = v4l2_ctrl_new_int_menu(ctrl_hdlr, &ov2740_ctrl_ops, V4L2_CID_LINK_FREQ, size - 1, 0, link_freq_menu_items); if (ov2740->link_freq) ov2740->link_freq->flags |= V4L2_CTRL_FLAG_READ_ONLY; pixel_rate = to_pixel_rate(OV2740_LINK_FREQ_360MHZ_INDEX); ov2740->pixel_rate = v4l2_ctrl_new_std(ctrl_hdlr, &ov2740_ctrl_ops, V4L2_CID_PIXEL_RATE, 0, pixel_rate, 1, pixel_rate); vblank_min = cur_mode->vts_min - cur_mode->height; vblank_max = OV2740_VTS_MAX - cur_mode->height; vblank_default = cur_mode->vts_def - cur_mode->height; ov2740->vblank = v4l2_ctrl_new_std(ctrl_hdlr, &ov2740_ctrl_ops, V4L2_CID_VBLANK, vblank_min, vblank_max, 1, vblank_default); h_blank = to_pixels_per_line(cur_mode->hts, cur_mode->link_freq_index); h_blank -= cur_mode->width; ov2740->hblank = v4l2_ctrl_new_std(ctrl_hdlr, &ov2740_ctrl_ops, V4L2_CID_HBLANK, h_blank, h_blank, 1, h_blank); if (ov2740->hblank) ov2740->hblank->flags |= V4L2_CTRL_FLAG_READ_ONLY; v4l2_ctrl_new_std(ctrl_hdlr, &ov2740_ctrl_ops, V4L2_CID_ANALOGUE_GAIN, OV2740_ANAL_GAIN_MIN, OV2740_ANAL_GAIN_MAX, OV2740_ANAL_GAIN_STEP, OV2740_ANAL_GAIN_MIN); v4l2_ctrl_new_std(ctrl_hdlr, &ov2740_ctrl_ops, V4L2_CID_DIGITAL_GAIN, OV2740_DGTL_GAIN_MIN, OV2740_DGTL_GAIN_MAX, OV2740_DGTL_GAIN_STEP, OV2740_DGTL_GAIN_DEFAULT); exposure_max = cur_mode->vts_def - OV2740_EXPOSURE_MAX_MARGIN; ov2740->exposure = v4l2_ctrl_new_std(ctrl_hdlr, &ov2740_ctrl_ops, V4L2_CID_EXPOSURE, OV2740_EXPOSURE_MIN, exposure_max, OV2740_EXPOSURE_STEP, exposure_max); v4l2_ctrl_new_std_menu_items(ctrl_hdlr, &ov2740_ctrl_ops, V4L2_CID_TEST_PATTERN, ARRAY_SIZE(ov2740_test_pattern_menu) - 1, 0, 0, ov2740_test_pattern_menu); if (ctrl_hdlr->error) { v4l2_ctrl_handler_free(ctrl_hdlr); return ctrl_hdlr->error; } ov2740->sd.ctrl_handler = ctrl_hdlr; return 0; } static void ov2740_update_pad_format(const struct ov2740_mode *mode, struct v4l2_mbus_framefmt *fmt) { fmt->width = mode->width; fmt->height = mode->height; fmt->code = MEDIA_BUS_FMT_SGRBG10_1X10; fmt->field = V4L2_FIELD_NONE; } static int ov2740_load_otp_data(struct nvm_data *nvm) { struct device *dev = regmap_get_device(nvm->regmap); struct ov2740 *ov2740 = to_ov2740(dev_get_drvdata(dev)); u32 isp_ctrl00 = 0; u32 isp_ctrl01 = 0; int ret; if (nvm->nvm_buffer) return 0; nvm->nvm_buffer = kzalloc(CUSTOMER_USE_OTP_SIZE, GFP_KERNEL); if (!nvm->nvm_buffer) return -ENOMEM; ret = ov2740_read_reg(ov2740, OV2740_REG_ISP_CTRL00, 1, &isp_ctrl00); if (ret) { dev_err(dev, "failed to read ISP CTRL00\n"); goto err; } ret = ov2740_read_reg(ov2740, OV2740_REG_ISP_CTRL01, 1, &isp_ctrl01); if (ret) { dev_err(dev, "failed to read ISP CTRL01\n"); goto err; } /* Clear bit 5 of ISP CTRL00 */ ret = ov2740_write_reg(ov2740, OV2740_REG_ISP_CTRL00, 1, isp_ctrl00 & ~BIT(5)); if (ret) { dev_err(dev, "failed to set ISP CTRL00\n"); goto err; } /* Clear bit 7 of ISP CTRL01 */ ret = ov2740_write_reg(ov2740, OV2740_REG_ISP_CTRL01, 1, isp_ctrl01 & ~BIT(7)); if (ret) { dev_err(dev, "failed to set ISP CTRL01\n"); goto err; } ret = ov2740_write_reg(ov2740, OV2740_REG_MODE_SELECT, 1, OV2740_MODE_STREAMING); if (ret) { dev_err(dev, "failed to set streaming mode\n"); goto err; } /* * Users are not allowed to access OTP-related registers and memory * during the 20 ms period after streaming starts (0x100 = 0x01). */ msleep(20); ret = regmap_bulk_read(nvm->regmap, OV2740_REG_OTP_CUSTOMER, nvm->nvm_buffer, CUSTOMER_USE_OTP_SIZE); if (ret) { dev_err(dev, "failed to read OTP data, ret %d\n", ret); goto err; } ret = ov2740_write_reg(ov2740, OV2740_REG_MODE_SELECT, 1, OV2740_MODE_STANDBY); if (ret) { dev_err(dev, "failed to set streaming mode\n"); goto err; } ret = ov2740_write_reg(ov2740, OV2740_REG_ISP_CTRL01, 1, isp_ctrl01); if (ret) { dev_err(dev, "failed to set ISP CTRL01\n"); goto err; } ret = ov2740_write_reg(ov2740, OV2740_REG_ISP_CTRL00, 1, isp_ctrl00); if (ret) { dev_err(dev, "failed to set ISP CTRL00\n"); goto err; } return 0; err: kfree(nvm->nvm_buffer); nvm->nvm_buffer = NULL; return ret; } static int ov2740_start_streaming(struct ov2740 *ov2740) { struct i2c_client *client = v4l2_get_subdevdata(&ov2740->sd); const struct ov2740_reg_list *reg_list; int link_freq_index; int ret; ret = ov2740_identify_module(ov2740); if (ret) return ret; if (ov2740->nvm) ov2740_load_otp_data(ov2740->nvm); link_freq_index = ov2740->cur_mode->link_freq_index; reg_list = &link_freq_configs[link_freq_index].reg_list; ret = ov2740_write_reg_list(ov2740, reg_list); if (ret) { dev_err(&client->dev, "failed to set plls\n"); return ret; } reg_list = &ov2740->cur_mode->reg_list; ret = ov2740_write_reg_list(ov2740, reg_list); if (ret) { dev_err(&client->dev, "failed to set mode\n"); return ret; } ret = __v4l2_ctrl_handler_setup(ov2740->sd.ctrl_handler); if (ret) return ret; ret = ov2740_write_reg(ov2740, OV2740_REG_MODE_SELECT, 1, OV2740_MODE_STREAMING); if (ret) dev_err(&client->dev, "failed to start streaming\n"); return ret; } static void ov2740_stop_streaming(struct ov2740 *ov2740) { struct i2c_client *client = v4l2_get_subdevdata(&ov2740->sd); if (ov2740_write_reg(ov2740, OV2740_REG_MODE_SELECT, 1, OV2740_MODE_STANDBY)) dev_err(&client->dev, "failed to stop streaming\n"); } static int ov2740_set_stream(struct v4l2_subdev *sd, int enable) { struct ov2740 *ov2740 = to_ov2740(sd); struct i2c_client *client = v4l2_get_subdevdata(sd); int ret = 0; if (ov2740->streaming == enable) return 0; mutex_lock(&ov2740->mutex); if (enable) { ret = pm_runtime_resume_and_get(&client->dev); if (ret < 0) { mutex_unlock(&ov2740->mutex); return ret; } ret = ov2740_start_streaming(ov2740); if (ret) { enable = 0; ov2740_stop_streaming(ov2740); pm_runtime_put(&client->dev); } } else { ov2740_stop_streaming(ov2740); pm_runtime_put(&client->dev); } ov2740->streaming = enable; mutex_unlock(&ov2740->mutex); return ret; } static int ov2740_suspend(struct device *dev) { struct v4l2_subdev *sd = dev_get_drvdata(dev); struct ov2740 *ov2740 = to_ov2740(sd); mutex_lock(&ov2740->mutex); if (ov2740->streaming) ov2740_stop_streaming(ov2740); mutex_unlock(&ov2740->mutex); return 0; } static int ov2740_resume(struct device *dev) { struct v4l2_subdev *sd = dev_get_drvdata(dev); struct ov2740 *ov2740 = to_ov2740(sd); int ret = 0; mutex_lock(&ov2740->mutex); if (!ov2740->streaming) goto exit; ret = ov2740_start_streaming(ov2740); if (ret) { ov2740->streaming = false; ov2740_stop_streaming(ov2740); } exit: mutex_unlock(&ov2740->mutex); return ret; } static int ov2740_set_format(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *fmt) { struct ov2740 *ov2740 = to_ov2740(sd); const struct ov2740_mode *mode; s32 vblank_def, h_blank; mode = v4l2_find_nearest_size(supported_modes, ARRAY_SIZE(supported_modes), width, height, fmt->format.width, fmt->format.height); mutex_lock(&ov2740->mutex); ov2740_update_pad_format(mode, &fmt->format); if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) { *v4l2_subdev_get_try_format(sd, sd_state, fmt->pad) = fmt->format; } else { ov2740->cur_mode = mode; __v4l2_ctrl_s_ctrl(ov2740->link_freq, mode->link_freq_index); __v4l2_ctrl_s_ctrl_int64(ov2740->pixel_rate, to_pixel_rate(mode->link_freq_index)); /* Update limits and set FPS to default */ vblank_def = mode->vts_def - mode->height; __v4l2_ctrl_modify_range(ov2740->vblank, mode->vts_min - mode->height, OV2740_VTS_MAX - mode->height, 1, vblank_def); __v4l2_ctrl_s_ctrl(ov2740->vblank, vblank_def); h_blank = to_pixels_per_line(mode->hts, mode->link_freq_index) - mode->width; __v4l2_ctrl_modify_range(ov2740->hblank, h_blank, h_blank, 1, h_blank); } mutex_unlock(&ov2740->mutex); return 0; } static int ov2740_get_format(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *fmt) { struct ov2740 *ov2740 = to_ov2740(sd); mutex_lock(&ov2740->mutex); if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) fmt->format = *v4l2_subdev_get_try_format(&ov2740->sd, sd_state, fmt->pad); else ov2740_update_pad_format(ov2740->cur_mode, &fmt->format); mutex_unlock(&ov2740->mutex); return 0; } static int ov2740_enum_mbus_code(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_mbus_code_enum *code) { if (code->index > 0) return -EINVAL; code->code = MEDIA_BUS_FMT_SGRBG10_1X10; return 0; } static int ov2740_enum_frame_size(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_frame_size_enum *fse) { if (fse->index >= ARRAY_SIZE(supported_modes)) return -EINVAL; if (fse->code != MEDIA_BUS_FMT_SGRBG10_1X10) return -EINVAL; fse->min_width = supported_modes[fse->index].width; fse->max_width = fse->min_width; fse->min_height = supported_modes[fse->index].height; fse->max_height = fse->min_height; return 0; } static int ov2740_open(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh) { struct ov2740 *ov2740 = to_ov2740(sd); mutex_lock(&ov2740->mutex); ov2740_update_pad_format(&supported_modes[0], v4l2_subdev_get_try_format(sd, fh->state, 0)); mutex_unlock(&ov2740->mutex); return 0; } static const struct v4l2_subdev_video_ops ov2740_video_ops = { .s_stream = ov2740_set_stream, }; static const struct v4l2_subdev_pad_ops ov2740_pad_ops = { .set_fmt = ov2740_set_format, .get_fmt = ov2740_get_format, .enum_mbus_code = ov2740_enum_mbus_code, .enum_frame_size = ov2740_enum_frame_size, }; static const struct v4l2_subdev_ops ov2740_subdev_ops = { .video = &ov2740_video_ops, .pad = &ov2740_pad_ops, }; static const struct media_entity_operations ov2740_subdev_entity_ops = { .link_validate = v4l2_subdev_link_validate, }; static const struct v4l2_subdev_internal_ops ov2740_internal_ops = { .open = ov2740_open, }; static int ov2740_check_hwcfg(struct device *dev) { struct fwnode_handle *ep; struct fwnode_handle *fwnode = dev_fwnode(dev); struct v4l2_fwnode_endpoint bus_cfg = { .bus_type = V4L2_MBUS_CSI2_DPHY }; u32 mclk; int ret; unsigned int i, j; ret = fwnode_property_read_u32(fwnode, "clock-frequency", &mclk); if (ret) return ret; if (mclk != OV2740_MCLK) return dev_err_probe(dev, -EINVAL, "external clock %d is not supported\n", mclk); ep = fwnode_graph_get_next_endpoint(fwnode, NULL); if (!ep) return -ENXIO; ret = v4l2_fwnode_endpoint_alloc_parse(ep, &bus_cfg); fwnode_handle_put(ep); if (ret) return ret; if (bus_cfg.bus.mipi_csi2.num_data_lanes != OV2740_DATA_LANES) { ret = dev_err_probe(dev, -EINVAL, "number of CSI2 data lanes %d is not supported\n", bus_cfg.bus.mipi_csi2.num_data_lanes); goto check_hwcfg_error; } if (!bus_cfg.nr_of_link_frequencies) { ret = dev_err_probe(dev, -EINVAL, "no link frequencies defined\n"); goto check_hwcfg_error; } for (i = 0; i < ARRAY_SIZE(link_freq_menu_items); i++) { for (j = 0; j < bus_cfg.nr_of_link_frequencies; j++) { if (link_freq_menu_items[i] == bus_cfg.link_frequencies[j]) break; } if (j == bus_cfg.nr_of_link_frequencies) { ret = dev_err_probe(dev, -EINVAL, "no link frequency %lld supported\n", link_freq_menu_items[i]); goto check_hwcfg_error; } } check_hwcfg_error: v4l2_fwnode_endpoint_free(&bus_cfg); return ret; } static void ov2740_remove(struct i2c_client *client) { struct v4l2_subdev *sd = i2c_get_clientdata(client); struct ov2740 *ov2740 = to_ov2740(sd); v4l2_async_unregister_subdev(sd); media_entity_cleanup(&sd->entity); v4l2_ctrl_handler_free(sd->ctrl_handler); pm_runtime_disable(&client->dev); mutex_destroy(&ov2740->mutex); } static int ov2740_nvmem_read(void *priv, unsigned int off, void *val, size_t count) { struct nvm_data *nvm = priv; struct device *dev = regmap_get_device(nvm->regmap); struct ov2740 *ov2740 = to_ov2740(dev_get_drvdata(dev)); int ret = 0; mutex_lock(&ov2740->mutex); if (nvm->nvm_buffer) { memcpy(val, nvm->nvm_buffer + off, count); goto exit; } ret = pm_runtime_resume_and_get(dev); if (ret < 0) { goto exit; } ret = ov2740_load_otp_data(nvm); if (!ret) memcpy(val, nvm->nvm_buffer + off, count); pm_runtime_put(dev); exit: mutex_unlock(&ov2740->mutex); return ret; } static int ov2740_register_nvmem(struct i2c_client *client, struct ov2740 *ov2740) { struct nvm_data *nvm; struct regmap_config regmap_config = { }; struct nvmem_config nvmem_config = { }; struct regmap *regmap; struct device *dev = &client->dev; nvm = devm_kzalloc(dev, sizeof(*nvm), GFP_KERNEL); if (!nvm) return -ENOMEM; regmap_config.val_bits = 8; regmap_config.reg_bits = 16; regmap_config.disable_locking = true; regmap = devm_regmap_init_i2c(client, &regmap_config); if (IS_ERR(regmap)) return PTR_ERR(regmap); nvm->regmap = regmap; nvmem_config.name = dev_name(dev); nvmem_config.dev = dev; nvmem_config.read_only = true; nvmem_config.root_only = true; nvmem_config.owner = THIS_MODULE; nvmem_config.compat = true; nvmem_config.base_dev = dev; nvmem_config.reg_read = ov2740_nvmem_read; nvmem_config.reg_write = NULL; nvmem_config.priv = nvm; nvmem_config.stride = 1; nvmem_config.word_size = 1; nvmem_config.size = CUSTOMER_USE_OTP_SIZE; nvm->nvmem = devm_nvmem_register(dev, &nvmem_config); if (IS_ERR(nvm->nvmem)) return PTR_ERR(nvm->nvmem); ov2740->nvm = nvm; return 0; } static int ov2740_probe(struct i2c_client *client) { struct device *dev = &client->dev; struct ov2740 *ov2740; bool full_power; int ret; ret = ov2740_check_hwcfg(&client->dev); if (ret) return dev_err_probe(dev, ret, "failed to check HW configuration\n"); ov2740 = devm_kzalloc(&client->dev, sizeof(*ov2740), GFP_KERNEL); if (!ov2740) return -ENOMEM; v4l2_i2c_subdev_init(&ov2740->sd, client, &ov2740_subdev_ops); full_power = acpi_dev_state_d0(&client->dev); if (full_power) { ret = ov2740_identify_module(ov2740); if (ret) return dev_err_probe(dev, ret, "failed to find sensor\n"); } mutex_init(&ov2740->mutex); ov2740->cur_mode = &supported_modes[0]; ret = ov2740_init_controls(ov2740); if (ret) { dev_err_probe(dev, ret, "failed to init controls\n"); goto probe_error_v4l2_ctrl_handler_free; } ov2740->sd.internal_ops = &ov2740_internal_ops; ov2740->sd.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE; ov2740->sd.entity.ops = &ov2740_subdev_entity_ops; ov2740->sd.entity.function = MEDIA_ENT_F_CAM_SENSOR; ov2740->pad.flags = MEDIA_PAD_FL_SOURCE; ret = media_entity_pads_init(&ov2740->sd.entity, 1, &ov2740->pad); if (ret) { dev_err_probe(dev, ret, "failed to init entity pads\n"); goto probe_error_v4l2_ctrl_handler_free; } ret = v4l2_async_register_subdev_sensor(&ov2740->sd); if (ret < 0) { dev_err_probe(dev, ret, "failed to register V4L2 subdev\n"); goto probe_error_media_entity_cleanup; } ret = ov2740_register_nvmem(client, ov2740); if (ret) dev_warn(&client->dev, "register nvmem failed, ret %d\n", ret); /* Set the device's state to active if it's in D0 state. */ if (full_power) pm_runtime_set_active(&client->dev); pm_runtime_enable(&client->dev); pm_runtime_idle(&client->dev); return 0; probe_error_media_entity_cleanup: media_entity_cleanup(&ov2740->sd.entity); probe_error_v4l2_ctrl_handler_free: v4l2_ctrl_handler_free(ov2740->sd.ctrl_handler); mutex_destroy(&ov2740->mutex); return ret; } static DEFINE_SIMPLE_DEV_PM_OPS(ov2740_pm_ops, ov2740_suspend, ov2740_resume); static const struct acpi_device_id ov2740_acpi_ids[] = { {"INT3474"}, {} }; MODULE_DEVICE_TABLE(acpi, ov2740_acpi_ids); static struct i2c_driver ov2740_i2c_driver = { .driver = { .name = "ov2740", .pm = pm_sleep_ptr(&ov2740_pm_ops), .acpi_match_table = ov2740_acpi_ids, }, .probe = ov2740_probe, .remove = ov2740_remove, .flags = I2C_DRV_ACPI_WAIVE_D0_PROBE, }; module_i2c_driver(ov2740_i2c_driver); MODULE_AUTHOR("Qiu, Tianshu <[email protected]>"); MODULE_AUTHOR("Shawn Tu"); MODULE_AUTHOR("Bingbu Cao <[email protected]>"); MODULE_DESCRIPTION("OmniVision OV2740 sensor driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/media/i2c/ov2740.c
// SPDX-License-Identifier: GPL-2.0-or-later /* tea6420 - i2c-driver for the tea6420 by SGS Thomson Copyright (C) 1998-2003 Michael Hunold <[email protected]> Copyright (C) 2008 Hans Verkuil <[email protected]> The tea6420 is a bus controlled audio-matrix with 5 stereo inputs, 4 stereo outputs and gain control for each output. It is cascadable, i.e. it can be found at the addresses 0x98 and 0x9a on the i2c-bus. For detailed information download the specifications directly from SGS Thomson at http://www.st.com */ #include <linux/module.h> #include <linux/ioctl.h> #include <linux/slab.h> #include <linux/i2c.h> #include <media/v4l2-device.h> #include "tea6420.h" MODULE_AUTHOR("Michael Hunold <[email protected]>"); MODULE_DESCRIPTION("tea6420 driver"); MODULE_LICENSE("GPL"); static int debug; module_param(debug, int, 0644); MODULE_PARM_DESC(debug, "Debug level (0-1)"); /* make a connection between the input 'i' and the output 'o' with gain 'g' (note: i = 6 means 'mute') */ static int tea6420_s_routing(struct v4l2_subdev *sd, u32 i, u32 o, u32 config) { struct i2c_client *client = v4l2_get_subdevdata(sd); int g = (o >> 4) & 0xf; u8 byte; int ret; o &= 0xf; v4l2_dbg(1, debug, sd, "i=%d, o=%d, g=%d\n", i, o, g); /* check if the parameters are valid */ if (i < 1 || i > 6 || o < 1 || o > 4 || g < 0 || g > 6 || g % 2 != 0) return -EINVAL; byte = ((o - 1) << 5); byte |= (i - 1); /* to understand this, have a look at the tea6420-specs (p.5) */ switch (g) { case 0: byte |= (3 << 3); break; case 2: byte |= (2 << 3); break; case 4: byte |= (1 << 3); break; case 6: break; } ret = i2c_smbus_write_byte(client, byte); if (ret) { v4l2_dbg(1, debug, sd, "i2c_smbus_write_byte() failed, ret:%d\n", ret); return -EIO; } return 0; } /* ----------------------------------------------------------------------- */ static const struct v4l2_subdev_audio_ops tea6420_audio_ops = { .s_routing = tea6420_s_routing, }; static const struct v4l2_subdev_ops tea6420_ops = { .audio = &tea6420_audio_ops, }; static int tea6420_probe(struct i2c_client *client) { struct v4l2_subdev *sd; int err, i; /* let's see whether this adapter can support what we need */ if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_WRITE_BYTE)) return -EIO; v4l_info(client, "chip found @ 0x%x (%s)\n", client->addr << 1, client->adapter->name); sd = devm_kzalloc(&client->dev, sizeof(*sd), GFP_KERNEL); if (sd == NULL) return -ENOMEM; v4l2_i2c_subdev_init(sd, client, &tea6420_ops); /* set initial values: set "mute"-input to all outputs at gain 0 */ err = 0; for (i = 1; i < 5; i++) err += tea6420_s_routing(sd, 6, i, 0); if (err) { v4l_dbg(1, debug, client, "could not initialize tea6420\n"); return -ENODEV; } return 0; } static void tea6420_remove(struct i2c_client *client) { struct v4l2_subdev *sd = i2c_get_clientdata(client); v4l2_device_unregister_subdev(sd); } static const struct i2c_device_id tea6420_id[] = { { "tea6420", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, tea6420_id); static struct i2c_driver tea6420_driver = { .driver = { .name = "tea6420", }, .probe = tea6420_probe, .remove = tea6420_remove, .id_table = tea6420_id, }; module_i2c_driver(tea6420_driver);
linux-master
drivers/media/i2c/tea6420.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * upd64031A - NEC Electronics Ghost Reduction for NTSC in Japan * * 2003 by T.Adachi <[email protected]> * 2003 by Takeru KOMORIYA <[email protected]> * 2006 by Hans Verkuil <[email protected]> */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/i2c.h> #include <linux/videodev2.h> #include <linux/slab.h> #include <media/v4l2-device.h> #include <media/i2c/upd64031a.h> /* --------------------- read registers functions define -------------------- */ /* bit masks */ #define GR_MODE_MASK 0xc0 #define DIRECT_3DYCS_CONNECT_MASK 0xc0 #define SYNC_CIRCUIT_MASK 0xa0 /* -------------------------------------------------------------------------- */ MODULE_DESCRIPTION("uPD64031A driver"); MODULE_AUTHOR("T. Adachi, Takeru KOMORIYA, Hans Verkuil"); MODULE_LICENSE("GPL"); static int debug; module_param(debug, int, 0644); MODULE_PARM_DESC(debug, "Debug level (0-1)"); enum { R00 = 0, R01, R02, R03, R04, R05, R06, R07, R08, R09, R0A, R0B, R0C, R0D, R0E, R0F, /* unused registers R10, R11, R12, R13, R14, R15, R16, R17, */ TOT_REGS }; struct upd64031a_state { struct v4l2_subdev sd; u8 regs[TOT_REGS]; u8 gr_mode; u8 direct_3dycs_connect; u8 ext_comp_sync; u8 ext_vert_sync; }; static inline struct upd64031a_state *to_state(struct v4l2_subdev *sd) { return container_of(sd, struct upd64031a_state, sd); } static u8 upd64031a_init[] = { 0x00, 0xb8, 0x48, 0xd2, 0xe6, 0x03, 0x10, 0x0b, 0xaf, 0x7f, 0x00, 0x00, 0x1d, 0x5e, 0x00, 0xd0 }; /* ------------------------------------------------------------------------ */ static u8 upd64031a_read(struct v4l2_subdev *sd, u8 reg) { struct i2c_client *client = v4l2_get_subdevdata(sd); u8 buf[2]; if (reg >= sizeof(buf)) return 0xff; i2c_master_recv(client, buf, 2); return buf[reg]; } /* ------------------------------------------------------------------------ */ static void upd64031a_write(struct v4l2_subdev *sd, u8 reg, u8 val) { struct i2c_client *client = v4l2_get_subdevdata(sd); u8 buf[2]; buf[0] = reg; buf[1] = val; v4l2_dbg(1, debug, sd, "write reg: %02X val: %02X\n", reg, val); if (i2c_master_send(client, buf, 2) != 2) v4l2_err(sd, "I/O error write 0x%02x/0x%02x\n", reg, val); } /* ------------------------------------------------------------------------ */ /* The input changed due to new input or channel changed */ static int upd64031a_s_frequency(struct v4l2_subdev *sd, const struct v4l2_frequency *freq) { struct upd64031a_state *state = to_state(sd); u8 reg = state->regs[R00]; v4l2_dbg(1, debug, sd, "changed input or channel\n"); upd64031a_write(sd, R00, reg | 0x10); upd64031a_write(sd, R00, reg & ~0x10); return 0; } /* ------------------------------------------------------------------------ */ static int upd64031a_s_routing(struct v4l2_subdev *sd, u32 input, u32 output, u32 config) { struct upd64031a_state *state = to_state(sd); u8 r00, r05, r08; state->gr_mode = (input & 3) << 6; state->direct_3dycs_connect = (input & 0xc) << 4; state->ext_comp_sync = (input & UPD64031A_COMPOSITE_EXTERNAL) << 1; state->ext_vert_sync = (input & UPD64031A_VERTICAL_EXTERNAL) << 2; r00 = (state->regs[R00] & ~GR_MODE_MASK) | state->gr_mode; r05 = (state->regs[R00] & ~SYNC_CIRCUIT_MASK) | state->ext_comp_sync | state->ext_vert_sync; r08 = (state->regs[R08] & ~DIRECT_3DYCS_CONNECT_MASK) | state->direct_3dycs_connect; upd64031a_write(sd, R00, r00); upd64031a_write(sd, R05, r05); upd64031a_write(sd, R08, r08); return upd64031a_s_frequency(sd, NULL); } static int upd64031a_log_status(struct v4l2_subdev *sd) { v4l2_info(sd, "Status: SA00=0x%02x SA01=0x%02x\n", upd64031a_read(sd, 0), upd64031a_read(sd, 1)); return 0; } #ifdef CONFIG_VIDEO_ADV_DEBUG static int upd64031a_g_register(struct v4l2_subdev *sd, struct v4l2_dbg_register *reg) { reg->val = upd64031a_read(sd, reg->reg & 0xff); reg->size = 1; return 0; } static int upd64031a_s_register(struct v4l2_subdev *sd, const struct v4l2_dbg_register *reg) { upd64031a_write(sd, reg->reg & 0xff, reg->val & 0xff); return 0; } #endif /* ----------------------------------------------------------------------- */ static const struct v4l2_subdev_core_ops upd64031a_core_ops = { .log_status = upd64031a_log_status, #ifdef CONFIG_VIDEO_ADV_DEBUG .g_register = upd64031a_g_register, .s_register = upd64031a_s_register, #endif }; static const struct v4l2_subdev_tuner_ops upd64031a_tuner_ops = { .s_frequency = upd64031a_s_frequency, }; static const struct v4l2_subdev_video_ops upd64031a_video_ops = { .s_routing = upd64031a_s_routing, }; static const struct v4l2_subdev_ops upd64031a_ops = { .core = &upd64031a_core_ops, .tuner = &upd64031a_tuner_ops, .video = &upd64031a_video_ops, }; /* ------------------------------------------------------------------------ */ /* i2c implementation */ static int upd64031a_probe(struct i2c_client *client) { struct upd64031a_state *state; struct v4l2_subdev *sd; int i; if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE_DATA)) return -EIO; v4l_info(client, "chip found @ 0x%x (%s)\n", client->addr << 1, client->adapter->name); state = devm_kzalloc(&client->dev, sizeof(*state), GFP_KERNEL); if (state == NULL) return -ENOMEM; sd = &state->sd; v4l2_i2c_subdev_init(sd, client, &upd64031a_ops); memcpy(state->regs, upd64031a_init, sizeof(state->regs)); state->gr_mode = UPD64031A_GR_ON << 6; state->direct_3dycs_connect = UPD64031A_3DYCS_COMPOSITE << 4; state->ext_comp_sync = state->ext_vert_sync = 0; for (i = 0; i < TOT_REGS; i++) upd64031a_write(sd, i, state->regs[i]); return 0; } static void upd64031a_remove(struct i2c_client *client) { struct v4l2_subdev *sd = i2c_get_clientdata(client); v4l2_device_unregister_subdev(sd); } /* ----------------------------------------------------------------------- */ static const struct i2c_device_id upd64031a_id[] = { { "upd64031a", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, upd64031a_id); static struct i2c_driver upd64031a_driver = { .driver = { .name = "upd64031a", }, .probe = upd64031a_probe, .remove = upd64031a_remove, .id_table = upd64031a_id, }; module_i2c_driver(upd64031a_driver);
linux-master
drivers/media/i2c/upd64031a.c
// SPDX-License-Identifier: GPL-2.0-only /* * ov2640 Camera Driver * * Copyright (C) 2010 Alberto Panizzo <[email protected]> * * Based on ov772x, ov9640 drivers and previous non merged implementations. * * Copyright 2005-2009 Freescale Semiconductor, Inc. All Rights Reserved. * Copyright (C) 2006, OmniVision */ #include <linux/init.h> #include <linux/module.h> #include <linux/i2c.h> #include <linux/clk.h> #include <linux/slab.h> #include <linux/delay.h> #include <linux/gpio/consumer.h> #include <linux/v4l2-mediabus.h> #include <linux/videodev2.h> #include <media/v4l2-device.h> #include <media/v4l2-event.h> #include <media/v4l2-subdev.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-image-sizes.h> #define VAL_SET(x, mask, rshift, lshift) \ ((((x) >> rshift) & mask) << lshift) /* * DSP registers * register offset for BANK_SEL == BANK_SEL_DSP */ #define R_BYPASS 0x05 /* Bypass DSP */ #define R_BYPASS_DSP_BYPAS 0x01 /* Bypass DSP, sensor out directly */ #define R_BYPASS_USE_DSP 0x00 /* Use the internal DSP */ #define QS 0x44 /* Quantization Scale Factor */ #define CTRLI 0x50 #define CTRLI_LP_DP 0x80 #define CTRLI_ROUND 0x40 #define CTRLI_V_DIV_SET(x) VAL_SET(x, 0x3, 0, 3) #define CTRLI_H_DIV_SET(x) VAL_SET(x, 0x3, 0, 0) #define HSIZE 0x51 /* H_SIZE[7:0] (real/4) */ #define HSIZE_SET(x) VAL_SET(x, 0xFF, 2, 0) #define VSIZE 0x52 /* V_SIZE[7:0] (real/4) */ #define VSIZE_SET(x) VAL_SET(x, 0xFF, 2, 0) #define XOFFL 0x53 /* OFFSET_X[7:0] */ #define XOFFL_SET(x) VAL_SET(x, 0xFF, 0, 0) #define YOFFL 0x54 /* OFFSET_Y[7:0] */ #define YOFFL_SET(x) VAL_SET(x, 0xFF, 0, 0) #define VHYX 0x55 /* Offset and size completion */ #define VHYX_VSIZE_SET(x) VAL_SET(x, 0x1, (8+2), 7) #define VHYX_HSIZE_SET(x) VAL_SET(x, 0x1, (8+2), 3) #define VHYX_YOFF_SET(x) VAL_SET(x, 0x3, 8, 4) #define VHYX_XOFF_SET(x) VAL_SET(x, 0x3, 8, 0) #define DPRP 0x56 #define TEST 0x57 /* Horizontal size completion */ #define TEST_HSIZE_SET(x) VAL_SET(x, 0x1, (9+2), 7) #define ZMOW 0x5A /* Zoom: Out Width OUTW[7:0] (real/4) */ #define ZMOW_OUTW_SET(x) VAL_SET(x, 0xFF, 2, 0) #define ZMOH 0x5B /* Zoom: Out Height OUTH[7:0] (real/4) */ #define ZMOH_OUTH_SET(x) VAL_SET(x, 0xFF, 2, 0) #define ZMHH 0x5C /* Zoom: Speed and H&W completion */ #define ZMHH_ZSPEED_SET(x) VAL_SET(x, 0x0F, 0, 4) #define ZMHH_OUTH_SET(x) VAL_SET(x, 0x1, (8+2), 2) #define ZMHH_OUTW_SET(x) VAL_SET(x, 0x3, (8+2), 0) #define BPADDR 0x7C /* SDE Indirect Register Access: Address */ #define BPDATA 0x7D /* SDE Indirect Register Access: Data */ #define CTRL2 0x86 /* DSP Module enable 2 */ #define CTRL2_DCW_EN 0x20 #define CTRL2_SDE_EN 0x10 #define CTRL2_UV_ADJ_EN 0x08 #define CTRL2_UV_AVG_EN 0x04 #define CTRL2_CMX_EN 0x01 #define CTRL3 0x87 /* DSP Module enable 3 */ #define CTRL3_BPC_EN 0x80 #define CTRL3_WPC_EN 0x40 #define SIZEL 0x8C /* Image Size Completion */ #define SIZEL_HSIZE8_11_SET(x) VAL_SET(x, 0x1, 11, 6) #define SIZEL_HSIZE8_SET(x) VAL_SET(x, 0x7, 0, 3) #define SIZEL_VSIZE8_SET(x) VAL_SET(x, 0x7, 0, 0) #define HSIZE8 0xC0 /* Image Horizontal Size HSIZE[10:3] */ #define HSIZE8_SET(x) VAL_SET(x, 0xFF, 3, 0) #define VSIZE8 0xC1 /* Image Vertical Size VSIZE[10:3] */ #define VSIZE8_SET(x) VAL_SET(x, 0xFF, 3, 0) #define CTRL0 0xC2 /* DSP Module enable 0 */ #define CTRL0_AEC_EN 0x80 #define CTRL0_AEC_SEL 0x40 #define CTRL0_STAT_SEL 0x20 #define CTRL0_VFIRST 0x10 #define CTRL0_YUV422 0x08 #define CTRL0_YUV_EN 0x04 #define CTRL0_RGB_EN 0x02 #define CTRL0_RAW_EN 0x01 #define CTRL1 0xC3 /* DSP Module enable 1 */ #define CTRL1_CIP 0x80 #define CTRL1_DMY 0x40 #define CTRL1_RAW_GMA 0x20 #define CTRL1_DG 0x10 #define CTRL1_AWB 0x08 #define CTRL1_AWB_GAIN 0x04 #define CTRL1_LENC 0x02 #define CTRL1_PRE 0x01 /* REG 0xC7 (unknown name): affects Auto White Balance (AWB) * AWB_OFF 0x40 * AWB_SIMPLE 0x10 * AWB_ON 0x00 (Advanced AWB ?) */ #define R_DVP_SP 0xD3 /* DVP output speed control */ #define R_DVP_SP_AUTO_MODE 0x80 #define R_DVP_SP_DVP_MASK 0x3F /* DVP PCLK = sysclk (48)/[6:0] (YUV0); * = sysclk (48)/(2*[6:0]) (RAW);*/ #define IMAGE_MODE 0xDA /* Image Output Format Select */ #define IMAGE_MODE_Y8_DVP_EN 0x40 #define IMAGE_MODE_JPEG_EN 0x10 #define IMAGE_MODE_YUV422 0x00 #define IMAGE_MODE_RAW10 0x04 /* (DVP) */ #define IMAGE_MODE_RGB565 0x08 #define IMAGE_MODE_HREF_VSYNC 0x02 /* HREF timing select in DVP JPEG output * mode (0 for HREF is same as sensor) */ #define IMAGE_MODE_LBYTE_FIRST 0x01 /* Byte swap enable for DVP * 1: Low byte first UYVY (C2[4] =0) * VYUY (C2[4] =1) * 0: High byte first YUYV (C2[4]=0) * YVYU (C2[4] = 1) */ #define RESET 0xE0 /* Reset */ #define RESET_MICROC 0x40 #define RESET_SCCB 0x20 #define RESET_JPEG 0x10 #define RESET_DVP 0x04 #define RESET_IPU 0x02 #define RESET_CIF 0x01 #define REGED 0xED /* Register ED */ #define REGED_CLK_OUT_DIS 0x10 #define MS_SP 0xF0 /* SCCB Master Speed */ #define SS_ID 0xF7 /* SCCB Slave ID */ #define SS_CTRL 0xF8 /* SCCB Slave Control */ #define SS_CTRL_ADD_AUTO_INC 0x20 #define SS_CTRL_EN 0x08 #define SS_CTRL_DELAY_CLK 0x04 #define SS_CTRL_ACC_EN 0x02 #define SS_CTRL_SEN_PASS_THR 0x01 #define MC_BIST 0xF9 /* Microcontroller misc register */ #define MC_BIST_RESET 0x80 /* Microcontroller Reset */ #define MC_BIST_BOOT_ROM_SEL 0x40 #define MC_BIST_12KB_SEL 0x20 #define MC_BIST_12KB_MASK 0x30 #define MC_BIST_512KB_SEL 0x08 #define MC_BIST_512KB_MASK 0x0C #define MC_BIST_BUSY_BIT_R 0x02 #define MC_BIST_MC_RES_ONE_SH_W 0x02 #define MC_BIST_LAUNCH 0x01 #define BANK_SEL 0xFF /* Register Bank Select */ #define BANK_SEL_DSP 0x00 #define BANK_SEL_SENS 0x01 /* * Sensor registers * register offset for BANK_SEL == BANK_SEL_SENS */ #define GAIN 0x00 /* AGC - Gain control gain setting */ #define COM1 0x03 /* Common control 1 */ #define COM1_1_DUMMY_FR 0x40 #define COM1_3_DUMMY_FR 0x80 #define COM1_7_DUMMY_FR 0xC0 #define COM1_VWIN_LSB_UXGA 0x0F #define COM1_VWIN_LSB_SVGA 0x0A #define COM1_VWIN_LSB_CIF 0x06 #define REG04 0x04 /* Register 04 */ #define REG04_DEF 0x20 /* Always set */ #define REG04_HFLIP_IMG 0x80 /* Horizontal mirror image ON/OFF */ #define REG04_VFLIP_IMG 0x40 /* Vertical flip image ON/OFF */ #define REG04_VREF_EN 0x10 #define REG04_HREF_EN 0x08 #define REG04_AEC_SET(x) VAL_SET(x, 0x3, 0, 0) #define REG08 0x08 /* Frame Exposure One-pin Control Pre-charge Row Num */ #define COM2 0x09 /* Common control 2 */ #define COM2_SOFT_SLEEP_MODE 0x10 /* Soft sleep mode */ /* Output drive capability */ #define COM2_OCAP_Nx_SET(N) (((N) - 1) & 0x03) /* N = [1x .. 4x] */ #define PID 0x0A /* Product ID Number MSB */ #define VER 0x0B /* Product ID Number LSB */ #define COM3 0x0C /* Common control 3 */ #define COM3_BAND_50H 0x04 /* 0 For Banding at 60H */ #define COM3_BAND_AUTO 0x02 /* Auto Banding */ #define COM3_SING_FR_SNAPSH 0x01 /* 0 For enable live video output after the * snapshot sequence*/ #define AEC 0x10 /* AEC[9:2] Exposure Value */ #define CLKRC 0x11 /* Internal clock */ #define CLKRC_EN 0x80 #define CLKRC_DIV_SET(x) (((x) - 1) & 0x1F) /* CLK = XVCLK/(x) */ #define COM7 0x12 /* Common control 7 */ #define COM7_SRST 0x80 /* Initiates system reset. All registers are * set to factory default values after which * the chip resumes normal operation */ #define COM7_RES_UXGA 0x00 /* Resolution selectors for UXGA */ #define COM7_RES_SVGA 0x40 /* SVGA */ #define COM7_RES_CIF 0x20 /* CIF */ #define COM7_ZOOM_EN 0x04 /* Enable Zoom mode */ #define COM7_COLOR_BAR_TEST 0x02 /* Enable Color Bar Test Pattern */ #define COM8 0x13 /* Common control 8 */ #define COM8_DEF 0xC0 #define COM8_BNDF_EN 0x20 /* Banding filter ON/OFF */ #define COM8_AGC_EN 0x04 /* AGC Auto/Manual control selection */ #define COM8_AEC_EN 0x01 /* Auto/Manual Exposure control */ #define COM9 0x14 /* Common control 9 * Automatic gain ceiling - maximum AGC value [7:5]*/ #define COM9_AGC_GAIN_2x 0x00 /* 000 : 2x */ #define COM9_AGC_GAIN_4x 0x20 /* 001 : 4x */ #define COM9_AGC_GAIN_8x 0x40 /* 010 : 8x */ #define COM9_AGC_GAIN_16x 0x60 /* 011 : 16x */ #define COM9_AGC_GAIN_32x 0x80 /* 100 : 32x */ #define COM9_AGC_GAIN_64x 0xA0 /* 101 : 64x */ #define COM9_AGC_GAIN_128x 0xC0 /* 110 : 128x */ #define COM10 0x15 /* Common control 10 */ #define COM10_PCLK_HREF 0x20 /* PCLK output qualified by HREF */ #define COM10_PCLK_RISE 0x10 /* Data is updated at the rising edge of * PCLK (user can latch data at the next * falling edge of PCLK). * 0 otherwise. */ #define COM10_HREF_INV 0x08 /* Invert HREF polarity: * HREF negative for valid data*/ #define COM10_VSINC_INV 0x02 /* Invert VSYNC polarity */ #define HSTART 0x17 /* Horizontal Window start MSB 8 bit */ #define HEND 0x18 /* Horizontal Window end MSB 8 bit */ #define VSTART 0x19 /* Vertical Window start MSB 8 bit */ #define VEND 0x1A /* Vertical Window end MSB 8 bit */ #define MIDH 0x1C /* Manufacturer ID byte - high */ #define MIDL 0x1D /* Manufacturer ID byte - low */ #define AEW 0x24 /* AGC/AEC - Stable operating region (upper limit) */ #define AEB 0x25 /* AGC/AEC - Stable operating region (lower limit) */ #define VV 0x26 /* AGC/AEC Fast mode operating region */ #define VV_HIGH_TH_SET(x) VAL_SET(x, 0xF, 0, 4) #define VV_LOW_TH_SET(x) VAL_SET(x, 0xF, 0, 0) #define REG2A 0x2A /* Dummy pixel insert MSB */ #define FRARL 0x2B /* Dummy pixel insert LSB */ #define ADDVFL 0x2D /* LSB of insert dummy lines in Vertical direction */ #define ADDVFH 0x2E /* MSB of insert dummy lines in Vertical direction */ #define YAVG 0x2F /* Y/G Channel Average value */ #define REG32 0x32 /* Common Control 32 */ #define REG32_PCLK_DIV_2 0x80 /* PCLK freq divided by 2 */ #define REG32_PCLK_DIV_4 0xC0 /* PCLK freq divided by 4 */ #define ARCOM2 0x34 /* Zoom: Horizontal start point */ #define REG45 0x45 /* Register 45 */ #define FLL 0x46 /* Frame Length Adjustment LSBs */ #define FLH 0x47 /* Frame Length Adjustment MSBs */ #define COM19 0x48 /* Zoom: Vertical start point */ #define ZOOMS 0x49 /* Zoom: Vertical start point */ #define COM22 0x4B /* Flash light control */ #define COM25 0x4E /* For Banding operations */ #define COM25_50HZ_BANDING_AEC_MSBS_MASK 0xC0 /* 50Hz Bd. AEC 2 MSBs */ #define COM25_60HZ_BANDING_AEC_MSBS_MASK 0x30 /* 60Hz Bd. AEC 2 MSBs */ #define COM25_50HZ_BANDING_AEC_MSBS_SET(x) VAL_SET(x, 0x3, 8, 6) #define COM25_60HZ_BANDING_AEC_MSBS_SET(x) VAL_SET(x, 0x3, 8, 4) #define BD50 0x4F /* 50Hz Banding AEC 8 LSBs */ #define BD50_50HZ_BANDING_AEC_LSBS_SET(x) VAL_SET(x, 0xFF, 0, 0) #define BD60 0x50 /* 60Hz Banding AEC 8 LSBs */ #define BD60_60HZ_BANDING_AEC_LSBS_SET(x) VAL_SET(x, 0xFF, 0, 0) #define REG5A 0x5A /* 50/60Hz Banding Maximum AEC Step */ #define BD50_MAX_AEC_STEP_MASK 0xF0 /* 50Hz Banding Max. AEC Step */ #define BD60_MAX_AEC_STEP_MASK 0x0F /* 60Hz Banding Max. AEC Step */ #define BD50_MAX_AEC_STEP_SET(x) VAL_SET((x - 1), 0x0F, 0, 4) #define BD60_MAX_AEC_STEP_SET(x) VAL_SET((x - 1), 0x0F, 0, 0) #define REG5D 0x5D /* AVGsel[7:0], 16-zone average weight option */ #define REG5E 0x5E /* AVGsel[15:8], 16-zone average weight option */ #define REG5F 0x5F /* AVGsel[23:16], 16-zone average weight option */ #define REG60 0x60 /* AVGsel[31:24], 16-zone average weight option */ #define HISTO_LOW 0x61 /* Histogram Algorithm Low Level */ #define HISTO_HIGH 0x62 /* Histogram Algorithm High Level */ /* * ID */ #define MANUFACTURER_ID 0x7FA2 #define PID_OV2640 0x2642 #define VERSION(pid, ver) ((pid << 8) | (ver & 0xFF)) /* * Struct */ struct regval_list { u8 reg_num; u8 value; }; struct ov2640_win_size { char *name; u32 width; u32 height; const struct regval_list *regs; }; struct ov2640_priv { struct v4l2_subdev subdev; #if defined(CONFIG_MEDIA_CONTROLLER) struct media_pad pad; #endif struct v4l2_ctrl_handler hdl; u32 cfmt_code; struct clk *clk; const struct ov2640_win_size *win; struct gpio_desc *resetb_gpio; struct gpio_desc *pwdn_gpio; struct mutex lock; /* lock to protect streaming and power_count */ bool streaming; int power_count; }; /* * Registers settings */ #define ENDMARKER { 0xff, 0xff } static const struct regval_list ov2640_init_regs[] = { { BANK_SEL, BANK_SEL_DSP }, { 0x2c, 0xff }, { 0x2e, 0xdf }, { BANK_SEL, BANK_SEL_SENS }, { 0x3c, 0x32 }, { CLKRC, CLKRC_DIV_SET(1) }, { COM2, COM2_OCAP_Nx_SET(3) }, { REG04, REG04_DEF | REG04_HREF_EN }, { COM8, COM8_DEF | COM8_BNDF_EN | COM8_AGC_EN | COM8_AEC_EN }, { COM9, COM9_AGC_GAIN_8x | 0x08}, { 0x2c, 0x0c }, { 0x33, 0x78 }, { 0x3a, 0x33 }, { 0x3b, 0xfb }, { 0x3e, 0x00 }, { 0x43, 0x11 }, { 0x16, 0x10 }, { 0x39, 0x02 }, { 0x35, 0x88 }, { 0x22, 0x0a }, { 0x37, 0x40 }, { 0x23, 0x00 }, { ARCOM2, 0xa0 }, { 0x06, 0x02 }, { 0x06, 0x88 }, { 0x07, 0xc0 }, { 0x0d, 0xb7 }, { 0x0e, 0x01 }, { 0x4c, 0x00 }, { 0x4a, 0x81 }, { 0x21, 0x99 }, { AEW, 0x40 }, { AEB, 0x38 }, { VV, VV_HIGH_TH_SET(0x08) | VV_LOW_TH_SET(0x02) }, { 0x5c, 0x00 }, { 0x63, 0x00 }, { FLL, 0x22 }, { COM3, 0x38 | COM3_BAND_AUTO }, { REG5D, 0x55 }, { REG5E, 0x7d }, { REG5F, 0x7d }, { REG60, 0x55 }, { HISTO_LOW, 0x70 }, { HISTO_HIGH, 0x80 }, { 0x7c, 0x05 }, { 0x20, 0x80 }, { 0x28, 0x30 }, { 0x6c, 0x00 }, { 0x6d, 0x80 }, { 0x6e, 0x00 }, { 0x70, 0x02 }, { 0x71, 0x94 }, { 0x73, 0xc1 }, { 0x3d, 0x34 }, { COM7, COM7_RES_UXGA | COM7_ZOOM_EN }, { REG5A, BD50_MAX_AEC_STEP_SET(6) | BD60_MAX_AEC_STEP_SET(8) }, /* 0x57 */ { COM25, COM25_50HZ_BANDING_AEC_MSBS_SET(0x0bb) | COM25_60HZ_BANDING_AEC_MSBS_SET(0x09c) }, /* 0x00 */ { BD50, BD50_50HZ_BANDING_AEC_LSBS_SET(0x0bb) }, /* 0xbb */ { BD60, BD60_60HZ_BANDING_AEC_LSBS_SET(0x09c) }, /* 0x9c */ { BANK_SEL, BANK_SEL_DSP }, { 0xe5, 0x7f }, { MC_BIST, MC_BIST_RESET | MC_BIST_BOOT_ROM_SEL }, { 0x41, 0x24 }, { RESET, RESET_JPEG | RESET_DVP }, { 0x76, 0xff }, { 0x33, 0xa0 }, { 0x42, 0x20 }, { 0x43, 0x18 }, { 0x4c, 0x00 }, { CTRL3, CTRL3_BPC_EN | CTRL3_WPC_EN | 0x10 }, { 0x88, 0x3f }, { 0xd7, 0x03 }, { 0xd9, 0x10 }, { R_DVP_SP, R_DVP_SP_AUTO_MODE | 0x2 }, { 0xc8, 0x08 }, { 0xc9, 0x80 }, { BPADDR, 0x00 }, { BPDATA, 0x00 }, { BPADDR, 0x03 }, { BPDATA, 0x48 }, { BPDATA, 0x48 }, { BPADDR, 0x08 }, { BPDATA, 0x20 }, { BPDATA, 0x10 }, { BPDATA, 0x0e }, { 0x90, 0x00 }, { 0x91, 0x0e }, { 0x91, 0x1a }, { 0x91, 0x31 }, { 0x91, 0x5a }, { 0x91, 0x69 }, { 0x91, 0x75 }, { 0x91, 0x7e }, { 0x91, 0x88 }, { 0x91, 0x8f }, { 0x91, 0x96 }, { 0x91, 0xa3 }, { 0x91, 0xaf }, { 0x91, 0xc4 }, { 0x91, 0xd7 }, { 0x91, 0xe8 }, { 0x91, 0x20 }, { 0x92, 0x00 }, { 0x93, 0x06 }, { 0x93, 0xe3 }, { 0x93, 0x03 }, { 0x93, 0x03 }, { 0x93, 0x00 }, { 0x93, 0x02 }, { 0x93, 0x00 }, { 0x93, 0x00 }, { 0x93, 0x00 }, { 0x93, 0x00 }, { 0x93, 0x00 }, { 0x93, 0x00 }, { 0x93, 0x00 }, { 0x96, 0x00 }, { 0x97, 0x08 }, { 0x97, 0x19 }, { 0x97, 0x02 }, { 0x97, 0x0c }, { 0x97, 0x24 }, { 0x97, 0x30 }, { 0x97, 0x28 }, { 0x97, 0x26 }, { 0x97, 0x02 }, { 0x97, 0x98 }, { 0x97, 0x80 }, { 0x97, 0x00 }, { 0x97, 0x00 }, { 0xa4, 0x00 }, { 0xa8, 0x00 }, { 0xc5, 0x11 }, { 0xc6, 0x51 }, { 0xbf, 0x80 }, { 0xc7, 0x10 }, /* simple AWB */ { 0xb6, 0x66 }, { 0xb8, 0xA5 }, { 0xb7, 0x64 }, { 0xb9, 0x7C }, { 0xb3, 0xaf }, { 0xb4, 0x97 }, { 0xb5, 0xFF }, { 0xb0, 0xC5 }, { 0xb1, 0x94 }, { 0xb2, 0x0f }, { 0xc4, 0x5c }, { 0xa6, 0x00 }, { 0xa7, 0x20 }, { 0xa7, 0xd8 }, { 0xa7, 0x1b }, { 0xa7, 0x31 }, { 0xa7, 0x00 }, { 0xa7, 0x18 }, { 0xa7, 0x20 }, { 0xa7, 0xd8 }, { 0xa7, 0x19 }, { 0xa7, 0x31 }, { 0xa7, 0x00 }, { 0xa7, 0x18 }, { 0xa7, 0x20 }, { 0xa7, 0xd8 }, { 0xa7, 0x19 }, { 0xa7, 0x31 }, { 0xa7, 0x00 }, { 0xa7, 0x18 }, { 0x7f, 0x00 }, { 0xe5, 0x1f }, { 0xe1, 0x77 }, { 0xdd, 0x7f }, { CTRL0, CTRL0_YUV422 | CTRL0_YUV_EN | CTRL0_RGB_EN }, ENDMARKER, }; /* * Register settings for window size * The preamble, setup the internal DSP to input an UXGA (1600x1200) image. * Then the different zooming configurations will setup the output image size. */ static const struct regval_list ov2640_size_change_preamble_regs[] = { { BANK_SEL, BANK_SEL_DSP }, { RESET, RESET_DVP }, { SIZEL, SIZEL_HSIZE8_11_SET(UXGA_WIDTH) | SIZEL_HSIZE8_SET(UXGA_WIDTH) | SIZEL_VSIZE8_SET(UXGA_HEIGHT) }, { HSIZE8, HSIZE8_SET(UXGA_WIDTH) }, { VSIZE8, VSIZE8_SET(UXGA_HEIGHT) }, { CTRL2, CTRL2_DCW_EN | CTRL2_SDE_EN | CTRL2_UV_AVG_EN | CTRL2_CMX_EN | CTRL2_UV_ADJ_EN }, { HSIZE, HSIZE_SET(UXGA_WIDTH) }, { VSIZE, VSIZE_SET(UXGA_HEIGHT) }, { XOFFL, XOFFL_SET(0) }, { YOFFL, YOFFL_SET(0) }, { VHYX, VHYX_HSIZE_SET(UXGA_WIDTH) | VHYX_VSIZE_SET(UXGA_HEIGHT) | VHYX_XOFF_SET(0) | VHYX_YOFF_SET(0)}, { TEST, TEST_HSIZE_SET(UXGA_WIDTH) }, ENDMARKER, }; #define PER_SIZE_REG_SEQ(x, y, v_div, h_div, pclk_div) \ { CTRLI, CTRLI_LP_DP | CTRLI_V_DIV_SET(v_div) | \ CTRLI_H_DIV_SET(h_div)}, \ { ZMOW, ZMOW_OUTW_SET(x) }, \ { ZMOH, ZMOH_OUTH_SET(y) }, \ { ZMHH, ZMHH_OUTW_SET(x) | ZMHH_OUTH_SET(y) }, \ { R_DVP_SP, pclk_div }, \ { RESET, 0x00} static const struct regval_list ov2640_qcif_regs[] = { PER_SIZE_REG_SEQ(QCIF_WIDTH, QCIF_HEIGHT, 3, 3, 4), ENDMARKER, }; static const struct regval_list ov2640_qvga_regs[] = { PER_SIZE_REG_SEQ(QVGA_WIDTH, QVGA_HEIGHT, 2, 2, 4), ENDMARKER, }; static const struct regval_list ov2640_cif_regs[] = { PER_SIZE_REG_SEQ(CIF_WIDTH, CIF_HEIGHT, 2, 2, 8), ENDMARKER, }; static const struct regval_list ov2640_vga_regs[] = { PER_SIZE_REG_SEQ(VGA_WIDTH, VGA_HEIGHT, 0, 0, 2), ENDMARKER, }; static const struct regval_list ov2640_svga_regs[] = { PER_SIZE_REG_SEQ(SVGA_WIDTH, SVGA_HEIGHT, 1, 1, 2), ENDMARKER, }; static const struct regval_list ov2640_xga_regs[] = { PER_SIZE_REG_SEQ(XGA_WIDTH, XGA_HEIGHT, 0, 0, 2), { CTRLI, 0x00}, ENDMARKER, }; static const struct regval_list ov2640_sxga_regs[] = { PER_SIZE_REG_SEQ(SXGA_WIDTH, SXGA_HEIGHT, 0, 0, 2), { CTRLI, 0x00}, { R_DVP_SP, 2 | R_DVP_SP_AUTO_MODE }, ENDMARKER, }; static const struct regval_list ov2640_uxga_regs[] = { PER_SIZE_REG_SEQ(UXGA_WIDTH, UXGA_HEIGHT, 0, 0, 0), { CTRLI, 0x00}, { R_DVP_SP, 0 | R_DVP_SP_AUTO_MODE }, ENDMARKER, }; #define OV2640_SIZE(n, w, h, r) \ {.name = n, .width = w , .height = h, .regs = r } static const struct ov2640_win_size ov2640_supported_win_sizes[] = { OV2640_SIZE("QCIF", QCIF_WIDTH, QCIF_HEIGHT, ov2640_qcif_regs), OV2640_SIZE("QVGA", QVGA_WIDTH, QVGA_HEIGHT, ov2640_qvga_regs), OV2640_SIZE("CIF", CIF_WIDTH, CIF_HEIGHT, ov2640_cif_regs), OV2640_SIZE("VGA", VGA_WIDTH, VGA_HEIGHT, ov2640_vga_regs), OV2640_SIZE("SVGA", SVGA_WIDTH, SVGA_HEIGHT, ov2640_svga_regs), OV2640_SIZE("XGA", XGA_WIDTH, XGA_HEIGHT, ov2640_xga_regs), OV2640_SIZE("SXGA", SXGA_WIDTH, SXGA_HEIGHT, ov2640_sxga_regs), OV2640_SIZE("UXGA", UXGA_WIDTH, UXGA_HEIGHT, ov2640_uxga_regs), }; /* * Register settings for pixel formats */ static const struct regval_list ov2640_format_change_preamble_regs[] = { { BANK_SEL, BANK_SEL_DSP }, { R_BYPASS, R_BYPASS_USE_DSP }, ENDMARKER, }; static const struct regval_list ov2640_yuyv_regs[] = { { IMAGE_MODE, IMAGE_MODE_YUV422 }, { 0xd7, 0x03 }, { 0x33, 0xa0 }, { 0xe5, 0x1f }, { 0xe1, 0x67 }, { RESET, 0x00 }, { R_BYPASS, R_BYPASS_USE_DSP }, ENDMARKER, }; static const struct regval_list ov2640_uyvy_regs[] = { { IMAGE_MODE, IMAGE_MODE_LBYTE_FIRST | IMAGE_MODE_YUV422 }, { 0xd7, 0x01 }, { 0x33, 0xa0 }, { 0xe1, 0x67 }, { RESET, 0x00 }, { R_BYPASS, R_BYPASS_USE_DSP }, ENDMARKER, }; static const struct regval_list ov2640_rgb565_be_regs[] = { { IMAGE_MODE, IMAGE_MODE_RGB565 }, { 0xd7, 0x03 }, { RESET, 0x00 }, { R_BYPASS, R_BYPASS_USE_DSP }, ENDMARKER, }; static const struct regval_list ov2640_rgb565_le_regs[] = { { IMAGE_MODE, IMAGE_MODE_LBYTE_FIRST | IMAGE_MODE_RGB565 }, { 0xd7, 0x03 }, { RESET, 0x00 }, { R_BYPASS, R_BYPASS_USE_DSP }, ENDMARKER, }; static u32 ov2640_codes[] = { MEDIA_BUS_FMT_YUYV8_2X8, MEDIA_BUS_FMT_UYVY8_2X8, MEDIA_BUS_FMT_YVYU8_2X8, MEDIA_BUS_FMT_VYUY8_2X8, MEDIA_BUS_FMT_RGB565_2X8_BE, MEDIA_BUS_FMT_RGB565_2X8_LE, }; /* * General functions */ static struct ov2640_priv *to_ov2640(const struct i2c_client *client) { return container_of(i2c_get_clientdata(client), struct ov2640_priv, subdev); } static int ov2640_write_array(struct i2c_client *client, const struct regval_list *vals) { int ret; while ((vals->reg_num != 0xff) || (vals->value != 0xff)) { ret = i2c_smbus_write_byte_data(client, vals->reg_num, vals->value); dev_vdbg(&client->dev, "array: 0x%02x, 0x%02x", vals->reg_num, vals->value); if (ret < 0) return ret; vals++; } return 0; } static int ov2640_mask_set(struct i2c_client *client, u8 reg, u8 mask, u8 set) { s32 val = i2c_smbus_read_byte_data(client, reg); if (val < 0) return val; val &= ~mask; val |= set & mask; dev_vdbg(&client->dev, "masks: 0x%02x, 0x%02x", reg, val); return i2c_smbus_write_byte_data(client, reg, val); } static int ov2640_reset(struct i2c_client *client) { int ret; static const struct regval_list reset_seq[] = { {BANK_SEL, BANK_SEL_SENS}, {COM7, COM7_SRST}, ENDMARKER, }; ret = ov2640_write_array(client, reset_seq); if (ret) goto err; msleep(5); err: dev_dbg(&client->dev, "%s: (ret %d)", __func__, ret); return ret; } static const char * const ov2640_test_pattern_menu[] = { "Disabled", "Eight Vertical Colour Bars", }; /* * functions */ static int ov2640_s_ctrl(struct v4l2_ctrl *ctrl) { struct v4l2_subdev *sd = &container_of(ctrl->handler, struct ov2640_priv, hdl)->subdev; struct i2c_client *client = v4l2_get_subdevdata(sd); struct ov2640_priv *priv = to_ov2640(client); u8 val; int ret; /* v4l2_ctrl_lock() locks our own mutex */ /* * If the device is not powered up by the host driver, do not apply any * controls to H/W at this time. Instead the controls will be restored * when the streaming is started. */ if (!priv->power_count) return 0; ret = i2c_smbus_write_byte_data(client, BANK_SEL, BANK_SEL_SENS); if (ret < 0) return ret; switch (ctrl->id) { case V4L2_CID_VFLIP: val = ctrl->val ? REG04_VFLIP_IMG | REG04_VREF_EN : 0x00; return ov2640_mask_set(client, REG04, REG04_VFLIP_IMG | REG04_VREF_EN, val); /* NOTE: REG04_VREF_EN: 1 line shift / even/odd line swap */ case V4L2_CID_HFLIP: val = ctrl->val ? REG04_HFLIP_IMG : 0x00; return ov2640_mask_set(client, REG04, REG04_HFLIP_IMG, val); case V4L2_CID_TEST_PATTERN: val = ctrl->val ? COM7_COLOR_BAR_TEST : 0x00; return ov2640_mask_set(client, COM7, COM7_COLOR_BAR_TEST, val); } return -EINVAL; } #ifdef CONFIG_VIDEO_ADV_DEBUG static int ov2640_g_register(struct v4l2_subdev *sd, struct v4l2_dbg_register *reg) { struct i2c_client *client = v4l2_get_subdevdata(sd); int ret; reg->size = 1; if (reg->reg > 0xff) return -EINVAL; ret = i2c_smbus_read_byte_data(client, reg->reg); if (ret < 0) return ret; reg->val = ret; return 0; } static int ov2640_s_register(struct v4l2_subdev *sd, const struct v4l2_dbg_register *reg) { struct i2c_client *client = v4l2_get_subdevdata(sd); if (reg->reg > 0xff || reg->val > 0xff) return -EINVAL; return i2c_smbus_write_byte_data(client, reg->reg, reg->val); } #endif static void ov2640_set_power(struct ov2640_priv *priv, int on) { #ifdef CONFIG_GPIOLIB if (priv->pwdn_gpio) gpiod_direction_output(priv->pwdn_gpio, !on); if (on && priv->resetb_gpio) { /* Active the resetb pin to perform a reset pulse */ gpiod_direction_output(priv->resetb_gpio, 1); usleep_range(3000, 5000); gpiod_set_value(priv->resetb_gpio, 0); } #endif } static int ov2640_s_power(struct v4l2_subdev *sd, int on) { struct i2c_client *client = v4l2_get_subdevdata(sd); struct ov2640_priv *priv = to_ov2640(client); mutex_lock(&priv->lock); /* * If the power count is modified from 0 to != 0 or from != 0 to 0, * update the power state. */ if (priv->power_count == !on) ov2640_set_power(priv, on); priv->power_count += on ? 1 : -1; WARN_ON(priv->power_count < 0); mutex_unlock(&priv->lock); return 0; } /* Select the nearest higher resolution for capture */ static const struct ov2640_win_size *ov2640_select_win(u32 width, u32 height) { int i, default_size = ARRAY_SIZE(ov2640_supported_win_sizes) - 1; for (i = 0; i < ARRAY_SIZE(ov2640_supported_win_sizes); i++) { if (ov2640_supported_win_sizes[i].width >= width && ov2640_supported_win_sizes[i].height >= height) return &ov2640_supported_win_sizes[i]; } return &ov2640_supported_win_sizes[default_size]; } static int ov2640_set_params(struct i2c_client *client, const struct ov2640_win_size *win, u32 code) { const struct regval_list *selected_cfmt_regs; u8 val; int ret; switch (code) { case MEDIA_BUS_FMT_RGB565_2X8_BE: dev_dbg(&client->dev, "%s: Selected cfmt RGB565 BE", __func__); selected_cfmt_regs = ov2640_rgb565_be_regs; break; case MEDIA_BUS_FMT_RGB565_2X8_LE: dev_dbg(&client->dev, "%s: Selected cfmt RGB565 LE", __func__); selected_cfmt_regs = ov2640_rgb565_le_regs; break; case MEDIA_BUS_FMT_YUYV8_2X8: dev_dbg(&client->dev, "%s: Selected cfmt YUYV (YUV422)", __func__); selected_cfmt_regs = ov2640_yuyv_regs; break; case MEDIA_BUS_FMT_UYVY8_2X8: default: dev_dbg(&client->dev, "%s: Selected cfmt UYVY", __func__); selected_cfmt_regs = ov2640_uyvy_regs; break; case MEDIA_BUS_FMT_YVYU8_2X8: dev_dbg(&client->dev, "%s: Selected cfmt YVYU", __func__); selected_cfmt_regs = ov2640_yuyv_regs; break; case MEDIA_BUS_FMT_VYUY8_2X8: dev_dbg(&client->dev, "%s: Selected cfmt VYUY", __func__); selected_cfmt_regs = ov2640_uyvy_regs; break; } /* reset hardware */ ov2640_reset(client); /* initialize the sensor with default data */ dev_dbg(&client->dev, "%s: Init default", __func__); ret = ov2640_write_array(client, ov2640_init_regs); if (ret < 0) goto err; /* select preamble */ dev_dbg(&client->dev, "%s: Set size to %s", __func__, win->name); ret = ov2640_write_array(client, ov2640_size_change_preamble_regs); if (ret < 0) goto err; /* set size win */ ret = ov2640_write_array(client, win->regs); if (ret < 0) goto err; /* cfmt preamble */ dev_dbg(&client->dev, "%s: Set cfmt", __func__); ret = ov2640_write_array(client, ov2640_format_change_preamble_regs); if (ret < 0) goto err; /* set cfmt */ ret = ov2640_write_array(client, selected_cfmt_regs); if (ret < 0) goto err; val = (code == MEDIA_BUS_FMT_YVYU8_2X8) || (code == MEDIA_BUS_FMT_VYUY8_2X8) ? CTRL0_VFIRST : 0x00; ret = ov2640_mask_set(client, CTRL0, CTRL0_VFIRST, val); if (ret < 0) goto err; return 0; err: dev_err(&client->dev, "%s: Error %d", __func__, ret); ov2640_reset(client); return ret; } static int ov2640_get_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *format) { struct v4l2_mbus_framefmt *mf = &format->format; struct i2c_client *client = v4l2_get_subdevdata(sd); struct ov2640_priv *priv = to_ov2640(client); if (format->pad) return -EINVAL; if (format->which == V4L2_SUBDEV_FORMAT_TRY) { #ifdef CONFIG_VIDEO_V4L2_SUBDEV_API mf = v4l2_subdev_get_try_format(sd, sd_state, 0); format->format = *mf; return 0; #else return -EINVAL; #endif } mf->width = priv->win->width; mf->height = priv->win->height; mf->code = priv->cfmt_code; mf->colorspace = V4L2_COLORSPACE_SRGB; mf->field = V4L2_FIELD_NONE; mf->ycbcr_enc = V4L2_YCBCR_ENC_DEFAULT; mf->quantization = V4L2_QUANTIZATION_DEFAULT; mf->xfer_func = V4L2_XFER_FUNC_DEFAULT; return 0; } static int ov2640_set_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *format) { struct v4l2_mbus_framefmt *mf = &format->format; struct i2c_client *client = v4l2_get_subdevdata(sd); struct ov2640_priv *priv = to_ov2640(client); const struct ov2640_win_size *win; int ret = 0; if (format->pad) return -EINVAL; mutex_lock(&priv->lock); /* select suitable win */ win = ov2640_select_win(mf->width, mf->height); mf->width = win->width; mf->height = win->height; mf->field = V4L2_FIELD_NONE; mf->colorspace = V4L2_COLORSPACE_SRGB; mf->ycbcr_enc = V4L2_YCBCR_ENC_DEFAULT; mf->quantization = V4L2_QUANTIZATION_DEFAULT; mf->xfer_func = V4L2_XFER_FUNC_DEFAULT; switch (mf->code) { case MEDIA_BUS_FMT_RGB565_2X8_BE: case MEDIA_BUS_FMT_RGB565_2X8_LE: case MEDIA_BUS_FMT_YUYV8_2X8: case MEDIA_BUS_FMT_UYVY8_2X8: case MEDIA_BUS_FMT_YVYU8_2X8: case MEDIA_BUS_FMT_VYUY8_2X8: break; default: mf->code = MEDIA_BUS_FMT_UYVY8_2X8; break; } if (format->which == V4L2_SUBDEV_FORMAT_ACTIVE) { struct ov2640_priv *priv = to_ov2640(client); if (priv->streaming) { ret = -EBUSY; goto out; } /* select win */ priv->win = win; /* select format */ priv->cfmt_code = mf->code; } else { sd_state->pads->try_fmt = *mf; } out: mutex_unlock(&priv->lock); return ret; } static int ov2640_init_cfg(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state) { #ifdef CONFIG_VIDEO_V4L2_SUBDEV_API struct v4l2_mbus_framefmt *try_fmt = v4l2_subdev_get_try_format(sd, sd_state, 0); const struct ov2640_win_size *win = ov2640_select_win(SVGA_WIDTH, SVGA_HEIGHT); try_fmt->width = win->width; try_fmt->height = win->height; try_fmt->code = MEDIA_BUS_FMT_UYVY8_2X8; try_fmt->colorspace = V4L2_COLORSPACE_SRGB; try_fmt->field = V4L2_FIELD_NONE; try_fmt->ycbcr_enc = V4L2_YCBCR_ENC_DEFAULT; try_fmt->quantization = V4L2_QUANTIZATION_DEFAULT; try_fmt->xfer_func = V4L2_XFER_FUNC_DEFAULT; #endif return 0; } static int ov2640_enum_mbus_code(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_mbus_code_enum *code) { if (code->pad || code->index >= ARRAY_SIZE(ov2640_codes)) return -EINVAL; code->code = ov2640_codes[code->index]; return 0; } static int ov2640_get_selection(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_selection *sel) { if (sel->which != V4L2_SUBDEV_FORMAT_ACTIVE) return -EINVAL; switch (sel->target) { case V4L2_SEL_TGT_CROP_BOUNDS: case V4L2_SEL_TGT_CROP: sel->r.left = 0; sel->r.top = 0; sel->r.width = UXGA_WIDTH; sel->r.height = UXGA_HEIGHT; return 0; default: return -EINVAL; } } static int ov2640_s_stream(struct v4l2_subdev *sd, int on) { struct i2c_client *client = v4l2_get_subdevdata(sd); struct ov2640_priv *priv = to_ov2640(client); int ret = 0; mutex_lock(&priv->lock); if (priv->streaming == !on) { if (on) { ret = ov2640_set_params(client, priv->win, priv->cfmt_code); if (!ret) ret = __v4l2_ctrl_handler_setup(&priv->hdl); } } if (!ret) priv->streaming = on; mutex_unlock(&priv->lock); return ret; } static int ov2640_video_probe(struct i2c_client *client) { struct ov2640_priv *priv = to_ov2640(client); u8 pid, ver, midh, midl; const char *devname; int ret; ret = ov2640_s_power(&priv->subdev, 1); if (ret < 0) return ret; /* * check and show product ID and manufacturer ID */ i2c_smbus_write_byte_data(client, BANK_SEL, BANK_SEL_SENS); pid = i2c_smbus_read_byte_data(client, PID); ver = i2c_smbus_read_byte_data(client, VER); midh = i2c_smbus_read_byte_data(client, MIDH); midl = i2c_smbus_read_byte_data(client, MIDL); switch (VERSION(pid, ver)) { case PID_OV2640: devname = "ov2640"; break; default: dev_err(&client->dev, "Product ID error %x:%x\n", pid, ver); ret = -ENODEV; goto done; } dev_info(&client->dev, "%s Product ID %0x:%0x Manufacturer ID %x:%x\n", devname, pid, ver, midh, midl); done: ov2640_s_power(&priv->subdev, 0); return ret; } static const struct v4l2_ctrl_ops ov2640_ctrl_ops = { .s_ctrl = ov2640_s_ctrl, }; static const struct v4l2_subdev_core_ops ov2640_subdev_core_ops = { .log_status = v4l2_ctrl_subdev_log_status, .subscribe_event = v4l2_ctrl_subdev_subscribe_event, .unsubscribe_event = v4l2_event_subdev_unsubscribe, #ifdef CONFIG_VIDEO_ADV_DEBUG .g_register = ov2640_g_register, .s_register = ov2640_s_register, #endif .s_power = ov2640_s_power, }; static const struct v4l2_subdev_pad_ops ov2640_subdev_pad_ops = { .init_cfg = ov2640_init_cfg, .enum_mbus_code = ov2640_enum_mbus_code, .get_selection = ov2640_get_selection, .get_fmt = ov2640_get_fmt, .set_fmt = ov2640_set_fmt, }; static const struct v4l2_subdev_video_ops ov2640_subdev_video_ops = { .s_stream = ov2640_s_stream, }; static const struct v4l2_subdev_ops ov2640_subdev_ops = { .core = &ov2640_subdev_core_ops, .pad = &ov2640_subdev_pad_ops, .video = &ov2640_subdev_video_ops, }; static int ov2640_probe_dt(struct i2c_client *client, struct ov2640_priv *priv) { int ret; /* Request the reset GPIO deasserted */ priv->resetb_gpio = devm_gpiod_get_optional(&client->dev, "resetb", GPIOD_OUT_LOW); if (!priv->resetb_gpio) dev_dbg(&client->dev, "resetb gpio is not assigned!\n"); ret = PTR_ERR_OR_ZERO(priv->resetb_gpio); if (ret && ret != -ENOSYS) { dev_dbg(&client->dev, "Error %d while getting resetb gpio\n", ret); return ret; } /* Request the power down GPIO asserted */ priv->pwdn_gpio = devm_gpiod_get_optional(&client->dev, "pwdn", GPIOD_OUT_HIGH); if (!priv->pwdn_gpio) dev_dbg(&client->dev, "pwdn gpio is not assigned!\n"); ret = PTR_ERR_OR_ZERO(priv->pwdn_gpio); if (ret && ret != -ENOSYS) { dev_dbg(&client->dev, "Error %d while getting pwdn gpio\n", ret); return ret; } return 0; } /* * i2c_driver functions */ static int ov2640_probe(struct i2c_client *client) { struct ov2640_priv *priv; struct i2c_adapter *adapter = client->adapter; int ret; if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA)) { dev_err(&adapter->dev, "OV2640: I2C-Adapter doesn't support SMBUS\n"); return -EIO; } priv = devm_kzalloc(&client->dev, sizeof(*priv), GFP_KERNEL); if (!priv) return -ENOMEM; if (client->dev.of_node) { priv->clk = devm_clk_get(&client->dev, "xvclk"); if (IS_ERR(priv->clk)) return PTR_ERR(priv->clk); ret = clk_prepare_enable(priv->clk); if (ret) return ret; } ret = ov2640_probe_dt(client, priv); if (ret) goto err_clk; priv->win = ov2640_select_win(SVGA_WIDTH, SVGA_HEIGHT); priv->cfmt_code = MEDIA_BUS_FMT_UYVY8_2X8; v4l2_i2c_subdev_init(&priv->subdev, client, &ov2640_subdev_ops); priv->subdev.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE | V4L2_SUBDEV_FL_HAS_EVENTS; mutex_init(&priv->lock); v4l2_ctrl_handler_init(&priv->hdl, 3); priv->hdl.lock = &priv->lock; v4l2_ctrl_new_std(&priv->hdl, &ov2640_ctrl_ops, V4L2_CID_VFLIP, 0, 1, 1, 0); v4l2_ctrl_new_std(&priv->hdl, &ov2640_ctrl_ops, V4L2_CID_HFLIP, 0, 1, 1, 0); v4l2_ctrl_new_std_menu_items(&priv->hdl, &ov2640_ctrl_ops, V4L2_CID_TEST_PATTERN, ARRAY_SIZE(ov2640_test_pattern_menu) - 1, 0, 0, ov2640_test_pattern_menu); priv->subdev.ctrl_handler = &priv->hdl; if (priv->hdl.error) { ret = priv->hdl.error; goto err_hdl; } #if defined(CONFIG_MEDIA_CONTROLLER) priv->pad.flags = MEDIA_PAD_FL_SOURCE; priv->subdev.entity.function = MEDIA_ENT_F_CAM_SENSOR; ret = media_entity_pads_init(&priv->subdev.entity, 1, &priv->pad); if (ret < 0) goto err_hdl; #endif ret = ov2640_video_probe(client); if (ret < 0) goto err_videoprobe; ret = v4l2_async_register_subdev(&priv->subdev); if (ret < 0) goto err_videoprobe; dev_info(&adapter->dev, "OV2640 Probed\n"); return 0; err_videoprobe: media_entity_cleanup(&priv->subdev.entity); err_hdl: v4l2_ctrl_handler_free(&priv->hdl); mutex_destroy(&priv->lock); err_clk: clk_disable_unprepare(priv->clk); return ret; } static void ov2640_remove(struct i2c_client *client) { struct ov2640_priv *priv = to_ov2640(client); v4l2_async_unregister_subdev(&priv->subdev); v4l2_ctrl_handler_free(&priv->hdl); mutex_destroy(&priv->lock); media_entity_cleanup(&priv->subdev.entity); v4l2_device_unregister_subdev(&priv->subdev); clk_disable_unprepare(priv->clk); } static const struct i2c_device_id ov2640_id[] = { { "ov2640", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, ov2640_id); static const struct of_device_id ov2640_of_match[] = { {.compatible = "ovti,ov2640", }, {}, }; MODULE_DEVICE_TABLE(of, ov2640_of_match); static struct i2c_driver ov2640_i2c_driver = { .driver = { .name = "ov2640", .of_match_table = ov2640_of_match, }, .probe = ov2640_probe, .remove = ov2640_remove, .id_table = ov2640_id, }; module_i2c_driver(ov2640_i2c_driver); MODULE_DESCRIPTION("Driver for Omni Vision 2640 sensor"); MODULE_AUTHOR("Alberto Panizzo"); MODULE_LICENSE("GPL v2");
linux-master
drivers/media/i2c/ov2640.c
// SPDX-License-Identifier: GPL-2.0 /* * ov5695 driver * * Copyright (C) 2017 Fuzhou Rockchip Electronics Co., Ltd. */ #include <linux/clk.h> #include <linux/device.h> #include <linux/delay.h> #include <linux/gpio/consumer.h> #include <linux/i2c.h> #include <linux/module.h> #include <linux/pm_runtime.h> #include <linux/regulator/consumer.h> #include <linux/sysfs.h> #include <media/media-entity.h> #include <media/v4l2-async.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-subdev.h> #ifndef V4L2_CID_DIGITAL_GAIN #define V4L2_CID_DIGITAL_GAIN V4L2_CID_GAIN #endif /* 45Mhz * 4 Binning */ #define OV5695_PIXEL_RATE (45 * 1000 * 1000 * 4) #define OV5695_XVCLK_FREQ 24000000 #define CHIP_ID 0x005695 #define OV5695_REG_CHIP_ID 0x300a #define OV5695_REG_CTRL_MODE 0x0100 #define OV5695_MODE_SW_STANDBY 0x0 #define OV5695_MODE_STREAMING BIT(0) #define OV5695_REG_EXPOSURE 0x3500 #define OV5695_EXPOSURE_MIN 4 #define OV5695_EXPOSURE_STEP 1 #define OV5695_VTS_MAX 0x7fff #define OV5695_REG_ANALOG_GAIN 0x3509 #define ANALOG_GAIN_MIN 0x10 #define ANALOG_GAIN_MAX 0xf8 #define ANALOG_GAIN_STEP 1 #define ANALOG_GAIN_DEFAULT 0xf8 #define OV5695_REG_DIGI_GAIN_H 0x350a #define OV5695_REG_DIGI_GAIN_L 0x350b #define OV5695_DIGI_GAIN_L_MASK 0x3f #define OV5695_DIGI_GAIN_H_SHIFT 6 #define OV5695_DIGI_GAIN_MIN 0 #define OV5695_DIGI_GAIN_MAX (0x4000 - 1) #define OV5695_DIGI_GAIN_STEP 1 #define OV5695_DIGI_GAIN_DEFAULT 1024 #define OV5695_REG_TEST_PATTERN 0x4503 #define OV5695_TEST_PATTERN_ENABLE 0x80 #define OV5695_TEST_PATTERN_DISABLE 0x0 #define OV5695_REG_VTS 0x380e #define REG_NULL 0xFFFF #define OV5695_REG_VALUE_08BIT 1 #define OV5695_REG_VALUE_16BIT 2 #define OV5695_REG_VALUE_24BIT 3 #define OV5695_LANES 2 #define OV5695_BITS_PER_SAMPLE 10 static const char * const ov5695_supply_names[] = { "avdd", /* Analog power */ "dovdd", /* Digital I/O power */ "dvdd", /* Digital core power */ }; #define OV5695_NUM_SUPPLIES ARRAY_SIZE(ov5695_supply_names) struct regval { u16 addr; u8 val; }; struct ov5695_mode { u32 width; u32 height; u32 max_fps; u32 hts_def; u32 vts_def; u32 exp_def; const struct regval *reg_list; }; struct ov5695 { struct i2c_client *client; struct clk *xvclk; struct gpio_desc *reset_gpio; struct regulator_bulk_data supplies[OV5695_NUM_SUPPLIES]; struct v4l2_subdev subdev; struct media_pad pad; struct v4l2_ctrl_handler ctrl_handler; struct v4l2_ctrl *exposure; struct v4l2_ctrl *anal_gain; struct v4l2_ctrl *digi_gain; struct v4l2_ctrl *hblank; struct v4l2_ctrl *vblank; struct v4l2_ctrl *test_pattern; struct mutex mutex; bool streaming; const struct ov5695_mode *cur_mode; }; #define to_ov5695(sd) container_of(sd, struct ov5695, subdev) /* * Xclk 24Mhz * Pclk 45Mhz * linelength 672(0x2a0) * framelength 2232(0x8b8) * grabwindow_width 1296 * grabwindow_height 972 * max_framerate 30fps * mipi_datarate per lane 840Mbps */ static const struct regval ov5695_global_regs[] = { {0x0103, 0x01}, {0x0100, 0x00}, {0x0300, 0x04}, {0x0301, 0x00}, {0x0302, 0x69}, {0x0303, 0x00}, {0x0304, 0x00}, {0x0305, 0x01}, {0x0307, 0x00}, {0x030b, 0x00}, {0x030c, 0x00}, {0x030d, 0x1e}, {0x030e, 0x04}, {0x030f, 0x03}, {0x0312, 0x01}, {0x3000, 0x00}, {0x3002, 0xa1}, {0x3008, 0x00}, {0x3010, 0x00}, {0x3022, 0x51}, {0x3106, 0x15}, {0x3107, 0x01}, {0x3108, 0x05}, {0x3500, 0x00}, {0x3501, 0x45}, {0x3502, 0x00}, {0x3503, 0x08}, {0x3504, 0x03}, {0x3505, 0x8c}, {0x3507, 0x03}, {0x3508, 0x00}, {0x3509, 0x10}, {0x350c, 0x00}, {0x350d, 0x80}, {0x3510, 0x00}, {0x3511, 0x02}, {0x3512, 0x00}, {0x3601, 0x55}, {0x3602, 0x58}, {0x3614, 0x30}, {0x3615, 0x77}, {0x3621, 0x08}, {0x3624, 0x40}, {0x3633, 0x0c}, {0x3634, 0x0c}, {0x3635, 0x0c}, {0x3636, 0x0c}, {0x3638, 0x00}, {0x3639, 0x00}, {0x363a, 0x00}, {0x363b, 0x00}, {0x363c, 0xff}, {0x363d, 0xfa}, {0x3650, 0x44}, {0x3651, 0x44}, {0x3652, 0x44}, {0x3653, 0x44}, {0x3654, 0x44}, {0x3655, 0x44}, {0x3656, 0x44}, {0x3657, 0x44}, {0x3660, 0x00}, {0x3661, 0x00}, {0x3662, 0x00}, {0x366a, 0x00}, {0x366e, 0x0c}, {0x3673, 0x04}, {0x3700, 0x14}, {0x3703, 0x0c}, {0x3715, 0x01}, {0x3733, 0x10}, {0x3734, 0x40}, {0x373f, 0xa0}, {0x3765, 0x20}, {0x37a1, 0x1d}, {0x37a8, 0x26}, {0x37ab, 0x14}, {0x37c2, 0x04}, {0x37cb, 0x09}, {0x37cc, 0x13}, {0x37cd, 0x1f}, {0x37ce, 0x1f}, {0x3800, 0x00}, {0x3801, 0x00}, {0x3802, 0x00}, {0x3803, 0x00}, {0x3804, 0x0a}, {0x3805, 0x3f}, {0x3806, 0x07}, {0x3807, 0xaf}, {0x3808, 0x05}, {0x3809, 0x10}, {0x380a, 0x03}, {0x380b, 0xcc}, {0x380c, 0x02}, {0x380d, 0xa0}, {0x380e, 0x08}, {0x380f, 0xb8}, {0x3810, 0x00}, {0x3811, 0x06}, {0x3812, 0x00}, {0x3813, 0x06}, {0x3814, 0x03}, {0x3815, 0x01}, {0x3816, 0x03}, {0x3817, 0x01}, {0x3818, 0x00}, {0x3819, 0x00}, {0x381a, 0x00}, {0x381b, 0x01}, {0x3820, 0x8b}, {0x3821, 0x01}, {0x3c80, 0x08}, {0x3c82, 0x00}, {0x3c83, 0x00}, {0x3c88, 0x00}, {0x3d85, 0x14}, {0x3f02, 0x08}, {0x3f03, 0x10}, {0x4008, 0x02}, {0x4009, 0x09}, {0x404e, 0x20}, {0x4501, 0x00}, {0x4502, 0x10}, {0x4800, 0x00}, {0x481f, 0x2a}, {0x4837, 0x13}, {0x5000, 0x17}, {0x5780, 0x3e}, {0x5781, 0x0f}, {0x5782, 0x44}, {0x5783, 0x02}, {0x5784, 0x01}, {0x5785, 0x01}, {0x5786, 0x00}, {0x5787, 0x04}, {0x5788, 0x02}, {0x5789, 0x0f}, {0x578a, 0xfd}, {0x578b, 0xf5}, {0x578c, 0xf5}, {0x578d, 0x03}, {0x578e, 0x08}, {0x578f, 0x0c}, {0x5790, 0x08}, {0x5791, 0x06}, {0x5792, 0x00}, {0x5793, 0x52}, {0x5794, 0xa3}, {0x5b00, 0x00}, {0x5b01, 0x1c}, {0x5b02, 0x00}, {0x5b03, 0x7f}, {0x5b05, 0x6c}, {0x5e10, 0xfc}, {0x4010, 0xf1}, {0x3503, 0x08}, {0x3505, 0x8c}, {0x3507, 0x03}, {0x3508, 0x00}, {0x3509, 0xf8}, {REG_NULL, 0x00}, }; /* * Xclk 24Mhz * Pclk 45Mhz * linelength 740(0x2e4) * framelength 2024(0x7e8) * grabwindow_width 2592 * grabwindow_height 1944 * max_framerate 30fps * mipi_datarate per lane 840Mbps */ static const struct regval ov5695_2592x1944_regs[] = { {0x3501, 0x7e}, {0x366e, 0x18}, {0x3800, 0x00}, {0x3801, 0x00}, {0x3802, 0x00}, {0x3803, 0x04}, {0x3804, 0x0a}, {0x3805, 0x3f}, {0x3806, 0x07}, {0x3807, 0xab}, {0x3808, 0x0a}, {0x3809, 0x20}, {0x380a, 0x07}, {0x380b, 0x98}, {0x380c, 0x02}, {0x380d, 0xe4}, {0x380e, 0x07}, {0x380f, 0xe8}, {0x3811, 0x06}, {0x3813, 0x08}, {0x3814, 0x01}, {0x3816, 0x01}, {0x3817, 0x01}, {0x3820, 0x88}, {0x3821, 0x00}, {0x4501, 0x00}, {0x4008, 0x04}, {0x4009, 0x13}, {REG_NULL, 0x00}, }; /* * Xclk 24Mhz * Pclk 45Mhz * linelength 672(0x2a0) * framelength 2232(0x8b8) * grabwindow_width 1920 * grabwindow_height 1080 * max_framerate 30fps * mipi_datarate per lane 840Mbps */ static const struct regval ov5695_1920x1080_regs[] = { {0x3501, 0x45}, {0x366e, 0x18}, {0x3800, 0x01}, {0x3801, 0x50}, {0x3802, 0x01}, {0x3803, 0xb8}, {0x3804, 0x08}, {0x3805, 0xef}, {0x3806, 0x05}, {0x3807, 0xf7}, {0x3808, 0x07}, {0x3809, 0x80}, {0x380a, 0x04}, {0x380b, 0x38}, {0x380c, 0x02}, {0x380d, 0xa0}, {0x380e, 0x08}, {0x380f, 0xb8}, {0x3811, 0x06}, {0x3813, 0x04}, {0x3814, 0x01}, {0x3816, 0x01}, {0x3817, 0x01}, {0x3820, 0x88}, {0x3821, 0x00}, {0x4501, 0x00}, {0x4008, 0x04}, {0x4009, 0x13}, {REG_NULL, 0x00} }; /* * Xclk 24Mhz * Pclk 45Mhz * linelength 740(0x02e4) * framelength 1012(0x03f4) * grabwindow_width 1296 * grabwindow_height 972 * max_framerate 60fps * mipi_datarate per lane 840Mbps */ static const struct regval ov5695_1296x972_regs[] = { {0x0103, 0x01}, {0x0100, 0x00}, {0x0300, 0x04}, {0x0301, 0x00}, {0x0302, 0x69}, {0x0303, 0x00}, {0x0304, 0x00}, {0x0305, 0x01}, {0x0307, 0x00}, {0x030b, 0x00}, {0x030c, 0x00}, {0x030d, 0x1e}, {0x030e, 0x04}, {0x030f, 0x03}, {0x0312, 0x01}, {0x3000, 0x00}, {0x3002, 0xa1}, {0x3008, 0x00}, {0x3010, 0x00}, {0x3016, 0x32}, {0x3022, 0x51}, {0x3106, 0x15}, {0x3107, 0x01}, {0x3108, 0x05}, {0x3500, 0x00}, {0x3501, 0x3e}, {0x3502, 0x00}, {0x3503, 0x08}, {0x3504, 0x03}, {0x3505, 0x8c}, {0x3507, 0x03}, {0x3508, 0x00}, {0x3509, 0x10}, {0x350c, 0x00}, {0x350d, 0x80}, {0x3510, 0x00}, {0x3511, 0x02}, {0x3512, 0x00}, {0x3601, 0x55}, {0x3602, 0x58}, {0x3611, 0x58}, {0x3614, 0x30}, {0x3615, 0x77}, {0x3621, 0x08}, {0x3624, 0x40}, {0x3633, 0x0c}, {0x3634, 0x0c}, {0x3635, 0x0c}, {0x3636, 0x0c}, {0x3638, 0x00}, {0x3639, 0x00}, {0x363a, 0x00}, {0x363b, 0x00}, {0x363c, 0xff}, {0x363d, 0xfa}, {0x3650, 0x44}, {0x3651, 0x44}, {0x3652, 0x44}, {0x3653, 0x44}, {0x3654, 0x44}, {0x3655, 0x44}, {0x3656, 0x44}, {0x3657, 0x44}, {0x3660, 0x00}, {0x3661, 0x00}, {0x3662, 0x00}, {0x366a, 0x00}, {0x366e, 0x0c}, {0x3673, 0x04}, {0x3700, 0x14}, {0x3703, 0x0c}, {0x3706, 0x24}, {0x3714, 0x27}, {0x3715, 0x01}, {0x3716, 0x00}, {0x3717, 0x02}, {0x3733, 0x10}, {0x3734, 0x40}, {0x373f, 0xa0}, {0x3765, 0x20}, {0x37a1, 0x1d}, {0x37a8, 0x26}, {0x37ab, 0x14}, {0x37c2, 0x04}, {0x37c3, 0xf0}, {0x37cb, 0x09}, {0x37cc, 0x13}, {0x37cd, 0x1f}, {0x37ce, 0x1f}, {0x3800, 0x00}, {0x3801, 0x00}, {0x3802, 0x00}, {0x3803, 0x00}, {0x3804, 0x0a}, {0x3805, 0x3f}, {0x3806, 0x07}, {0x3807, 0xaf}, {0x3808, 0x05}, {0x3809, 0x10}, {0x380a, 0x03}, {0x380b, 0xcc}, {0x380c, 0x02}, {0x380d, 0xe4}, {0x380e, 0x03}, {0x380f, 0xf4}, {0x3810, 0x00}, {0x3811, 0x00}, {0x3812, 0x00}, {0x3813, 0x06}, {0x3814, 0x03}, {0x3815, 0x01}, {0x3816, 0x03}, {0x3817, 0x01}, {0x3818, 0x00}, {0x3819, 0x00}, {0x381a, 0x00}, {0x381b, 0x01}, {0x3820, 0x8b}, {0x3821, 0x01}, {0x3c80, 0x08}, {0x3c82, 0x00}, {0x3c83, 0x00}, {0x3c88, 0x00}, {0x3d85, 0x14}, {0x3f02, 0x08}, {0x3f03, 0x10}, {0x4008, 0x02}, {0x4009, 0x09}, {0x404e, 0x20}, {0x4501, 0x00}, {0x4502, 0x10}, {0x4800, 0x00}, {0x481f, 0x2a}, {0x4837, 0x13}, {0x5000, 0x13}, {0x5780, 0x3e}, {0x5781, 0x0f}, {0x5782, 0x44}, {0x5783, 0x02}, {0x5784, 0x01}, {0x5785, 0x01}, {0x5786, 0x00}, {0x5787, 0x04}, {0x5788, 0x02}, {0x5789, 0x0f}, {0x578a, 0xfd}, {0x578b, 0xf5}, {0x578c, 0xf5}, {0x578d, 0x03}, {0x578e, 0x08}, {0x578f, 0x0c}, {0x5790, 0x08}, {0x5791, 0x06}, {0x5792, 0x00}, {0x5793, 0x52}, {0x5794, 0xa3}, {0x5b00, 0x00}, {0x5b01, 0x1c}, {0x5b02, 0x00}, {0x5b03, 0x7f}, {0x5b05, 0x6c}, {0x5e10, 0xfc}, {0x4010, 0xf1}, {0x3503, 0x08}, {0x3505, 0x8c}, {0x3507, 0x03}, {0x3508, 0x00}, {0x3509, 0xf8}, {0x0100, 0x01}, {REG_NULL, 0x00} }; /* * Xclk 24Mhz * Pclk 45Mhz * linelength 672(0x2a0) * framelength 2232(0x8b8) * grabwindow_width 1280 * grabwindow_height 720 * max_framerate 30fps * mipi_datarate per lane 840Mbps */ static const struct regval ov5695_1280x720_regs[] = { {0x3501, 0x45}, {0x366e, 0x0c}, {0x3800, 0x00}, {0x3801, 0x00}, {0x3802, 0x01}, {0x3803, 0x00}, {0x3804, 0x0a}, {0x3805, 0x3f}, {0x3806, 0x06}, {0x3807, 0xaf}, {0x3808, 0x05}, {0x3809, 0x00}, {0x380a, 0x02}, {0x380b, 0xd0}, {0x380c, 0x02}, {0x380d, 0xa0}, {0x380e, 0x08}, {0x380f, 0xb8}, {0x3811, 0x06}, {0x3813, 0x02}, {0x3814, 0x03}, {0x3816, 0x03}, {0x3817, 0x01}, {0x3820, 0x8b}, {0x3821, 0x01}, {0x4501, 0x00}, {0x4008, 0x02}, {0x4009, 0x09}, {REG_NULL, 0x00} }; /* * Xclk 24Mhz * Pclk 45Mhz * linelength 672(0x2a0) * framelength 558(0x22e) * grabwindow_width 640 * grabwindow_height 480 * max_framerate 120fps * mipi_datarate per lane 840Mbps */ static const struct regval ov5695_640x480_regs[] = { {0x3501, 0x22}, {0x366e, 0x0c}, {0x3800, 0x00}, {0x3801, 0x00}, {0x3802, 0x00}, {0x3803, 0x08}, {0x3804, 0x0a}, {0x3805, 0x3f}, {0x3806, 0x07}, {0x3807, 0xa7}, {0x3808, 0x02}, {0x3809, 0x80}, {0x380a, 0x01}, {0x380b, 0xe0}, {0x380c, 0x02}, {0x380d, 0xa0}, {0x380e, 0x02}, {0x380f, 0x2e}, {0x3811, 0x06}, {0x3813, 0x04}, {0x3814, 0x07}, {0x3816, 0x05}, {0x3817, 0x03}, {0x3820, 0x8d}, {0x3821, 0x01}, {0x4501, 0x00}, {0x4008, 0x02}, {0x4009, 0x09}, {REG_NULL, 0x00} }; static const struct ov5695_mode supported_modes[] = { { .width = 2592, .height = 1944, .max_fps = 30, .exp_def = 0x0450, .hts_def = 0x02e4 * 4, .vts_def = 0x07e8, .reg_list = ov5695_2592x1944_regs, }, { .width = 1920, .height = 1080, .max_fps = 30, .exp_def = 0x0450, .hts_def = 0x02a0 * 4, .vts_def = 0x08b8, .reg_list = ov5695_1920x1080_regs, }, { .width = 1296, .height = 972, .max_fps = 60, .exp_def = 0x03e0, .hts_def = 0x02e4 * 4, .vts_def = 0x03f4, .reg_list = ov5695_1296x972_regs, }, { .width = 1280, .height = 720, .max_fps = 30, .exp_def = 0x0450, .hts_def = 0x02a0 * 4, .vts_def = 0x08b8, .reg_list = ov5695_1280x720_regs, }, { .width = 640, .height = 480, .max_fps = 120, .exp_def = 0x0450, .hts_def = 0x02a0 * 4, .vts_def = 0x022e, .reg_list = ov5695_640x480_regs, }, }; #define OV5695_LINK_FREQ_420MHZ 420000000 static const s64 link_freq_menu_items[] = { OV5695_LINK_FREQ_420MHZ }; static const char * const ov5695_test_pattern_menu[] = { "Disabled", "Vertical Color Bar Type 1", "Vertical Color Bar Type 2", "Vertical Color Bar Type 3", "Vertical Color Bar Type 4" }; /* Write registers up to 4 at a time */ static int ov5695_write_reg(struct i2c_client *client, u16 reg, u32 len, u32 val) { u32 buf_i, val_i; u8 buf[6]; u8 *val_p; __be32 val_be; if (len > 4) return -EINVAL; buf[0] = reg >> 8; buf[1] = reg & 0xff; val_be = cpu_to_be32(val); val_p = (u8 *)&val_be; buf_i = 2; val_i = 4 - len; while (val_i < 4) buf[buf_i++] = val_p[val_i++]; if (i2c_master_send(client, buf, len + 2) != len + 2) return -EIO; return 0; } static int ov5695_write_array(struct i2c_client *client, const struct regval *regs) { u32 i; int ret = 0; for (i = 0; ret == 0 && regs[i].addr != REG_NULL; i++) ret = ov5695_write_reg(client, regs[i].addr, OV5695_REG_VALUE_08BIT, regs[i].val); return ret; } /* Read registers up to 4 at a time */ static int ov5695_read_reg(struct i2c_client *client, u16 reg, unsigned int len, u32 *val) { struct i2c_msg msgs[2]; u8 *data_be_p; __be32 data_be = 0; __be16 reg_addr_be = cpu_to_be16(reg); int ret; if (len > 4) return -EINVAL; data_be_p = (u8 *)&data_be; /* Write register address */ msgs[0].addr = client->addr; msgs[0].flags = 0; msgs[0].len = 2; msgs[0].buf = (u8 *)&reg_addr_be; /* Read data from register */ msgs[1].addr = client->addr; msgs[1].flags = I2C_M_RD; msgs[1].len = len; msgs[1].buf = &data_be_p[4 - len]; ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs)); if (ret != ARRAY_SIZE(msgs)) return -EIO; *val = be32_to_cpu(data_be); return 0; } static int ov5695_get_reso_dist(const struct ov5695_mode *mode, struct v4l2_mbus_framefmt *framefmt) { return abs(mode->width - framefmt->width) + abs(mode->height - framefmt->height); } static const struct ov5695_mode * ov5695_find_best_fit(struct v4l2_subdev_format *fmt) { struct v4l2_mbus_framefmt *framefmt = &fmt->format; int dist; int cur_best_fit = 0; int cur_best_fit_dist = -1; int i; for (i = 0; i < ARRAY_SIZE(supported_modes); i++) { dist = ov5695_get_reso_dist(&supported_modes[i], framefmt); if (cur_best_fit_dist == -1 || dist < cur_best_fit_dist) { cur_best_fit_dist = dist; cur_best_fit = i; } } return &supported_modes[cur_best_fit]; } static int ov5695_set_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *fmt) { struct ov5695 *ov5695 = to_ov5695(sd); const struct ov5695_mode *mode; s64 h_blank, vblank_def; mutex_lock(&ov5695->mutex); mode = ov5695_find_best_fit(fmt); fmt->format.code = MEDIA_BUS_FMT_SBGGR10_1X10; fmt->format.width = mode->width; fmt->format.height = mode->height; fmt->format.field = V4L2_FIELD_NONE; if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) { #ifdef CONFIG_VIDEO_V4L2_SUBDEV_API *v4l2_subdev_get_try_format(sd, sd_state, fmt->pad) = fmt->format; #endif } else { ov5695->cur_mode = mode; h_blank = mode->hts_def - mode->width; __v4l2_ctrl_modify_range(ov5695->hblank, h_blank, h_blank, 1, h_blank); vblank_def = mode->vts_def - mode->height; __v4l2_ctrl_modify_range(ov5695->vblank, vblank_def, OV5695_VTS_MAX - mode->height, 1, vblank_def); } mutex_unlock(&ov5695->mutex); return 0; } static int ov5695_get_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *fmt) { struct ov5695 *ov5695 = to_ov5695(sd); const struct ov5695_mode *mode = ov5695->cur_mode; mutex_lock(&ov5695->mutex); if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) { #ifdef CONFIG_VIDEO_V4L2_SUBDEV_API fmt->format = *v4l2_subdev_get_try_format(sd, sd_state, fmt->pad); #else mutex_unlock(&ov5695->mutex); return -EINVAL; #endif } else { fmt->format.width = mode->width; fmt->format.height = mode->height; fmt->format.code = MEDIA_BUS_FMT_SBGGR10_1X10; fmt->format.field = V4L2_FIELD_NONE; } mutex_unlock(&ov5695->mutex); return 0; } static int ov5695_enum_mbus_code(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_mbus_code_enum *code) { if (code->index != 0) return -EINVAL; code->code = MEDIA_BUS_FMT_SBGGR10_1X10; return 0; } static int ov5695_enum_frame_sizes(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_frame_size_enum *fse) { if (fse->index >= ARRAY_SIZE(supported_modes)) return -EINVAL; if (fse->code != MEDIA_BUS_FMT_SBGGR10_1X10) return -EINVAL; fse->min_width = supported_modes[fse->index].width; fse->max_width = supported_modes[fse->index].width; fse->max_height = supported_modes[fse->index].height; fse->min_height = supported_modes[fse->index].height; return 0; } static int ov5695_enable_test_pattern(struct ov5695 *ov5695, u32 pattern) { u32 val; if (pattern) val = (pattern - 1) | OV5695_TEST_PATTERN_ENABLE; else val = OV5695_TEST_PATTERN_DISABLE; return ov5695_write_reg(ov5695->client, OV5695_REG_TEST_PATTERN, OV5695_REG_VALUE_08BIT, val); } static int __ov5695_start_stream(struct ov5695 *ov5695) { int ret; ret = ov5695_write_array(ov5695->client, ov5695_global_regs); if (ret) return ret; ret = ov5695_write_array(ov5695->client, ov5695->cur_mode->reg_list); if (ret) return ret; /* In case these controls are set before streaming */ ret = __v4l2_ctrl_handler_setup(&ov5695->ctrl_handler); if (ret) return ret; return ov5695_write_reg(ov5695->client, OV5695_REG_CTRL_MODE, OV5695_REG_VALUE_08BIT, OV5695_MODE_STREAMING); } static int __ov5695_stop_stream(struct ov5695 *ov5695) { return ov5695_write_reg(ov5695->client, OV5695_REG_CTRL_MODE, OV5695_REG_VALUE_08BIT, OV5695_MODE_SW_STANDBY); } static int ov5695_s_stream(struct v4l2_subdev *sd, int on) { struct ov5695 *ov5695 = to_ov5695(sd); struct i2c_client *client = ov5695->client; int ret = 0; mutex_lock(&ov5695->mutex); on = !!on; if (on == ov5695->streaming) goto unlock_and_return; if (on) { ret = pm_runtime_resume_and_get(&client->dev); if (ret < 0) goto unlock_and_return; ret = __ov5695_start_stream(ov5695); if (ret) { v4l2_err(sd, "start stream failed while write regs\n"); pm_runtime_put(&client->dev); goto unlock_and_return; } } else { __ov5695_stop_stream(ov5695); pm_runtime_put(&client->dev); } ov5695->streaming = on; unlock_and_return: mutex_unlock(&ov5695->mutex); return ret; } static int __ov5695_power_on(struct ov5695 *ov5695) { int i, ret; struct device *dev = &ov5695->client->dev; ret = clk_prepare_enable(ov5695->xvclk); if (ret < 0) { dev_err(dev, "Failed to enable xvclk\n"); return ret; } gpiod_set_value_cansleep(ov5695->reset_gpio, 1); /* * The hardware requires the regulators to be powered on in order, * so enable them one by one. */ for (i = 0; i < OV5695_NUM_SUPPLIES; i++) { ret = regulator_enable(ov5695->supplies[i].consumer); if (ret) { dev_err(dev, "Failed to enable %s: %d\n", ov5695->supplies[i].supply, ret); goto disable_reg_clk; } } gpiod_set_value_cansleep(ov5695->reset_gpio, 0); usleep_range(1000, 1200); return 0; disable_reg_clk: for (--i; i >= 0; i--) regulator_disable(ov5695->supplies[i].consumer); clk_disable_unprepare(ov5695->xvclk); return ret; } static void __ov5695_power_off(struct ov5695 *ov5695) { struct device *dev = &ov5695->client->dev; int i, ret; clk_disable_unprepare(ov5695->xvclk); gpiod_set_value_cansleep(ov5695->reset_gpio, 1); /* * The hardware requires the regulators to be powered off in order, * so disable them one by one. */ for (i = OV5695_NUM_SUPPLIES - 1; i >= 0; i--) { ret = regulator_disable(ov5695->supplies[i].consumer); if (ret) dev_err(dev, "Failed to disable %s: %d\n", ov5695->supplies[i].supply, ret); } } static int __maybe_unused ov5695_runtime_resume(struct device *dev) { struct v4l2_subdev *sd = dev_get_drvdata(dev); struct ov5695 *ov5695 = to_ov5695(sd); return __ov5695_power_on(ov5695); } static int __maybe_unused ov5695_runtime_suspend(struct device *dev) { struct v4l2_subdev *sd = dev_get_drvdata(dev); struct ov5695 *ov5695 = to_ov5695(sd); __ov5695_power_off(ov5695); return 0; } #ifdef CONFIG_VIDEO_V4L2_SUBDEV_API static int ov5695_open(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh) { struct ov5695 *ov5695 = to_ov5695(sd); struct v4l2_mbus_framefmt *try_fmt = v4l2_subdev_get_try_format(sd, fh->state, 0); const struct ov5695_mode *def_mode = &supported_modes[0]; mutex_lock(&ov5695->mutex); /* Initialize try_fmt */ try_fmt->width = def_mode->width; try_fmt->height = def_mode->height; try_fmt->code = MEDIA_BUS_FMT_SBGGR10_1X10; try_fmt->field = V4L2_FIELD_NONE; mutex_unlock(&ov5695->mutex); /* No crop or compose */ return 0; } #endif static const struct dev_pm_ops ov5695_pm_ops = { SET_RUNTIME_PM_OPS(ov5695_runtime_suspend, ov5695_runtime_resume, NULL) }; #ifdef CONFIG_VIDEO_V4L2_SUBDEV_API static const struct v4l2_subdev_internal_ops ov5695_internal_ops = { .open = ov5695_open, }; #endif static const struct v4l2_subdev_video_ops ov5695_video_ops = { .s_stream = ov5695_s_stream, }; static const struct v4l2_subdev_pad_ops ov5695_pad_ops = { .enum_mbus_code = ov5695_enum_mbus_code, .enum_frame_size = ov5695_enum_frame_sizes, .get_fmt = ov5695_get_fmt, .set_fmt = ov5695_set_fmt, }; static const struct v4l2_subdev_ops ov5695_subdev_ops = { .video = &ov5695_video_ops, .pad = &ov5695_pad_ops, }; static int ov5695_set_ctrl(struct v4l2_ctrl *ctrl) { struct ov5695 *ov5695 = container_of(ctrl->handler, struct ov5695, ctrl_handler); struct i2c_client *client = ov5695->client; s64 max; int ret = 0; /* Propagate change of current control to all related controls */ switch (ctrl->id) { case V4L2_CID_VBLANK: /* Update max exposure while meeting expected vblanking */ max = ov5695->cur_mode->height + ctrl->val - 4; __v4l2_ctrl_modify_range(ov5695->exposure, ov5695->exposure->minimum, max, ov5695->exposure->step, ov5695->exposure->default_value); break; } if (!pm_runtime_get_if_in_use(&client->dev)) return 0; switch (ctrl->id) { case V4L2_CID_EXPOSURE: /* 4 least significant bits of exposure are fractional part */ ret = ov5695_write_reg(ov5695->client, OV5695_REG_EXPOSURE, OV5695_REG_VALUE_24BIT, ctrl->val << 4); break; case V4L2_CID_ANALOGUE_GAIN: ret = ov5695_write_reg(ov5695->client, OV5695_REG_ANALOG_GAIN, OV5695_REG_VALUE_08BIT, ctrl->val); break; case V4L2_CID_DIGITAL_GAIN: ret = ov5695_write_reg(ov5695->client, OV5695_REG_DIGI_GAIN_L, OV5695_REG_VALUE_08BIT, ctrl->val & OV5695_DIGI_GAIN_L_MASK); ret = ov5695_write_reg(ov5695->client, OV5695_REG_DIGI_GAIN_H, OV5695_REG_VALUE_08BIT, ctrl->val >> OV5695_DIGI_GAIN_H_SHIFT); break; case V4L2_CID_VBLANK: ret = ov5695_write_reg(ov5695->client, OV5695_REG_VTS, OV5695_REG_VALUE_16BIT, ctrl->val + ov5695->cur_mode->height); break; case V4L2_CID_TEST_PATTERN: ret = ov5695_enable_test_pattern(ov5695, ctrl->val); break; default: dev_warn(&client->dev, "%s Unhandled id:0x%x, val:0x%x\n", __func__, ctrl->id, ctrl->val); break; } pm_runtime_put(&client->dev); return ret; } static const struct v4l2_ctrl_ops ov5695_ctrl_ops = { .s_ctrl = ov5695_set_ctrl, }; static int ov5695_initialize_controls(struct ov5695 *ov5695) { const struct ov5695_mode *mode; struct v4l2_ctrl_handler *handler; struct v4l2_ctrl *ctrl; s64 exposure_max, vblank_def; u32 h_blank; int ret; handler = &ov5695->ctrl_handler; mode = ov5695->cur_mode; ret = v4l2_ctrl_handler_init(handler, 8); if (ret) return ret; handler->lock = &ov5695->mutex; ctrl = v4l2_ctrl_new_int_menu(handler, NULL, V4L2_CID_LINK_FREQ, 0, 0, link_freq_menu_items); if (ctrl) ctrl->flags |= V4L2_CTRL_FLAG_READ_ONLY; v4l2_ctrl_new_std(handler, NULL, V4L2_CID_PIXEL_RATE, 0, OV5695_PIXEL_RATE, 1, OV5695_PIXEL_RATE); h_blank = mode->hts_def - mode->width; ov5695->hblank = v4l2_ctrl_new_std(handler, NULL, V4L2_CID_HBLANK, h_blank, h_blank, 1, h_blank); if (ov5695->hblank) ov5695->hblank->flags |= V4L2_CTRL_FLAG_READ_ONLY; vblank_def = mode->vts_def - mode->height; ov5695->vblank = v4l2_ctrl_new_std(handler, &ov5695_ctrl_ops, V4L2_CID_VBLANK, vblank_def, OV5695_VTS_MAX - mode->height, 1, vblank_def); exposure_max = mode->vts_def - 4; ov5695->exposure = v4l2_ctrl_new_std(handler, &ov5695_ctrl_ops, V4L2_CID_EXPOSURE, OV5695_EXPOSURE_MIN, exposure_max, OV5695_EXPOSURE_STEP, mode->exp_def); ov5695->anal_gain = v4l2_ctrl_new_std(handler, &ov5695_ctrl_ops, V4L2_CID_ANALOGUE_GAIN, ANALOG_GAIN_MIN, ANALOG_GAIN_MAX, ANALOG_GAIN_STEP, ANALOG_GAIN_DEFAULT); /* Digital gain */ ov5695->digi_gain = v4l2_ctrl_new_std(handler, &ov5695_ctrl_ops, V4L2_CID_DIGITAL_GAIN, OV5695_DIGI_GAIN_MIN, OV5695_DIGI_GAIN_MAX, OV5695_DIGI_GAIN_STEP, OV5695_DIGI_GAIN_DEFAULT); ov5695->test_pattern = v4l2_ctrl_new_std_menu_items(handler, &ov5695_ctrl_ops, V4L2_CID_TEST_PATTERN, ARRAY_SIZE(ov5695_test_pattern_menu) - 1, 0, 0, ov5695_test_pattern_menu); if (handler->error) { ret = handler->error; dev_err(&ov5695->client->dev, "Failed to init controls(%d)\n", ret); goto err_free_handler; } ov5695->subdev.ctrl_handler = handler; return 0; err_free_handler: v4l2_ctrl_handler_free(handler); return ret; } static int ov5695_check_sensor_id(struct ov5695 *ov5695, struct i2c_client *client) { struct device *dev = &ov5695->client->dev; u32 id = 0; int ret; ret = ov5695_read_reg(client, OV5695_REG_CHIP_ID, OV5695_REG_VALUE_24BIT, &id); if (id != CHIP_ID) { dev_err(dev, "Unexpected sensor id(%06x), ret(%d)\n", id, ret); return ret; } dev_info(dev, "Detected OV%06x sensor\n", CHIP_ID); return 0; } static int ov5695_configure_regulators(struct ov5695 *ov5695) { int i; for (i = 0; i < OV5695_NUM_SUPPLIES; i++) ov5695->supplies[i].supply = ov5695_supply_names[i]; return devm_regulator_bulk_get(&ov5695->client->dev, OV5695_NUM_SUPPLIES, ov5695->supplies); } static int ov5695_probe(struct i2c_client *client) { struct device *dev = &client->dev; struct ov5695 *ov5695; struct v4l2_subdev *sd; int ret; ov5695 = devm_kzalloc(dev, sizeof(*ov5695), GFP_KERNEL); if (!ov5695) return -ENOMEM; ov5695->client = client; ov5695->cur_mode = &supported_modes[0]; ov5695->xvclk = devm_clk_get(dev, "xvclk"); if (IS_ERR(ov5695->xvclk)) { dev_err(dev, "Failed to get xvclk\n"); return -EINVAL; } ret = clk_set_rate(ov5695->xvclk, OV5695_XVCLK_FREQ); if (ret < 0) { dev_err(dev, "Failed to set xvclk rate (24MHz)\n"); return ret; } if (clk_get_rate(ov5695->xvclk) != OV5695_XVCLK_FREQ) dev_warn(dev, "xvclk mismatched, modes are based on 24MHz\n"); ov5695->reset_gpio = devm_gpiod_get(dev, "reset", GPIOD_OUT_HIGH); if (IS_ERR(ov5695->reset_gpio)) { dev_err(dev, "Failed to get reset-gpios\n"); return -EINVAL; } ret = ov5695_configure_regulators(ov5695); if (ret) { dev_err(dev, "Failed to get power regulators\n"); return ret; } mutex_init(&ov5695->mutex); sd = &ov5695->subdev; v4l2_i2c_subdev_init(sd, client, &ov5695_subdev_ops); ret = ov5695_initialize_controls(ov5695); if (ret) goto err_destroy_mutex; ret = __ov5695_power_on(ov5695); if (ret) goto err_free_handler; ret = ov5695_check_sensor_id(ov5695, client); if (ret) goto err_power_off; #ifdef CONFIG_VIDEO_V4L2_SUBDEV_API sd->internal_ops = &ov5695_internal_ops; sd->flags |= V4L2_SUBDEV_FL_HAS_DEVNODE; #endif #if defined(CONFIG_MEDIA_CONTROLLER) ov5695->pad.flags = MEDIA_PAD_FL_SOURCE; sd->entity.function = MEDIA_ENT_F_CAM_SENSOR; ret = media_entity_pads_init(&sd->entity, 1, &ov5695->pad); if (ret < 0) goto err_power_off; #endif ret = v4l2_async_register_subdev_sensor(sd); if (ret) { dev_err(dev, "v4l2 async register subdev failed\n"); goto err_clean_entity; } pm_runtime_set_active(dev); pm_runtime_enable(dev); pm_runtime_idle(dev); return 0; err_clean_entity: #if defined(CONFIG_MEDIA_CONTROLLER) media_entity_cleanup(&sd->entity); #endif err_power_off: __ov5695_power_off(ov5695); err_free_handler: v4l2_ctrl_handler_free(&ov5695->ctrl_handler); err_destroy_mutex: mutex_destroy(&ov5695->mutex); return ret; } static void ov5695_remove(struct i2c_client *client) { struct v4l2_subdev *sd = i2c_get_clientdata(client); struct ov5695 *ov5695 = to_ov5695(sd); v4l2_async_unregister_subdev(sd); #if defined(CONFIG_MEDIA_CONTROLLER) media_entity_cleanup(&sd->entity); #endif v4l2_ctrl_handler_free(&ov5695->ctrl_handler); mutex_destroy(&ov5695->mutex); pm_runtime_disable(&client->dev); if (!pm_runtime_status_suspended(&client->dev)) __ov5695_power_off(ov5695); pm_runtime_set_suspended(&client->dev); } #if IS_ENABLED(CONFIG_OF) static const struct of_device_id ov5695_of_match[] = { { .compatible = "ovti,ov5695" }, {}, }; MODULE_DEVICE_TABLE(of, ov5695_of_match); #endif static struct i2c_driver ov5695_i2c_driver = { .driver = { .name = "ov5695", .pm = &ov5695_pm_ops, .of_match_table = of_match_ptr(ov5695_of_match), }, .probe = ov5695_probe, .remove = ov5695_remove, }; module_i2c_driver(ov5695_i2c_driver); MODULE_DESCRIPTION("OmniVision ov5695 sensor driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/media/i2c/ov5695.c
// SPDX-License-Identifier: GPL-2.0-only /* * drivers/media/i2c/lm3646.c * General device driver for TI lm3646, Dual FLASH LED Driver * * Copyright (C) 2014 Texas Instruments * * Contact: Daniel Jeong <[email protected]> * Ldd-Mlp <[email protected]> */ #include <linux/delay.h> #include <linux/i2c.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/regmap.h> #include <linux/videodev2.h> #include <media/i2c/lm3646.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-device.h> /* registers definitions */ #define REG_ENABLE 0x01 #define REG_TORCH_BR 0x05 #define REG_FLASH_BR 0x05 #define REG_FLASH_TOUT 0x04 #define REG_FLAG 0x08 #define REG_STROBE_SRC 0x06 #define REG_LED1_FLASH_BR 0x06 #define REG_LED1_TORCH_BR 0x07 #define MASK_ENABLE 0x03 #define MASK_TORCH_BR 0x70 #define MASK_FLASH_BR 0x0F #define MASK_FLASH_TOUT 0x07 #define MASK_FLAG 0xFF #define MASK_STROBE_SRC 0x80 /* Fault Mask */ #define FAULT_TIMEOUT (1<<0) #define FAULT_SHORT_CIRCUIT (1<<1) #define FAULT_UVLO (1<<2) #define FAULT_IVFM (1<<3) #define FAULT_OCP (1<<4) #define FAULT_OVERTEMP (1<<5) #define FAULT_NTC_TRIP (1<<6) #define FAULT_OVP (1<<7) enum led_mode { MODE_SHDN = 0x0, MODE_TORCH = 0x2, MODE_FLASH = 0x3, }; /* * struct lm3646_flash * * @pdata: platform data * @regmap: reg. map for i2c * @lock: muxtex for serial access. * @led_mode: V4L2 LED mode * @ctrls_led: V4L2 controls * @subdev_led: V4L2 subdev * @mode_reg : mode register value */ struct lm3646_flash { struct device *dev; struct lm3646_platform_data *pdata; struct regmap *regmap; struct v4l2_ctrl_handler ctrls_led; struct v4l2_subdev subdev_led; u8 mode_reg; }; #define to_lm3646_flash(_ctrl) \ container_of(_ctrl->handler, struct lm3646_flash, ctrls_led) /* enable mode control */ static int lm3646_mode_ctrl(struct lm3646_flash *flash, enum v4l2_flash_led_mode led_mode) { switch (led_mode) { case V4L2_FLASH_LED_MODE_NONE: return regmap_write(flash->regmap, REG_ENABLE, flash->mode_reg | MODE_SHDN); case V4L2_FLASH_LED_MODE_TORCH: return regmap_write(flash->regmap, REG_ENABLE, flash->mode_reg | MODE_TORCH); case V4L2_FLASH_LED_MODE_FLASH: return regmap_write(flash->regmap, REG_ENABLE, flash->mode_reg | MODE_FLASH); } return -EINVAL; } /* V4L2 controls */ static int lm3646_get_ctrl(struct v4l2_ctrl *ctrl) { struct lm3646_flash *flash = to_lm3646_flash(ctrl); unsigned int reg_val; int rval; if (ctrl->id != V4L2_CID_FLASH_FAULT) return -EINVAL; rval = regmap_read(flash->regmap, REG_FLAG, &reg_val); if (rval < 0) return rval; ctrl->val = 0; if (reg_val & FAULT_TIMEOUT) ctrl->val |= V4L2_FLASH_FAULT_TIMEOUT; if (reg_val & FAULT_SHORT_CIRCUIT) ctrl->val |= V4L2_FLASH_FAULT_SHORT_CIRCUIT; if (reg_val & FAULT_UVLO) ctrl->val |= V4L2_FLASH_FAULT_UNDER_VOLTAGE; if (reg_val & FAULT_IVFM) ctrl->val |= V4L2_FLASH_FAULT_INPUT_VOLTAGE; if (reg_val & FAULT_OCP) ctrl->val |= V4L2_FLASH_FAULT_OVER_CURRENT; if (reg_val & FAULT_OVERTEMP) ctrl->val |= V4L2_FLASH_FAULT_OVER_TEMPERATURE; if (reg_val & FAULT_NTC_TRIP) ctrl->val |= V4L2_FLASH_FAULT_LED_OVER_TEMPERATURE; if (reg_val & FAULT_OVP) ctrl->val |= V4L2_FLASH_FAULT_OVER_VOLTAGE; return 0; } static int lm3646_set_ctrl(struct v4l2_ctrl *ctrl) { struct lm3646_flash *flash = to_lm3646_flash(ctrl); unsigned int reg_val; int rval; switch (ctrl->id) { case V4L2_CID_FLASH_LED_MODE: if (ctrl->val != V4L2_FLASH_LED_MODE_FLASH) return lm3646_mode_ctrl(flash, ctrl->val); /* switch to SHDN mode before flash strobe on */ return lm3646_mode_ctrl(flash, V4L2_FLASH_LED_MODE_NONE); case V4L2_CID_FLASH_STROBE_SOURCE: return regmap_update_bits(flash->regmap, REG_STROBE_SRC, MASK_STROBE_SRC, (ctrl->val) << 7); case V4L2_CID_FLASH_STROBE: /* read and check current mode of chip to start flash */ rval = regmap_read(flash->regmap, REG_ENABLE, &reg_val); if (rval < 0 || ((reg_val & MASK_ENABLE) != MODE_SHDN)) return rval; /* flash on */ return lm3646_mode_ctrl(flash, V4L2_FLASH_LED_MODE_FLASH); case V4L2_CID_FLASH_STROBE_STOP: /* * flash mode will be turned automatically * from FLASH mode to SHDN mode after flash duration timeout * read and check current mode of chip to stop flash */ rval = regmap_read(flash->regmap, REG_ENABLE, &reg_val); if (rval < 0) return rval; if ((reg_val & MASK_ENABLE) == MODE_FLASH) return lm3646_mode_ctrl(flash, V4L2_FLASH_LED_MODE_NONE); return rval; case V4L2_CID_FLASH_TIMEOUT: return regmap_update_bits(flash->regmap, REG_FLASH_TOUT, MASK_FLASH_TOUT, LM3646_FLASH_TOUT_ms_TO_REG (ctrl->val)); case V4L2_CID_FLASH_INTENSITY: return regmap_update_bits(flash->regmap, REG_FLASH_BR, MASK_FLASH_BR, LM3646_TOTAL_FLASH_BRT_uA_TO_REG (ctrl->val)); case V4L2_CID_FLASH_TORCH_INTENSITY: return regmap_update_bits(flash->regmap, REG_TORCH_BR, MASK_TORCH_BR, LM3646_TOTAL_TORCH_BRT_uA_TO_REG (ctrl->val) << 4); } return -EINVAL; } static const struct v4l2_ctrl_ops lm3646_led_ctrl_ops = { .g_volatile_ctrl = lm3646_get_ctrl, .s_ctrl = lm3646_set_ctrl, }; static int lm3646_init_controls(struct lm3646_flash *flash) { struct v4l2_ctrl *fault; struct v4l2_ctrl_handler *hdl = &flash->ctrls_led; const struct v4l2_ctrl_ops *ops = &lm3646_led_ctrl_ops; v4l2_ctrl_handler_init(hdl, 8); /* flash mode */ v4l2_ctrl_new_std_menu(hdl, ops, V4L2_CID_FLASH_LED_MODE, V4L2_FLASH_LED_MODE_TORCH, ~0x7, V4L2_FLASH_LED_MODE_NONE); /* flash source */ v4l2_ctrl_new_std_menu(hdl, ops, V4L2_CID_FLASH_STROBE_SOURCE, 0x1, ~0x3, V4L2_FLASH_STROBE_SOURCE_SOFTWARE); /* flash strobe */ v4l2_ctrl_new_std(hdl, ops, V4L2_CID_FLASH_STROBE, 0, 0, 0, 0); /* flash strobe stop */ v4l2_ctrl_new_std(hdl, ops, V4L2_CID_FLASH_STROBE_STOP, 0, 0, 0, 0); /* flash strobe timeout */ v4l2_ctrl_new_std(hdl, ops, V4L2_CID_FLASH_TIMEOUT, LM3646_FLASH_TOUT_MIN, LM3646_FLASH_TOUT_MAX, LM3646_FLASH_TOUT_STEP, flash->pdata->flash_timeout); /* max flash current */ v4l2_ctrl_new_std(hdl, ops, V4L2_CID_FLASH_INTENSITY, LM3646_TOTAL_FLASH_BRT_MIN, LM3646_TOTAL_FLASH_BRT_MAX, LM3646_TOTAL_FLASH_BRT_STEP, LM3646_TOTAL_FLASH_BRT_MAX); /* max torch current */ v4l2_ctrl_new_std(hdl, ops, V4L2_CID_FLASH_TORCH_INTENSITY, LM3646_TOTAL_TORCH_BRT_MIN, LM3646_TOTAL_TORCH_BRT_MAX, LM3646_TOTAL_TORCH_BRT_STEP, LM3646_TOTAL_TORCH_BRT_MAX); /* fault */ fault = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_FLASH_FAULT, 0, V4L2_FLASH_FAULT_OVER_VOLTAGE | V4L2_FLASH_FAULT_OVER_TEMPERATURE | V4L2_FLASH_FAULT_SHORT_CIRCUIT | V4L2_FLASH_FAULT_TIMEOUT, 0, 0); if (fault != NULL) fault->flags |= V4L2_CTRL_FLAG_VOLATILE; if (hdl->error) return hdl->error; flash->subdev_led.ctrl_handler = hdl; return 0; } /* initialize device */ static const struct v4l2_subdev_ops lm3646_ops = { .core = NULL, }; static const struct regmap_config lm3646_regmap = { .reg_bits = 8, .val_bits = 8, .max_register = 0xFF, }; static int lm3646_subdev_init(struct lm3646_flash *flash) { struct i2c_client *client = to_i2c_client(flash->dev); int rval; v4l2_i2c_subdev_init(&flash->subdev_led, client, &lm3646_ops); flash->subdev_led.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE; strscpy(flash->subdev_led.name, LM3646_NAME, sizeof(flash->subdev_led.name)); rval = lm3646_init_controls(flash); if (rval) goto err_out; rval = media_entity_pads_init(&flash->subdev_led.entity, 0, NULL); if (rval < 0) goto err_out; flash->subdev_led.entity.function = MEDIA_ENT_F_FLASH; return rval; err_out: v4l2_ctrl_handler_free(&flash->ctrls_led); return rval; } static int lm3646_init_device(struct lm3646_flash *flash) { unsigned int reg_val; int rval; /* read the value of mode register to reduce redundant i2c accesses */ rval = regmap_read(flash->regmap, REG_ENABLE, &reg_val); if (rval < 0) return rval; flash->mode_reg = reg_val & 0xfc; /* output disable */ rval = lm3646_mode_ctrl(flash, V4L2_FLASH_LED_MODE_NONE); if (rval < 0) return rval; /* * LED1 flash current setting * LED2 flash current = Total(Max) flash current - LED1 flash current */ rval = regmap_update_bits(flash->regmap, REG_LED1_FLASH_BR, 0x7F, LM3646_LED1_FLASH_BRT_uA_TO_REG (flash->pdata->led1_flash_brt)); if (rval < 0) return rval; /* * LED1 torch current setting * LED2 torch current = Total(Max) torch current - LED1 torch current */ rval = regmap_update_bits(flash->regmap, REG_LED1_TORCH_BR, 0x7F, LM3646_LED1_TORCH_BRT_uA_TO_REG (flash->pdata->led1_torch_brt)); if (rval < 0) return rval; /* Reset flag register */ return regmap_read(flash->regmap, REG_FLAG, &reg_val); } static int lm3646_probe(struct i2c_client *client) { struct lm3646_flash *flash; struct lm3646_platform_data *pdata = dev_get_platdata(&client->dev); int rval; flash = devm_kzalloc(&client->dev, sizeof(*flash), GFP_KERNEL); if (flash == NULL) return -ENOMEM; flash->regmap = devm_regmap_init_i2c(client, &lm3646_regmap); if (IS_ERR(flash->regmap)) return PTR_ERR(flash->regmap); /* check device tree if there is no platform data */ if (pdata == NULL) { pdata = devm_kzalloc(&client->dev, sizeof(struct lm3646_platform_data), GFP_KERNEL); if (pdata == NULL) return -ENOMEM; /* use default data in case of no platform data */ pdata->flash_timeout = LM3646_FLASH_TOUT_MAX; pdata->led1_torch_brt = LM3646_LED1_TORCH_BRT_MAX; pdata->led1_flash_brt = LM3646_LED1_FLASH_BRT_MAX; } flash->pdata = pdata; flash->dev = &client->dev; rval = lm3646_subdev_init(flash); if (rval < 0) return rval; rval = lm3646_init_device(flash); if (rval < 0) return rval; i2c_set_clientdata(client, flash); return 0; } static void lm3646_remove(struct i2c_client *client) { struct lm3646_flash *flash = i2c_get_clientdata(client); v4l2_device_unregister_subdev(&flash->subdev_led); v4l2_ctrl_handler_free(&flash->ctrls_led); media_entity_cleanup(&flash->subdev_led.entity); } static const struct i2c_device_id lm3646_id_table[] = { {LM3646_NAME, 0}, {} }; MODULE_DEVICE_TABLE(i2c, lm3646_id_table); static struct i2c_driver lm3646_i2c_driver = { .driver = { .name = LM3646_NAME, }, .probe = lm3646_probe, .remove = lm3646_remove, .id_table = lm3646_id_table, }; module_i2c_driver(lm3646_i2c_driver); MODULE_AUTHOR("Daniel Jeong <[email protected]>"); MODULE_AUTHOR("Ldd Mlp <[email protected]>"); MODULE_DESCRIPTION("Texas Instruments LM3646 Dual Flash LED driver"); MODULE_LICENSE("GPL");
linux-master
drivers/media/i2c/lm3646.c
// SPDX-License-Identifier: GPL-2.0-only /* * drivers/media/i2c/tvp514x.c * * TI TVP5146/47 decoder driver * * Copyright (C) 2008 Texas Instruments Inc * Author: Vaibhav Hiremath <[email protected]> * * Contributors: * Sivaraj R <[email protected]> * Brijesh R Jadav <[email protected]> * Hardik Shah <[email protected]> * Manjunath Hadli <[email protected]> * Karicheri Muralidharan <[email protected]> * Prabhakar Lad <[email protected]> */ #include <linux/i2c.h> #include <linux/slab.h> #include <linux/delay.h> #include <linux/videodev2.h> #include <linux/module.h> #include <linux/v4l2-mediabus.h> #include <linux/of.h> #include <linux/of_graph.h> #include <media/v4l2-async.h> #include <media/v4l2-device.h> #include <media/v4l2-common.h> #include <media/v4l2-mediabus.h> #include <media/v4l2-fwnode.h> #include <media/v4l2-ctrls.h> #include <media/i2c/tvp514x.h> #include <media/media-entity.h> #include "tvp514x_regs.h" /* Private macros for TVP */ #define I2C_RETRY_COUNT (5) #define LOCK_RETRY_COUNT (5) #define LOCK_RETRY_DELAY (200) /* Debug functions */ static bool debug; module_param(debug, bool, 0644); MODULE_PARM_DESC(debug, "Debug level (0-1)"); MODULE_AUTHOR("Texas Instruments"); MODULE_DESCRIPTION("TVP514X linux decoder driver"); MODULE_LICENSE("GPL"); /* enum tvp514x_std - enum for supported standards */ enum tvp514x_std { STD_NTSC_MJ = 0, STD_PAL_BDGHIN, STD_INVALID }; /** * struct tvp514x_std_info - Structure to store standard information * @width: Line width in pixels * @height:Number of active lines * @video_std: Value to write in REG_VIDEO_STD register * @standard: v4l2 standard structure information */ struct tvp514x_std_info { unsigned long width; unsigned long height; u8 video_std; struct v4l2_standard standard; }; static struct tvp514x_reg tvp514x_reg_list_default[0x40]; static int tvp514x_s_stream(struct v4l2_subdev *sd, int enable); /** * struct tvp514x_decoder - TVP5146/47 decoder object * @sd: Subdevice Slave handle * @hdl: embedded &struct v4l2_ctrl_handler * @tvp514x_regs: copy of hw's regs with preset values. * @pdata: Board specific * @ver: Chip version * @streaming: TVP5146/47 decoder streaming - enabled or disabled. * @pix: Current pixel format * @num_fmts: Number of formats * @fmt_list: Format list * @current_std: Current standard * @num_stds: Number of standards * @std_list: Standards list * @input: Input routing at chip level * @output: Output routing at chip level * @pad: subdev media pad associated with the decoder * @format: media bus frame format * @int_seq: driver's register init sequence */ struct tvp514x_decoder { struct v4l2_subdev sd; struct v4l2_ctrl_handler hdl; struct tvp514x_reg tvp514x_regs[ARRAY_SIZE(tvp514x_reg_list_default)]; const struct tvp514x_platform_data *pdata; int ver; int streaming; struct v4l2_pix_format pix; int num_fmts; const struct v4l2_fmtdesc *fmt_list; enum tvp514x_std current_std; int num_stds; const struct tvp514x_std_info *std_list; /* Input and Output Routing parameters */ u32 input; u32 output; /* mc related members */ struct media_pad pad; struct v4l2_mbus_framefmt format; struct tvp514x_reg *int_seq; }; /* TVP514x default register values */ static struct tvp514x_reg tvp514x_reg_list_default[] = { /* Composite selected */ {TOK_WRITE, REG_INPUT_SEL, 0x05}, {TOK_WRITE, REG_AFE_GAIN_CTRL, 0x0F}, /* Auto mode */ {TOK_WRITE, REG_VIDEO_STD, 0x00}, {TOK_WRITE, REG_OPERATION_MODE, 0x00}, {TOK_SKIP, REG_AUTOSWITCH_MASK, 0x3F}, {TOK_WRITE, REG_COLOR_KILLER, 0x10}, {TOK_WRITE, REG_LUMA_CONTROL1, 0x00}, {TOK_WRITE, REG_LUMA_CONTROL2, 0x00}, {TOK_WRITE, REG_LUMA_CONTROL3, 0x02}, {TOK_WRITE, REG_BRIGHTNESS, 0x80}, {TOK_WRITE, REG_CONTRAST, 0x80}, {TOK_WRITE, REG_SATURATION, 0x80}, {TOK_WRITE, REG_HUE, 0x00}, {TOK_WRITE, REG_CHROMA_CONTROL1, 0x00}, {TOK_WRITE, REG_CHROMA_CONTROL2, 0x0E}, /* Reserved */ {TOK_SKIP, 0x0F, 0x00}, {TOK_WRITE, REG_COMP_PR_SATURATION, 0x80}, {TOK_WRITE, REG_COMP_Y_CONTRAST, 0x80}, {TOK_WRITE, REG_COMP_PB_SATURATION, 0x80}, /* Reserved */ {TOK_SKIP, 0x13, 0x00}, {TOK_WRITE, REG_COMP_Y_BRIGHTNESS, 0x80}, /* Reserved */ {TOK_SKIP, 0x15, 0x00}, /* NTSC timing */ {TOK_SKIP, REG_AVID_START_PIXEL_LSB, 0x55}, {TOK_SKIP, REG_AVID_START_PIXEL_MSB, 0x00}, {TOK_SKIP, REG_AVID_STOP_PIXEL_LSB, 0x25}, {TOK_SKIP, REG_AVID_STOP_PIXEL_MSB, 0x03}, /* NTSC timing */ {TOK_SKIP, REG_HSYNC_START_PIXEL_LSB, 0x00}, {TOK_SKIP, REG_HSYNC_START_PIXEL_MSB, 0x00}, {TOK_SKIP, REG_HSYNC_STOP_PIXEL_LSB, 0x40}, {TOK_SKIP, REG_HSYNC_STOP_PIXEL_MSB, 0x00}, /* NTSC timing */ {TOK_SKIP, REG_VSYNC_START_LINE_LSB, 0x04}, {TOK_SKIP, REG_VSYNC_START_LINE_MSB, 0x00}, {TOK_SKIP, REG_VSYNC_STOP_LINE_LSB, 0x07}, {TOK_SKIP, REG_VSYNC_STOP_LINE_MSB, 0x00}, /* NTSC timing */ {TOK_SKIP, REG_VBLK_START_LINE_LSB, 0x01}, {TOK_SKIP, REG_VBLK_START_LINE_MSB, 0x00}, {TOK_SKIP, REG_VBLK_STOP_LINE_LSB, 0x15}, {TOK_SKIP, REG_VBLK_STOP_LINE_MSB, 0x00}, /* Reserved */ {TOK_SKIP, 0x26, 0x00}, /* Reserved */ {TOK_SKIP, 0x27, 0x00}, {TOK_SKIP, REG_FAST_SWTICH_CONTROL, 0xCC}, /* Reserved */ {TOK_SKIP, 0x29, 0x00}, {TOK_SKIP, REG_FAST_SWTICH_SCART_DELAY, 0x00}, /* Reserved */ {TOK_SKIP, 0x2B, 0x00}, {TOK_SKIP, REG_SCART_DELAY, 0x00}, {TOK_SKIP, REG_CTI_DELAY, 0x00}, {TOK_SKIP, REG_CTI_CONTROL, 0x00}, /* Reserved */ {TOK_SKIP, 0x2F, 0x00}, /* Reserved */ {TOK_SKIP, 0x30, 0x00}, /* Reserved */ {TOK_SKIP, 0x31, 0x00}, /* HS, VS active high */ {TOK_WRITE, REG_SYNC_CONTROL, 0x00}, /* 10-bit BT.656 */ {TOK_WRITE, REG_OUTPUT_FORMATTER1, 0x00}, /* Enable clk & data */ {TOK_WRITE, REG_OUTPUT_FORMATTER2, 0x11}, /* Enable AVID & FLD */ {TOK_WRITE, REG_OUTPUT_FORMATTER3, 0xEE}, /* Enable VS & HS */ {TOK_WRITE, REG_OUTPUT_FORMATTER4, 0xAF}, {TOK_WRITE, REG_OUTPUT_FORMATTER5, 0xFF}, {TOK_WRITE, REG_OUTPUT_FORMATTER6, 0xFF}, /* Clear status */ {TOK_WRITE, REG_CLEAR_LOST_LOCK, 0x01}, {TOK_TERM, 0, 0}, }; /* * List of image formats supported by TVP5146/47 decoder * Currently we are using 8 bit mode only, but can be * extended to 10/20 bit mode. */ static const struct v4l2_fmtdesc tvp514x_fmt_list[] = { { .index = 0, .type = V4L2_BUF_TYPE_VIDEO_CAPTURE, .flags = 0, .description = "8-bit UYVY 4:2:2 Format", .pixelformat = V4L2_PIX_FMT_UYVY, }, }; /* * Supported standards - * * Currently supports two standards only, need to add support for rest of the * modes, like SECAM, etc... */ static const struct tvp514x_std_info tvp514x_std_list[] = { /* Standard: STD_NTSC_MJ */ [STD_NTSC_MJ] = { .width = NTSC_NUM_ACTIVE_PIXELS, .height = NTSC_NUM_ACTIVE_LINES, .video_std = VIDEO_STD_NTSC_MJ_BIT, .standard = { .index = 0, .id = V4L2_STD_NTSC, .name = "NTSC", .frameperiod = {1001, 30000}, .framelines = 525 }, /* Standard: STD_PAL_BDGHIN */ }, [STD_PAL_BDGHIN] = { .width = PAL_NUM_ACTIVE_PIXELS, .height = PAL_NUM_ACTIVE_LINES, .video_std = VIDEO_STD_PAL_BDGHIN_BIT, .standard = { .index = 1, .id = V4L2_STD_PAL, .name = "PAL", .frameperiod = {1, 25}, .framelines = 625 }, }, /* Standard: need to add for additional standard */ }; static inline struct tvp514x_decoder *to_decoder(struct v4l2_subdev *sd) { return container_of(sd, struct tvp514x_decoder, sd); } static inline struct v4l2_subdev *to_sd(struct v4l2_ctrl *ctrl) { return &container_of(ctrl->handler, struct tvp514x_decoder, hdl)->sd; } /** * tvp514x_read_reg() - Read a value from a register in an TVP5146/47. * @sd: ptr to v4l2_subdev struct * @reg: TVP5146/47 register address * * Returns value read if successful, or non-zero (-1) otherwise. */ static int tvp514x_read_reg(struct v4l2_subdev *sd, u8 reg) { int err, retry = 0; struct i2c_client *client = v4l2_get_subdevdata(sd); read_again: err = i2c_smbus_read_byte_data(client, reg); if (err < 0) { if (retry <= I2C_RETRY_COUNT) { v4l2_warn(sd, "Read: retry ... %d\n", retry); retry++; msleep_interruptible(10); goto read_again; } } return err; } /** * dump_reg() - dump the register content of TVP5146/47. * @sd: ptr to v4l2_subdev struct * @reg: TVP5146/47 register address */ static void dump_reg(struct v4l2_subdev *sd, u8 reg) { u32 val; val = tvp514x_read_reg(sd, reg); v4l2_info(sd, "Reg(0x%.2X): 0x%.2X\n", reg, val); } /** * tvp514x_write_reg() - Write a value to a register in TVP5146/47 * @sd: ptr to v4l2_subdev struct * @reg: TVP5146/47 register address * @val: value to be written to the register * * Write a value to a register in an TVP5146/47 decoder device. * Returns zero if successful, or non-zero otherwise. */ static int tvp514x_write_reg(struct v4l2_subdev *sd, u8 reg, u8 val) { int err, retry = 0; struct i2c_client *client = v4l2_get_subdevdata(sd); write_again: err = i2c_smbus_write_byte_data(client, reg, val); if (err) { if (retry <= I2C_RETRY_COUNT) { v4l2_warn(sd, "Write: retry ... %d\n", retry); retry++; msleep_interruptible(10); goto write_again; } } return err; } /** * tvp514x_write_regs() : Initializes a list of TVP5146/47 registers * @sd: ptr to v4l2_subdev struct * @reglist: list of TVP5146/47 registers and values * * Initializes a list of TVP5146/47 registers:- * if token is TOK_TERM, then entire write operation terminates * if token is TOK_DELAY, then a delay of 'val' msec is introduced * if token is TOK_SKIP, then the register write is skipped * if token is TOK_WRITE, then the register write is performed * Returns zero if successful, or non-zero otherwise. */ static int tvp514x_write_regs(struct v4l2_subdev *sd, const struct tvp514x_reg reglist[]) { int err; const struct tvp514x_reg *next = reglist; for (; next->token != TOK_TERM; next++) { if (next->token == TOK_DELAY) { msleep(next->val); continue; } if (next->token == TOK_SKIP) continue; err = tvp514x_write_reg(sd, next->reg, (u8) next->val); if (err) { v4l2_err(sd, "Write failed. Err[%d]\n", err); return err; } } return 0; } /** * tvp514x_query_current_std() : Query the current standard detected by TVP5146/47 * @sd: ptr to v4l2_subdev struct * * Returns the current standard detected by TVP5146/47, STD_INVALID if there is no * standard detected. */ static enum tvp514x_std tvp514x_query_current_std(struct v4l2_subdev *sd) { u8 std, std_status; std = tvp514x_read_reg(sd, REG_VIDEO_STD); if ((std & VIDEO_STD_MASK) == VIDEO_STD_AUTO_SWITCH_BIT) /* use the standard status register */ std_status = tvp514x_read_reg(sd, REG_VIDEO_STD_STATUS); else /* use the standard register itself */ std_status = std; switch (std_status & VIDEO_STD_MASK) { case VIDEO_STD_NTSC_MJ_BIT: return STD_NTSC_MJ; case VIDEO_STD_PAL_BDGHIN_BIT: return STD_PAL_BDGHIN; default: return STD_INVALID; } return STD_INVALID; } /* TVP5146/47 register dump function */ static void tvp514x_reg_dump(struct v4l2_subdev *sd) { dump_reg(sd, REG_INPUT_SEL); dump_reg(sd, REG_AFE_GAIN_CTRL); dump_reg(sd, REG_VIDEO_STD); dump_reg(sd, REG_OPERATION_MODE); dump_reg(sd, REG_COLOR_KILLER); dump_reg(sd, REG_LUMA_CONTROL1); dump_reg(sd, REG_LUMA_CONTROL2); dump_reg(sd, REG_LUMA_CONTROL3); dump_reg(sd, REG_BRIGHTNESS); dump_reg(sd, REG_CONTRAST); dump_reg(sd, REG_SATURATION); dump_reg(sd, REG_HUE); dump_reg(sd, REG_CHROMA_CONTROL1); dump_reg(sd, REG_CHROMA_CONTROL2); dump_reg(sd, REG_COMP_PR_SATURATION); dump_reg(sd, REG_COMP_Y_CONTRAST); dump_reg(sd, REG_COMP_PB_SATURATION); dump_reg(sd, REG_COMP_Y_BRIGHTNESS); dump_reg(sd, REG_AVID_START_PIXEL_LSB); dump_reg(sd, REG_AVID_START_PIXEL_MSB); dump_reg(sd, REG_AVID_STOP_PIXEL_LSB); dump_reg(sd, REG_AVID_STOP_PIXEL_MSB); dump_reg(sd, REG_HSYNC_START_PIXEL_LSB); dump_reg(sd, REG_HSYNC_START_PIXEL_MSB); dump_reg(sd, REG_HSYNC_STOP_PIXEL_LSB); dump_reg(sd, REG_HSYNC_STOP_PIXEL_MSB); dump_reg(sd, REG_VSYNC_START_LINE_LSB); dump_reg(sd, REG_VSYNC_START_LINE_MSB); dump_reg(sd, REG_VSYNC_STOP_LINE_LSB); dump_reg(sd, REG_VSYNC_STOP_LINE_MSB); dump_reg(sd, REG_VBLK_START_LINE_LSB); dump_reg(sd, REG_VBLK_START_LINE_MSB); dump_reg(sd, REG_VBLK_STOP_LINE_LSB); dump_reg(sd, REG_VBLK_STOP_LINE_MSB); dump_reg(sd, REG_SYNC_CONTROL); dump_reg(sd, REG_OUTPUT_FORMATTER1); dump_reg(sd, REG_OUTPUT_FORMATTER2); dump_reg(sd, REG_OUTPUT_FORMATTER3); dump_reg(sd, REG_OUTPUT_FORMATTER4); dump_reg(sd, REG_OUTPUT_FORMATTER5); dump_reg(sd, REG_OUTPUT_FORMATTER6); dump_reg(sd, REG_CLEAR_LOST_LOCK); } /** * tvp514x_configure() - Configure the TVP5146/47 registers * @sd: ptr to v4l2_subdev struct * @decoder: ptr to tvp514x_decoder structure * * Returns zero if successful, or non-zero otherwise. */ static int tvp514x_configure(struct v4l2_subdev *sd, struct tvp514x_decoder *decoder) { int err; /* common register initialization */ err = tvp514x_write_regs(sd, decoder->tvp514x_regs); if (err) return err; if (debug) tvp514x_reg_dump(sd); return 0; } /** * tvp514x_detect() - Detect if an tvp514x is present, and if so which revision. * @sd: pointer to standard V4L2 sub-device structure * @decoder: pointer to tvp514x_decoder structure * * A device is considered to be detected if the chip ID (LSB and MSB) * registers match the expected values. * Any value of the rom version register is accepted. * Returns ENODEV error number if no device is detected, or zero * if a device is detected. */ static int tvp514x_detect(struct v4l2_subdev *sd, struct tvp514x_decoder *decoder) { u8 chip_id_msb, chip_id_lsb, rom_ver; struct i2c_client *client = v4l2_get_subdevdata(sd); chip_id_msb = tvp514x_read_reg(sd, REG_CHIP_ID_MSB); chip_id_lsb = tvp514x_read_reg(sd, REG_CHIP_ID_LSB); rom_ver = tvp514x_read_reg(sd, REG_ROM_VERSION); v4l2_dbg(1, debug, sd, "chip id detected msb:0x%x lsb:0x%x rom version:0x%x\n", chip_id_msb, chip_id_lsb, rom_ver); if ((chip_id_msb != TVP514X_CHIP_ID_MSB) || ((chip_id_lsb != TVP5146_CHIP_ID_LSB) && (chip_id_lsb != TVP5147_CHIP_ID_LSB))) { /* We didn't read the values we expected, so this must not be * an TVP5146/47. */ v4l2_err(sd, "chip id mismatch msb:0x%x lsb:0x%x\n", chip_id_msb, chip_id_lsb); return -ENODEV; } decoder->ver = rom_ver; v4l2_info(sd, "%s (Version - 0x%.2x) found at 0x%x (%s)\n", client->name, decoder->ver, client->addr << 1, client->adapter->name); return 0; } /** * tvp514x_querystd() - V4L2 decoder interface handler for querystd * @sd: pointer to standard V4L2 sub-device structure * @std_id: standard V4L2 std_id ioctl enum * * Returns the current standard detected by TVP5146/47. If no active input is * detected then *std_id is set to 0 and the function returns 0. */ static int tvp514x_querystd(struct v4l2_subdev *sd, v4l2_std_id *std_id) { struct tvp514x_decoder *decoder = to_decoder(sd); enum tvp514x_std current_std; enum tvp514x_input input_sel; u8 sync_lock_status, lock_mask; if (std_id == NULL) return -EINVAL; /* To query the standard the TVP514x must power on the ADCs. */ if (!decoder->streaming) { tvp514x_s_stream(sd, 1); msleep(LOCK_RETRY_DELAY); } /* query the current standard */ current_std = tvp514x_query_current_std(sd); if (current_std == STD_INVALID) { *std_id = V4L2_STD_UNKNOWN; return 0; } input_sel = decoder->input; switch (input_sel) { case INPUT_CVBS_VI1A: case INPUT_CVBS_VI1B: case INPUT_CVBS_VI1C: case INPUT_CVBS_VI2A: case INPUT_CVBS_VI2B: case INPUT_CVBS_VI2C: case INPUT_CVBS_VI3A: case INPUT_CVBS_VI3B: case INPUT_CVBS_VI3C: case INPUT_CVBS_VI4A: lock_mask = STATUS_CLR_SUBCAR_LOCK_BIT | STATUS_HORZ_SYNC_LOCK_BIT | STATUS_VIRT_SYNC_LOCK_BIT; break; case INPUT_SVIDEO_VI2A_VI1A: case INPUT_SVIDEO_VI2B_VI1B: case INPUT_SVIDEO_VI2C_VI1C: case INPUT_SVIDEO_VI2A_VI3A: case INPUT_SVIDEO_VI2B_VI3B: case INPUT_SVIDEO_VI2C_VI3C: case INPUT_SVIDEO_VI4A_VI1A: case INPUT_SVIDEO_VI4A_VI1B: case INPUT_SVIDEO_VI4A_VI1C: case INPUT_SVIDEO_VI4A_VI3A: case INPUT_SVIDEO_VI4A_VI3B: case INPUT_SVIDEO_VI4A_VI3C: lock_mask = STATUS_HORZ_SYNC_LOCK_BIT | STATUS_VIRT_SYNC_LOCK_BIT; break; /*Need to add other interfaces*/ default: return -EINVAL; } /* check whether signal is locked */ sync_lock_status = tvp514x_read_reg(sd, REG_STATUS1); if (lock_mask != (sync_lock_status & lock_mask)) { *std_id = V4L2_STD_UNKNOWN; return 0; /* No input detected */ } *std_id &= decoder->std_list[current_std].standard.id; v4l2_dbg(1, debug, sd, "Current STD: %s\n", decoder->std_list[current_std].standard.name); return 0; } /** * tvp514x_s_std() - V4L2 decoder interface handler for s_std * @sd: pointer to standard V4L2 sub-device structure * @std_id: standard V4L2 v4l2_std_id ioctl enum * * If std_id is supported, sets the requested standard. Otherwise, returns * -EINVAL */ static int tvp514x_s_std(struct v4l2_subdev *sd, v4l2_std_id std_id) { struct tvp514x_decoder *decoder = to_decoder(sd); int err, i; for (i = 0; i < decoder->num_stds; i++) if (std_id & decoder->std_list[i].standard.id) break; if ((i == decoder->num_stds) || (i == STD_INVALID)) return -EINVAL; err = tvp514x_write_reg(sd, REG_VIDEO_STD, decoder->std_list[i].video_std); if (err) return err; decoder->current_std = i; decoder->tvp514x_regs[REG_VIDEO_STD].val = decoder->std_list[i].video_std; v4l2_dbg(1, debug, sd, "Standard set to: %s\n", decoder->std_list[i].standard.name); return 0; } /** * tvp514x_s_routing() - V4L2 decoder interface handler for s_routing * @sd: pointer to standard V4L2 sub-device structure * @input: input selector for routing the signal * @output: output selector for routing the signal * @config: config value. Not used * * If index is valid, selects the requested input. Otherwise, returns -EINVAL if * the input is not supported or there is no active signal present in the * selected input. */ static int tvp514x_s_routing(struct v4l2_subdev *sd, u32 input, u32 output, u32 config) { struct tvp514x_decoder *decoder = to_decoder(sd); int err; enum tvp514x_input input_sel; enum tvp514x_output output_sel; if ((input >= INPUT_INVALID) || (output >= OUTPUT_INVALID)) /* Index out of bound */ return -EINVAL; input_sel = input; output_sel = output; err = tvp514x_write_reg(sd, REG_INPUT_SEL, input_sel); if (err) return err; output_sel |= tvp514x_read_reg(sd, REG_OUTPUT_FORMATTER1) & 0x7; err = tvp514x_write_reg(sd, REG_OUTPUT_FORMATTER1, output_sel); if (err) return err; decoder->tvp514x_regs[REG_INPUT_SEL].val = input_sel; decoder->tvp514x_regs[REG_OUTPUT_FORMATTER1].val = output_sel; decoder->input = input; decoder->output = output; v4l2_dbg(1, debug, sd, "Input set to: %d\n", input_sel); return 0; } /** * tvp514x_s_ctrl() - V4L2 decoder interface handler for s_ctrl * @ctrl: pointer to v4l2_ctrl structure * * If the requested control is supported, sets the control's current * value in HW. Otherwise, returns -EINVAL if the control is not supported. */ static int tvp514x_s_ctrl(struct v4l2_ctrl *ctrl) { struct v4l2_subdev *sd = to_sd(ctrl); struct tvp514x_decoder *decoder = to_decoder(sd); int err = -EINVAL, value; value = ctrl->val; switch (ctrl->id) { case V4L2_CID_BRIGHTNESS: err = tvp514x_write_reg(sd, REG_BRIGHTNESS, value); if (!err) decoder->tvp514x_regs[REG_BRIGHTNESS].val = value; break; case V4L2_CID_CONTRAST: err = tvp514x_write_reg(sd, REG_CONTRAST, value); if (!err) decoder->tvp514x_regs[REG_CONTRAST].val = value; break; case V4L2_CID_SATURATION: err = tvp514x_write_reg(sd, REG_SATURATION, value); if (!err) decoder->tvp514x_regs[REG_SATURATION].val = value; break; case V4L2_CID_HUE: if (value == 180) value = 0x7F; else if (value == -180) value = 0x80; err = tvp514x_write_reg(sd, REG_HUE, value); if (!err) decoder->tvp514x_regs[REG_HUE].val = value; break; case V4L2_CID_AUTOGAIN: err = tvp514x_write_reg(sd, REG_AFE_GAIN_CTRL, value ? 0x0f : 0x0c); if (!err) decoder->tvp514x_regs[REG_AFE_GAIN_CTRL].val = value; break; } v4l2_dbg(1, debug, sd, "Set Control: ID - %d - %d\n", ctrl->id, ctrl->val); return err; } /** * tvp514x_g_frame_interval() - V4L2 decoder interface handler * @sd: pointer to standard V4L2 sub-device structure * @ival: pointer to a v4l2_subdev_frame_interval structure * * Returns the decoder's video CAPTURE parameters. */ static int tvp514x_g_frame_interval(struct v4l2_subdev *sd, struct v4l2_subdev_frame_interval *ival) { struct tvp514x_decoder *decoder = to_decoder(sd); enum tvp514x_std current_std; /* get the current standard */ current_std = decoder->current_std; ival->interval = decoder->std_list[current_std].standard.frameperiod; return 0; } /** * tvp514x_s_frame_interval() - V4L2 decoder interface handler * @sd: pointer to standard V4L2 sub-device structure * @ival: pointer to a v4l2_subdev_frame_interval structure * * Configures the decoder to use the input parameters, if possible. If * not possible, returns the appropriate error code. */ static int tvp514x_s_frame_interval(struct v4l2_subdev *sd, struct v4l2_subdev_frame_interval *ival) { struct tvp514x_decoder *decoder = to_decoder(sd); struct v4l2_fract *timeperframe; enum tvp514x_std current_std; timeperframe = &ival->interval; /* get the current standard */ current_std = decoder->current_std; *timeperframe = decoder->std_list[current_std].standard.frameperiod; return 0; } /** * tvp514x_s_stream() - V4L2 decoder i/f handler for s_stream * @sd: pointer to standard V4L2 sub-device structure * @enable: streaming enable or disable * * Sets streaming to enable or disable, if possible. */ static int tvp514x_s_stream(struct v4l2_subdev *sd, int enable) { int err = 0; struct tvp514x_decoder *decoder = to_decoder(sd); if (decoder->streaming == enable) return 0; switch (enable) { case 0: { /* Power Down Sequence */ err = tvp514x_write_reg(sd, REG_OPERATION_MODE, 0x01); if (err) { v4l2_err(sd, "Unable to turn off decoder\n"); return err; } decoder->streaming = enable; break; } case 1: { /* Power Up Sequence */ err = tvp514x_write_regs(sd, decoder->int_seq); if (err) { v4l2_err(sd, "Unable to turn on decoder\n"); return err; } /* Detect if not already detected */ err = tvp514x_detect(sd, decoder); if (err) { v4l2_err(sd, "Unable to detect decoder\n"); return err; } err = tvp514x_configure(sd, decoder); if (err) { v4l2_err(sd, "Unable to configure decoder\n"); return err; } decoder->streaming = enable; break; } default: err = -ENODEV; break; } return err; } static const struct v4l2_ctrl_ops tvp514x_ctrl_ops = { .s_ctrl = tvp514x_s_ctrl, }; /** * tvp514x_enum_mbus_code() - V4L2 decoder interface handler for enum_mbus_code * @sd: pointer to standard V4L2 sub-device structure * @sd_state: subdev state * @code: pointer to v4l2_subdev_mbus_code_enum structure * * Enumertaes mbus codes supported */ static int tvp514x_enum_mbus_code(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_mbus_code_enum *code) { u32 pad = code->pad; u32 index = code->index; memset(code, 0, sizeof(*code)); code->index = index; code->pad = pad; if (index != 0) return -EINVAL; code->code = MEDIA_BUS_FMT_UYVY8_2X8; return 0; } /** * tvp514x_get_pad_format() - V4L2 decoder interface handler for get pad format * @sd: pointer to standard V4L2 sub-device structure * @sd_state: subdev state * @format: pointer to v4l2_subdev_format structure * * Retrieves pad format which is active or tried based on requirement */ static int tvp514x_get_pad_format(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *format) { struct tvp514x_decoder *decoder = to_decoder(sd); __u32 which = format->which; if (format->pad) return -EINVAL; if (which == V4L2_SUBDEV_FORMAT_ACTIVE) { format->format = decoder->format; return 0; } format->format.code = MEDIA_BUS_FMT_UYVY8_2X8; format->format.width = tvp514x_std_list[decoder->current_std].width; format->format.height = tvp514x_std_list[decoder->current_std].height; format->format.colorspace = V4L2_COLORSPACE_SMPTE170M; format->format.field = V4L2_FIELD_INTERLACED; return 0; } /** * tvp514x_set_pad_format() - V4L2 decoder interface handler for set pad format * @sd: pointer to standard V4L2 sub-device structure * @sd_state: subdev state * @fmt: pointer to v4l2_subdev_format structure * * Set pad format for the output pad */ static int tvp514x_set_pad_format(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *fmt) { struct tvp514x_decoder *decoder = to_decoder(sd); if (fmt->format.field != V4L2_FIELD_INTERLACED || fmt->format.code != MEDIA_BUS_FMT_UYVY8_2X8 || fmt->format.colorspace != V4L2_COLORSPACE_SMPTE170M || fmt->format.width != tvp514x_std_list[decoder->current_std].width || fmt->format.height != tvp514x_std_list[decoder->current_std].height) return -EINVAL; decoder->format = fmt->format; return 0; } static const struct v4l2_subdev_video_ops tvp514x_video_ops = { .s_std = tvp514x_s_std, .s_routing = tvp514x_s_routing, .querystd = tvp514x_querystd, .g_frame_interval = tvp514x_g_frame_interval, .s_frame_interval = tvp514x_s_frame_interval, .s_stream = tvp514x_s_stream, }; static const struct v4l2_subdev_pad_ops tvp514x_pad_ops = { .enum_mbus_code = tvp514x_enum_mbus_code, .get_fmt = tvp514x_get_pad_format, .set_fmt = tvp514x_set_pad_format, }; static const struct v4l2_subdev_ops tvp514x_ops = { .video = &tvp514x_video_ops, .pad = &tvp514x_pad_ops, }; static const struct tvp514x_decoder tvp514x_dev = { .streaming = 0, .fmt_list = tvp514x_fmt_list, .num_fmts = ARRAY_SIZE(tvp514x_fmt_list), .pix = { /* Default to NTSC 8-bit YUV 422 */ .width = NTSC_NUM_ACTIVE_PIXELS, .height = NTSC_NUM_ACTIVE_LINES, .pixelformat = V4L2_PIX_FMT_UYVY, .field = V4L2_FIELD_INTERLACED, .bytesperline = NTSC_NUM_ACTIVE_PIXELS * 2, .sizeimage = NTSC_NUM_ACTIVE_PIXELS * 2 * NTSC_NUM_ACTIVE_LINES, .colorspace = V4L2_COLORSPACE_SMPTE170M, }, .current_std = STD_NTSC_MJ, .std_list = tvp514x_std_list, .num_stds = ARRAY_SIZE(tvp514x_std_list), }; static struct tvp514x_platform_data * tvp514x_get_pdata(struct i2c_client *client) { struct tvp514x_platform_data *pdata = NULL; struct v4l2_fwnode_endpoint bus_cfg = { .bus_type = 0 }; struct device_node *endpoint; unsigned int flags; if (!IS_ENABLED(CONFIG_OF) || !client->dev.of_node) return client->dev.platform_data; endpoint = of_graph_get_next_endpoint(client->dev.of_node, NULL); if (!endpoint) return NULL; if (v4l2_fwnode_endpoint_parse(of_fwnode_handle(endpoint), &bus_cfg)) goto done; pdata = devm_kzalloc(&client->dev, sizeof(*pdata), GFP_KERNEL); if (!pdata) goto done; flags = bus_cfg.bus.parallel.flags; if (flags & V4L2_MBUS_HSYNC_ACTIVE_HIGH) pdata->hs_polarity = 1; if (flags & V4L2_MBUS_VSYNC_ACTIVE_HIGH) pdata->vs_polarity = 1; if (flags & V4L2_MBUS_PCLK_SAMPLE_RISING) pdata->clk_polarity = 1; done: of_node_put(endpoint); return pdata; } /** * tvp514x_probe() - decoder driver i2c probe handler * @client: i2c driver client device structure * * Register decoder as an i2c client device and V4L2 * device. */ static int tvp514x_probe(struct i2c_client *client) { const struct i2c_device_id *id = i2c_client_get_device_id(client); struct tvp514x_platform_data *pdata = tvp514x_get_pdata(client); struct tvp514x_decoder *decoder; struct v4l2_subdev *sd; int ret; if (pdata == NULL) { dev_err(&client->dev, "No platform data\n"); return -EINVAL; } /* Check if the adapter supports the needed features */ if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE_DATA)) return -EIO; decoder = devm_kzalloc(&client->dev, sizeof(*decoder), GFP_KERNEL); if (!decoder) return -ENOMEM; /* Initialize the tvp514x_decoder with default configuration */ *decoder = tvp514x_dev; /* Copy default register configuration */ memcpy(decoder->tvp514x_regs, tvp514x_reg_list_default, sizeof(tvp514x_reg_list_default)); decoder->int_seq = (struct tvp514x_reg *)id->driver_data; /* Copy board specific information here */ decoder->pdata = pdata; /** * Fetch platform specific data, and configure the * tvp514x_reg_list[] accordingly. Since this is one * time configuration, no need to preserve. */ decoder->tvp514x_regs[REG_OUTPUT_FORMATTER2].val |= (decoder->pdata->clk_polarity << 1); decoder->tvp514x_regs[REG_SYNC_CONTROL].val |= ((decoder->pdata->hs_polarity << 2) | (decoder->pdata->vs_polarity << 3)); /* Set default standard to auto */ decoder->tvp514x_regs[REG_VIDEO_STD].val = VIDEO_STD_AUTO_SWITCH_BIT; /* Register with V4L2 layer as slave device */ sd = &decoder->sd; v4l2_i2c_subdev_init(sd, client, &tvp514x_ops); #if defined(CONFIG_MEDIA_CONTROLLER) decoder->pad.flags = MEDIA_PAD_FL_SOURCE; decoder->sd.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE; decoder->sd.entity.function = MEDIA_ENT_F_ATV_DECODER; ret = media_entity_pads_init(&decoder->sd.entity, 1, &decoder->pad); if (ret < 0) { v4l2_err(sd, "%s decoder driver failed to register !!\n", sd->name); return ret; } #endif v4l2_ctrl_handler_init(&decoder->hdl, 5); v4l2_ctrl_new_std(&decoder->hdl, &tvp514x_ctrl_ops, V4L2_CID_BRIGHTNESS, 0, 255, 1, 128); v4l2_ctrl_new_std(&decoder->hdl, &tvp514x_ctrl_ops, V4L2_CID_CONTRAST, 0, 255, 1, 128); v4l2_ctrl_new_std(&decoder->hdl, &tvp514x_ctrl_ops, V4L2_CID_SATURATION, 0, 255, 1, 128); v4l2_ctrl_new_std(&decoder->hdl, &tvp514x_ctrl_ops, V4L2_CID_HUE, -180, 180, 180, 0); v4l2_ctrl_new_std(&decoder->hdl, &tvp514x_ctrl_ops, V4L2_CID_AUTOGAIN, 0, 1, 1, 1); sd->ctrl_handler = &decoder->hdl; if (decoder->hdl.error) { ret = decoder->hdl.error; goto done; } v4l2_ctrl_handler_setup(&decoder->hdl); ret = v4l2_async_register_subdev(&decoder->sd); if (!ret) v4l2_info(sd, "%s decoder driver registered !!\n", sd->name); done: if (ret < 0) { v4l2_ctrl_handler_free(&decoder->hdl); media_entity_cleanup(&decoder->sd.entity); } return ret; } /** * tvp514x_remove() - decoder driver i2c remove handler * @client: i2c driver client device structure * * Unregister decoder as an i2c client device and V4L2 * device. Complement of tvp514x_probe(). */ static void tvp514x_remove(struct i2c_client *client) { struct v4l2_subdev *sd = i2c_get_clientdata(client); struct tvp514x_decoder *decoder = to_decoder(sd); v4l2_async_unregister_subdev(&decoder->sd); media_entity_cleanup(&decoder->sd.entity); v4l2_ctrl_handler_free(&decoder->hdl); } /* TVP5146 Init/Power on Sequence */ static const struct tvp514x_reg tvp5146_init_reg_seq[] = { {TOK_WRITE, REG_VBUS_ADDRESS_ACCESS1, 0x02}, {TOK_WRITE, REG_VBUS_ADDRESS_ACCESS2, 0x00}, {TOK_WRITE, REG_VBUS_ADDRESS_ACCESS3, 0x80}, {TOK_WRITE, REG_VBUS_DATA_ACCESS_NO_VBUS_ADDR_INCR, 0x01}, {TOK_WRITE, REG_VBUS_ADDRESS_ACCESS1, 0x60}, {TOK_WRITE, REG_VBUS_ADDRESS_ACCESS2, 0x00}, {TOK_WRITE, REG_VBUS_ADDRESS_ACCESS3, 0xB0}, {TOK_WRITE, REG_VBUS_DATA_ACCESS_NO_VBUS_ADDR_INCR, 0x01}, {TOK_WRITE, REG_VBUS_DATA_ACCESS_NO_VBUS_ADDR_INCR, 0x00}, {TOK_WRITE, REG_OPERATION_MODE, 0x01}, {TOK_WRITE, REG_OPERATION_MODE, 0x00}, {TOK_TERM, 0, 0}, }; /* TVP5147 Init/Power on Sequence */ static const struct tvp514x_reg tvp5147_init_reg_seq[] = { {TOK_WRITE, REG_VBUS_ADDRESS_ACCESS1, 0x02}, {TOK_WRITE, REG_VBUS_ADDRESS_ACCESS2, 0x00}, {TOK_WRITE, REG_VBUS_ADDRESS_ACCESS3, 0x80}, {TOK_WRITE, REG_VBUS_DATA_ACCESS_NO_VBUS_ADDR_INCR, 0x01}, {TOK_WRITE, REG_VBUS_ADDRESS_ACCESS1, 0x60}, {TOK_WRITE, REG_VBUS_ADDRESS_ACCESS2, 0x00}, {TOK_WRITE, REG_VBUS_ADDRESS_ACCESS3, 0xB0}, {TOK_WRITE, REG_VBUS_DATA_ACCESS_NO_VBUS_ADDR_INCR, 0x01}, {TOK_WRITE, REG_VBUS_ADDRESS_ACCESS1, 0x16}, {TOK_WRITE, REG_VBUS_ADDRESS_ACCESS2, 0x00}, {TOK_WRITE, REG_VBUS_ADDRESS_ACCESS3, 0xA0}, {TOK_WRITE, REG_VBUS_DATA_ACCESS_NO_VBUS_ADDR_INCR, 0x16}, {TOK_WRITE, REG_VBUS_ADDRESS_ACCESS1, 0x60}, {TOK_WRITE, REG_VBUS_ADDRESS_ACCESS2, 0x00}, {TOK_WRITE, REG_VBUS_ADDRESS_ACCESS3, 0xB0}, {TOK_WRITE, REG_VBUS_DATA_ACCESS_NO_VBUS_ADDR_INCR, 0x00}, {TOK_WRITE, REG_OPERATION_MODE, 0x01}, {TOK_WRITE, REG_OPERATION_MODE, 0x00}, {TOK_TERM, 0, 0}, }; /* TVP5146M2/TVP5147M1 Init/Power on Sequence */ static const struct tvp514x_reg tvp514xm_init_reg_seq[] = { {TOK_WRITE, REG_OPERATION_MODE, 0x01}, {TOK_WRITE, REG_OPERATION_MODE, 0x00}, {TOK_TERM, 0, 0}, }; /* * I2C Device Table - * * name - Name of the actual device/chip. * driver_data - Driver data */ static const struct i2c_device_id tvp514x_id[] = { {"tvp5146", (unsigned long)tvp5146_init_reg_seq}, {"tvp5146m2", (unsigned long)tvp514xm_init_reg_seq}, {"tvp5147", (unsigned long)tvp5147_init_reg_seq}, {"tvp5147m1", (unsigned long)tvp514xm_init_reg_seq}, {}, }; MODULE_DEVICE_TABLE(i2c, tvp514x_id); #if IS_ENABLED(CONFIG_OF) static const struct of_device_id tvp514x_of_match[] = { { .compatible = "ti,tvp5146", }, { .compatible = "ti,tvp5146m2", }, { .compatible = "ti,tvp5147", }, { .compatible = "ti,tvp5147m1", }, { /* sentinel */ }, }; MODULE_DEVICE_TABLE(of, tvp514x_of_match); #endif static struct i2c_driver tvp514x_driver = { .driver = { .of_match_table = of_match_ptr(tvp514x_of_match), .name = TVP514X_MODULE_NAME, }, .probe = tvp514x_probe, .remove = tvp514x_remove, .id_table = tvp514x_id, }; module_i2c_driver(tvp514x_driver);
linux-master
drivers/media/i2c/tvp514x.c
// SPDX-License-Identifier: GPL-2.0 /* * A V4L2 driver for OmniVision OV5647 cameras. * * Based on Samsung S5K6AAFX SXGA 1/6" 1.3M CMOS Image Sensor driver * Copyright (C) 2011 Sylwester Nawrocki <[email protected]> * * Based on Omnivision OV7670 Camera Driver * Copyright (C) 2006-7 Jonathan Corbet <[email protected]> * * Copyright (C) 2016, Synopsys, Inc. */ #include <linux/clk.h> #include <linux/delay.h> #include <linux/gpio/consumer.h> #include <linux/i2c.h> #include <linux/init.h> #include <linux/io.h> #include <linux/module.h> #include <linux/of_graph.h> #include <linux/pm_runtime.h> #include <linux/slab.h> #include <linux/videodev2.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-device.h> #include <media/v4l2-event.h> #include <media/v4l2-fwnode.h> #include <media/v4l2-image-sizes.h> #include <media/v4l2-mediabus.h> /* * From the datasheet, "20ms after PWDN goes low or 20ms after RESETB goes * high if reset is inserted after PWDN goes high, host can access sensor's * SCCB to initialize sensor." */ #define PWDN_ACTIVE_DELAY_MS 20 #define MIPI_CTRL00_CLOCK_LANE_GATE BIT(5) #define MIPI_CTRL00_LINE_SYNC_ENABLE BIT(4) #define MIPI_CTRL00_BUS_IDLE BIT(2) #define MIPI_CTRL00_CLOCK_LANE_DISABLE BIT(0) #define OV5647_SW_STANDBY 0x0100 #define OV5647_SW_RESET 0x0103 #define OV5647_REG_CHIPID_H 0x300a #define OV5647_REG_CHIPID_L 0x300b #define OV5640_REG_PAD_OUT 0x300d #define OV5647_REG_EXP_HI 0x3500 #define OV5647_REG_EXP_MID 0x3501 #define OV5647_REG_EXP_LO 0x3502 #define OV5647_REG_AEC_AGC 0x3503 #define OV5647_REG_GAIN_HI 0x350a #define OV5647_REG_GAIN_LO 0x350b #define OV5647_REG_VTS_HI 0x380e #define OV5647_REG_VTS_LO 0x380f #define OV5647_REG_FRAME_OFF_NUMBER 0x4202 #define OV5647_REG_MIPI_CTRL00 0x4800 #define OV5647_REG_MIPI_CTRL14 0x4814 #define OV5647_REG_AWB 0x5001 #define OV5647_REG_ISPCTRL3D 0x503d #define REG_TERM 0xfffe #define VAL_TERM 0xfe #define REG_DLY 0xffff /* OV5647 native and active pixel array size */ #define OV5647_NATIVE_WIDTH 2624U #define OV5647_NATIVE_HEIGHT 1956U #define OV5647_PIXEL_ARRAY_LEFT 16U #define OV5647_PIXEL_ARRAY_TOP 16U #define OV5647_PIXEL_ARRAY_WIDTH 2592U #define OV5647_PIXEL_ARRAY_HEIGHT 1944U #define OV5647_VBLANK_MIN 4 #define OV5647_VTS_MAX 32767 #define OV5647_EXPOSURE_MIN 4 #define OV5647_EXPOSURE_STEP 1 #define OV5647_EXPOSURE_DEFAULT 1000 #define OV5647_EXPOSURE_MAX 65535 struct regval_list { u16 addr; u8 data; }; struct ov5647_mode { struct v4l2_mbus_framefmt format; struct v4l2_rect crop; u64 pixel_rate; int hts; int vts; const struct regval_list *reg_list; unsigned int num_regs; }; struct ov5647 { struct v4l2_subdev sd; struct media_pad pad; struct mutex lock; struct clk *xclk; struct gpio_desc *pwdn; bool clock_ncont; struct v4l2_ctrl_handler ctrls; const struct ov5647_mode *mode; struct v4l2_ctrl *pixel_rate; struct v4l2_ctrl *hblank; struct v4l2_ctrl *vblank; struct v4l2_ctrl *exposure; bool streaming; }; static inline struct ov5647 *to_sensor(struct v4l2_subdev *sd) { return container_of(sd, struct ov5647, sd); } static const char * const ov5647_test_pattern_menu[] = { "Disabled", "Color Bars", "Color Squares", "Random Data", }; static const u8 ov5647_test_pattern_val[] = { 0x00, /* Disabled */ 0x80, /* Color Bars */ 0x82, /* Color Squares */ 0x81, /* Random Data */ }; static const struct regval_list sensor_oe_disable_regs[] = { {0x3000, 0x00}, {0x3001, 0x00}, {0x3002, 0x00}, }; static const struct regval_list sensor_oe_enable_regs[] = { {0x3000, 0x0f}, {0x3001, 0xff}, {0x3002, 0xe4}, }; static struct regval_list ov5647_2592x1944_10bpp[] = { {0x0100, 0x00}, {0x0103, 0x01}, {0x3034, 0x1a}, {0x3035, 0x21}, {0x3036, 0x69}, {0x303c, 0x11}, {0x3106, 0xf5}, {0x3821, 0x06}, {0x3820, 0x00}, {0x3827, 0xec}, {0x370c, 0x03}, {0x3612, 0x5b}, {0x3618, 0x04}, {0x5000, 0x06}, {0x5002, 0x41}, {0x5003, 0x08}, {0x5a00, 0x08}, {0x3000, 0x00}, {0x3001, 0x00}, {0x3002, 0x00}, {0x3016, 0x08}, {0x3017, 0xe0}, {0x3018, 0x44}, {0x301c, 0xf8}, {0x301d, 0xf0}, {0x3a18, 0x00}, {0x3a19, 0xf8}, {0x3c01, 0x80}, {0x3b07, 0x0c}, {0x380c, 0x0b}, {0x380d, 0x1c}, {0x3814, 0x11}, {0x3815, 0x11}, {0x3708, 0x64}, {0x3709, 0x12}, {0x3808, 0x0a}, {0x3809, 0x20}, {0x380a, 0x07}, {0x380b, 0x98}, {0x3800, 0x00}, {0x3801, 0x00}, {0x3802, 0x00}, {0x3803, 0x00}, {0x3804, 0x0a}, {0x3805, 0x3f}, {0x3806, 0x07}, {0x3807, 0xa3}, {0x3811, 0x10}, {0x3813, 0x06}, {0x3630, 0x2e}, {0x3632, 0xe2}, {0x3633, 0x23}, {0x3634, 0x44}, {0x3636, 0x06}, {0x3620, 0x64}, {0x3621, 0xe0}, {0x3600, 0x37}, {0x3704, 0xa0}, {0x3703, 0x5a}, {0x3715, 0x78}, {0x3717, 0x01}, {0x3731, 0x02}, {0x370b, 0x60}, {0x3705, 0x1a}, {0x3f05, 0x02}, {0x3f06, 0x10}, {0x3f01, 0x0a}, {0x3a08, 0x01}, {0x3a09, 0x28}, {0x3a0a, 0x00}, {0x3a0b, 0xf6}, {0x3a0d, 0x08}, {0x3a0e, 0x06}, {0x3a0f, 0x58}, {0x3a10, 0x50}, {0x3a1b, 0x58}, {0x3a1e, 0x50}, {0x3a11, 0x60}, {0x3a1f, 0x28}, {0x4001, 0x02}, {0x4004, 0x04}, {0x4000, 0x09}, {0x4837, 0x19}, {0x4800, 0x24}, {0x3503, 0x03}, {0x0100, 0x01}, }; static struct regval_list ov5647_1080p30_10bpp[] = { {0x0100, 0x00}, {0x0103, 0x01}, {0x3034, 0x1a}, {0x3035, 0x21}, {0x3036, 0x62}, {0x303c, 0x11}, {0x3106, 0xf5}, {0x3821, 0x06}, {0x3820, 0x00}, {0x3827, 0xec}, {0x370c, 0x03}, {0x3612, 0x5b}, {0x3618, 0x04}, {0x5000, 0x06}, {0x5002, 0x41}, {0x5003, 0x08}, {0x5a00, 0x08}, {0x3000, 0x00}, {0x3001, 0x00}, {0x3002, 0x00}, {0x3016, 0x08}, {0x3017, 0xe0}, {0x3018, 0x44}, {0x301c, 0xf8}, {0x301d, 0xf0}, {0x3a18, 0x00}, {0x3a19, 0xf8}, {0x3c01, 0x80}, {0x3b07, 0x0c}, {0x380c, 0x09}, {0x380d, 0x70}, {0x3814, 0x11}, {0x3815, 0x11}, {0x3708, 0x64}, {0x3709, 0x12}, {0x3808, 0x07}, {0x3809, 0x80}, {0x380a, 0x04}, {0x380b, 0x38}, {0x3800, 0x01}, {0x3801, 0x5c}, {0x3802, 0x01}, {0x3803, 0xb2}, {0x3804, 0x08}, {0x3805, 0xe3}, {0x3806, 0x05}, {0x3807, 0xf1}, {0x3811, 0x04}, {0x3813, 0x02}, {0x3630, 0x2e}, {0x3632, 0xe2}, {0x3633, 0x23}, {0x3634, 0x44}, {0x3636, 0x06}, {0x3620, 0x64}, {0x3621, 0xe0}, {0x3600, 0x37}, {0x3704, 0xa0}, {0x3703, 0x5a}, {0x3715, 0x78}, {0x3717, 0x01}, {0x3731, 0x02}, {0x370b, 0x60}, {0x3705, 0x1a}, {0x3f05, 0x02}, {0x3f06, 0x10}, {0x3f01, 0x0a}, {0x3a08, 0x01}, {0x3a09, 0x4b}, {0x3a0a, 0x01}, {0x3a0b, 0x13}, {0x3a0d, 0x04}, {0x3a0e, 0x03}, {0x3a0f, 0x58}, {0x3a10, 0x50}, {0x3a1b, 0x58}, {0x3a1e, 0x50}, {0x3a11, 0x60}, {0x3a1f, 0x28}, {0x4001, 0x02}, {0x4004, 0x04}, {0x4000, 0x09}, {0x4837, 0x19}, {0x4800, 0x34}, {0x3503, 0x03}, {0x0100, 0x01}, }; static struct regval_list ov5647_2x2binned_10bpp[] = { {0x0100, 0x00}, {0x0103, 0x01}, {0x3034, 0x1a}, {0x3035, 0x21}, {0x3036, 0x62}, {0x303c, 0x11}, {0x3106, 0xf5}, {0x3827, 0xec}, {0x370c, 0x03}, {0x3612, 0x59}, {0x3618, 0x00}, {0x5000, 0x06}, {0x5002, 0x41}, {0x5003, 0x08}, {0x5a00, 0x08}, {0x3000, 0x00}, {0x3001, 0x00}, {0x3002, 0x00}, {0x3016, 0x08}, {0x3017, 0xe0}, {0x3018, 0x44}, {0x301c, 0xf8}, {0x301d, 0xf0}, {0x3a18, 0x00}, {0x3a19, 0xf8}, {0x3c01, 0x80}, {0x3b07, 0x0c}, {0x3800, 0x00}, {0x3801, 0x00}, {0x3802, 0x00}, {0x3803, 0x00}, {0x3804, 0x0a}, {0x3805, 0x3f}, {0x3806, 0x07}, {0x3807, 0xa3}, {0x3808, 0x05}, {0x3809, 0x10}, {0x380a, 0x03}, {0x380b, 0xcc}, {0x380c, 0x07}, {0x380d, 0x68}, {0x3811, 0x0c}, {0x3813, 0x06}, {0x3814, 0x31}, {0x3815, 0x31}, {0x3630, 0x2e}, {0x3632, 0xe2}, {0x3633, 0x23}, {0x3634, 0x44}, {0x3636, 0x06}, {0x3620, 0x64}, {0x3621, 0xe0}, {0x3600, 0x37}, {0x3704, 0xa0}, {0x3703, 0x5a}, {0x3715, 0x78}, {0x3717, 0x01}, {0x3731, 0x02}, {0x370b, 0x60}, {0x3705, 0x1a}, {0x3f05, 0x02}, {0x3f06, 0x10}, {0x3f01, 0x0a}, {0x3a08, 0x01}, {0x3a09, 0x28}, {0x3a0a, 0x00}, {0x3a0b, 0xf6}, {0x3a0d, 0x08}, {0x3a0e, 0x06}, {0x3a0f, 0x58}, {0x3a10, 0x50}, {0x3a1b, 0x58}, {0x3a1e, 0x50}, {0x3a11, 0x60}, {0x3a1f, 0x28}, {0x4001, 0x02}, {0x4004, 0x04}, {0x4000, 0x09}, {0x4837, 0x16}, {0x4800, 0x24}, {0x3503, 0x03}, {0x3820, 0x41}, {0x3821, 0x07}, {0x350a, 0x00}, {0x350b, 0x10}, {0x3500, 0x00}, {0x3501, 0x1a}, {0x3502, 0xf0}, {0x3212, 0xa0}, {0x0100, 0x01}, }; static struct regval_list ov5647_640x480_10bpp[] = { {0x0100, 0x00}, {0x0103, 0x01}, {0x3035, 0x11}, {0x3036, 0x46}, {0x303c, 0x11}, {0x3821, 0x07}, {0x3820, 0x41}, {0x370c, 0x03}, {0x3612, 0x59}, {0x3618, 0x00}, {0x5000, 0x06}, {0x5003, 0x08}, {0x5a00, 0x08}, {0x3000, 0xff}, {0x3001, 0xff}, {0x3002, 0xff}, {0x301d, 0xf0}, {0x3a18, 0x00}, {0x3a19, 0xf8}, {0x3c01, 0x80}, {0x3b07, 0x0c}, {0x380c, 0x07}, {0x380d, 0x3c}, {0x3814, 0x35}, {0x3815, 0x35}, {0x3708, 0x64}, {0x3709, 0x52}, {0x3808, 0x02}, {0x3809, 0x80}, {0x380a, 0x01}, {0x380b, 0xe0}, {0x3800, 0x00}, {0x3801, 0x10}, {0x3802, 0x00}, {0x3803, 0x00}, {0x3804, 0x0a}, {0x3805, 0x2f}, {0x3806, 0x07}, {0x3807, 0x9f}, {0x3630, 0x2e}, {0x3632, 0xe2}, {0x3633, 0x23}, {0x3634, 0x44}, {0x3620, 0x64}, {0x3621, 0xe0}, {0x3600, 0x37}, {0x3704, 0xa0}, {0x3703, 0x5a}, {0x3715, 0x78}, {0x3717, 0x01}, {0x3731, 0x02}, {0x370b, 0x60}, {0x3705, 0x1a}, {0x3f05, 0x02}, {0x3f06, 0x10}, {0x3f01, 0x0a}, {0x3a08, 0x01}, {0x3a09, 0x2e}, {0x3a0a, 0x00}, {0x3a0b, 0xfb}, {0x3a0d, 0x02}, {0x3a0e, 0x01}, {0x3a0f, 0x58}, {0x3a10, 0x50}, {0x3a1b, 0x58}, {0x3a1e, 0x50}, {0x3a11, 0x60}, {0x3a1f, 0x28}, {0x4001, 0x02}, {0x4004, 0x02}, {0x4000, 0x09}, {0x3000, 0x00}, {0x3001, 0x00}, {0x3002, 0x00}, {0x3017, 0xe0}, {0x301c, 0xfc}, {0x3636, 0x06}, {0x3016, 0x08}, {0x3827, 0xec}, {0x3018, 0x44}, {0x3035, 0x21}, {0x3106, 0xf5}, {0x3034, 0x1a}, {0x301c, 0xf8}, {0x4800, 0x34}, {0x3503, 0x03}, {0x0100, 0x01}, }; static const struct ov5647_mode ov5647_modes[] = { /* 2592x1944 full resolution full FOV 10-bit mode. */ { .format = { .code = MEDIA_BUS_FMT_SBGGR10_1X10, .colorspace = V4L2_COLORSPACE_SRGB, .field = V4L2_FIELD_NONE, .width = 2592, .height = 1944 }, .crop = { .left = OV5647_PIXEL_ARRAY_LEFT, .top = OV5647_PIXEL_ARRAY_TOP, .width = 2592, .height = 1944 }, .pixel_rate = 87500000, .hts = 2844, .vts = 0x7b0, .reg_list = ov5647_2592x1944_10bpp, .num_regs = ARRAY_SIZE(ov5647_2592x1944_10bpp) }, /* 1080p30 10-bit mode. Full resolution centre-cropped down to 1080p. */ { .format = { .code = MEDIA_BUS_FMT_SBGGR10_1X10, .colorspace = V4L2_COLORSPACE_SRGB, .field = V4L2_FIELD_NONE, .width = 1920, .height = 1080 }, .crop = { .left = 348 + OV5647_PIXEL_ARRAY_LEFT, .top = 434 + OV5647_PIXEL_ARRAY_TOP, .width = 1928, .height = 1080, }, .pixel_rate = 81666700, .hts = 2416, .vts = 0x450, .reg_list = ov5647_1080p30_10bpp, .num_regs = ARRAY_SIZE(ov5647_1080p30_10bpp) }, /* 2x2 binned full FOV 10-bit mode. */ { .format = { .code = MEDIA_BUS_FMT_SBGGR10_1X10, .colorspace = V4L2_COLORSPACE_SRGB, .field = V4L2_FIELD_NONE, .width = 1296, .height = 972 }, .crop = { .left = OV5647_PIXEL_ARRAY_LEFT, .top = OV5647_PIXEL_ARRAY_TOP, .width = 2592, .height = 1944, }, .pixel_rate = 81666700, .hts = 1896, .vts = 0x59b, .reg_list = ov5647_2x2binned_10bpp, .num_regs = ARRAY_SIZE(ov5647_2x2binned_10bpp) }, /* 10-bit VGA full FOV 60fps. 2x2 binned and subsampled down to VGA. */ { .format = { .code = MEDIA_BUS_FMT_SBGGR10_1X10, .colorspace = V4L2_COLORSPACE_SRGB, .field = V4L2_FIELD_NONE, .width = 640, .height = 480 }, .crop = { .left = 16 + OV5647_PIXEL_ARRAY_LEFT, .top = OV5647_PIXEL_ARRAY_TOP, .width = 2560, .height = 1920, }, .pixel_rate = 55000000, .hts = 1852, .vts = 0x1f8, .reg_list = ov5647_640x480_10bpp, .num_regs = ARRAY_SIZE(ov5647_640x480_10bpp) }, }; /* Default sensor mode is 2x2 binned 640x480 SBGGR10_1X10. */ #define OV5647_DEFAULT_MODE (&ov5647_modes[3]) #define OV5647_DEFAULT_FORMAT (ov5647_modes[3].format) static int ov5647_write16(struct v4l2_subdev *sd, u16 reg, u16 val) { unsigned char data[4] = { reg >> 8, reg & 0xff, val >> 8, val & 0xff}; struct i2c_client *client = v4l2_get_subdevdata(sd); int ret; ret = i2c_master_send(client, data, 4); if (ret < 0) { dev_dbg(&client->dev, "%s: i2c write error, reg: %x\n", __func__, reg); return ret; } return 0; } static int ov5647_write(struct v4l2_subdev *sd, u16 reg, u8 val) { unsigned char data[3] = { reg >> 8, reg & 0xff, val}; struct i2c_client *client = v4l2_get_subdevdata(sd); int ret; ret = i2c_master_send(client, data, 3); if (ret < 0) { dev_dbg(&client->dev, "%s: i2c write error, reg: %x\n", __func__, reg); return ret; } return 0; } static int ov5647_read(struct v4l2_subdev *sd, u16 reg, u8 *val) { struct i2c_client *client = v4l2_get_subdevdata(sd); u8 buf[2] = { reg >> 8, reg & 0xff }; struct i2c_msg msg[2]; int ret; msg[0].addr = client->addr; msg[0].flags = client->flags; msg[0].buf = buf; msg[0].len = sizeof(buf); msg[1].addr = client->addr; msg[1].flags = client->flags | I2C_M_RD; msg[1].buf = buf; msg[1].len = 1; ret = i2c_transfer(client->adapter, msg, 2); if (ret != 2) { dev_err(&client->dev, "%s: i2c read error, reg: %x = %d\n", __func__, reg, ret); return ret >= 0 ? -EINVAL : ret; } *val = buf[0]; return 0; } static int ov5647_write_array(struct v4l2_subdev *sd, const struct regval_list *regs, int array_size) { int i, ret; for (i = 0; i < array_size; i++) { ret = ov5647_write(sd, regs[i].addr, regs[i].data); if (ret < 0) return ret; } return 0; } static int ov5647_set_virtual_channel(struct v4l2_subdev *sd, int channel) { u8 channel_id; int ret; ret = ov5647_read(sd, OV5647_REG_MIPI_CTRL14, &channel_id); if (ret < 0) return ret; channel_id &= ~(3 << 6); return ov5647_write(sd, OV5647_REG_MIPI_CTRL14, channel_id | (channel << 6)); } static int ov5647_set_mode(struct v4l2_subdev *sd) { struct i2c_client *client = v4l2_get_subdevdata(sd); struct ov5647 *sensor = to_sensor(sd); u8 resetval, rdval; int ret; ret = ov5647_read(sd, OV5647_SW_STANDBY, &rdval); if (ret < 0) return ret; ret = ov5647_write_array(sd, sensor->mode->reg_list, sensor->mode->num_regs); if (ret < 0) { dev_err(&client->dev, "write sensor default regs error\n"); return ret; } ret = ov5647_set_virtual_channel(sd, 0); if (ret < 0) return ret; ret = ov5647_read(sd, OV5647_SW_STANDBY, &resetval); if (ret < 0) return ret; if (!(resetval & 0x01)) { dev_err(&client->dev, "Device was in SW standby"); ret = ov5647_write(sd, OV5647_SW_STANDBY, 0x01); if (ret < 0) return ret; } return 0; } static int ov5647_stream_on(struct v4l2_subdev *sd) { struct i2c_client *client = v4l2_get_subdevdata(sd); struct ov5647 *sensor = to_sensor(sd); u8 val = MIPI_CTRL00_BUS_IDLE; int ret; ret = ov5647_set_mode(sd); if (ret) { dev_err(&client->dev, "Failed to program sensor mode: %d\n", ret); return ret; } /* Apply customized values from user when stream starts. */ ret = __v4l2_ctrl_handler_setup(sd->ctrl_handler); if (ret) return ret; if (sensor->clock_ncont) val |= MIPI_CTRL00_CLOCK_LANE_GATE | MIPI_CTRL00_LINE_SYNC_ENABLE; ret = ov5647_write(sd, OV5647_REG_MIPI_CTRL00, val); if (ret < 0) return ret; ret = ov5647_write(sd, OV5647_REG_FRAME_OFF_NUMBER, 0x00); if (ret < 0) return ret; return ov5647_write(sd, OV5640_REG_PAD_OUT, 0x00); } static int ov5647_stream_off(struct v4l2_subdev *sd) { int ret; ret = ov5647_write(sd, OV5647_REG_MIPI_CTRL00, MIPI_CTRL00_CLOCK_LANE_GATE | MIPI_CTRL00_BUS_IDLE | MIPI_CTRL00_CLOCK_LANE_DISABLE); if (ret < 0) return ret; ret = ov5647_write(sd, OV5647_REG_FRAME_OFF_NUMBER, 0x0f); if (ret < 0) return ret; return ov5647_write(sd, OV5640_REG_PAD_OUT, 0x01); } static int ov5647_power_on(struct device *dev) { struct ov5647 *sensor = dev_get_drvdata(dev); int ret; dev_dbg(dev, "OV5647 power on\n"); if (sensor->pwdn) { gpiod_set_value_cansleep(sensor->pwdn, 0); msleep(PWDN_ACTIVE_DELAY_MS); } ret = clk_prepare_enable(sensor->xclk); if (ret < 0) { dev_err(dev, "clk prepare enable failed\n"); goto error_pwdn; } ret = ov5647_write_array(&sensor->sd, sensor_oe_enable_regs, ARRAY_SIZE(sensor_oe_enable_regs)); if (ret < 0) { dev_err(dev, "write sensor_oe_enable_regs error\n"); goto error_clk_disable; } /* Stream off to coax lanes into LP-11 state. */ ret = ov5647_stream_off(&sensor->sd); if (ret < 0) { dev_err(dev, "camera not available, check power\n"); goto error_clk_disable; } return 0; error_clk_disable: clk_disable_unprepare(sensor->xclk); error_pwdn: gpiod_set_value_cansleep(sensor->pwdn, 1); return ret; } static int ov5647_power_off(struct device *dev) { struct ov5647 *sensor = dev_get_drvdata(dev); u8 rdval; int ret; dev_dbg(dev, "OV5647 power off\n"); ret = ov5647_write_array(&sensor->sd, sensor_oe_disable_regs, ARRAY_SIZE(sensor_oe_disable_regs)); if (ret < 0) dev_dbg(dev, "disable oe failed\n"); /* Enter software standby */ ret = ov5647_read(&sensor->sd, OV5647_SW_STANDBY, &rdval); if (ret < 0) dev_dbg(dev, "software standby failed\n"); rdval &= ~0x01; ret = ov5647_write(&sensor->sd, OV5647_SW_STANDBY, rdval); if (ret < 0) dev_dbg(dev, "software standby failed\n"); clk_disable_unprepare(sensor->xclk); gpiod_set_value_cansleep(sensor->pwdn, 1); return 0; } #ifdef CONFIG_VIDEO_ADV_DEBUG static int ov5647_sensor_get_register(struct v4l2_subdev *sd, struct v4l2_dbg_register *reg) { int ret; u8 val; ret = ov5647_read(sd, reg->reg & 0xff, &val); if (ret < 0) return ret; reg->val = val; reg->size = 1; return 0; } static int ov5647_sensor_set_register(struct v4l2_subdev *sd, const struct v4l2_dbg_register *reg) { return ov5647_write(sd, reg->reg & 0xff, reg->val & 0xff); } #endif /* Subdev core operations registration */ static const struct v4l2_subdev_core_ops ov5647_subdev_core_ops = { .subscribe_event = v4l2_ctrl_subdev_subscribe_event, .unsubscribe_event = v4l2_event_subdev_unsubscribe, #ifdef CONFIG_VIDEO_ADV_DEBUG .g_register = ov5647_sensor_get_register, .s_register = ov5647_sensor_set_register, #endif }; static const struct v4l2_rect * __ov5647_get_pad_crop(struct ov5647 *ov5647, struct v4l2_subdev_state *sd_state, unsigned int pad, enum v4l2_subdev_format_whence which) { switch (which) { case V4L2_SUBDEV_FORMAT_TRY: return v4l2_subdev_get_try_crop(&ov5647->sd, sd_state, pad); case V4L2_SUBDEV_FORMAT_ACTIVE: return &ov5647->mode->crop; } return NULL; } static int ov5647_s_stream(struct v4l2_subdev *sd, int enable) { struct i2c_client *client = v4l2_get_subdevdata(sd); struct ov5647 *sensor = to_sensor(sd); int ret; mutex_lock(&sensor->lock); if (sensor->streaming == enable) { mutex_unlock(&sensor->lock); return 0; } if (enable) { ret = pm_runtime_resume_and_get(&client->dev); if (ret < 0) goto error_unlock; ret = ov5647_stream_on(sd); if (ret < 0) { dev_err(&client->dev, "stream start failed: %d\n", ret); goto error_pm; } } else { ret = ov5647_stream_off(sd); if (ret < 0) { dev_err(&client->dev, "stream stop failed: %d\n", ret); goto error_pm; } pm_runtime_put(&client->dev); } sensor->streaming = enable; mutex_unlock(&sensor->lock); return 0; error_pm: pm_runtime_put(&client->dev); error_unlock: mutex_unlock(&sensor->lock); return ret; } static const struct v4l2_subdev_video_ops ov5647_subdev_video_ops = { .s_stream = ov5647_s_stream, }; static int ov5647_enum_mbus_code(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_mbus_code_enum *code) { if (code->index > 0) return -EINVAL; code->code = MEDIA_BUS_FMT_SBGGR10_1X10; return 0; } static int ov5647_enum_frame_size(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_frame_size_enum *fse) { const struct v4l2_mbus_framefmt *fmt; if (fse->code != MEDIA_BUS_FMT_SBGGR10_1X10 || fse->index >= ARRAY_SIZE(ov5647_modes)) return -EINVAL; fmt = &ov5647_modes[fse->index].format; fse->min_width = fmt->width; fse->max_width = fmt->width; fse->min_height = fmt->height; fse->max_height = fmt->height; return 0; } static int ov5647_get_pad_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *format) { struct v4l2_mbus_framefmt *fmt = &format->format; const struct v4l2_mbus_framefmt *sensor_format; struct ov5647 *sensor = to_sensor(sd); mutex_lock(&sensor->lock); switch (format->which) { case V4L2_SUBDEV_FORMAT_TRY: sensor_format = v4l2_subdev_get_try_format(sd, sd_state, format->pad); break; default: sensor_format = &sensor->mode->format; break; } *fmt = *sensor_format; mutex_unlock(&sensor->lock); return 0; } static int ov5647_set_pad_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *format) { struct v4l2_mbus_framefmt *fmt = &format->format; struct ov5647 *sensor = to_sensor(sd); const struct ov5647_mode *mode; mode = v4l2_find_nearest_size(ov5647_modes, ARRAY_SIZE(ov5647_modes), format.width, format.height, fmt->width, fmt->height); /* Update the sensor mode and apply at it at streamon time. */ mutex_lock(&sensor->lock); if (format->which == V4L2_SUBDEV_FORMAT_TRY) { *v4l2_subdev_get_try_format(sd, sd_state, format->pad) = mode->format; } else { int exposure_max, exposure_def; int hblank, vblank; sensor->mode = mode; __v4l2_ctrl_modify_range(sensor->pixel_rate, mode->pixel_rate, mode->pixel_rate, 1, mode->pixel_rate); hblank = mode->hts - mode->format.width; __v4l2_ctrl_modify_range(sensor->hblank, hblank, hblank, 1, hblank); vblank = mode->vts - mode->format.height; __v4l2_ctrl_modify_range(sensor->vblank, OV5647_VBLANK_MIN, OV5647_VTS_MAX - mode->format.height, 1, vblank); __v4l2_ctrl_s_ctrl(sensor->vblank, vblank); exposure_max = mode->vts - 4; exposure_def = min(exposure_max, OV5647_EXPOSURE_DEFAULT); __v4l2_ctrl_modify_range(sensor->exposure, sensor->exposure->minimum, exposure_max, sensor->exposure->step, exposure_def); } *fmt = mode->format; mutex_unlock(&sensor->lock); return 0; } static int ov5647_get_selection(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_selection *sel) { switch (sel->target) { case V4L2_SEL_TGT_CROP: { struct ov5647 *sensor = to_sensor(sd); mutex_lock(&sensor->lock); sel->r = *__ov5647_get_pad_crop(sensor, sd_state, sel->pad, sel->which); mutex_unlock(&sensor->lock); return 0; } case V4L2_SEL_TGT_NATIVE_SIZE: sel->r.top = 0; sel->r.left = 0; sel->r.width = OV5647_NATIVE_WIDTH; sel->r.height = OV5647_NATIVE_HEIGHT; return 0; case V4L2_SEL_TGT_CROP_DEFAULT: case V4L2_SEL_TGT_CROP_BOUNDS: sel->r.top = OV5647_PIXEL_ARRAY_TOP; sel->r.left = OV5647_PIXEL_ARRAY_LEFT; sel->r.width = OV5647_PIXEL_ARRAY_WIDTH; sel->r.height = OV5647_PIXEL_ARRAY_HEIGHT; return 0; } return -EINVAL; } static const struct v4l2_subdev_pad_ops ov5647_subdev_pad_ops = { .enum_mbus_code = ov5647_enum_mbus_code, .enum_frame_size = ov5647_enum_frame_size, .set_fmt = ov5647_set_pad_fmt, .get_fmt = ov5647_get_pad_fmt, .get_selection = ov5647_get_selection, }; static const struct v4l2_subdev_ops ov5647_subdev_ops = { .core = &ov5647_subdev_core_ops, .video = &ov5647_subdev_video_ops, .pad = &ov5647_subdev_pad_ops, }; static int ov5647_detect(struct v4l2_subdev *sd) { struct i2c_client *client = v4l2_get_subdevdata(sd); u8 read; int ret; ret = ov5647_write(sd, OV5647_SW_RESET, 0x01); if (ret < 0) return ret; ret = ov5647_read(sd, OV5647_REG_CHIPID_H, &read); if (ret < 0) return ret; if (read != 0x56) { dev_err(&client->dev, "ID High expected 0x56 got %x", read); return -ENODEV; } ret = ov5647_read(sd, OV5647_REG_CHIPID_L, &read); if (ret < 0) return ret; if (read != 0x47) { dev_err(&client->dev, "ID Low expected 0x47 got %x", read); return -ENODEV; } return ov5647_write(sd, OV5647_SW_RESET, 0x00); } static int ov5647_open(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh) { struct v4l2_mbus_framefmt *format = v4l2_subdev_get_try_format(sd, fh->state, 0); struct v4l2_rect *crop = v4l2_subdev_get_try_crop(sd, fh->state, 0); crop->left = OV5647_PIXEL_ARRAY_LEFT; crop->top = OV5647_PIXEL_ARRAY_TOP; crop->width = OV5647_PIXEL_ARRAY_WIDTH; crop->height = OV5647_PIXEL_ARRAY_HEIGHT; *format = OV5647_DEFAULT_FORMAT; return 0; } static const struct v4l2_subdev_internal_ops ov5647_subdev_internal_ops = { .open = ov5647_open, }; static int ov5647_s_auto_white_balance(struct v4l2_subdev *sd, u32 val) { return ov5647_write(sd, OV5647_REG_AWB, val ? 1 : 0); } static int ov5647_s_autogain(struct v4l2_subdev *sd, u32 val) { int ret; u8 reg; /* Non-zero turns on AGC by clearing bit 1.*/ ret = ov5647_read(sd, OV5647_REG_AEC_AGC, &reg); if (ret) return ret; return ov5647_write(sd, OV5647_REG_AEC_AGC, val ? reg & ~BIT(1) : reg | BIT(1)); } static int ov5647_s_exposure_auto(struct v4l2_subdev *sd, u32 val) { int ret; u8 reg; /* * Everything except V4L2_EXPOSURE_MANUAL turns on AEC by * clearing bit 0. */ ret = ov5647_read(sd, OV5647_REG_AEC_AGC, &reg); if (ret) return ret; return ov5647_write(sd, OV5647_REG_AEC_AGC, val == V4L2_EXPOSURE_MANUAL ? reg | BIT(0) : reg & ~BIT(0)); } static int ov5647_s_analogue_gain(struct v4l2_subdev *sd, u32 val) { int ret; /* 10 bits of gain, 2 in the high register. */ ret = ov5647_write(sd, OV5647_REG_GAIN_HI, (val >> 8) & 3); if (ret) return ret; return ov5647_write(sd, OV5647_REG_GAIN_LO, val & 0xff); } static int ov5647_s_exposure(struct v4l2_subdev *sd, u32 val) { int ret; /* * Sensor has 20 bits, but the bottom 4 bits are fractions of a line * which we leave as zero (and don't receive in "val"). */ ret = ov5647_write(sd, OV5647_REG_EXP_HI, (val >> 12) & 0xf); if (ret) return ret; ret = ov5647_write(sd, OV5647_REG_EXP_MID, (val >> 4) & 0xff); if (ret) return ret; return ov5647_write(sd, OV5647_REG_EXP_LO, (val & 0xf) << 4); } static int ov5647_s_ctrl(struct v4l2_ctrl *ctrl) { struct ov5647 *sensor = container_of(ctrl->handler, struct ov5647, ctrls); struct v4l2_subdev *sd = &sensor->sd; struct i2c_client *client = v4l2_get_subdevdata(sd); int ret = 0; /* v4l2_ctrl_lock() locks our own mutex */ if (ctrl->id == V4L2_CID_VBLANK) { int exposure_max, exposure_def; /* Update max exposure while meeting expected vblanking */ exposure_max = sensor->mode->format.height + ctrl->val - 4; exposure_def = min(exposure_max, OV5647_EXPOSURE_DEFAULT); __v4l2_ctrl_modify_range(sensor->exposure, sensor->exposure->minimum, exposure_max, sensor->exposure->step, exposure_def); } /* * If the device is not powered up do not apply any controls * to H/W at this time. Instead the controls will be restored * at s_stream(1) time. */ if (pm_runtime_get_if_in_use(&client->dev) == 0) return 0; switch (ctrl->id) { case V4L2_CID_AUTO_WHITE_BALANCE: ret = ov5647_s_auto_white_balance(sd, ctrl->val); break; case V4L2_CID_AUTOGAIN: ret = ov5647_s_autogain(sd, ctrl->val); break; case V4L2_CID_EXPOSURE_AUTO: ret = ov5647_s_exposure_auto(sd, ctrl->val); break; case V4L2_CID_ANALOGUE_GAIN: ret = ov5647_s_analogue_gain(sd, ctrl->val); break; case V4L2_CID_EXPOSURE: ret = ov5647_s_exposure(sd, ctrl->val); break; case V4L2_CID_VBLANK: ret = ov5647_write16(sd, OV5647_REG_VTS_HI, sensor->mode->format.height + ctrl->val); break; case V4L2_CID_TEST_PATTERN: ret = ov5647_write(sd, OV5647_REG_ISPCTRL3D, ov5647_test_pattern_val[ctrl->val]); break; /* Read-only, but we adjust it based on mode. */ case V4L2_CID_PIXEL_RATE: case V4L2_CID_HBLANK: /* Read-only, but we adjust it based on mode. */ break; default: dev_info(&client->dev, "Control (id:0x%x, val:0x%x) not supported\n", ctrl->id, ctrl->val); return -EINVAL; } pm_runtime_put(&client->dev); return ret; } static const struct v4l2_ctrl_ops ov5647_ctrl_ops = { .s_ctrl = ov5647_s_ctrl, }; static int ov5647_init_controls(struct ov5647 *sensor) { struct i2c_client *client = v4l2_get_subdevdata(&sensor->sd); int hblank, exposure_max, exposure_def; v4l2_ctrl_handler_init(&sensor->ctrls, 9); v4l2_ctrl_new_std(&sensor->ctrls, &ov5647_ctrl_ops, V4L2_CID_AUTOGAIN, 0, 1, 1, 0); v4l2_ctrl_new_std(&sensor->ctrls, &ov5647_ctrl_ops, V4L2_CID_AUTO_WHITE_BALANCE, 0, 1, 1, 0); v4l2_ctrl_new_std_menu(&sensor->ctrls, &ov5647_ctrl_ops, V4L2_CID_EXPOSURE_AUTO, V4L2_EXPOSURE_MANUAL, 0, V4L2_EXPOSURE_MANUAL); exposure_max = sensor->mode->vts - 4; exposure_def = min(exposure_max, OV5647_EXPOSURE_DEFAULT); sensor->exposure = v4l2_ctrl_new_std(&sensor->ctrls, &ov5647_ctrl_ops, V4L2_CID_EXPOSURE, OV5647_EXPOSURE_MIN, exposure_max, OV5647_EXPOSURE_STEP, exposure_def); /* min: 16 = 1.0x; max (10 bits); default: 32 = 2.0x. */ v4l2_ctrl_new_std(&sensor->ctrls, &ov5647_ctrl_ops, V4L2_CID_ANALOGUE_GAIN, 16, 1023, 1, 32); /* By default, PIXEL_RATE is read only, but it does change per mode */ sensor->pixel_rate = v4l2_ctrl_new_std(&sensor->ctrls, &ov5647_ctrl_ops, V4L2_CID_PIXEL_RATE, sensor->mode->pixel_rate, sensor->mode->pixel_rate, 1, sensor->mode->pixel_rate); /* By default, HBLANK is read only, but it does change per mode. */ hblank = sensor->mode->hts - sensor->mode->format.width; sensor->hblank = v4l2_ctrl_new_std(&sensor->ctrls, &ov5647_ctrl_ops, V4L2_CID_HBLANK, hblank, hblank, 1, hblank); sensor->vblank = v4l2_ctrl_new_std(&sensor->ctrls, &ov5647_ctrl_ops, V4L2_CID_VBLANK, OV5647_VBLANK_MIN, OV5647_VTS_MAX - sensor->mode->format.height, 1, sensor->mode->vts - sensor->mode->format.height); v4l2_ctrl_new_std_menu_items(&sensor->ctrls, &ov5647_ctrl_ops, V4L2_CID_TEST_PATTERN, ARRAY_SIZE(ov5647_test_pattern_menu) - 1, 0, 0, ov5647_test_pattern_menu); if (sensor->ctrls.error) goto handler_free; sensor->pixel_rate->flags |= V4L2_CTRL_FLAG_READ_ONLY; sensor->hblank->flags |= V4L2_CTRL_FLAG_READ_ONLY; sensor->sd.ctrl_handler = &sensor->ctrls; return 0; handler_free: dev_err(&client->dev, "%s Controls initialization failed (%d)\n", __func__, sensor->ctrls.error); v4l2_ctrl_handler_free(&sensor->ctrls); return sensor->ctrls.error; } static int ov5647_parse_dt(struct ov5647 *sensor, struct device_node *np) { struct v4l2_fwnode_endpoint bus_cfg = { .bus_type = V4L2_MBUS_CSI2_DPHY, }; struct device_node *ep; int ret; ep = of_graph_get_next_endpoint(np, NULL); if (!ep) return -EINVAL; ret = v4l2_fwnode_endpoint_parse(of_fwnode_handle(ep), &bus_cfg); if (ret) goto out; sensor->clock_ncont = bus_cfg.bus.mipi_csi2.flags & V4L2_MBUS_CSI2_NONCONTINUOUS_CLOCK; out: of_node_put(ep); return ret; } static int ov5647_probe(struct i2c_client *client) { struct device_node *np = client->dev.of_node; struct device *dev = &client->dev; struct ov5647 *sensor; struct v4l2_subdev *sd; u32 xclk_freq; int ret; sensor = devm_kzalloc(dev, sizeof(*sensor), GFP_KERNEL); if (!sensor) return -ENOMEM; if (IS_ENABLED(CONFIG_OF) && np) { ret = ov5647_parse_dt(sensor, np); if (ret) { dev_err(dev, "DT parsing error: %d\n", ret); return ret; } } sensor->xclk = devm_clk_get(dev, NULL); if (IS_ERR(sensor->xclk)) { dev_err(dev, "could not get xclk"); return PTR_ERR(sensor->xclk); } xclk_freq = clk_get_rate(sensor->xclk); if (xclk_freq != 25000000) { dev_err(dev, "Unsupported clock frequency: %u\n", xclk_freq); return -EINVAL; } /* Request the power down GPIO asserted. */ sensor->pwdn = devm_gpiod_get_optional(dev, "pwdn", GPIOD_OUT_HIGH); if (IS_ERR(sensor->pwdn)) { dev_err(dev, "Failed to get 'pwdn' gpio\n"); return -EINVAL; } mutex_init(&sensor->lock); sensor->mode = OV5647_DEFAULT_MODE; ret = ov5647_init_controls(sensor); if (ret) goto mutex_destroy; sd = &sensor->sd; v4l2_i2c_subdev_init(sd, client, &ov5647_subdev_ops); sd->internal_ops = &ov5647_subdev_internal_ops; sd->flags |= V4L2_SUBDEV_FL_HAS_DEVNODE | V4L2_SUBDEV_FL_HAS_EVENTS; sensor->pad.flags = MEDIA_PAD_FL_SOURCE; sd->entity.function = MEDIA_ENT_F_CAM_SENSOR; ret = media_entity_pads_init(&sd->entity, 1, &sensor->pad); if (ret < 0) goto ctrl_handler_free; ret = ov5647_power_on(dev); if (ret) goto entity_cleanup; ret = ov5647_detect(sd); if (ret < 0) goto power_off; ret = v4l2_async_register_subdev(sd); if (ret < 0) goto power_off; /* Enable runtime PM and turn off the device */ pm_runtime_set_active(dev); pm_runtime_enable(dev); pm_runtime_idle(dev); dev_dbg(dev, "OmniVision OV5647 camera driver probed\n"); return 0; power_off: ov5647_power_off(dev); entity_cleanup: media_entity_cleanup(&sd->entity); ctrl_handler_free: v4l2_ctrl_handler_free(&sensor->ctrls); mutex_destroy: mutex_destroy(&sensor->lock); return ret; } static void ov5647_remove(struct i2c_client *client) { struct v4l2_subdev *sd = i2c_get_clientdata(client); struct ov5647 *sensor = to_sensor(sd); v4l2_async_unregister_subdev(&sensor->sd); media_entity_cleanup(&sensor->sd.entity); v4l2_ctrl_handler_free(&sensor->ctrls); v4l2_device_unregister_subdev(sd); pm_runtime_disable(&client->dev); mutex_destroy(&sensor->lock); } static const struct dev_pm_ops ov5647_pm_ops = { SET_RUNTIME_PM_OPS(ov5647_power_off, ov5647_power_on, NULL) }; static const struct i2c_device_id ov5647_id[] = { { "ov5647", 0 }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(i2c, ov5647_id); #if IS_ENABLED(CONFIG_OF) static const struct of_device_id ov5647_of_match[] = { { .compatible = "ovti,ov5647" }, { /* sentinel */ }, }; MODULE_DEVICE_TABLE(of, ov5647_of_match); #endif static struct i2c_driver ov5647_driver = { .driver = { .of_match_table = of_match_ptr(ov5647_of_match), .name = "ov5647", .pm = &ov5647_pm_ops, }, .probe = ov5647_probe, .remove = ov5647_remove, .id_table = ov5647_id, }; module_i2c_driver(ov5647_driver); MODULE_AUTHOR("Ramiro Oliveira <[email protected]>"); MODULE_DESCRIPTION("A low-level driver for OmniVision ov5647 sensors"); MODULE_LICENSE("GPL v2");
linux-master
drivers/media/i2c/ov5647.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Programming the mspx4xx sound processor family * * (c) 1997-2001 Gerd Knorr <[email protected]> */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/i2c.h> #include <linux/freezer.h> #include <linux/videodev2.h> #include <media/v4l2-common.h> #include <media/drv-intf/msp3400.h> #include <linux/kthread.h> #include <linux/suspend.h> #include "msp3400-driver.h" /* this one uses the automatic sound standard detection of newer msp34xx chip versions */ static struct { int retval; int main, second; char *name; v4l2_std_id std; } msp_stdlist[] = { { 0x0000, 0, 0, "could not detect sound standard", V4L2_STD_ALL }, { 0x0001, 0, 0, "autodetect start", V4L2_STD_ALL }, { 0x0002, MSP_CARRIER(4.5), MSP_CARRIER(4.72), "4.5/4.72 M Dual FM-Stereo", V4L2_STD_MN }, { 0x0003, MSP_CARRIER(5.5), MSP_CARRIER(5.7421875), "5.5/5.74 B/G Dual FM-Stereo", V4L2_STD_BG }, { 0x0004, MSP_CARRIER(6.5), MSP_CARRIER(6.2578125), "6.5/6.25 D/K1 Dual FM-Stereo", V4L2_STD_DK }, { 0x0005, MSP_CARRIER(6.5), MSP_CARRIER(6.7421875), "6.5/6.74 D/K2 Dual FM-Stereo", V4L2_STD_DK }, { 0x0006, MSP_CARRIER(6.5), MSP_CARRIER(6.5), "6.5 D/K FM-Mono (HDEV3)", V4L2_STD_DK }, { 0x0007, MSP_CARRIER(6.5), MSP_CARRIER(5.7421875), "6.5/5.74 D/K3 Dual FM-Stereo", V4L2_STD_DK }, { 0x0008, MSP_CARRIER(5.5), MSP_CARRIER(5.85), "5.5/5.85 B/G NICAM FM", V4L2_STD_BG }, { 0x0009, MSP_CARRIER(6.5), MSP_CARRIER(5.85), "6.5/5.85 L NICAM AM", V4L2_STD_L }, { 0x000a, MSP_CARRIER(6.0), MSP_CARRIER(6.55), "6.0/6.55 I NICAM FM", V4L2_STD_PAL_I }, { 0x000b, MSP_CARRIER(6.5), MSP_CARRIER(5.85), "6.5/5.85 D/K NICAM FM", V4L2_STD_DK }, { 0x000c, MSP_CARRIER(6.5), MSP_CARRIER(5.85), "6.5/5.85 D/K NICAM FM (HDEV2)", V4L2_STD_DK }, { 0x000d, MSP_CARRIER(6.5), MSP_CARRIER(5.85), "6.5/5.85 D/K NICAM FM (HDEV3)", V4L2_STD_DK }, { 0x0020, MSP_CARRIER(4.5), MSP_CARRIER(4.5), "4.5 M BTSC-Stereo", V4L2_STD_MTS }, { 0x0021, MSP_CARRIER(4.5), MSP_CARRIER(4.5), "4.5 M BTSC-Mono + SAP", V4L2_STD_MTS }, { 0x0030, MSP_CARRIER(4.5), MSP_CARRIER(4.5), "4.5 M EIA-J Japan Stereo", V4L2_STD_NTSC_M_JP }, { 0x0040, MSP_CARRIER(10.7), MSP_CARRIER(10.7), "10.7 FM-Stereo Radio", V4L2_STD_ALL }, { 0x0050, MSP_CARRIER(6.5), MSP_CARRIER(6.5), "6.5 SAT-Mono", V4L2_STD_ALL }, { 0x0051, MSP_CARRIER(7.02), MSP_CARRIER(7.20), "7.02/7.20 SAT-Stereo", V4L2_STD_ALL }, { 0x0060, MSP_CARRIER(7.2), MSP_CARRIER(7.2), "7.2 SAT ADR", V4L2_STD_ALL }, { -1, 0, 0, NULL, 0 }, /* EOF */ }; static struct msp3400c_init_data_dem { int fir1[6]; int fir2[6]; int cdo1; int cdo2; int ad_cv; int mode_reg; int dsp_src; int dsp_matrix; } msp3400c_init_data[] = { { /* AM (for carrier detect / msp3400) */ {75, 19, 36, 35, 39, 40}, {75, 19, 36, 35, 39, 40}, MSP_CARRIER(5.5), MSP_CARRIER(5.5), 0x00d0, 0x0500, 0x0020, 0x3000 }, { /* AM (for carrier detect / msp3410) */ {-1, -1, -8, 2, 59, 126}, {-1, -1, -8, 2, 59, 126}, MSP_CARRIER(5.5), MSP_CARRIER(5.5), 0x00d0, 0x0100, 0x0020, 0x3000 }, { /* FM Radio */ {-8, -8, 4, 6, 78, 107}, {-8, -8, 4, 6, 78, 107}, MSP_CARRIER(10.7), MSP_CARRIER(10.7), 0x00d0, 0x0480, 0x0020, 0x3000 }, { /* Terrestrial FM-mono + FM-stereo */ {3, 18, 27, 48, 66, 72}, {3, 18, 27, 48, 66, 72}, MSP_CARRIER(5.5), MSP_CARRIER(5.5), 0x00d0, 0x0480, 0x0030, 0x3000 }, { /* Sat FM-mono */ { 1, 9, 14, 24, 33, 37}, { 3, 18, 27, 48, 66, 72}, MSP_CARRIER(6.5), MSP_CARRIER(6.5), 0x00c6, 0x0480, 0x0000, 0x3000 }, { /* NICAM/FM -- B/G (5.5/5.85), D/K (6.5/5.85) */ {-2, -8, -10, 10, 50, 86}, {3, 18, 27, 48, 66, 72}, MSP_CARRIER(5.5), MSP_CARRIER(5.5), 0x00d0, 0x0040, 0x0120, 0x3000 }, { /* NICAM/FM -- I (6.0/6.552) */ {2, 4, -6, -4, 40, 94}, {3, 18, 27, 48, 66, 72}, MSP_CARRIER(6.0), MSP_CARRIER(6.0), 0x00d0, 0x0040, 0x0120, 0x3000 }, { /* NICAM/AM -- L (6.5/5.85) */ {-2, -8, -10, 10, 50, 86}, {-4, -12, -9, 23, 79, 126}, MSP_CARRIER(6.5), MSP_CARRIER(6.5), 0x00c6, 0x0140, 0x0120, 0x7c00 }, }; struct msp3400c_carrier_detect { int cdo; char *name; }; static struct msp3400c_carrier_detect msp3400c_carrier_detect_main[] = { /* main carrier */ { MSP_CARRIER(4.5), "4.5 NTSC" }, { MSP_CARRIER(5.5), "5.5 PAL B/G" }, { MSP_CARRIER(6.0), "6.0 PAL I" }, { MSP_CARRIER(6.5), "6.5 PAL D/K + SAT + SECAM" } }; static struct msp3400c_carrier_detect msp3400c_carrier_detect_55[] = { /* PAL B/G */ { MSP_CARRIER(5.7421875), "5.742 PAL B/G FM-stereo" }, { MSP_CARRIER(5.85), "5.85 PAL B/G NICAM" } }; static struct msp3400c_carrier_detect msp3400c_carrier_detect_65[] = { /* PAL SAT / SECAM */ { MSP_CARRIER(5.85), "5.85 PAL D/K + SECAM NICAM" }, { MSP_CARRIER(6.2578125), "6.25 PAL D/K1 FM-stereo" }, { MSP_CARRIER(6.7421875), "6.74 PAL D/K2 FM-stereo" }, { MSP_CARRIER(7.02), "7.02 PAL SAT FM-stereo s/b" }, { MSP_CARRIER(7.20), "7.20 PAL SAT FM-stereo s" }, { MSP_CARRIER(7.38), "7.38 PAL SAT FM-stereo b" }, }; /* ------------------------------------------------------------------------ */ const char *msp_standard_std_name(int std) { int i; for (i = 0; msp_stdlist[i].name != NULL; i++) if (msp_stdlist[i].retval == std) return msp_stdlist[i].name; return "unknown"; } static v4l2_std_id msp_standard_std(int std) { int i; for (i = 0; msp_stdlist[i].name != NULL; i++) if (msp_stdlist[i].retval == std) return msp_stdlist[i].std; return V4L2_STD_ALL; } static void msp_set_source(struct i2c_client *client, u16 src) { struct msp_state *state = to_state(i2c_get_clientdata(client)); if (msp_dolby) { msp_write_dsp(client, 0x0008, 0x0520); /* I2S1 */ msp_write_dsp(client, 0x0009, 0x0620); /* I2S2 */ } else { msp_write_dsp(client, 0x0008, src); msp_write_dsp(client, 0x0009, src); } msp_write_dsp(client, 0x000a, src); msp_write_dsp(client, 0x000b, src); msp_write_dsp(client, 0x000c, src); if (state->has_scart2_out) msp_write_dsp(client, 0x0041, src); } void msp3400c_set_carrier(struct i2c_client *client, int cdo1, int cdo2) { msp_write_dem(client, 0x0093, cdo1 & 0xfff); msp_write_dem(client, 0x009b, cdo1 >> 12); msp_write_dem(client, 0x00a3, cdo2 & 0xfff); msp_write_dem(client, 0x00ab, cdo2 >> 12); msp_write_dem(client, 0x0056, 0); /* LOAD_REG_1/2 */ } void msp3400c_set_mode(struct i2c_client *client, int mode) { struct msp_state *state = to_state(i2c_get_clientdata(client)); struct msp3400c_init_data_dem *data = &msp3400c_init_data[mode]; int tuner = (state->route_in >> 3) & 1; int i; dev_dbg_lvl(&client->dev, 1, msp_debug, "set_mode: %d\n", mode); state->mode = mode; state->rxsubchans = V4L2_TUNER_SUB_MONO; msp_write_dem(client, 0x00bb, data->ad_cv | (tuner ? 0x100 : 0)); for (i = 5; i >= 0; i--) /* fir 1 */ msp_write_dem(client, 0x0001, data->fir1[i]); msp_write_dem(client, 0x0005, 0x0004); /* fir 2 */ msp_write_dem(client, 0x0005, 0x0040); msp_write_dem(client, 0x0005, 0x0000); for (i = 5; i >= 0; i--) msp_write_dem(client, 0x0005, data->fir2[i]); msp_write_dem(client, 0x0083, data->mode_reg); msp3400c_set_carrier(client, data->cdo1, data->cdo2); msp_set_source(client, data->dsp_src); /* set prescales */ /* volume prescale for SCART (AM mono input) */ msp_write_dsp(client, 0x000d, 0x1900); msp_write_dsp(client, 0x000e, data->dsp_matrix); if (state->has_nicam) /* nicam prescale */ msp_write_dsp(client, 0x0010, 0x5a00); } /* Set audio mode. Note that the pre-'G' models do not support BTSC+SAP, nor do they support stereo BTSC. */ static void msp3400c_set_audmode(struct i2c_client *client) { static char *strmode[] = { "mono", "stereo", "lang2", "lang1", "lang1+lang2" }; struct msp_state *state = to_state(i2c_get_clientdata(client)); char *modestr = (state->audmode >= 0 && state->audmode < 5) ? strmode[state->audmode] : "unknown"; int src = 0; /* channel source: FM/AM, nicam or SCART */ int audmode = state->audmode; if (state->opmode == OPMODE_AUTOSELECT) { /* this method would break everything, let's make sure * it's never called */ dev_dbg_lvl(&client->dev, 1, msp_debug, "set_audmode called with mode=%d instead of set_source (ignored)\n", state->audmode); return; } /* Note: for the C and D revs no NTSC stereo + SAP is possible as the hardware does not support SAP. So the rxsubchans combination of STEREO | LANG2 does not occur. */ if (state->mode != MSP_MODE_EXTERN) { /* switch to mono if only mono is available */ if (state->rxsubchans == V4L2_TUNER_SUB_MONO) audmode = V4L2_TUNER_MODE_MONO; /* if bilingual */ else if (state->rxsubchans & V4L2_TUNER_SUB_LANG2) { /* and mono or stereo, then fallback to lang1 */ if (audmode == V4L2_TUNER_MODE_MONO || audmode == V4L2_TUNER_MODE_STEREO) audmode = V4L2_TUNER_MODE_LANG1; } /* if stereo, and audmode is not mono, then switch to stereo */ else if (audmode != V4L2_TUNER_MODE_MONO) audmode = V4L2_TUNER_MODE_STEREO; } /* switch demodulator */ switch (state->mode) { case MSP_MODE_FM_TERRA: dev_dbg_lvl(&client->dev, 1, msp_debug, "FM set_audmode: %s\n", modestr); switch (audmode) { case V4L2_TUNER_MODE_STEREO: msp_write_dsp(client, 0x000e, 0x3001); break; case V4L2_TUNER_MODE_MONO: case V4L2_TUNER_MODE_LANG1: case V4L2_TUNER_MODE_LANG2: case V4L2_TUNER_MODE_LANG1_LANG2: msp_write_dsp(client, 0x000e, 0x3000); break; } break; case MSP_MODE_FM_SAT: dev_dbg_lvl(&client->dev, 1, msp_debug, "SAT set_audmode: %s\n", modestr); switch (audmode) { case V4L2_TUNER_MODE_MONO: msp3400c_set_carrier(client, MSP_CARRIER(6.5), MSP_CARRIER(6.5)); break; case V4L2_TUNER_MODE_STEREO: case V4L2_TUNER_MODE_LANG1_LANG2: msp3400c_set_carrier(client, MSP_CARRIER(7.2), MSP_CARRIER(7.02)); break; case V4L2_TUNER_MODE_LANG1: msp3400c_set_carrier(client, MSP_CARRIER(7.38), MSP_CARRIER(7.02)); break; case V4L2_TUNER_MODE_LANG2: msp3400c_set_carrier(client, MSP_CARRIER(7.38), MSP_CARRIER(7.02)); break; } break; case MSP_MODE_FM_NICAM1: case MSP_MODE_FM_NICAM2: case MSP_MODE_AM_NICAM: dev_dbg_lvl(&client->dev, 1, msp_debug, "NICAM set_audmode: %s\n", modestr); if (state->nicam_on) src = 0x0100; /* NICAM */ break; case MSP_MODE_BTSC: dev_dbg_lvl(&client->dev, 1, msp_debug, "BTSC set_audmode: %s\n", modestr); break; case MSP_MODE_EXTERN: dev_dbg_lvl(&client->dev, 1, msp_debug, "extern set_audmode: %s\n", modestr); src = 0x0200; /* SCART */ break; case MSP_MODE_FM_RADIO: dev_dbg_lvl(&client->dev, 1, msp_debug, "FM-Radio set_audmode: %s\n", modestr); break; default: dev_dbg_lvl(&client->dev, 1, msp_debug, "mono set_audmode\n"); return; } /* switch audio */ dev_dbg_lvl(&client->dev, 1, msp_debug, "set audmode %d\n", audmode); switch (audmode) { case V4L2_TUNER_MODE_STEREO: case V4L2_TUNER_MODE_LANG1_LANG2: src |= 0x0020; break; case V4L2_TUNER_MODE_MONO: if (state->mode == MSP_MODE_AM_NICAM) { dev_dbg_lvl(&client->dev, 1, msp_debug, "switching to AM mono\n"); /* AM mono decoding is handled by tuner, not MSP chip */ /* SCART switching control register */ msp_set_scart(client, SCART_MONO, 0); src = 0x0200; break; } if (state->rxsubchans & V4L2_TUNER_SUB_STEREO) src = 0x0030; break; case V4L2_TUNER_MODE_LANG1: break; case V4L2_TUNER_MODE_LANG2: src |= 0x0010; break; } dev_dbg_lvl(&client->dev, 1, msp_debug, "set_audmode final source/matrix = 0x%x\n", src); msp_set_source(client, src); } static void msp3400c_print_mode(struct i2c_client *client) { struct msp_state *state = to_state(i2c_get_clientdata(client)); if (state->main == state->second) dev_dbg_lvl(&client->dev, 1, msp_debug, "mono sound carrier: %d.%03d MHz\n", state->main / 910000, (state->main / 910) % 1000); else dev_dbg_lvl(&client->dev, 1, msp_debug, "main sound carrier: %d.%03d MHz\n", state->main / 910000, (state->main / 910) % 1000); if (state->mode == MSP_MODE_FM_NICAM1 || state->mode == MSP_MODE_FM_NICAM2) dev_dbg_lvl(&client->dev, 1, msp_debug, "NICAM/FM carrier : %d.%03d MHz\n", state->second / 910000, (state->second/910) % 1000); if (state->mode == MSP_MODE_AM_NICAM) dev_dbg_lvl(&client->dev, 1, msp_debug, "NICAM/AM carrier : %d.%03d MHz\n", state->second / 910000, (state->second / 910) % 1000); if (state->mode == MSP_MODE_FM_TERRA && state->main != state->second) { dev_dbg_lvl(&client->dev, 1, msp_debug, "FM-stereo carrier : %d.%03d MHz\n", state->second / 910000, (state->second / 910) % 1000); } } /* ----------------------------------------------------------------------- */ static int msp3400c_detect_stereo(struct i2c_client *client) { struct msp_state *state = to_state(i2c_get_clientdata(client)); int val; int rxsubchans = state->rxsubchans; int newnicam = state->nicam_on; int update = 0; switch (state->mode) { case MSP_MODE_FM_TERRA: val = msp_read_dsp(client, 0x18); if (val > 32767) val -= 65536; dev_dbg_lvl(&client->dev, 2, msp_debug, "stereo detect register: %d\n", val); if (val > 8192) { rxsubchans = V4L2_TUNER_SUB_STEREO; } else if (val < -4096) { rxsubchans = V4L2_TUNER_SUB_LANG1 | V4L2_TUNER_SUB_LANG2; } else { rxsubchans = V4L2_TUNER_SUB_MONO; } newnicam = 0; break; case MSP_MODE_FM_NICAM1: case MSP_MODE_FM_NICAM2: case MSP_MODE_AM_NICAM: val = msp_read_dem(client, 0x23); dev_dbg_lvl(&client->dev, 2, msp_debug, "nicam sync=%d, mode=%d\n", val & 1, (val & 0x1e) >> 1); if (val & 1) { /* nicam synced */ switch ((val & 0x1e) >> 1) { case 0: case 8: rxsubchans = V4L2_TUNER_SUB_STEREO; break; case 1: case 9: rxsubchans = V4L2_TUNER_SUB_MONO; break; case 2: case 10: rxsubchans = V4L2_TUNER_SUB_LANG1 | V4L2_TUNER_SUB_LANG2; break; default: rxsubchans = V4L2_TUNER_SUB_MONO; break; } newnicam = 1; } else { newnicam = 0; rxsubchans = V4L2_TUNER_SUB_MONO; } break; } if (rxsubchans != state->rxsubchans) { update = 1; dev_dbg_lvl(&client->dev, 1, msp_debug, "watch: rxsubchans %02x => %02x\n", state->rxsubchans, rxsubchans); state->rxsubchans = rxsubchans; } if (newnicam != state->nicam_on) { update = 1; dev_dbg_lvl(&client->dev, 1, msp_debug, "watch: nicam %d => %d\n", state->nicam_on, newnicam); state->nicam_on = newnicam; } return update; } /* * A kernel thread for msp3400 control -- we don't want to block the * in the ioctl while doing the sound carrier & stereo detect */ /* stereo/multilang monitoring */ static void watch_stereo(struct i2c_client *client) { struct msp_state *state = to_state(i2c_get_clientdata(client)); if (msp_detect_stereo(client)) msp_set_audmode(client); if (msp_once) state->watch_stereo = 0; } int msp3400c_thread(void *data) { struct i2c_client *client = data; struct msp_state *state = to_state(i2c_get_clientdata(client)); struct msp3400c_carrier_detect *cd; int count, max1, max2, val1, val2, val, i; dev_dbg_lvl(&client->dev, 1, msp_debug, "msp3400 daemon started\n"); state->detected_std = V4L2_STD_ALL; set_freezable(); for (;;) { dev_dbg_lvl(&client->dev, 2, msp_debug, "msp3400 thread: sleep\n"); msp_sleep(state, -1); dev_dbg_lvl(&client->dev, 2, msp_debug, "msp3400 thread: wakeup\n"); restart: dev_dbg_lvl(&client->dev, 2, msp_debug, "thread: restart scan\n"); state->restart = 0; if (kthread_should_stop()) break; if (state->radio || MSP_MODE_EXTERN == state->mode) { /* no carrier scan, just unmute */ dev_dbg_lvl(&client->dev, 1, msp_debug, "thread: no carrier scan\n"); state->scan_in_progress = 0; msp_update_volume(state); continue; } /* mute audio */ state->scan_in_progress = 1; msp_update_volume(state); msp3400c_set_mode(client, MSP_MODE_AM_DETECT); val1 = val2 = 0; max1 = max2 = -1; state->watch_stereo = 0; state->nicam_on = 0; /* wait for tuner to settle down after a channel change */ if (msp_sleep(state, 200)) goto restart; /* carrier detect pass #1 -- main carrier */ cd = msp3400c_carrier_detect_main; count = ARRAY_SIZE(msp3400c_carrier_detect_main); if (msp_amsound && (state->v4l2_std & V4L2_STD_SECAM)) { /* autodetect doesn't work well with AM ... */ max1 = 3; count = 0; dev_dbg_lvl(&client->dev, 1, msp_debug, "AM sound override\n"); } for (i = 0; i < count; i++) { msp3400c_set_carrier(client, cd[i].cdo, cd[i].cdo); if (msp_sleep(state, 100)) goto restart; val = msp_read_dsp(client, 0x1b); if (val > 32767) val -= 65536; if (val1 < val) { val1 = val; max1 = i; } dev_dbg_lvl(&client->dev, 1, msp_debug, "carrier1 val: %5d / %s\n", val, cd[i].name); } /* carrier detect pass #2 -- second (stereo) carrier */ switch (max1) { case 1: /* 5.5 */ cd = msp3400c_carrier_detect_55; count = ARRAY_SIZE(msp3400c_carrier_detect_55); break; case 3: /* 6.5 */ cd = msp3400c_carrier_detect_65; count = ARRAY_SIZE(msp3400c_carrier_detect_65); break; case 0: /* 4.5 */ case 2: /* 6.0 */ default: cd = NULL; count = 0; break; } if (msp_amsound && (state->v4l2_std & V4L2_STD_SECAM)) { /* autodetect doesn't work well with AM ... */ cd = NULL; count = 0; max2 = 0; } for (i = 0; i < count; i++) { msp3400c_set_carrier(client, cd[i].cdo, cd[i].cdo); if (msp_sleep(state, 100)) goto restart; val = msp_read_dsp(client, 0x1b); if (val > 32767) val -= 65536; if (val2 < val) { val2 = val; max2 = i; } dev_dbg_lvl(&client->dev, 1, msp_debug, "carrier2 val: %5d / %s\n", val, cd[i].name); } /* program the msp3400 according to the results */ state->main = msp3400c_carrier_detect_main[max1].cdo; switch (max1) { case 1: /* 5.5 */ state->detected_std = V4L2_STD_BG | V4L2_STD_PAL_H; if (max2 == 0) { /* B/G FM-stereo */ state->second = msp3400c_carrier_detect_55[max2].cdo; msp3400c_set_mode(client, MSP_MODE_FM_TERRA); state->watch_stereo = 1; } else if (max2 == 1 && state->has_nicam) { /* B/G NICAM */ state->second = msp3400c_carrier_detect_55[max2].cdo; msp3400c_set_mode(client, MSP_MODE_FM_NICAM1); state->nicam_on = 1; state->watch_stereo = 1; } else { goto no_second; } break; case 2: /* 6.0 */ /* PAL I NICAM */ state->detected_std = V4L2_STD_PAL_I; state->second = MSP_CARRIER(6.552); msp3400c_set_mode(client, MSP_MODE_FM_NICAM2); state->nicam_on = 1; state->watch_stereo = 1; break; case 3: /* 6.5 */ if (max2 == 1 || max2 == 2) { /* D/K FM-stereo */ state->second = msp3400c_carrier_detect_65[max2].cdo; msp3400c_set_mode(client, MSP_MODE_FM_TERRA); state->watch_stereo = 1; state->detected_std = V4L2_STD_DK; } else if (max2 == 0 && (state->v4l2_std & V4L2_STD_SECAM)) { /* L NICAM or AM-mono */ state->second = msp3400c_carrier_detect_65[max2].cdo; msp3400c_set_mode(client, MSP_MODE_AM_NICAM); state->watch_stereo = 1; state->detected_std = V4L2_STD_L; } else if (max2 == 0 && state->has_nicam) { /* D/K NICAM */ state->second = msp3400c_carrier_detect_65[max2].cdo; msp3400c_set_mode(client, MSP_MODE_FM_NICAM1); state->nicam_on = 1; state->watch_stereo = 1; state->detected_std = V4L2_STD_DK; } else { goto no_second; } break; case 0: /* 4.5 */ state->detected_std = V4L2_STD_MN; fallthrough; default: no_second: state->second = msp3400c_carrier_detect_main[max1].cdo; msp3400c_set_mode(client, MSP_MODE_FM_TERRA); break; } msp3400c_set_carrier(client, state->second, state->main); /* unmute */ state->scan_in_progress = 0; msp3400c_set_audmode(client); msp_update_volume(state); if (msp_debug) msp3400c_print_mode(client); /* monitor tv audio mode, the first time don't wait so long to get a quick stereo/bilingual result */ count = 3; while (state->watch_stereo) { if (msp_sleep(state, count ? 1000 : 5000)) goto restart; if (count) count--; watch_stereo(client); } } dev_dbg_lvl(&client->dev, 1, msp_debug, "thread: exit\n"); return 0; } int msp3410d_thread(void *data) { struct i2c_client *client = data; struct msp_state *state = to_state(i2c_get_clientdata(client)); int val, i, std, count; dev_dbg_lvl(&client->dev, 1, msp_debug, "msp3410 daemon started\n"); state->detected_std = V4L2_STD_ALL; set_freezable(); for (;;) { dev_dbg_lvl(&client->dev, 2, msp_debug, "msp3410 thread: sleep\n"); msp_sleep(state, -1); dev_dbg_lvl(&client->dev, 2, msp_debug, "msp3410 thread: wakeup\n"); restart: dev_dbg_lvl(&client->dev, 2, msp_debug, "thread: restart scan\n"); state->restart = 0; if (kthread_should_stop()) break; if (state->mode == MSP_MODE_EXTERN) { /* no carrier scan needed, just unmute */ dev_dbg_lvl(&client->dev, 1, msp_debug, "thread: no carrier scan\n"); state->scan_in_progress = 0; msp_update_volume(state); continue; } /* mute audio */ state->scan_in_progress = 1; msp_update_volume(state); /* start autodetect. Note: autodetect is not supported for NTSC-M and radio, hence we force the standard in those cases. */ if (state->radio) std = 0x40; else std = (state->v4l2_std & V4L2_STD_NTSC) ? 0x20 : 1; state->watch_stereo = 0; state->nicam_on = 0; /* wait for tuner to settle down after a channel change */ if (msp_sleep(state, 200)) goto restart; if (msp_debug) dev_dbg_lvl(&client->dev, 2, msp_debug, "setting standard: %s (0x%04x)\n", msp_standard_std_name(std), std); if (std != 1) { /* programmed some specific mode */ val = std; } else { /* triggered autodetect */ msp_write_dem(client, 0x20, std); for (;;) { if (msp_sleep(state, 100)) goto restart; /* check results */ val = msp_read_dem(client, 0x7e); if (val < 0x07ff) break; dev_dbg_lvl(&client->dev, 2, msp_debug, "detection still in progress\n"); } } for (i = 0; msp_stdlist[i].name != NULL; i++) if (msp_stdlist[i].retval == val) break; dev_dbg_lvl(&client->dev, 1, msp_debug, "current standard: %s (0x%04x)\n", msp_standard_std_name(val), val); state->main = msp_stdlist[i].main; state->second = msp_stdlist[i].second; state->std = val; state->rxsubchans = V4L2_TUNER_SUB_MONO; if (msp_amsound && !state->radio && (state->v4l2_std & V4L2_STD_SECAM) && (val != 0x0009)) { /* autodetection has failed, let backup */ dev_dbg_lvl(&client->dev, 1, msp_debug, "autodetection failed, switching to backup standard: %s (0x%04x)\n", msp_stdlist[8].name ? msp_stdlist[8].name : "unknown", val); state->std = val = 0x0009; msp_write_dem(client, 0x20, val); } else { state->detected_std = msp_standard_std(state->std); } /* set stereo */ switch (val) { case 0x0008: /* B/G NICAM */ case 0x000a: /* I NICAM */ case 0x000b: /* D/K NICAM */ if (val == 0x000a) state->mode = MSP_MODE_FM_NICAM2; else state->mode = MSP_MODE_FM_NICAM1; /* just turn on stereo */ state->nicam_on = 1; state->watch_stereo = 1; break; case 0x0009: state->mode = MSP_MODE_AM_NICAM; state->nicam_on = 1; state->watch_stereo = 1; break; case 0x0020: /* BTSC */ /* The pre-'G' models only have BTSC-mono */ state->mode = MSP_MODE_BTSC; break; case 0x0040: /* FM radio */ state->mode = MSP_MODE_FM_RADIO; state->rxsubchans = V4L2_TUNER_SUB_STEREO; /* not needed in theory if we have radio, but short programming enables carrier mute */ msp3400c_set_mode(client, MSP_MODE_FM_RADIO); msp3400c_set_carrier(client, MSP_CARRIER(10.7), MSP_CARRIER(10.7)); break; case 0x0002: case 0x0003: case 0x0004: case 0x0005: state->mode = MSP_MODE_FM_TERRA; state->watch_stereo = 1; break; } /* set various prescales */ msp_write_dsp(client, 0x0d, 0x1900); /* scart */ msp_write_dsp(client, 0x0e, 0x3000); /* FM */ if (state->has_nicam) msp_write_dsp(client, 0x10, 0x5a00); /* nicam */ if (state->has_i2s_conf) msp_write_dem(client, 0x40, state->i2s_mode); /* unmute */ msp3400c_set_audmode(client); state->scan_in_progress = 0; msp_update_volume(state); /* monitor tv audio mode, the first time don't wait so long to get a quick stereo/bilingual result */ count = 3; while (state->watch_stereo) { if (msp_sleep(state, count ? 1000 : 5000)) goto restart; if (count) count--; watch_stereo(client); } } dev_dbg_lvl(&client->dev, 1, msp_debug, "thread: exit\n"); return 0; } /* ----------------------------------------------------------------------- */ /* msp34xxG + (autoselect no-thread) * this one uses both automatic standard detection and automatic sound * select which are available in the newer G versions * struct msp: only norm, acb and source are really used in this mode */ static int msp34xxg_modus(struct i2c_client *client) { struct msp_state *state = to_state(i2c_get_clientdata(client)); if (state->radio) { dev_dbg_lvl(&client->dev, 1, msp_debug, "selected radio modus\n"); return 0x0001; } if (state->v4l2_std == V4L2_STD_NTSC_M_JP) { dev_dbg_lvl(&client->dev, 1, msp_debug, "selected M (EIA-J) modus\n"); return 0x4001; } if (state->v4l2_std == V4L2_STD_NTSC_M_KR) { dev_dbg_lvl(&client->dev, 1, msp_debug, "selected M (A2) modus\n"); return 0x0001; } if (state->v4l2_std == V4L2_STD_SECAM_L) { dev_dbg_lvl(&client->dev, 1, msp_debug, "selected SECAM-L modus\n"); return 0x6001; } if (state->v4l2_std & V4L2_STD_MN) { dev_dbg_lvl(&client->dev, 1, msp_debug, "selected M (BTSC) modus\n"); return 0x2001; } return 0x7001; } static void msp34xxg_set_source(struct i2c_client *client, u16 reg, int in) { struct msp_state *state = to_state(i2c_get_clientdata(client)); int source, matrix; switch (state->audmode) { case V4L2_TUNER_MODE_MONO: source = 0; /* mono only */ matrix = 0x30; break; case V4L2_TUNER_MODE_LANG2: source = 4; /* stereo or B */ matrix = 0x10; break; case V4L2_TUNER_MODE_LANG1_LANG2: source = 1; /* stereo or A|B */ matrix = 0x20; break; case V4L2_TUNER_MODE_LANG1: source = 3; /* stereo or A */ matrix = 0x00; break; case V4L2_TUNER_MODE_STEREO: default: source = 3; /* stereo or A */ matrix = 0x20; break; } if (in == MSP_DSP_IN_TUNER) source = (source << 8) | 0x20; /* the msp34x2g puts the MAIN_AVC, MAIN and AUX sources in 12, 13, 14 instead of 11, 12, 13. So we add one for that msp version. */ else if (in >= MSP_DSP_IN_MAIN_AVC && state->has_dolby_pro_logic) source = ((in + 1) << 8) | matrix; else source = (in << 8) | matrix; dev_dbg_lvl(&client->dev, 1, msp_debug, "set source to %d (0x%x) for output %02x\n", in, source, reg); msp_write_dsp(client, reg, source); } static void msp34xxg_set_sources(struct i2c_client *client) { struct msp_state *state = to_state(i2c_get_clientdata(client)); u32 in = state->route_in; msp34xxg_set_source(client, 0x0008, (in >> 4) & 0xf); /* quasi-peak detector is set to same input as the loudspeaker (MAIN) */ msp34xxg_set_source(client, 0x000c, (in >> 4) & 0xf); msp34xxg_set_source(client, 0x0009, (in >> 8) & 0xf); msp34xxg_set_source(client, 0x000a, (in >> 12) & 0xf); if (state->has_scart2_out) msp34xxg_set_source(client, 0x0041, (in >> 16) & 0xf); msp34xxg_set_source(client, 0x000b, (in >> 20) & 0xf); } /* (re-)initialize the msp34xxg */ static void msp34xxg_reset(struct i2c_client *client) { struct msp_state *state = to_state(i2c_get_clientdata(client)); int tuner = (state->route_in >> 3) & 1; int modus; /* initialize std to 1 (autodetect) to signal that no standard is selected yet. */ state->std = 1; msp_reset(client); if (state->has_i2s_conf) msp_write_dem(client, 0x40, state->i2s_mode); /* step-by-step initialisation, as described in the manual */ modus = msp34xxg_modus(client); modus |= tuner ? 0x100 : 0; msp_write_dem(client, 0x30, modus); /* write the dsps that may have an influence on standard/audio autodetection right now */ msp34xxg_set_sources(client); msp_write_dsp(client, 0x0d, 0x1900); /* scart */ msp_write_dsp(client, 0x0e, 0x3000); /* FM */ if (state->has_nicam) msp_write_dsp(client, 0x10, 0x5a00); /* nicam */ /* set identification threshold. Personally, I * I set it to a higher value than the default * of 0x190 to ignore noisy stereo signals. * this needs tuning. (recommended range 0x00a0-0x03c0) * 0x7f0 = forced mono mode * * a2 threshold for stereo/bilingual. * Note: this register is part of the Manual/Compatibility mode. * It is supported by all 'G'-family chips. */ msp_write_dem(client, 0x22, msp_stereo_thresh); } int msp34xxg_thread(void *data) { struct i2c_client *client = data; struct msp_state *state = to_state(i2c_get_clientdata(client)); int val, i; dev_dbg_lvl(&client->dev, 1, msp_debug, "msp34xxg daemon started\n"); state->detected_std = V4L2_STD_ALL; set_freezable(); for (;;) { dev_dbg_lvl(&client->dev, 2, msp_debug, "msp34xxg thread: sleep\n"); msp_sleep(state, -1); dev_dbg_lvl(&client->dev, 2, msp_debug, "msp34xxg thread: wakeup\n"); restart: dev_dbg_lvl(&client->dev, 1, msp_debug, "thread: restart scan\n"); state->restart = 0; if (kthread_should_stop()) break; if (state->mode == MSP_MODE_EXTERN) { /* no carrier scan needed, just unmute */ dev_dbg_lvl(&client->dev, 1, msp_debug, "thread: no carrier scan\n"); state->scan_in_progress = 0; msp_update_volume(state); continue; } /* setup the chip*/ msp34xxg_reset(client); state->std = state->radio ? 0x40 : (state->force_btsc && msp_standard == 1) ? 32 : msp_standard; msp_write_dem(client, 0x20, state->std); /* start autodetect */ if (state->std != 1) goto unmute; /* watch autodetect */ dev_dbg_lvl(&client->dev, 1, msp_debug, "started autodetect, waiting for result\n"); for (i = 0; i < 10; i++) { if (msp_sleep(state, 100)) goto restart; /* check results */ val = msp_read_dem(client, 0x7e); if (val < 0x07ff) { state->std = val; break; } dev_dbg_lvl(&client->dev, 2, msp_debug, "detection still in progress\n"); } if (state->std == 1) { dev_dbg_lvl(&client->dev, 1, msp_debug, "detection still in progress after 10 tries. giving up.\n"); continue; } unmute: dev_dbg_lvl(&client->dev, 1, msp_debug, "detected standard: %s (0x%04x)\n", msp_standard_std_name(state->std), state->std); state->detected_std = msp_standard_std(state->std); if (state->std == 9) { /* AM NICAM mode */ msp_write_dsp(client, 0x0e, 0x7c00); } /* unmute: dispatch sound to scart output, set scart volume */ msp_update_volume(state); /* restore ACB */ if (msp_write_dsp(client, 0x13, state->acb)) return -1; /* the periodic stereo/SAP check is only relevant for the 0x20 standard (BTSC) */ if (state->std != 0x20) continue; state->watch_stereo = 1; /* monitor tv audio mode, the first time don't wait in order to get a quick stereo/SAP update */ watch_stereo(client); while (state->watch_stereo) { watch_stereo(client); if (msp_sleep(state, 5000)) goto restart; } } dev_dbg_lvl(&client->dev, 1, msp_debug, "thread: exit\n"); return 0; } static int msp34xxg_detect_stereo(struct i2c_client *client) { struct msp_state *state = to_state(i2c_get_clientdata(client)); int status = msp_read_dem(client, 0x0200); int is_bilingual = status & 0x100; int is_stereo = status & 0x40; int oldrx = state->rxsubchans; if (state->mode == MSP_MODE_EXTERN) return 0; state->rxsubchans = 0; if (is_stereo) state->rxsubchans = V4L2_TUNER_SUB_STEREO; else state->rxsubchans = V4L2_TUNER_SUB_MONO; if (is_bilingual) { if (state->std == 0x20) state->rxsubchans |= V4L2_TUNER_SUB_SAP; else state->rxsubchans = V4L2_TUNER_SUB_LANG1 | V4L2_TUNER_SUB_LANG2; } dev_dbg_lvl(&client->dev, 1, msp_debug, "status=0x%x, stereo=%d, bilingual=%d -> rxsubchans=%d\n", status, is_stereo, is_bilingual, state->rxsubchans); return (oldrx != state->rxsubchans); } static void msp34xxg_set_audmode(struct i2c_client *client) { struct msp_state *state = to_state(i2c_get_clientdata(client)); if (state->std == 0x20) { if ((state->rxsubchans & V4L2_TUNER_SUB_SAP) && (state->audmode == V4L2_TUNER_MODE_LANG1_LANG2 || state->audmode == V4L2_TUNER_MODE_LANG2)) { msp_write_dem(client, 0x20, 0x21); } else { msp_write_dem(client, 0x20, 0x20); } } msp34xxg_set_sources(client); } void msp_set_audmode(struct i2c_client *client) { struct msp_state *state = to_state(i2c_get_clientdata(client)); switch (state->opmode) { case OPMODE_MANUAL: case OPMODE_AUTODETECT: msp3400c_set_audmode(client); break; case OPMODE_AUTOSELECT: msp34xxg_set_audmode(client); break; } } int msp_detect_stereo(struct i2c_client *client) { struct msp_state *state = to_state(i2c_get_clientdata(client)); switch (state->opmode) { case OPMODE_MANUAL: case OPMODE_AUTODETECT: return msp3400c_detect_stereo(client); case OPMODE_AUTOSELECT: return msp34xxg_detect_stereo(client); } return 0; }
linux-master
drivers/media/i2c/msp3400-kthreads.c
// SPDX-License-Identifier: GPL-2.0 /* * Driver for the Texas Instruments DS90UB953 video serializer * * Based on a driver from Luca Ceresoli <[email protected]> * * Copyright (c) 2019 Luca Ceresoli <[email protected]> * Copyright (c) 2023 Tomi Valkeinen <[email protected]> */ #include <linux/clk-provider.h> #include <linux/clk.h> #include <linux/delay.h> #include <linux/fwnode.h> #include <linux/gpio/driver.h> #include <linux/i2c-atr.h> #include <linux/i2c.h> #include <linux/kernel.h> #include <linux/math64.h> #include <linux/module.h> #include <linux/property.h> #include <linux/rational.h> #include <linux/regmap.h> #include <media/i2c/ds90ub9xx.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-event.h> #include <media/v4l2-fwnode.h> #include <media/v4l2-mediabus.h> #include <media/v4l2-subdev.h> #define UB953_PAD_SINK 0 #define UB953_PAD_SOURCE 1 #define UB953_NUM_GPIOS 4 #define UB953_DEFAULT_CLKOUT_RATE 25000000UL #define UB953_REG_RESET_CTL 0x01 #define UB953_REG_RESET_CTL_DIGITAL_RESET_1 BIT(1) #define UB953_REG_RESET_CTL_DIGITAL_RESET_0 BIT(0) #define UB953_REG_GENERAL_CFG 0x02 #define UB953_REG_GENERAL_CFG_CONT_CLK BIT(6) #define UB953_REG_GENERAL_CFG_CSI_LANE_SEL_SHIFT 4 #define UB953_REG_GENERAL_CFG_CSI_LANE_SEL_MASK GENMASK(5, 4) #define UB953_REG_GENERAL_CFG_CRC_TX_GEN_ENABLE BIT(1) #define UB953_REG_GENERAL_CFG_I2C_STRAP_MODE BIT(0) #define UB953_REG_MODE_SEL 0x03 #define UB953_REG_MODE_SEL_MODE_DONE BIT(3) #define UB953_REG_MODE_SEL_MODE_OVERRIDE BIT(4) #define UB953_REG_MODE_SEL_MODE_MASK GENMASK(2, 0) #define UB953_REG_CLKOUT_CTRL0 0x06 #define UB953_REG_CLKOUT_CTRL1 0x07 #define UB953_REG_SCL_HIGH_TIME 0x0b #define UB953_REG_SCL_LOW_TIME 0x0c #define UB953_REG_LOCAL_GPIO_DATA 0x0d #define UB953_REG_LOCAL_GPIO_DATA_GPIO_RMTEN(n) BIT(4 + (n)) #define UB953_REG_LOCAL_GPIO_DATA_GPIO_OUT_SRC(n) BIT(0 + (n)) #define UB953_REG_GPIO_INPUT_CTRL 0x0e #define UB953_REG_GPIO_INPUT_CTRL_OUT_EN(n) BIT(4 + (n)) #define UB953_REG_GPIO_INPUT_CTRL_INPUT_EN(n) BIT(0 + (n)) #define UB953_REG_REV_MASK_ID 0x50 #define UB953_REG_GENERAL_STATUS 0x52 #define UB953_REG_GPIO_PIN_STS 0x53 #define UB953_REG_GPIO_PIN_STS_GPIO_STS(n) BIT(0 + (n)) #define UB953_REG_BIST_ERR_CNT 0x54 #define UB953_REG_CRC_ERR_CNT1 0x55 #define UB953_REG_CRC_ERR_CNT2 0x56 #define UB953_REG_CSI_ERR_CNT 0x5c #define UB953_REG_CSI_ERR_STATUS 0x5d #define UB953_REG_CSI_ERR_DLANE01 0x5e #define UB953_REG_CSI_ERR_DLANE23 0x5f #define UB953_REG_CSI_ERR_CLK_LANE 0x60 #define UB953_REG_CSI_PKT_HDR_VC_ID 0x61 #define UB953_REG_PKT_HDR_WC_LSB 0x62 #define UB953_REG_PKT_HDR_WC_MSB 0x63 #define UB953_REG_CSI_ECC 0x64 #define UB953_REG_IND_ACC_CTL 0xb0 #define UB953_REG_IND_ACC_ADDR 0xb1 #define UB953_REG_IND_ACC_DATA 0xb2 #define UB953_REG_FPD3_RX_ID(n) (0xf0 + (n)) #define UB953_REG_FPD3_RX_ID_LEN 6 /* Indirect register blocks */ #define UB953_IND_TARGET_PAT_GEN 0x00 #define UB953_IND_TARGET_FPD3_TX 0x01 #define UB953_IND_TARGET_DIE_ID 0x02 #define UB953_IND_PGEN_CTL 0x01 #define UB953_IND_PGEN_CTL_PGEN_ENABLE BIT(0) #define UB953_IND_PGEN_CFG 0x02 #define UB953_IND_PGEN_CSI_DI 0x03 #define UB953_IND_PGEN_LINE_SIZE1 0x04 #define UB953_IND_PGEN_LINE_SIZE0 0x05 #define UB953_IND_PGEN_BAR_SIZE1 0x06 #define UB953_IND_PGEN_BAR_SIZE0 0x07 #define UB953_IND_PGEN_ACT_LPF1 0x08 #define UB953_IND_PGEN_ACT_LPF0 0x09 #define UB953_IND_PGEN_TOT_LPF1 0x0a #define UB953_IND_PGEN_TOT_LPF0 0x0b #define UB953_IND_PGEN_LINE_PD1 0x0c #define UB953_IND_PGEN_LINE_PD0 0x0d #define UB953_IND_PGEN_VBP 0x0e #define UB953_IND_PGEN_VFP 0x0f #define UB953_IND_PGEN_COLOR(n) (0x10 + (n)) /* n <= 15 */ /* Note: Only sync mode supported for now */ enum ub953_mode { /* FPD-Link III CSI-2 synchronous mode */ UB953_MODE_SYNC, /* FPD-Link III CSI-2 non-synchronous mode, external ref clock */ UB953_MODE_NONSYNC_EXT, /* FPD-Link III CSI-2 non-synchronous mode, internal ref clock */ UB953_MODE_NONSYNC_INT, /* FPD-Link III DVP mode */ UB953_MODE_DVP, }; struct ub953_hw_data { const char *model; bool is_ub971; }; struct ub953_clkout_data { u32 hs_div; u32 m; u32 n; unsigned long rate; }; struct ub953_data { const struct ub953_hw_data *hw_data; struct i2c_client *client; struct regmap *regmap; struct clk *clkin; u32 num_data_lanes; bool non_continous_clk; struct gpio_chip gpio_chip; struct v4l2_subdev sd; struct media_pad pads[2]; struct v4l2_async_notifier notifier; struct v4l2_subdev *source_sd; u16 source_sd_pad; u64 enabled_source_streams; /* lock for register access */ struct mutex reg_lock; u8 current_indirect_target; struct clk_hw clkout_clk_hw; enum ub953_mode mode; const struct ds90ub9xx_platform_data *plat_data; }; static inline struct ub953_data *sd_to_ub953(struct v4l2_subdev *sd) { return container_of(sd, struct ub953_data, sd); } /* * HW Access */ static int ub953_read(struct ub953_data *priv, u8 reg, u8 *val) { unsigned int v; int ret; mutex_lock(&priv->reg_lock); ret = regmap_read(priv->regmap, reg, &v); if (ret) { dev_err(&priv->client->dev, "Cannot read register 0x%02x: %d\n", reg, ret); goto out_unlock; } *val = v; out_unlock: mutex_unlock(&priv->reg_lock); return ret; } static int ub953_write(struct ub953_data *priv, u8 reg, u8 val) { int ret; mutex_lock(&priv->reg_lock); ret = regmap_write(priv->regmap, reg, val); if (ret) dev_err(&priv->client->dev, "Cannot write register 0x%02x: %d\n", reg, ret); mutex_unlock(&priv->reg_lock); return ret; } static int ub953_select_ind_reg_block(struct ub953_data *priv, u8 block) { struct device *dev = &priv->client->dev; int ret; if (priv->current_indirect_target == block) return 0; ret = regmap_write(priv->regmap, UB953_REG_IND_ACC_CTL, block << 2); if (ret) { dev_err(dev, "%s: cannot select indirect target %u (%d)\n", __func__, block, ret); return ret; } priv->current_indirect_target = block; return 0; } __maybe_unused static int ub953_read_ind(struct ub953_data *priv, u8 block, u8 reg, u8 *val) { unsigned int v; int ret; mutex_lock(&priv->reg_lock); ret = ub953_select_ind_reg_block(priv, block); if (ret) goto out_unlock; ret = regmap_write(priv->regmap, UB953_REG_IND_ACC_ADDR, reg); if (ret) { dev_err(&priv->client->dev, "Write to IND_ACC_ADDR failed when reading %u:%x02x: %d\n", block, reg, ret); goto out_unlock; } ret = regmap_read(priv->regmap, UB953_REG_IND_ACC_DATA, &v); if (ret) { dev_err(&priv->client->dev, "Write to IND_ACC_DATA failed when reading %u:%x02x: %d\n", block, reg, ret); goto out_unlock; } *val = v; out_unlock: mutex_unlock(&priv->reg_lock); return ret; } __maybe_unused static int ub953_write_ind(struct ub953_data *priv, u8 block, u8 reg, u8 val) { int ret; mutex_lock(&priv->reg_lock); ret = ub953_select_ind_reg_block(priv, block); if (ret) goto out_unlock; ret = regmap_write(priv->regmap, UB953_REG_IND_ACC_ADDR, reg); if (ret) { dev_err(&priv->client->dev, "Write to IND_ACC_ADDR failed when writing %u:%x02x: %d\n", block, reg, ret); goto out_unlock; } ret = regmap_write(priv->regmap, UB953_REG_IND_ACC_DATA, val); if (ret) { dev_err(&priv->client->dev, "Write to IND_ACC_DATA failed when writing %u:%x02x\n: %d\n", block, reg, ret); } out_unlock: mutex_unlock(&priv->reg_lock); return ret; } /* * GPIO chip */ static int ub953_gpio_get_direction(struct gpio_chip *gc, unsigned int offset) { struct ub953_data *priv = gpiochip_get_data(gc); int ret; u8 v; ret = ub953_read(priv, UB953_REG_GPIO_INPUT_CTRL, &v); if (ret) return ret; if (v & UB953_REG_GPIO_INPUT_CTRL_INPUT_EN(offset)) return GPIO_LINE_DIRECTION_IN; else return GPIO_LINE_DIRECTION_OUT; } static int ub953_gpio_direction_in(struct gpio_chip *gc, unsigned int offset) { struct ub953_data *priv = gpiochip_get_data(gc); return regmap_update_bits(priv->regmap, UB953_REG_GPIO_INPUT_CTRL, UB953_REG_GPIO_INPUT_CTRL_INPUT_EN(offset) | UB953_REG_GPIO_INPUT_CTRL_OUT_EN(offset), UB953_REG_GPIO_INPUT_CTRL_INPUT_EN(offset)); } static int ub953_gpio_direction_out(struct gpio_chip *gc, unsigned int offset, int value) { struct ub953_data *priv = gpiochip_get_data(gc); int ret; ret = regmap_update_bits(priv->regmap, UB953_REG_LOCAL_GPIO_DATA, UB953_REG_LOCAL_GPIO_DATA_GPIO_OUT_SRC(offset), value ? UB953_REG_LOCAL_GPIO_DATA_GPIO_OUT_SRC(offset) : 0); if (ret) return ret; return regmap_update_bits(priv->regmap, UB953_REG_GPIO_INPUT_CTRL, UB953_REG_GPIO_INPUT_CTRL_INPUT_EN(offset) | UB953_REG_GPIO_INPUT_CTRL_OUT_EN(offset), UB953_REG_GPIO_INPUT_CTRL_OUT_EN(offset)); } static int ub953_gpio_get(struct gpio_chip *gc, unsigned int offset) { struct ub953_data *priv = gpiochip_get_data(gc); int ret; u8 v; ret = ub953_read(priv, UB953_REG_GPIO_PIN_STS, &v); if (ret) return ret; return !!(v & UB953_REG_GPIO_PIN_STS_GPIO_STS(offset)); } static void ub953_gpio_set(struct gpio_chip *gc, unsigned int offset, int value) { struct ub953_data *priv = gpiochip_get_data(gc); regmap_update_bits(priv->regmap, UB953_REG_LOCAL_GPIO_DATA, UB953_REG_LOCAL_GPIO_DATA_GPIO_OUT_SRC(offset), value ? UB953_REG_LOCAL_GPIO_DATA_GPIO_OUT_SRC(offset) : 0); } static int ub953_gpio_of_xlate(struct gpio_chip *gc, const struct of_phandle_args *gpiospec, u32 *flags) { if (flags) *flags = gpiospec->args[1]; return gpiospec->args[0]; } static int ub953_gpiochip_probe(struct ub953_data *priv) { struct device *dev = &priv->client->dev; struct gpio_chip *gc = &priv->gpio_chip; int ret; /* Set all GPIOs to local input mode */ ub953_write(priv, UB953_REG_LOCAL_GPIO_DATA, 0); ub953_write(priv, UB953_REG_GPIO_INPUT_CTRL, 0xf); gc->label = dev_name(dev); gc->parent = dev; gc->owner = THIS_MODULE; gc->base = -1; gc->can_sleep = true; gc->ngpio = UB953_NUM_GPIOS; gc->get_direction = ub953_gpio_get_direction; gc->direction_input = ub953_gpio_direction_in; gc->direction_output = ub953_gpio_direction_out; gc->get = ub953_gpio_get; gc->set = ub953_gpio_set; gc->of_xlate = ub953_gpio_of_xlate; gc->of_gpio_n_cells = 2; ret = gpiochip_add_data(gc, priv); if (ret) { dev_err(dev, "Failed to add GPIOs: %d\n", ret); return ret; } return 0; } static void ub953_gpiochip_remove(struct ub953_data *priv) { gpiochip_remove(&priv->gpio_chip); } /* * V4L2 */ static int _ub953_set_routing(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, struct v4l2_subdev_krouting *routing) { static const struct v4l2_mbus_framefmt format = { .width = 640, .height = 480, .code = MEDIA_BUS_FMT_UYVY8_1X16, .field = V4L2_FIELD_NONE, .colorspace = V4L2_COLORSPACE_SRGB, .ycbcr_enc = V4L2_YCBCR_ENC_601, .quantization = V4L2_QUANTIZATION_LIM_RANGE, .xfer_func = V4L2_XFER_FUNC_SRGB, }; int ret; /* * Note: we can only support up to V4L2_FRAME_DESC_ENTRY_MAX, until * frame desc is made dynamically allocated. */ if (routing->num_routes > V4L2_FRAME_DESC_ENTRY_MAX) return -EINVAL; ret = v4l2_subdev_routing_validate(sd, routing, V4L2_SUBDEV_ROUTING_ONLY_1_TO_1); if (ret) return ret; ret = v4l2_subdev_set_routing_with_fmt(sd, state, routing, &format); if (ret) return ret; return 0; } static int ub953_set_routing(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, enum v4l2_subdev_format_whence which, struct v4l2_subdev_krouting *routing) { struct ub953_data *priv = sd_to_ub953(sd); if (which == V4L2_SUBDEV_FORMAT_ACTIVE && priv->enabled_source_streams) return -EBUSY; return _ub953_set_routing(sd, state, routing); } static int ub953_get_frame_desc(struct v4l2_subdev *sd, unsigned int pad, struct v4l2_mbus_frame_desc *fd) { struct ub953_data *priv = sd_to_ub953(sd); struct v4l2_mbus_frame_desc source_fd; struct v4l2_subdev_route *route; struct v4l2_subdev_state *state; int ret; if (pad != UB953_PAD_SOURCE) return -EINVAL; ret = v4l2_subdev_call(priv->source_sd, pad, get_frame_desc, priv->source_sd_pad, &source_fd); if (ret) return ret; memset(fd, 0, sizeof(*fd)); fd->type = V4L2_MBUS_FRAME_DESC_TYPE_CSI2; state = v4l2_subdev_lock_and_get_active_state(sd); for_each_active_route(&state->routing, route) { struct v4l2_mbus_frame_desc_entry *source_entry = NULL; unsigned int i; if (route->source_pad != pad) continue; for (i = 0; i < source_fd.num_entries; i++) { if (source_fd.entry[i].stream == route->sink_stream) { source_entry = &source_fd.entry[i]; break; } } if (!source_entry) { dev_err(&priv->client->dev, "Failed to find stream from source frame desc\n"); ret = -EPIPE; goto out_unlock; } fd->entry[fd->num_entries].stream = route->source_stream; fd->entry[fd->num_entries].flags = source_entry->flags; fd->entry[fd->num_entries].length = source_entry->length; fd->entry[fd->num_entries].pixelcode = source_entry->pixelcode; fd->entry[fd->num_entries].bus.csi2.vc = source_entry->bus.csi2.vc; fd->entry[fd->num_entries].bus.csi2.dt = source_entry->bus.csi2.dt; fd->num_entries++; } out_unlock: v4l2_subdev_unlock_state(state); return ret; } static int ub953_set_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, struct v4l2_subdev_format *format) { struct ub953_data *priv = sd_to_ub953(sd); struct v4l2_mbus_framefmt *fmt; if (format->which == V4L2_SUBDEV_FORMAT_ACTIVE && priv->enabled_source_streams) return -EBUSY; /* No transcoding, source and sink formats must match. */ if (format->pad == UB953_PAD_SOURCE) return v4l2_subdev_get_fmt(sd, state, format); /* Set sink format */ fmt = v4l2_subdev_state_get_stream_format(state, format->pad, format->stream); if (!fmt) return -EINVAL; *fmt = format->format; /* Propagate to source format */ fmt = v4l2_subdev_state_get_opposite_stream_format(state, format->pad, format->stream); if (!fmt) return -EINVAL; *fmt = format->format; return 0; } static int ub953_init_cfg(struct v4l2_subdev *sd, struct v4l2_subdev_state *state) { struct v4l2_subdev_route routes[] = { { .sink_pad = UB953_PAD_SINK, .sink_stream = 0, .source_pad = UB953_PAD_SOURCE, .source_stream = 0, .flags = V4L2_SUBDEV_ROUTE_FL_ACTIVE, }, }; struct v4l2_subdev_krouting routing = { .num_routes = ARRAY_SIZE(routes), .routes = routes, }; return _ub953_set_routing(sd, state, &routing); } static int ub953_log_status(struct v4l2_subdev *sd) { struct ub953_data *priv = sd_to_ub953(sd); struct device *dev = &priv->client->dev; u8 v = 0, v1 = 0, v2 = 0; unsigned int i; char id[UB953_REG_FPD3_RX_ID_LEN]; u8 gpio_local_data = 0; u8 gpio_input_ctrl = 0; u8 gpio_pin_sts = 0; for (i = 0; i < sizeof(id); i++) ub953_read(priv, UB953_REG_FPD3_RX_ID(i), &id[i]); dev_info(dev, "ID '%.*s'\n", (int)sizeof(id), id); ub953_read(priv, UB953_REG_GENERAL_STATUS, &v); dev_info(dev, "GENERAL_STATUS %#02x\n", v); ub953_read(priv, UB953_REG_CRC_ERR_CNT1, &v1); ub953_read(priv, UB953_REG_CRC_ERR_CNT2, &v2); dev_info(dev, "CRC error count %u\n", v1 | (v2 << 8)); ub953_read(priv, UB953_REG_CSI_ERR_CNT, &v); dev_info(dev, "CSI error count %u\n", v); ub953_read(priv, UB953_REG_CSI_ERR_STATUS, &v); dev_info(dev, "CSI_ERR_STATUS %#02x\n", v); ub953_read(priv, UB953_REG_CSI_ERR_DLANE01, &v); dev_info(dev, "CSI_ERR_DLANE01 %#02x\n", v); ub953_read(priv, UB953_REG_CSI_ERR_DLANE23, &v); dev_info(dev, "CSI_ERR_DLANE23 %#02x\n", v); ub953_read(priv, UB953_REG_CSI_ERR_CLK_LANE, &v); dev_info(dev, "CSI_ERR_CLK_LANE %#02x\n", v); ub953_read(priv, UB953_REG_CSI_PKT_HDR_VC_ID, &v); dev_info(dev, "CSI packet header VC %u ID %u\n", v >> 6, v & 0x3f); ub953_read(priv, UB953_REG_PKT_HDR_WC_LSB, &v1); ub953_read(priv, UB953_REG_PKT_HDR_WC_MSB, &v2); dev_info(dev, "CSI packet header WC %u\n", (v2 << 8) | v1); ub953_read(priv, UB953_REG_CSI_ECC, &v); dev_info(dev, "CSI ECC %#02x\n", v); ub953_read(priv, UB953_REG_LOCAL_GPIO_DATA, &gpio_local_data); ub953_read(priv, UB953_REG_GPIO_INPUT_CTRL, &gpio_input_ctrl); ub953_read(priv, UB953_REG_GPIO_PIN_STS, &gpio_pin_sts); for (i = 0; i < UB953_NUM_GPIOS; i++) { dev_info(dev, "GPIO%u: remote: %u is_input: %u is_output: %u val: %u sts: %u\n", i, !!(gpio_local_data & UB953_REG_LOCAL_GPIO_DATA_GPIO_RMTEN(i)), !!(gpio_input_ctrl & UB953_REG_GPIO_INPUT_CTRL_INPUT_EN(i)), !!(gpio_input_ctrl & UB953_REG_GPIO_INPUT_CTRL_OUT_EN(i)), !!(gpio_local_data & UB953_REG_LOCAL_GPIO_DATA_GPIO_OUT_SRC(i)), !!(gpio_pin_sts & UB953_REG_GPIO_PIN_STS_GPIO_STS(i))); } return 0; } static int ub953_enable_streams(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, u32 pad, u64 streams_mask) { struct ub953_data *priv = sd_to_ub953(sd); u64 sink_streams; int ret; sink_streams = v4l2_subdev_state_xlate_streams(state, UB953_PAD_SOURCE, UB953_PAD_SINK, &streams_mask); ret = v4l2_subdev_enable_streams(priv->source_sd, priv->source_sd_pad, sink_streams); if (ret) return ret; priv->enabled_source_streams |= streams_mask; return 0; } static int ub953_disable_streams(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, u32 pad, u64 streams_mask) { struct ub953_data *priv = sd_to_ub953(sd); u64 sink_streams; int ret; sink_streams = v4l2_subdev_state_xlate_streams(state, UB953_PAD_SOURCE, UB953_PAD_SINK, &streams_mask); ret = v4l2_subdev_disable_streams(priv->source_sd, priv->source_sd_pad, sink_streams); if (ret) return ret; priv->enabled_source_streams &= ~streams_mask; return 0; } static const struct v4l2_subdev_pad_ops ub953_pad_ops = { .enable_streams = ub953_enable_streams, .disable_streams = ub953_disable_streams, .set_routing = ub953_set_routing, .get_frame_desc = ub953_get_frame_desc, .get_fmt = v4l2_subdev_get_fmt, .set_fmt = ub953_set_fmt, .init_cfg = ub953_init_cfg, }; static const struct v4l2_subdev_core_ops ub953_subdev_core_ops = { .log_status = ub953_log_status, .subscribe_event = v4l2_ctrl_subdev_subscribe_event, .unsubscribe_event = v4l2_event_subdev_unsubscribe, }; static const struct v4l2_subdev_ops ub953_subdev_ops = { .core = &ub953_subdev_core_ops, .pad = &ub953_pad_ops, }; static const struct media_entity_operations ub953_entity_ops = { .link_validate = v4l2_subdev_link_validate, }; static int ub953_notify_bound(struct v4l2_async_notifier *notifier, struct v4l2_subdev *source_subdev, struct v4l2_async_connection *asd) { struct ub953_data *priv = sd_to_ub953(notifier->sd); struct device *dev = &priv->client->dev; int ret; ret = media_entity_get_fwnode_pad(&source_subdev->entity, source_subdev->fwnode, MEDIA_PAD_FL_SOURCE); if (ret < 0) { dev_err(dev, "Failed to find pad for %s\n", source_subdev->name); return ret; } priv->source_sd = source_subdev; priv->source_sd_pad = ret; ret = media_create_pad_link(&source_subdev->entity, priv->source_sd_pad, &priv->sd.entity, 0, MEDIA_LNK_FL_ENABLED | MEDIA_LNK_FL_IMMUTABLE); if (ret) { dev_err(dev, "Unable to link %s:%u -> %s:0\n", source_subdev->name, priv->source_sd_pad, priv->sd.name); return ret; } return 0; } static const struct v4l2_async_notifier_operations ub953_notify_ops = { .bound = ub953_notify_bound, }; static int ub953_v4l2_notifier_register(struct ub953_data *priv) { struct device *dev = &priv->client->dev; struct v4l2_async_connection *asd; struct fwnode_handle *ep_fwnode; int ret; ep_fwnode = fwnode_graph_get_endpoint_by_id(dev_fwnode(dev), UB953_PAD_SINK, 0, 0); if (!ep_fwnode) { dev_err(dev, "No graph endpoint\n"); return -ENODEV; } v4l2_async_subdev_nf_init(&priv->notifier, &priv->sd); asd = v4l2_async_nf_add_fwnode_remote(&priv->notifier, ep_fwnode, struct v4l2_async_connection); fwnode_handle_put(ep_fwnode); if (IS_ERR(asd)) { dev_err(dev, "Failed to add subdev: %ld", PTR_ERR(asd)); v4l2_async_nf_cleanup(&priv->notifier); return PTR_ERR(asd); } priv->notifier.ops = &ub953_notify_ops; ret = v4l2_async_nf_register(&priv->notifier); if (ret) { dev_err(dev, "Failed to register subdev_notifier"); v4l2_async_nf_cleanup(&priv->notifier); return ret; } return 0; } static void ub953_v4l2_notifier_unregister(struct ub953_data *priv) { v4l2_async_nf_unregister(&priv->notifier); v4l2_async_nf_cleanup(&priv->notifier); } /* * Probing */ static int ub953_i2c_master_init(struct ub953_data *priv) { /* i2c fast mode */ u32 ref = 26250000; u32 scl_high = 915; /* ns */ u32 scl_low = 1641; /* ns */ int ret; scl_high = div64_u64((u64)scl_high * ref, 1000000000) - 5; scl_low = div64_u64((u64)scl_low * ref, 1000000000) - 5; ret = ub953_write(priv, UB953_REG_SCL_HIGH_TIME, scl_high); if (ret) return ret; ret = ub953_write(priv, UB953_REG_SCL_LOW_TIME, scl_low); if (ret) return ret; return 0; } static u64 ub953_get_fc_rate(struct ub953_data *priv) { switch (priv->mode) { case UB953_MODE_SYNC: if (priv->hw_data->is_ub971) return priv->plat_data->bc_rate * 160ull; else return priv->plat_data->bc_rate / 2 * 160ull; case UB953_MODE_NONSYNC_EXT: /* CLKIN_DIV = 1 always */ return clk_get_rate(priv->clkin) * 80ull; default: /* Not supported */ return 0; } } static unsigned long ub953_calc_clkout_ub953(struct ub953_data *priv, unsigned long target, u64 fc, u8 *hs_div, u8 *m, u8 *n) { /* * We always use 4 as a pre-divider (HS_CLK_DIV = 2). * * According to the datasheet: * - "HS_CLK_DIV typically should be set to either 16, 8, or 4 (default)." * - "if it is not possible to have an integer ratio of N/M, it is best to * select a smaller value for HS_CLK_DIV. * * For above reasons the default HS_CLK_DIV seems the best in the average * case. Use always that value to keep the code simple. */ static const unsigned long hs_clk_div = 4; u64 fc_divided; unsigned long mul, div; unsigned long res; /* clkout = fc / hs_clk_div * m / n */ fc_divided = div_u64(fc, hs_clk_div); rational_best_approximation(target, fc_divided, (1 << 5) - 1, (1 << 8) - 1, &mul, &div); res = div_u64(fc_divided * mul, div); *hs_div = hs_clk_div; *m = mul; *n = div; return res; } static unsigned long ub953_calc_clkout_ub971(struct ub953_data *priv, unsigned long target, u64 fc, u8 *m, u8 *n) { u64 fc_divided; unsigned long mul, div; unsigned long res; /* clkout = fc * m / (8 * n) */ fc_divided = div_u64(fc, 8); rational_best_approximation(target, fc_divided, (1 << 5) - 1, (1 << 8) - 1, &mul, &div); res = div_u64(fc_divided * mul, div); *m = mul; *n = div; return res; } static void ub953_calc_clkout_params(struct ub953_data *priv, unsigned long target_rate, struct ub953_clkout_data *clkout_data) { struct device *dev = &priv->client->dev; unsigned long clkout_rate; u64 fc_rate; fc_rate = ub953_get_fc_rate(priv); if (priv->hw_data->is_ub971) { u8 m, n; clkout_rate = ub953_calc_clkout_ub971(priv, target_rate, fc_rate, &m, &n); clkout_data->m = m; clkout_data->n = n; dev_dbg(dev, "%s %llu * %u / (8 * %u) = %lu (requested %lu)", __func__, fc_rate, m, n, clkout_rate, target_rate); } else { u8 hs_div, m, n; clkout_rate = ub953_calc_clkout_ub953(priv, target_rate, fc_rate, &hs_div, &m, &n); clkout_data->hs_div = hs_div; clkout_data->m = m; clkout_data->n = n; dev_dbg(dev, "%s %llu / %u * %u / %u = %lu (requested %lu)", __func__, fc_rate, hs_div, m, n, clkout_rate, target_rate); } clkout_data->rate = clkout_rate; } static void ub953_write_clkout_regs(struct ub953_data *priv, const struct ub953_clkout_data *clkout_data) { u8 clkout_ctrl0, clkout_ctrl1; if (priv->hw_data->is_ub971) clkout_ctrl0 = clkout_data->m; else clkout_ctrl0 = (__ffs(clkout_data->hs_div) << 5) | clkout_data->m; clkout_ctrl1 = clkout_data->n; ub953_write(priv, UB953_REG_CLKOUT_CTRL0, clkout_ctrl0); ub953_write(priv, UB953_REG_CLKOUT_CTRL1, clkout_ctrl1); } static unsigned long ub953_clkout_recalc_rate(struct clk_hw *hw, unsigned long parent_rate) { struct ub953_data *priv = container_of(hw, struct ub953_data, clkout_clk_hw); struct device *dev = &priv->client->dev; u8 ctrl0, ctrl1; u32 mul, div; u64 fc_rate; u32 hs_clk_div; u64 rate; int ret; ret = ub953_read(priv, UB953_REG_CLKOUT_CTRL0, &ctrl0); if (ret) { dev_err(dev, "Failed to read CLKOUT_CTRL0: %d\n", ret); return 0; } ret = ub953_read(priv, UB953_REG_CLKOUT_CTRL1, &ctrl1); if (ret) { dev_err(dev, "Failed to read CLKOUT_CTRL1: %d\n", ret); return 0; } fc_rate = ub953_get_fc_rate(priv); if (priv->hw_data->is_ub971) { mul = ctrl0 & 0x1f; div = ctrl1; if (div == 0) return 0; rate = div_u64(fc_rate * mul, 8 * div); dev_dbg(dev, "clkout: fc rate %llu, mul %u, div %u = %llu\n", fc_rate, mul, div, rate); } else { mul = ctrl0 & 0x1f; hs_clk_div = 1 << (ctrl0 >> 5); div = ctrl1; if (div == 0) return 0; rate = div_u64(div_u64(fc_rate, hs_clk_div) * mul, div); dev_dbg(dev, "clkout: fc rate %llu, hs_clk_div %u, mul %u, div %u = %llu\n", fc_rate, hs_clk_div, mul, div, rate); } return rate; } static long ub953_clkout_round_rate(struct clk_hw *hw, unsigned long rate, unsigned long *parent_rate) { struct ub953_data *priv = container_of(hw, struct ub953_data, clkout_clk_hw); struct ub953_clkout_data clkout_data; ub953_calc_clkout_params(priv, rate, &clkout_data); return clkout_data.rate; } static int ub953_clkout_set_rate(struct clk_hw *hw, unsigned long rate, unsigned long parent_rate) { struct ub953_data *priv = container_of(hw, struct ub953_data, clkout_clk_hw); struct ub953_clkout_data clkout_data; ub953_calc_clkout_params(priv, rate, &clkout_data); dev_dbg(&priv->client->dev, "%s %lu (requested %lu)\n", __func__, clkout_data.rate, rate); ub953_write_clkout_regs(priv, &clkout_data); return 0; } static const struct clk_ops ub953_clkout_ops = { .recalc_rate = ub953_clkout_recalc_rate, .round_rate = ub953_clkout_round_rate, .set_rate = ub953_clkout_set_rate, }; static int ub953_register_clkout(struct ub953_data *priv) { struct device *dev = &priv->client->dev; const struct clk_init_data init = { .name = kasprintf(GFP_KERNEL, "ds90%s.%s.clk_out", priv->hw_data->model, dev_name(dev)), .ops = &ub953_clkout_ops, }; struct ub953_clkout_data clkout_data; int ret; if (!init.name) return -ENOMEM; /* Initialize clkout to 25MHz by default */ ub953_calc_clkout_params(priv, UB953_DEFAULT_CLKOUT_RATE, &clkout_data); ub953_write_clkout_regs(priv, &clkout_data); priv->clkout_clk_hw.init = &init; ret = devm_clk_hw_register(dev, &priv->clkout_clk_hw); kfree(init.name); if (ret) return dev_err_probe(dev, ret, "Cannot register clock HW\n"); ret = devm_of_clk_add_hw_provider(dev, of_clk_hw_simple_get, &priv->clkout_clk_hw); if (ret) return dev_err_probe(dev, ret, "Cannot add OF clock provider\n"); return 0; } static int ub953_add_i2c_adapter(struct ub953_data *priv) { struct device *dev = &priv->client->dev; struct fwnode_handle *i2c_handle; int ret; i2c_handle = device_get_named_child_node(dev, "i2c"); if (!i2c_handle) return 0; ret = i2c_atr_add_adapter(priv->plat_data->atr, priv->plat_data->port, dev, i2c_handle); fwnode_handle_put(i2c_handle); if (ret) return ret; return 0; } static const struct regmap_config ub953_regmap_config = { .name = "ds90ub953", .reg_bits = 8, .val_bits = 8, .reg_format_endian = REGMAP_ENDIAN_DEFAULT, .val_format_endian = REGMAP_ENDIAN_DEFAULT, }; static int ub953_parse_dt(struct ub953_data *priv) { struct device *dev = &priv->client->dev; struct v4l2_fwnode_endpoint vep = { .bus_type = V4L2_MBUS_CSI2_DPHY, }; struct fwnode_handle *ep_fwnode; unsigned char nlanes; int ret; ep_fwnode = fwnode_graph_get_endpoint_by_id(dev_fwnode(dev), UB953_PAD_SINK, 0, 0); if (!ep_fwnode) return dev_err_probe(dev, -ENOENT, "no endpoint found\n"); ret = v4l2_fwnode_endpoint_parse(ep_fwnode, &vep); fwnode_handle_put(ep_fwnode); if (ret) return dev_err_probe(dev, ret, "failed to parse sink endpoint data\n"); nlanes = vep.bus.mipi_csi2.num_data_lanes; if (nlanes != 1 && nlanes != 2 && nlanes != 4) return dev_err_probe(dev, -EINVAL, "bad number of data-lanes: %u\n", nlanes); priv->num_data_lanes = nlanes; priv->non_continous_clk = vep.bus.mipi_csi2.flags & V4L2_MBUS_CSI2_NONCONTINUOUS_CLOCK; return 0; } static int ub953_hw_init(struct ub953_data *priv) { struct device *dev = &priv->client->dev; bool mode_override; int ret; u8 v; ret = ub953_read(priv, UB953_REG_MODE_SEL, &v); if (ret) return ret; if (!(v & UB953_REG_MODE_SEL_MODE_DONE)) return dev_err_probe(dev, -EIO, "Mode value not stabilized\n"); mode_override = v & UB953_REG_MODE_SEL_MODE_OVERRIDE; switch (v & UB953_REG_MODE_SEL_MODE_MASK) { case 0: priv->mode = UB953_MODE_SYNC; break; case 2: priv->mode = UB953_MODE_NONSYNC_EXT; break; case 3: priv->mode = UB953_MODE_NONSYNC_INT; break; case 5: priv->mode = UB953_MODE_DVP; break; default: return dev_err_probe(dev, -EIO, "Invalid mode in mode register\n"); } dev_dbg(dev, "mode from %s: %#x\n", mode_override ? "reg" : "strap", priv->mode); if (priv->mode != UB953_MODE_SYNC && priv->mode != UB953_MODE_NONSYNC_EXT) return dev_err_probe(dev, -ENODEV, "Unsupported mode selected: %u\n", priv->mode); if (priv->mode == UB953_MODE_NONSYNC_EXT && !priv->clkin) return dev_err_probe(dev, -EINVAL, "clkin required for non-sync ext mode\n"); ret = ub953_read(priv, UB953_REG_REV_MASK_ID, &v); if (ret) return dev_err_probe(dev, ret, "Failed to read revision"); dev_info(dev, "Found %s rev/mask %#04x\n", priv->hw_data->model, v); ret = ub953_read(priv, UB953_REG_GENERAL_CFG, &v); if (ret) return ret; dev_dbg(dev, "i2c strap setting %s V\n", (v & UB953_REG_GENERAL_CFG_I2C_STRAP_MODE) ? "1.8" : "3.3"); ret = ub953_i2c_master_init(priv); if (ret) return dev_err_probe(dev, ret, "i2c init failed\n"); ub953_write(priv, UB953_REG_GENERAL_CFG, (priv->non_continous_clk ? 0 : UB953_REG_GENERAL_CFG_CONT_CLK) | ((priv->num_data_lanes - 1) << UB953_REG_GENERAL_CFG_CSI_LANE_SEL_SHIFT) | UB953_REG_GENERAL_CFG_CRC_TX_GEN_ENABLE); return 0; } static int ub953_subdev_init(struct ub953_data *priv) { struct device *dev = &priv->client->dev; int ret; v4l2_i2c_subdev_init(&priv->sd, priv->client, &ub953_subdev_ops); priv->sd.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE | V4L2_SUBDEV_FL_HAS_EVENTS | V4L2_SUBDEV_FL_STREAMS; priv->sd.entity.function = MEDIA_ENT_F_VID_IF_BRIDGE; priv->sd.entity.ops = &ub953_entity_ops; priv->pads[0].flags = MEDIA_PAD_FL_SINK; priv->pads[1].flags = MEDIA_PAD_FL_SOURCE; ret = media_entity_pads_init(&priv->sd.entity, 2, priv->pads); if (ret) return dev_err_probe(dev, ret, "Failed to init pads\n"); ret = v4l2_subdev_init_finalize(&priv->sd); if (ret) goto err_entity_cleanup; ret = ub953_v4l2_notifier_register(priv); if (ret) { dev_err_probe(dev, ret, "v4l2 subdev notifier register failed\n"); goto err_free_state; } ret = v4l2_async_register_subdev(&priv->sd); if (ret) { dev_err_probe(dev, ret, "v4l2_async_register_subdev error\n"); goto err_unreg_notif; } return 0; err_unreg_notif: ub953_v4l2_notifier_unregister(priv); err_free_state: v4l2_subdev_cleanup(&priv->sd); err_entity_cleanup: media_entity_cleanup(&priv->sd.entity); return ret; } static void ub953_subdev_uninit(struct ub953_data *priv) { v4l2_async_unregister_subdev(&priv->sd); ub953_v4l2_notifier_unregister(priv); v4l2_subdev_cleanup(&priv->sd); fwnode_handle_put(priv->sd.fwnode); media_entity_cleanup(&priv->sd.entity); } static int ub953_probe(struct i2c_client *client) { struct device *dev = &client->dev; struct ub953_data *priv; int ret; priv = devm_kzalloc(dev, sizeof(*priv), GFP_KERNEL); if (!priv) return -ENOMEM; priv->client = client; priv->hw_data = device_get_match_data(dev); priv->plat_data = dev_get_platdata(&client->dev); if (!priv->plat_data) return dev_err_probe(dev, -ENODEV, "Platform data missing\n"); mutex_init(&priv->reg_lock); /* * Initialize to invalid values so that the first reg writes will * configure the target. */ priv->current_indirect_target = 0xff; priv->regmap = devm_regmap_init_i2c(client, &ub953_regmap_config); if (IS_ERR(priv->regmap)) { ret = PTR_ERR(priv->regmap); dev_err_probe(dev, ret, "Failed to init regmap\n"); goto err_mutex_destroy; } priv->clkin = devm_clk_get_optional(dev, "clkin"); if (IS_ERR(priv->clkin)) { ret = PTR_ERR(priv->clkin); dev_err_probe(dev, ret, "failed to parse 'clkin'\n"); goto err_mutex_destroy; } ret = ub953_parse_dt(priv); if (ret) goto err_mutex_destroy; ret = ub953_hw_init(priv); if (ret) goto err_mutex_destroy; ret = ub953_gpiochip_probe(priv); if (ret) { dev_err_probe(dev, ret, "Failed to init gpiochip\n"); goto err_mutex_destroy; } ret = ub953_register_clkout(priv); if (ret) { dev_err_probe(dev, ret, "Failed to register clkout\n"); goto err_gpiochip_remove; } ret = ub953_subdev_init(priv); if (ret) goto err_gpiochip_remove; ret = ub953_add_i2c_adapter(priv); if (ret) { dev_err_probe(dev, ret, "failed to add remote i2c adapter\n"); goto err_subdev_uninit; } return 0; err_subdev_uninit: ub953_subdev_uninit(priv); err_gpiochip_remove: ub953_gpiochip_remove(priv); err_mutex_destroy: mutex_destroy(&priv->reg_lock); return ret; } static void ub953_remove(struct i2c_client *client) { struct v4l2_subdev *sd = i2c_get_clientdata(client); struct ub953_data *priv = sd_to_ub953(sd); i2c_atr_del_adapter(priv->plat_data->atr, priv->plat_data->port); ub953_subdev_uninit(priv); ub953_gpiochip_remove(priv); mutex_destroy(&priv->reg_lock); } static const struct ub953_hw_data ds90ub953_hw = { .model = "ub953", }; static const struct ub953_hw_data ds90ub971_hw = { .model = "ub971", .is_ub971 = true, }; static const struct i2c_device_id ub953_id[] = { { "ds90ub953-q1", (kernel_ulong_t)&ds90ub953_hw }, { "ds90ub971-q1", (kernel_ulong_t)&ds90ub971_hw }, {} }; MODULE_DEVICE_TABLE(i2c, ub953_id); static const struct of_device_id ub953_dt_ids[] = { { .compatible = "ti,ds90ub953-q1", .data = &ds90ub953_hw }, { .compatible = "ti,ds90ub971-q1", .data = &ds90ub971_hw }, {} }; MODULE_DEVICE_TABLE(of, ub953_dt_ids); static struct i2c_driver ds90ub953_driver = { .probe = ub953_probe, .remove = ub953_remove, .id_table = ub953_id, .driver = { .name = "ds90ub953", .of_match_table = ub953_dt_ids, }, }; module_i2c_driver(ds90ub953_driver); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Texas Instruments FPD-Link III/IV CSI-2 Serializers Driver"); MODULE_AUTHOR("Luca Ceresoli <[email protected]>"); MODULE_AUTHOR("Tomi Valkeinen <[email protected]>"); MODULE_IMPORT_NS(I2C_ATR);
linux-master
drivers/media/i2c/ds90ub953.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2023 Intel Corporation. */ #include <asm/unaligned.h> #include <linux/acpi.h> #include <linux/bitfield.h> #include <linux/i2c.h> #include <linux/module.h> #include <linux/pm_runtime.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-device.h> #include <media/v4l2-event.h> #include <media/v4l2-fwnode.h> #define OV01A10_LINK_FREQ_400MHZ 400000000ULL #define OV01A10_SCLK 40000000LL #define OV01A10_DATA_LANES 1 #define OV01A10_REG_CHIP_ID 0x300a #define OV01A10_CHIP_ID 0x560141 #define OV01A10_REG_MODE_SELECT 0x0100 #define OV01A10_MODE_STANDBY 0x00 #define OV01A10_MODE_STREAMING 0x01 /* pixel array */ #define OV01A10_PIXEL_ARRAY_WIDTH 1296 #define OV01A10_PIXEL_ARRAY_HEIGHT 816 #define OV01A10_ACITVE_WIDTH 1280 #define OV01A10_ACITVE_HEIGHT 800 /* vertical and horizontal timings */ #define OV01A10_REG_VTS 0x380e #define OV01A10_VTS_DEF 0x0380 #define OV01A10_VTS_MIN 0x0380 #define OV01A10_VTS_MAX 0xffff #define OV01A10_HTS_DEF 1488 /* exposure controls */ #define OV01A10_REG_EXPOSURE 0x3501 #define OV01A10_EXPOSURE_MIN 4 #define OV01A10_EXPOSURE_MAX_MARGIN 8 #define OV01A10_EXPOSURE_STEP 1 /* analog gain controls */ #define OV01A10_REG_ANALOG_GAIN 0x3508 #define OV01A10_ANAL_GAIN_MIN 0x100 #define OV01A10_ANAL_GAIN_MAX 0xffff #define OV01A10_ANAL_GAIN_STEP 1 /* digital gain controls */ #define OV01A10_REG_DIGITAL_GAIN_B 0x350a #define OV01A10_REG_DIGITAL_GAIN_GB 0x3510 #define OV01A10_REG_DIGITAL_GAIN_GR 0x3513 #define OV01A10_REG_DIGITAL_GAIN_R 0x3516 #define OV01A10_DGTL_GAIN_MIN 0 #define OV01A10_DGTL_GAIN_MAX 0x3ffff #define OV01A10_DGTL_GAIN_STEP 1 #define OV01A10_DGTL_GAIN_DEFAULT 1024 /* test pattern control */ #define OV01A10_REG_TEST_PATTERN 0x4503 #define OV01A10_TEST_PATTERN_ENABLE BIT(7) #define OV01A10_LINK_FREQ_400MHZ_INDEX 0 /* flip and mirror control */ #define OV01A10_REG_FORMAT1 0x3820 #define OV01A10_VFLIP_MASK BIT(4) #define OV01A10_HFLIP_MASK BIT(3) /* window offset */ #define OV01A10_REG_X_WIN 0x3811 #define OV01A10_REG_Y_WIN 0x3813 struct ov01a10_reg { u16 address; u8 val; }; struct ov01a10_reg_list { u32 num_of_regs; const struct ov01a10_reg *regs; }; struct ov01a10_link_freq_config { const struct ov01a10_reg_list reg_list; }; struct ov01a10_mode { u32 width; u32 height; u32 hts; u32 vts_def; u32 vts_min; u32 link_freq_index; const struct ov01a10_reg_list reg_list; }; static const struct ov01a10_reg mipi_data_rate_720mbps[] = { {0x0103, 0x01}, {0x0302, 0x00}, {0x0303, 0x06}, {0x0304, 0x01}, {0x0305, 0xe0}, {0x0306, 0x00}, {0x0308, 0x01}, {0x0309, 0x00}, {0x030c, 0x01}, {0x0322, 0x01}, {0x0323, 0x06}, {0x0324, 0x01}, {0x0325, 0x68}, }; static const struct ov01a10_reg sensor_1280x800_setting[] = { {0x3002, 0xa1}, {0x301e, 0xf0}, {0x3022, 0x01}, {0x3501, 0x03}, {0x3502, 0x78}, {0x3504, 0x0c}, {0x3508, 0x01}, {0x3509, 0x00}, {0x3601, 0xc0}, {0x3603, 0x71}, {0x3610, 0x68}, {0x3611, 0x86}, {0x3640, 0x10}, {0x3641, 0x80}, {0x3642, 0xdc}, {0x3646, 0x55}, {0x3647, 0x57}, {0x364b, 0x00}, {0x3653, 0x10}, {0x3655, 0x00}, {0x3656, 0x00}, {0x365f, 0x0f}, {0x3661, 0x45}, {0x3662, 0x24}, {0x3663, 0x11}, {0x3664, 0x07}, {0x3709, 0x34}, {0x370b, 0x6f}, {0x3714, 0x22}, {0x371b, 0x27}, {0x371c, 0x67}, {0x371d, 0xa7}, {0x371e, 0xe7}, {0x3730, 0x81}, {0x3733, 0x10}, {0x3734, 0x40}, {0x3737, 0x04}, {0x3739, 0x1c}, {0x3767, 0x00}, {0x376c, 0x81}, {0x3772, 0x14}, {0x37c2, 0x04}, {0x37d8, 0x03}, {0x37d9, 0x0c}, {0x37e0, 0x00}, {0x37e1, 0x08}, {0x37e2, 0x10}, {0x37e3, 0x04}, {0x37e4, 0x04}, {0x37e5, 0x03}, {0x37e6, 0x04}, {0x3800, 0x00}, {0x3801, 0x00}, {0x3802, 0x00}, {0x3803, 0x00}, {0x3804, 0x05}, {0x3805, 0x0f}, {0x3806, 0x03}, {0x3807, 0x2f}, {0x3808, 0x05}, {0x3809, 0x00}, {0x380a, 0x03}, {0x380b, 0x20}, {0x380c, 0x02}, {0x380d, 0xe8}, {0x380e, 0x03}, {0x380f, 0x80}, {0x3810, 0x00}, {0x3811, 0x08}, {0x3812, 0x00}, {0x3813, 0x08}, {0x3814, 0x01}, {0x3815, 0x01}, {0x3816, 0x01}, {0x3817, 0x01}, {0x3820, 0xa0}, {0x3822, 0x13}, {0x3832, 0x28}, {0x3833, 0x10}, {0x3b00, 0x00}, {0x3c80, 0x00}, {0x3c88, 0x02}, {0x3c8c, 0x07}, {0x3c8d, 0x40}, {0x3cc7, 0x80}, {0x4000, 0xc3}, {0x4001, 0xe0}, {0x4003, 0x40}, {0x4008, 0x02}, {0x4009, 0x19}, {0x400a, 0x01}, {0x400b, 0x6c}, {0x4011, 0x00}, {0x4041, 0x00}, {0x4300, 0xff}, {0x4301, 0x00}, {0x4302, 0x0f}, {0x4503, 0x00}, {0x4601, 0x50}, {0x4800, 0x64}, {0x481f, 0x34}, {0x4825, 0x33}, {0x4837, 0x11}, {0x4881, 0x40}, {0x4883, 0x01}, {0x4890, 0x00}, {0x4901, 0x00}, {0x4902, 0x00}, {0x4b00, 0x2a}, {0x4b0d, 0x00}, {0x450a, 0x04}, {0x450b, 0x00}, {0x5000, 0x65}, {0x5200, 0x18}, {0x5004, 0x00}, {0x5080, 0x40}, {0x0305, 0xf4}, {0x0325, 0xc2}, }; static const char * const ov01a10_test_pattern_menu[] = { "Disabled", "Color Bar", "Top-Bottom Darker Color Bar", "Right-Left Darker Color Bar", "Color Bar type 4", }; static const s64 link_freq_menu_items[] = { OV01A10_LINK_FREQ_400MHZ, }; static const struct ov01a10_link_freq_config link_freq_configs[] = { [OV01A10_LINK_FREQ_400MHZ_INDEX] = { .reg_list = { .num_of_regs = ARRAY_SIZE(mipi_data_rate_720mbps), .regs = mipi_data_rate_720mbps, } }, }; static const struct ov01a10_mode supported_modes[] = { { .width = OV01A10_ACITVE_WIDTH, .height = OV01A10_ACITVE_HEIGHT, .hts = OV01A10_HTS_DEF, .vts_def = OV01A10_VTS_DEF, .vts_min = OV01A10_VTS_MIN, .reg_list = { .num_of_regs = ARRAY_SIZE(sensor_1280x800_setting), .regs = sensor_1280x800_setting, }, .link_freq_index = OV01A10_LINK_FREQ_400MHZ_INDEX, }, }; struct ov01a10 { struct v4l2_subdev sd; struct media_pad pad; struct v4l2_ctrl_handler ctrl_handler; /* v4l2 controls */ struct v4l2_ctrl *link_freq; struct v4l2_ctrl *pixel_rate; struct v4l2_ctrl *vblank; struct v4l2_ctrl *hblank; struct v4l2_ctrl *exposure; const struct ov01a10_mode *cur_mode; /* streaming state */ bool streaming; }; static inline struct ov01a10 *to_ov01a10(struct v4l2_subdev *subdev) { return container_of(subdev, struct ov01a10, sd); } static int ov01a10_read_reg(struct ov01a10 *ov01a10, u16 reg, u16 len, u32 *val) { struct i2c_client *client = v4l2_get_subdevdata(&ov01a10->sd); struct i2c_msg msgs[2]; u8 addr_buf[2]; u8 data_buf[4] = {0}; int ret = 0; if (len > sizeof(data_buf)) return -EINVAL; put_unaligned_be16(reg, addr_buf); msgs[0].addr = client->addr; msgs[0].flags = 0; msgs[0].len = sizeof(addr_buf); msgs[0].buf = addr_buf; msgs[1].addr = client->addr; msgs[1].flags = I2C_M_RD; msgs[1].len = len; msgs[1].buf = &data_buf[sizeof(data_buf) - len]; ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs)); if (ret != ARRAY_SIZE(msgs)) return ret < 0 ? ret : -EIO; *val = get_unaligned_be32(data_buf); return 0; } static int ov01a10_write_reg(struct ov01a10 *ov01a10, u16 reg, u16 len, u32 val) { struct i2c_client *client = v4l2_get_subdevdata(&ov01a10->sd); u8 buf[6]; int ret = 0; if (len > 4) return -EINVAL; put_unaligned_be16(reg, buf); put_unaligned_be32(val << 8 * (4 - len), buf + 2); ret = i2c_master_send(client, buf, len + 2); if (ret != len + 2) return ret < 0 ? ret : -EIO; return 0; } static int ov01a10_write_reg_list(struct ov01a10 *ov01a10, const struct ov01a10_reg_list *r_list) { struct i2c_client *client = v4l2_get_subdevdata(&ov01a10->sd); unsigned int i; int ret = 0; for (i = 0; i < r_list->num_of_regs; i++) { ret = ov01a10_write_reg(ov01a10, r_list->regs[i].address, 1, r_list->regs[i].val); if (ret) { dev_err_ratelimited(&client->dev, "write reg 0x%4.4x err = %d\n", r_list->regs[i].address, ret); return ret; } } return 0; } static int ov01a10_update_digital_gain(struct ov01a10 *ov01a10, u32 d_gain) { struct i2c_client *client = v4l2_get_subdevdata(&ov01a10->sd); u32 real = d_gain << 6; int ret = 0; ret = ov01a10_write_reg(ov01a10, OV01A10_REG_DIGITAL_GAIN_B, 3, real); if (ret) { dev_err(&client->dev, "failed to set DIGITAL_GAIN_B\n"); return ret; } ret = ov01a10_write_reg(ov01a10, OV01A10_REG_DIGITAL_GAIN_GB, 3, real); if (ret) { dev_err(&client->dev, "failed to set DIGITAL_GAIN_GB\n"); return ret; } ret = ov01a10_write_reg(ov01a10, OV01A10_REG_DIGITAL_GAIN_GR, 3, real); if (ret) { dev_err(&client->dev, "failed to set DIGITAL_GAIN_GR\n"); return ret; } ret = ov01a10_write_reg(ov01a10, OV01A10_REG_DIGITAL_GAIN_R, 3, real); if (ret) dev_err(&client->dev, "failed to set DIGITAL_GAIN_R\n"); return ret; } static int ov01a10_test_pattern(struct ov01a10 *ov01a10, u32 pattern) { if (!pattern) return 0; pattern = (pattern - 1) | OV01A10_TEST_PATTERN_ENABLE; return ov01a10_write_reg(ov01a10, OV01A10_REG_TEST_PATTERN, 1, pattern); } /* for vflip and hflip, use 0x9 as window offset to keep the bayer */ static int ov01a10_set_hflip(struct ov01a10 *ov01a10, u32 hflip) { int ret; u32 val, offset; offset = hflip ? 0x9 : 0x8; ret = ov01a10_write_reg(ov01a10, OV01A10_REG_X_WIN, 1, offset); if (ret) return ret; ret = ov01a10_read_reg(ov01a10, OV01A10_REG_FORMAT1, 1, &val); if (ret) return ret; val = hflip ? val | FIELD_PREP(OV01A10_HFLIP_MASK, 0x1) : val & ~OV01A10_HFLIP_MASK; return ov01a10_write_reg(ov01a10, OV01A10_REG_FORMAT1, 1, val); } static int ov01a10_set_vflip(struct ov01a10 *ov01a10, u32 vflip) { int ret; u32 val, offset; offset = vflip ? 0x9 : 0x8; ret = ov01a10_write_reg(ov01a10, OV01A10_REG_Y_WIN, 1, offset); if (ret) return ret; ret = ov01a10_read_reg(ov01a10, OV01A10_REG_FORMAT1, 1, &val); if (ret) return ret; val = vflip ? val | FIELD_PREP(OV01A10_VFLIP_MASK, 0x1) : val & ~OV01A10_VFLIP_MASK; return ov01a10_write_reg(ov01a10, OV01A10_REG_FORMAT1, 1, val); } static int ov01a10_set_ctrl(struct v4l2_ctrl *ctrl) { struct ov01a10 *ov01a10 = container_of(ctrl->handler, struct ov01a10, ctrl_handler); struct i2c_client *client = v4l2_get_subdevdata(&ov01a10->sd); s64 exposure_max; int ret = 0; if (ctrl->id == V4L2_CID_VBLANK) { exposure_max = ov01a10->cur_mode->height + ctrl->val - OV01A10_EXPOSURE_MAX_MARGIN; __v4l2_ctrl_modify_range(ov01a10->exposure, ov01a10->exposure->minimum, exposure_max, ov01a10->exposure->step, exposure_max); } if (!pm_runtime_get_if_in_use(&client->dev)) return 0; switch (ctrl->id) { case V4L2_CID_ANALOGUE_GAIN: ret = ov01a10_write_reg(ov01a10, OV01A10_REG_ANALOG_GAIN, 2, ctrl->val); break; case V4L2_CID_DIGITAL_GAIN: ret = ov01a10_update_digital_gain(ov01a10, ctrl->val); break; case V4L2_CID_EXPOSURE: ret = ov01a10_write_reg(ov01a10, OV01A10_REG_EXPOSURE, 2, ctrl->val); break; case V4L2_CID_VBLANK: ret = ov01a10_write_reg(ov01a10, OV01A10_REG_VTS, 2, ov01a10->cur_mode->height + ctrl->val); break; case V4L2_CID_TEST_PATTERN: ret = ov01a10_test_pattern(ov01a10, ctrl->val); break; case V4L2_CID_HFLIP: ov01a10_set_hflip(ov01a10, ctrl->val); break; case V4L2_CID_VFLIP: ov01a10_set_vflip(ov01a10, ctrl->val); break; default: ret = -EINVAL; break; } pm_runtime_put(&client->dev); return ret; } static const struct v4l2_ctrl_ops ov01a10_ctrl_ops = { .s_ctrl = ov01a10_set_ctrl, }; static int ov01a10_init_controls(struct ov01a10 *ov01a10) { struct i2c_client *client = v4l2_get_subdevdata(&ov01a10->sd); struct v4l2_fwnode_device_properties props; u32 vblank_min, vblank_max, vblank_default; struct v4l2_ctrl_handler *ctrl_hdlr; const struct ov01a10_mode *cur_mode; s64 exposure_max, h_blank; int ret = 0; int size; ret = v4l2_fwnode_device_parse(&client->dev, &props); if (ret) return ret; ctrl_hdlr = &ov01a10->ctrl_handler; ret = v4l2_ctrl_handler_init(ctrl_hdlr, 12); if (ret) return ret; cur_mode = ov01a10->cur_mode; size = ARRAY_SIZE(link_freq_menu_items); ov01a10->link_freq = v4l2_ctrl_new_int_menu(ctrl_hdlr, &ov01a10_ctrl_ops, V4L2_CID_LINK_FREQ, size - 1, 0, link_freq_menu_items); if (ov01a10->link_freq) ov01a10->link_freq->flags |= V4L2_CTRL_FLAG_READ_ONLY; ov01a10->pixel_rate = v4l2_ctrl_new_std(ctrl_hdlr, &ov01a10_ctrl_ops, V4L2_CID_PIXEL_RATE, 0, OV01A10_SCLK, 1, OV01A10_SCLK); vblank_min = cur_mode->vts_min - cur_mode->height; vblank_max = OV01A10_VTS_MAX - cur_mode->height; vblank_default = cur_mode->vts_def - cur_mode->height; ov01a10->vblank = v4l2_ctrl_new_std(ctrl_hdlr, &ov01a10_ctrl_ops, V4L2_CID_VBLANK, vblank_min, vblank_max, 1, vblank_default); h_blank = cur_mode->hts - cur_mode->width; ov01a10->hblank = v4l2_ctrl_new_std(ctrl_hdlr, &ov01a10_ctrl_ops, V4L2_CID_HBLANK, h_blank, h_blank, 1, h_blank); if (ov01a10->hblank) ov01a10->hblank->flags |= V4L2_CTRL_FLAG_READ_ONLY; v4l2_ctrl_new_std(ctrl_hdlr, &ov01a10_ctrl_ops, V4L2_CID_ANALOGUE_GAIN, OV01A10_ANAL_GAIN_MIN, OV01A10_ANAL_GAIN_MAX, OV01A10_ANAL_GAIN_STEP, OV01A10_ANAL_GAIN_MIN); v4l2_ctrl_new_std(ctrl_hdlr, &ov01a10_ctrl_ops, V4L2_CID_DIGITAL_GAIN, OV01A10_DGTL_GAIN_MIN, OV01A10_DGTL_GAIN_MAX, OV01A10_DGTL_GAIN_STEP, OV01A10_DGTL_GAIN_DEFAULT); exposure_max = cur_mode->vts_def - OV01A10_EXPOSURE_MAX_MARGIN; ov01a10->exposure = v4l2_ctrl_new_std(ctrl_hdlr, &ov01a10_ctrl_ops, V4L2_CID_EXPOSURE, OV01A10_EXPOSURE_MIN, exposure_max, OV01A10_EXPOSURE_STEP, exposure_max); v4l2_ctrl_new_std_menu_items(ctrl_hdlr, &ov01a10_ctrl_ops, V4L2_CID_TEST_PATTERN, ARRAY_SIZE(ov01a10_test_pattern_menu) - 1, 0, 0, ov01a10_test_pattern_menu); v4l2_ctrl_new_std(ctrl_hdlr, &ov01a10_ctrl_ops, V4L2_CID_HFLIP, 0, 1, 1, 0); v4l2_ctrl_new_std(ctrl_hdlr, &ov01a10_ctrl_ops, V4L2_CID_VFLIP, 0, 1, 1, 0); ret = v4l2_ctrl_new_fwnode_properties(ctrl_hdlr, &ov01a10_ctrl_ops, &props); if (ret) goto fail; if (ctrl_hdlr->error) { ret = ctrl_hdlr->error; goto fail; } ov01a10->sd.ctrl_handler = ctrl_hdlr; return 0; fail: v4l2_ctrl_handler_free(ctrl_hdlr); return ret; } static void ov01a10_update_pad_format(const struct ov01a10_mode *mode, struct v4l2_mbus_framefmt *fmt) { fmt->width = mode->width; fmt->height = mode->height; fmt->code = MEDIA_BUS_FMT_SBGGR10_1X10; fmt->field = V4L2_FIELD_NONE; fmt->colorspace = V4L2_COLORSPACE_RAW; } static int ov01a10_start_streaming(struct ov01a10 *ov01a10) { struct i2c_client *client = v4l2_get_subdevdata(&ov01a10->sd); const struct ov01a10_reg_list *reg_list; int link_freq_index; int ret = 0; link_freq_index = ov01a10->cur_mode->link_freq_index; reg_list = &link_freq_configs[link_freq_index].reg_list; ret = ov01a10_write_reg_list(ov01a10, reg_list); if (ret) { dev_err(&client->dev, "failed to set plls\n"); return ret; } reg_list = &ov01a10->cur_mode->reg_list; ret = ov01a10_write_reg_list(ov01a10, reg_list); if (ret) { dev_err(&client->dev, "failed to set mode\n"); return ret; } ret = __v4l2_ctrl_handler_setup(ov01a10->sd.ctrl_handler); if (ret) return ret; ret = ov01a10_write_reg(ov01a10, OV01A10_REG_MODE_SELECT, 1, OV01A10_MODE_STREAMING); if (ret) dev_err(&client->dev, "failed to start streaming\n"); return ret; } static void ov01a10_stop_streaming(struct ov01a10 *ov01a10) { struct i2c_client *client = v4l2_get_subdevdata(&ov01a10->sd); int ret = 0; ret = ov01a10_write_reg(ov01a10, OV01A10_REG_MODE_SELECT, 1, OV01A10_MODE_STANDBY); if (ret) dev_err(&client->dev, "failed to stop streaming\n"); } static int ov01a10_set_stream(struct v4l2_subdev *sd, int enable) { struct ov01a10 *ov01a10 = to_ov01a10(sd); struct i2c_client *client = v4l2_get_subdevdata(sd); struct v4l2_subdev_state *state; int ret = 0; state = v4l2_subdev_lock_and_get_active_state(sd); if (ov01a10->streaming == enable) goto unlock; if (enable) { ret = pm_runtime_resume_and_get(&client->dev); if (ret < 0) goto unlock; ret = ov01a10_start_streaming(ov01a10); if (ret) { pm_runtime_put(&client->dev); goto unlock; } goto done; } ov01a10_stop_streaming(ov01a10); pm_runtime_put(&client->dev); done: ov01a10->streaming = enable; unlock: v4l2_subdev_unlock_state(state); return ret; } static int __maybe_unused ov01a10_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct v4l2_subdev *sd = i2c_get_clientdata(client); struct ov01a10 *ov01a10 = to_ov01a10(sd); struct v4l2_subdev_state *state; state = v4l2_subdev_lock_and_get_active_state(sd); if (ov01a10->streaming) ov01a10_stop_streaming(ov01a10); v4l2_subdev_unlock_state(state); return 0; } static int __maybe_unused ov01a10_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct v4l2_subdev *sd = i2c_get_clientdata(client); struct ov01a10 *ov01a10 = to_ov01a10(sd); struct v4l2_subdev_state *state; int ret = 0; state = v4l2_subdev_lock_and_get_active_state(sd); if (!ov01a10->streaming) goto exit; ret = ov01a10_start_streaming(ov01a10); if (ret) { ov01a10->streaming = false; ov01a10_stop_streaming(ov01a10); } exit: v4l2_subdev_unlock_state(state); return ret; } static int ov01a10_set_format(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *fmt) { struct ov01a10 *ov01a10 = to_ov01a10(sd); const struct ov01a10_mode *mode; struct v4l2_mbus_framefmt *format; s32 vblank_def, h_blank; mode = v4l2_find_nearest_size(supported_modes, ARRAY_SIZE(supported_modes), width, height, fmt->format.width, fmt->format.height); ov01a10_update_pad_format(mode, &fmt->format); if (fmt->which == V4L2_SUBDEV_FORMAT_ACTIVE) { ov01a10->cur_mode = mode; __v4l2_ctrl_s_ctrl(ov01a10->link_freq, mode->link_freq_index); __v4l2_ctrl_s_ctrl_int64(ov01a10->pixel_rate, OV01A10_SCLK); vblank_def = mode->vts_def - mode->height; __v4l2_ctrl_modify_range(ov01a10->vblank, mode->vts_min - mode->height, OV01A10_VTS_MAX - mode->height, 1, vblank_def); __v4l2_ctrl_s_ctrl(ov01a10->vblank, vblank_def); h_blank = mode->hts - mode->width; __v4l2_ctrl_modify_range(ov01a10->hblank, h_blank, h_blank, 1, h_blank); } format = v4l2_subdev_get_pad_format(sd, sd_state, fmt->stream); *format = fmt->format; return 0; } static int ov01a10_init_cfg(struct v4l2_subdev *sd, struct v4l2_subdev_state *state) { struct v4l2_subdev_format fmt = { .which = V4L2_SUBDEV_FORMAT_TRY, .format = { .width = OV01A10_ACITVE_WIDTH, .height = OV01A10_ACITVE_HEIGHT, }, }; ov01a10_set_format(sd, state, &fmt); return 0; } static int ov01a10_enum_mbus_code(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_mbus_code_enum *code) { if (code->index > 0) return -EINVAL; code->code = MEDIA_BUS_FMT_SBGGR10_1X10; return 0; } static int ov01a10_enum_frame_size(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_frame_size_enum *fse) { if (fse->index >= ARRAY_SIZE(supported_modes) || fse->code != MEDIA_BUS_FMT_SBGGR10_1X10) return -EINVAL; fse->min_width = supported_modes[fse->index].width; fse->max_width = fse->min_width; fse->min_height = supported_modes[fse->index].height; fse->max_height = fse->min_height; return 0; } static int ov01a10_get_selection(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, struct v4l2_subdev_selection *sel) { if (sel->which != V4L2_SUBDEV_FORMAT_ACTIVE) return -EINVAL; switch (sel->target) { case V4L2_SEL_TGT_NATIVE_SIZE: case V4L2_SEL_TGT_CROP_BOUNDS: sel->r.top = 0; sel->r.left = 0; sel->r.width = OV01A10_PIXEL_ARRAY_WIDTH; sel->r.height = OV01A10_PIXEL_ARRAY_HEIGHT; return 0; case V4L2_SEL_TGT_CROP: case V4L2_SEL_TGT_CROP_DEFAULT: sel->r.top = (OV01A10_PIXEL_ARRAY_HEIGHT - OV01A10_ACITVE_HEIGHT) / 2; sel->r.left = (OV01A10_PIXEL_ARRAY_WIDTH - OV01A10_ACITVE_WIDTH) / 2; sel->r.width = OV01A10_ACITVE_WIDTH; sel->r.height = OV01A10_ACITVE_HEIGHT; return 0; } return -EINVAL; } static const struct v4l2_subdev_core_ops ov01a10_core_ops = { .log_status = v4l2_ctrl_subdev_log_status, .subscribe_event = v4l2_ctrl_subdev_subscribe_event, .unsubscribe_event = v4l2_event_subdev_unsubscribe, }; static const struct v4l2_subdev_video_ops ov01a10_video_ops = { .s_stream = ov01a10_set_stream, }; static const struct v4l2_subdev_pad_ops ov01a10_pad_ops = { .init_cfg = ov01a10_init_cfg, .set_fmt = ov01a10_set_format, .get_fmt = v4l2_subdev_get_fmt, .get_selection = ov01a10_get_selection, .enum_mbus_code = ov01a10_enum_mbus_code, .enum_frame_size = ov01a10_enum_frame_size, }; static const struct v4l2_subdev_ops ov01a10_subdev_ops = { .core = &ov01a10_core_ops, .video = &ov01a10_video_ops, .pad = &ov01a10_pad_ops, }; static const struct media_entity_operations ov01a10_subdev_entity_ops = { .link_validate = v4l2_subdev_link_validate, }; static int ov01a10_identify_module(struct ov01a10 *ov01a10) { struct i2c_client *client = v4l2_get_subdevdata(&ov01a10->sd); int ret; u32 val; ret = ov01a10_read_reg(ov01a10, OV01A10_REG_CHIP_ID, 3, &val); if (ret) return ret; if (val != OV01A10_CHIP_ID) { dev_err(&client->dev, "chip id mismatch: %x!=%x\n", OV01A10_CHIP_ID, val); return -EIO; } return 0; } static void ov01a10_remove(struct i2c_client *client) { struct v4l2_subdev *sd = i2c_get_clientdata(client); v4l2_async_unregister_subdev(sd); media_entity_cleanup(&sd->entity); v4l2_ctrl_handler_free(sd->ctrl_handler); pm_runtime_disable(&client->dev); } static int ov01a10_probe(struct i2c_client *client) { struct device *dev = &client->dev; struct ov01a10 *ov01a10; int ret = 0; ov01a10 = devm_kzalloc(dev, sizeof(*ov01a10), GFP_KERNEL); if (!ov01a10) return -ENOMEM; v4l2_i2c_subdev_init(&ov01a10->sd, client, &ov01a10_subdev_ops); ret = ov01a10_identify_module(ov01a10); if (ret) return dev_err_probe(dev, ret, "failed to find sensor\n"); ov01a10->cur_mode = &supported_modes[0]; ret = ov01a10_init_controls(ov01a10); if (ret) { dev_err(dev, "failed to init controls: %d\n", ret); return ret; } ov01a10->sd.state_lock = ov01a10->ctrl_handler.lock; ov01a10->sd.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE | V4L2_SUBDEV_FL_HAS_EVENTS; ov01a10->sd.entity.ops = &ov01a10_subdev_entity_ops; ov01a10->sd.entity.function = MEDIA_ENT_F_CAM_SENSOR; ov01a10->pad.flags = MEDIA_PAD_FL_SOURCE; ret = media_entity_pads_init(&ov01a10->sd.entity, 1, &ov01a10->pad); if (ret) { dev_err(dev, "Failed to init entity pads: %d\n", ret); goto err_handler_free; } ret = v4l2_subdev_init_finalize(&ov01a10->sd); if (ret) { dev_err(dev, "Failed to allocate subdev state: %d\n", ret); goto err_media_entity_cleanup; } ret = v4l2_async_register_subdev_sensor(&ov01a10->sd); if (ret < 0) { dev_err(dev, "Failed to register subdev: %d\n", ret); goto err_media_entity_cleanup; } pm_runtime_enable(dev); pm_runtime_idle(dev); return 0; err_media_entity_cleanup: media_entity_cleanup(&ov01a10->sd.entity); err_handler_free: v4l2_ctrl_handler_free(ov01a10->sd.ctrl_handler); return ret; } static const struct dev_pm_ops ov01a10_pm_ops = { SET_SYSTEM_SLEEP_PM_OPS(ov01a10_suspend, ov01a10_resume) }; #ifdef CONFIG_ACPI static const struct acpi_device_id ov01a10_acpi_ids[] = { { "OVTI01A0" }, { } }; MODULE_DEVICE_TABLE(acpi, ov01a10_acpi_ids); #endif static struct i2c_driver ov01a10_i2c_driver = { .driver = { .name = "ov01a10", .pm = &ov01a10_pm_ops, .acpi_match_table = ACPI_PTR(ov01a10_acpi_ids), }, .probe = ov01a10_probe, .remove = ov01a10_remove, }; module_i2c_driver(ov01a10_i2c_driver); MODULE_AUTHOR("Bingbu Cao <[email protected]>"); MODULE_AUTHOR("Wang Yating <[email protected]>"); MODULE_DESCRIPTION("OmniVision OV01A10 sensor driver"); MODULE_LICENSE("GPL");
linux-master
drivers/media/i2c/ov01a10.c
// SPDX-License-Identifier: GPL-2.0-or-later /* Driver for SAA6588 RDS decoder (c) 2005 Hans J. Koch */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/i2c.h> #include <linux/types.h> #include <linux/videodev2.h> #include <linux/init.h> #include <linux/errno.h> #include <linux/slab.h> #include <linux/poll.h> #include <linux/wait.h> #include <linux/uaccess.h> #include <media/i2c/saa6588.h> #include <media/v4l2-device.h> /* insmod options */ static unsigned int debug; static unsigned int xtal; static unsigned int mmbs; static unsigned int plvl; static unsigned int bufblocks = 100; module_param(debug, int, 0644); MODULE_PARM_DESC(debug, "enable debug messages"); module_param(xtal, int, 0); MODULE_PARM_DESC(xtal, "select oscillator frequency (0..3), default 0"); module_param(mmbs, int, 0); MODULE_PARM_DESC(mmbs, "enable MMBS mode: 0=off (default), 1=on"); module_param(plvl, int, 0); MODULE_PARM_DESC(plvl, "select pause level (0..3), default 0"); module_param(bufblocks, int, 0); MODULE_PARM_DESC(bufblocks, "number of buffered blocks, default 100"); MODULE_DESCRIPTION("v4l2 driver module for SAA6588 RDS decoder"); MODULE_AUTHOR("Hans J. Koch <[email protected]>"); MODULE_LICENSE("GPL"); /* ---------------------------------------------------------------------- */ #define UNSET (-1U) #define PREFIX "saa6588: " #define dprintk if (debug) printk struct saa6588 { struct v4l2_subdev sd; struct delayed_work work; spinlock_t lock; unsigned char *buffer; unsigned int buf_size; unsigned int rd_index; unsigned int wr_index; unsigned int block_count; unsigned char last_blocknum; wait_queue_head_t read_queue; int data_available_for_read; u8 sync; }; static inline struct saa6588 *to_saa6588(struct v4l2_subdev *sd) { return container_of(sd, struct saa6588, sd); } /* ---------------------------------------------------------------------- */ /* * SAA6588 defines */ /* Initialization and mode control byte (0w) */ /* bit 0+1 (DAC0/DAC1) */ #define cModeStandard 0x00 #define cModeFastPI 0x01 #define cModeReducedRequest 0x02 #define cModeInvalid 0x03 /* bit 2 (RBDS) */ #define cProcessingModeRDS 0x00 #define cProcessingModeRBDS 0x04 /* bit 3+4 (SYM0/SYM1) */ #define cErrCorrectionNone 0x00 #define cErrCorrection2Bits 0x08 #define cErrCorrection5Bits 0x10 #define cErrCorrectionNoneRBDS 0x18 /* bit 5 (NWSY) */ #define cSyncNormal 0x00 #define cSyncRestart 0x20 /* bit 6 (TSQD) */ #define cSigQualityDetectOFF 0x00 #define cSigQualityDetectON 0x40 /* bit 7 (SQCM) */ #define cSigQualityTriggered 0x00 #define cSigQualityContinous 0x80 /* Pause level and flywheel control byte (1w) */ /* bits 0..5 (FEB0..FEB5) */ #define cFlywheelMaxBlocksMask 0x3F #define cFlywheelDefault 0x20 /* bits 6+7 (PL0/PL1) */ #define cPauseLevel_11mV 0x00 #define cPauseLevel_17mV 0x40 #define cPauseLevel_27mV 0x80 #define cPauseLevel_43mV 0xC0 /* Pause time/oscillator frequency/quality detector control byte (1w) */ /* bits 0..4 (SQS0..SQS4) */ #define cQualityDetectSensMask 0x1F #define cQualityDetectDefault 0x0F /* bit 5 (SOSC) */ #define cSelectOscFreqOFF 0x00 #define cSelectOscFreqON 0x20 /* bit 6+7 (PTF0/PTF1) */ #define cOscFreq_4332kHz 0x00 #define cOscFreq_8664kHz 0x40 #define cOscFreq_12996kHz 0x80 #define cOscFreq_17328kHz 0xC0 /* ---------------------------------------------------------------------- */ static bool block_from_buf(struct saa6588 *s, unsigned char *buf) { int i; if (s->rd_index == s->wr_index) { if (debug > 2) dprintk(PREFIX "Read: buffer empty.\n"); return false; } if (debug > 2) { dprintk(PREFIX "Read: "); for (i = s->rd_index; i < s->rd_index + 3; i++) dprintk("0x%02x ", s->buffer[i]); } memcpy(buf, &s->buffer[s->rd_index], 3); s->rd_index += 3; if (s->rd_index >= s->buf_size) s->rd_index = 0; s->block_count--; if (debug > 2) dprintk("%d blocks total.\n", s->block_count); return true; } static void read_from_buf(struct saa6588 *s, struct saa6588_command *a) { unsigned char __user *buf_ptr = a->buffer; unsigned char buf[3]; unsigned long flags; unsigned int rd_blocks; unsigned int i; a->result = 0; if (!a->buffer) return; while (!a->nonblocking && !s->data_available_for_read) { int ret = wait_event_interruptible(s->read_queue, s->data_available_for_read); if (ret == -ERESTARTSYS) { a->result = -EINTR; return; } } rd_blocks = a->block_count; spin_lock_irqsave(&s->lock, flags); if (rd_blocks > s->block_count) rd_blocks = s->block_count; spin_unlock_irqrestore(&s->lock, flags); if (!rd_blocks) return; for (i = 0; i < rd_blocks; i++) { bool got_block; spin_lock_irqsave(&s->lock, flags); got_block = block_from_buf(s, buf); spin_unlock_irqrestore(&s->lock, flags); if (!got_block) break; if (copy_to_user(buf_ptr, buf, 3)) { a->result = -EFAULT; return; } buf_ptr += 3; a->result += 3; } spin_lock_irqsave(&s->lock, flags); s->data_available_for_read = (s->block_count > 0); spin_unlock_irqrestore(&s->lock, flags); } static void block_to_buf(struct saa6588 *s, unsigned char *blockbuf) { unsigned int i; if (debug > 3) dprintk(PREFIX "New block: "); for (i = 0; i < 3; ++i) { if (debug > 3) dprintk("0x%02x ", blockbuf[i]); s->buffer[s->wr_index] = blockbuf[i]; s->wr_index++; } if (s->wr_index >= s->buf_size) s->wr_index = 0; if (s->wr_index == s->rd_index) { s->rd_index += 3; if (s->rd_index >= s->buf_size) s->rd_index = 0; } else s->block_count++; if (debug > 3) dprintk("%d blocks total.\n", s->block_count); } static void saa6588_i2c_poll(struct saa6588 *s) { struct i2c_client *client = v4l2_get_subdevdata(&s->sd); unsigned long flags; unsigned char tmpbuf[6]; unsigned char blocknum; unsigned char tmp; /* Although we only need 3 bytes, we have to read at least 6. SAA6588 returns garbage otherwise. */ if (6 != i2c_master_recv(client, &tmpbuf[0], 6)) { if (debug > 1) dprintk(PREFIX "read error!\n"); return; } s->sync = tmpbuf[0] & 0x10; if (!s->sync) return; blocknum = tmpbuf[0] >> 5; if (blocknum == s->last_blocknum) { if (debug > 3) dprintk("Saw block %d again.\n", blocknum); return; } s->last_blocknum = blocknum; /* Byte order according to v4l2 specification: Byte 0: Least Significant Byte of RDS Block Byte 1: Most Significant Byte of RDS Block Byte 2 Bit 7: Error bit. Indicates that an uncorrectable error occurred during reception of this block. Bit 6: Corrected bit. Indicates that an error was corrected for this data block. Bits 5-3: Same as bits 0-2. Bits 2-0: Block number. SAA6588 byte order is Status-MSB-LSB, so we have to swap the first and the last of the 3 bytes block. */ swap(tmpbuf[2], tmpbuf[0]); /* Map 'Invalid block E' to 'Invalid Block' */ if (blocknum == 6) blocknum = V4L2_RDS_BLOCK_INVALID; /* And if are not in mmbs mode, then 'Block E' is also mapped to 'Invalid Block'. As far as I can tell MMBS is discontinued, and if there is ever a need to support E blocks, then please contact the linux-media mailinglist. */ else if (!mmbs && blocknum == 5) blocknum = V4L2_RDS_BLOCK_INVALID; tmp = blocknum; tmp |= blocknum << 3; /* Received offset == Offset Name (OK ?) */ if ((tmpbuf[2] & 0x03) == 0x03) tmp |= V4L2_RDS_BLOCK_ERROR; /* uncorrectable error */ else if ((tmpbuf[2] & 0x03) != 0x00) tmp |= V4L2_RDS_BLOCK_CORRECTED; /* corrected error */ tmpbuf[2] = tmp; /* Is this enough ? Should we also check other bits ? */ spin_lock_irqsave(&s->lock, flags); block_to_buf(s, tmpbuf); spin_unlock_irqrestore(&s->lock, flags); s->data_available_for_read = 1; wake_up_interruptible(&s->read_queue); } static void saa6588_work(struct work_struct *work) { struct saa6588 *s = container_of(work, struct saa6588, work.work); saa6588_i2c_poll(s); schedule_delayed_work(&s->work, msecs_to_jiffies(20)); } static void saa6588_configure(struct saa6588 *s) { struct i2c_client *client = v4l2_get_subdevdata(&s->sd); unsigned char buf[3]; int rc; buf[0] = cSyncRestart; if (mmbs) buf[0] |= cProcessingModeRBDS; buf[1] = cFlywheelDefault; switch (plvl) { case 0: buf[1] |= cPauseLevel_11mV; break; case 1: buf[1] |= cPauseLevel_17mV; break; case 2: buf[1] |= cPauseLevel_27mV; break; case 3: buf[1] |= cPauseLevel_43mV; break; default: /* nothing */ break; } buf[2] = cQualityDetectDefault | cSelectOscFreqON; switch (xtal) { case 0: buf[2] |= cOscFreq_4332kHz; break; case 1: buf[2] |= cOscFreq_8664kHz; break; case 2: buf[2] |= cOscFreq_12996kHz; break; case 3: buf[2] |= cOscFreq_17328kHz; break; default: /* nothing */ break; } dprintk(PREFIX "writing: 0w=0x%02x 1w=0x%02x 2w=0x%02x\n", buf[0], buf[1], buf[2]); rc = i2c_master_send(client, buf, 3); if (rc != 3) printk(PREFIX "i2c i/o error: rc == %d (should be 3)\n", rc); } /* ---------------------------------------------------------------------- */ static long saa6588_command(struct v4l2_subdev *sd, unsigned int cmd, void *arg) { struct saa6588 *s = to_saa6588(sd); struct saa6588_command *a = arg; switch (cmd) { /* --- close() for /dev/radio --- */ case SAA6588_CMD_CLOSE: s->data_available_for_read = 1; wake_up_interruptible(&s->read_queue); s->data_available_for_read = 0; a->result = 0; break; /* --- read() for /dev/radio --- */ case SAA6588_CMD_READ: read_from_buf(s, a); break; /* --- poll() for /dev/radio --- */ case SAA6588_CMD_POLL: a->poll_mask = 0; if (s->data_available_for_read) a->poll_mask |= EPOLLIN | EPOLLRDNORM; poll_wait(a->instance, &s->read_queue, a->event_list); break; default: /* nothing */ return -ENOIOCTLCMD; } return 0; } static int saa6588_g_tuner(struct v4l2_subdev *sd, struct v4l2_tuner *vt) { struct saa6588 *s = to_saa6588(sd); vt->capability |= V4L2_TUNER_CAP_RDS | V4L2_TUNER_CAP_RDS_BLOCK_IO; if (s->sync) vt->rxsubchans |= V4L2_TUNER_SUB_RDS; return 0; } static int saa6588_s_tuner(struct v4l2_subdev *sd, const struct v4l2_tuner *vt) { struct saa6588 *s = to_saa6588(sd); saa6588_configure(s); return 0; } /* ----------------------------------------------------------------------- */ static const struct v4l2_subdev_core_ops saa6588_core_ops = { .command = saa6588_command, }; static const struct v4l2_subdev_tuner_ops saa6588_tuner_ops = { .g_tuner = saa6588_g_tuner, .s_tuner = saa6588_s_tuner, }; static const struct v4l2_subdev_ops saa6588_ops = { .core = &saa6588_core_ops, .tuner = &saa6588_tuner_ops, }; /* ---------------------------------------------------------------------- */ static int saa6588_probe(struct i2c_client *client) { struct saa6588 *s; struct v4l2_subdev *sd; v4l_info(client, "saa6588 found @ 0x%x (%s)\n", client->addr << 1, client->adapter->name); s = devm_kzalloc(&client->dev, sizeof(*s), GFP_KERNEL); if (s == NULL) return -ENOMEM; s->buf_size = bufblocks * 3; s->buffer = devm_kzalloc(&client->dev, s->buf_size, GFP_KERNEL); if (s->buffer == NULL) return -ENOMEM; sd = &s->sd; v4l2_i2c_subdev_init(sd, client, &saa6588_ops); spin_lock_init(&s->lock); s->block_count = 0; s->wr_index = 0; s->rd_index = 0; s->last_blocknum = 0xff; init_waitqueue_head(&s->read_queue); s->data_available_for_read = 0; saa6588_configure(s); /* start polling via eventd */ INIT_DELAYED_WORK(&s->work, saa6588_work); schedule_delayed_work(&s->work, 0); return 0; } static void saa6588_remove(struct i2c_client *client) { struct v4l2_subdev *sd = i2c_get_clientdata(client); struct saa6588 *s = to_saa6588(sd); v4l2_device_unregister_subdev(sd); cancel_delayed_work_sync(&s->work); } /* ----------------------------------------------------------------------- */ static const struct i2c_device_id saa6588_id[] = { { "saa6588", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, saa6588_id); static struct i2c_driver saa6588_driver = { .driver = { .name = "saa6588", }, .probe = saa6588_probe, .remove = saa6588_remove, .id_table = saa6588_id, }; module_i2c_driver(saa6588_driver);
linux-master
drivers/media/i2c/saa6588.c
// SPDX-License-Identifier: GPL-2.0-only /* * Driver for MT9V022, MT9V024, MT9V032, and MT9V034 CMOS Image Sensors * * Copyright (C) 2010, Laurent Pinchart <[email protected]> * * Based on the MT9M001 driver, * * Copyright (C) 2008, Guennadi Liakhovetski <[email protected]> */ #include <linux/clk.h> #include <linux/delay.h> #include <linux/gpio/consumer.h> #include <linux/i2c.h> #include <linux/log2.h> #include <linux/mutex.h> #include <linux/of.h> #include <linux/of_graph.h> #include <linux/regmap.h> #include <linux/slab.h> #include <linux/videodev2.h> #include <linux/v4l2-mediabus.h> #include <linux/module.h> #include <media/i2c/mt9v032.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-device.h> #include <media/v4l2-fwnode.h> #include <media/v4l2-subdev.h> /* The first four rows are black rows. The active area spans 753x481 pixels. */ #define MT9V032_PIXEL_ARRAY_HEIGHT 485 #define MT9V032_PIXEL_ARRAY_WIDTH 753 #define MT9V032_SYSCLK_FREQ_DEF 26600000 #define MT9V032_CHIP_VERSION 0x00 #define MT9V032_CHIP_ID_REV1 0x1311 #define MT9V032_CHIP_ID_REV3 0x1313 #define MT9V034_CHIP_ID_REV1 0X1324 #define MT9V032_COLUMN_START 0x01 #define MT9V032_COLUMN_START_MIN 1 #define MT9V032_COLUMN_START_DEF 1 #define MT9V032_COLUMN_START_MAX 752 #define MT9V032_ROW_START 0x02 #define MT9V032_ROW_START_MIN 4 #define MT9V032_ROW_START_DEF 5 #define MT9V032_ROW_START_MAX 482 #define MT9V032_WINDOW_HEIGHT 0x03 #define MT9V032_WINDOW_HEIGHT_MIN 1 #define MT9V032_WINDOW_HEIGHT_DEF 480 #define MT9V032_WINDOW_HEIGHT_MAX 480 #define MT9V032_WINDOW_WIDTH 0x04 #define MT9V032_WINDOW_WIDTH_MIN 1 #define MT9V032_WINDOW_WIDTH_DEF 752 #define MT9V032_WINDOW_WIDTH_MAX 752 #define MT9V032_HORIZONTAL_BLANKING 0x05 #define MT9V032_HORIZONTAL_BLANKING_MIN 43 #define MT9V034_HORIZONTAL_BLANKING_MIN 61 #define MT9V032_HORIZONTAL_BLANKING_DEF 94 #define MT9V032_HORIZONTAL_BLANKING_MAX 1023 #define MT9V032_VERTICAL_BLANKING 0x06 #define MT9V032_VERTICAL_BLANKING_MIN 4 #define MT9V034_VERTICAL_BLANKING_MIN 2 #define MT9V032_VERTICAL_BLANKING_DEF 45 #define MT9V032_VERTICAL_BLANKING_MAX 3000 #define MT9V034_VERTICAL_BLANKING_MAX 32288 #define MT9V032_CHIP_CONTROL 0x07 #define MT9V032_CHIP_CONTROL_MASTER_MODE (1 << 3) #define MT9V032_CHIP_CONTROL_DOUT_ENABLE (1 << 7) #define MT9V032_CHIP_CONTROL_SEQUENTIAL (1 << 8) #define MT9V032_SHUTTER_WIDTH1 0x08 #define MT9V032_SHUTTER_WIDTH2 0x09 #define MT9V032_SHUTTER_WIDTH_CONTROL 0x0a #define MT9V032_TOTAL_SHUTTER_WIDTH 0x0b #define MT9V032_TOTAL_SHUTTER_WIDTH_MIN 1 #define MT9V034_TOTAL_SHUTTER_WIDTH_MIN 0 #define MT9V032_TOTAL_SHUTTER_WIDTH_DEF 480 #define MT9V032_TOTAL_SHUTTER_WIDTH_MAX 32767 #define MT9V034_TOTAL_SHUTTER_WIDTH_MAX 32765 #define MT9V032_RESET 0x0c #define MT9V032_READ_MODE 0x0d #define MT9V032_READ_MODE_ROW_BIN_MASK (3 << 0) #define MT9V032_READ_MODE_ROW_BIN_SHIFT 0 #define MT9V032_READ_MODE_COLUMN_BIN_MASK (3 << 2) #define MT9V032_READ_MODE_COLUMN_BIN_SHIFT 2 #define MT9V032_READ_MODE_ROW_FLIP (1 << 4) #define MT9V032_READ_MODE_COLUMN_FLIP (1 << 5) #define MT9V032_READ_MODE_DARK_COLUMNS (1 << 6) #define MT9V032_READ_MODE_DARK_ROWS (1 << 7) #define MT9V032_READ_MODE_RESERVED 0x0300 #define MT9V032_PIXEL_OPERATION_MODE 0x0f #define MT9V034_PIXEL_OPERATION_MODE_HDR (1 << 0) #define MT9V034_PIXEL_OPERATION_MODE_COLOR (1 << 1) #define MT9V032_PIXEL_OPERATION_MODE_COLOR (1 << 2) #define MT9V032_PIXEL_OPERATION_MODE_HDR (1 << 6) #define MT9V032_ANALOG_GAIN 0x35 #define MT9V032_ANALOG_GAIN_MIN 16 #define MT9V032_ANALOG_GAIN_DEF 16 #define MT9V032_ANALOG_GAIN_MAX 64 #define MT9V032_MAX_ANALOG_GAIN 0x36 #define MT9V032_MAX_ANALOG_GAIN_MAX 127 #define MT9V032_FRAME_DARK_AVERAGE 0x42 #define MT9V032_DARK_AVG_THRESH 0x46 #define MT9V032_DARK_AVG_LOW_THRESH_MASK (255 << 0) #define MT9V032_DARK_AVG_LOW_THRESH_SHIFT 0 #define MT9V032_DARK_AVG_HIGH_THRESH_MASK (255 << 8) #define MT9V032_DARK_AVG_HIGH_THRESH_SHIFT 8 #define MT9V032_ROW_NOISE_CORR_CONTROL 0x70 #define MT9V034_ROW_NOISE_CORR_ENABLE (1 << 0) #define MT9V034_ROW_NOISE_CORR_USE_BLK_AVG (1 << 1) #define MT9V032_ROW_NOISE_CORR_ENABLE (1 << 5) #define MT9V032_ROW_NOISE_CORR_USE_BLK_AVG (1 << 7) #define MT9V032_PIXEL_CLOCK 0x74 #define MT9V034_PIXEL_CLOCK 0x72 #define MT9V032_PIXEL_CLOCK_INV_LINE (1 << 0) #define MT9V032_PIXEL_CLOCK_INV_FRAME (1 << 1) #define MT9V032_PIXEL_CLOCK_XOR_LINE (1 << 2) #define MT9V032_PIXEL_CLOCK_CONT_LINE (1 << 3) #define MT9V032_PIXEL_CLOCK_INV_PXL_CLK (1 << 4) #define MT9V032_TEST_PATTERN 0x7f #define MT9V032_TEST_PATTERN_DATA_MASK (1023 << 0) #define MT9V032_TEST_PATTERN_DATA_SHIFT 0 #define MT9V032_TEST_PATTERN_USE_DATA (1 << 10) #define MT9V032_TEST_PATTERN_GRAY_MASK (3 << 11) #define MT9V032_TEST_PATTERN_GRAY_NONE (0 << 11) #define MT9V032_TEST_PATTERN_GRAY_VERTICAL (1 << 11) #define MT9V032_TEST_PATTERN_GRAY_HORIZONTAL (2 << 11) #define MT9V032_TEST_PATTERN_GRAY_DIAGONAL (3 << 11) #define MT9V032_TEST_PATTERN_ENABLE (1 << 13) #define MT9V032_TEST_PATTERN_FLIP (1 << 14) #define MT9V032_AEGC_DESIRED_BIN 0xa5 #define MT9V032_AEC_UPDATE_FREQUENCY 0xa6 #define MT9V032_AEC_LPF 0xa8 #define MT9V032_AGC_UPDATE_FREQUENCY 0xa9 #define MT9V032_AGC_LPF 0xaa #define MT9V032_AEC_AGC_ENABLE 0xaf #define MT9V032_AEC_ENABLE (1 << 0) #define MT9V032_AGC_ENABLE (1 << 1) #define MT9V034_AEC_MAX_SHUTTER_WIDTH 0xad #define MT9V032_AEC_MAX_SHUTTER_WIDTH 0xbd #define MT9V032_THERMAL_INFO 0xc1 enum mt9v032_model { MT9V032_MODEL_V022_COLOR, /* MT9V022IX7ATC */ MT9V032_MODEL_V022_MONO, /* MT9V022IX7ATM */ MT9V032_MODEL_V024_COLOR, /* MT9V024IA7XTC */ MT9V032_MODEL_V024_MONO, /* MT9V024IA7XTM */ MT9V032_MODEL_V032_COLOR, /* MT9V032C12STM */ MT9V032_MODEL_V032_MONO, /* MT9V032C12STC */ MT9V032_MODEL_V034_COLOR, MT9V032_MODEL_V034_MONO, }; struct mt9v032_model_version { unsigned int version; const char *name; }; struct mt9v032_model_data { unsigned int min_row_time; unsigned int min_hblank; unsigned int min_vblank; unsigned int max_vblank; unsigned int min_shutter; unsigned int max_shutter; unsigned int pclk_reg; unsigned int aec_max_shutter_reg; const struct v4l2_ctrl_config * const aec_max_shutter_v4l2_ctrl; }; struct mt9v032_model_info { const struct mt9v032_model_data *data; bool color; }; static const struct mt9v032_model_version mt9v032_versions[] = { { MT9V032_CHIP_ID_REV1, "MT9V022/MT9V032 rev1/2" }, { MT9V032_CHIP_ID_REV3, "MT9V022/MT9V032 rev3" }, { MT9V034_CHIP_ID_REV1, "MT9V024/MT9V034 rev1" }, }; struct mt9v032 { struct v4l2_subdev subdev; struct media_pad pad; struct v4l2_mbus_framefmt format; struct v4l2_rect crop; unsigned int hratio; unsigned int vratio; struct v4l2_ctrl_handler ctrls; struct { struct v4l2_ctrl *link_freq; struct v4l2_ctrl *pixel_rate; }; struct mutex power_lock; int power_count; struct regmap *regmap; struct clk *clk; struct gpio_desc *reset_gpio; struct gpio_desc *standby_gpio; struct mt9v032_platform_data *pdata; const struct mt9v032_model_info *model; const struct mt9v032_model_version *version; u32 sysclk; u16 aec_agc; u16 hblank; struct { struct v4l2_ctrl *test_pattern; struct v4l2_ctrl *test_pattern_color; }; }; static struct mt9v032 *to_mt9v032(struct v4l2_subdev *sd) { return container_of(sd, struct mt9v032, subdev); } static int mt9v032_update_aec_agc(struct mt9v032 *mt9v032, u16 which, int enable) { struct regmap *map = mt9v032->regmap; u16 value = mt9v032->aec_agc; int ret; if (enable) value |= which; else value &= ~which; ret = regmap_write(map, MT9V032_AEC_AGC_ENABLE, value); if (ret < 0) return ret; mt9v032->aec_agc = value; return 0; } static int mt9v032_update_hblank(struct mt9v032 *mt9v032) { struct v4l2_rect *crop = &mt9v032->crop; unsigned int min_hblank = mt9v032->model->data->min_hblank; unsigned int hblank; if (mt9v032->version->version == MT9V034_CHIP_ID_REV1) min_hblank += (mt9v032->hratio - 1) * 10; min_hblank = max_t(int, mt9v032->model->data->min_row_time - crop->width, min_hblank); hblank = max_t(unsigned int, mt9v032->hblank, min_hblank); return regmap_write(mt9v032->regmap, MT9V032_HORIZONTAL_BLANKING, hblank); } static int mt9v032_power_on(struct mt9v032 *mt9v032) { struct regmap *map = mt9v032->regmap; int ret; gpiod_set_value_cansleep(mt9v032->reset_gpio, 1); ret = clk_set_rate(mt9v032->clk, mt9v032->sysclk); if (ret < 0) return ret; /* System clock has to be enabled before releasing the reset */ ret = clk_prepare_enable(mt9v032->clk); if (ret) return ret; udelay(1); if (mt9v032->reset_gpio) { gpiod_set_value_cansleep(mt9v032->reset_gpio, 0); /* After releasing reset we need to wait 10 clock cycles * before accessing the sensor over I2C. As the minimum SYSCLK * frequency is 13MHz, waiting 1µs will be enough in the worst * case. */ udelay(1); } /* Reset the chip and stop data read out */ ret = regmap_write(map, MT9V032_RESET, 1); if (ret < 0) goto err; ret = regmap_write(map, MT9V032_RESET, 0); if (ret < 0) goto err; ret = regmap_write(map, MT9V032_CHIP_CONTROL, MT9V032_CHIP_CONTROL_MASTER_MODE); if (ret < 0) goto err; return 0; err: clk_disable_unprepare(mt9v032->clk); return ret; } static void mt9v032_power_off(struct mt9v032 *mt9v032) { clk_disable_unprepare(mt9v032->clk); } static int __mt9v032_set_power(struct mt9v032 *mt9v032, bool on) { struct regmap *map = mt9v032->regmap; int ret; if (!on) { mt9v032_power_off(mt9v032); return 0; } ret = mt9v032_power_on(mt9v032); if (ret < 0) return ret; /* Configure the pixel clock polarity */ if (mt9v032->pdata && mt9v032->pdata->clk_pol) { ret = regmap_write(map, mt9v032->model->data->pclk_reg, MT9V032_PIXEL_CLOCK_INV_PXL_CLK); if (ret < 0) return ret; } /* Disable the noise correction algorithm and restore the controls. */ ret = regmap_write(map, MT9V032_ROW_NOISE_CORR_CONTROL, 0); if (ret < 0) return ret; return v4l2_ctrl_handler_setup(&mt9v032->ctrls); } /* ----------------------------------------------------------------------------- * V4L2 subdev video operations */ static struct v4l2_mbus_framefmt * __mt9v032_get_pad_format(struct mt9v032 *mt9v032, struct v4l2_subdev_state *sd_state, unsigned int pad, enum v4l2_subdev_format_whence which) { switch (which) { case V4L2_SUBDEV_FORMAT_TRY: return v4l2_subdev_get_try_format(&mt9v032->subdev, sd_state, pad); case V4L2_SUBDEV_FORMAT_ACTIVE: return &mt9v032->format; default: return NULL; } } static struct v4l2_rect * __mt9v032_get_pad_crop(struct mt9v032 *mt9v032, struct v4l2_subdev_state *sd_state, unsigned int pad, enum v4l2_subdev_format_whence which) { switch (which) { case V4L2_SUBDEV_FORMAT_TRY: return v4l2_subdev_get_try_crop(&mt9v032->subdev, sd_state, pad); case V4L2_SUBDEV_FORMAT_ACTIVE: return &mt9v032->crop; default: return NULL; } } static int mt9v032_s_stream(struct v4l2_subdev *subdev, int enable) { const u16 mode = MT9V032_CHIP_CONTROL_DOUT_ENABLE | MT9V032_CHIP_CONTROL_SEQUENTIAL; struct mt9v032 *mt9v032 = to_mt9v032(subdev); struct v4l2_rect *crop = &mt9v032->crop; struct regmap *map = mt9v032->regmap; unsigned int hbin; unsigned int vbin; int ret; if (!enable) return regmap_update_bits(map, MT9V032_CHIP_CONTROL, mode, 0); /* Configure the window size and row/column bin */ hbin = fls(mt9v032->hratio) - 1; vbin = fls(mt9v032->vratio) - 1; ret = regmap_update_bits(map, MT9V032_READ_MODE, ~MT9V032_READ_MODE_RESERVED, hbin << MT9V032_READ_MODE_COLUMN_BIN_SHIFT | vbin << MT9V032_READ_MODE_ROW_BIN_SHIFT); if (ret < 0) return ret; ret = regmap_write(map, MT9V032_COLUMN_START, crop->left); if (ret < 0) return ret; ret = regmap_write(map, MT9V032_ROW_START, crop->top); if (ret < 0) return ret; ret = regmap_write(map, MT9V032_WINDOW_WIDTH, crop->width); if (ret < 0) return ret; ret = regmap_write(map, MT9V032_WINDOW_HEIGHT, crop->height); if (ret < 0) return ret; ret = mt9v032_update_hblank(mt9v032); if (ret < 0) return ret; /* Switch to master "normal" mode */ return regmap_update_bits(map, MT9V032_CHIP_CONTROL, mode, mode); } static int mt9v032_enum_mbus_code(struct v4l2_subdev *subdev, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_mbus_code_enum *code) { struct mt9v032 *mt9v032 = to_mt9v032(subdev); if (code->index > 0) return -EINVAL; code->code = mt9v032->format.code; return 0; } static int mt9v032_enum_frame_size(struct v4l2_subdev *subdev, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_frame_size_enum *fse) { struct mt9v032 *mt9v032 = to_mt9v032(subdev); if (fse->index >= 3) return -EINVAL; if (mt9v032->format.code != fse->code) return -EINVAL; fse->min_width = MT9V032_WINDOW_WIDTH_DEF / (1 << fse->index); fse->max_width = fse->min_width; fse->min_height = MT9V032_WINDOW_HEIGHT_DEF / (1 << fse->index); fse->max_height = fse->min_height; return 0; } static int mt9v032_get_format(struct v4l2_subdev *subdev, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *format) { struct mt9v032 *mt9v032 = to_mt9v032(subdev); format->format = *__mt9v032_get_pad_format(mt9v032, sd_state, format->pad, format->which); return 0; } static void mt9v032_configure_pixel_rate(struct mt9v032 *mt9v032) { struct i2c_client *client = v4l2_get_subdevdata(&mt9v032->subdev); int ret; ret = v4l2_ctrl_s_ctrl_int64(mt9v032->pixel_rate, mt9v032->sysclk / mt9v032->hratio); if (ret < 0) dev_warn(&client->dev, "failed to set pixel rate (%d)\n", ret); } static unsigned int mt9v032_calc_ratio(unsigned int input, unsigned int output) { /* Compute the power-of-two binning factor closest to the input size to * output size ratio. Given that the output size is bounded by input/4 * and input, a generic implementation would be an ineffective luxury. */ if (output * 3 > input * 2) return 1; if (output * 3 > input) return 2; return 4; } static int mt9v032_set_format(struct v4l2_subdev *subdev, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *format) { struct mt9v032 *mt9v032 = to_mt9v032(subdev); struct v4l2_mbus_framefmt *__format; struct v4l2_rect *__crop; unsigned int width; unsigned int height; unsigned int hratio; unsigned int vratio; __crop = __mt9v032_get_pad_crop(mt9v032, sd_state, format->pad, format->which); /* Clamp the width and height to avoid dividing by zero. */ width = clamp(ALIGN(format->format.width, 2), max_t(unsigned int, __crop->width / 4, MT9V032_WINDOW_WIDTH_MIN), __crop->width); height = clamp(ALIGN(format->format.height, 2), max_t(unsigned int, __crop->height / 4, MT9V032_WINDOW_HEIGHT_MIN), __crop->height); hratio = mt9v032_calc_ratio(__crop->width, width); vratio = mt9v032_calc_ratio(__crop->height, height); __format = __mt9v032_get_pad_format(mt9v032, sd_state, format->pad, format->which); __format->width = __crop->width / hratio; __format->height = __crop->height / vratio; if (format->which == V4L2_SUBDEV_FORMAT_ACTIVE) { mt9v032->hratio = hratio; mt9v032->vratio = vratio; mt9v032_configure_pixel_rate(mt9v032); } format->format = *__format; return 0; } static int mt9v032_get_selection(struct v4l2_subdev *subdev, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_selection *sel) { struct mt9v032 *mt9v032 = to_mt9v032(subdev); if (sel->target != V4L2_SEL_TGT_CROP) return -EINVAL; sel->r = *__mt9v032_get_pad_crop(mt9v032, sd_state, sel->pad, sel->which); return 0; } static int mt9v032_set_selection(struct v4l2_subdev *subdev, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_selection *sel) { struct mt9v032 *mt9v032 = to_mt9v032(subdev); struct v4l2_mbus_framefmt *__format; struct v4l2_rect *__crop; struct v4l2_rect rect; if (sel->target != V4L2_SEL_TGT_CROP) return -EINVAL; /* Clamp the crop rectangle boundaries and align them to a non multiple * of 2 pixels to ensure a GRBG Bayer pattern. */ rect.left = clamp(ALIGN(sel->r.left + 1, 2) - 1, MT9V032_COLUMN_START_MIN, MT9V032_COLUMN_START_MAX); rect.top = clamp(ALIGN(sel->r.top + 1, 2) - 1, MT9V032_ROW_START_MIN, MT9V032_ROW_START_MAX); rect.width = clamp_t(unsigned int, ALIGN(sel->r.width, 2), MT9V032_WINDOW_WIDTH_MIN, MT9V032_WINDOW_WIDTH_MAX); rect.height = clamp_t(unsigned int, ALIGN(sel->r.height, 2), MT9V032_WINDOW_HEIGHT_MIN, MT9V032_WINDOW_HEIGHT_MAX); rect.width = min_t(unsigned int, rect.width, MT9V032_PIXEL_ARRAY_WIDTH - rect.left); rect.height = min_t(unsigned int, rect.height, MT9V032_PIXEL_ARRAY_HEIGHT - rect.top); __crop = __mt9v032_get_pad_crop(mt9v032, sd_state, sel->pad, sel->which); if (rect.width != __crop->width || rect.height != __crop->height) { /* Reset the output image size if the crop rectangle size has * been modified. */ __format = __mt9v032_get_pad_format(mt9v032, sd_state, sel->pad, sel->which); __format->width = rect.width; __format->height = rect.height; if (sel->which == V4L2_SUBDEV_FORMAT_ACTIVE) { mt9v032->hratio = 1; mt9v032->vratio = 1; mt9v032_configure_pixel_rate(mt9v032); } } *__crop = rect; sel->r = rect; return 0; } /* ----------------------------------------------------------------------------- * V4L2 subdev control operations */ #define V4L2_CID_TEST_PATTERN_COLOR (V4L2_CID_USER_BASE | 0x1001) /* * Value between 1 and 64 to set the desired bin. This is effectively a measure * of how bright the image is supposed to be. Both AGC and AEC try to reach * this. */ #define V4L2_CID_AEGC_DESIRED_BIN (V4L2_CID_USER_BASE | 0x1002) /* * LPF is the low pass filter capability of the chip. Both AEC and AGC have * this setting. This limits the speed in which AGC/AEC adjust their settings. * Possible values are 0-2. 0 means no LPF. For 1 and 2 this equation is used: * * if |(calculated new exp - current exp)| > (current exp / 4) * next exp = calculated new exp * else * next exp = current exp + ((calculated new exp - current exp) / 2^LPF) */ #define V4L2_CID_AEC_LPF (V4L2_CID_USER_BASE | 0x1003) #define V4L2_CID_AGC_LPF (V4L2_CID_USER_BASE | 0x1004) /* * Value between 0 and 15. This is the number of frames being skipped before * updating the auto exposure/gain. */ #define V4L2_CID_AEC_UPDATE_INTERVAL (V4L2_CID_USER_BASE | 0x1005) #define V4L2_CID_AGC_UPDATE_INTERVAL (V4L2_CID_USER_BASE | 0x1006) /* * Maximum shutter width used for AEC. */ #define V4L2_CID_AEC_MAX_SHUTTER_WIDTH (V4L2_CID_USER_BASE | 0x1007) static int mt9v032_s_ctrl(struct v4l2_ctrl *ctrl) { struct mt9v032 *mt9v032 = container_of(ctrl->handler, struct mt9v032, ctrls); struct regmap *map = mt9v032->regmap; u32 freq; u16 data; switch (ctrl->id) { case V4L2_CID_AUTOGAIN: return mt9v032_update_aec_agc(mt9v032, MT9V032_AGC_ENABLE, ctrl->val); case V4L2_CID_GAIN: return regmap_write(map, MT9V032_ANALOG_GAIN, ctrl->val); case V4L2_CID_EXPOSURE_AUTO: return mt9v032_update_aec_agc(mt9v032, MT9V032_AEC_ENABLE, !ctrl->val); case V4L2_CID_EXPOSURE: return regmap_write(map, MT9V032_TOTAL_SHUTTER_WIDTH, ctrl->val); case V4L2_CID_HBLANK: mt9v032->hblank = ctrl->val; return mt9v032_update_hblank(mt9v032); case V4L2_CID_VBLANK: return regmap_write(map, MT9V032_VERTICAL_BLANKING, ctrl->val); case V4L2_CID_PIXEL_RATE: case V4L2_CID_LINK_FREQ: if (mt9v032->link_freq == NULL) break; freq = mt9v032->pdata->link_freqs[mt9v032->link_freq->val]; *mt9v032->pixel_rate->p_new.p_s64 = freq; mt9v032->sysclk = freq; break; case V4L2_CID_TEST_PATTERN: switch (mt9v032->test_pattern->val) { case 0: data = 0; break; case 1: data = MT9V032_TEST_PATTERN_GRAY_VERTICAL | MT9V032_TEST_PATTERN_ENABLE; break; case 2: data = MT9V032_TEST_PATTERN_GRAY_HORIZONTAL | MT9V032_TEST_PATTERN_ENABLE; break; case 3: data = MT9V032_TEST_PATTERN_GRAY_DIAGONAL | MT9V032_TEST_PATTERN_ENABLE; break; default: data = (mt9v032->test_pattern_color->val << MT9V032_TEST_PATTERN_DATA_SHIFT) | MT9V032_TEST_PATTERN_USE_DATA | MT9V032_TEST_PATTERN_ENABLE | MT9V032_TEST_PATTERN_FLIP; break; } return regmap_write(map, MT9V032_TEST_PATTERN, data); case V4L2_CID_AEGC_DESIRED_BIN: return regmap_write(map, MT9V032_AEGC_DESIRED_BIN, ctrl->val); case V4L2_CID_AEC_LPF: return regmap_write(map, MT9V032_AEC_LPF, ctrl->val); case V4L2_CID_AGC_LPF: return regmap_write(map, MT9V032_AGC_LPF, ctrl->val); case V4L2_CID_AEC_UPDATE_INTERVAL: return regmap_write(map, MT9V032_AEC_UPDATE_FREQUENCY, ctrl->val); case V4L2_CID_AGC_UPDATE_INTERVAL: return regmap_write(map, MT9V032_AGC_UPDATE_FREQUENCY, ctrl->val); case V4L2_CID_AEC_MAX_SHUTTER_WIDTH: return regmap_write(map, mt9v032->model->data->aec_max_shutter_reg, ctrl->val); } return 0; } static const struct v4l2_ctrl_ops mt9v032_ctrl_ops = { .s_ctrl = mt9v032_s_ctrl, }; static const char * const mt9v032_test_pattern_menu[] = { "Disabled", "Gray Vertical Shade", "Gray Horizontal Shade", "Gray Diagonal Shade", "Plain", }; static const struct v4l2_ctrl_config mt9v032_test_pattern_color = { .ops = &mt9v032_ctrl_ops, .id = V4L2_CID_TEST_PATTERN_COLOR, .type = V4L2_CTRL_TYPE_INTEGER, .name = "Test Pattern Color", .min = 0, .max = 1023, .step = 1, .def = 0, .flags = 0, }; static const struct v4l2_ctrl_config mt9v032_aegc_controls[] = { { .ops = &mt9v032_ctrl_ops, .id = V4L2_CID_AEGC_DESIRED_BIN, .type = V4L2_CTRL_TYPE_INTEGER, .name = "AEC/AGC Desired Bin", .min = 1, .max = 64, .step = 1, .def = 58, .flags = 0, }, { .ops = &mt9v032_ctrl_ops, .id = V4L2_CID_AEC_LPF, .type = V4L2_CTRL_TYPE_INTEGER, .name = "AEC Low Pass Filter", .min = 0, .max = 2, .step = 1, .def = 0, .flags = 0, }, { .ops = &mt9v032_ctrl_ops, .id = V4L2_CID_AGC_LPF, .type = V4L2_CTRL_TYPE_INTEGER, .name = "AGC Low Pass Filter", .min = 0, .max = 2, .step = 1, .def = 2, .flags = 0, }, { .ops = &mt9v032_ctrl_ops, .id = V4L2_CID_AEC_UPDATE_INTERVAL, .type = V4L2_CTRL_TYPE_INTEGER, .name = "AEC Update Interval", .min = 0, .max = 16, .step = 1, .def = 2, .flags = 0, }, { .ops = &mt9v032_ctrl_ops, .id = V4L2_CID_AGC_UPDATE_INTERVAL, .type = V4L2_CTRL_TYPE_INTEGER, .name = "AGC Update Interval", .min = 0, .max = 16, .step = 1, .def = 2, .flags = 0, } }; static const struct v4l2_ctrl_config mt9v032_aec_max_shutter_width = { .ops = &mt9v032_ctrl_ops, .id = V4L2_CID_AEC_MAX_SHUTTER_WIDTH, .type = V4L2_CTRL_TYPE_INTEGER, .name = "AEC Max Shutter Width", .min = 1, .max = 2047, .step = 1, .def = 480, .flags = 0, }; static const struct v4l2_ctrl_config mt9v034_aec_max_shutter_width = { .ops = &mt9v032_ctrl_ops, .id = V4L2_CID_AEC_MAX_SHUTTER_WIDTH, .type = V4L2_CTRL_TYPE_INTEGER, .name = "AEC Max Shutter Width", .min = 1, .max = 32765, .step = 1, .def = 480, .flags = 0, }; /* ----------------------------------------------------------------------------- * V4L2 subdev core operations */ static int mt9v032_set_power(struct v4l2_subdev *subdev, int on) { struct mt9v032 *mt9v032 = to_mt9v032(subdev); int ret = 0; mutex_lock(&mt9v032->power_lock); /* If the power count is modified from 0 to != 0 or from != 0 to 0, * update the power state. */ if (mt9v032->power_count == !on) { ret = __mt9v032_set_power(mt9v032, !!on); if (ret < 0) goto done; } /* Update the power count. */ mt9v032->power_count += on ? 1 : -1; WARN_ON(mt9v032->power_count < 0); done: mutex_unlock(&mt9v032->power_lock); return ret; } /* ----------------------------------------------------------------------------- * V4L2 subdev internal operations */ static int mt9v032_registered(struct v4l2_subdev *subdev) { struct i2c_client *client = v4l2_get_subdevdata(subdev); struct mt9v032 *mt9v032 = to_mt9v032(subdev); unsigned int i; u32 version; int ret; dev_info(&client->dev, "Probing MT9V032 at address 0x%02x\n", client->addr); ret = mt9v032_power_on(mt9v032); if (ret < 0) { dev_err(&client->dev, "MT9V032 power up failed\n"); return ret; } /* Read and check the sensor version */ ret = regmap_read(mt9v032->regmap, MT9V032_CHIP_VERSION, &version); mt9v032_power_off(mt9v032); if (ret < 0) { dev_err(&client->dev, "Failed reading chip version\n"); return ret; } for (i = 0; i < ARRAY_SIZE(mt9v032_versions); ++i) { if (mt9v032_versions[i].version == version) { mt9v032->version = &mt9v032_versions[i]; break; } } if (mt9v032->version == NULL) { dev_err(&client->dev, "Unsupported chip version 0x%04x\n", version); return -ENODEV; } dev_info(&client->dev, "%s detected at address 0x%02x\n", mt9v032->version->name, client->addr); mt9v032_configure_pixel_rate(mt9v032); return ret; } static int mt9v032_open(struct v4l2_subdev *subdev, struct v4l2_subdev_fh *fh) { struct mt9v032 *mt9v032 = to_mt9v032(subdev); struct v4l2_mbus_framefmt *format; struct v4l2_rect *crop; crop = v4l2_subdev_get_try_crop(subdev, fh->state, 0); crop->left = MT9V032_COLUMN_START_DEF; crop->top = MT9V032_ROW_START_DEF; crop->width = MT9V032_WINDOW_WIDTH_DEF; crop->height = MT9V032_WINDOW_HEIGHT_DEF; format = v4l2_subdev_get_try_format(subdev, fh->state, 0); if (mt9v032->model->color) format->code = MEDIA_BUS_FMT_SGRBG10_1X10; else format->code = MEDIA_BUS_FMT_Y10_1X10; format->width = MT9V032_WINDOW_WIDTH_DEF; format->height = MT9V032_WINDOW_HEIGHT_DEF; format->field = V4L2_FIELD_NONE; format->colorspace = V4L2_COLORSPACE_SRGB; return mt9v032_set_power(subdev, 1); } static int mt9v032_close(struct v4l2_subdev *subdev, struct v4l2_subdev_fh *fh) { return mt9v032_set_power(subdev, 0); } static const struct v4l2_subdev_core_ops mt9v032_subdev_core_ops = { .s_power = mt9v032_set_power, }; static const struct v4l2_subdev_video_ops mt9v032_subdev_video_ops = { .s_stream = mt9v032_s_stream, }; static const struct v4l2_subdev_pad_ops mt9v032_subdev_pad_ops = { .enum_mbus_code = mt9v032_enum_mbus_code, .enum_frame_size = mt9v032_enum_frame_size, .get_fmt = mt9v032_get_format, .set_fmt = mt9v032_set_format, .get_selection = mt9v032_get_selection, .set_selection = mt9v032_set_selection, }; static const struct v4l2_subdev_ops mt9v032_subdev_ops = { .core = &mt9v032_subdev_core_ops, .video = &mt9v032_subdev_video_ops, .pad = &mt9v032_subdev_pad_ops, }; static const struct v4l2_subdev_internal_ops mt9v032_subdev_internal_ops = { .registered = mt9v032_registered, .open = mt9v032_open, .close = mt9v032_close, }; static const struct regmap_config mt9v032_regmap_config = { .reg_bits = 8, .val_bits = 16, .max_register = 0xff, .cache_type = REGCACHE_RBTREE, }; /* ----------------------------------------------------------------------------- * Driver initialization and probing */ static struct mt9v032_platform_data * mt9v032_get_pdata(struct i2c_client *client) { struct mt9v032_platform_data *pdata = NULL; struct v4l2_fwnode_endpoint endpoint = { .bus_type = 0 }; struct device_node *np; struct property *prop; if (!IS_ENABLED(CONFIG_OF) || !client->dev.of_node) return client->dev.platform_data; np = of_graph_get_next_endpoint(client->dev.of_node, NULL); if (!np) return NULL; if (v4l2_fwnode_endpoint_parse(of_fwnode_handle(np), &endpoint) < 0) goto done; pdata = devm_kzalloc(&client->dev, sizeof(*pdata), GFP_KERNEL); if (!pdata) goto done; prop = of_find_property(np, "link-frequencies", NULL); if (prop) { u64 *link_freqs; size_t size = prop->length / sizeof(*link_freqs); link_freqs = devm_kcalloc(&client->dev, size, sizeof(*link_freqs), GFP_KERNEL); if (!link_freqs) goto done; if (of_property_read_u64_array(np, "link-frequencies", link_freqs, size) < 0) goto done; pdata->link_freqs = link_freqs; pdata->link_def_freq = link_freqs[0]; } pdata->clk_pol = !!(endpoint.bus.parallel.flags & V4L2_MBUS_PCLK_SAMPLE_RISING); done: of_node_put(np); return pdata; } static int mt9v032_probe(struct i2c_client *client) { const struct i2c_device_id *did = i2c_client_get_device_id(client); struct mt9v032_platform_data *pdata = mt9v032_get_pdata(client); struct mt9v032 *mt9v032; unsigned int i; int ret; mt9v032 = devm_kzalloc(&client->dev, sizeof(*mt9v032), GFP_KERNEL); if (!mt9v032) return -ENOMEM; mt9v032->regmap = devm_regmap_init_i2c(client, &mt9v032_regmap_config); if (IS_ERR(mt9v032->regmap)) return PTR_ERR(mt9v032->regmap); mt9v032->clk = devm_clk_get(&client->dev, NULL); if (IS_ERR(mt9v032->clk)) return PTR_ERR(mt9v032->clk); mt9v032->reset_gpio = devm_gpiod_get_optional(&client->dev, "reset", GPIOD_OUT_HIGH); if (IS_ERR(mt9v032->reset_gpio)) return PTR_ERR(mt9v032->reset_gpio); mt9v032->standby_gpio = devm_gpiod_get_optional(&client->dev, "standby", GPIOD_OUT_LOW); if (IS_ERR(mt9v032->standby_gpio)) return PTR_ERR(mt9v032->standby_gpio); mutex_init(&mt9v032->power_lock); mt9v032->pdata = pdata; mt9v032->model = (const void *)did->driver_data; v4l2_ctrl_handler_init(&mt9v032->ctrls, 11 + ARRAY_SIZE(mt9v032_aegc_controls)); v4l2_ctrl_new_std(&mt9v032->ctrls, &mt9v032_ctrl_ops, V4L2_CID_AUTOGAIN, 0, 1, 1, 1); v4l2_ctrl_new_std(&mt9v032->ctrls, &mt9v032_ctrl_ops, V4L2_CID_GAIN, MT9V032_ANALOG_GAIN_MIN, MT9V032_ANALOG_GAIN_MAX, 1, MT9V032_ANALOG_GAIN_DEF); v4l2_ctrl_new_std_menu(&mt9v032->ctrls, &mt9v032_ctrl_ops, V4L2_CID_EXPOSURE_AUTO, V4L2_EXPOSURE_MANUAL, 0, V4L2_EXPOSURE_AUTO); v4l2_ctrl_new_std(&mt9v032->ctrls, &mt9v032_ctrl_ops, V4L2_CID_EXPOSURE, mt9v032->model->data->min_shutter, mt9v032->model->data->max_shutter, 1, MT9V032_TOTAL_SHUTTER_WIDTH_DEF); v4l2_ctrl_new_std(&mt9v032->ctrls, &mt9v032_ctrl_ops, V4L2_CID_HBLANK, mt9v032->model->data->min_hblank, MT9V032_HORIZONTAL_BLANKING_MAX, 1, MT9V032_HORIZONTAL_BLANKING_DEF); v4l2_ctrl_new_std(&mt9v032->ctrls, &mt9v032_ctrl_ops, V4L2_CID_VBLANK, mt9v032->model->data->min_vblank, mt9v032->model->data->max_vblank, 1, MT9V032_VERTICAL_BLANKING_DEF); mt9v032->test_pattern = v4l2_ctrl_new_std_menu_items(&mt9v032->ctrls, &mt9v032_ctrl_ops, V4L2_CID_TEST_PATTERN, ARRAY_SIZE(mt9v032_test_pattern_menu) - 1, 0, 0, mt9v032_test_pattern_menu); mt9v032->test_pattern_color = v4l2_ctrl_new_custom(&mt9v032->ctrls, &mt9v032_test_pattern_color, NULL); v4l2_ctrl_new_custom(&mt9v032->ctrls, mt9v032->model->data->aec_max_shutter_v4l2_ctrl, NULL); for (i = 0; i < ARRAY_SIZE(mt9v032_aegc_controls); ++i) v4l2_ctrl_new_custom(&mt9v032->ctrls, &mt9v032_aegc_controls[i], NULL); v4l2_ctrl_cluster(2, &mt9v032->test_pattern); mt9v032->pixel_rate = v4l2_ctrl_new_std(&mt9v032->ctrls, &mt9v032_ctrl_ops, V4L2_CID_PIXEL_RATE, 1, INT_MAX, 1, 1); if (pdata && pdata->link_freqs) { unsigned int def = 0; for (i = 0; pdata->link_freqs[i]; ++i) { if (pdata->link_freqs[i] == pdata->link_def_freq) def = i; } mt9v032->link_freq = v4l2_ctrl_new_int_menu(&mt9v032->ctrls, &mt9v032_ctrl_ops, V4L2_CID_LINK_FREQ, i - 1, def, pdata->link_freqs); v4l2_ctrl_cluster(2, &mt9v032->link_freq); } mt9v032->subdev.ctrl_handler = &mt9v032->ctrls; if (mt9v032->ctrls.error) { dev_err(&client->dev, "control initialization error %d\n", mt9v032->ctrls.error); ret = mt9v032->ctrls.error; goto err; } mt9v032->crop.left = MT9V032_COLUMN_START_DEF; mt9v032->crop.top = MT9V032_ROW_START_DEF; mt9v032->crop.width = MT9V032_WINDOW_WIDTH_DEF; mt9v032->crop.height = MT9V032_WINDOW_HEIGHT_DEF; if (mt9v032->model->color) mt9v032->format.code = MEDIA_BUS_FMT_SGRBG10_1X10; else mt9v032->format.code = MEDIA_BUS_FMT_Y10_1X10; mt9v032->format.width = MT9V032_WINDOW_WIDTH_DEF; mt9v032->format.height = MT9V032_WINDOW_HEIGHT_DEF; mt9v032->format.field = V4L2_FIELD_NONE; mt9v032->format.colorspace = V4L2_COLORSPACE_SRGB; mt9v032->hratio = 1; mt9v032->vratio = 1; mt9v032->aec_agc = MT9V032_AEC_ENABLE | MT9V032_AGC_ENABLE; mt9v032->hblank = MT9V032_HORIZONTAL_BLANKING_DEF; mt9v032->sysclk = MT9V032_SYSCLK_FREQ_DEF; v4l2_i2c_subdev_init(&mt9v032->subdev, client, &mt9v032_subdev_ops); mt9v032->subdev.internal_ops = &mt9v032_subdev_internal_ops; mt9v032->subdev.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE; mt9v032->subdev.entity.function = MEDIA_ENT_F_CAM_SENSOR; mt9v032->pad.flags = MEDIA_PAD_FL_SOURCE; ret = media_entity_pads_init(&mt9v032->subdev.entity, 1, &mt9v032->pad); if (ret < 0) goto err; mt9v032->subdev.dev = &client->dev; ret = v4l2_async_register_subdev(&mt9v032->subdev); if (ret < 0) goto err; return 0; err: media_entity_cleanup(&mt9v032->subdev.entity); v4l2_ctrl_handler_free(&mt9v032->ctrls); return ret; } static void mt9v032_remove(struct i2c_client *client) { struct v4l2_subdev *subdev = i2c_get_clientdata(client); struct mt9v032 *mt9v032 = to_mt9v032(subdev); v4l2_async_unregister_subdev(subdev); v4l2_ctrl_handler_free(&mt9v032->ctrls); media_entity_cleanup(&subdev->entity); } static const struct mt9v032_model_data mt9v032_model_data[] = { { /* MT9V022, MT9V032 revisions 1/2/3 */ .min_row_time = 660, .min_hblank = MT9V032_HORIZONTAL_BLANKING_MIN, .min_vblank = MT9V032_VERTICAL_BLANKING_MIN, .max_vblank = MT9V032_VERTICAL_BLANKING_MAX, .min_shutter = MT9V032_TOTAL_SHUTTER_WIDTH_MIN, .max_shutter = MT9V032_TOTAL_SHUTTER_WIDTH_MAX, .pclk_reg = MT9V032_PIXEL_CLOCK, .aec_max_shutter_reg = MT9V032_AEC_MAX_SHUTTER_WIDTH, .aec_max_shutter_v4l2_ctrl = &mt9v032_aec_max_shutter_width, }, { /* MT9V024, MT9V034 */ .min_row_time = 690, .min_hblank = MT9V034_HORIZONTAL_BLANKING_MIN, .min_vblank = MT9V034_VERTICAL_BLANKING_MIN, .max_vblank = MT9V034_VERTICAL_BLANKING_MAX, .min_shutter = MT9V034_TOTAL_SHUTTER_WIDTH_MIN, .max_shutter = MT9V034_TOTAL_SHUTTER_WIDTH_MAX, .pclk_reg = MT9V034_PIXEL_CLOCK, .aec_max_shutter_reg = MT9V034_AEC_MAX_SHUTTER_WIDTH, .aec_max_shutter_v4l2_ctrl = &mt9v034_aec_max_shutter_width, }, }; static const struct mt9v032_model_info mt9v032_models[] = { [MT9V032_MODEL_V022_COLOR] = { .data = &mt9v032_model_data[0], .color = true, }, [MT9V032_MODEL_V022_MONO] = { .data = &mt9v032_model_data[0], .color = false, }, [MT9V032_MODEL_V024_COLOR] = { .data = &mt9v032_model_data[1], .color = true, }, [MT9V032_MODEL_V024_MONO] = { .data = &mt9v032_model_data[1], .color = false, }, [MT9V032_MODEL_V032_COLOR] = { .data = &mt9v032_model_data[0], .color = true, }, [MT9V032_MODEL_V032_MONO] = { .data = &mt9v032_model_data[0], .color = false, }, [MT9V032_MODEL_V034_COLOR] = { .data = &mt9v032_model_data[1], .color = true, }, [MT9V032_MODEL_V034_MONO] = { .data = &mt9v032_model_data[1], .color = false, }, }; static const struct i2c_device_id mt9v032_id[] = { { "mt9v022", (kernel_ulong_t)&mt9v032_models[MT9V032_MODEL_V022_COLOR] }, { "mt9v022m", (kernel_ulong_t)&mt9v032_models[MT9V032_MODEL_V022_MONO] }, { "mt9v024", (kernel_ulong_t)&mt9v032_models[MT9V032_MODEL_V024_COLOR] }, { "mt9v024m", (kernel_ulong_t)&mt9v032_models[MT9V032_MODEL_V024_MONO] }, { "mt9v032", (kernel_ulong_t)&mt9v032_models[MT9V032_MODEL_V032_COLOR] }, { "mt9v032m", (kernel_ulong_t)&mt9v032_models[MT9V032_MODEL_V032_MONO] }, { "mt9v034", (kernel_ulong_t)&mt9v032_models[MT9V032_MODEL_V034_COLOR] }, { "mt9v034m", (kernel_ulong_t)&mt9v032_models[MT9V032_MODEL_V034_MONO] }, { } }; MODULE_DEVICE_TABLE(i2c, mt9v032_id); #if IS_ENABLED(CONFIG_OF) static const struct of_device_id mt9v032_of_match[] = { { .compatible = "aptina,mt9v022" }, { .compatible = "aptina,mt9v022m" }, { .compatible = "aptina,mt9v024" }, { .compatible = "aptina,mt9v024m" }, { .compatible = "aptina,mt9v032" }, { .compatible = "aptina,mt9v032m" }, { .compatible = "aptina,mt9v034" }, { .compatible = "aptina,mt9v034m" }, { /* Sentinel */ } }; MODULE_DEVICE_TABLE(of, mt9v032_of_match); #endif static struct i2c_driver mt9v032_driver = { .driver = { .name = "mt9v032", .of_match_table = of_match_ptr(mt9v032_of_match), }, .probe = mt9v032_probe, .remove = mt9v032_remove, .id_table = mt9v032_id, }; module_i2c_driver(mt9v032_driver); MODULE_DESCRIPTION("Aptina MT9V032 Camera driver"); MODULE_AUTHOR("Laurent Pinchart <[email protected]>"); MODULE_LICENSE("GPL");
linux-master
drivers/media/i2c/mt9v032.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (C) 2005-2006 Micronas USA Inc. */ #include <linux/module.h> #include <linux/init.h> #include <linux/i2c.h> #include <linux/videodev2.h> #include <linux/ioctl.h> #include <media/v4l2-device.h> #include <media/v4l2-ctrls.h> #include <linux/slab.h> MODULE_DESCRIPTION("TW9903 I2C subdev driver"); MODULE_LICENSE("GPL v2"); /* * This driver is based on the wis-tw9903.c source that was in * drivers/staging/media/go7007. That source had commented out code for * saturation and scaling (neither seemed to work). If anyone ever gets * hardware to test this driver, then that code might be useful to look at. * You need to get the kernel sources of, say, kernel 3.8 where that * wis-tw9903 driver is still present. */ struct tw9903 { struct v4l2_subdev sd; struct v4l2_ctrl_handler hdl; v4l2_std_id norm; }; static inline struct tw9903 *to_state(struct v4l2_subdev *sd) { return container_of(sd, struct tw9903, sd); } static const u8 initial_registers[] = { 0x02, 0x44, /* input 1, composite */ 0x03, 0x92, /* correct digital format */ 0x04, 0x00, 0x05, 0x80, /* or 0x00 for PAL */ 0x06, 0x40, /* second internal current reference */ 0x07, 0x02, /* window */ 0x08, 0x14, /* window */ 0x09, 0xf0, /* window */ 0x0a, 0x81, /* window */ 0x0b, 0xd0, /* window */ 0x0c, 0x8c, 0x0d, 0x00, /* scaling */ 0x0e, 0x11, /* scaling */ 0x0f, 0x00, /* scaling */ 0x10, 0x00, /* brightness */ 0x11, 0x60, /* contrast */ 0x12, 0x01, /* sharpness */ 0x13, 0x7f, /* U gain */ 0x14, 0x5a, /* V gain */ 0x15, 0x00, /* hue */ 0x16, 0xc3, /* sharpness */ 0x18, 0x00, 0x19, 0x58, /* vbi */ 0x1a, 0x80, 0x1c, 0x0f, /* video norm */ 0x1d, 0x7f, /* video norm */ 0x20, 0xa0, /* clamping gain (working 0x50) */ 0x21, 0x22, 0x22, 0xf0, 0x23, 0xfe, 0x24, 0x3c, 0x25, 0x38, 0x26, 0x44, 0x27, 0x20, 0x28, 0x00, 0x29, 0x15, 0x2a, 0xa0, 0x2b, 0x44, 0x2c, 0x37, 0x2d, 0x00, 0x2e, 0xa5, /* burst PLL control (working: a9) */ 0x2f, 0xe0, /* 0xea is blue test frame -- 0xe0 for normal */ 0x31, 0x00, 0x33, 0x22, 0x34, 0x11, 0x35, 0x35, 0x3b, 0x05, 0x06, 0xc0, /* reset device */ 0x00, 0x00, /* Terminator (reg 0x00 is read-only) */ }; static int write_reg(struct v4l2_subdev *sd, u8 reg, u8 value) { struct i2c_client *client = v4l2_get_subdevdata(sd); return i2c_smbus_write_byte_data(client, reg, value); } static int write_regs(struct v4l2_subdev *sd, const u8 *regs) { int i; for (i = 0; regs[i] != 0x00; i += 2) if (write_reg(sd, regs[i], regs[i + 1]) < 0) return -1; return 0; } static int tw9903_s_video_routing(struct v4l2_subdev *sd, u32 input, u32 output, u32 config) { write_reg(sd, 0x02, 0x40 | (input << 1)); return 0; } static int tw9903_s_std(struct v4l2_subdev *sd, v4l2_std_id norm) { struct tw9903 *dec = to_state(sd); bool is_60hz = norm & V4L2_STD_525_60; static const u8 config_60hz[] = { 0x05, 0x80, 0x07, 0x02, 0x08, 0x14, 0x09, 0xf0, 0, 0, }; static const u8 config_50hz[] = { 0x05, 0x00, 0x07, 0x12, 0x08, 0x18, 0x09, 0x20, 0, 0, }; write_regs(sd, is_60hz ? config_60hz : config_50hz); dec->norm = norm; return 0; } static int tw9903_s_ctrl(struct v4l2_ctrl *ctrl) { struct tw9903 *dec = container_of(ctrl->handler, struct tw9903, hdl); struct v4l2_subdev *sd = &dec->sd; switch (ctrl->id) { case V4L2_CID_BRIGHTNESS: write_reg(sd, 0x10, ctrl->val); break; case V4L2_CID_CONTRAST: write_reg(sd, 0x11, ctrl->val); break; case V4L2_CID_HUE: write_reg(sd, 0x15, ctrl->val); break; default: return -EINVAL; } return 0; } static int tw9903_log_status(struct v4l2_subdev *sd) { struct tw9903 *dec = to_state(sd); bool is_60hz = dec->norm & V4L2_STD_525_60; v4l2_info(sd, "Standard: %d Hz\n", is_60hz ? 60 : 50); v4l2_ctrl_subdev_log_status(sd); return 0; } /* --------------------------------------------------------------------------*/ static const struct v4l2_ctrl_ops tw9903_ctrl_ops = { .s_ctrl = tw9903_s_ctrl, }; static const struct v4l2_subdev_core_ops tw9903_core_ops = { .log_status = tw9903_log_status, }; static const struct v4l2_subdev_video_ops tw9903_video_ops = { .s_std = tw9903_s_std, .s_routing = tw9903_s_video_routing, }; static const struct v4l2_subdev_ops tw9903_ops = { .core = &tw9903_core_ops, .video = &tw9903_video_ops, }; /* --------------------------------------------------------------------------*/ static int tw9903_probe(struct i2c_client *client) { struct tw9903 *dec; struct v4l2_subdev *sd; struct v4l2_ctrl_handler *hdl; /* Check if the adapter supports the needed features */ if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE_DATA)) return -EIO; v4l_info(client, "chip found @ 0x%02x (%s)\n", client->addr << 1, client->adapter->name); dec = devm_kzalloc(&client->dev, sizeof(*dec), GFP_KERNEL); if (dec == NULL) return -ENOMEM; sd = &dec->sd; v4l2_i2c_subdev_init(sd, client, &tw9903_ops); hdl = &dec->hdl; v4l2_ctrl_handler_init(hdl, 4); v4l2_ctrl_new_std(hdl, &tw9903_ctrl_ops, V4L2_CID_BRIGHTNESS, -128, 127, 1, 0); v4l2_ctrl_new_std(hdl, &tw9903_ctrl_ops, V4L2_CID_CONTRAST, 0, 255, 1, 0x60); v4l2_ctrl_new_std(hdl, &tw9903_ctrl_ops, V4L2_CID_HUE, -128, 127, 1, 0); sd->ctrl_handler = hdl; if (hdl->error) { int err = hdl->error; v4l2_ctrl_handler_free(hdl); return err; } /* Initialize tw9903 */ dec->norm = V4L2_STD_NTSC; if (write_regs(sd, initial_registers) < 0) { v4l2_err(client, "error initializing TW9903\n"); return -EINVAL; } return 0; } static void tw9903_remove(struct i2c_client *client) { struct v4l2_subdev *sd = i2c_get_clientdata(client); v4l2_device_unregister_subdev(sd); v4l2_ctrl_handler_free(&to_state(sd)->hdl); } /* ----------------------------------------------------------------------- */ static const struct i2c_device_id tw9903_id[] = { { "tw9903", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, tw9903_id); static struct i2c_driver tw9903_driver = { .driver = { .name = "tw9903", }, .probe = tw9903_probe, .remove = tw9903_remove, .id_table = tw9903_id, }; module_i2c_driver(tw9903_driver);
linux-master
drivers/media/i2c/tw9903.c
// SPDX-License-Identifier: GPL-2.0 /* * video-i2c.c - Support for I2C transport video devices * * Copyright (C) 2018 Matt Ranostay <[email protected]> * * Supported: * - Panasonic AMG88xx Grid-Eye Sensors * - Melexis MLX90640 Thermal Cameras */ #include <linux/bits.h> #include <linux/delay.h> #include <linux/freezer.h> #include <linux/hwmon.h> #include <linux/kthread.h> #include <linux/i2c.h> #include <linux/list.h> #include <linux/mod_devicetable.h> #include <linux/module.h> #include <linux/mutex.h> #include <linux/pm_runtime.h> #include <linux/nvmem-provider.h> #include <linux/regmap.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/videodev2.h> #include <media/v4l2-common.h> #include <media/v4l2-device.h> #include <media/v4l2-event.h> #include <media/v4l2-fh.h> #include <media/v4l2-ioctl.h> #include <media/videobuf2-v4l2.h> #include <media/videobuf2-vmalloc.h> #define VIDEO_I2C_DRIVER "video-i2c" /* Power control register */ #define AMG88XX_REG_PCTL 0x00 #define AMG88XX_PCTL_NORMAL 0x00 #define AMG88XX_PCTL_SLEEP 0x10 /* Reset register */ #define AMG88XX_REG_RST 0x01 #define AMG88XX_RST_FLAG 0x30 #define AMG88XX_RST_INIT 0x3f /* Frame rate register */ #define AMG88XX_REG_FPSC 0x02 #define AMG88XX_FPSC_1FPS BIT(0) /* Thermistor register */ #define AMG88XX_REG_TTHL 0x0e /* Temperature register */ #define AMG88XX_REG_T01L 0x80 /* RAM */ #define MLX90640_RAM_START_ADDR 0x0400 /* EEPROM */ #define MLX90640_EEPROM_START_ADDR 0x2400 /* Control register */ #define MLX90640_REG_CTL1 0x800d #define MLX90640_REG_CTL1_MASK GENMASK(9, 7) #define MLX90640_REG_CTL1_MASK_SHIFT 7 struct video_i2c_chip; struct video_i2c_buffer { struct vb2_v4l2_buffer vb; struct list_head list; }; struct video_i2c_data { struct regmap *regmap; const struct video_i2c_chip *chip; struct mutex lock; spinlock_t slock; unsigned int sequence; struct mutex queue_lock; struct v4l2_device v4l2_dev; struct video_device vdev; struct vb2_queue vb_vidq; struct task_struct *kthread_vid_cap; struct list_head vid_cap_active; struct v4l2_fract frame_interval; }; static const struct v4l2_fmtdesc amg88xx_format = { .pixelformat = V4L2_PIX_FMT_Y12, }; static const struct v4l2_frmsize_discrete amg88xx_size = { .width = 8, .height = 8, }; static const struct v4l2_fmtdesc mlx90640_format = { .pixelformat = V4L2_PIX_FMT_Y16_BE, }; static const struct v4l2_frmsize_discrete mlx90640_size = { .width = 32, .height = 26, /* 24 lines of pixel data + 2 lines of processing data */ }; static const struct regmap_config amg88xx_regmap_config = { .reg_bits = 8, .val_bits = 8, .max_register = 0xff }; static const struct regmap_config mlx90640_regmap_config = { .reg_bits = 16, .val_bits = 16, }; struct video_i2c_chip { /* video dimensions */ const struct v4l2_fmtdesc *format; const struct v4l2_frmsize_discrete *size; /* available frame intervals */ const struct v4l2_fract *frame_intervals; unsigned int num_frame_intervals; /* pixel buffer size */ unsigned int buffer_size; /* pixel size in bits */ unsigned int bpp; const struct regmap_config *regmap_config; struct nvmem_config *nvmem_config; /* setup function */ int (*setup)(struct video_i2c_data *data); /* xfer function */ int (*xfer)(struct video_i2c_data *data, char *buf); /* power control function */ int (*set_power)(struct video_i2c_data *data, bool on); /* hwmon init function */ int (*hwmon_init)(struct video_i2c_data *data); }; static int mlx90640_nvram_read(void *priv, unsigned int offset, void *val, size_t bytes) { struct video_i2c_data *data = priv; return regmap_bulk_read(data->regmap, MLX90640_EEPROM_START_ADDR + offset, val, bytes); } static struct nvmem_config mlx90640_nvram_config = { .name = "mlx90640_nvram", .word_size = 2, .stride = 1, .size = 1664, .reg_read = mlx90640_nvram_read, }; static int amg88xx_xfer(struct video_i2c_data *data, char *buf) { return regmap_bulk_read(data->regmap, AMG88XX_REG_T01L, buf, data->chip->buffer_size); } static int mlx90640_xfer(struct video_i2c_data *data, char *buf) { return regmap_bulk_read(data->regmap, MLX90640_RAM_START_ADDR, buf, data->chip->buffer_size); } static int amg88xx_setup(struct video_i2c_data *data) { unsigned int mask = AMG88XX_FPSC_1FPS; unsigned int val; if (data->frame_interval.numerator == data->frame_interval.denominator) val = mask; else val = 0; return regmap_update_bits(data->regmap, AMG88XX_REG_FPSC, mask, val); } static int mlx90640_setup(struct video_i2c_data *data) { unsigned int n, idx; for (n = 0; n < data->chip->num_frame_intervals - 1; n++) { if (V4L2_FRACT_COMPARE(data->frame_interval, ==, data->chip->frame_intervals[n])) break; } idx = data->chip->num_frame_intervals - n - 1; return regmap_update_bits(data->regmap, MLX90640_REG_CTL1, MLX90640_REG_CTL1_MASK, idx << MLX90640_REG_CTL1_MASK_SHIFT); } static int amg88xx_set_power_on(struct video_i2c_data *data) { int ret; ret = regmap_write(data->regmap, AMG88XX_REG_PCTL, AMG88XX_PCTL_NORMAL); if (ret) return ret; msleep(50); ret = regmap_write(data->regmap, AMG88XX_REG_RST, AMG88XX_RST_INIT); if (ret) return ret; usleep_range(2000, 3000); ret = regmap_write(data->regmap, AMG88XX_REG_RST, AMG88XX_RST_FLAG); if (ret) return ret; /* * Wait two frames before reading thermistor and temperature registers */ msleep(200); return 0; } static int amg88xx_set_power_off(struct video_i2c_data *data) { int ret; ret = regmap_write(data->regmap, AMG88XX_REG_PCTL, AMG88XX_PCTL_SLEEP); if (ret) return ret; /* * Wait for a while to avoid resuming normal mode immediately after * entering sleep mode, otherwise the device occasionally goes wrong * (thermistor and temperature registers are not updated at all) */ msleep(100); return 0; } static int amg88xx_set_power(struct video_i2c_data *data, bool on) { if (on) return amg88xx_set_power_on(data); return amg88xx_set_power_off(data); } #if IS_REACHABLE(CONFIG_HWMON) static const u32 amg88xx_temp_config[] = { HWMON_T_INPUT, 0 }; static const struct hwmon_channel_info amg88xx_temp = { .type = hwmon_temp, .config = amg88xx_temp_config, }; static const struct hwmon_channel_info * const amg88xx_info[] = { &amg88xx_temp, NULL }; static umode_t amg88xx_is_visible(const void *drvdata, enum hwmon_sensor_types type, u32 attr, int channel) { return 0444; } static int amg88xx_read(struct device *dev, enum hwmon_sensor_types type, u32 attr, int channel, long *val) { struct video_i2c_data *data = dev_get_drvdata(dev); __le16 buf; int tmp; tmp = pm_runtime_resume_and_get(regmap_get_device(data->regmap)); if (tmp < 0) return tmp; tmp = regmap_bulk_read(data->regmap, AMG88XX_REG_TTHL, &buf, 2); pm_runtime_mark_last_busy(regmap_get_device(data->regmap)); pm_runtime_put_autosuspend(regmap_get_device(data->regmap)); if (tmp) return tmp; tmp = le16_to_cpu(buf); /* * Check for sign bit, this isn't a two's complement value but an * absolute temperature that needs to be inverted in the case of being * negative. */ if (tmp & BIT(11)) tmp = -(tmp & 0x7ff); *val = (tmp * 625) / 10; return 0; } static const struct hwmon_ops amg88xx_hwmon_ops = { .is_visible = amg88xx_is_visible, .read = amg88xx_read, }; static const struct hwmon_chip_info amg88xx_chip_info = { .ops = &amg88xx_hwmon_ops, .info = amg88xx_info, }; static int amg88xx_hwmon_init(struct video_i2c_data *data) { struct device *dev = regmap_get_device(data->regmap); void *hwmon = devm_hwmon_device_register_with_info(dev, "amg88xx", data, &amg88xx_chip_info, NULL); return PTR_ERR_OR_ZERO(hwmon); } #else #define amg88xx_hwmon_init NULL #endif enum { AMG88XX, MLX90640, }; static const struct v4l2_fract amg88xx_frame_intervals[] = { { 1, 10 }, { 1, 1 }, }; static const struct v4l2_fract mlx90640_frame_intervals[] = { { 1, 64 }, { 1, 32 }, { 1, 16 }, { 1, 8 }, { 1, 4 }, { 1, 2 }, { 1, 1 }, { 2, 1 }, }; static const struct video_i2c_chip video_i2c_chip[] = { [AMG88XX] = { .size = &amg88xx_size, .format = &amg88xx_format, .frame_intervals = amg88xx_frame_intervals, .num_frame_intervals = ARRAY_SIZE(amg88xx_frame_intervals), .buffer_size = 128, .bpp = 16, .regmap_config = &amg88xx_regmap_config, .setup = &amg88xx_setup, .xfer = &amg88xx_xfer, .set_power = amg88xx_set_power, .hwmon_init = amg88xx_hwmon_init, }, [MLX90640] = { .size = &mlx90640_size, .format = &mlx90640_format, .frame_intervals = mlx90640_frame_intervals, .num_frame_intervals = ARRAY_SIZE(mlx90640_frame_intervals), .buffer_size = 1664, .bpp = 16, .regmap_config = &mlx90640_regmap_config, .nvmem_config = &mlx90640_nvram_config, .setup = mlx90640_setup, .xfer = mlx90640_xfer, }, }; static const struct v4l2_file_operations video_i2c_fops = { .owner = THIS_MODULE, .open = v4l2_fh_open, .release = vb2_fop_release, .poll = vb2_fop_poll, .read = vb2_fop_read, .mmap = vb2_fop_mmap, .unlocked_ioctl = video_ioctl2, }; static int queue_setup(struct vb2_queue *vq, unsigned int *nbuffers, unsigned int *nplanes, unsigned int sizes[], struct device *alloc_devs[]) { struct video_i2c_data *data = vb2_get_drv_priv(vq); unsigned int size = data->chip->buffer_size; if (vq->num_buffers + *nbuffers < 2) *nbuffers = 2; if (*nplanes) return sizes[0] < size ? -EINVAL : 0; *nplanes = 1; sizes[0] = size; return 0; } static int buffer_prepare(struct vb2_buffer *vb) { struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb); struct video_i2c_data *data = vb2_get_drv_priv(vb->vb2_queue); unsigned int size = data->chip->buffer_size; if (vb2_plane_size(vb, 0) < size) return -EINVAL; vbuf->field = V4L2_FIELD_NONE; vb2_set_plane_payload(vb, 0, size); return 0; } static void buffer_queue(struct vb2_buffer *vb) { struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb); struct video_i2c_data *data = vb2_get_drv_priv(vb->vb2_queue); struct video_i2c_buffer *buf = container_of(vbuf, struct video_i2c_buffer, vb); spin_lock(&data->slock); list_add_tail(&buf->list, &data->vid_cap_active); spin_unlock(&data->slock); } static int video_i2c_thread_vid_cap(void *priv) { struct video_i2c_data *data = priv; u32 delay = mult_frac(1000000UL, data->frame_interval.numerator, data->frame_interval.denominator); s64 end_us = ktime_to_us(ktime_get()); set_freezable(); do { struct video_i2c_buffer *vid_cap_buf = NULL; s64 current_us; int schedule_delay; try_to_freeze(); spin_lock(&data->slock); if (!list_empty(&data->vid_cap_active)) { vid_cap_buf = list_last_entry(&data->vid_cap_active, struct video_i2c_buffer, list); list_del(&vid_cap_buf->list); } spin_unlock(&data->slock); if (vid_cap_buf) { struct vb2_buffer *vb2_buf = &vid_cap_buf->vb.vb2_buf; void *vbuf = vb2_plane_vaddr(vb2_buf, 0); int ret; ret = data->chip->xfer(data, vbuf); vb2_buf->timestamp = ktime_get_ns(); vid_cap_buf->vb.sequence = data->sequence++; vb2_buffer_done(vb2_buf, ret ? VB2_BUF_STATE_ERROR : VB2_BUF_STATE_DONE); } end_us += delay; current_us = ktime_to_us(ktime_get()); if (current_us < end_us) { schedule_delay = end_us - current_us; usleep_range(schedule_delay * 3 / 4, schedule_delay); } else { end_us = current_us; } } while (!kthread_should_stop()); return 0; } static void video_i2c_del_list(struct vb2_queue *vq, enum vb2_buffer_state state) { struct video_i2c_data *data = vb2_get_drv_priv(vq); struct video_i2c_buffer *buf, *tmp; spin_lock(&data->slock); list_for_each_entry_safe(buf, tmp, &data->vid_cap_active, list) { list_del(&buf->list); vb2_buffer_done(&buf->vb.vb2_buf, state); } spin_unlock(&data->slock); } static int start_streaming(struct vb2_queue *vq, unsigned int count) { struct video_i2c_data *data = vb2_get_drv_priv(vq); struct device *dev = regmap_get_device(data->regmap); int ret; if (data->kthread_vid_cap) return 0; ret = pm_runtime_resume_and_get(dev); if (ret < 0) goto error_del_list; ret = data->chip->setup(data); if (ret) goto error_rpm_put; data->sequence = 0; data->kthread_vid_cap = kthread_run(video_i2c_thread_vid_cap, data, "%s-vid-cap", data->v4l2_dev.name); ret = PTR_ERR_OR_ZERO(data->kthread_vid_cap); if (!ret) return 0; error_rpm_put: pm_runtime_mark_last_busy(dev); pm_runtime_put_autosuspend(dev); error_del_list: video_i2c_del_list(vq, VB2_BUF_STATE_QUEUED); return ret; } static void stop_streaming(struct vb2_queue *vq) { struct video_i2c_data *data = vb2_get_drv_priv(vq); if (data->kthread_vid_cap == NULL) return; kthread_stop(data->kthread_vid_cap); data->kthread_vid_cap = NULL; pm_runtime_mark_last_busy(regmap_get_device(data->regmap)); pm_runtime_put_autosuspend(regmap_get_device(data->regmap)); video_i2c_del_list(vq, VB2_BUF_STATE_ERROR); } static const struct vb2_ops video_i2c_video_qops = { .queue_setup = queue_setup, .buf_prepare = buffer_prepare, .buf_queue = buffer_queue, .start_streaming = start_streaming, .stop_streaming = stop_streaming, .wait_prepare = vb2_ops_wait_prepare, .wait_finish = vb2_ops_wait_finish, }; static int video_i2c_querycap(struct file *file, void *priv, struct v4l2_capability *vcap) { struct video_i2c_data *data = video_drvdata(file); struct device *dev = regmap_get_device(data->regmap); struct i2c_client *client = to_i2c_client(dev); strscpy(vcap->driver, data->v4l2_dev.name, sizeof(vcap->driver)); strscpy(vcap->card, data->vdev.name, sizeof(vcap->card)); sprintf(vcap->bus_info, "I2C:%d-%d", client->adapter->nr, client->addr); return 0; } static int video_i2c_g_input(struct file *file, void *fh, unsigned int *inp) { *inp = 0; return 0; } static int video_i2c_s_input(struct file *file, void *fh, unsigned int inp) { return (inp > 0) ? -EINVAL : 0; } static int video_i2c_enum_input(struct file *file, void *fh, struct v4l2_input *vin) { if (vin->index > 0) return -EINVAL; strscpy(vin->name, "Camera", sizeof(vin->name)); vin->type = V4L2_INPUT_TYPE_CAMERA; return 0; } static int video_i2c_enum_fmt_vid_cap(struct file *file, void *fh, struct v4l2_fmtdesc *fmt) { struct video_i2c_data *data = video_drvdata(file); enum v4l2_buf_type type = fmt->type; if (fmt->index > 0) return -EINVAL; *fmt = *data->chip->format; fmt->type = type; return 0; } static int video_i2c_enum_framesizes(struct file *file, void *fh, struct v4l2_frmsizeenum *fsize) { const struct video_i2c_data *data = video_drvdata(file); const struct v4l2_frmsize_discrete *size = data->chip->size; /* currently only one frame size is allowed */ if (fsize->index > 0) return -EINVAL; if (fsize->pixel_format != data->chip->format->pixelformat) return -EINVAL; fsize->type = V4L2_FRMSIZE_TYPE_DISCRETE; fsize->discrete.width = size->width; fsize->discrete.height = size->height; return 0; } static int video_i2c_enum_frameintervals(struct file *file, void *priv, struct v4l2_frmivalenum *fe) { const struct video_i2c_data *data = video_drvdata(file); const struct v4l2_frmsize_discrete *size = data->chip->size; if (fe->index >= data->chip->num_frame_intervals) return -EINVAL; if (fe->width != size->width || fe->height != size->height) return -EINVAL; fe->type = V4L2_FRMIVAL_TYPE_DISCRETE; fe->discrete = data->chip->frame_intervals[fe->index]; return 0; } static int video_i2c_try_fmt_vid_cap(struct file *file, void *fh, struct v4l2_format *fmt) { const struct video_i2c_data *data = video_drvdata(file); const struct v4l2_frmsize_discrete *size = data->chip->size; struct v4l2_pix_format *pix = &fmt->fmt.pix; unsigned int bpp = data->chip->bpp / 8; pix->width = size->width; pix->height = size->height; pix->pixelformat = data->chip->format->pixelformat; pix->field = V4L2_FIELD_NONE; pix->bytesperline = pix->width * bpp; pix->sizeimage = pix->bytesperline * pix->height; pix->colorspace = V4L2_COLORSPACE_RAW; return 0; } static int video_i2c_s_fmt_vid_cap(struct file *file, void *fh, struct v4l2_format *fmt) { struct video_i2c_data *data = video_drvdata(file); if (vb2_is_busy(&data->vb_vidq)) return -EBUSY; return video_i2c_try_fmt_vid_cap(file, fh, fmt); } static int video_i2c_g_parm(struct file *filp, void *priv, struct v4l2_streamparm *parm) { struct video_i2c_data *data = video_drvdata(filp); if (parm->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) return -EINVAL; parm->parm.capture.readbuffers = 1; parm->parm.capture.capability = V4L2_CAP_TIMEPERFRAME; parm->parm.capture.timeperframe = data->frame_interval; return 0; } static int video_i2c_s_parm(struct file *filp, void *priv, struct v4l2_streamparm *parm) { struct video_i2c_data *data = video_drvdata(filp); int i; for (i = 0; i < data->chip->num_frame_intervals - 1; i++) { if (V4L2_FRACT_COMPARE(parm->parm.capture.timeperframe, <=, data->chip->frame_intervals[i])) break; } data->frame_interval = data->chip->frame_intervals[i]; return video_i2c_g_parm(filp, priv, parm); } static const struct v4l2_ioctl_ops video_i2c_ioctl_ops = { .vidioc_querycap = video_i2c_querycap, .vidioc_g_input = video_i2c_g_input, .vidioc_s_input = video_i2c_s_input, .vidioc_enum_input = video_i2c_enum_input, .vidioc_enum_fmt_vid_cap = video_i2c_enum_fmt_vid_cap, .vidioc_enum_framesizes = video_i2c_enum_framesizes, .vidioc_enum_frameintervals = video_i2c_enum_frameintervals, .vidioc_g_fmt_vid_cap = video_i2c_try_fmt_vid_cap, .vidioc_s_fmt_vid_cap = video_i2c_s_fmt_vid_cap, .vidioc_g_parm = video_i2c_g_parm, .vidioc_s_parm = video_i2c_s_parm, .vidioc_try_fmt_vid_cap = video_i2c_try_fmt_vid_cap, .vidioc_reqbufs = vb2_ioctl_reqbufs, .vidioc_create_bufs = vb2_ioctl_create_bufs, .vidioc_prepare_buf = vb2_ioctl_prepare_buf, .vidioc_querybuf = vb2_ioctl_querybuf, .vidioc_qbuf = vb2_ioctl_qbuf, .vidioc_dqbuf = vb2_ioctl_dqbuf, .vidioc_streamon = vb2_ioctl_streamon, .vidioc_streamoff = vb2_ioctl_streamoff, }; static void video_i2c_release(struct video_device *vdev) { struct video_i2c_data *data = video_get_drvdata(vdev); v4l2_device_unregister(&data->v4l2_dev); mutex_destroy(&data->lock); mutex_destroy(&data->queue_lock); regmap_exit(data->regmap); kfree(data); } static int video_i2c_probe(struct i2c_client *client) { const struct i2c_device_id *id = i2c_client_get_device_id(client); struct video_i2c_data *data; struct v4l2_device *v4l2_dev; struct vb2_queue *queue; int ret = -ENODEV; data = kzalloc(sizeof(*data), GFP_KERNEL); if (!data) return -ENOMEM; if (dev_fwnode(&client->dev)) data->chip = device_get_match_data(&client->dev); else if (id) data->chip = &video_i2c_chip[id->driver_data]; else goto error_free_device; data->regmap = regmap_init_i2c(client, data->chip->regmap_config); if (IS_ERR(data->regmap)) { ret = PTR_ERR(data->regmap); goto error_free_device; } v4l2_dev = &data->v4l2_dev; strscpy(v4l2_dev->name, VIDEO_I2C_DRIVER, sizeof(v4l2_dev->name)); ret = v4l2_device_register(&client->dev, v4l2_dev); if (ret < 0) goto error_regmap_exit; mutex_init(&data->lock); mutex_init(&data->queue_lock); queue = &data->vb_vidq; queue->type = V4L2_BUF_TYPE_VIDEO_CAPTURE; queue->io_modes = VB2_DMABUF | VB2_MMAP | VB2_USERPTR | VB2_READ; queue->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC; queue->drv_priv = data; queue->buf_struct_size = sizeof(struct video_i2c_buffer); queue->min_buffers_needed = 1; queue->ops = &video_i2c_video_qops; queue->mem_ops = &vb2_vmalloc_memops; ret = vb2_queue_init(queue); if (ret < 0) goto error_unregister_device; data->vdev.queue = queue; data->vdev.queue->lock = &data->queue_lock; snprintf(data->vdev.name, sizeof(data->vdev.name), "I2C %d-%d Transport Video", client->adapter->nr, client->addr); data->vdev.v4l2_dev = v4l2_dev; data->vdev.fops = &video_i2c_fops; data->vdev.lock = &data->lock; data->vdev.ioctl_ops = &video_i2c_ioctl_ops; data->vdev.release = video_i2c_release; data->vdev.device_caps = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_READWRITE | V4L2_CAP_STREAMING; spin_lock_init(&data->slock); INIT_LIST_HEAD(&data->vid_cap_active); data->frame_interval = data->chip->frame_intervals[0]; video_set_drvdata(&data->vdev, data); i2c_set_clientdata(client, data); if (data->chip->set_power) { ret = data->chip->set_power(data, true); if (ret) goto error_unregister_device; } pm_runtime_get_noresume(&client->dev); pm_runtime_set_active(&client->dev); pm_runtime_enable(&client->dev); pm_runtime_set_autosuspend_delay(&client->dev, 2000); pm_runtime_use_autosuspend(&client->dev); if (data->chip->hwmon_init) { ret = data->chip->hwmon_init(data); if (ret < 0) { dev_warn(&client->dev, "failed to register hwmon device\n"); } } if (data->chip->nvmem_config) { struct nvmem_config *config = data->chip->nvmem_config; struct nvmem_device *device; config->priv = data; config->dev = &client->dev; device = devm_nvmem_register(&client->dev, config); if (IS_ERR(device)) { dev_warn(&client->dev, "failed to register nvmem device\n"); } } ret = video_register_device(&data->vdev, VFL_TYPE_VIDEO, -1); if (ret < 0) goto error_pm_disable; pm_runtime_mark_last_busy(&client->dev); pm_runtime_put_autosuspend(&client->dev); return 0; error_pm_disable: pm_runtime_disable(&client->dev); pm_runtime_set_suspended(&client->dev); pm_runtime_put_noidle(&client->dev); if (data->chip->set_power) data->chip->set_power(data, false); error_unregister_device: v4l2_device_unregister(v4l2_dev); mutex_destroy(&data->lock); mutex_destroy(&data->queue_lock); error_regmap_exit: regmap_exit(data->regmap); error_free_device: kfree(data); return ret; } static void video_i2c_remove(struct i2c_client *client) { struct video_i2c_data *data = i2c_get_clientdata(client); pm_runtime_get_sync(&client->dev); pm_runtime_disable(&client->dev); pm_runtime_set_suspended(&client->dev); pm_runtime_put_noidle(&client->dev); if (data->chip->set_power) data->chip->set_power(data, false); video_unregister_device(&data->vdev); } #ifdef CONFIG_PM static int video_i2c_pm_runtime_suspend(struct device *dev) { struct video_i2c_data *data = i2c_get_clientdata(to_i2c_client(dev)); if (!data->chip->set_power) return 0; return data->chip->set_power(data, false); } static int video_i2c_pm_runtime_resume(struct device *dev) { struct video_i2c_data *data = i2c_get_clientdata(to_i2c_client(dev)); if (!data->chip->set_power) return 0; return data->chip->set_power(data, true); } #endif static const struct dev_pm_ops video_i2c_pm_ops = { SET_RUNTIME_PM_OPS(video_i2c_pm_runtime_suspend, video_i2c_pm_runtime_resume, NULL) }; static const struct i2c_device_id video_i2c_id_table[] = { { "amg88xx", AMG88XX }, { "mlx90640", MLX90640 }, {} }; MODULE_DEVICE_TABLE(i2c, video_i2c_id_table); static const struct of_device_id video_i2c_of_match[] = { { .compatible = "panasonic,amg88xx", .data = &video_i2c_chip[AMG88XX] }, { .compatible = "melexis,mlx90640", .data = &video_i2c_chip[MLX90640] }, {} }; MODULE_DEVICE_TABLE(of, video_i2c_of_match); static struct i2c_driver video_i2c_driver = { .driver = { .name = VIDEO_I2C_DRIVER, .of_match_table = video_i2c_of_match, .pm = &video_i2c_pm_ops, }, .probe = video_i2c_probe, .remove = video_i2c_remove, .id_table = video_i2c_id_table, }; module_i2c_driver(video_i2c_driver); MODULE_AUTHOR("Matt Ranostay <[email protected]>"); MODULE_DESCRIPTION("I2C transport video support"); MODULE_LICENSE("GPL v2");
linux-master
drivers/media/i2c/video-i2c.c
// SPDX-License-Identifier: GPL-2.0-only /* * Driver for MT9P031 CMOS Image Sensor from Aptina * * Copyright (C) 2011, Laurent Pinchart <[email protected]> * Copyright (C) 2011, Javier Martin <[email protected]> * Copyright (C) 2011, Guennadi Liakhovetski <[email protected]> * * Based on the MT9V032 driver and Bastian Hecht's code. */ #include <linux/clk.h> #include <linux/delay.h> #include <linux/device.h> #include <linux/gpio/consumer.h> #include <linux/i2c.h> #include <linux/log2.h> #include <linux/module.h> #include <linux/of.h> #include <linux/of_graph.h> #include <linux/pm.h> #include <linux/regulator/consumer.h> #include <linux/slab.h> #include <linux/videodev2.h> #include <media/i2c/mt9p031.h> #include <media/v4l2-async.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-device.h> #include <media/v4l2-fwnode.h> #include <media/v4l2-subdev.h> #include "aptina-pll.h" #define MT9P031_PIXEL_ARRAY_WIDTH 2752 #define MT9P031_PIXEL_ARRAY_HEIGHT 2004 #define MT9P031_CHIP_VERSION 0x00 #define MT9P031_CHIP_VERSION_VALUE 0x1801 #define MT9P031_ROW_START 0x01 #define MT9P031_ROW_START_MIN 0 #define MT9P031_ROW_START_MAX 2004 #define MT9P031_ROW_START_DEF 54 #define MT9P031_COLUMN_START 0x02 #define MT9P031_COLUMN_START_MIN 0 #define MT9P031_COLUMN_START_MAX 2750 #define MT9P031_COLUMN_START_DEF 16 #define MT9P031_WINDOW_HEIGHT 0x03 #define MT9P031_WINDOW_HEIGHT_MIN 2 #define MT9P031_WINDOW_HEIGHT_MAX 2006 #define MT9P031_WINDOW_HEIGHT_DEF 1944 #define MT9P031_WINDOW_WIDTH 0x04 #define MT9P031_WINDOW_WIDTH_MIN 2 #define MT9P031_WINDOW_WIDTH_MAX 2752 #define MT9P031_WINDOW_WIDTH_DEF 2592 #define MT9P031_HORIZONTAL_BLANK 0x05 #define MT9P031_HORIZONTAL_BLANK_MIN 0 #define MT9P031_HORIZONTAL_BLANK_MAX 4095 #define MT9P031_VERTICAL_BLANK 0x06 #define MT9P031_VERTICAL_BLANK_MIN 1 #define MT9P031_VERTICAL_BLANK_MAX 4096 #define MT9P031_VERTICAL_BLANK_DEF 26 #define MT9P031_OUTPUT_CONTROL 0x07 #define MT9P031_OUTPUT_CONTROL_CEN 2 #define MT9P031_OUTPUT_CONTROL_SYN 1 #define MT9P031_OUTPUT_CONTROL_DEF 0x1f82 #define MT9P031_SHUTTER_WIDTH_UPPER 0x08 #define MT9P031_SHUTTER_WIDTH_LOWER 0x09 #define MT9P031_SHUTTER_WIDTH_MIN 1 #define MT9P031_SHUTTER_WIDTH_MAX 1048575 #define MT9P031_SHUTTER_WIDTH_DEF 1943 #define MT9P031_PLL_CONTROL 0x10 #define MT9P031_PLL_CONTROL_PWROFF 0x0050 #define MT9P031_PLL_CONTROL_PWRON 0x0051 #define MT9P031_PLL_CONTROL_USEPLL 0x0052 #define MT9P031_PLL_CONFIG_1 0x11 #define MT9P031_PLL_CONFIG_2 0x12 #define MT9P031_PIXEL_CLOCK_CONTROL 0x0a #define MT9P031_PIXEL_CLOCK_INVERT BIT(15) #define MT9P031_PIXEL_CLOCK_SHIFT(n) ((n) << 8) #define MT9P031_PIXEL_CLOCK_DIVIDE(n) ((n) << 0) #define MT9P031_RESTART 0x0b #define MT9P031_FRAME_PAUSE_RESTART BIT(1) #define MT9P031_FRAME_RESTART BIT(0) #define MT9P031_SHUTTER_DELAY 0x0c #define MT9P031_RST 0x0d #define MT9P031_RST_ENABLE BIT(0) #define MT9P031_READ_MODE_1 0x1e #define MT9P031_READ_MODE_2 0x20 #define MT9P031_READ_MODE_2_ROW_MIR BIT(15) #define MT9P031_READ_MODE_2_COL_MIR BIT(14) #define MT9P031_READ_MODE_2_ROW_BLC BIT(6) #define MT9P031_ROW_ADDRESS_MODE 0x22 #define MT9P031_COLUMN_ADDRESS_MODE 0x23 #define MT9P031_GLOBAL_GAIN 0x35 #define MT9P031_GLOBAL_GAIN_MIN 8 #define MT9P031_GLOBAL_GAIN_MAX 1024 #define MT9P031_GLOBAL_GAIN_DEF 8 #define MT9P031_GLOBAL_GAIN_MULT BIT(6) #define MT9P031_ROW_BLACK_TARGET 0x49 #define MT9P031_ROW_BLACK_DEF_OFFSET 0x4b #define MT9P031_GREEN1_OFFSET 0x60 #define MT9P031_GREEN2_OFFSET 0x61 #define MT9P031_BLACK_LEVEL_CALIBRATION 0x62 #define MT9P031_BLC_MANUAL_BLC BIT(0) #define MT9P031_RED_OFFSET 0x63 #define MT9P031_BLUE_OFFSET 0x64 #define MT9P031_TEST_PATTERN 0xa0 #define MT9P031_TEST_PATTERN_SHIFT 3 #define MT9P031_TEST_PATTERN_ENABLE BIT(0) #define MT9P031_TEST_PATTERN_GREEN 0xa1 #define MT9P031_TEST_PATTERN_RED 0xa2 #define MT9P031_TEST_PATTERN_BLUE 0xa3 enum mt9p031_model { MT9P031_MODEL_COLOR, MT9P031_MODEL_MONOCHROME, }; struct mt9p031 { struct v4l2_subdev subdev; struct media_pad pad; struct v4l2_rect crop; /* Sensor window */ struct v4l2_mbus_framefmt format; struct mt9p031_platform_data *pdata; struct mutex power_lock; /* lock to protect power_count */ int power_count; struct clk *clk; struct regulator_bulk_data regulators[3]; enum mt9p031_model model; struct aptina_pll pll; unsigned int clk_div; bool use_pll; struct gpio_desc *reset; struct v4l2_ctrl_handler ctrls; struct v4l2_ctrl *blc_auto; struct v4l2_ctrl *blc_offset; /* Registers cache */ u16 output_control; u16 mode2; }; static struct mt9p031 *to_mt9p031(struct v4l2_subdev *sd) { return container_of(sd, struct mt9p031, subdev); } static int mt9p031_read(struct i2c_client *client, u8 reg) { return i2c_smbus_read_word_swapped(client, reg); } static int mt9p031_write(struct i2c_client *client, u8 reg, u16 data) { return i2c_smbus_write_word_swapped(client, reg, data); } static int mt9p031_set_output_control(struct mt9p031 *mt9p031, u16 clear, u16 set) { struct i2c_client *client = v4l2_get_subdevdata(&mt9p031->subdev); u16 value = (mt9p031->output_control & ~clear) | set; int ret; ret = mt9p031_write(client, MT9P031_OUTPUT_CONTROL, value); if (ret < 0) return ret; mt9p031->output_control = value; return 0; } static int mt9p031_set_mode2(struct mt9p031 *mt9p031, u16 clear, u16 set) { struct i2c_client *client = v4l2_get_subdevdata(&mt9p031->subdev); u16 value = (mt9p031->mode2 & ~clear) | set; int ret; ret = mt9p031_write(client, MT9P031_READ_MODE_2, value); if (ret < 0) return ret; mt9p031->mode2 = value; return 0; } static int mt9p031_reset(struct mt9p031 *mt9p031) { struct i2c_client *client = v4l2_get_subdevdata(&mt9p031->subdev); int ret; /* Disable chip output, synchronous option update */ ret = mt9p031_write(client, MT9P031_RST, MT9P031_RST_ENABLE); if (ret < 0) return ret; ret = mt9p031_write(client, MT9P031_RST, 0); if (ret < 0) return ret; ret = mt9p031_write(client, MT9P031_PIXEL_CLOCK_CONTROL, MT9P031_PIXEL_CLOCK_DIVIDE(mt9p031->clk_div)); if (ret < 0) return ret; return mt9p031_set_output_control(mt9p031, MT9P031_OUTPUT_CONTROL_CEN, 0); } static int mt9p031_clk_setup(struct mt9p031 *mt9p031) { static const struct aptina_pll_limits limits = { .ext_clock_min = 6000000, .ext_clock_max = 27000000, .int_clock_min = 2000000, .int_clock_max = 13500000, .out_clock_min = 180000000, .out_clock_max = 360000000, .pix_clock_max = 96000000, .n_min = 1, .n_max = 64, .m_min = 16, .m_max = 255, .p1_min = 1, .p1_max = 128, }; struct i2c_client *client = v4l2_get_subdevdata(&mt9p031->subdev); struct mt9p031_platform_data *pdata = mt9p031->pdata; unsigned long ext_freq; int ret; mt9p031->clk = devm_clk_get(&client->dev, NULL); if (IS_ERR(mt9p031->clk)) return PTR_ERR(mt9p031->clk); ret = clk_set_rate(mt9p031->clk, pdata->ext_freq); if (ret < 0) return ret; ext_freq = clk_get_rate(mt9p031->clk); /* If the external clock frequency is out of bounds for the PLL use the * pixel clock divider only and disable the PLL. */ if (ext_freq > limits.ext_clock_max) { unsigned int div; div = DIV_ROUND_UP(ext_freq, pdata->target_freq); div = roundup_pow_of_two(div) / 2; mt9p031->clk_div = min_t(unsigned int, div, 64); mt9p031->use_pll = false; return 0; } mt9p031->pll.ext_clock = ext_freq; mt9p031->pll.pix_clock = pdata->target_freq; mt9p031->use_pll = true; return aptina_pll_calculate(&client->dev, &limits, &mt9p031->pll); } static int mt9p031_pll_enable(struct mt9p031 *mt9p031) { struct i2c_client *client = v4l2_get_subdevdata(&mt9p031->subdev); int ret; if (!mt9p031->use_pll) return 0; ret = mt9p031_write(client, MT9P031_PLL_CONTROL, MT9P031_PLL_CONTROL_PWRON); if (ret < 0) return ret; ret = mt9p031_write(client, MT9P031_PLL_CONFIG_1, (mt9p031->pll.m << 8) | (mt9p031->pll.n - 1)); if (ret < 0) return ret; ret = mt9p031_write(client, MT9P031_PLL_CONFIG_2, mt9p031->pll.p1 - 1); if (ret < 0) return ret; usleep_range(1000, 2000); ret = mt9p031_write(client, MT9P031_PLL_CONTROL, MT9P031_PLL_CONTROL_PWRON | MT9P031_PLL_CONTROL_USEPLL); return ret; } static inline int mt9p031_pll_disable(struct mt9p031 *mt9p031) { struct i2c_client *client = v4l2_get_subdevdata(&mt9p031->subdev); if (!mt9p031->use_pll) return 0; return mt9p031_write(client, MT9P031_PLL_CONTROL, MT9P031_PLL_CONTROL_PWROFF); } static int mt9p031_power_on(struct mt9p031 *mt9p031) { unsigned long rate, delay; int ret; /* Ensure RESET_BAR is active */ if (mt9p031->reset) { gpiod_set_value(mt9p031->reset, 1); usleep_range(1000, 2000); } /* Bring up the supplies */ ret = regulator_bulk_enable(ARRAY_SIZE(mt9p031->regulators), mt9p031->regulators); if (ret < 0) return ret; /* Enable clock */ if (mt9p031->clk) { ret = clk_prepare_enable(mt9p031->clk); if (ret) { regulator_bulk_disable(ARRAY_SIZE(mt9p031->regulators), mt9p031->regulators); return ret; } } /* Now RESET_BAR must be high */ if (mt9p031->reset) { gpiod_set_value(mt9p031->reset, 0); /* Wait 850000 EXTCLK cycles before de-asserting reset. */ rate = clk_get_rate(mt9p031->clk); if (!rate) rate = 6000000; /* Slowest supported clock, 6 MHz */ delay = DIV_ROUND_UP(850000 * 1000, rate); msleep(delay); } return 0; } static void mt9p031_power_off(struct mt9p031 *mt9p031) { if (mt9p031->reset) { gpiod_set_value(mt9p031->reset, 1); usleep_range(1000, 2000); } regulator_bulk_disable(ARRAY_SIZE(mt9p031->regulators), mt9p031->regulators); clk_disable_unprepare(mt9p031->clk); } static int __mt9p031_set_power(struct mt9p031 *mt9p031, bool on) { struct i2c_client *client = v4l2_get_subdevdata(&mt9p031->subdev); int ret; if (!on) { mt9p031_power_off(mt9p031); return 0; } ret = mt9p031_power_on(mt9p031); if (ret < 0) return ret; ret = mt9p031_reset(mt9p031); if (ret < 0) { dev_err(&client->dev, "Failed to reset the camera\n"); return ret; } /* Configure the pixel clock polarity */ if (mt9p031->pdata && mt9p031->pdata->pixclk_pol) { ret = mt9p031_write(client, MT9P031_PIXEL_CLOCK_CONTROL, MT9P031_PIXEL_CLOCK_INVERT); if (ret < 0) return ret; } return v4l2_ctrl_handler_setup(&mt9p031->ctrls); } /* ----------------------------------------------------------------------------- * V4L2 subdev video operations */ static int mt9p031_set_params(struct mt9p031 *mt9p031) { struct i2c_client *client = v4l2_get_subdevdata(&mt9p031->subdev); struct v4l2_mbus_framefmt *format = &mt9p031->format; const struct v4l2_rect *crop = &mt9p031->crop; unsigned int hblank; unsigned int vblank; unsigned int xskip; unsigned int yskip; unsigned int xbin; unsigned int ybin; int ret; /* Windows position and size. * * TODO: Make sure the start coordinates and window size match the * skipping, binning and mirroring (see description of registers 2 and 4 * in table 13, and Binning section on page 41). */ ret = mt9p031_write(client, MT9P031_COLUMN_START, crop->left); if (ret < 0) return ret; ret = mt9p031_write(client, MT9P031_ROW_START, crop->top); if (ret < 0) return ret; ret = mt9p031_write(client, MT9P031_WINDOW_WIDTH, crop->width - 1); if (ret < 0) return ret; ret = mt9p031_write(client, MT9P031_WINDOW_HEIGHT, crop->height - 1); if (ret < 0) return ret; /* Row and column binning and skipping. Use the maximum binning value * compatible with the skipping settings. */ xskip = DIV_ROUND_CLOSEST(crop->width, format->width); yskip = DIV_ROUND_CLOSEST(crop->height, format->height); xbin = 1 << (ffs(xskip) - 1); ybin = 1 << (ffs(yskip) - 1); ret = mt9p031_write(client, MT9P031_COLUMN_ADDRESS_MODE, ((xbin - 1) << 4) | (xskip - 1)); if (ret < 0) return ret; ret = mt9p031_write(client, MT9P031_ROW_ADDRESS_MODE, ((ybin - 1) << 4) | (yskip - 1)); if (ret < 0) return ret; /* Blanking - use minimum value for horizontal blanking and default * value for vertical blanking. */ hblank = 346 * ybin + 64 + (80 >> min_t(unsigned int, xbin, 3)); vblank = MT9P031_VERTICAL_BLANK_DEF; ret = mt9p031_write(client, MT9P031_HORIZONTAL_BLANK, hblank - 1); if (ret < 0) return ret; ret = mt9p031_write(client, MT9P031_VERTICAL_BLANK, vblank - 1); if (ret < 0) return ret; return ret; } static int mt9p031_s_stream(struct v4l2_subdev *subdev, int enable) { struct mt9p031 *mt9p031 = to_mt9p031(subdev); struct i2c_client *client = v4l2_get_subdevdata(subdev); int val; int ret; if (!enable) { /* enable pause restart */ val = MT9P031_FRAME_PAUSE_RESTART; ret = mt9p031_write(client, MT9P031_RESTART, val); if (ret < 0) return ret; /* enable restart + keep pause restart set */ val |= MT9P031_FRAME_RESTART; ret = mt9p031_write(client, MT9P031_RESTART, val); if (ret < 0) return ret; /* Stop sensor readout */ ret = mt9p031_set_output_control(mt9p031, MT9P031_OUTPUT_CONTROL_CEN, 0); if (ret < 0) return ret; return mt9p031_pll_disable(mt9p031); } ret = mt9p031_set_params(mt9p031); if (ret < 0) return ret; /* Switch to master "normal" mode */ ret = mt9p031_set_output_control(mt9p031, 0, MT9P031_OUTPUT_CONTROL_CEN); if (ret < 0) return ret; /* * - clear pause restart * - don't clear restart as clearing restart manually can cause * undefined behavior */ val = MT9P031_FRAME_RESTART; ret = mt9p031_write(client, MT9P031_RESTART, val); if (ret < 0) return ret; return mt9p031_pll_enable(mt9p031); } static int mt9p031_enum_mbus_code(struct v4l2_subdev *subdev, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_mbus_code_enum *code) { struct mt9p031 *mt9p031 = to_mt9p031(subdev); if (code->pad || code->index) return -EINVAL; code->code = mt9p031->format.code; return 0; } static int mt9p031_enum_frame_size(struct v4l2_subdev *subdev, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_frame_size_enum *fse) { struct mt9p031 *mt9p031 = to_mt9p031(subdev); if (fse->index >= 8 || fse->code != mt9p031->format.code) return -EINVAL; fse->min_width = MT9P031_WINDOW_WIDTH_DEF / min_t(unsigned int, 7, fse->index + 1); fse->max_width = fse->min_width; fse->min_height = MT9P031_WINDOW_HEIGHT_DEF / (fse->index + 1); fse->max_height = fse->min_height; return 0; } static struct v4l2_mbus_framefmt * __mt9p031_get_pad_format(struct mt9p031 *mt9p031, struct v4l2_subdev_state *sd_state, unsigned int pad, u32 which) { switch (which) { case V4L2_SUBDEV_FORMAT_TRY: return v4l2_subdev_get_try_format(&mt9p031->subdev, sd_state, pad); case V4L2_SUBDEV_FORMAT_ACTIVE: return &mt9p031->format; default: return NULL; } } static struct v4l2_rect * __mt9p031_get_pad_crop(struct mt9p031 *mt9p031, struct v4l2_subdev_state *sd_state, unsigned int pad, u32 which) { switch (which) { case V4L2_SUBDEV_FORMAT_TRY: return v4l2_subdev_get_try_crop(&mt9p031->subdev, sd_state, pad); case V4L2_SUBDEV_FORMAT_ACTIVE: return &mt9p031->crop; default: return NULL; } } static int mt9p031_get_format(struct v4l2_subdev *subdev, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *fmt) { struct mt9p031 *mt9p031 = to_mt9p031(subdev); fmt->format = *__mt9p031_get_pad_format(mt9p031, sd_state, fmt->pad, fmt->which); return 0; } static int mt9p031_set_format(struct v4l2_subdev *subdev, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *format) { struct mt9p031 *mt9p031 = to_mt9p031(subdev); struct v4l2_mbus_framefmt *__format; struct v4l2_rect *__crop; unsigned int width; unsigned int height; unsigned int hratio; unsigned int vratio; __crop = __mt9p031_get_pad_crop(mt9p031, sd_state, format->pad, format->which); /* Clamp the width and height to avoid dividing by zero. */ width = clamp_t(unsigned int, ALIGN(format->format.width, 2), max_t(unsigned int, __crop->width / 7, MT9P031_WINDOW_WIDTH_MIN), __crop->width); height = clamp_t(unsigned int, ALIGN(format->format.height, 2), max_t(unsigned int, __crop->height / 8, MT9P031_WINDOW_HEIGHT_MIN), __crop->height); hratio = DIV_ROUND_CLOSEST(__crop->width, width); vratio = DIV_ROUND_CLOSEST(__crop->height, height); __format = __mt9p031_get_pad_format(mt9p031, sd_state, format->pad, format->which); __format->width = __crop->width / hratio; __format->height = __crop->height / vratio; format->format = *__format; return 0; } static int mt9p031_get_selection(struct v4l2_subdev *subdev, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_selection *sel) { struct mt9p031 *mt9p031 = to_mt9p031(subdev); switch (sel->target) { case V4L2_SEL_TGT_CROP_BOUNDS: sel->r.left = MT9P031_COLUMN_START_MIN; sel->r.top = MT9P031_ROW_START_MIN; sel->r.width = MT9P031_WINDOW_WIDTH_MAX; sel->r.height = MT9P031_WINDOW_HEIGHT_MAX; return 0; case V4L2_SEL_TGT_CROP: sel->r = *__mt9p031_get_pad_crop(mt9p031, sd_state, sel->pad, sel->which); return 0; default: return -EINVAL; } } static int mt9p031_set_selection(struct v4l2_subdev *subdev, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_selection *sel) { struct mt9p031 *mt9p031 = to_mt9p031(subdev); struct v4l2_mbus_framefmt *__format; struct v4l2_rect *__crop; struct v4l2_rect rect; if (sel->target != V4L2_SEL_TGT_CROP) return -EINVAL; /* Clamp the crop rectangle boundaries and align them to a multiple of 2 * pixels to ensure a GRBG Bayer pattern. */ rect.left = clamp(ALIGN(sel->r.left, 2), MT9P031_COLUMN_START_MIN, MT9P031_COLUMN_START_MAX); rect.top = clamp(ALIGN(sel->r.top, 2), MT9P031_ROW_START_MIN, MT9P031_ROW_START_MAX); rect.width = clamp_t(unsigned int, ALIGN(sel->r.width, 2), MT9P031_WINDOW_WIDTH_MIN, MT9P031_WINDOW_WIDTH_MAX); rect.height = clamp_t(unsigned int, ALIGN(sel->r.height, 2), MT9P031_WINDOW_HEIGHT_MIN, MT9P031_WINDOW_HEIGHT_MAX); rect.width = min_t(unsigned int, rect.width, MT9P031_PIXEL_ARRAY_WIDTH - rect.left); rect.height = min_t(unsigned int, rect.height, MT9P031_PIXEL_ARRAY_HEIGHT - rect.top); __crop = __mt9p031_get_pad_crop(mt9p031, sd_state, sel->pad, sel->which); if (rect.width != __crop->width || rect.height != __crop->height) { /* Reset the output image size if the crop rectangle size has * been modified. */ __format = __mt9p031_get_pad_format(mt9p031, sd_state, sel->pad, sel->which); __format->width = rect.width; __format->height = rect.height; } *__crop = rect; sel->r = rect; return 0; } static int mt9p031_init_cfg(struct v4l2_subdev *subdev, struct v4l2_subdev_state *sd_state) { struct mt9p031 *mt9p031 = to_mt9p031(subdev); struct v4l2_mbus_framefmt *format; struct v4l2_rect *crop; const int which = sd_state == NULL ? V4L2_SUBDEV_FORMAT_ACTIVE : V4L2_SUBDEV_FORMAT_TRY; crop = __mt9p031_get_pad_crop(mt9p031, sd_state, 0, which); crop->left = MT9P031_COLUMN_START_DEF; crop->top = MT9P031_ROW_START_DEF; crop->width = MT9P031_WINDOW_WIDTH_DEF; crop->height = MT9P031_WINDOW_HEIGHT_DEF; format = __mt9p031_get_pad_format(mt9p031, sd_state, 0, which); if (mt9p031->model == MT9P031_MODEL_MONOCHROME) format->code = MEDIA_BUS_FMT_Y12_1X12; else format->code = MEDIA_BUS_FMT_SGRBG12_1X12; format->width = MT9P031_WINDOW_WIDTH_DEF; format->height = MT9P031_WINDOW_HEIGHT_DEF; format->field = V4L2_FIELD_NONE; format->colorspace = V4L2_COLORSPACE_SRGB; return 0; } /* ----------------------------------------------------------------------------- * V4L2 subdev control operations */ #define V4L2_CID_BLC_AUTO (V4L2_CID_USER_BASE | 0x1002) #define V4L2_CID_BLC_TARGET_LEVEL (V4L2_CID_USER_BASE | 0x1003) #define V4L2_CID_BLC_ANALOG_OFFSET (V4L2_CID_USER_BASE | 0x1004) #define V4L2_CID_BLC_DIGITAL_OFFSET (V4L2_CID_USER_BASE | 0x1005) static int mt9p031_restore_blc(struct mt9p031 *mt9p031) { struct i2c_client *client = v4l2_get_subdevdata(&mt9p031->subdev); int ret; if (mt9p031->blc_auto->cur.val != 0) { ret = mt9p031_set_mode2(mt9p031, 0, MT9P031_READ_MODE_2_ROW_BLC); if (ret < 0) return ret; } if (mt9p031->blc_offset->cur.val != 0) { ret = mt9p031_write(client, MT9P031_ROW_BLACK_TARGET, mt9p031->blc_offset->cur.val); if (ret < 0) return ret; } return 0; } static int mt9p031_s_ctrl(struct v4l2_ctrl *ctrl) { struct mt9p031 *mt9p031 = container_of(ctrl->handler, struct mt9p031, ctrls); struct i2c_client *client = v4l2_get_subdevdata(&mt9p031->subdev); u16 data; int ret; if (ctrl->flags & V4L2_CTRL_FLAG_INACTIVE) return 0; switch (ctrl->id) { case V4L2_CID_EXPOSURE: ret = mt9p031_write(client, MT9P031_SHUTTER_WIDTH_UPPER, (ctrl->val >> 16) & 0xffff); if (ret < 0) return ret; return mt9p031_write(client, MT9P031_SHUTTER_WIDTH_LOWER, ctrl->val & 0xffff); case V4L2_CID_GAIN: /* Gain is controlled by 2 analog stages and a digital stage. * Valid values for the 3 stages are * * Stage Min Max Step * ------------------------------------------ * First analog stage x1 x2 1 * Second analog stage x1 x4 0.125 * Digital stage x1 x16 0.125 * * To minimize noise, the gain stages should be used in the * second analog stage, first analog stage, digital stage order. * Gain from a previous stage should be pushed to its maximum * value before the next stage is used. */ if (ctrl->val <= 32) { data = ctrl->val; } else if (ctrl->val <= 64) { ctrl->val &= ~1; data = (1 << 6) | (ctrl->val >> 1); } else { ctrl->val &= ~7; data = ((ctrl->val - 64) << 5) | (1 << 6) | 32; } return mt9p031_write(client, MT9P031_GLOBAL_GAIN, data); case V4L2_CID_HFLIP: if (ctrl->val) return mt9p031_set_mode2(mt9p031, 0, MT9P031_READ_MODE_2_COL_MIR); else return mt9p031_set_mode2(mt9p031, MT9P031_READ_MODE_2_COL_MIR, 0); case V4L2_CID_VFLIP: if (ctrl->val) return mt9p031_set_mode2(mt9p031, 0, MT9P031_READ_MODE_2_ROW_MIR); else return mt9p031_set_mode2(mt9p031, MT9P031_READ_MODE_2_ROW_MIR, 0); case V4L2_CID_TEST_PATTERN: /* The digital side of the Black Level Calibration function must * be disabled when generating a test pattern to avoid artifacts * in the image. Activate (deactivate) the BLC-related controls * when the test pattern is enabled (disabled). */ v4l2_ctrl_activate(mt9p031->blc_auto, ctrl->val == 0); v4l2_ctrl_activate(mt9p031->blc_offset, ctrl->val == 0); if (!ctrl->val) { /* Restore the BLC settings. */ ret = mt9p031_restore_blc(mt9p031); if (ret < 0) return ret; return mt9p031_write(client, MT9P031_TEST_PATTERN, 0); } ret = mt9p031_write(client, MT9P031_TEST_PATTERN_GREEN, 0x05a0); if (ret < 0) return ret; ret = mt9p031_write(client, MT9P031_TEST_PATTERN_RED, 0x0a50); if (ret < 0) return ret; ret = mt9p031_write(client, MT9P031_TEST_PATTERN_BLUE, 0x0aa0); if (ret < 0) return ret; /* Disable digital BLC when generating a test pattern. */ ret = mt9p031_set_mode2(mt9p031, MT9P031_READ_MODE_2_ROW_BLC, 0); if (ret < 0) return ret; ret = mt9p031_write(client, MT9P031_ROW_BLACK_DEF_OFFSET, 0); if (ret < 0) return ret; return mt9p031_write(client, MT9P031_TEST_PATTERN, ((ctrl->val - 1) << MT9P031_TEST_PATTERN_SHIFT) | MT9P031_TEST_PATTERN_ENABLE); case V4L2_CID_BLC_AUTO: ret = mt9p031_set_mode2(mt9p031, ctrl->val ? 0 : MT9P031_READ_MODE_2_ROW_BLC, ctrl->val ? MT9P031_READ_MODE_2_ROW_BLC : 0); if (ret < 0) return ret; return mt9p031_write(client, MT9P031_BLACK_LEVEL_CALIBRATION, ctrl->val ? 0 : MT9P031_BLC_MANUAL_BLC); case V4L2_CID_BLC_TARGET_LEVEL: return mt9p031_write(client, MT9P031_ROW_BLACK_TARGET, ctrl->val); case V4L2_CID_BLC_ANALOG_OFFSET: data = ctrl->val & ((1 << 9) - 1); ret = mt9p031_write(client, MT9P031_GREEN1_OFFSET, data); if (ret < 0) return ret; ret = mt9p031_write(client, MT9P031_GREEN2_OFFSET, data); if (ret < 0) return ret; ret = mt9p031_write(client, MT9P031_RED_OFFSET, data); if (ret < 0) return ret; return mt9p031_write(client, MT9P031_BLUE_OFFSET, data); case V4L2_CID_BLC_DIGITAL_OFFSET: return mt9p031_write(client, MT9P031_ROW_BLACK_DEF_OFFSET, ctrl->val & ((1 << 12) - 1)); } return 0; } static const struct v4l2_ctrl_ops mt9p031_ctrl_ops = { .s_ctrl = mt9p031_s_ctrl, }; static const char * const mt9p031_test_pattern_menu[] = { "Disabled", "Color Field", "Horizontal Gradient", "Vertical Gradient", "Diagonal Gradient", "Classic Test Pattern", "Walking 1s", "Monochrome Horizontal Bars", "Monochrome Vertical Bars", "Vertical Color Bars", }; static const struct v4l2_ctrl_config mt9p031_ctrls[] = { { .ops = &mt9p031_ctrl_ops, .id = V4L2_CID_BLC_AUTO, .type = V4L2_CTRL_TYPE_BOOLEAN, .name = "BLC, Auto", .min = 0, .max = 1, .step = 1, .def = 1, .flags = 0, }, { .ops = &mt9p031_ctrl_ops, .id = V4L2_CID_BLC_TARGET_LEVEL, .type = V4L2_CTRL_TYPE_INTEGER, .name = "BLC Target Level", .min = 0, .max = 4095, .step = 1, .def = 168, .flags = 0, }, { .ops = &mt9p031_ctrl_ops, .id = V4L2_CID_BLC_ANALOG_OFFSET, .type = V4L2_CTRL_TYPE_INTEGER, .name = "BLC Analog Offset", .min = -255, .max = 255, .step = 1, .def = 32, .flags = 0, }, { .ops = &mt9p031_ctrl_ops, .id = V4L2_CID_BLC_DIGITAL_OFFSET, .type = V4L2_CTRL_TYPE_INTEGER, .name = "BLC Digital Offset", .min = -2048, .max = 2047, .step = 1, .def = 40, .flags = 0, } }; /* ----------------------------------------------------------------------------- * V4L2 subdev core operations */ static int mt9p031_set_power(struct v4l2_subdev *subdev, int on) { struct mt9p031 *mt9p031 = to_mt9p031(subdev); int ret = 0; mutex_lock(&mt9p031->power_lock); /* If the power count is modified from 0 to != 0 or from != 0 to 0, * update the power state. */ if (mt9p031->power_count == !on) { ret = __mt9p031_set_power(mt9p031, !!on); if (ret < 0) goto out; } /* Update the power count. */ mt9p031->power_count += on ? 1 : -1; WARN_ON(mt9p031->power_count < 0); out: mutex_unlock(&mt9p031->power_lock); return ret; } /* ----------------------------------------------------------------------------- * V4L2 subdev internal operations */ static int mt9p031_registered(struct v4l2_subdev *subdev) { struct i2c_client *client = v4l2_get_subdevdata(subdev); struct mt9p031 *mt9p031 = to_mt9p031(subdev); s32 data; int ret; ret = mt9p031_power_on(mt9p031); if (ret < 0) { dev_err(&client->dev, "MT9P031 power up failed\n"); return ret; } /* Read out the chip version register */ data = mt9p031_read(client, MT9P031_CHIP_VERSION); mt9p031_power_off(mt9p031); if (data != MT9P031_CHIP_VERSION_VALUE) { dev_err(&client->dev, "MT9P031 not detected, wrong version " "0x%04x\n", data); return -ENODEV; } dev_info(&client->dev, "MT9P031 detected at address 0x%02x\n", client->addr); return 0; } static int mt9p031_open(struct v4l2_subdev *subdev, struct v4l2_subdev_fh *fh) { return mt9p031_set_power(subdev, 1); } static int mt9p031_close(struct v4l2_subdev *subdev, struct v4l2_subdev_fh *fh) { return mt9p031_set_power(subdev, 0); } static const struct v4l2_subdev_core_ops mt9p031_subdev_core_ops = { .s_power = mt9p031_set_power, }; static const struct v4l2_subdev_video_ops mt9p031_subdev_video_ops = { .s_stream = mt9p031_s_stream, }; static const struct v4l2_subdev_pad_ops mt9p031_subdev_pad_ops = { .init_cfg = mt9p031_init_cfg, .enum_mbus_code = mt9p031_enum_mbus_code, .enum_frame_size = mt9p031_enum_frame_size, .get_fmt = mt9p031_get_format, .set_fmt = mt9p031_set_format, .get_selection = mt9p031_get_selection, .set_selection = mt9p031_set_selection, }; static const struct v4l2_subdev_ops mt9p031_subdev_ops = { .core = &mt9p031_subdev_core_ops, .video = &mt9p031_subdev_video_ops, .pad = &mt9p031_subdev_pad_ops, }; static const struct v4l2_subdev_internal_ops mt9p031_subdev_internal_ops = { .registered = mt9p031_registered, .open = mt9p031_open, .close = mt9p031_close, }; /* ----------------------------------------------------------------------------- * Driver initialization and probing */ static struct mt9p031_platform_data * mt9p031_get_pdata(struct i2c_client *client) { struct mt9p031_platform_data *pdata = NULL; struct device_node *np; struct v4l2_fwnode_endpoint endpoint = { .bus_type = V4L2_MBUS_PARALLEL }; if (!IS_ENABLED(CONFIG_OF) || !client->dev.of_node) return client->dev.platform_data; np = of_graph_get_next_endpoint(client->dev.of_node, NULL); if (!np) return NULL; if (v4l2_fwnode_endpoint_parse(of_fwnode_handle(np), &endpoint) < 0) goto done; pdata = devm_kzalloc(&client->dev, sizeof(*pdata), GFP_KERNEL); if (!pdata) goto done; of_property_read_u32(np, "input-clock-frequency", &pdata->ext_freq); of_property_read_u32(np, "pixel-clock-frequency", &pdata->target_freq); pdata->pixclk_pol = !!(endpoint.bus.parallel.flags & V4L2_MBUS_PCLK_SAMPLE_RISING); done: of_node_put(np); return pdata; } static int mt9p031_probe(struct i2c_client *client) { const struct i2c_device_id *did = i2c_client_get_device_id(client); struct mt9p031_platform_data *pdata = mt9p031_get_pdata(client); struct i2c_adapter *adapter = client->adapter; struct mt9p031 *mt9p031; unsigned int i; int ret; if (pdata == NULL) { dev_err(&client->dev, "No platform data\n"); return -EINVAL; } if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_WORD_DATA)) { dev_warn(&client->dev, "I2C-Adapter doesn't support I2C_FUNC_SMBUS_WORD\n"); return -EIO; } mt9p031 = devm_kzalloc(&client->dev, sizeof(*mt9p031), GFP_KERNEL); if (mt9p031 == NULL) return -ENOMEM; mt9p031->pdata = pdata; mt9p031->output_control = MT9P031_OUTPUT_CONTROL_DEF; mt9p031->mode2 = MT9P031_READ_MODE_2_ROW_BLC; mt9p031->model = did->driver_data; mt9p031->regulators[0].supply = "vdd"; mt9p031->regulators[1].supply = "vdd_io"; mt9p031->regulators[2].supply = "vaa"; ret = devm_regulator_bulk_get(&client->dev, 3, mt9p031->regulators); if (ret < 0) { dev_err(&client->dev, "Unable to get regulators\n"); return ret; } mutex_init(&mt9p031->power_lock); v4l2_ctrl_handler_init(&mt9p031->ctrls, ARRAY_SIZE(mt9p031_ctrls) + 6); v4l2_ctrl_new_std(&mt9p031->ctrls, &mt9p031_ctrl_ops, V4L2_CID_EXPOSURE, MT9P031_SHUTTER_WIDTH_MIN, MT9P031_SHUTTER_WIDTH_MAX, 1, MT9P031_SHUTTER_WIDTH_DEF); v4l2_ctrl_new_std(&mt9p031->ctrls, &mt9p031_ctrl_ops, V4L2_CID_GAIN, MT9P031_GLOBAL_GAIN_MIN, MT9P031_GLOBAL_GAIN_MAX, 1, MT9P031_GLOBAL_GAIN_DEF); v4l2_ctrl_new_std(&mt9p031->ctrls, &mt9p031_ctrl_ops, V4L2_CID_HFLIP, 0, 1, 1, 0); v4l2_ctrl_new_std(&mt9p031->ctrls, &mt9p031_ctrl_ops, V4L2_CID_VFLIP, 0, 1, 1, 0); v4l2_ctrl_new_std(&mt9p031->ctrls, &mt9p031_ctrl_ops, V4L2_CID_PIXEL_RATE, pdata->target_freq, pdata->target_freq, 1, pdata->target_freq); v4l2_ctrl_new_std_menu_items(&mt9p031->ctrls, &mt9p031_ctrl_ops, V4L2_CID_TEST_PATTERN, ARRAY_SIZE(mt9p031_test_pattern_menu) - 1, 0, 0, mt9p031_test_pattern_menu); for (i = 0; i < ARRAY_SIZE(mt9p031_ctrls); ++i) v4l2_ctrl_new_custom(&mt9p031->ctrls, &mt9p031_ctrls[i], NULL); mt9p031->subdev.ctrl_handler = &mt9p031->ctrls; if (mt9p031->ctrls.error) { printk(KERN_INFO "%s: control initialization error %d\n", __func__, mt9p031->ctrls.error); ret = mt9p031->ctrls.error; goto done; } mt9p031->blc_auto = v4l2_ctrl_find(&mt9p031->ctrls, V4L2_CID_BLC_AUTO); mt9p031->blc_offset = v4l2_ctrl_find(&mt9p031->ctrls, V4L2_CID_BLC_DIGITAL_OFFSET); v4l2_i2c_subdev_init(&mt9p031->subdev, client, &mt9p031_subdev_ops); mt9p031->subdev.internal_ops = &mt9p031_subdev_internal_ops; mt9p031->subdev.entity.function = MEDIA_ENT_F_CAM_SENSOR; mt9p031->pad.flags = MEDIA_PAD_FL_SOURCE; ret = media_entity_pads_init(&mt9p031->subdev.entity, 1, &mt9p031->pad); if (ret < 0) goto done; mt9p031->subdev.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE; ret = mt9p031_init_cfg(&mt9p031->subdev, NULL); if (ret) goto done; mt9p031->reset = devm_gpiod_get_optional(&client->dev, "reset", GPIOD_OUT_HIGH); ret = mt9p031_clk_setup(mt9p031); if (ret) goto done; ret = v4l2_async_register_subdev(&mt9p031->subdev); done: if (ret < 0) { v4l2_ctrl_handler_free(&mt9p031->ctrls); media_entity_cleanup(&mt9p031->subdev.entity); mutex_destroy(&mt9p031->power_lock); } return ret; } static void mt9p031_remove(struct i2c_client *client) { struct v4l2_subdev *subdev = i2c_get_clientdata(client); struct mt9p031 *mt9p031 = to_mt9p031(subdev); v4l2_ctrl_handler_free(&mt9p031->ctrls); v4l2_async_unregister_subdev(subdev); media_entity_cleanup(&subdev->entity); mutex_destroy(&mt9p031->power_lock); } static const struct i2c_device_id mt9p031_id[] = { { "mt9p006", MT9P031_MODEL_COLOR }, { "mt9p031", MT9P031_MODEL_COLOR }, { "mt9p031m", MT9P031_MODEL_MONOCHROME }, { } }; MODULE_DEVICE_TABLE(i2c, mt9p031_id); #if IS_ENABLED(CONFIG_OF) static const struct of_device_id mt9p031_of_match[] = { { .compatible = "aptina,mt9p006", }, { .compatible = "aptina,mt9p031", }, { .compatible = "aptina,mt9p031m", }, { /* sentinel */ }, }; MODULE_DEVICE_TABLE(of, mt9p031_of_match); #endif static struct i2c_driver mt9p031_i2c_driver = { .driver = { .of_match_table = of_match_ptr(mt9p031_of_match), .name = "mt9p031", }, .probe = mt9p031_probe, .remove = mt9p031_remove, .id_table = mt9p031_id, }; module_i2c_driver(mt9p031_i2c_driver); MODULE_DESCRIPTION("Aptina MT9P031 Camera driver"); MODULE_AUTHOR("Bastian Hecht <[email protected]>"); MODULE_LICENSE("GPL v2");
linux-master
drivers/media/i2c/mt9p031.c
// SPDX-License-Identifier: GPL-2.0-only /* * Driver for Samsung S5K5BAF UXGA 1/5" 2M CMOS Image Sensor * with embedded SoC ISP. * * Copyright (C) 2013, Samsung Electronics Co., Ltd. * Andrzej Hajda <[email protected]> * * Based on S5K6AA driver authored by Sylwester Nawrocki * Copyright (C) 2013, Samsung Electronics Co., Ltd. */ #include <linux/clk.h> #include <linux/delay.h> #include <linux/firmware.h> #include <linux/gpio/consumer.h> #include <linux/i2c.h> #include <linux/media.h> #include <linux/module.h> #include <linux/of_graph.h> #include <linux/regulator/consumer.h> #include <linux/slab.h> #include <media/media-entity.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-device.h> #include <media/v4l2-subdev.h> #include <media/v4l2-mediabus.h> #include <media/v4l2-fwnode.h> static int debug; module_param(debug, int, 0644); #define S5K5BAF_DRIVER_NAME "s5k5baf" #define S5K5BAF_DEFAULT_MCLK_FREQ 24000000U #define S5K5BAF_CLK_NAME "mclk" #define S5K5BAF_FW_FILENAME "s5k5baf-cfg.bin" #define S5K5BAF_FW_TAG "SF00" #define S5K5BAG_FW_TAG_LEN 2 #define S5K5BAG_FW_MAX_COUNT 16 #define S5K5BAF_CIS_WIDTH 1600 #define S5K5BAF_CIS_HEIGHT 1200 #define S5K5BAF_WIN_WIDTH_MIN 8 #define S5K5BAF_WIN_HEIGHT_MIN 8 #define S5K5BAF_GAIN_RED_DEF 127 #define S5K5BAF_GAIN_GREEN_DEF 95 #define S5K5BAF_GAIN_BLUE_DEF 180 /* Default number of MIPI CSI-2 data lanes used */ #define S5K5BAF_DEF_NUM_LANES 1 #define AHB_MSB_ADDR_PTR 0xfcfc /* * Register interface pages (the most significant word of the address) */ #define PAGE_IF_HW 0xd000 #define PAGE_IF_SW 0x7000 /* * H/W register Interface (PAGE_IF_HW) */ #define REG_SW_LOAD_COMPLETE 0x0014 #define REG_CMDWR_PAGE 0x0028 #define REG_CMDWR_ADDR 0x002a #define REG_CMDRD_PAGE 0x002c #define REG_CMDRD_ADDR 0x002e #define REG_CMD_BUF 0x0f12 #define REG_SET_HOST_INT 0x1000 #define REG_CLEAR_HOST_INT 0x1030 #define REG_PATTERN_SET 0x3100 #define REG_PATTERN_WIDTH 0x3118 #define REG_PATTERN_HEIGHT 0x311a #define REG_PATTERN_PARAM 0x311c /* * S/W register interface (PAGE_IF_SW) */ /* Firmware revision information */ #define REG_FW_APIVER 0x012e #define S5K5BAF_FW_APIVER 0x0001 #define REG_FW_REVISION 0x0130 #define REG_FW_SENSOR_ID 0x0152 /* Initialization parameters */ /* Master clock frequency in KHz */ #define REG_I_INCLK_FREQ_L 0x01b8 #define REG_I_INCLK_FREQ_H 0x01ba #define MIN_MCLK_FREQ_KHZ 6000U #define MAX_MCLK_FREQ_KHZ 48000U #define REG_I_USE_NPVI_CLOCKS 0x01c6 #define NPVI_CLOCKS 1 #define REG_I_USE_NMIPI_CLOCKS 0x01c8 #define NMIPI_CLOCKS 1 #define REG_I_BLOCK_INTERNAL_PLL_CALC 0x01ca /* Clock configurations, n = 0..2. REG_I_* frequency unit is 4 kHz. */ #define REG_I_OPCLK_4KHZ(n) ((n) * 6 + 0x01cc) #define REG_I_MIN_OUTRATE_4KHZ(n) ((n) * 6 + 0x01ce) #define REG_I_MAX_OUTRATE_4KHZ(n) ((n) * 6 + 0x01d0) #define SCLK_PVI_FREQ 24000 #define SCLK_MIPI_FREQ 48000 #define PCLK_MIN_FREQ 6000 #define PCLK_MAX_FREQ 48000 #define REG_I_USE_REGS_API 0x01de #define REG_I_INIT_PARAMS_UPDATED 0x01e0 #define REG_I_ERROR_INFO 0x01e2 /* General purpose parameters */ #define REG_USER_BRIGHTNESS 0x01e4 #define REG_USER_CONTRAST 0x01e6 #define REG_USER_SATURATION 0x01e8 #define REG_USER_SHARPBLUR 0x01ea #define REG_G_SPEC_EFFECTS 0x01ee #define REG_G_ENABLE_PREV 0x01f0 #define REG_G_ENABLE_PREV_CHG 0x01f2 #define REG_G_NEW_CFG_SYNC 0x01f8 #define REG_G_PREVREQ_IN_WIDTH 0x01fa #define REG_G_PREVREQ_IN_HEIGHT 0x01fc #define REG_G_PREVREQ_IN_XOFFS 0x01fe #define REG_G_PREVREQ_IN_YOFFS 0x0200 #define REG_G_PREVZOOM_IN_WIDTH 0x020a #define REG_G_PREVZOOM_IN_HEIGHT 0x020c #define REG_G_PREVZOOM_IN_XOFFS 0x020e #define REG_G_PREVZOOM_IN_YOFFS 0x0210 #define REG_G_INPUTS_CHANGE_REQ 0x021a #define REG_G_ACTIVE_PREV_CFG 0x021c #define REG_G_PREV_CFG_CHG 0x021e #define REG_G_PREV_OPEN_AFTER_CH 0x0220 #define REG_G_PREV_CFG_ERROR 0x0222 #define CFG_ERROR_RANGE 0x0b #define REG_G_PREV_CFG_BYPASS_CHANGED 0x022a #define REG_G_ACTUAL_P_FR_TIME 0x023a #define REG_G_ACTUAL_P_OUT_RATE 0x023c #define REG_G_ACTUAL_C_FR_TIME 0x023e #define REG_G_ACTUAL_C_OUT_RATE 0x0240 /* Preview control section. n = 0...4. */ #define PREG(n, x) ((n) * 0x26 + x) #define REG_P_OUT_WIDTH(n) PREG(n, 0x0242) #define REG_P_OUT_HEIGHT(n) PREG(n, 0x0244) #define REG_P_FMT(n) PREG(n, 0x0246) #define REG_P_MAX_OUT_RATE(n) PREG(n, 0x0248) #define REG_P_MIN_OUT_RATE(n) PREG(n, 0x024a) #define REG_P_PVI_MASK(n) PREG(n, 0x024c) #define PVI_MASK_MIPI 0x52 #define REG_P_CLK_INDEX(n) PREG(n, 0x024e) #define CLK_PVI_INDEX 0 #define CLK_MIPI_INDEX NPVI_CLOCKS #define REG_P_FR_RATE_TYPE(n) PREG(n, 0x0250) #define FR_RATE_DYNAMIC 0 #define FR_RATE_FIXED 1 #define FR_RATE_FIXED_ACCURATE 2 #define REG_P_FR_RATE_Q_TYPE(n) PREG(n, 0x0252) #define FR_RATE_Q_DYNAMIC 0 #define FR_RATE_Q_BEST_FRRATE 1 /* Binning enabled */ #define FR_RATE_Q_BEST_QUALITY 2 /* Binning disabled */ /* Frame period in 0.1 ms units */ #define REG_P_MAX_FR_TIME(n) PREG(n, 0x0254) #define REG_P_MIN_FR_TIME(n) PREG(n, 0x0256) #define S5K5BAF_MIN_FR_TIME 333 /* x100 us */ #define S5K5BAF_MAX_FR_TIME 6500 /* x100 us */ /* The below 5 registers are for "device correction" values */ #define REG_P_SATURATION(n) PREG(n, 0x0258) #define REG_P_SHARP_BLUR(n) PREG(n, 0x025a) #define REG_P_GLAMOUR(n) PREG(n, 0x025c) #define REG_P_COLORTEMP(n) PREG(n, 0x025e) #define REG_P_GAMMA_INDEX(n) PREG(n, 0x0260) #define REG_P_PREV_MIRROR(n) PREG(n, 0x0262) #define REG_P_CAP_MIRROR(n) PREG(n, 0x0264) #define REG_P_CAP_ROTATION(n) PREG(n, 0x0266) /* Extended image property controls */ /* Exposure time in 10 us units */ #define REG_SF_USR_EXPOSURE_L 0x03bc #define REG_SF_USR_EXPOSURE_H 0x03be #define REG_SF_USR_EXPOSURE_CHG 0x03c0 #define REG_SF_USR_TOT_GAIN 0x03c2 #define REG_SF_USR_TOT_GAIN_CHG 0x03c4 #define REG_SF_RGAIN 0x03c6 #define REG_SF_RGAIN_CHG 0x03c8 #define REG_SF_GGAIN 0x03ca #define REG_SF_GGAIN_CHG 0x03cc #define REG_SF_BGAIN 0x03ce #define REG_SF_BGAIN_CHG 0x03d0 #define REG_SF_WBGAIN_CHG 0x03d2 #define REG_SF_FLICKER_QUANT 0x03d4 #define REG_SF_FLICKER_QUANT_CHG 0x03d6 /* Output interface (parallel/MIPI) setup */ #define REG_OIF_EN_MIPI_LANES 0x03f2 #define REG_OIF_EN_PACKETS 0x03f4 #define EN_PACKETS_CSI2 0xc3 #define REG_OIF_CFG_CHG 0x03f6 /* Auto-algorithms enable mask */ #define REG_DBG_AUTOALG_EN 0x03f8 #define AALG_ALL_EN BIT(0) #define AALG_AE_EN BIT(1) #define AALG_DIVLEI_EN BIT(2) #define AALG_WB_EN BIT(3) #define AALG_USE_WB_FOR_ISP BIT(4) #define AALG_FLICKER_EN BIT(5) #define AALG_FIT_EN BIT(6) #define AALG_WRHW_EN BIT(7) /* Pointers to color correction matrices */ #define REG_PTR_CCM_HORIZON 0x06d0 #define REG_PTR_CCM_INCANDESCENT 0x06d4 #define REG_PTR_CCM_WARM_WHITE 0x06d8 #define REG_PTR_CCM_COOL_WHITE 0x06dc #define REG_PTR_CCM_DL50 0x06e0 #define REG_PTR_CCM_DL65 0x06e4 #define REG_PTR_CCM_OUTDOOR 0x06ec #define REG_ARR_CCM(n) (0x2800 + 36 * (n)) static const char * const s5k5baf_supply_names[] = { "vdda", /* Analog power supply 2.8V (2.6V to 3.0V) */ "vddreg", /* Regulator input power supply 1.8V (1.7V to 1.9V) or 2.8V (2.6V to 3.0) */ "vddio", /* I/O power supply 1.8V (1.65V to 1.95V) or 2.8V (2.5V to 3.1V) */ }; #define S5K5BAF_NUM_SUPPLIES ARRAY_SIZE(s5k5baf_supply_names) enum s5k5baf_gpio_id { STBY, RSET, NUM_GPIOS, }; #define PAD_CIS 0 #define PAD_OUT 1 #define NUM_CIS_PADS 1 #define NUM_ISP_PADS 2 struct s5k5baf_pixfmt { u32 code; u32 colorspace; /* REG_P_FMT(x) register value */ u16 reg_p_fmt; }; struct s5k5baf_ctrls { struct v4l2_ctrl_handler handler; struct { /* Auto / manual white balance cluster */ struct v4l2_ctrl *awb; struct v4l2_ctrl *gain_red; struct v4l2_ctrl *gain_blue; }; struct { /* Mirror cluster */ struct v4l2_ctrl *hflip; struct v4l2_ctrl *vflip; }; struct { /* Auto exposure / manual exposure and gain cluster */ struct v4l2_ctrl *auto_exp; struct v4l2_ctrl *exposure; struct v4l2_ctrl *gain; }; }; enum { S5K5BAF_FW_ID_PATCH, S5K5BAF_FW_ID_CCM, S5K5BAF_FW_ID_CIS, }; struct s5k5baf_fw { u16 count; struct { u16 id; u16 offset; } seq[]; }; struct s5k5baf { struct gpio_desc *gpios[NUM_GPIOS]; enum v4l2_mbus_type bus_type; u8 nlanes; struct regulator_bulk_data supplies[S5K5BAF_NUM_SUPPLIES]; struct clk *clock; u32 mclk_frequency; struct s5k5baf_fw *fw; struct v4l2_subdev cis_sd; struct media_pad cis_pad; struct v4l2_subdev sd; struct media_pad pads[NUM_ISP_PADS]; /* protects the struct members below */ struct mutex lock; int error; struct v4l2_rect crop_sink; struct v4l2_rect compose; struct v4l2_rect crop_source; /* index to s5k5baf_formats array */ int pixfmt; /* actual frame interval in 100us */ u16 fiv; /* requested frame interval in 100us */ u16 req_fiv; /* cache for REG_DBG_AUTOALG_EN register */ u16 auto_alg; struct s5k5baf_ctrls ctrls; unsigned int streaming:1; unsigned int apply_cfg:1; unsigned int apply_crop:1; unsigned int valid_auto_alg:1; unsigned int power; }; static const struct s5k5baf_pixfmt s5k5baf_formats[] = { { MEDIA_BUS_FMT_VYUY8_2X8, V4L2_COLORSPACE_JPEG, 5 }, /* range 16-240 */ { MEDIA_BUS_FMT_VYUY8_2X8, V4L2_COLORSPACE_REC709, 6 }, { MEDIA_BUS_FMT_RGB565_2X8_BE, V4L2_COLORSPACE_JPEG, 0 }, }; static struct v4l2_rect s5k5baf_cis_rect = { 0, 0, S5K5BAF_CIS_WIDTH, S5K5BAF_CIS_HEIGHT }; /* Setfile contains set of I2C command sequences. Each sequence has its ID. * setfile format: * u8 magic[4]; * u16 count; number of sequences * struct { * u16 id; sequence id * u16 offset; sequence offset in data array * } seq[count]; * u16 data[*]; array containing sequences * */ static int s5k5baf_fw_parse(struct device *dev, struct s5k5baf_fw **fw, size_t count, const __le16 *data) { struct s5k5baf_fw *f; u16 *d, i, *end; int ret; if (count < S5K5BAG_FW_TAG_LEN + 1) { dev_err(dev, "firmware file too short (%zu)\n", count); return -EINVAL; } ret = memcmp(data, S5K5BAF_FW_TAG, S5K5BAG_FW_TAG_LEN * sizeof(u16)); if (ret != 0) { dev_err(dev, "invalid firmware magic number\n"); return -EINVAL; } data += S5K5BAG_FW_TAG_LEN; count -= S5K5BAG_FW_TAG_LEN; d = devm_kcalloc(dev, count, sizeof(u16), GFP_KERNEL); if (!d) return -ENOMEM; for (i = 0; i < count; ++i) d[i] = le16_to_cpu(data[i]); f = (struct s5k5baf_fw *)d; if (count < 1 + 2 * f->count) { dev_err(dev, "invalid firmware header (count=%d size=%zu)\n", f->count, 2 * (count + S5K5BAG_FW_TAG_LEN)); return -EINVAL; } end = d + count; d += 1 + 2 * f->count; for (i = 0; i < f->count; ++i) { if (f->seq[i].offset + d <= end) continue; dev_err(dev, "invalid firmware header (seq=%d)\n", i); return -EINVAL; } *fw = f; return 0; } static inline struct v4l2_subdev *ctrl_to_sd(struct v4l2_ctrl *ctrl) { return &container_of(ctrl->handler, struct s5k5baf, ctrls.handler)->sd; } static inline bool s5k5baf_is_cis_subdev(struct v4l2_subdev *sd) { return sd->entity.function == MEDIA_ENT_F_CAM_SENSOR; } static inline struct s5k5baf *to_s5k5baf(struct v4l2_subdev *sd) { if (s5k5baf_is_cis_subdev(sd)) return container_of(sd, struct s5k5baf, cis_sd); else return container_of(sd, struct s5k5baf, sd); } static u16 s5k5baf_i2c_read(struct s5k5baf *state, u16 addr) { struct i2c_client *c = v4l2_get_subdevdata(&state->sd); __be16 w, r; u16 res; struct i2c_msg msg[] = { { .addr = c->addr, .flags = 0, .len = 2, .buf = (u8 *)&w }, { .addr = c->addr, .flags = I2C_M_RD, .len = 2, .buf = (u8 *)&r }, }; int ret; if (state->error) return 0; w = cpu_to_be16(addr); ret = i2c_transfer(c->adapter, msg, 2); res = be16_to_cpu(r); v4l2_dbg(3, debug, c, "i2c_read: 0x%04x : 0x%04x\n", addr, res); if (ret != 2) { v4l2_err(c, "i2c_read: error during transfer (%d)\n", ret); state->error = ret; } return res; } static void s5k5baf_i2c_write(struct s5k5baf *state, u16 addr, u16 val) { u8 buf[4] = { addr >> 8, addr & 0xFF, val >> 8, val & 0xFF }; struct i2c_client *c = v4l2_get_subdevdata(&state->sd); int ret; if (state->error) return; ret = i2c_master_send(c, buf, 4); v4l2_dbg(3, debug, c, "i2c_write: 0x%04x : 0x%04x\n", addr, val); if (ret != 4) { v4l2_err(c, "i2c_write: error during transfer (%d)\n", ret); state->error = ret; } } static u16 s5k5baf_read(struct s5k5baf *state, u16 addr) { s5k5baf_i2c_write(state, REG_CMDRD_ADDR, addr); return s5k5baf_i2c_read(state, REG_CMD_BUF); } static void s5k5baf_write(struct s5k5baf *state, u16 addr, u16 val) { s5k5baf_i2c_write(state, REG_CMDWR_ADDR, addr); s5k5baf_i2c_write(state, REG_CMD_BUF, val); } static void s5k5baf_write_arr_seq(struct s5k5baf *state, u16 addr, u16 count, const u16 *seq) { struct i2c_client *c = v4l2_get_subdevdata(&state->sd); __be16 buf[65]; s5k5baf_i2c_write(state, REG_CMDWR_ADDR, addr); if (state->error) return; v4l2_dbg(3, debug, c, "i2c_write_seq(count=%d): %*ph\n", count, min(2 * count, 64), seq); buf[0] = cpu_to_be16(REG_CMD_BUF); while (count > 0) { int n = min_t(int, count, ARRAY_SIZE(buf) - 1); int ret, i; for (i = 1; i <= n; ++i) buf[i] = cpu_to_be16(*seq++); i *= 2; ret = i2c_master_send(c, (char *)buf, i); if (ret != i) { v4l2_err(c, "i2c_write_seq: error during transfer (%d)\n", ret); state->error = ret; break; } count -= n; } } #define s5k5baf_write_seq(state, addr, seq...) \ s5k5baf_write_arr_seq(state, addr, sizeof((char[]){ seq }), \ (const u16 []){ seq }) /* add items count at the beginning of the list */ #define NSEQ(seq...) sizeof((char[]){ seq }), seq /* * s5k5baf_write_nseq() - Writes sequences of values to sensor memory via i2c * @nseq: sequence of u16 words in format: * (N, address, value[1]...value[N-1])*,0 * Ex.: * u16 seq[] = { NSEQ(0x4000, 1, 1), NSEQ(0x4010, 640, 480), 0 }; * ret = s5k5baf_write_nseq(c, seq); */ static void s5k5baf_write_nseq(struct s5k5baf *state, const u16 *nseq) { int count; while ((count = *nseq++)) { u16 addr = *nseq++; --count; s5k5baf_write_arr_seq(state, addr, count, nseq); nseq += count; } } static void s5k5baf_synchronize(struct s5k5baf *state, int timeout, u16 addr) { unsigned long end = jiffies + msecs_to_jiffies(timeout); u16 reg; s5k5baf_write(state, addr, 1); do { reg = s5k5baf_read(state, addr); if (state->error || !reg) return; usleep_range(5000, 10000); } while (time_is_after_jiffies(end)); v4l2_err(&state->sd, "timeout on register synchronize (%#x)\n", addr); state->error = -ETIMEDOUT; } static u16 *s5k5baf_fw_get_seq(struct s5k5baf *state, u16 seq_id) { struct s5k5baf_fw *fw = state->fw; u16 *data; int i; if (fw == NULL) return NULL; data = &fw->seq[0].id + 2 * fw->count; for (i = 0; i < fw->count; ++i) { if (fw->seq[i].id == seq_id) return data + fw->seq[i].offset; } return NULL; } static void s5k5baf_hw_patch(struct s5k5baf *state) { u16 *seq = s5k5baf_fw_get_seq(state, S5K5BAF_FW_ID_PATCH); if (seq) s5k5baf_write_nseq(state, seq); } static void s5k5baf_hw_set_clocks(struct s5k5baf *state) { unsigned long mclk = state->mclk_frequency / 1000; u16 status; static const u16 nseq_clk_cfg[] = { NSEQ(REG_I_USE_NPVI_CLOCKS, NPVI_CLOCKS, NMIPI_CLOCKS, 0, SCLK_PVI_FREQ / 4, PCLK_MIN_FREQ / 4, PCLK_MAX_FREQ / 4, SCLK_MIPI_FREQ / 4, PCLK_MIN_FREQ / 4, PCLK_MAX_FREQ / 4), NSEQ(REG_I_USE_REGS_API, 1), 0 }; s5k5baf_write_seq(state, REG_I_INCLK_FREQ_L, mclk & 0xffff, mclk >> 16); s5k5baf_write_nseq(state, nseq_clk_cfg); s5k5baf_synchronize(state, 250, REG_I_INIT_PARAMS_UPDATED); status = s5k5baf_read(state, REG_I_ERROR_INFO); if (!state->error && status) { v4l2_err(&state->sd, "error configuring PLL (%d)\n", status); state->error = -EINVAL; } } /* set custom color correction matrices for various illuminations */ static void s5k5baf_hw_set_ccm(struct s5k5baf *state) { u16 *seq = s5k5baf_fw_get_seq(state, S5K5BAF_FW_ID_CCM); if (seq) s5k5baf_write_nseq(state, seq); } /* CIS sensor tuning, based on undocumented android driver code */ static void s5k5baf_hw_set_cis(struct s5k5baf *state) { u16 *seq = s5k5baf_fw_get_seq(state, S5K5BAF_FW_ID_CIS); if (!seq) return; s5k5baf_i2c_write(state, REG_CMDWR_PAGE, PAGE_IF_HW); s5k5baf_write_nseq(state, seq); s5k5baf_i2c_write(state, REG_CMDWR_PAGE, PAGE_IF_SW); } static void s5k5baf_hw_sync_cfg(struct s5k5baf *state) { s5k5baf_write(state, REG_G_PREV_CFG_CHG, 1); if (state->apply_crop) { s5k5baf_write(state, REG_G_INPUTS_CHANGE_REQ, 1); s5k5baf_write(state, REG_G_PREV_CFG_BYPASS_CHANGED, 1); } s5k5baf_synchronize(state, 500, REG_G_NEW_CFG_SYNC); } /* Set horizontal and vertical image flipping */ static void s5k5baf_hw_set_mirror(struct s5k5baf *state) { u16 flip = state->ctrls.vflip->val | (state->ctrls.vflip->val << 1); s5k5baf_write(state, REG_P_PREV_MIRROR(0), flip); if (state->streaming) s5k5baf_hw_sync_cfg(state); } static void s5k5baf_hw_set_alg(struct s5k5baf *state, u16 alg, bool enable) { u16 cur_alg, new_alg; if (!state->valid_auto_alg) cur_alg = s5k5baf_read(state, REG_DBG_AUTOALG_EN); else cur_alg = state->auto_alg; new_alg = enable ? (cur_alg | alg) : (cur_alg & ~alg); if (new_alg != cur_alg) s5k5baf_write(state, REG_DBG_AUTOALG_EN, new_alg); if (state->error) return; state->valid_auto_alg = 1; state->auto_alg = new_alg; } /* Configure auto/manual white balance and R/G/B gains */ static void s5k5baf_hw_set_awb(struct s5k5baf *state, int awb) { struct s5k5baf_ctrls *ctrls = &state->ctrls; if (!awb) s5k5baf_write_seq(state, REG_SF_RGAIN, ctrls->gain_red->val, 1, S5K5BAF_GAIN_GREEN_DEF, 1, ctrls->gain_blue->val, 1, 1); s5k5baf_hw_set_alg(state, AALG_WB_EN, awb); } /* Program FW with exposure time, 'exposure' in us units */ static void s5k5baf_hw_set_user_exposure(struct s5k5baf *state, int exposure) { unsigned int time = exposure / 10; s5k5baf_write_seq(state, REG_SF_USR_EXPOSURE_L, time & 0xffff, time >> 16, 1); } static void s5k5baf_hw_set_user_gain(struct s5k5baf *state, int gain) { s5k5baf_write_seq(state, REG_SF_USR_TOT_GAIN, gain, 1); } /* Set auto/manual exposure and total gain */ static void s5k5baf_hw_set_auto_exposure(struct s5k5baf *state, int value) { if (value == V4L2_EXPOSURE_AUTO) { s5k5baf_hw_set_alg(state, AALG_AE_EN | AALG_DIVLEI_EN, true); } else { unsigned int exp_time = state->ctrls.exposure->val; s5k5baf_hw_set_user_exposure(state, exp_time); s5k5baf_hw_set_user_gain(state, state->ctrls.gain->val); s5k5baf_hw_set_alg(state, AALG_AE_EN | AALG_DIVLEI_EN, false); } } static void s5k5baf_hw_set_anti_flicker(struct s5k5baf *state, int v) { if (v == V4L2_CID_POWER_LINE_FREQUENCY_AUTO) { s5k5baf_hw_set_alg(state, AALG_FLICKER_EN, true); } else { /* The V4L2_CID_LINE_FREQUENCY control values match * the register values */ s5k5baf_write_seq(state, REG_SF_FLICKER_QUANT, v, 1); s5k5baf_hw_set_alg(state, AALG_FLICKER_EN, false); } } static void s5k5baf_hw_set_colorfx(struct s5k5baf *state, int val) { static const u16 colorfx[] = { [V4L2_COLORFX_NONE] = 0, [V4L2_COLORFX_BW] = 1, [V4L2_COLORFX_NEGATIVE] = 2, [V4L2_COLORFX_SEPIA] = 3, [V4L2_COLORFX_SKY_BLUE] = 4, [V4L2_COLORFX_SKETCH] = 5, }; s5k5baf_write(state, REG_G_SPEC_EFFECTS, colorfx[val]); } static int s5k5baf_find_pixfmt(struct v4l2_mbus_framefmt *mf) { int i, c = -1; for (i = 0; i < ARRAY_SIZE(s5k5baf_formats); i++) { if (mf->colorspace != s5k5baf_formats[i].colorspace) continue; if (mf->code == s5k5baf_formats[i].code) return i; if (c < 0) c = i; } return (c < 0) ? 0 : c; } static int s5k5baf_clear_error(struct s5k5baf *state) { int ret = state->error; state->error = 0; return ret; } static int s5k5baf_hw_set_video_bus(struct s5k5baf *state) { u16 en_pkts; if (state->bus_type == V4L2_MBUS_CSI2_DPHY) en_pkts = EN_PACKETS_CSI2; else en_pkts = 0; s5k5baf_write_seq(state, REG_OIF_EN_MIPI_LANES, state->nlanes, en_pkts, 1); return s5k5baf_clear_error(state); } static u16 s5k5baf_get_cfg_error(struct s5k5baf *state) { u16 err = s5k5baf_read(state, REG_G_PREV_CFG_ERROR); if (err) s5k5baf_write(state, REG_G_PREV_CFG_ERROR, 0); return err; } static void s5k5baf_hw_set_fiv(struct s5k5baf *state, u16 fiv) { s5k5baf_write(state, REG_P_MAX_FR_TIME(0), fiv); s5k5baf_hw_sync_cfg(state); } static void s5k5baf_hw_find_min_fiv(struct s5k5baf *state) { u16 err, fiv; int n; fiv = s5k5baf_read(state, REG_G_ACTUAL_P_FR_TIME); if (state->error) return; for (n = 5; n > 0; --n) { s5k5baf_hw_set_fiv(state, fiv); err = s5k5baf_get_cfg_error(state); if (state->error) return; switch (err) { case CFG_ERROR_RANGE: ++fiv; break; case 0: state->fiv = fiv; v4l2_info(&state->sd, "found valid frame interval: %d00us\n", fiv); return; default: v4l2_err(&state->sd, "error setting frame interval: %d\n", err); state->error = -EINVAL; } } v4l2_err(&state->sd, "cannot find correct frame interval\n"); state->error = -ERANGE; } static void s5k5baf_hw_validate_cfg(struct s5k5baf *state) { u16 err; err = s5k5baf_get_cfg_error(state); if (state->error) return; switch (err) { case 0: state->apply_cfg = 1; return; case CFG_ERROR_RANGE: s5k5baf_hw_find_min_fiv(state); if (!state->error) state->apply_cfg = 1; return; default: v4l2_err(&state->sd, "error setting format: %d\n", err); state->error = -EINVAL; } } static void s5k5baf_rescale(struct v4l2_rect *r, const struct v4l2_rect *v, const struct v4l2_rect *n, const struct v4l2_rect *d) { r->left = v->left * n->width / d->width; r->top = v->top * n->height / d->height; r->width = v->width * n->width / d->width; r->height = v->height * n->height / d->height; } static int s5k5baf_hw_set_crop_rects(struct s5k5baf *state) { struct v4l2_rect *p, r; u16 err; int ret; p = &state->crop_sink; s5k5baf_write_seq(state, REG_G_PREVREQ_IN_WIDTH, p->width, p->height, p->left, p->top); s5k5baf_rescale(&r, &state->crop_source, &state->crop_sink, &state->compose); s5k5baf_write_seq(state, REG_G_PREVZOOM_IN_WIDTH, r.width, r.height, r.left, r.top); s5k5baf_synchronize(state, 500, REG_G_INPUTS_CHANGE_REQ); s5k5baf_synchronize(state, 500, REG_G_PREV_CFG_BYPASS_CHANGED); err = s5k5baf_get_cfg_error(state); ret = s5k5baf_clear_error(state); if (ret < 0) return ret; switch (err) { case 0: break; case CFG_ERROR_RANGE: /* retry crop with frame interval set to max */ s5k5baf_hw_set_fiv(state, S5K5BAF_MAX_FR_TIME); err = s5k5baf_get_cfg_error(state); ret = s5k5baf_clear_error(state); if (ret < 0) return ret; if (err) { v4l2_err(&state->sd, "crop error on max frame interval: %d\n", err); state->error = -EINVAL; } s5k5baf_hw_set_fiv(state, state->req_fiv); s5k5baf_hw_validate_cfg(state); break; default: v4l2_err(&state->sd, "crop error: %d\n", err); return -EINVAL; } if (!state->apply_cfg) return 0; p = &state->crop_source; s5k5baf_write_seq(state, REG_P_OUT_WIDTH(0), p->width, p->height); s5k5baf_hw_set_fiv(state, state->req_fiv); s5k5baf_hw_validate_cfg(state); return s5k5baf_clear_error(state); } static void s5k5baf_hw_set_config(struct s5k5baf *state) { u16 reg_fmt = s5k5baf_formats[state->pixfmt].reg_p_fmt; struct v4l2_rect *r = &state->crop_source; s5k5baf_write_seq(state, REG_P_OUT_WIDTH(0), r->width, r->height, reg_fmt, PCLK_MAX_FREQ >> 2, PCLK_MIN_FREQ >> 2, PVI_MASK_MIPI, CLK_MIPI_INDEX, FR_RATE_FIXED, FR_RATE_Q_DYNAMIC, state->req_fiv, S5K5BAF_MIN_FR_TIME); s5k5baf_hw_sync_cfg(state); s5k5baf_hw_validate_cfg(state); } static void s5k5baf_hw_set_test_pattern(struct s5k5baf *state, int id) { s5k5baf_i2c_write(state, REG_PATTERN_WIDTH, 800); s5k5baf_i2c_write(state, REG_PATTERN_HEIGHT, 511); s5k5baf_i2c_write(state, REG_PATTERN_PARAM, 0); s5k5baf_i2c_write(state, REG_PATTERN_SET, id); } static void s5k5baf_gpio_assert(struct s5k5baf *state, int id) { gpiod_set_value_cansleep(state->gpios[id], 1); } static void s5k5baf_gpio_deassert(struct s5k5baf *state, int id) { gpiod_set_value_cansleep(state->gpios[id], 0); } static int s5k5baf_power_on(struct s5k5baf *state) { int ret; ret = regulator_bulk_enable(S5K5BAF_NUM_SUPPLIES, state->supplies); if (ret < 0) goto err; ret = clk_set_rate(state->clock, state->mclk_frequency); if (ret < 0) goto err_reg_dis; ret = clk_prepare_enable(state->clock); if (ret < 0) goto err_reg_dis; v4l2_dbg(1, debug, &state->sd, "clock frequency: %ld\n", clk_get_rate(state->clock)); s5k5baf_gpio_deassert(state, STBY); usleep_range(50, 100); s5k5baf_gpio_deassert(state, RSET); return 0; err_reg_dis: regulator_bulk_disable(S5K5BAF_NUM_SUPPLIES, state->supplies); err: v4l2_err(&state->sd, "%s() failed (%d)\n", __func__, ret); return ret; } static int s5k5baf_power_off(struct s5k5baf *state) { int ret; state->streaming = 0; state->apply_cfg = 0; state->apply_crop = 0; s5k5baf_gpio_assert(state, RSET); s5k5baf_gpio_assert(state, STBY); if (!IS_ERR(state->clock)) clk_disable_unprepare(state->clock); ret = regulator_bulk_disable(S5K5BAF_NUM_SUPPLIES, state->supplies); if (ret < 0) v4l2_err(&state->sd, "failed to disable regulators\n"); return 0; } static void s5k5baf_hw_init(struct s5k5baf *state) { s5k5baf_i2c_write(state, AHB_MSB_ADDR_PTR, PAGE_IF_HW); s5k5baf_i2c_write(state, REG_CLEAR_HOST_INT, 0); s5k5baf_i2c_write(state, REG_SW_LOAD_COMPLETE, 1); s5k5baf_i2c_write(state, REG_CMDRD_PAGE, PAGE_IF_SW); s5k5baf_i2c_write(state, REG_CMDWR_PAGE, PAGE_IF_SW); } /* * V4L2 subdev core and video operations */ static void s5k5baf_initialize_data(struct s5k5baf *state) { state->pixfmt = 0; state->req_fiv = 10000 / 15; state->fiv = state->req_fiv; state->valid_auto_alg = 0; } static int s5k5baf_load_setfile(struct s5k5baf *state) { struct i2c_client *c = v4l2_get_subdevdata(&state->sd); const struct firmware *fw; int ret; ret = request_firmware(&fw, S5K5BAF_FW_FILENAME, &c->dev); if (ret < 0) { dev_warn(&c->dev, "firmware file (%s) not loaded\n", S5K5BAF_FW_FILENAME); return ret; } ret = s5k5baf_fw_parse(&c->dev, &state->fw, fw->size / 2, (__le16 *)fw->data); release_firmware(fw); return ret; } static int s5k5baf_set_power(struct v4l2_subdev *sd, int on) { struct s5k5baf *state = to_s5k5baf(sd); int ret = 0; mutex_lock(&state->lock); if (state->power != !on) goto out; if (on) { if (state->fw == NULL) s5k5baf_load_setfile(state); s5k5baf_initialize_data(state); ret = s5k5baf_power_on(state); if (ret < 0) goto out; s5k5baf_hw_init(state); s5k5baf_hw_patch(state); s5k5baf_i2c_write(state, REG_SET_HOST_INT, 1); s5k5baf_hw_set_clocks(state); ret = s5k5baf_hw_set_video_bus(state); if (ret < 0) goto out; s5k5baf_hw_set_cis(state); s5k5baf_hw_set_ccm(state); ret = s5k5baf_clear_error(state); if (!ret) state->power++; } else { s5k5baf_power_off(state); state->power--; } out: mutex_unlock(&state->lock); if (!ret && on) ret = v4l2_ctrl_handler_setup(&state->ctrls.handler); return ret; } static void s5k5baf_hw_set_stream(struct s5k5baf *state, int enable) { s5k5baf_write_seq(state, REG_G_ENABLE_PREV, enable, 1); } static int s5k5baf_s_stream(struct v4l2_subdev *sd, int on) { struct s5k5baf *state = to_s5k5baf(sd); int ret; mutex_lock(&state->lock); if (state->streaming == !!on) { ret = 0; goto out; } if (on) { s5k5baf_hw_set_config(state); ret = s5k5baf_hw_set_crop_rects(state); if (ret < 0) goto out; s5k5baf_hw_set_stream(state, 1); s5k5baf_i2c_write(state, 0xb0cc, 0x000b); } else { s5k5baf_hw_set_stream(state, 0); } ret = s5k5baf_clear_error(state); if (!ret) state->streaming = !state->streaming; out: mutex_unlock(&state->lock); return ret; } static int s5k5baf_g_frame_interval(struct v4l2_subdev *sd, struct v4l2_subdev_frame_interval *fi) { struct s5k5baf *state = to_s5k5baf(sd); mutex_lock(&state->lock); fi->interval.numerator = state->fiv; fi->interval.denominator = 10000; mutex_unlock(&state->lock); return 0; } static void s5k5baf_set_frame_interval(struct s5k5baf *state, struct v4l2_subdev_frame_interval *fi) { struct v4l2_fract *i = &fi->interval; if (fi->interval.denominator == 0) state->req_fiv = S5K5BAF_MAX_FR_TIME; else state->req_fiv = clamp_t(u32, i->numerator * 10000 / i->denominator, S5K5BAF_MIN_FR_TIME, S5K5BAF_MAX_FR_TIME); state->fiv = state->req_fiv; if (state->apply_cfg) { s5k5baf_hw_set_fiv(state, state->req_fiv); s5k5baf_hw_validate_cfg(state); } *i = (struct v4l2_fract){ state->fiv, 10000 }; if (state->fiv == state->req_fiv) v4l2_info(&state->sd, "frame interval changed to %d00us\n", state->fiv); } static int s5k5baf_s_frame_interval(struct v4l2_subdev *sd, struct v4l2_subdev_frame_interval *fi) { struct s5k5baf *state = to_s5k5baf(sd); mutex_lock(&state->lock); s5k5baf_set_frame_interval(state, fi); mutex_unlock(&state->lock); return 0; } /* * V4L2 subdev pad level and video operations */ static int s5k5baf_enum_frame_interval(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_frame_interval_enum *fie) { if (fie->index > S5K5BAF_MAX_FR_TIME - S5K5BAF_MIN_FR_TIME || fie->pad != PAD_CIS) return -EINVAL; v4l_bound_align_image(&fie->width, S5K5BAF_WIN_WIDTH_MIN, S5K5BAF_CIS_WIDTH, 1, &fie->height, S5K5BAF_WIN_HEIGHT_MIN, S5K5BAF_CIS_HEIGHT, 1, 0); fie->interval.numerator = S5K5BAF_MIN_FR_TIME + fie->index; fie->interval.denominator = 10000; return 0; } static int s5k5baf_enum_mbus_code(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_mbus_code_enum *code) { if (code->pad == PAD_CIS) { if (code->index > 0) return -EINVAL; code->code = MEDIA_BUS_FMT_FIXED; return 0; } if (code->index >= ARRAY_SIZE(s5k5baf_formats)) return -EINVAL; code->code = s5k5baf_formats[code->index].code; return 0; } static int s5k5baf_enum_frame_size(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_frame_size_enum *fse) { int i; if (fse->index > 0) return -EINVAL; if (fse->pad == PAD_CIS) { fse->code = MEDIA_BUS_FMT_FIXED; fse->min_width = S5K5BAF_CIS_WIDTH; fse->max_width = S5K5BAF_CIS_WIDTH; fse->min_height = S5K5BAF_CIS_HEIGHT; fse->max_height = S5K5BAF_CIS_HEIGHT; return 0; } i = ARRAY_SIZE(s5k5baf_formats); while (--i) if (fse->code == s5k5baf_formats[i].code) break; fse->code = s5k5baf_formats[i].code; fse->min_width = S5K5BAF_WIN_WIDTH_MIN; fse->max_width = S5K5BAF_CIS_WIDTH; fse->max_height = S5K5BAF_WIN_HEIGHT_MIN; fse->min_height = S5K5BAF_CIS_HEIGHT; return 0; } static void s5k5baf_try_cis_format(struct v4l2_mbus_framefmt *mf) { mf->width = S5K5BAF_CIS_WIDTH; mf->height = S5K5BAF_CIS_HEIGHT; mf->code = MEDIA_BUS_FMT_FIXED; mf->colorspace = V4L2_COLORSPACE_JPEG; mf->field = V4L2_FIELD_NONE; } static int s5k5baf_try_isp_format(struct v4l2_mbus_framefmt *mf) { int pixfmt; v4l_bound_align_image(&mf->width, S5K5BAF_WIN_WIDTH_MIN, S5K5BAF_CIS_WIDTH, 1, &mf->height, S5K5BAF_WIN_HEIGHT_MIN, S5K5BAF_CIS_HEIGHT, 1, 0); pixfmt = s5k5baf_find_pixfmt(mf); mf->colorspace = s5k5baf_formats[pixfmt].colorspace; mf->code = s5k5baf_formats[pixfmt].code; mf->field = V4L2_FIELD_NONE; return pixfmt; } static int s5k5baf_get_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *fmt) { struct s5k5baf *state = to_s5k5baf(sd); const struct s5k5baf_pixfmt *pixfmt; struct v4l2_mbus_framefmt *mf; if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) { mf = v4l2_subdev_get_try_format(sd, sd_state, fmt->pad); fmt->format = *mf; return 0; } mf = &fmt->format; if (fmt->pad == PAD_CIS) { s5k5baf_try_cis_format(mf); return 0; } mf->field = V4L2_FIELD_NONE; mutex_lock(&state->lock); pixfmt = &s5k5baf_formats[state->pixfmt]; mf->width = state->crop_source.width; mf->height = state->crop_source.height; mf->code = pixfmt->code; mf->colorspace = pixfmt->colorspace; mutex_unlock(&state->lock); return 0; } static int s5k5baf_set_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *fmt) { struct v4l2_mbus_framefmt *mf = &fmt->format; struct s5k5baf *state = to_s5k5baf(sd); const struct s5k5baf_pixfmt *pixfmt; int ret = 0; mf->field = V4L2_FIELD_NONE; if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) { *v4l2_subdev_get_try_format(sd, sd_state, fmt->pad) = *mf; return 0; } if (fmt->pad == PAD_CIS) { s5k5baf_try_cis_format(mf); return 0; } mutex_lock(&state->lock); if (state->streaming) { mutex_unlock(&state->lock); return -EBUSY; } state->pixfmt = s5k5baf_try_isp_format(mf); pixfmt = &s5k5baf_formats[state->pixfmt]; mf->code = pixfmt->code; mf->colorspace = pixfmt->colorspace; mf->width = state->crop_source.width; mf->height = state->crop_source.height; mutex_unlock(&state->lock); return ret; } enum selection_rect { R_CIS, R_CROP_SINK, R_COMPOSE, R_CROP_SOURCE, R_INVALID }; static enum selection_rect s5k5baf_get_sel_rect(u32 pad, u32 target) { switch (target) { case V4L2_SEL_TGT_CROP_BOUNDS: return pad ? R_COMPOSE : R_CIS; case V4L2_SEL_TGT_CROP: return pad ? R_CROP_SOURCE : R_CROP_SINK; case V4L2_SEL_TGT_COMPOSE_BOUNDS: return pad ? R_INVALID : R_CROP_SINK; case V4L2_SEL_TGT_COMPOSE: return pad ? R_INVALID : R_COMPOSE; default: return R_INVALID; } } static int s5k5baf_is_bound_target(u32 target) { return target == V4L2_SEL_TGT_CROP_BOUNDS || target == V4L2_SEL_TGT_COMPOSE_BOUNDS; } static int s5k5baf_get_selection(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_selection *sel) { enum selection_rect rtype; struct s5k5baf *state = to_s5k5baf(sd); rtype = s5k5baf_get_sel_rect(sel->pad, sel->target); switch (rtype) { case R_INVALID: return -EINVAL; case R_CIS: sel->r = s5k5baf_cis_rect; return 0; default: break; } if (sel->which == V4L2_SUBDEV_FORMAT_TRY) { if (rtype == R_COMPOSE) sel->r = *v4l2_subdev_get_try_compose(sd, sd_state, sel->pad); else sel->r = *v4l2_subdev_get_try_crop(sd, sd_state, sel->pad); return 0; } mutex_lock(&state->lock); switch (rtype) { case R_CROP_SINK: sel->r = state->crop_sink; break; case R_COMPOSE: sel->r = state->compose; break; case R_CROP_SOURCE: sel->r = state->crop_source; break; default: break; } if (s5k5baf_is_bound_target(sel->target)) { sel->r.left = 0; sel->r.top = 0; } mutex_unlock(&state->lock); return 0; } /* bounds range [start, start+len) to [0, max) and aligns to 2 */ static void s5k5baf_bound_range(u32 *start, u32 *len, u32 max) { if (*len > max) *len = max; if (*start + *len > max) *start = max - *len; *start &= ~1; *len &= ~1; if (*len < S5K5BAF_WIN_WIDTH_MIN) *len = S5K5BAF_WIN_WIDTH_MIN; } static void s5k5baf_bound_rect(struct v4l2_rect *r, u32 width, u32 height) { s5k5baf_bound_range(&r->left, &r->width, width); s5k5baf_bound_range(&r->top, &r->height, height); } static void s5k5baf_set_rect_and_adjust(struct v4l2_rect **rects, enum selection_rect first, struct v4l2_rect *v) { struct v4l2_rect *r, *br; enum selection_rect i = first; *rects[first] = *v; do { r = rects[i]; br = rects[i - 1]; s5k5baf_bound_rect(r, br->width, br->height); } while (++i != R_INVALID); *v = *rects[first]; } static bool s5k5baf_cmp_rect(const struct v4l2_rect *r1, const struct v4l2_rect *r2) { return !memcmp(r1, r2, sizeof(*r1)); } static int s5k5baf_set_selection(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_selection *sel) { static enum selection_rect rtype; struct s5k5baf *state = to_s5k5baf(sd); struct v4l2_rect **rects; int ret = 0; rtype = s5k5baf_get_sel_rect(sel->pad, sel->target); if (rtype == R_INVALID || s5k5baf_is_bound_target(sel->target)) return -EINVAL; /* allow only scaling on compose */ if (rtype == R_COMPOSE) { sel->r.left = 0; sel->r.top = 0; } if (sel->which == V4L2_SUBDEV_FORMAT_TRY) { rects = (struct v4l2_rect * []) { &s5k5baf_cis_rect, v4l2_subdev_get_try_crop(sd, sd_state, PAD_CIS), v4l2_subdev_get_try_compose(sd, sd_state, PAD_CIS), v4l2_subdev_get_try_crop(sd, sd_state, PAD_OUT) }; s5k5baf_set_rect_and_adjust(rects, rtype, &sel->r); return 0; } rects = (struct v4l2_rect * []) { &s5k5baf_cis_rect, &state->crop_sink, &state->compose, &state->crop_source }; mutex_lock(&state->lock); if (state->streaming) { /* adjust sel->r to avoid output resolution change */ if (rtype < R_CROP_SOURCE) { if (sel->r.width < state->crop_source.width) sel->r.width = state->crop_source.width; if (sel->r.height < state->crop_source.height) sel->r.height = state->crop_source.height; } else { sel->r.width = state->crop_source.width; sel->r.height = state->crop_source.height; } } s5k5baf_set_rect_and_adjust(rects, rtype, &sel->r); if (!s5k5baf_cmp_rect(&state->crop_sink, &s5k5baf_cis_rect) || !s5k5baf_cmp_rect(&state->compose, &s5k5baf_cis_rect)) state->apply_crop = 1; if (state->streaming) ret = s5k5baf_hw_set_crop_rects(state); mutex_unlock(&state->lock); return ret; } static const struct v4l2_subdev_pad_ops s5k5baf_cis_pad_ops = { .enum_mbus_code = s5k5baf_enum_mbus_code, .enum_frame_size = s5k5baf_enum_frame_size, .get_fmt = s5k5baf_get_fmt, .set_fmt = s5k5baf_set_fmt, }; static const struct v4l2_subdev_pad_ops s5k5baf_pad_ops = { .enum_mbus_code = s5k5baf_enum_mbus_code, .enum_frame_size = s5k5baf_enum_frame_size, .enum_frame_interval = s5k5baf_enum_frame_interval, .get_fmt = s5k5baf_get_fmt, .set_fmt = s5k5baf_set_fmt, .get_selection = s5k5baf_get_selection, .set_selection = s5k5baf_set_selection, }; static const struct v4l2_subdev_video_ops s5k5baf_video_ops = { .g_frame_interval = s5k5baf_g_frame_interval, .s_frame_interval = s5k5baf_s_frame_interval, .s_stream = s5k5baf_s_stream, }; /* * V4L2 subdev controls */ static int s5k5baf_s_ctrl(struct v4l2_ctrl *ctrl) { struct v4l2_subdev *sd = ctrl_to_sd(ctrl); struct s5k5baf *state = to_s5k5baf(sd); int ret; v4l2_dbg(1, debug, sd, "ctrl: %s, value: %d\n", ctrl->name, ctrl->val); mutex_lock(&state->lock); if (state->power == 0) goto unlock; switch (ctrl->id) { case V4L2_CID_AUTO_WHITE_BALANCE: s5k5baf_hw_set_awb(state, ctrl->val); break; case V4L2_CID_BRIGHTNESS: s5k5baf_write(state, REG_USER_BRIGHTNESS, ctrl->val); break; case V4L2_CID_COLORFX: s5k5baf_hw_set_colorfx(state, ctrl->val); break; case V4L2_CID_CONTRAST: s5k5baf_write(state, REG_USER_CONTRAST, ctrl->val); break; case V4L2_CID_EXPOSURE_AUTO: s5k5baf_hw_set_auto_exposure(state, ctrl->val); break; case V4L2_CID_HFLIP: s5k5baf_hw_set_mirror(state); break; case V4L2_CID_POWER_LINE_FREQUENCY: s5k5baf_hw_set_anti_flicker(state, ctrl->val); break; case V4L2_CID_SATURATION: s5k5baf_write(state, REG_USER_SATURATION, ctrl->val); break; case V4L2_CID_SHARPNESS: s5k5baf_write(state, REG_USER_SHARPBLUR, ctrl->val); break; case V4L2_CID_WHITE_BALANCE_TEMPERATURE: s5k5baf_write(state, REG_P_COLORTEMP(0), ctrl->val); if (state->apply_cfg) s5k5baf_hw_sync_cfg(state); break; case V4L2_CID_TEST_PATTERN: s5k5baf_hw_set_test_pattern(state, ctrl->val); break; } unlock: ret = s5k5baf_clear_error(state); mutex_unlock(&state->lock); return ret; } static const struct v4l2_ctrl_ops s5k5baf_ctrl_ops = { .s_ctrl = s5k5baf_s_ctrl, }; static const char * const s5k5baf_test_pattern_menu[] = { "Disabled", "Blank", "Bars", "Gradients", "Textile", "Textile2", "Squares" }; static int s5k5baf_initialize_ctrls(struct s5k5baf *state) { const struct v4l2_ctrl_ops *ops = &s5k5baf_ctrl_ops; struct s5k5baf_ctrls *ctrls = &state->ctrls; struct v4l2_ctrl_handler *hdl = &ctrls->handler; int ret; ret = v4l2_ctrl_handler_init(hdl, 16); if (ret < 0) { v4l2_err(&state->sd, "cannot init ctrl handler (%d)\n", ret); return ret; } /* Auto white balance cluster */ ctrls->awb = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_AUTO_WHITE_BALANCE, 0, 1, 1, 1); ctrls->gain_red = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_RED_BALANCE, 0, 255, 1, S5K5BAF_GAIN_RED_DEF); ctrls->gain_blue = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_BLUE_BALANCE, 0, 255, 1, S5K5BAF_GAIN_BLUE_DEF); v4l2_ctrl_auto_cluster(3, &ctrls->awb, 0, false); ctrls->hflip = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_HFLIP, 0, 1, 1, 0); ctrls->vflip = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_VFLIP, 0, 1, 1, 0); v4l2_ctrl_cluster(2, &ctrls->hflip); ctrls->auto_exp = v4l2_ctrl_new_std_menu(hdl, ops, V4L2_CID_EXPOSURE_AUTO, V4L2_EXPOSURE_MANUAL, 0, V4L2_EXPOSURE_AUTO); /* Exposure time: x 1 us */ ctrls->exposure = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_EXPOSURE, 0, 6000000U, 1, 100000U); /* Total gain: 256 <=> 1x */ ctrls->gain = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_GAIN, 0, 256, 1, 256); v4l2_ctrl_auto_cluster(3, &ctrls->auto_exp, 0, false); v4l2_ctrl_new_std_menu(hdl, ops, V4L2_CID_POWER_LINE_FREQUENCY, V4L2_CID_POWER_LINE_FREQUENCY_AUTO, 0, V4L2_CID_POWER_LINE_FREQUENCY_AUTO); v4l2_ctrl_new_std_menu(hdl, ops, V4L2_CID_COLORFX, V4L2_COLORFX_SKY_BLUE, ~0x6f, V4L2_COLORFX_NONE); v4l2_ctrl_new_std(hdl, ops, V4L2_CID_WHITE_BALANCE_TEMPERATURE, 0, 256, 1, 0); v4l2_ctrl_new_std(hdl, ops, V4L2_CID_SATURATION, -127, 127, 1, 0); v4l2_ctrl_new_std(hdl, ops, V4L2_CID_BRIGHTNESS, -127, 127, 1, 0); v4l2_ctrl_new_std(hdl, ops, V4L2_CID_CONTRAST, -127, 127, 1, 0); v4l2_ctrl_new_std(hdl, ops, V4L2_CID_SHARPNESS, -127, 127, 1, 0); v4l2_ctrl_new_std_menu_items(hdl, ops, V4L2_CID_TEST_PATTERN, ARRAY_SIZE(s5k5baf_test_pattern_menu) - 1, 0, 0, s5k5baf_test_pattern_menu); if (hdl->error) { v4l2_err(&state->sd, "error creating controls (%d)\n", hdl->error); ret = hdl->error; v4l2_ctrl_handler_free(hdl); return ret; } state->sd.ctrl_handler = hdl; return 0; } /* * V4L2 subdev internal operations */ static int s5k5baf_open(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh) { struct v4l2_mbus_framefmt *mf; mf = v4l2_subdev_get_try_format(sd, fh->state, PAD_CIS); s5k5baf_try_cis_format(mf); if (s5k5baf_is_cis_subdev(sd)) return 0; mf = v4l2_subdev_get_try_format(sd, fh->state, PAD_OUT); mf->colorspace = s5k5baf_formats[0].colorspace; mf->code = s5k5baf_formats[0].code; mf->width = s5k5baf_cis_rect.width; mf->height = s5k5baf_cis_rect.height; mf->field = V4L2_FIELD_NONE; *v4l2_subdev_get_try_crop(sd, fh->state, PAD_CIS) = s5k5baf_cis_rect; *v4l2_subdev_get_try_compose(sd, fh->state, PAD_CIS) = s5k5baf_cis_rect; *v4l2_subdev_get_try_crop(sd, fh->state, PAD_OUT) = s5k5baf_cis_rect; return 0; } static int s5k5baf_check_fw_revision(struct s5k5baf *state) { u16 api_ver = 0, fw_rev = 0, s_id = 0; int ret; api_ver = s5k5baf_read(state, REG_FW_APIVER); fw_rev = s5k5baf_read(state, REG_FW_REVISION) & 0xff; s_id = s5k5baf_read(state, REG_FW_SENSOR_ID); ret = s5k5baf_clear_error(state); if (ret < 0) return ret; v4l2_info(&state->sd, "FW API=%#x, revision=%#x sensor_id=%#x\n", api_ver, fw_rev, s_id); if (api_ver != S5K5BAF_FW_APIVER) { v4l2_err(&state->sd, "FW API version not supported\n"); return -ENODEV; } return 0; } static int s5k5baf_registered(struct v4l2_subdev *sd) { struct s5k5baf *state = to_s5k5baf(sd); int ret; ret = v4l2_device_register_subdev(sd->v4l2_dev, &state->cis_sd); if (ret < 0) v4l2_err(sd, "failed to register subdev %s\n", state->cis_sd.name); else ret = media_create_pad_link(&state->cis_sd.entity, PAD_CIS, &state->sd.entity, PAD_CIS, MEDIA_LNK_FL_IMMUTABLE | MEDIA_LNK_FL_ENABLED); return ret; } static void s5k5baf_unregistered(struct v4l2_subdev *sd) { struct s5k5baf *state = to_s5k5baf(sd); v4l2_device_unregister_subdev(&state->cis_sd); } static const struct v4l2_subdev_ops s5k5baf_cis_subdev_ops = { .pad = &s5k5baf_cis_pad_ops, }; static const struct v4l2_subdev_internal_ops s5k5baf_cis_subdev_internal_ops = { .open = s5k5baf_open, }; static const struct v4l2_subdev_internal_ops s5k5baf_subdev_internal_ops = { .registered = s5k5baf_registered, .unregistered = s5k5baf_unregistered, .open = s5k5baf_open, }; static const struct v4l2_subdev_core_ops s5k5baf_core_ops = { .s_power = s5k5baf_set_power, .log_status = v4l2_ctrl_subdev_log_status, }; static const struct v4l2_subdev_ops s5k5baf_subdev_ops = { .core = &s5k5baf_core_ops, .pad = &s5k5baf_pad_ops, .video = &s5k5baf_video_ops, }; static int s5k5baf_configure_gpios(struct s5k5baf *state) { static const char * const name[] = { "stbyn", "rstn" }; static const char * const label[] = { "S5K5BAF_STBY", "S5K5BAF_RST" }; struct i2c_client *c = v4l2_get_subdevdata(&state->sd); struct gpio_desc *gpio; int ret, i; for (i = 0; i < NUM_GPIOS; ++i) { gpio = devm_gpiod_get(&c->dev, name[i], GPIOD_OUT_HIGH); ret = PTR_ERR_OR_ZERO(gpio); if (ret) { v4l2_err(c, "failed to request gpio %s: %d\n", name[i], ret); return ret; } ret = gpiod_set_consumer_name(gpio, label[i]); if (ret) { v4l2_err(c, "failed to set up name for gpio %s: %d\n", name[i], ret); return ret; } state->gpios[i] = gpio; } return 0; } static int s5k5baf_parse_device_node(struct s5k5baf *state, struct device *dev) { struct device_node *node = dev->of_node; struct device_node *node_ep; struct v4l2_fwnode_endpoint ep = { .bus_type = 0 }; int ret; if (!node) { dev_err(dev, "no device-tree node provided\n"); return -EINVAL; } ret = of_property_read_u32(node, "clock-frequency", &state->mclk_frequency); if (ret < 0) { state->mclk_frequency = S5K5BAF_DEFAULT_MCLK_FREQ; dev_info(dev, "using default %u Hz clock frequency\n", state->mclk_frequency); } node_ep = of_graph_get_next_endpoint(node, NULL); if (!node_ep) { dev_err(dev, "no endpoint defined at node %pOF\n", node); return -EINVAL; } ret = v4l2_fwnode_endpoint_parse(of_fwnode_handle(node_ep), &ep); of_node_put(node_ep); if (ret) return ret; state->bus_type = ep.bus_type; switch (state->bus_type) { case V4L2_MBUS_CSI2_DPHY: state->nlanes = ep.bus.mipi_csi2.num_data_lanes; break; case V4L2_MBUS_PARALLEL: break; default: dev_err(dev, "unsupported bus in endpoint defined at node %pOF\n", node); return -EINVAL; } return 0; } static int s5k5baf_configure_subdevs(struct s5k5baf *state, struct i2c_client *c) { struct v4l2_subdev *sd; int ret; sd = &state->cis_sd; v4l2_subdev_init(sd, &s5k5baf_cis_subdev_ops); sd->owner = THIS_MODULE; v4l2_set_subdevdata(sd, state); snprintf(sd->name, sizeof(sd->name), "S5K5BAF-CIS %d-%04x", i2c_adapter_id(c->adapter), c->addr); sd->internal_ops = &s5k5baf_cis_subdev_internal_ops; sd->flags |= V4L2_SUBDEV_FL_HAS_DEVNODE; state->cis_pad.flags = MEDIA_PAD_FL_SOURCE; sd->entity.function = MEDIA_ENT_F_CAM_SENSOR; ret = media_entity_pads_init(&sd->entity, NUM_CIS_PADS, &state->cis_pad); if (ret < 0) goto err; sd = &state->sd; v4l2_i2c_subdev_init(sd, c, &s5k5baf_subdev_ops); snprintf(sd->name, sizeof(sd->name), "S5K5BAF-ISP %d-%04x", i2c_adapter_id(c->adapter), c->addr); sd->internal_ops = &s5k5baf_subdev_internal_ops; sd->flags |= V4L2_SUBDEV_FL_HAS_DEVNODE; state->pads[PAD_CIS].flags = MEDIA_PAD_FL_SINK; state->pads[PAD_OUT].flags = MEDIA_PAD_FL_SOURCE; sd->entity.function = MEDIA_ENT_F_V4L2_SUBDEV_UNKNOWN; ret = media_entity_pads_init(&sd->entity, NUM_ISP_PADS, state->pads); if (!ret) return 0; media_entity_cleanup(&state->cis_sd.entity); err: dev_err(&c->dev, "cannot init media entity %s\n", sd->name); return ret; } static int s5k5baf_configure_regulators(struct s5k5baf *state) { struct i2c_client *c = v4l2_get_subdevdata(&state->sd); int ret; int i; for (i = 0; i < S5K5BAF_NUM_SUPPLIES; i++) state->supplies[i].supply = s5k5baf_supply_names[i]; ret = devm_regulator_bulk_get(&c->dev, S5K5BAF_NUM_SUPPLIES, state->supplies); if (ret < 0) v4l2_err(c, "failed to get regulators\n"); return ret; } static int s5k5baf_probe(struct i2c_client *c) { struct s5k5baf *state; int ret; state = devm_kzalloc(&c->dev, sizeof(*state), GFP_KERNEL); if (!state) return -ENOMEM; mutex_init(&state->lock); state->crop_sink = s5k5baf_cis_rect; state->compose = s5k5baf_cis_rect; state->crop_source = s5k5baf_cis_rect; ret = s5k5baf_parse_device_node(state, &c->dev); if (ret < 0) return ret; ret = s5k5baf_configure_subdevs(state, c); if (ret < 0) return ret; ret = s5k5baf_configure_gpios(state); if (ret < 0) goto err_me; ret = s5k5baf_configure_regulators(state); if (ret < 0) goto err_me; state->clock = devm_clk_get(state->sd.dev, S5K5BAF_CLK_NAME); if (IS_ERR(state->clock)) { ret = -EPROBE_DEFER; goto err_me; } ret = s5k5baf_power_on(state); if (ret < 0) { ret = -EPROBE_DEFER; goto err_me; } s5k5baf_hw_init(state); ret = s5k5baf_check_fw_revision(state); s5k5baf_power_off(state); if (ret < 0) goto err_me; ret = s5k5baf_initialize_ctrls(state); if (ret < 0) goto err_me; ret = v4l2_async_register_subdev(&state->sd); if (ret < 0) goto err_ctrl; return 0; err_ctrl: v4l2_ctrl_handler_free(state->sd.ctrl_handler); err_me: media_entity_cleanup(&state->sd.entity); media_entity_cleanup(&state->cis_sd.entity); return ret; } static void s5k5baf_remove(struct i2c_client *c) { struct v4l2_subdev *sd = i2c_get_clientdata(c); struct s5k5baf *state = to_s5k5baf(sd); v4l2_async_unregister_subdev(sd); v4l2_ctrl_handler_free(sd->ctrl_handler); media_entity_cleanup(&sd->entity); sd = &state->cis_sd; v4l2_device_unregister_subdev(sd); media_entity_cleanup(&sd->entity); } static const struct i2c_device_id s5k5baf_id[] = { { S5K5BAF_DRIVER_NAME, 0 }, { }, }; MODULE_DEVICE_TABLE(i2c, s5k5baf_id); static const struct of_device_id s5k5baf_of_match[] = { { .compatible = "samsung,s5k5baf" }, { } }; MODULE_DEVICE_TABLE(of, s5k5baf_of_match); static struct i2c_driver s5k5baf_i2c_driver = { .driver = { .of_match_table = s5k5baf_of_match, .name = S5K5BAF_DRIVER_NAME }, .probe = s5k5baf_probe, .remove = s5k5baf_remove, .id_table = s5k5baf_id, }; module_i2c_driver(s5k5baf_i2c_driver); MODULE_DESCRIPTION("Samsung S5K5BAF(X) UXGA camera driver"); MODULE_AUTHOR("Andrzej Hajda <[email protected]>"); MODULE_LICENSE("GPL v2");
linux-master
drivers/media/i2c/s5k5baf.c
// SPDX-License-Identifier: GPL-2.0 /* * adv7180.c Analog Devices ADV7180 video decoder driver * Copyright (c) 2009 Intel Corporation * Copyright (C) 2013 Cogent Embedded, Inc. * Copyright (C) 2013 Renesas Solutions Corp. */ #include <linux/module.h> #include <linux/init.h> #include <linux/errno.h> #include <linux/kernel.h> #include <linux/interrupt.h> #include <linux/i2c.h> #include <linux/slab.h> #include <linux/of.h> #include <linux/gpio/consumer.h> #include <linux/videodev2.h> #include <media/v4l2-ioctl.h> #include <media/v4l2-event.h> #include <media/v4l2-device.h> #include <media/v4l2-ctrls.h> #include <linux/mutex.h> #include <linux/delay.h> #define ADV7180_STD_AD_PAL_BG_NTSC_J_SECAM 0x0 #define ADV7180_STD_AD_PAL_BG_NTSC_J_SECAM_PED 0x1 #define ADV7180_STD_AD_PAL_N_NTSC_J_SECAM 0x2 #define ADV7180_STD_AD_PAL_N_NTSC_M_SECAM 0x3 #define ADV7180_STD_NTSC_J 0x4 #define ADV7180_STD_NTSC_M 0x5 #define ADV7180_STD_PAL60 0x6 #define ADV7180_STD_NTSC_443 0x7 #define ADV7180_STD_PAL_BG 0x8 #define ADV7180_STD_PAL_N 0x9 #define ADV7180_STD_PAL_M 0xa #define ADV7180_STD_PAL_M_PED 0xb #define ADV7180_STD_PAL_COMB_N 0xc #define ADV7180_STD_PAL_COMB_N_PED 0xd #define ADV7180_STD_PAL_SECAM 0xe #define ADV7180_STD_PAL_SECAM_PED 0xf #define ADV7180_REG_INPUT_CONTROL 0x0000 #define ADV7180_INPUT_CONTROL_INSEL_MASK 0x0f #define ADV7182_REG_INPUT_VIDSEL 0x0002 #define ADV7182_REG_INPUT_RESERVED BIT(2) #define ADV7180_REG_OUTPUT_CONTROL 0x0003 #define ADV7180_REG_EXTENDED_OUTPUT_CONTROL 0x0004 #define ADV7180_EXTENDED_OUTPUT_CONTROL_NTSCDIS 0xC5 #define ADV7180_REG_AUTODETECT_ENABLE 0x0007 #define ADV7180_AUTODETECT_DEFAULT 0x7f /* Contrast */ #define ADV7180_REG_CON 0x0008 /*Unsigned */ #define ADV7180_CON_MIN 0 #define ADV7180_CON_DEF 128 #define ADV7180_CON_MAX 255 /* Brightness*/ #define ADV7180_REG_BRI 0x000a /*Signed */ #define ADV7180_BRI_MIN -128 #define ADV7180_BRI_DEF 0 #define ADV7180_BRI_MAX 127 /* Hue */ #define ADV7180_REG_HUE 0x000b /*Signed, inverted */ #define ADV7180_HUE_MIN -127 #define ADV7180_HUE_DEF 0 #define ADV7180_HUE_MAX 128 #define ADV7180_REG_DEF_VALUE_Y 0x000c #define ADV7180_DEF_VAL_EN 0x1 #define ADV7180_DEF_VAL_AUTO_EN 0x2 #define ADV7180_REG_CTRL 0x000e #define ADV7180_CTRL_IRQ_SPACE 0x20 #define ADV7180_REG_PWR_MAN 0x0f #define ADV7180_PWR_MAN_ON 0x04 #define ADV7180_PWR_MAN_OFF 0x24 #define ADV7180_PWR_MAN_RES 0x80 #define ADV7180_REG_STATUS1 0x0010 #define ADV7180_STATUS1_IN_LOCK 0x01 #define ADV7180_STATUS1_AUTOD_MASK 0x70 #define ADV7180_STATUS1_AUTOD_NTSM_M_J 0x00 #define ADV7180_STATUS1_AUTOD_NTSC_4_43 0x10 #define ADV7180_STATUS1_AUTOD_PAL_M 0x20 #define ADV7180_STATUS1_AUTOD_PAL_60 0x30 #define ADV7180_STATUS1_AUTOD_PAL_B_G 0x40 #define ADV7180_STATUS1_AUTOD_SECAM 0x50 #define ADV7180_STATUS1_AUTOD_PAL_COMB 0x60 #define ADV7180_STATUS1_AUTOD_SECAM_525 0x70 #define ADV7180_REG_IDENT 0x0011 #define ADV7180_ID_7180 0x18 #define ADV7180_REG_STATUS3 0x0013 #define ADV7180_REG_ANALOG_CLAMP_CTL 0x0014 #define ADV7180_REG_SHAP_FILTER_CTL_1 0x0017 #define ADV7180_REG_CTRL_2 0x001d #define ADV7180_REG_VSYNC_FIELD_CTL_1 0x0031 #define ADV7180_VSYNC_FIELD_CTL_1_NEWAV 0x12 #define ADV7180_REG_MANUAL_WIN_CTL_1 0x003d #define ADV7180_REG_MANUAL_WIN_CTL_2 0x003e #define ADV7180_REG_MANUAL_WIN_CTL_3 0x003f #define ADV7180_REG_LOCK_CNT 0x0051 #define ADV7180_REG_CVBS_TRIM 0x0052 #define ADV7180_REG_CLAMP_ADJ 0x005a #define ADV7180_REG_RES_CIR 0x005f #define ADV7180_REG_DIFF_MODE 0x0060 #define ADV7180_REG_ICONF1 0x2040 #define ADV7180_ICONF1_ACTIVE_LOW 0x01 #define ADV7180_ICONF1_PSYNC_ONLY 0x10 #define ADV7180_ICONF1_ACTIVE_TO_CLR 0xC0 /* Saturation */ #define ADV7180_REG_SD_SAT_CB 0x00e3 /*Unsigned */ #define ADV7180_REG_SD_SAT_CR 0x00e4 /*Unsigned */ #define ADV7180_SAT_MIN 0 #define ADV7180_SAT_DEF 128 #define ADV7180_SAT_MAX 255 #define ADV7180_IRQ1_LOCK 0x01 #define ADV7180_IRQ1_UNLOCK 0x02 #define ADV7180_REG_ISR1 0x2042 #define ADV7180_REG_ICR1 0x2043 #define ADV7180_REG_IMR1 0x2044 #define ADV7180_REG_IMR2 0x2048 #define ADV7180_IRQ3_AD_CHANGE 0x08 #define ADV7180_REG_ISR3 0x204A #define ADV7180_REG_ICR3 0x204B #define ADV7180_REG_IMR3 0x204C #define ADV7180_REG_IMR4 0x2050 #define ADV7180_REG_NTSC_V_BIT_END 0x00E6 #define ADV7180_NTSC_V_BIT_END_MANUAL_NVEND 0x4F #define ADV7180_REG_VPP_SLAVE_ADDR 0xFD #define ADV7180_REG_CSI_SLAVE_ADDR 0xFE #define ADV7180_REG_ACE_CTRL1 0x4080 #define ADV7180_REG_ACE_CTRL5 0x4084 #define ADV7180_REG_FLCONTROL 0x40e0 #define ADV7180_FLCONTROL_FL_ENABLE 0x1 #define ADV7180_REG_RST_CLAMP 0x809c #define ADV7180_REG_AGC_ADJ1 0x80b6 #define ADV7180_REG_AGC_ADJ2 0x80c0 #define ADV7180_CSI_REG_PWRDN 0x00 #define ADV7180_CSI_PWRDN 0x80 #define ADV7180_INPUT_CVBS_AIN1 0x00 #define ADV7180_INPUT_CVBS_AIN2 0x01 #define ADV7180_INPUT_CVBS_AIN3 0x02 #define ADV7180_INPUT_CVBS_AIN4 0x03 #define ADV7180_INPUT_CVBS_AIN5 0x04 #define ADV7180_INPUT_CVBS_AIN6 0x05 #define ADV7180_INPUT_SVIDEO_AIN1_AIN2 0x06 #define ADV7180_INPUT_SVIDEO_AIN3_AIN4 0x07 #define ADV7180_INPUT_SVIDEO_AIN5_AIN6 0x08 #define ADV7180_INPUT_YPRPB_AIN1_AIN2_AIN3 0x09 #define ADV7180_INPUT_YPRPB_AIN4_AIN5_AIN6 0x0a #define ADV7182_INPUT_CVBS_AIN1 0x00 #define ADV7182_INPUT_CVBS_AIN2 0x01 #define ADV7182_INPUT_CVBS_AIN3 0x02 #define ADV7182_INPUT_CVBS_AIN4 0x03 #define ADV7182_INPUT_CVBS_AIN5 0x04 #define ADV7182_INPUT_CVBS_AIN6 0x05 #define ADV7182_INPUT_CVBS_AIN7 0x06 #define ADV7182_INPUT_CVBS_AIN8 0x07 #define ADV7182_INPUT_SVIDEO_AIN1_AIN2 0x08 #define ADV7182_INPUT_SVIDEO_AIN3_AIN4 0x09 #define ADV7182_INPUT_SVIDEO_AIN5_AIN6 0x0a #define ADV7182_INPUT_SVIDEO_AIN7_AIN8 0x0b #define ADV7182_INPUT_YPRPB_AIN1_AIN2_AIN3 0x0c #define ADV7182_INPUT_YPRPB_AIN4_AIN5_AIN6 0x0d #define ADV7182_INPUT_DIFF_CVBS_AIN1_AIN2 0x0e #define ADV7182_INPUT_DIFF_CVBS_AIN3_AIN4 0x0f #define ADV7182_INPUT_DIFF_CVBS_AIN5_AIN6 0x10 #define ADV7182_INPUT_DIFF_CVBS_AIN7_AIN8 0x11 #define ADV7180_DEFAULT_CSI_I2C_ADDR 0x44 #define ADV7180_DEFAULT_VPP_I2C_ADDR 0x42 #define V4L2_CID_ADV_FAST_SWITCH (V4L2_CID_USER_ADV7180_BASE + 0x00) /* Initial number of frames to skip to avoid possible garbage */ #define ADV7180_NUM_OF_SKIP_FRAMES 2 struct adv7180_state; #define ADV7180_FLAG_RESET_POWERED BIT(0) #define ADV7180_FLAG_V2 BIT(1) #define ADV7180_FLAG_MIPI_CSI2 BIT(2) #define ADV7180_FLAG_I2P BIT(3) struct adv7180_chip_info { unsigned int flags; unsigned int valid_input_mask; int (*set_std)(struct adv7180_state *st, unsigned int std); int (*select_input)(struct adv7180_state *st, unsigned int input); int (*init)(struct adv7180_state *state); }; struct adv7180_state { struct v4l2_ctrl_handler ctrl_hdl; struct v4l2_subdev sd; struct media_pad pad; struct mutex mutex; /* mutual excl. when accessing chip */ int irq; struct gpio_desc *pwdn_gpio; struct gpio_desc *rst_gpio; v4l2_std_id curr_norm; bool powered; bool streaming; u8 input; struct i2c_client *client; unsigned int register_page; struct i2c_client *csi_client; struct i2c_client *vpp_client; const struct adv7180_chip_info *chip_info; enum v4l2_field field; bool force_bt656_4; }; #define to_adv7180_sd(_ctrl) (&container_of(_ctrl->handler, \ struct adv7180_state, \ ctrl_hdl)->sd) static int adv7180_select_page(struct adv7180_state *state, unsigned int page) { if (state->register_page != page) { i2c_smbus_write_byte_data(state->client, ADV7180_REG_CTRL, page); state->register_page = page; } return 0; } static int adv7180_write(struct adv7180_state *state, unsigned int reg, unsigned int value) { lockdep_assert_held(&state->mutex); adv7180_select_page(state, reg >> 8); return i2c_smbus_write_byte_data(state->client, reg & 0xff, value); } static int adv7180_read(struct adv7180_state *state, unsigned int reg) { lockdep_assert_held(&state->mutex); adv7180_select_page(state, reg >> 8); return i2c_smbus_read_byte_data(state->client, reg & 0xff); } static int adv7180_csi_write(struct adv7180_state *state, unsigned int reg, unsigned int value) { return i2c_smbus_write_byte_data(state->csi_client, reg, value); } static int adv7180_set_video_standard(struct adv7180_state *state, unsigned int std) { return state->chip_info->set_std(state, std); } static int adv7180_vpp_write(struct adv7180_state *state, unsigned int reg, unsigned int value) { return i2c_smbus_write_byte_data(state->vpp_client, reg, value); } static v4l2_std_id adv7180_std_to_v4l2(u8 status1) { /* in case V4L2_IN_ST_NO_SIGNAL */ if (!(status1 & ADV7180_STATUS1_IN_LOCK)) return V4L2_STD_UNKNOWN; switch (status1 & ADV7180_STATUS1_AUTOD_MASK) { case ADV7180_STATUS1_AUTOD_NTSM_M_J: return V4L2_STD_NTSC; case ADV7180_STATUS1_AUTOD_NTSC_4_43: return V4L2_STD_NTSC_443; case ADV7180_STATUS1_AUTOD_PAL_M: return V4L2_STD_PAL_M; case ADV7180_STATUS1_AUTOD_PAL_60: return V4L2_STD_PAL_60; case ADV7180_STATUS1_AUTOD_PAL_B_G: return V4L2_STD_PAL; case ADV7180_STATUS1_AUTOD_SECAM: return V4L2_STD_SECAM; case ADV7180_STATUS1_AUTOD_PAL_COMB: return V4L2_STD_PAL_Nc | V4L2_STD_PAL_N; case ADV7180_STATUS1_AUTOD_SECAM_525: return V4L2_STD_SECAM; default: return V4L2_STD_UNKNOWN; } } static int v4l2_std_to_adv7180(v4l2_std_id std) { if (std == V4L2_STD_PAL_60) return ADV7180_STD_PAL60; if (std == V4L2_STD_NTSC_443) return ADV7180_STD_NTSC_443; if (std == V4L2_STD_PAL_N) return ADV7180_STD_PAL_N; if (std == V4L2_STD_PAL_M) return ADV7180_STD_PAL_M; if (std == V4L2_STD_PAL_Nc) return ADV7180_STD_PAL_COMB_N; if (std & V4L2_STD_PAL) return ADV7180_STD_PAL_BG; if (std & V4L2_STD_NTSC) return ADV7180_STD_NTSC_M; if (std & V4L2_STD_SECAM) return ADV7180_STD_PAL_SECAM; return -EINVAL; } static u32 adv7180_status_to_v4l2(u8 status1) { if (!(status1 & ADV7180_STATUS1_IN_LOCK)) return V4L2_IN_ST_NO_SIGNAL; return 0; } static int __adv7180_status(struct adv7180_state *state, u32 *status, v4l2_std_id *std) { int status1 = adv7180_read(state, ADV7180_REG_STATUS1); if (status1 < 0) return status1; if (status) *status = adv7180_status_to_v4l2(status1); if (std) *std = adv7180_std_to_v4l2(status1); return 0; } static inline struct adv7180_state *to_state(struct v4l2_subdev *sd) { return container_of(sd, struct adv7180_state, sd); } static int adv7180_querystd(struct v4l2_subdev *sd, v4l2_std_id *std) { struct adv7180_state *state = to_state(sd); int err = mutex_lock_interruptible(&state->mutex); if (err) return err; if (state->streaming) { err = -EBUSY; goto unlock; } err = adv7180_set_video_standard(state, ADV7180_STD_AD_PAL_BG_NTSC_J_SECAM); if (err) goto unlock; msleep(100); __adv7180_status(state, NULL, std); err = v4l2_std_to_adv7180(state->curr_norm); if (err < 0) goto unlock; err = adv7180_set_video_standard(state, err); unlock: mutex_unlock(&state->mutex); return err; } static int adv7180_s_routing(struct v4l2_subdev *sd, u32 input, u32 output, u32 config) { struct adv7180_state *state = to_state(sd); int ret = mutex_lock_interruptible(&state->mutex); if (ret) return ret; if (input > 31 || !(BIT(input) & state->chip_info->valid_input_mask)) { ret = -EINVAL; goto out; } ret = state->chip_info->select_input(state, input); if (ret == 0) state->input = input; out: mutex_unlock(&state->mutex); return ret; } static int adv7180_g_input_status(struct v4l2_subdev *sd, u32 *status) { struct adv7180_state *state = to_state(sd); int ret = mutex_lock_interruptible(&state->mutex); if (ret) return ret; ret = __adv7180_status(state, status, NULL); mutex_unlock(&state->mutex); return ret; } static int adv7180_program_std(struct adv7180_state *state) { int ret; ret = v4l2_std_to_adv7180(state->curr_norm); if (ret < 0) return ret; ret = adv7180_set_video_standard(state, ret); if (ret < 0) return ret; return 0; } static int adv7180_s_std(struct v4l2_subdev *sd, v4l2_std_id std) { struct adv7180_state *state = to_state(sd); int ret = mutex_lock_interruptible(&state->mutex); if (ret) return ret; /* Make sure we can support this std */ ret = v4l2_std_to_adv7180(std); if (ret < 0) goto out; state->curr_norm = std; ret = adv7180_program_std(state); out: mutex_unlock(&state->mutex); return ret; } static int adv7180_g_std(struct v4l2_subdev *sd, v4l2_std_id *norm) { struct adv7180_state *state = to_state(sd); *norm = state->curr_norm; return 0; } static int adv7180_g_frame_interval(struct v4l2_subdev *sd, struct v4l2_subdev_frame_interval *fi) { struct adv7180_state *state = to_state(sd); if (state->curr_norm & V4L2_STD_525_60) { fi->interval.numerator = 1001; fi->interval.denominator = 30000; } else { fi->interval.numerator = 1; fi->interval.denominator = 25; } return 0; } static void adv7180_set_power_pin(struct adv7180_state *state, bool on) { if (!state->pwdn_gpio) return; if (on) { gpiod_set_value_cansleep(state->pwdn_gpio, 0); usleep_range(5000, 10000); } else { gpiod_set_value_cansleep(state->pwdn_gpio, 1); } } static void adv7180_set_reset_pin(struct adv7180_state *state, bool on) { if (!state->rst_gpio) return; if (on) { gpiod_set_value_cansleep(state->rst_gpio, 1); } else { gpiod_set_value_cansleep(state->rst_gpio, 0); usleep_range(5000, 10000); } } static int adv7180_set_power(struct adv7180_state *state, bool on) { u8 val; int ret; if (on) val = ADV7180_PWR_MAN_ON; else val = ADV7180_PWR_MAN_OFF; ret = adv7180_write(state, ADV7180_REG_PWR_MAN, val); if (ret) return ret; if (state->chip_info->flags & ADV7180_FLAG_MIPI_CSI2) { if (on) { adv7180_csi_write(state, 0xDE, 0x02); adv7180_csi_write(state, 0xD2, 0xF7); adv7180_csi_write(state, 0xD8, 0x65); adv7180_csi_write(state, 0xE0, 0x09); adv7180_csi_write(state, 0x2C, 0x00); if (state->field == V4L2_FIELD_NONE) adv7180_csi_write(state, 0x1D, 0x80); adv7180_csi_write(state, 0x00, 0x00); } else { adv7180_csi_write(state, 0x00, 0x80); } } return 0; } static int adv7180_s_power(struct v4l2_subdev *sd, int on) { struct adv7180_state *state = to_state(sd); int ret; ret = mutex_lock_interruptible(&state->mutex); if (ret) return ret; ret = adv7180_set_power(state, on); if (ret == 0) state->powered = on; mutex_unlock(&state->mutex); return ret; } static const char * const test_pattern_menu[] = { "Single color", "Color bars", "Luma ramp", "Boundary box", "Disable", }; static int adv7180_test_pattern(struct adv7180_state *state, int value) { unsigned int reg = 0; /* Map menu value into register value */ if (value < 3) reg = value; if (value == 3) reg = 5; adv7180_write(state, ADV7180_REG_ANALOG_CLAMP_CTL, reg); if (value == ARRAY_SIZE(test_pattern_menu) - 1) { reg = adv7180_read(state, ADV7180_REG_DEF_VALUE_Y); reg &= ~ADV7180_DEF_VAL_EN; adv7180_write(state, ADV7180_REG_DEF_VALUE_Y, reg); return 0; } reg = adv7180_read(state, ADV7180_REG_DEF_VALUE_Y); reg |= ADV7180_DEF_VAL_EN | ADV7180_DEF_VAL_AUTO_EN; adv7180_write(state, ADV7180_REG_DEF_VALUE_Y, reg); return 0; } static int adv7180_s_ctrl(struct v4l2_ctrl *ctrl) { struct v4l2_subdev *sd = to_adv7180_sd(ctrl); struct adv7180_state *state = to_state(sd); int ret = mutex_lock_interruptible(&state->mutex); int val; if (ret) return ret; val = ctrl->val; switch (ctrl->id) { case V4L2_CID_BRIGHTNESS: ret = adv7180_write(state, ADV7180_REG_BRI, val); break; case V4L2_CID_HUE: /*Hue is inverted according to HSL chart */ ret = adv7180_write(state, ADV7180_REG_HUE, -val); break; case V4L2_CID_CONTRAST: ret = adv7180_write(state, ADV7180_REG_CON, val); break; case V4L2_CID_SATURATION: /* *This could be V4L2_CID_BLUE_BALANCE/V4L2_CID_RED_BALANCE *Let's not confuse the user, everybody understands saturation */ ret = adv7180_write(state, ADV7180_REG_SD_SAT_CB, val); if (ret < 0) break; ret = adv7180_write(state, ADV7180_REG_SD_SAT_CR, val); break; case V4L2_CID_ADV_FAST_SWITCH: if (ctrl->val) { /* ADI required write */ adv7180_write(state, 0x80d9, 0x44); adv7180_write(state, ADV7180_REG_FLCONTROL, ADV7180_FLCONTROL_FL_ENABLE); } else { /* ADI required write */ adv7180_write(state, 0x80d9, 0xc4); adv7180_write(state, ADV7180_REG_FLCONTROL, 0x00); } break; case V4L2_CID_TEST_PATTERN: ret = adv7180_test_pattern(state, val); break; default: ret = -EINVAL; } mutex_unlock(&state->mutex); return ret; } static const struct v4l2_ctrl_ops adv7180_ctrl_ops = { .s_ctrl = adv7180_s_ctrl, }; static const struct v4l2_ctrl_config adv7180_ctrl_fast_switch = { .ops = &adv7180_ctrl_ops, .id = V4L2_CID_ADV_FAST_SWITCH, .name = "Fast Switching", .type = V4L2_CTRL_TYPE_BOOLEAN, .min = 0, .max = 1, .step = 1, }; static int adv7180_init_controls(struct adv7180_state *state) { v4l2_ctrl_handler_init(&state->ctrl_hdl, 4); v4l2_ctrl_new_std(&state->ctrl_hdl, &adv7180_ctrl_ops, V4L2_CID_BRIGHTNESS, ADV7180_BRI_MIN, ADV7180_BRI_MAX, 1, ADV7180_BRI_DEF); v4l2_ctrl_new_std(&state->ctrl_hdl, &adv7180_ctrl_ops, V4L2_CID_CONTRAST, ADV7180_CON_MIN, ADV7180_CON_MAX, 1, ADV7180_CON_DEF); v4l2_ctrl_new_std(&state->ctrl_hdl, &adv7180_ctrl_ops, V4L2_CID_SATURATION, ADV7180_SAT_MIN, ADV7180_SAT_MAX, 1, ADV7180_SAT_DEF); v4l2_ctrl_new_std(&state->ctrl_hdl, &adv7180_ctrl_ops, V4L2_CID_HUE, ADV7180_HUE_MIN, ADV7180_HUE_MAX, 1, ADV7180_HUE_DEF); v4l2_ctrl_new_custom(&state->ctrl_hdl, &adv7180_ctrl_fast_switch, NULL); v4l2_ctrl_new_std_menu_items(&state->ctrl_hdl, &adv7180_ctrl_ops, V4L2_CID_TEST_PATTERN, ARRAY_SIZE(test_pattern_menu) - 1, 0, ARRAY_SIZE(test_pattern_menu) - 1, test_pattern_menu); state->sd.ctrl_handler = &state->ctrl_hdl; if (state->ctrl_hdl.error) { int err = state->ctrl_hdl.error; v4l2_ctrl_handler_free(&state->ctrl_hdl); return err; } v4l2_ctrl_handler_setup(&state->ctrl_hdl); return 0; } static void adv7180_exit_controls(struct adv7180_state *state) { v4l2_ctrl_handler_free(&state->ctrl_hdl); } static int adv7180_enum_mbus_code(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_mbus_code_enum *code) { if (code->index != 0) return -EINVAL; code->code = MEDIA_BUS_FMT_UYVY8_2X8; return 0; } static int adv7180_mbus_fmt(struct v4l2_subdev *sd, struct v4l2_mbus_framefmt *fmt) { struct adv7180_state *state = to_state(sd); fmt->code = MEDIA_BUS_FMT_UYVY8_2X8; fmt->colorspace = V4L2_COLORSPACE_SMPTE170M; fmt->width = 720; fmt->height = state->curr_norm & V4L2_STD_525_60 ? 480 : 576; if (state->field == V4L2_FIELD_ALTERNATE) fmt->height /= 2; return 0; } static int adv7180_set_field_mode(struct adv7180_state *state) { if (!(state->chip_info->flags & ADV7180_FLAG_I2P)) return 0; if (state->field == V4L2_FIELD_NONE) { if (state->chip_info->flags & ADV7180_FLAG_MIPI_CSI2) { adv7180_csi_write(state, 0x01, 0x20); adv7180_csi_write(state, 0x02, 0x28); adv7180_csi_write(state, 0x03, 0x38); adv7180_csi_write(state, 0x04, 0x30); adv7180_csi_write(state, 0x05, 0x30); adv7180_csi_write(state, 0x06, 0x80); adv7180_csi_write(state, 0x07, 0x70); adv7180_csi_write(state, 0x08, 0x50); } adv7180_vpp_write(state, 0xa3, 0x00); adv7180_vpp_write(state, 0x5b, 0x00); adv7180_vpp_write(state, 0x55, 0x80); } else { if (state->chip_info->flags & ADV7180_FLAG_MIPI_CSI2) { adv7180_csi_write(state, 0x01, 0x18); adv7180_csi_write(state, 0x02, 0x18); adv7180_csi_write(state, 0x03, 0x30); adv7180_csi_write(state, 0x04, 0x20); adv7180_csi_write(state, 0x05, 0x28); adv7180_csi_write(state, 0x06, 0x40); adv7180_csi_write(state, 0x07, 0x58); adv7180_csi_write(state, 0x08, 0x30); } adv7180_vpp_write(state, 0xa3, 0x70); adv7180_vpp_write(state, 0x5b, 0x80); adv7180_vpp_write(state, 0x55, 0x00); } return 0; } static int adv7180_get_pad_format(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *format) { struct adv7180_state *state = to_state(sd); if (format->which == V4L2_SUBDEV_FORMAT_TRY) { format->format = *v4l2_subdev_get_try_format(sd, sd_state, 0); } else { adv7180_mbus_fmt(sd, &format->format); format->format.field = state->field; } return 0; } static int adv7180_set_pad_format(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *format) { struct adv7180_state *state = to_state(sd); struct v4l2_mbus_framefmt *framefmt; int ret; switch (format->format.field) { case V4L2_FIELD_NONE: if (state->chip_info->flags & ADV7180_FLAG_I2P) break; fallthrough; default: format->format.field = V4L2_FIELD_ALTERNATE; break; } ret = adv7180_mbus_fmt(sd, &format->format); if (format->which == V4L2_SUBDEV_FORMAT_ACTIVE) { if (state->field != format->format.field) { state->field = format->format.field; adv7180_set_power(state, false); adv7180_set_field_mode(state); adv7180_set_power(state, true); } } else { framefmt = v4l2_subdev_get_try_format(sd, sd_state, 0); *framefmt = format->format; } return ret; } static int adv7180_init_cfg(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state) { struct v4l2_subdev_format fmt = { .which = sd_state ? V4L2_SUBDEV_FORMAT_TRY : V4L2_SUBDEV_FORMAT_ACTIVE, }; return adv7180_set_pad_format(sd, sd_state, &fmt); } static int adv7180_get_mbus_config(struct v4l2_subdev *sd, unsigned int pad, struct v4l2_mbus_config *cfg) { struct adv7180_state *state = to_state(sd); if (state->chip_info->flags & ADV7180_FLAG_MIPI_CSI2) { cfg->type = V4L2_MBUS_CSI2_DPHY; cfg->bus.mipi_csi2.num_data_lanes = 1; cfg->bus.mipi_csi2.flags = 0; } else { /* * The ADV7180 sensor supports BT.601/656 output modes. * The BT.656 is default and not yet configurable by s/w. */ cfg->bus.parallel.flags = V4L2_MBUS_MASTER | V4L2_MBUS_PCLK_SAMPLE_RISING | V4L2_MBUS_DATA_ACTIVE_HIGH; cfg->type = V4L2_MBUS_BT656; } return 0; } static int adv7180_get_skip_frames(struct v4l2_subdev *sd, u32 *frames) { *frames = ADV7180_NUM_OF_SKIP_FRAMES; return 0; } static int adv7180_g_pixelaspect(struct v4l2_subdev *sd, struct v4l2_fract *aspect) { struct adv7180_state *state = to_state(sd); if (state->curr_norm & V4L2_STD_525_60) { aspect->numerator = 11; aspect->denominator = 10; } else { aspect->numerator = 54; aspect->denominator = 59; } return 0; } static int adv7180_g_tvnorms(struct v4l2_subdev *sd, v4l2_std_id *norm) { *norm = V4L2_STD_ALL; return 0; } static int adv7180_s_stream(struct v4l2_subdev *sd, int enable) { struct adv7180_state *state = to_state(sd); int ret; /* It's always safe to stop streaming, no need to take the lock */ if (!enable) { state->streaming = enable; return 0; } /* Must wait until querystd released the lock */ ret = mutex_lock_interruptible(&state->mutex); if (ret) return ret; state->streaming = enable; mutex_unlock(&state->mutex); return 0; } static int adv7180_subscribe_event(struct v4l2_subdev *sd, struct v4l2_fh *fh, struct v4l2_event_subscription *sub) { switch (sub->type) { case V4L2_EVENT_SOURCE_CHANGE: return v4l2_src_change_event_subdev_subscribe(sd, fh, sub); case V4L2_EVENT_CTRL: return v4l2_ctrl_subdev_subscribe_event(sd, fh, sub); default: return -EINVAL; } } static const struct v4l2_subdev_video_ops adv7180_video_ops = { .s_std = adv7180_s_std, .g_std = adv7180_g_std, .g_frame_interval = adv7180_g_frame_interval, .querystd = adv7180_querystd, .g_input_status = adv7180_g_input_status, .s_routing = adv7180_s_routing, .g_pixelaspect = adv7180_g_pixelaspect, .g_tvnorms = adv7180_g_tvnorms, .s_stream = adv7180_s_stream, }; static const struct v4l2_subdev_core_ops adv7180_core_ops = { .s_power = adv7180_s_power, .subscribe_event = adv7180_subscribe_event, .unsubscribe_event = v4l2_event_subdev_unsubscribe, }; static const struct v4l2_subdev_pad_ops adv7180_pad_ops = { .init_cfg = adv7180_init_cfg, .enum_mbus_code = adv7180_enum_mbus_code, .set_fmt = adv7180_set_pad_format, .get_fmt = adv7180_get_pad_format, .get_mbus_config = adv7180_get_mbus_config, }; static const struct v4l2_subdev_sensor_ops adv7180_sensor_ops = { .g_skip_frames = adv7180_get_skip_frames, }; static const struct v4l2_subdev_ops adv7180_ops = { .core = &adv7180_core_ops, .video = &adv7180_video_ops, .pad = &adv7180_pad_ops, .sensor = &adv7180_sensor_ops, }; static irqreturn_t adv7180_irq(int irq, void *devid) { struct adv7180_state *state = devid; u8 isr3; mutex_lock(&state->mutex); isr3 = adv7180_read(state, ADV7180_REG_ISR3); /* clear */ adv7180_write(state, ADV7180_REG_ICR3, isr3); if (isr3 & ADV7180_IRQ3_AD_CHANGE) { static const struct v4l2_event src_ch = { .type = V4L2_EVENT_SOURCE_CHANGE, .u.src_change.changes = V4L2_EVENT_SRC_CH_RESOLUTION, }; v4l2_subdev_notify_event(&state->sd, &src_ch); } mutex_unlock(&state->mutex); return IRQ_HANDLED; } static int adv7180_init(struct adv7180_state *state) { int ret; /* ITU-R BT.656-4 compatible */ ret = adv7180_write(state, ADV7180_REG_EXTENDED_OUTPUT_CONTROL, ADV7180_EXTENDED_OUTPUT_CONTROL_NTSCDIS); if (ret < 0) return ret; /* Manually set V bit end position in NTSC mode */ return adv7180_write(state, ADV7180_REG_NTSC_V_BIT_END, ADV7180_NTSC_V_BIT_END_MANUAL_NVEND); } static int adv7180_set_std(struct adv7180_state *state, unsigned int std) { return adv7180_write(state, ADV7180_REG_INPUT_CONTROL, (std << 4) | state->input); } static int adv7180_select_input(struct adv7180_state *state, unsigned int input) { int ret; ret = adv7180_read(state, ADV7180_REG_INPUT_CONTROL); if (ret < 0) return ret; ret &= ~ADV7180_INPUT_CONTROL_INSEL_MASK; ret |= input; return adv7180_write(state, ADV7180_REG_INPUT_CONTROL, ret); } static int adv7182_init(struct adv7180_state *state) { if (state->chip_info->flags & ADV7180_FLAG_MIPI_CSI2) adv7180_write(state, ADV7180_REG_CSI_SLAVE_ADDR, ADV7180_DEFAULT_CSI_I2C_ADDR << 1); if (state->chip_info->flags & ADV7180_FLAG_I2P) adv7180_write(state, ADV7180_REG_VPP_SLAVE_ADDR, ADV7180_DEFAULT_VPP_I2C_ADDR << 1); if (state->chip_info->flags & ADV7180_FLAG_V2) { /* ADI recommended writes for improved video quality */ adv7180_write(state, 0x0080, 0x51); adv7180_write(state, 0x0081, 0x51); adv7180_write(state, 0x0082, 0x68); } /* ADI required writes */ if (state->chip_info->flags & ADV7180_FLAG_MIPI_CSI2) { adv7180_write(state, ADV7180_REG_OUTPUT_CONTROL, 0x4e); adv7180_write(state, ADV7180_REG_EXTENDED_OUTPUT_CONTROL, 0x57); adv7180_write(state, ADV7180_REG_CTRL_2, 0xc0); } else { if (state->chip_info->flags & ADV7180_FLAG_V2) { if (state->force_bt656_4) { /* ITU-R BT.656-4 compatible */ adv7180_write(state, ADV7180_REG_EXTENDED_OUTPUT_CONTROL, ADV7180_EXTENDED_OUTPUT_CONTROL_NTSCDIS); /* Manually set NEWAVMODE */ adv7180_write(state, ADV7180_REG_VSYNC_FIELD_CTL_1, ADV7180_VSYNC_FIELD_CTL_1_NEWAV); /* Manually set V bit end position in NTSC mode */ adv7180_write(state, ADV7180_REG_NTSC_V_BIT_END, ADV7180_NTSC_V_BIT_END_MANUAL_NVEND); } else { adv7180_write(state, ADV7180_REG_EXTENDED_OUTPUT_CONTROL, 0x17); } } else adv7180_write(state, ADV7180_REG_EXTENDED_OUTPUT_CONTROL, 0x07); adv7180_write(state, ADV7180_REG_OUTPUT_CONTROL, 0x0c); adv7180_write(state, ADV7180_REG_CTRL_2, 0x40); } adv7180_write(state, 0x0013, 0x00); return 0; } static int adv7182_set_std(struct adv7180_state *state, unsigned int std) { /* Failing to set the reserved bit can result in increased video noise */ return adv7180_write(state, ADV7182_REG_INPUT_VIDSEL, (std << 4) | ADV7182_REG_INPUT_RESERVED); } enum adv7182_input_type { ADV7182_INPUT_TYPE_CVBS, ADV7182_INPUT_TYPE_DIFF_CVBS, ADV7182_INPUT_TYPE_SVIDEO, ADV7182_INPUT_TYPE_YPBPR, }; static enum adv7182_input_type adv7182_get_input_type(unsigned int input) { switch (input) { case ADV7182_INPUT_CVBS_AIN1: case ADV7182_INPUT_CVBS_AIN2: case ADV7182_INPUT_CVBS_AIN3: case ADV7182_INPUT_CVBS_AIN4: case ADV7182_INPUT_CVBS_AIN5: case ADV7182_INPUT_CVBS_AIN6: case ADV7182_INPUT_CVBS_AIN7: case ADV7182_INPUT_CVBS_AIN8: return ADV7182_INPUT_TYPE_CVBS; case ADV7182_INPUT_SVIDEO_AIN1_AIN2: case ADV7182_INPUT_SVIDEO_AIN3_AIN4: case ADV7182_INPUT_SVIDEO_AIN5_AIN6: case ADV7182_INPUT_SVIDEO_AIN7_AIN8: return ADV7182_INPUT_TYPE_SVIDEO; case ADV7182_INPUT_YPRPB_AIN1_AIN2_AIN3: case ADV7182_INPUT_YPRPB_AIN4_AIN5_AIN6: return ADV7182_INPUT_TYPE_YPBPR; case ADV7182_INPUT_DIFF_CVBS_AIN1_AIN2: case ADV7182_INPUT_DIFF_CVBS_AIN3_AIN4: case ADV7182_INPUT_DIFF_CVBS_AIN5_AIN6: case ADV7182_INPUT_DIFF_CVBS_AIN7_AIN8: return ADV7182_INPUT_TYPE_DIFF_CVBS; default: /* Will never happen */ return 0; } } /* ADI recommended writes to registers 0x52, 0x53, 0x54 */ static unsigned int adv7182_lbias_settings[][3] = { [ADV7182_INPUT_TYPE_CVBS] = { 0xCB, 0x4E, 0x80 }, [ADV7182_INPUT_TYPE_DIFF_CVBS] = { 0xC0, 0x4E, 0x80 }, [ADV7182_INPUT_TYPE_SVIDEO] = { 0x0B, 0xCE, 0x80 }, [ADV7182_INPUT_TYPE_YPBPR] = { 0x0B, 0x4E, 0xC0 }, }; static unsigned int adv7280_lbias_settings[][3] = { [ADV7182_INPUT_TYPE_CVBS] = { 0xCD, 0x4E, 0x80 }, [ADV7182_INPUT_TYPE_DIFF_CVBS] = { 0xC0, 0x4E, 0x80 }, [ADV7182_INPUT_TYPE_SVIDEO] = { 0x0B, 0xCE, 0x80 }, [ADV7182_INPUT_TYPE_YPBPR] = { 0x0B, 0x4E, 0xC0 }, }; static int adv7182_select_input(struct adv7180_state *state, unsigned int input) { enum adv7182_input_type input_type; unsigned int *lbias; unsigned int i; int ret; ret = adv7180_write(state, ADV7180_REG_INPUT_CONTROL, input); if (ret) return ret; /* Reset clamp circuitry - ADI recommended writes */ adv7180_write(state, ADV7180_REG_RST_CLAMP, 0x00); adv7180_write(state, ADV7180_REG_RST_CLAMP, 0xff); input_type = adv7182_get_input_type(input); switch (input_type) { case ADV7182_INPUT_TYPE_CVBS: case ADV7182_INPUT_TYPE_DIFF_CVBS: /* ADI recommends to use the SH1 filter */ adv7180_write(state, ADV7180_REG_SHAP_FILTER_CTL_1, 0x41); break; default: adv7180_write(state, ADV7180_REG_SHAP_FILTER_CTL_1, 0x01); break; } if (state->chip_info->flags & ADV7180_FLAG_V2) lbias = adv7280_lbias_settings[input_type]; else lbias = adv7182_lbias_settings[input_type]; for (i = 0; i < ARRAY_SIZE(adv7182_lbias_settings[0]); i++) adv7180_write(state, ADV7180_REG_CVBS_TRIM + i, lbias[i]); if (input_type == ADV7182_INPUT_TYPE_DIFF_CVBS) { /* ADI required writes to make differential CVBS work */ adv7180_write(state, ADV7180_REG_RES_CIR, 0xa8); adv7180_write(state, ADV7180_REG_CLAMP_ADJ, 0x90); adv7180_write(state, ADV7180_REG_DIFF_MODE, 0xb0); adv7180_write(state, ADV7180_REG_AGC_ADJ1, 0x08); adv7180_write(state, ADV7180_REG_AGC_ADJ2, 0xa0); } else { adv7180_write(state, ADV7180_REG_RES_CIR, 0xf0); adv7180_write(state, ADV7180_REG_CLAMP_ADJ, 0xd0); adv7180_write(state, ADV7180_REG_DIFF_MODE, 0x10); adv7180_write(state, ADV7180_REG_AGC_ADJ1, 0x9c); adv7180_write(state, ADV7180_REG_AGC_ADJ2, 0x00); } return 0; } static const struct adv7180_chip_info adv7180_info = { .flags = ADV7180_FLAG_RESET_POWERED, /* We cannot discriminate between LQFP and 40-pin LFCSP, so accept * all inputs and let the card driver take care of validation */ .valid_input_mask = BIT(ADV7180_INPUT_CVBS_AIN1) | BIT(ADV7180_INPUT_CVBS_AIN2) | BIT(ADV7180_INPUT_CVBS_AIN3) | BIT(ADV7180_INPUT_CVBS_AIN4) | BIT(ADV7180_INPUT_CVBS_AIN5) | BIT(ADV7180_INPUT_CVBS_AIN6) | BIT(ADV7180_INPUT_SVIDEO_AIN1_AIN2) | BIT(ADV7180_INPUT_SVIDEO_AIN3_AIN4) | BIT(ADV7180_INPUT_SVIDEO_AIN5_AIN6) | BIT(ADV7180_INPUT_YPRPB_AIN1_AIN2_AIN3) | BIT(ADV7180_INPUT_YPRPB_AIN4_AIN5_AIN6), .init = adv7180_init, .set_std = adv7180_set_std, .select_input = adv7180_select_input, }; static const struct adv7180_chip_info adv7182_info = { .valid_input_mask = BIT(ADV7182_INPUT_CVBS_AIN1) | BIT(ADV7182_INPUT_CVBS_AIN2) | BIT(ADV7182_INPUT_CVBS_AIN3) | BIT(ADV7182_INPUT_CVBS_AIN4) | BIT(ADV7182_INPUT_SVIDEO_AIN1_AIN2) | BIT(ADV7182_INPUT_SVIDEO_AIN3_AIN4) | BIT(ADV7182_INPUT_YPRPB_AIN1_AIN2_AIN3) | BIT(ADV7182_INPUT_DIFF_CVBS_AIN1_AIN2) | BIT(ADV7182_INPUT_DIFF_CVBS_AIN3_AIN4), .init = adv7182_init, .set_std = adv7182_set_std, .select_input = adv7182_select_input, }; static const struct adv7180_chip_info adv7280_info = { .flags = ADV7180_FLAG_V2 | ADV7180_FLAG_I2P, .valid_input_mask = BIT(ADV7182_INPUT_CVBS_AIN1) | BIT(ADV7182_INPUT_CVBS_AIN2) | BIT(ADV7182_INPUT_CVBS_AIN3) | BIT(ADV7182_INPUT_CVBS_AIN4) | BIT(ADV7182_INPUT_SVIDEO_AIN1_AIN2) | BIT(ADV7182_INPUT_SVIDEO_AIN3_AIN4) | BIT(ADV7182_INPUT_YPRPB_AIN1_AIN2_AIN3), .init = adv7182_init, .set_std = adv7182_set_std, .select_input = adv7182_select_input, }; static const struct adv7180_chip_info adv7280_m_info = { .flags = ADV7180_FLAG_V2 | ADV7180_FLAG_MIPI_CSI2 | ADV7180_FLAG_I2P, .valid_input_mask = BIT(ADV7182_INPUT_CVBS_AIN1) | BIT(ADV7182_INPUT_CVBS_AIN2) | BIT(ADV7182_INPUT_CVBS_AIN3) | BIT(ADV7182_INPUT_CVBS_AIN4) | BIT(ADV7182_INPUT_CVBS_AIN5) | BIT(ADV7182_INPUT_CVBS_AIN6) | BIT(ADV7182_INPUT_CVBS_AIN7) | BIT(ADV7182_INPUT_CVBS_AIN8) | BIT(ADV7182_INPUT_SVIDEO_AIN1_AIN2) | BIT(ADV7182_INPUT_SVIDEO_AIN3_AIN4) | BIT(ADV7182_INPUT_SVIDEO_AIN5_AIN6) | BIT(ADV7182_INPUT_SVIDEO_AIN7_AIN8) | BIT(ADV7182_INPUT_YPRPB_AIN1_AIN2_AIN3) | BIT(ADV7182_INPUT_YPRPB_AIN4_AIN5_AIN6), .init = adv7182_init, .set_std = adv7182_set_std, .select_input = adv7182_select_input, }; static const struct adv7180_chip_info adv7281_info = { .flags = ADV7180_FLAG_V2 | ADV7180_FLAG_MIPI_CSI2, .valid_input_mask = BIT(ADV7182_INPUT_CVBS_AIN1) | BIT(ADV7182_INPUT_CVBS_AIN2) | BIT(ADV7182_INPUT_CVBS_AIN7) | BIT(ADV7182_INPUT_CVBS_AIN8) | BIT(ADV7182_INPUT_SVIDEO_AIN1_AIN2) | BIT(ADV7182_INPUT_SVIDEO_AIN7_AIN8) | BIT(ADV7182_INPUT_DIFF_CVBS_AIN1_AIN2) | BIT(ADV7182_INPUT_DIFF_CVBS_AIN7_AIN8), .init = adv7182_init, .set_std = adv7182_set_std, .select_input = adv7182_select_input, }; static const struct adv7180_chip_info adv7281_m_info = { .flags = ADV7180_FLAG_V2 | ADV7180_FLAG_MIPI_CSI2, .valid_input_mask = BIT(ADV7182_INPUT_CVBS_AIN1) | BIT(ADV7182_INPUT_CVBS_AIN2) | BIT(ADV7182_INPUT_CVBS_AIN3) | BIT(ADV7182_INPUT_CVBS_AIN4) | BIT(ADV7182_INPUT_CVBS_AIN7) | BIT(ADV7182_INPUT_CVBS_AIN8) | BIT(ADV7182_INPUT_SVIDEO_AIN1_AIN2) | BIT(ADV7182_INPUT_SVIDEO_AIN3_AIN4) | BIT(ADV7182_INPUT_SVIDEO_AIN7_AIN8) | BIT(ADV7182_INPUT_YPRPB_AIN1_AIN2_AIN3) | BIT(ADV7182_INPUT_DIFF_CVBS_AIN1_AIN2) | BIT(ADV7182_INPUT_DIFF_CVBS_AIN3_AIN4) | BIT(ADV7182_INPUT_DIFF_CVBS_AIN7_AIN8), .init = adv7182_init, .set_std = adv7182_set_std, .select_input = adv7182_select_input, }; static const struct adv7180_chip_info adv7281_ma_info = { .flags = ADV7180_FLAG_V2 | ADV7180_FLAG_MIPI_CSI2, .valid_input_mask = BIT(ADV7182_INPUT_CVBS_AIN1) | BIT(ADV7182_INPUT_CVBS_AIN2) | BIT(ADV7182_INPUT_CVBS_AIN3) | BIT(ADV7182_INPUT_CVBS_AIN4) | BIT(ADV7182_INPUT_CVBS_AIN5) | BIT(ADV7182_INPUT_CVBS_AIN6) | BIT(ADV7182_INPUT_CVBS_AIN7) | BIT(ADV7182_INPUT_CVBS_AIN8) | BIT(ADV7182_INPUT_SVIDEO_AIN1_AIN2) | BIT(ADV7182_INPUT_SVIDEO_AIN3_AIN4) | BIT(ADV7182_INPUT_SVIDEO_AIN5_AIN6) | BIT(ADV7182_INPUT_SVIDEO_AIN7_AIN8) | BIT(ADV7182_INPUT_YPRPB_AIN1_AIN2_AIN3) | BIT(ADV7182_INPUT_YPRPB_AIN4_AIN5_AIN6) | BIT(ADV7182_INPUT_DIFF_CVBS_AIN1_AIN2) | BIT(ADV7182_INPUT_DIFF_CVBS_AIN3_AIN4) | BIT(ADV7182_INPUT_DIFF_CVBS_AIN5_AIN6) | BIT(ADV7182_INPUT_DIFF_CVBS_AIN7_AIN8), .init = adv7182_init, .set_std = adv7182_set_std, .select_input = adv7182_select_input, }; static const struct adv7180_chip_info adv7282_info = { .flags = ADV7180_FLAG_V2 | ADV7180_FLAG_I2P, .valid_input_mask = BIT(ADV7182_INPUT_CVBS_AIN1) | BIT(ADV7182_INPUT_CVBS_AIN2) | BIT(ADV7182_INPUT_CVBS_AIN7) | BIT(ADV7182_INPUT_CVBS_AIN8) | BIT(ADV7182_INPUT_SVIDEO_AIN1_AIN2) | BIT(ADV7182_INPUT_SVIDEO_AIN7_AIN8) | BIT(ADV7182_INPUT_DIFF_CVBS_AIN1_AIN2) | BIT(ADV7182_INPUT_DIFF_CVBS_AIN7_AIN8), .init = adv7182_init, .set_std = adv7182_set_std, .select_input = adv7182_select_input, }; static const struct adv7180_chip_info adv7282_m_info = { .flags = ADV7180_FLAG_V2 | ADV7180_FLAG_MIPI_CSI2 | ADV7180_FLAG_I2P, .valid_input_mask = BIT(ADV7182_INPUT_CVBS_AIN1) | BIT(ADV7182_INPUT_CVBS_AIN2) | BIT(ADV7182_INPUT_CVBS_AIN3) | BIT(ADV7182_INPUT_CVBS_AIN4) | BIT(ADV7182_INPUT_CVBS_AIN7) | BIT(ADV7182_INPUT_CVBS_AIN8) | BIT(ADV7182_INPUT_SVIDEO_AIN1_AIN2) | BIT(ADV7182_INPUT_SVIDEO_AIN3_AIN4) | BIT(ADV7182_INPUT_SVIDEO_AIN7_AIN8) | BIT(ADV7182_INPUT_DIFF_CVBS_AIN1_AIN2) | BIT(ADV7182_INPUT_DIFF_CVBS_AIN3_AIN4) | BIT(ADV7182_INPUT_DIFF_CVBS_AIN7_AIN8), .init = adv7182_init, .set_std = adv7182_set_std, .select_input = adv7182_select_input, }; static int init_device(struct adv7180_state *state) { int ret; mutex_lock(&state->mutex); adv7180_set_power_pin(state, true); adv7180_set_reset_pin(state, false); adv7180_write(state, ADV7180_REG_PWR_MAN, ADV7180_PWR_MAN_RES); usleep_range(5000, 10000); ret = state->chip_info->init(state); if (ret) goto out_unlock; ret = adv7180_program_std(state); if (ret) goto out_unlock; adv7180_set_field_mode(state); /* register for interrupts */ if (state->irq > 0) { /* config the Interrupt pin to be active low */ ret = adv7180_write(state, ADV7180_REG_ICONF1, ADV7180_ICONF1_ACTIVE_LOW | ADV7180_ICONF1_PSYNC_ONLY); if (ret < 0) goto out_unlock; ret = adv7180_write(state, ADV7180_REG_IMR1, 0); if (ret < 0) goto out_unlock; ret = adv7180_write(state, ADV7180_REG_IMR2, 0); if (ret < 0) goto out_unlock; /* enable AD change interrupts interrupts */ ret = adv7180_write(state, ADV7180_REG_IMR3, ADV7180_IRQ3_AD_CHANGE); if (ret < 0) goto out_unlock; ret = adv7180_write(state, ADV7180_REG_IMR4, 0); if (ret < 0) goto out_unlock; } out_unlock: mutex_unlock(&state->mutex); return ret; } static int adv7180_probe(struct i2c_client *client) { const struct i2c_device_id *id = i2c_client_get_device_id(client); struct device_node *np = client->dev.of_node; struct adv7180_state *state; struct v4l2_subdev *sd; int ret; /* Check if the adapter supports the needed features */ if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE_DATA)) return -EIO; state = devm_kzalloc(&client->dev, sizeof(*state), GFP_KERNEL); if (state == NULL) return -ENOMEM; state->client = client; state->field = V4L2_FIELD_ALTERNATE; state->chip_info = (struct adv7180_chip_info *)id->driver_data; state->pwdn_gpio = devm_gpiod_get_optional(&client->dev, "powerdown", GPIOD_OUT_HIGH); if (IS_ERR(state->pwdn_gpio)) { ret = PTR_ERR(state->pwdn_gpio); v4l_err(client, "request for power pin failed: %d\n", ret); return ret; } state->rst_gpio = devm_gpiod_get_optional(&client->dev, "reset", GPIOD_OUT_HIGH); if (IS_ERR(state->rst_gpio)) { ret = PTR_ERR(state->rst_gpio); v4l_err(client, "request for reset pin failed: %d\n", ret); return ret; } if (of_property_read_bool(np, "adv,force-bt656-4")) state->force_bt656_4 = true; if (state->chip_info->flags & ADV7180_FLAG_MIPI_CSI2) { state->csi_client = i2c_new_dummy_device(client->adapter, ADV7180_DEFAULT_CSI_I2C_ADDR); if (IS_ERR(state->csi_client)) return PTR_ERR(state->csi_client); } if (state->chip_info->flags & ADV7180_FLAG_I2P) { state->vpp_client = i2c_new_dummy_device(client->adapter, ADV7180_DEFAULT_VPP_I2C_ADDR); if (IS_ERR(state->vpp_client)) { ret = PTR_ERR(state->vpp_client); goto err_unregister_csi_client; } } state->irq = client->irq; mutex_init(&state->mutex); state->curr_norm = V4L2_STD_NTSC; if (state->chip_info->flags & ADV7180_FLAG_RESET_POWERED) state->powered = true; else state->powered = false; state->input = 0; sd = &state->sd; v4l2_i2c_subdev_init(sd, client, &adv7180_ops); sd->flags |= V4L2_SUBDEV_FL_HAS_DEVNODE | V4L2_SUBDEV_FL_HAS_EVENTS; ret = adv7180_init_controls(state); if (ret) goto err_unregister_vpp_client; state->pad.flags = MEDIA_PAD_FL_SOURCE; sd->entity.function = MEDIA_ENT_F_ATV_DECODER; ret = media_entity_pads_init(&sd->entity, 1, &state->pad); if (ret) goto err_free_ctrl; ret = init_device(state); if (ret) goto err_media_entity_cleanup; if (state->irq) { ret = request_threaded_irq(client->irq, NULL, adv7180_irq, IRQF_ONESHOT | IRQF_TRIGGER_FALLING, KBUILD_MODNAME, state); if (ret) goto err_media_entity_cleanup; } ret = v4l2_async_register_subdev(sd); if (ret) goto err_free_irq; mutex_lock(&state->mutex); ret = adv7180_read(state, ADV7180_REG_IDENT); mutex_unlock(&state->mutex); if (ret < 0) goto err_v4l2_async_unregister; v4l_info(client, "chip id 0x%x found @ 0x%02x (%s)\n", ret, client->addr, client->adapter->name); return 0; err_v4l2_async_unregister: v4l2_async_unregister_subdev(sd); err_free_irq: if (state->irq > 0) free_irq(client->irq, state); err_media_entity_cleanup: media_entity_cleanup(&sd->entity); err_free_ctrl: adv7180_exit_controls(state); err_unregister_vpp_client: i2c_unregister_device(state->vpp_client); err_unregister_csi_client: i2c_unregister_device(state->csi_client); mutex_destroy(&state->mutex); return ret; } static void adv7180_remove(struct i2c_client *client) { struct v4l2_subdev *sd = i2c_get_clientdata(client); struct adv7180_state *state = to_state(sd); v4l2_async_unregister_subdev(sd); if (state->irq > 0) free_irq(client->irq, state); media_entity_cleanup(&sd->entity); adv7180_exit_controls(state); i2c_unregister_device(state->vpp_client); i2c_unregister_device(state->csi_client); adv7180_set_reset_pin(state, true); adv7180_set_power_pin(state, false); mutex_destroy(&state->mutex); } static const struct i2c_device_id adv7180_id[] = { { "adv7180", (kernel_ulong_t)&adv7180_info }, { "adv7180cp", (kernel_ulong_t)&adv7180_info }, { "adv7180st", (kernel_ulong_t)&adv7180_info }, { "adv7182", (kernel_ulong_t)&adv7182_info }, { "adv7280", (kernel_ulong_t)&adv7280_info }, { "adv7280-m", (kernel_ulong_t)&adv7280_m_info }, { "adv7281", (kernel_ulong_t)&adv7281_info }, { "adv7281-m", (kernel_ulong_t)&adv7281_m_info }, { "adv7281-ma", (kernel_ulong_t)&adv7281_ma_info }, { "adv7282", (kernel_ulong_t)&adv7282_info }, { "adv7282-m", (kernel_ulong_t)&adv7282_m_info }, {}, }; MODULE_DEVICE_TABLE(i2c, adv7180_id); #ifdef CONFIG_PM_SLEEP static int adv7180_suspend(struct device *dev) { struct v4l2_subdev *sd = dev_get_drvdata(dev); struct adv7180_state *state = to_state(sd); return adv7180_set_power(state, false); } static int adv7180_resume(struct device *dev) { struct v4l2_subdev *sd = dev_get_drvdata(dev); struct adv7180_state *state = to_state(sd); int ret; ret = init_device(state); if (ret < 0) return ret; ret = adv7180_set_power(state, state->powered); if (ret) return ret; return 0; } static SIMPLE_DEV_PM_OPS(adv7180_pm_ops, adv7180_suspend, adv7180_resume); #define ADV7180_PM_OPS (&adv7180_pm_ops) #else #define ADV7180_PM_OPS NULL #endif #ifdef CONFIG_OF static const struct of_device_id adv7180_of_id[] = { { .compatible = "adi,adv7180", }, { .compatible = "adi,adv7180cp", }, { .compatible = "adi,adv7180st", }, { .compatible = "adi,adv7182", }, { .compatible = "adi,adv7280", }, { .compatible = "adi,adv7280-m", }, { .compatible = "adi,adv7281", }, { .compatible = "adi,adv7281-m", }, { .compatible = "adi,adv7281-ma", }, { .compatible = "adi,adv7282", }, { .compatible = "adi,adv7282-m", }, { }, }; MODULE_DEVICE_TABLE(of, adv7180_of_id); #endif static struct i2c_driver adv7180_driver = { .driver = { .name = KBUILD_MODNAME, .pm = ADV7180_PM_OPS, .of_match_table = of_match_ptr(adv7180_of_id), }, .probe = adv7180_probe, .remove = adv7180_remove, .id_table = adv7180_id, }; module_i2c_driver(adv7180_driver); MODULE_DESCRIPTION("Analog Devices ADV7180 video decoder driver"); MODULE_AUTHOR("Mocean Laboratories"); MODULE_LICENSE("GPL v2");
linux-master
drivers/media/i2c/adv7180.c
// SPDX-License-Identifier: GPL-2.0 // Copyright (c) 2022 Intel Corporation. #include <asm/unaligned.h> #include <linux/acpi.h> #include <linux/delay.h> #include <linux/i2c.h> #include <linux/module.h> #include <linux/pm_runtime.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-device.h> #include <media/v4l2-fwnode.h> #define HI847_REG_VALUE_08BIT 1 #define HI847_REG_VALUE_16BIT 2 #define HI847_REG_VALUE_24BIT 3 #define HI847_LINK_FREQ_400MHZ 400000000ULL #define HI847_LINK_FREQ_200MHZ 200000000ULL #define HI847_SCLK 72000000ULL #define HI847_MCLK 19200000 #define HI847_DATA_LANES 4 #define HI847_RGB_DEPTH 10 #define HI847_REG_CHIP_ID 0x0716 #define HI847_CHIP_ID 0x0847 #define HI847_REG_MODE_SELECT 0x0B00 #define HI847_MODE_STANDBY 0x0000 #define HI847_MODE_STREAMING 0x0100 #define HI847_REG_MODE_TG 0x027E #define HI847_REG_MODE_TG_ENABLE 0x0100 #define HI847_REG_MODE_TG_DISABLE 0x0000 /* vertical-timings from sensor */ #define HI847_REG_FLL 0x020E #define HI847_FLL_30FPS 0x0B51 #define HI847_FLL_30FPS_MIN 0x0B51 #define HI847_FLL_60FPS 0x05A9 #define HI847_FLL_60FPS_MIN 0x05A9 #define HI847_FLL_MAX 0x7fff /* horizontal-timings from sensor */ #define HI847_REG_LLP 0x0206 /* Exposure controls from sensor */ #define HI847_REG_EXPOSURE 0x020A #define HI847_EXPOSURE_MIN 4 #define HI847_EXPOSURE_MAX_MARGIN 4 #define HI847_EXPOSURE_STEP 1 /* Analog gain controls from sensor */ #define HI847_REG_ANALOG_GAIN 0x0212 #define HI847_ANAL_GAIN_MIN 0 #define HI847_ANAL_GAIN_MAX 240 #define HI847_ANAL_GAIN_STEP 1 /* Digital gain controls from sensor */ #define HI847_REG_MWB_GR_GAIN 0x0214 #define HI847_REG_MWB_GB_GAIN 0x0216 #define HI847_REG_MWB_R_GAIN 0x0218 #define HI847_REG_MWB_B_GAIN 0x021A #define HI847_DGTL_GAIN_MIN 1 #define HI847_DGTL_GAIN_MAX 8191 #define HI847_DGTL_GAIN_STEP 1 #define HI847_DGTL_GAIN_DEFAULT 512 /* Test Pattern Control */ #define HI847_REG_ISP 0X0B04 #define HI847_REG_ISP_TPG_EN 0x0001 #define HI847_REG_TEST_PATTERN 0x0C0A /* Flip Mirror Controls from sensor */ #define HI847_REG_MIRROR_FLIP 0x0202 #define HI847_REG_FORMAT_X 0x0F04 #define HI847_REG_FORMAT_Y 0x0F06 enum { HI847_LINK_FREQ_400MHZ_INDEX, HI847_LINK_FREQ_200MHZ_INDEX, }; struct hi847_reg { u16 address; u16 val; }; struct hi847_reg_list { u32 num_of_regs; const struct hi847_reg *regs; }; struct hi847_link_freq_config { const struct hi847_reg_list reg_list; }; struct hi847_mode { /* Frame width in pixels */ u32 width; /* Frame height in pixels */ u32 height; /* Horizontal timining size */ u32 llp; /* Default vertical timining size */ u32 fll_def; /* Min vertical timining size */ u32 fll_min; /* Link frequency needed for this resolution */ u32 link_freq_index; /* Sensor register settings for this resolution */ const struct hi847_reg_list reg_list; }; #define to_hi847(_sd) container_of(_sd, struct hi847, sd) //SENSOR_INITIALIZATION static const struct hi847_reg mipi_data_rate_lane_4[] = { {0x0790, 0x0100}, {0x2000, 0x0000}, {0x2002, 0x0058}, {0x2006, 0x40B2}, {0x2008, 0xB05C}, {0x200A, 0x8446}, {0x200C, 0x40B2}, {0x200E, 0xB082}, {0x2010, 0x8450}, {0x2012, 0x40B2}, {0x2014, 0xB0AE}, {0x2016, 0x84C6}, {0x2018, 0x40B2}, {0x201A, 0xB11A}, {0x201C, 0x84BC}, {0x201E, 0x40B2}, {0x2020, 0xB34A}, {0x2022, 0x84B4}, {0x2024, 0x40B2}, {0x2026, 0xB386}, {0x2028, 0x84B0}, {0x202A, 0x40B2}, {0x202C, 0xB3B4}, {0x202E, 0x84B8}, {0x2030, 0x40B2}, {0x2032, 0xB0F4}, {0x2034, 0x8470}, {0x2036, 0x40B2}, {0x2038, 0xB3EA}, {0x203A, 0x847C}, {0x203C, 0x40B2}, {0x203E, 0xB658}, {0x2040, 0x8478}, {0x2042, 0x40B2}, {0x2044, 0xB67E}, {0x2046, 0x847E}, {0x2048, 0x40B2}, {0x204A, 0xB78E}, {0x204C, 0x843A}, {0x204E, 0x40B2}, {0x2050, 0xB980}, {0x2052, 0x845C}, {0x2054, 0x40B2}, {0x2056, 0xB9B0}, {0x2058, 0x845E}, {0x205A, 0x4130}, {0x205C, 0x1292}, {0x205E, 0xD016}, {0x2060, 0xB3D2}, {0x2062, 0x0B00}, {0x2064, 0x2002}, {0x2066, 0xD2E2}, {0x2068, 0x0381}, {0x206A, 0x93C2}, {0x206C, 0x0263}, {0x206E, 0x2001}, {0x2070, 0x4130}, {0x2072, 0x422D}, {0x2074, 0x403E}, {0x2076, 0x888E}, {0x2078, 0x403F}, {0x207A, 0x192A}, {0x207C, 0x1292}, {0x207E, 0x843E}, {0x2080, 0x3FF7}, {0x2082, 0x422D}, {0x2084, 0x403E}, {0x2086, 0x192A}, {0x2088, 0x403F}, {0x208A, 0x888E}, {0x208C, 0x1292}, {0x208E, 0x843E}, {0x2090, 0xB3D2}, {0x2092, 0x0267}, {0x2094, 0x2403}, {0x2096, 0xD0F2}, {0x2098, 0x0040}, {0x209A, 0x0381}, {0x209C, 0x90F2}, {0x209E, 0x0010}, {0x20A0, 0x0260}, {0x20A2, 0x2002}, {0x20A4, 0x1292}, {0x20A6, 0x84BC}, {0x20A8, 0x1292}, {0x20AA, 0xD020}, {0x20AC, 0x4130}, {0x20AE, 0x1292}, {0x20B0, 0x8470}, {0x20B2, 0x1292}, {0x20B4, 0x8452}, {0x20B6, 0x0900}, {0x20B8, 0x7118}, {0x20BA, 0x1292}, {0x20BC, 0x848E}, {0x20BE, 0x0900}, {0x20C0, 0x7112}, {0x20C2, 0x0800}, {0x20C4, 0x7A20}, {0x20C6, 0x4292}, {0x20C8, 0x87DE}, {0x20CA, 0x7334}, {0x20CC, 0x0F00}, {0x20CE, 0x7304}, {0x20D0, 0x421F}, {0x20D2, 0x8718}, {0x20D4, 0x1292}, {0x20D6, 0x846E}, {0x20D8, 0x1292}, {0x20DA, 0x8488}, {0x20DC, 0x0B00}, {0x20DE, 0x7114}, {0x20E0, 0x0002}, {0x20E2, 0x1292}, {0x20E4, 0x848C}, {0x20E6, 0x1292}, {0x20E8, 0x8454}, {0x20EA, 0x43C2}, {0x20EC, 0x86EE}, {0x20EE, 0x1292}, {0x20F0, 0x8444}, {0x20F2, 0x4130}, {0x20F4, 0x4392}, {0x20F6, 0x7360}, {0x20F8, 0xB3D2}, {0x20FA, 0x0B00}, {0x20FC, 0x2402}, {0x20FE, 0xC2E2}, {0x2100, 0x0381}, {0x2102, 0x0900}, {0x2104, 0x732C}, {0x2106, 0x4382}, {0x2108, 0x7360}, {0x210A, 0x422D}, {0x210C, 0x403E}, {0x210E, 0x87F0}, {0x2110, 0x403F}, {0x2112, 0x87E8}, {0x2114, 0x1292}, {0x2116, 0x843E}, {0x2118, 0x4130}, {0x211A, 0x120B}, {0x211C, 0x120A}, {0x211E, 0x4392}, {0x2120, 0x87FA}, {0x2122, 0x4392}, {0x2124, 0x760E}, {0x2126, 0x0900}, {0x2128, 0x760C}, {0x212A, 0x421B}, {0x212C, 0x760A}, {0x212E, 0x903B}, {0x2130, 0x0201}, {0x2132, 0x2408}, {0x2134, 0x903B}, {0x2136, 0x0102}, {0x2138, 0x2405}, {0x213A, 0x4292}, {0x213C, 0x030A}, {0x213E, 0x87F8}, {0x2140, 0x1292}, {0x2142, 0x849A}, {0x2144, 0x903B}, {0x2146, 0x0020}, {0x2148, 0x2010}, {0x214A, 0x403B}, {0x214C, 0x8498}, {0x214E, 0x422F}, {0x2150, 0x12AB}, {0x2152, 0x403F}, {0x2154, 0x0028}, {0x2156, 0x12AB}, {0x2158, 0x403B}, {0x215A, 0x84C4}, {0x215C, 0x407F}, {0x215E, 0xFFAA}, {0x2160, 0x12AB}, {0x2162, 0x407F}, {0x2164, 0x0055}, {0x2166, 0x12AB}, {0x2168, 0x3FDC}, {0x216A, 0x903B}, {0x216C, 0x0021}, {0x216E, 0x2890}, {0x2170, 0x903B}, {0x2172, 0x0100}, {0x2174, 0x200D}, {0x2176, 0x403F}, {0x2178, 0x0028}, {0x217A, 0x1292}, {0x217C, 0x8498}, {0x217E, 0x425F}, {0x2180, 0x0306}, {0x2182, 0x1292}, {0x2184, 0x84C4}, {0x2186, 0x4FC2}, {0x2188, 0x0318}, {0x218A, 0x0261}, {0x218C, 0x0000}, {0x218E, 0x3FC9}, {0x2190, 0x903B}, {0x2192, 0x0101}, {0x2194, 0x2858}, {0x2196, 0x903B}, {0x2198, 0x0200}, {0x219A, 0x2450}, {0x219C, 0x903B}, {0x219E, 0x0201}, {0x21A0, 0x2C47}, {0x21A2, 0x903B}, {0x21A4, 0x0102}, {0x21A6, 0x2041}, {0x21A8, 0x93E2}, {0x21AA, 0x0262}, {0x21AC, 0x240A}, {0x21AE, 0x425F}, {0x21B0, 0x0306}, {0x21B2, 0x1292}, {0x21B4, 0x84C4}, {0x21B6, 0x4F4E}, {0x21B8, 0x4EC2}, {0x21BA, 0x0318}, {0x21BC, 0x0260}, {0x21BE, 0x0000}, {0x21C0, 0x3FB0}, {0x21C2, 0x403A}, {0x21C4, 0x8030}, {0x21C6, 0x4382}, {0x21C8, 0x0326}, {0x21CA, 0x4382}, {0x21CC, 0x0328}, {0x21CE, 0x421B}, {0x21D0, 0x030C}, {0x21D2, 0x930B}, {0x21D4, 0x2420}, {0x21D6, 0x4A5F}, {0x21D8, 0x0001}, {0x21DA, 0x1292}, {0x21DC, 0x84C4}, {0x21DE, 0x4F4E}, {0x21E0, 0x4A5F}, {0x21E2, 0x0001}, {0x21E4, 0x9F0E}, {0x21E6, 0x2402}, {0x21E8, 0x5392}, {0x21EA, 0x0326}, {0x21EC, 0x4ECA}, {0x21EE, 0x0001}, {0x21F0, 0x533B}, {0x21F2, 0x2411}, {0x21F4, 0x4A6F}, {0x21F6, 0x1292}, {0x21F8, 0x84C4}, {0x21FA, 0x4F4E}, {0x21FC, 0x4A6F}, {0x21FE, 0x9F0E}, {0x2200, 0x2402}, {0x2202, 0x5392}, {0x2204, 0x0326}, {0x2206, 0x4ECA}, {0x2208, 0x0000}, {0x220A, 0x533B}, {0x220C, 0x532A}, {0x220E, 0x0260}, {0x2210, 0x0000}, {0x2212, 0x930B}, {0x2214, 0x23E0}, {0x2216, 0x40B2}, {0x2218, 0xAA55}, {0x221A, 0x0328}, {0x221C, 0xB0F2}, {0x221E, 0x0040}, {0x2220, 0x0381}, {0x2222, 0x277F}, {0x2224, 0xD3D2}, {0x2226, 0x0267}, {0x2228, 0x3F7C}, {0x222A, 0x0261}, {0x222C, 0x0000}, {0x222E, 0x3F79}, {0x2230, 0x903B}, {0x2232, 0x0201}, {0x2234, 0x23FA}, {0x2236, 0x1292}, {0x2238, 0x84C0}, {0x223A, 0x3F73}, {0x223C, 0x1292}, {0x223E, 0x84C0}, {0x2240, 0x0261}, {0x2242, 0x0000}, {0x2244, 0x3F6E}, {0x2246, 0x903B}, {0x2248, 0x0040}, {0x224A, 0x2018}, {0x224C, 0x422F}, {0x224E, 0x1292}, {0x2250, 0x8498}, {0x2252, 0x12B0}, {0x2254, 0xF0EA}, {0x2256, 0x907F}, {0x2258, 0xFFAA}, {0x225A, 0x240D}, {0x225C, 0x5392}, {0x225E, 0x0312}, {0x2260, 0x12B0}, {0x2262, 0xF0EA}, {0x2264, 0x907F}, {0x2266, 0x0055}, {0x2268, 0x2403}, {0x226A, 0x5392}, {0x226C, 0x0312}, {0x226E, 0x3F59}, {0x2270, 0x5392}, {0x2272, 0x0310}, {0x2274, 0x3F56}, {0x2276, 0x5392}, {0x2278, 0x0310}, {0x227A, 0x3FF2}, {0x227C, 0x903B}, {0x227E, 0x0080}, {0x2280, 0x23D4}, {0x2282, 0x4382}, {0x2284, 0x0312}, {0x2286, 0x4382}, {0x2288, 0x0310}, {0x228A, 0x0261}, {0x228C, 0x0000}, {0x228E, 0x3F49}, {0x2290, 0x932B}, {0x2292, 0x2005}, {0x2294, 0x403F}, {0x2296, 0x0028}, {0x2298, 0x1292}, {0x229A, 0x8498}, {0x229C, 0x3F42}, {0x229E, 0x903B}, {0x22A0, 0x0003}, {0x22A2, 0x284B}, {0x22A4, 0x923B}, {0x22A6, 0x2015}, {0x22A8, 0x403F}, {0x22AA, 0x0023}, {0x22AC, 0x1292}, {0x22AE, 0x8498}, {0x22B0, 0x421B}, {0x22B2, 0x87F8}, {0x22B4, 0x421F}, {0x22B6, 0x030C}, {0x22B8, 0x9F0B}, {0x22BA, 0x2F33}, {0x22BC, 0x1292}, {0x22BE, 0x84BA}, {0x22C0, 0x930F}, {0x22C2, 0x2004}, {0x22C4, 0x5392}, {0x22C6, 0x0312}, {0x22C8, 0x531B}, {0x22CA, 0x3FF4}, {0x22CC, 0x5392}, {0x22CE, 0x0310}, {0x22D0, 0x3FFB}, {0x22D2, 0x903B}, {0x22D4, 0x0009}, {0x22D6, 0x2818}, {0x22D8, 0x903B}, {0x22DA, 0x0010}, {0x22DC, 0x23A6}, {0x22DE, 0x403F}, {0x22E0, 0x0027}, {0x22E2, 0x1292}, {0x22E4, 0x8498}, {0x22E6, 0x421B}, {0x22E8, 0x87F8}, {0x22EA, 0x421F}, {0x22EC, 0x030C}, {0x22EE, 0x9F0B}, {0x22F0, 0x2F18}, {0x22F2, 0x1292}, {0x22F4, 0x84BA}, {0x22F6, 0x930F}, {0x22F8, 0x2004}, {0x22FA, 0x5392}, {0x22FC, 0x0312}, {0x22FE, 0x531B}, {0x2300, 0x3FF4}, {0x2302, 0x5392}, {0x2304, 0x0310}, {0x2306, 0x3FFB}, {0x2308, 0x922B}, {0x230A, 0x238F}, {0x230C, 0x421B}, {0x230E, 0x87F8}, {0x2310, 0x421F}, {0x2312, 0x030C}, {0x2314, 0x9F0B}, {0x2316, 0x2C0B}, {0x2318, 0x1292}, {0x231A, 0x84C2}, {0x231C, 0x934F}, {0x231E, 0x240A}, {0x2320, 0x5392}, {0x2322, 0x0312}, {0x2324, 0x531B}, {0x2326, 0x421F}, {0x2328, 0x030C}, {0x232A, 0x9F0B}, {0x232C, 0x2BF5}, {0x232E, 0x0261}, {0x2330, 0x0000}, {0x2332, 0x3EF7}, {0x2334, 0x5392}, {0x2336, 0x0310}, {0x2338, 0x3FF5}, {0x233A, 0x930B}, {0x233C, 0x277F}, {0x233E, 0x931B}, {0x2340, 0x277A}, {0x2342, 0x3F73}, {0x2344, 0x413A}, {0x2346, 0x413B}, {0x2348, 0x4130}, {0x234A, 0x4F0C}, {0x234C, 0x403F}, {0x234E, 0x0267}, {0x2350, 0xF0FF}, {0x2352, 0xFFDF}, {0x2354, 0x0000}, {0x2356, 0xF0FF}, {0x2358, 0xFFEF}, {0x235A, 0x0000}, {0x235C, 0x421D}, {0x235E, 0x84B0}, {0x2360, 0x403E}, {0x2362, 0x06F9}, {0x2364, 0x4C0F}, {0x2366, 0x1292}, {0x2368, 0x84AC}, {0x236A, 0x4F4E}, {0x236C, 0xB31E}, {0x236E, 0x2403}, {0x2370, 0xD0F2}, {0x2372, 0x0020}, {0x2374, 0x0267}, {0x2376, 0xB32E}, {0x2378, 0x2403}, {0x237A, 0xD0F2}, {0x237C, 0x0010}, {0x237E, 0x0267}, {0x2380, 0xC3E2}, {0x2382, 0x0267}, {0x2384, 0x4130}, {0x2386, 0x120B}, {0x2388, 0x120A}, {0x238A, 0x403A}, {0x238C, 0x1140}, {0x238E, 0x1292}, {0x2390, 0xD080}, {0x2392, 0x430B}, {0x2394, 0x4A0F}, {0x2396, 0x532A}, {0x2398, 0x1292}, {0x239A, 0x84A4}, {0x239C, 0x4F0E}, {0x239E, 0x430F}, {0x23A0, 0x5E82}, {0x23A2, 0x87FC}, {0x23A4, 0x6F82}, {0x23A6, 0x87FE}, {0x23A8, 0x531B}, {0x23AA, 0x923B}, {0x23AC, 0x2BF3}, {0x23AE, 0x413A}, {0x23B0, 0x413B}, {0x23B2, 0x4130}, {0x23B4, 0xF0F2}, {0x23B6, 0x007F}, {0x23B8, 0x0267}, {0x23BA, 0x421D}, {0x23BC, 0x84B6}, {0x23BE, 0x403E}, {0x23C0, 0x01F9}, {0x23C2, 0x1292}, {0x23C4, 0x84AC}, {0x23C6, 0x4F4E}, {0x23C8, 0xF35F}, {0x23CA, 0x2403}, {0x23CC, 0xD0F2}, {0x23CE, 0xFF80}, {0x23D0, 0x0267}, {0x23D2, 0xB36E}, {0x23D4, 0x2404}, {0x23D6, 0xD0F2}, {0x23D8, 0x0040}, {0x23DA, 0x0267}, {0x23DC, 0x3C03}, {0x23DE, 0xF0F2}, {0x23E0, 0xFFBF}, {0x23E2, 0x0267}, {0x23E4, 0xC2E2}, {0x23E6, 0x0267}, {0x23E8, 0x4130}, {0x23EA, 0x120B}, {0x23EC, 0x120A}, {0x23EE, 0x8231}, {0x23F0, 0x430B}, {0x23F2, 0x93C2}, {0x23F4, 0x0C0A}, {0x23F6, 0x2404}, {0x23F8, 0xB3D2}, {0x23FA, 0x0B05}, {0x23FC, 0x2401}, {0x23FE, 0x431B}, {0x2400, 0x422D}, {0x2402, 0x403E}, {0x2404, 0x192A}, {0x2406, 0x403F}, {0x2408, 0x888E}, {0x240A, 0x1292}, {0x240C, 0x843E}, {0x240E, 0x930B}, {0x2410, 0x20F4}, {0x2412, 0x93E2}, {0x2414, 0x0241}, {0x2416, 0x24EB}, {0x2418, 0x403A}, {0x241A, 0x0292}, {0x241C, 0x4AA2}, {0x241E, 0x0A00}, {0x2420, 0xB2E2}, {0x2422, 0x0361}, {0x2424, 0x2405}, {0x2426, 0x4A2F}, {0x2428, 0x1292}, {0x242A, 0x8474}, {0x242C, 0x4F82}, {0x242E, 0x0A1C}, {0x2430, 0x93C2}, {0x2432, 0x0360}, {0x2434, 0x34CD}, {0x2436, 0x430C}, {0x2438, 0x4C0F}, {0x243A, 0x5F0F}, {0x243C, 0x4F0D}, {0x243E, 0x510D}, {0x2440, 0x4F0E}, {0x2442, 0x5A0E}, {0x2444, 0x4E1E}, {0x2446, 0x0002}, {0x2448, 0x4F1F}, {0x244A, 0x192A}, {0x244C, 0x1202}, {0x244E, 0xC232}, {0x2450, 0x4303}, {0x2452, 0x4E82}, {0x2454, 0x0130}, {0x2456, 0x4F82}, {0x2458, 0x0138}, {0x245A, 0x421E}, {0x245C, 0x013A}, {0x245E, 0x421F}, {0x2460, 0x013C}, {0x2462, 0x4132}, {0x2464, 0x108E}, {0x2466, 0x108F}, {0x2468, 0xEF4E}, {0x246A, 0xEF0E}, {0x246C, 0xF37F}, {0x246E, 0xC312}, {0x2470, 0x100F}, {0x2472, 0x100E}, {0x2474, 0x4E8D}, {0x2476, 0x0000}, {0x2478, 0x531C}, {0x247A, 0x922C}, {0x247C, 0x2BDD}, {0x247E, 0xB3D2}, {0x2480, 0x1921}, {0x2482, 0x2403}, {0x2484, 0x410F}, {0x2486, 0x1292}, {0x2488, 0x847E}, {0x248A, 0x403B}, {0x248C, 0x843E}, {0x248E, 0x422D}, {0x2490, 0x410E}, {0x2492, 0x403F}, {0x2494, 0x1908}, {0x2496, 0x12AB}, {0x2498, 0x403D}, {0x249A, 0x0005}, {0x249C, 0x403E}, {0x249E, 0x0292}, {0x24A0, 0x403F}, {0x24A2, 0x86E4}, {0x24A4, 0x12AB}, {0x24A6, 0x421F}, {0x24A8, 0x060E}, {0x24AA, 0x9F82}, {0x24AC, 0x8720}, {0x24AE, 0x288D}, {0x24B0, 0x9382}, {0x24B2, 0x060E}, {0x24B4, 0x248A}, {0x24B6, 0x90BA}, {0x24B8, 0x0010}, {0x24BA, 0x0000}, {0x24BC, 0x2C0B}, {0x24BE, 0x93C2}, {0x24C0, 0x86EE}, {0x24C2, 0x2008}, {0x24C4, 0x403F}, {0x24C6, 0x06A7}, {0x24C8, 0xD0FF}, {0x24CA, 0x0007}, {0x24CC, 0x0000}, {0x24CE, 0xF0FF}, {0x24D0, 0xFFF8}, {0x24D2, 0x0000}, {0x24D4, 0x4392}, {0x24D6, 0x8720}, {0x24D8, 0x403F}, {0x24DA, 0x06A7}, {0x24DC, 0xD2EF}, {0x24DE, 0x0000}, {0x24E0, 0xC2EF}, {0x24E2, 0x0000}, {0x24E4, 0x93C2}, {0x24E6, 0x87D3}, {0x24E8, 0x2068}, {0x24EA, 0xB0F2}, {0x24EC, 0x0040}, {0x24EE, 0x0B05}, {0x24F0, 0x2461}, {0x24F2, 0xD3D2}, {0x24F4, 0x0410}, {0x24F6, 0xB3E2}, {0x24F8, 0x0381}, {0x24FA, 0x2089}, {0x24FC, 0x90B2}, {0x24FE, 0x0030}, {0x2500, 0x0A00}, {0x2502, 0x2C52}, {0x2504, 0x93C2}, {0x2506, 0x86EE}, {0x2508, 0x204F}, {0x250A, 0x430E}, {0x250C, 0x430C}, {0x250E, 0x4C0F}, {0x2510, 0x5F0F}, {0x2512, 0x5F0F}, {0x2514, 0x5F0F}, {0x2516, 0x4F1F}, {0x2518, 0x8668}, {0x251A, 0xF03F}, {0x251C, 0x07FF}, {0x251E, 0x903F}, {0x2520, 0x0400}, {0x2522, 0x343E}, {0x2524, 0x5F0E}, {0x2526, 0x531C}, {0x2528, 0x923C}, {0x252A, 0x2BF1}, {0x252C, 0x4E0F}, {0x252E, 0x930E}, {0x2530, 0x3834}, {0x2532, 0x110F}, {0x2534, 0x110F}, {0x2536, 0x110F}, {0x2538, 0x9382}, {0x253A, 0x86EE}, {0x253C, 0x2023}, {0x253E, 0x5F82}, {0x2540, 0x87D6}, {0x2542, 0x403B}, {0x2544, 0x87D6}, {0x2546, 0x4B2F}, {0x2548, 0x12B0}, {0x254A, 0xB624}, {0x254C, 0x4F8B}, {0x254E, 0x0000}, {0x2550, 0x430C}, {0x2552, 0x4C0D}, {0x2554, 0x5D0D}, {0x2556, 0x5D0D}, {0x2558, 0x5D0D}, {0x255A, 0x403A}, {0x255C, 0x87D8}, {0x255E, 0x421B}, {0x2560, 0x87D6}, {0x2562, 0x4B0F}, {0x2564, 0x8A2F}, {0x2566, 0x4F0E}, {0x2568, 0x4E0F}, {0x256A, 0x5F0F}, {0x256C, 0x7F0F}, {0x256E, 0xE33F}, {0x2570, 0x8E8D}, {0x2572, 0x8668}, {0x2574, 0x7F8D}, {0x2576, 0x866A}, {0x2578, 0x531C}, {0x257A, 0x923C}, {0x257C, 0x2BEA}, {0x257E, 0x4B8A}, {0x2580, 0x0000}, {0x2582, 0x3C45}, {0x2584, 0x9382}, {0x2586, 0x86F0}, {0x2588, 0x2005}, {0x258A, 0x4382}, {0x258C, 0x87D6}, {0x258E, 0x4382}, {0x2590, 0x87D8}, {0x2592, 0x3FD7}, {0x2594, 0x4F82}, {0x2596, 0x87D6}, {0x2598, 0x3FD4}, {0x259A, 0x503F}, {0x259C, 0x0007}, {0x259E, 0x3FC9}, {0x25A0, 0x5F0E}, {0x25A2, 0x503E}, {0x25A4, 0xF800}, {0x25A6, 0x3FBF}, {0x25A8, 0x430F}, {0x25AA, 0x12B0}, {0x25AC, 0xB624}, {0x25AE, 0x4382}, {0x25B0, 0x87D6}, {0x25B2, 0x3C2D}, {0x25B4, 0xC3D2}, {0x25B6, 0x0410}, {0x25B8, 0x3F9E}, {0x25BA, 0x430D}, {0x25BC, 0x403E}, {0x25BE, 0x0050}, {0x25C0, 0x403F}, {0x25C2, 0x85C8}, {0x25C4, 0x1292}, {0x25C6, 0x844E}, {0x25C8, 0x3F90}, {0x25CA, 0x5392}, {0x25CC, 0x8720}, {0x25CE, 0x3F84}, {0x25D0, 0x403B}, {0x25D2, 0x843E}, {0x25D4, 0x4A0F}, {0x25D6, 0x532F}, {0x25D8, 0x422D}, {0x25DA, 0x4F0E}, {0x25DC, 0x403F}, {0x25DE, 0x0E08}, {0x25E0, 0x12AB}, {0x25E2, 0x422D}, {0x25E4, 0x403E}, {0x25E6, 0x192A}, {0x25E8, 0x410F}, {0x25EA, 0x12AB}, {0x25EC, 0x3F48}, {0x25EE, 0x93C2}, {0x25F0, 0x86EE}, {0x25F2, 0x2312}, {0x25F4, 0x403A}, {0x25F6, 0x86E4}, {0x25F8, 0x3F11}, {0x25FA, 0x403D}, {0x25FC, 0x0200}, {0x25FE, 0x422E}, {0x2600, 0x403F}, {0x2602, 0x192A}, {0x2604, 0x1292}, {0x2606, 0x844E}, {0x2608, 0xC3D2}, {0x260A, 0x1921}, {0x260C, 0x3F02}, {0x260E, 0x422D}, {0x2610, 0x403E}, {0x2612, 0x888E}, {0x2614, 0x403F}, {0x2616, 0x192A}, {0x2618, 0x1292}, {0x261A, 0x843E}, {0x261C, 0x5231}, {0x261E, 0x413A}, {0x2620, 0x413B}, {0x2622, 0x4130}, {0x2624, 0x4382}, {0x2626, 0x052C}, {0x2628, 0x4F0D}, {0x262A, 0x930D}, {0x262C, 0x3402}, {0x262E, 0xE33D}, {0x2630, 0x531D}, {0x2632, 0xF03D}, {0x2634, 0x07F0}, {0x2636, 0x4D0E}, {0x2638, 0xC312}, {0x263A, 0x100E}, {0x263C, 0x110E}, {0x263E, 0x110E}, {0x2640, 0x110E}, {0x2642, 0x930F}, {0x2644, 0x3803}, {0x2646, 0x4EC2}, {0x2648, 0x052C}, {0x264A, 0x3C04}, {0x264C, 0x4EC2}, {0x264E, 0x052D}, {0x2650, 0xE33D}, {0x2652, 0x531D}, {0x2654, 0x4D0F}, {0x2656, 0x4130}, {0x2658, 0x1292}, {0x265A, 0xD048}, {0x265C, 0x93C2}, {0x265E, 0x86EE}, {0x2660, 0x200D}, {0x2662, 0xB0F2}, {0x2664, 0x0020}, {0x2666, 0x0381}, {0x2668, 0x2407}, {0x266A, 0x9292}, {0x266C, 0x8722}, {0x266E, 0x0384}, {0x2670, 0x2C03}, {0x2672, 0xD3D2}, {0x2674, 0x0649}, {0x2676, 0x4130}, {0x2678, 0xC3D2}, {0x267A, 0x0649}, {0x267C, 0x4130}, {0x267E, 0x120B}, {0x2680, 0x120A}, {0x2682, 0x1209}, {0x2684, 0x1208}, {0x2686, 0x1207}, {0x2688, 0x1206}, {0x268A, 0x1205}, {0x268C, 0x1204}, {0x268E, 0x8231}, {0x2690, 0x4F81}, {0x2692, 0x0000}, {0x2694, 0x4381}, {0x2696, 0x0002}, {0x2698, 0x4304}, {0x269A, 0x411C}, {0x269C, 0x0002}, {0x269E, 0x5C0C}, {0x26A0, 0x4C0F}, {0x26A2, 0x5F0F}, {0x26A4, 0x5F0F}, {0x26A6, 0x5F0F}, {0x26A8, 0x5F0F}, {0x26AA, 0x5F0F}, {0x26AC, 0x503F}, {0x26AE, 0x1980}, {0x26B0, 0x440D}, {0x26B2, 0x5D0D}, {0x26B4, 0x4D0E}, {0x26B6, 0x5F0E}, {0x26B8, 0x4E2E}, {0x26BA, 0x4D05}, {0x26BC, 0x5505}, {0x26BE, 0x5F05}, {0x26C0, 0x4516}, {0x26C2, 0x0008}, {0x26C4, 0x4517}, {0x26C6, 0x000A}, {0x26C8, 0x460A}, {0x26CA, 0x470B}, {0x26CC, 0xF30A}, {0x26CE, 0xF32B}, {0x26D0, 0x4A81}, {0x26D2, 0x0004}, {0x26D4, 0x4B81}, {0x26D6, 0x0006}, {0x26D8, 0xB03E}, {0x26DA, 0x2000}, {0x26DC, 0x2404}, {0x26DE, 0xF03E}, {0x26E0, 0x1FFF}, {0x26E2, 0xE33E}, {0x26E4, 0x531E}, {0x26E6, 0xF317}, {0x26E8, 0x503E}, {0x26EA, 0x2000}, {0x26EC, 0x4E0F}, {0x26EE, 0x5F0F}, {0x26F0, 0x7F0F}, {0x26F2, 0xE33F}, {0x26F4, 0x512C}, {0x26F6, 0x4C28}, {0x26F8, 0x4309}, {0x26FA, 0x4E0A}, {0x26FC, 0x4F0B}, {0x26FE, 0x480C}, {0x2700, 0x490D}, {0x2702, 0x1202}, {0x2704, 0xC232}, {0x2706, 0x12B0}, {0x2708, 0xFFC0}, {0x270A, 0x4132}, {0x270C, 0x108E}, {0x270E, 0x108F}, {0x2710, 0xEF4E}, {0x2712, 0xEF0E}, {0x2714, 0xF37F}, {0x2716, 0xC312}, {0x2718, 0x100F}, {0x271A, 0x100E}, {0x271C, 0x4E85}, {0x271E, 0x0018}, {0x2720, 0x4F85}, {0x2722, 0x001A}, {0x2724, 0x480A}, {0x2726, 0x490B}, {0x2728, 0x460C}, {0x272A, 0x470D}, {0x272C, 0x1202}, {0x272E, 0xC232}, {0x2730, 0x12B0}, {0x2732, 0xFFC0}, {0x2734, 0x4132}, {0x2736, 0x4E0C}, {0x2738, 0x4F0D}, {0x273A, 0x108C}, {0x273C, 0x108D}, {0x273E, 0xED4C}, {0x2740, 0xED0C}, {0x2742, 0xF37D}, {0x2744, 0xC312}, {0x2746, 0x100D}, {0x2748, 0x100C}, {0x274A, 0x411E}, {0x274C, 0x0004}, {0x274E, 0x411F}, {0x2750, 0x0006}, {0x2752, 0x5E0E}, {0x2754, 0x6F0F}, {0x2756, 0x5E0E}, {0x2758, 0x6F0F}, {0x275A, 0x5E0E}, {0x275C, 0x6F0F}, {0x275E, 0xDE0C}, {0x2760, 0xDF0D}, {0x2762, 0x4C85}, {0x2764, 0x002C}, {0x2766, 0x4D85}, {0x2768, 0x002E}, {0x276A, 0x5314}, {0x276C, 0x9224}, {0x276E, 0x2B95}, {0x2770, 0x5391}, {0x2772, 0x0002}, {0x2774, 0x92A1}, {0x2776, 0x0002}, {0x2778, 0x2B8F}, {0x277A, 0x5231}, {0x277C, 0x4134}, {0x277E, 0x4135}, {0x2780, 0x4136}, {0x2782, 0x4137}, {0x2784, 0x4138}, {0x2786, 0x4139}, {0x2788, 0x413A}, {0x278A, 0x413B}, {0x278C, 0x4130}, {0x278E, 0x120B}, {0x2790, 0x120A}, {0x2792, 0x1209}, {0x2794, 0x8031}, {0x2796, 0x000C}, {0x2798, 0x425F}, {0x279A, 0x0205}, {0x279C, 0xC312}, {0x279E, 0x104F}, {0x27A0, 0x114F}, {0x27A2, 0x114F}, {0x27A4, 0x114F}, {0x27A6, 0x114F}, {0x27A8, 0x114F}, {0x27AA, 0xF37F}, {0x27AC, 0x4F0B}, {0x27AE, 0xF31B}, {0x27B0, 0x5B0B}, {0x27B2, 0x5B0B}, {0x27B4, 0x5B0B}, {0x27B6, 0x503B}, {0x27B8, 0xD194}, {0x27BA, 0x4219}, {0x27BC, 0x0508}, {0x27BE, 0xF039}, {0x27C0, 0x2000}, {0x27C2, 0x4F0A}, {0x27C4, 0xC312}, {0x27C6, 0x100A}, {0x27C8, 0xE31A}, {0x27CA, 0x421F}, {0x27CC, 0x87DE}, {0x27CE, 0x503F}, {0x27D0, 0xFF60}, {0x27D2, 0x903F}, {0x27D4, 0x00C8}, {0x27D6, 0x2C02}, {0x27D8, 0x403F}, {0x27DA, 0x00C8}, {0x27DC, 0x4F82}, {0x27DE, 0x7322}, {0x27E0, 0xB3D2}, {0x27E2, 0x0381}, {0x27E4, 0x2009}, {0x27E6, 0x421F}, {0x27E8, 0x86F0}, {0x27EA, 0xD21F}, {0x27EC, 0x86EE}, {0x27EE, 0x930F}, {0x27F0, 0x24B9}, {0x27F2, 0x40F2}, {0x27F4, 0xFF80}, {0x27F6, 0x0619}, {0x27F8, 0x1292}, {0x27FA, 0xD00A}, {0x27FC, 0xB3D2}, {0x27FE, 0x0385}, {0x2800, 0x2405}, {0x2802, 0x421F}, {0x2804, 0x880A}, {0x2806, 0x4F92}, {0x2808, 0x0002}, {0x280A, 0x8714}, {0x280C, 0x430D}, {0x280E, 0x93C2}, {0x2810, 0x87D0}, {0x2812, 0x2003}, {0x2814, 0xB2F2}, {0x2816, 0x0360}, {0x2818, 0x2001}, {0x281A, 0x431D}, {0x281C, 0x425F}, {0x281E, 0x87D3}, {0x2820, 0xD25F}, {0x2822, 0x87D2}, {0x2824, 0xF37F}, {0x2826, 0x5F0F}, {0x2828, 0x425E}, {0x282A, 0x87CD}, {0x282C, 0xDE0F}, {0x282E, 0x5F0F}, {0x2830, 0x5B0F}, {0x2832, 0x4FA2}, {0x2834, 0x0402}, {0x2836, 0x930D}, {0x2838, 0x2007}, {0x283A, 0x930A}, {0x283C, 0x248E}, {0x283E, 0x4F5F}, {0x2840, 0x0001}, {0x2842, 0xF37F}, {0x2844, 0x4FC2}, {0x2846, 0x0403}, {0x2848, 0x93C2}, {0x284A, 0x87CD}, {0x284C, 0x2483}, {0x284E, 0xC2F2}, {0x2850, 0x0400}, {0x2852, 0xB2E2}, {0x2854, 0x0265}, {0x2856, 0x2407}, {0x2858, 0x421F}, {0x285A, 0x0508}, {0x285C, 0xF03F}, {0x285E, 0xFFDF}, {0x2860, 0xD90F}, {0x2862, 0x4F82}, {0x2864, 0x0508}, {0x2866, 0xB3D2}, {0x2868, 0x0383}, {0x286A, 0x2484}, {0x286C, 0x403F}, {0x286E, 0x0508}, {0x2870, 0x4FB1}, {0x2872, 0x0000}, {0x2874, 0x4FB1}, {0x2876, 0x0002}, {0x2878, 0x4FB1}, {0x287A, 0x0004}, {0x287C, 0x403F}, {0x287E, 0x0500}, {0x2880, 0x4FB1}, {0x2882, 0x0006}, {0x2884, 0x4FB1}, {0x2886, 0x0008}, {0x2888, 0x4FB1}, {0x288A, 0x000A}, {0x288C, 0xB3E2}, {0x288E, 0x0383}, {0x2890, 0x2412}, {0x2892, 0xC2E1}, {0x2894, 0x0002}, {0x2896, 0xB2E2}, {0x2898, 0x0383}, {0x289A, 0x434F}, {0x289C, 0x634F}, {0x289E, 0xF37F}, {0x28A0, 0x4F4E}, {0x28A2, 0x114E}, {0x28A4, 0x434E}, {0x28A6, 0x104E}, {0x28A8, 0x415F}, {0x28AA, 0x0007}, {0x28AC, 0xF07F}, {0x28AE, 0x007F}, {0x28B0, 0xDE4F}, {0x28B2, 0x4FC1}, {0x28B4, 0x0007}, {0x28B6, 0xB2F2}, {0x28B8, 0x0383}, {0x28BA, 0x2415}, {0x28BC, 0xF0F1}, {0x28BE, 0xFFBF}, {0x28C0, 0x0000}, {0x28C2, 0xB0F2}, {0x28C4, 0x0010}, {0x28C6, 0x0383}, {0x28C8, 0x434E}, {0x28CA, 0x634E}, {0x28CC, 0x5E4E}, {0x28CE, 0x5E4E}, {0x28D0, 0x5E4E}, {0x28D2, 0x5E4E}, {0x28D4, 0x5E4E}, {0x28D6, 0x5E4E}, {0x28D8, 0x415F}, {0x28DA, 0x0006}, {0x28DC, 0xF07F}, {0x28DE, 0xFFBF}, {0x28E0, 0xDE4F}, {0x28E2, 0x4FC1}, {0x28E4, 0x0006}, {0x28E6, 0xB0F2}, {0x28E8, 0x0020}, {0x28EA, 0x0383}, {0x28EC, 0x2410}, {0x28EE, 0xF0F1}, {0x28F0, 0xFFDF}, {0x28F2, 0x0002}, {0x28F4, 0xB0F2}, {0x28F6, 0x0040}, {0x28F8, 0x0383}, {0x28FA, 0x434E}, {0x28FC, 0x634E}, {0x28FE, 0x5E4E}, {0x2900, 0x5E4E}, {0x2902, 0x415F}, {0x2904, 0x0008}, {0x2906, 0xC26F}, {0x2908, 0xDE4F}, {0x290A, 0x4FC1}, {0x290C, 0x0008}, {0x290E, 0x93C2}, {0x2910, 0x0383}, {0x2912, 0x3412}, {0x2914, 0xF0F1}, {0x2916, 0xFFDF}, {0x2918, 0x0000}, {0x291A, 0x425E}, {0x291C, 0x0382}, {0x291E, 0xF35E}, {0x2920, 0x5E4E}, {0x2922, 0x5E4E}, {0x2924, 0x5E4E}, {0x2926, 0x5E4E}, {0x2928, 0x5E4E}, {0x292A, 0x415F}, {0x292C, 0x0006}, {0x292E, 0xF07F}, {0x2930, 0xFFDF}, {0x2932, 0xDE4F}, {0x2934, 0x4FC1}, {0x2936, 0x0006}, {0x2938, 0x410F}, {0x293A, 0x4FB2}, {0x293C, 0x0508}, {0x293E, 0x4FB2}, {0x2940, 0x050A}, {0x2942, 0x4FB2}, {0x2944, 0x050C}, {0x2946, 0x4FB2}, {0x2948, 0x0500}, {0x294A, 0x4FB2}, {0x294C, 0x0502}, {0x294E, 0x4FB2}, {0x2950, 0x0504}, {0x2952, 0x3C10}, {0x2954, 0xD2F2}, {0x2956, 0x0400}, {0x2958, 0x3F7C}, {0x295A, 0x4F6F}, {0x295C, 0xF37F}, {0x295E, 0x4FC2}, {0x2960, 0x0402}, {0x2962, 0x3F72}, {0x2964, 0x90F2}, {0x2966, 0x0011}, {0x2968, 0x0619}, {0x296A, 0x2B46}, {0x296C, 0x50F2}, {0x296E, 0xFFF0}, {0x2970, 0x0619}, {0x2972, 0x3F42}, {0x2974, 0x5031}, {0x2976, 0x000C}, {0x2978, 0x4139}, {0x297A, 0x413A}, {0x297C, 0x413B}, {0x297E, 0x4130}, {0x2980, 0x0900}, {0x2982, 0x7312}, {0x2984, 0x421F}, {0x2986, 0x0A08}, {0x2988, 0xF03F}, {0x298A, 0xF7FF}, {0x298C, 0x4F82}, {0x298E, 0x0A88}, {0x2990, 0x0900}, {0x2992, 0x7312}, {0x2994, 0x421F}, {0x2996, 0x0A0E}, {0x2998, 0xF03F}, {0x299A, 0x7FFF}, {0x299C, 0x4F82}, {0x299E, 0x0A8E}, {0x29A0, 0x0900}, {0x29A2, 0x7312}, {0x29A4, 0x421F}, {0x29A6, 0x0A1E}, {0x29A8, 0xC31F}, {0x29AA, 0x4F82}, {0x29AC, 0x0A9E}, {0x29AE, 0x4130}, {0x29B0, 0x4292}, {0x29B2, 0x0A08}, {0x29B4, 0x0A88}, {0x29B6, 0x0900}, {0x29B8, 0x7312}, {0x29BA, 0x4292}, {0x29BC, 0x0A0E}, {0x29BE, 0x0A8E}, {0x29C0, 0x0900}, {0x29C2, 0x7312}, {0x29C4, 0x4292}, {0x29C6, 0x0A1E}, {0x29C8, 0x0A9E}, {0x29CA, 0x4130}, {0x29CC, 0x7400}, {0x29CE, 0x8058}, {0x29D0, 0x1807}, {0x29D2, 0x00E0}, {0x29D4, 0x7002}, {0x29D6, 0x17C7}, {0x29D8, 0x0045}, {0x29DA, 0x0006}, {0x29DC, 0x17CC}, {0x29DE, 0x0015}, {0x29E0, 0x1512}, {0x29E2, 0x216F}, {0x29E4, 0x005B}, {0x29E6, 0x005D}, {0x29E8, 0x00DE}, {0x29EA, 0x00DD}, {0x29EC, 0x5023}, {0x29EE, 0x00DE}, {0x29F0, 0x005B}, {0x29F2, 0x0410}, {0x29F4, 0x0091}, {0x29F6, 0x0015}, {0x29F8, 0x0040}, {0x29FA, 0x7023}, {0x29FC, 0x1653}, {0x29FE, 0x0156}, {0x2A00, 0x0001}, {0x2A02, 0x2081}, {0x2A04, 0x7020}, {0x2A06, 0x2F99}, {0x2A08, 0x005C}, {0x2A0A, 0x0000}, {0x2A0C, 0x5040}, {0x2A0E, 0x0045}, {0x2A10, 0x213A}, {0x2A12, 0x0303}, {0x2A14, 0x0148}, {0x2A16, 0x0049}, {0x2A18, 0x0045}, {0x2A1A, 0x0046}, {0x2A1C, 0x05DD}, {0x2A1E, 0x00DE}, {0x2A20, 0x00DD}, {0x2A22, 0x00DC}, {0x2A24, 0x00DE}, {0x2A26, 0x04D6}, {0x2A28, 0x2014}, {0x2A2A, 0x2081}, {0x2A2C, 0x7087}, {0x2A2E, 0x2F99}, {0x2A30, 0x005C}, {0x2A32, 0x0002}, {0x2A34, 0x5060}, {0x2A36, 0x31C0}, {0x2A38, 0x2122}, {0x2A3A, 0x7800}, {0x2A3C, 0xC08C}, {0x2A3E, 0x0001}, {0x2A40, 0x9038}, {0x2A42, 0x59F7}, {0x2A44, 0x907A}, {0x2A46, 0x03D8}, {0x2A48, 0x8D90}, {0x2A4A, 0x01C0}, {0x2A4C, 0x7400}, {0x2A4E, 0x8058}, {0x2A50, 0x1807}, {0x2A52, 0x00E0}, {0x2A54, 0x7002}, {0x2A56, 0x17C7}, {0x2A58, 0x0045}, {0x2A5A, 0x0006}, {0x2A5C, 0x17CC}, {0x2A5E, 0x0015}, {0x2A60, 0x1512}, {0x2A62, 0x216F}, {0x2A64, 0x005B}, {0x2A66, 0x005D}, {0x2A68, 0x00DE}, {0x2A6A, 0x00DD}, {0x2A6C, 0x5023}, {0x2A6E, 0x00DE}, {0x2A70, 0x005B}, {0x2A72, 0x0410}, {0x2A74, 0x0091}, {0x2A76, 0x0015}, {0x2A78, 0x0040}, {0x2A7A, 0x7023}, {0x2A7C, 0x1653}, {0x2A7E, 0x0156}, {0x2A80, 0x0001}, {0x2A82, 0x2081}, {0x2A84, 0x7020}, {0x2A86, 0x2F99}, {0x2A88, 0x005C}, {0x2A8A, 0x0000}, {0x2A8C, 0x5040}, {0x2A8E, 0x0045}, {0x2A90, 0x213A}, {0x2A92, 0x0303}, {0x2A94, 0x0148}, {0x2A96, 0x0049}, {0x2A98, 0x0045}, {0x2A9A, 0x0046}, {0x2A9C, 0x05DD}, {0x2A9E, 0x00DE}, {0x2AA0, 0x00DD}, {0x2AA2, 0x00DC}, {0x2AA4, 0x00DE}, {0x2AA6, 0x0296}, {0x2AA8, 0x2014}, {0x2AAA, 0x2081}, {0x2AAC, 0x7087}, {0x2AAE, 0x2F99}, {0x2AB0, 0x005C}, {0x2AB2, 0x0002}, {0x2AB4, 0x5060}, {0x2AB6, 0x31C0}, {0x2AB8, 0x2122}, {0x2ABA, 0x7800}, {0x2ABC, 0xC08C}, {0x2ABE, 0x0001}, {0x2AC0, 0x9038}, {0x2AC2, 0x59F7}, {0x2AC4, 0x907A}, {0x2AC6, 0x03D8}, {0x2AC8, 0x8D90}, {0x2ACA, 0x01C0}, {0x2ACC, 0x7400}, {0x2ACE, 0x2002}, {0x2AD0, 0x70DF}, {0x2AD2, 0x2F21}, {0x2AD4, 0x04C1}, {0x2AD6, 0x0D80}, {0x2AD8, 0x7800}, {0x2ADA, 0x0041}, {0x2ADC, 0x7400}, {0x2ADE, 0x2004}, {0x2AE0, 0x70DF}, {0x2AE2, 0x2F21}, {0x2AE4, 0x04C2}, {0x2AE6, 0x0D80}, {0x2AE8, 0x7800}, {0x2AEA, 0x7400}, {0x2AEC, 0x2008}, {0x2AEE, 0x70DF}, {0x2AF0, 0x2F21}, {0x2AF2, 0x04C3}, {0x2AF4, 0x0D80}, {0x2AF6, 0x7800}, {0x2AF8, 0x7400}, {0x2AFA, 0x0004}, {0x2AFC, 0x70DF}, {0x2AFE, 0x2F22}, {0x2B00, 0x7008}, {0x2B02, 0x2F1F}, {0x2B04, 0x7021}, {0x2B06, 0x2F01}, {0x2B08, 0x7800}, {0x2B0A, 0x7400}, {0x2B0C, 0x0002}, {0x2B0E, 0x70DF}, {0x2B10, 0x3F5F}, {0x2B12, 0x703A}, {0x2B14, 0x2F01}, {0x2B16, 0x7800}, {0x2B18, 0x7400}, {0x2B1A, 0x2010}, {0x2B1C, 0x70DF}, {0x2B1E, 0x3F40}, {0x2B20, 0x700A}, {0x2B22, 0x0FC0}, {0x2B24, 0x7800}, {0x2B26, 0x7400}, {0x2B28, 0x2004}, {0x2B2A, 0x70DF}, {0x2B2C, 0x2F21}, {0x2B2E, 0x04C2}, {0x2B30, 0x0D80}, {0x2B32, 0x7800}, {0x2B34, 0x0041}, {0x2B36, 0x7400}, {0x2B38, 0x2002}, {0x2B3A, 0x70DF}, {0x2B3C, 0x2F22}, {0x2B3E, 0x04C1}, {0x2B40, 0x0D80}, {0x2B42, 0x7800}, {0x2B44, 0x7400}, {0x2B46, 0x0001}, {0x2B48, 0x70DF}, {0x2B4A, 0x3F5F}, {0x2B4C, 0x703A}, {0x2B4E, 0x2F01}, {0x2B50, 0x7800}, {0x2B52, 0x7400}, {0x2B54, 0x200A}, {0x2B56, 0x70DF}, {0x2B58, 0x3F40}, {0x2B5A, 0x700A}, {0x2B5C, 0x0FC0}, {0x2B5E, 0x7800}, {0x2B60, 0x7400}, {0x2B62, 0x2015}, {0x2B64, 0x70DF}, {0x2B66, 0x3F5F}, {0x2B68, 0x703A}, {0x2B6A, 0x2F01}, {0x2B6C, 0x7800}, {0x2B6E, 0x7400}, {0x2B70, 0x7800}, {0x2B72, 0x007F}, {0x2B74, 0x0000}, {0x2B76, 0xB9CC}, {0x2B78, 0x0000}, {0x2B7A, 0xB9CC}, {0x2B7C, 0xBA3C}, {0x2B7E, 0x0002}, {0x2B80, 0x0000}, {0x2B82, 0xBA4C}, {0x2B84, 0x0000}, {0x2B86, 0xBA4C}, {0x2B88, 0xBABC}, {0x2B8A, 0x0002}, {0x2B8C, 0x0063}, {0x2B8E, 0xBB26}, {0x2B90, 0x0063}, {0x2B92, 0xBB36}, {0x2B94, 0x0063}, {0x2B96, 0xBAEA}, {0x2B98, 0x0063}, {0x2B9A, 0xBAF8}, {0x2B9C, 0xBADA}, {0x2B9E, 0x0004}, {0x2BA0, 0x0063}, {0x2BA2, 0xBAEA}, {0x2BA4, 0x0063}, {0x2BA6, 0xBB18}, {0x2BA8, 0x0063}, {0x2BAA, 0xBB26}, {0x2BAC, 0x0063}, {0x2BAE, 0xBB44}, {0x2BB0, 0xBADA}, {0x2BB2, 0x0004}, {0x2BB4, 0x0063}, {0x2BB6, 0xBACC}, {0x2BB8, 0x0063}, {0x2BBA, 0xBADC}, {0x2BBC, 0x0063}, {0x2BBE, 0xBAEA}, {0x2BC0, 0x0063}, {0x2BC2, 0xBAF8}, {0x2BC4, 0xBADA}, {0x2BC6, 0x0004}, {0x2BC8, 0x0063}, {0x2BCA, 0xBAEA}, {0x2BCC, 0x0063}, {0x2BCE, 0xBB18}, {0x2BD0, 0x0063}, {0x2BD2, 0xBACC}, {0x2BD4, 0x0063}, {0x2BD6, 0xBB0A}, {0x2BD8, 0xBADA}, {0x2BDA, 0x0004}, {0x2BDC, 0x0063}, {0x2BDE, 0xBACC}, {0x2BE0, 0x0063}, {0x2BE2, 0xBADC}, {0x2BE4, 0x0063}, {0x2BE6, 0xBAEA}, {0x2BE8, 0x0063}, {0x2BEA, 0xBB18}, {0x2BEC, 0xBADA}, {0x2BEE, 0x0004}, {0x2BF0, 0xFFFF}, {0x2BF2, 0xBB6E}, {0x2BF4, 0x0000}, {0x2BF6, 0x0000}, {0x2BF8, 0x0000}, {0x2BFA, 0x0000}, {0x2BFC, 0x0000}, {0x2BFE, 0x0000}, {0x2C00, 0xBB72}, {0x2C02, 0x0001}, {0x2C04, 0x0063}, {0x2C06, 0xBB52}, {0x2C08, 0x0063}, {0x2C0A, 0xBB60}, {0x2C0C, 0x0000}, {0x2C0E, 0x0000}, {0x2C10, 0x0000}, {0x2C12, 0x0000}, {0x2C14, 0xBADA}, {0x2C16, 0x0002}, {0x2C18, 0x0066}, {0x2C1A, 0x0067}, {0x2C1C, 0x00AF}, {0x2C1E, 0x01CF}, {0x2C20, 0x0087}, {0x2C22, 0x0083}, {0x2C24, 0x011B}, {0x2C26, 0x035A}, {0x2C28, 0x00FA}, {0x2C2A, 0x00F2}, {0x2C2C, 0x00A6}, {0x2C2E, 0x00A4}, {0x2C30, 0xFFFF}, {0x2C32, 0x002C}, {0x2C34, 0x0058}, {0x2C36, 0x0000}, {0x2C38, 0x0000}, {0x2C3A, 0xBC18}, {0x2C3C, 0xBB74}, {0x2C3E, 0xBB80}, {0x2C40, 0xBC32}, {0x2C42, 0xBB8C}, {0x2C44, 0xBBA0}, {0x2C46, 0xBB8C}, {0x2C48, 0xBBA0}, {0x2C4A, 0xBC04}, {0x2C4C, 0xBC04}, {0x2C4E, 0xBBF0}, {0x2C50, 0xBBF0}, {0x2C52, 0xBBB4}, {0x2C54, 0xBBC8}, {0x2C56, 0xBBB4}, {0x2C58, 0xBBC8}, {0x2C5A, 0xBC04}, {0x2C5C, 0xBC04}, {0x2C5E, 0xBBF0}, {0x2C60, 0xBBF0}, {0x2C62, 0xBB8C}, {0x2C64, 0xBBA0}, {0x2C66, 0xBB8C}, {0x2C68, 0xBBA0}, {0x2C6A, 0xBC04}, {0x2C6C, 0xBC04}, {0x2C6E, 0xBBF0}, {0x2C70, 0xBBF0}, {0x2C72, 0xBBB4}, {0x2C74, 0xBBC8}, {0x2C76, 0xBBB4}, {0x2C78, 0xBBC8}, {0x2C7A, 0xBC04}, {0x2C7C, 0xBC04}, {0x2C7E, 0xBBF0}, {0x2C80, 0xBBF0}, {0x3800, 0x880E}, {0x3802, 0xBC62}, {0x3804, 0xBC40}, {0x3806, 0xD13E}, {0x3808, 0xBC42}, {0x380A, 0xBC3C}, {0x380C, 0x0000}, {0x380E, 0x0040}, {0x3810, 0x0040}, {0x3812, 0x0040}, {0x3814, 0x0043}, {0x3816, 0x0046}, {0x3818, 0x004B}, {0x381A, 0x004D}, {0x381C, 0x0051}, {0x381E, 0x0055}, {0x3820, 0x005A}, {0x3822, 0x005E}, {0x3824, 0x0062}, {0x3826, 0x0067}, {0x3828, 0x006C}, {0x382A, 0x0070}, {0x382C, 0x0078}, {0x382E, 0x0086}, {0x3830, 0x0090}, {0x3832, 0x0096}, {0x3834, 0x009D}, {0x3836, 0x00A5}, {0x3838, 0x00AD}, {0x383A, 0x00B4}, {0x383C, 0x00B9}, {0x383E, 0x00BE}, {0x3840, 0x00C3}, {0x3842, 0x00C8}, {0x3844, 0x00CD}, {0x3846, 0x00D2}, {0x3848, 0x00D7}, {0x384A, 0x00DC}, {0x384C, 0x00DC}, {0x384E, 0x0000}, {0x3850, 0x0000}, {0x3852, 0x0000}, {0x3854, 0x0000}, {0x3856, 0x0000}, {0x3858, 0x0000}, {0x385A, 0x0000}, {0x385C, 0x0000}, {0x385E, 0x0000}, {0x3860, 0x0000}, {0x3862, 0x0000}, {0x3864, 0x0000}, {0x3866, 0x0000}, {0x3868, 0x0000}, {0x386A, 0x0000}, {0x386C, 0x0000}, {0x386E, 0x0000}, {0x3870, 0x0000}, {0x3872, 0x0000}, {0x3874, 0x0000}, {0x3876, 0x0000}, {0x3878, 0x0000}, {0x387A, 0x0000}, {0x387C, 0x0000}, {0x387E, 0x0000}, {0x3880, 0x0000}, {0x3882, 0x0000}, {0x3884, 0x0000}, {0x3886, 0x0000}, {0x3888, 0x0000}, {0x388A, 0x0000}, {0x388C, 0x0000}, {0x026A, 0xFFFF}, {0x026C, 0x00FF}, {0x026E, 0x0000}, {0x0360, 0x1E8E}, {0x040E, 0x01EB}, {0x0600, 0x1130}, {0x0602, 0x3112}, {0x0604, 0x8048}, {0x0606, 0x00E9}, {0x067A, 0x0404}, {0x067C, 0x0404}, {0x06A8, 0x0240}, {0x06AA, 0x00CA}, {0x06AC, 0x0041}, {0x06B4, 0x3FFF}, {0x06DE, 0x0404}, {0x06E0, 0x0404}, {0x06E2, 0xFF00}, {0x06E4, 0x8333}, {0x06E6, 0x8333}, {0x06E8, 0x8333}, {0x06EA, 0x8333}, {0x052A, 0x0000}, {0x052C, 0x0000}, {0x0F06, 0x0002}, {0x0A04, 0xB4C5}, {0x0A06, 0xC400}, {0x0A08, 0x988A}, {0x0A0A, 0xA387}, {0x0A0E, 0xEEC0}, {0x0A12, 0x0000}, {0x0A18, 0x0010}, {0x0A1C, 0x0040}, {0x0A20, 0x0015}, {0x0C00, 0x0021}, {0x0C16, 0x0002}, {0x0708, 0x6FC0}, {0x070C, 0x0000}, {0x120C, 0x1428}, {0x121A, 0x0000}, {0x121C, 0x1896}, {0x121E, 0x0032}, {0x1220, 0x0000}, {0x1222, 0x96FF}, {0x1244, 0x0000}, {0x105C, 0x0F0B}, {0x1958, 0x0000}, {0x195A, 0x004C}, {0x195C, 0x0097}, {0x195E, 0x0221}, {0x1960, 0x03FE}, {0x1980, 0x00E0}, {0x1982, 0x0010}, {0x1984, 0x2018}, {0x1986, 0x0008}, {0x1988, 0x0000}, {0x198A, 0x0000}, {0x198C, 0x0880}, {0x198E, 0x0000}, {0x1990, 0x1A00}, {0x1992, 0x0000}, {0x1994, 0x2800}, {0x1996, 0x0002}, {0x1962, 0x0000}, {0x1964, 0x004C}, {0x1966, 0x0097}, {0x1968, 0x0221}, {0x196A, 0x03FE}, {0x19C0, 0x00E0}, {0x19C2, 0x0010}, {0x19C4, 0x2018}, {0x19C6, 0x0008}, {0x19C8, 0x0000}, {0x19CA, 0x0000}, {0x19CC, 0x0880}, {0x19CE, 0x0000}, {0x19D0, 0x1A00}, {0x19D2, 0x0000}, {0x19D4, 0x2800}, {0x19D6, 0x0002}, {0x196C, 0x0000}, {0x196E, 0x004C}, {0x1970, 0x0097}, {0x1972, 0x0221}, {0x1974, 0x03FE}, {0x1A00, 0x00E0}, {0x1A02, 0x0010}, {0x1A04, 0x2018}, {0x1A06, 0x0008}, {0x1A08, 0x0000}, {0x1A0A, 0x0000}, {0x1A0C, 0x0880}, {0x1A0E, 0x0000}, {0x1A10, 0x1A00}, {0x1A12, 0x0000}, {0x1A14, 0x2800}, {0x1A16, 0x0002}, {0x1976, 0x0000}, {0x1978, 0x004C}, {0x197A, 0x0097}, {0x197C, 0x0221}, {0x197E, 0x03FE}, {0x1A40, 0x00E0}, {0x1A42, 0x0010}, {0x1A44, 0x2018}, {0x1A46, 0x0008}, {0x1A48, 0x0000}, {0x1A4A, 0x0000}, {0x1A4C, 0x0880}, {0x1A4E, 0x0000}, {0x1A50, 0x1A00}, {0x1A52, 0x0000}, {0x1A54, 0x2800}, {0x1A56, 0x0002}, {0x192A, 0x0201}, {0x0384, 0x0001}, {0x027E, 0x0100}, }; static const struct hi847_reg mode_3264x2448_regs[] = { {0x0B00, 0x0000}, {0x0204, 0x0000}, {0x0206, 0x033C}, {0x020A, 0x0B4D}, {0x020E, 0x0B51}, {0x0214, 0x0200}, {0x0216, 0x0200}, {0x0218, 0x0200}, {0x021A, 0x0200}, {0x0224, 0x002E}, {0x022A, 0x0017}, {0x022C, 0x0E1F}, {0x022E, 0x09C1}, {0x0234, 0x1111}, {0x0236, 0x1111}, {0x0238, 0x1111}, {0x023A, 0x1111}, {0x0250, 0x0000}, {0x0252, 0x0006}, {0x0254, 0x0000}, {0x0256, 0x0000}, {0x0258, 0x0000}, {0x025A, 0x0000}, {0x025C, 0x0000}, {0x025E, 0x0202}, {0x0268, 0x00CD}, {0x0440, 0x0002}, {0x0F00, 0x0000}, {0x0F04, 0x0008}, {0x0F06, 0x0002}, {0x0B02, 0x0100}, {0x0B04, 0x00DC}, {0x0B12, 0x0CC0}, {0x0B14, 0x0990}, {0x0B20, 0x0100}, {0x1100, 0x1100}, {0x1102, 0x0008}, {0x1108, 0x0202}, {0x1118, 0x0000}, {0x0A10, 0xB040}, {0x0C14, 0x0008}, {0x0C18, 0x0CC0}, {0x0C1A, 0x0990}, {0x0730, 0x0001}, {0x0732, 0x0000}, {0x0734, 0x0300}, {0x0736, 0x004B}, {0x0738, 0x0001}, {0x073C, 0x0900}, {0x0740, 0x0000}, {0x0742, 0x0000}, {0x0744, 0x0300}, {0x0746, 0x007D}, {0x0748, 0x0002}, {0x074A, 0x0900}, {0x074C, 0x0000}, {0x074E, 0x0100}, {0x0750, 0x0000}, {0x1200, 0x0946}, {0x1202, 0x1A00}, {0x120E, 0x6027}, {0x1210, 0x8027}, {0x1246, 0x0105}, {0x1000, 0x0300}, {0x1002, 0xC311}, {0x1004, 0x2BB0}, {0x1010, 0x087B}, {0x1012, 0x0040}, {0x1014, 0x0020}, {0x1016, 0x0020}, {0x101A, 0x0020}, {0x1020, 0xC107}, {0x1022, 0x081E}, {0x1024, 0x0509}, {0x1026, 0x0B0A}, {0x1028, 0x1409}, {0x102A, 0x0B05}, {0x102C, 0x1400}, {0x1038, 0x0000}, {0x103E, 0x0001}, {0x1040, 0x0000}, {0x1042, 0x0008}, {0x1044, 0x0120}, {0x1046, 0x01B0}, {0x1048, 0x0090}, {0x1066, 0x089C}, {0x1600, 0x0000}, {0x1608, 0x0028}, {0x160A, 0x0C80}, {0x160C, 0x001A}, {0x160E, 0x0960}, {0x0252, 0x0009}, {0x0202, 0x0000}, }; static const struct hi847_reg mode_1632x1224_regs[] = { {0x0B00, 0x0000}, {0x0204, 0x0200}, {0x0206, 0x033C}, {0x020A, 0x05A5}, {0x020E, 0x05A9}, {0x0214, 0x0200}, {0x0216, 0x0200}, {0x0218, 0x0200}, {0x021A, 0x0200}, {0x0224, 0x002C}, {0x022A, 0x0015}, {0x022C, 0x0E2D}, {0x022E, 0x09C1}, {0x0234, 0x3311}, {0x0236, 0x3311}, {0x0238, 0x3311}, {0x023A, 0x2222}, {0x0250, 0x0000}, {0x0252, 0x0006}, {0x0254, 0x0000}, {0x0256, 0x0000}, {0x0258, 0x0000}, {0x025A, 0x0000}, {0x025C, 0x0000}, {0x025E, 0x0202}, {0x0268, 0x00CD}, {0x0440, 0x0002}, {0x0F00, 0x0400}, {0x0F04, 0x0004}, {0x0F06, 0x0002}, {0x0B02, 0x0100}, {0x0B04, 0x00FC}, {0x0B12, 0x0660}, {0x0B14, 0x04C8}, {0x0B20, 0x0200}, {0x1100, 0x1100}, {0x1102, 0x0008}, {0x1108, 0x0402}, {0x1118, 0x0000}, {0x0A10, 0xB060}, {0x0C14, 0x0008}, {0x0C18, 0x0CC0}, {0x0C1A, 0x04C8}, {0x0730, 0x0001}, {0x0732, 0x0000}, {0x0734, 0x0300}, {0x0736, 0x004B}, {0x0738, 0x0001}, {0x073C, 0x0900}, {0x0740, 0x0000}, {0x0742, 0x0000}, {0x0744, 0x0300}, {0x0746, 0x007D}, {0x0748, 0x0002}, {0x074A, 0x0900}, {0x074C, 0x0100}, {0x074E, 0x0100}, {0x0750, 0x0000}, {0x1200, 0x0946}, {0x1202, 0x1A00}, {0x120E, 0x6027}, {0x1210, 0x8027}, {0x1246, 0x0105}, {0x1000, 0x0300}, {0x1002, 0xC311}, {0x1004, 0x2BB0}, {0x1010, 0x042B}, {0x1012, 0x0012}, {0x1014, 0x0020}, {0x1016, 0x0020}, {0x101A, 0x0020}, {0x1020, 0xC103}, {0x1022, 0x040F}, {0x1024, 0x0304}, {0x1026, 0x0607}, {0x1028, 0x0D06}, {0x102A, 0x0605}, {0x102C, 0x0C00}, {0x1038, 0x0000}, {0x103E, 0x0101}, {0x1040, 0x0000}, {0x1042, 0x0008}, {0x1044, 0x0120}, {0x1046, 0x01B0}, {0x1048, 0x0090}, {0x1066, 0x043B}, {0x1600, 0x0400}, {0x1608, 0x0028}, {0x160A, 0x0C80}, {0x160C, 0x001A}, {0x160E, 0x0960}, {0x0252, 0x0009}, {0x0202, 0x0000}, }; static const char * const hi847_test_pattern_menu[] = { "No Pattern", "Solid Colour", "100% Colour Bars", "Fade To Grey Colour Bars", "PN9", "Horizontal Gradient Pattern", "Vertical Gradient Pattern", "Check Board", "Slant Pattern", }; static const s64 link_freq_menu_items[] = { HI847_LINK_FREQ_400MHZ, HI847_LINK_FREQ_200MHZ, }; static const struct hi847_link_freq_config link_freq_configs[] = { [HI847_LINK_FREQ_400MHZ_INDEX] = { .reg_list = { .num_of_regs = ARRAY_SIZE(mipi_data_rate_lane_4), .regs = mipi_data_rate_lane_4, } }, [HI847_LINK_FREQ_200MHZ_INDEX] = { .reg_list = { .num_of_regs = ARRAY_SIZE(mipi_data_rate_lane_4), .regs = mipi_data_rate_lane_4, } } }; static const struct hi847_mode supported_modes[] = { { .width = 3264, .height = 2448, .fll_def = HI847_FLL_30FPS, .fll_min = HI847_FLL_30FPS_MIN, .llp = 0x033C, .reg_list = { .num_of_regs = ARRAY_SIZE(mode_3264x2448_regs), .regs = mode_3264x2448_regs, }, .link_freq_index = HI847_LINK_FREQ_400MHZ_INDEX, }, { .width = 1632, .height = 1224, .fll_def = HI847_FLL_60FPS, .fll_min = HI847_FLL_60FPS_MIN, .llp = 0x033C, .reg_list = { .num_of_regs = ARRAY_SIZE(mode_1632x1224_regs), .regs = mode_1632x1224_regs, }, .link_freq_index = HI847_LINK_FREQ_200MHZ_INDEX, } }; struct hi847 { struct v4l2_subdev sd; struct media_pad pad; struct v4l2_ctrl_handler ctrl_handler; /* V4L2 Controls */ struct v4l2_ctrl *link_freq; struct v4l2_ctrl *pixel_rate; struct v4l2_ctrl *vblank; struct v4l2_ctrl *hblank; struct v4l2_ctrl *exposure; struct v4l2_ctrl *vflip; struct v4l2_ctrl *hflip; /* Current mode */ const struct hi847_mode *cur_mode; /* To serialize asynchronus callbacks */ struct mutex mutex; /* Streaming on/off */ bool streaming; }; static u64 to_pixel_rate(u32 f_index) { u64 pixel_rate = link_freq_menu_items[f_index] * 2 * HI847_DATA_LANES; do_div(pixel_rate, HI847_RGB_DEPTH); return pixel_rate; } static int hi847_read_reg(struct hi847 *hi847, u16 reg, u16 len, u32 *val) { struct i2c_client *client = v4l2_get_subdevdata(&hi847->sd); struct i2c_msg msgs[2]; u8 addr_buf[2]; u8 data_buf[4] = {0}; int ret; if (len > 4) return -EINVAL; put_unaligned_be16(reg, addr_buf); msgs[0].addr = client->addr; msgs[0].flags = 0; msgs[0].len = sizeof(addr_buf); msgs[0].buf = addr_buf; msgs[1].addr = client->addr; msgs[1].flags = I2C_M_RD; msgs[1].len = len; msgs[1].buf = &data_buf[4 - len]; ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs)); if (ret != ARRAY_SIZE(msgs)) return -EIO; *val = get_unaligned_be32(data_buf); return 0; } static int hi847_write_reg(struct hi847 *hi847, u16 reg, u16 len, u32 val) { struct i2c_client *client = v4l2_get_subdevdata(&hi847->sd); u8 buf[6]; if (len > 4) return -EINVAL; put_unaligned_be16(reg, buf); put_unaligned_be32(val << 8 * (4 - len), buf + 2); if (i2c_master_send(client, buf, len + 2) != len + 2) return -EIO; return 0; } static int hi847_write_reg_list(struct hi847 *hi847, const struct hi847_reg_list *r_list) { struct i2c_client *client = v4l2_get_subdevdata(&hi847->sd); unsigned int i; int ret; for (i = 0; i < r_list->num_of_regs; i++) { ret = hi847_write_reg(hi847, r_list->regs[i].address, HI847_REG_VALUE_16BIT, r_list->regs[i].val); if (ret) { dev_err_ratelimited(&client->dev, "failed to write reg 0x%4.4x. error = %d", r_list->regs[i].address, ret); return ret; } } return 0; } static int hi847_update_digital_gain(struct hi847 *hi847, u32 d_gain) { int ret; ret = hi847_write_reg(hi847, HI847_REG_MWB_GR_GAIN, HI847_REG_VALUE_16BIT, d_gain); if (ret) return ret; ret = hi847_write_reg(hi847, HI847_REG_MWB_GB_GAIN, HI847_REG_VALUE_16BIT, d_gain); if (ret) return ret; ret = hi847_write_reg(hi847, HI847_REG_MWB_R_GAIN, HI847_REG_VALUE_16BIT, d_gain); if (ret) return ret; return hi847_write_reg(hi847, HI847_REG_MWB_B_GAIN, HI847_REG_VALUE_16BIT, d_gain); } static int hi847_test_pattern(struct hi847 *hi847, u32 pattern) { int ret; u32 val; if (pattern) { ret = hi847_read_reg(hi847, HI847_REG_ISP, HI847_REG_VALUE_16BIT, &val); if (ret) return ret; ret = hi847_write_reg(hi847, HI847_REG_ISP, HI847_REG_VALUE_16BIT, val | HI847_REG_ISP_TPG_EN); if (ret) return ret; } ret = hi847_read_reg(hi847, HI847_REG_TEST_PATTERN, HI847_REG_VALUE_16BIT, &val); if (ret) return ret; return hi847_write_reg(hi847, HI847_REG_TEST_PATTERN, HI847_REG_VALUE_16BIT, val | pattern << 8); } static int hi847_grbg_shift(struct hi847 *hi847) { int ret; int hflip, vflip; /* regs shift for full size */ static const u32 FORMAT_X_SHIFT_1[2][2] = { { 0x0008, 0x0007, }, { 0x0008, 0x0007, }, }; static const u32 FORMAT_Y_SHIFT_1[2][2] = { { 0x0002, 0x0002, }, { 0x0001, 0x0001, }, }; /* regs shift for binning size */ static const u32 FORMAT_X_SHIFT_2[2][2] = { { 0x0004, 0x0003, }, { 0x0004, 0x0003, }, }; static const u32 FORMAT_Y_SHIFT_2[2][2] = { { 0x0002, 0x0002, }, { 0x0001, 0x0001, }, }; hflip = hi847->hflip->val; vflip = hi847->vflip->val; if (hi847->cur_mode->width == 3264) { ret = hi847_write_reg(hi847, HI847_REG_FORMAT_X, HI847_REG_VALUE_16BIT, FORMAT_X_SHIFT_1[vflip][hflip]); if (ret) return ret; return hi847_write_reg(hi847, HI847_REG_FORMAT_Y, HI847_REG_VALUE_16BIT, FORMAT_Y_SHIFT_1[vflip][hflip]); } else { ret = hi847_write_reg(hi847, HI847_REG_FORMAT_X, HI847_REG_VALUE_16BIT, FORMAT_X_SHIFT_2[vflip][hflip]); if (ret) return ret; return hi847_write_reg(hi847, HI847_REG_FORMAT_Y, HI847_REG_VALUE_16BIT, FORMAT_Y_SHIFT_2[vflip][hflip]); } } static int hi847_set_ctrl_hflip(struct hi847 *hi847, u32 ctrl_val) { int ret; u32 val; ret = hi847_read_reg(hi847, HI847_REG_MIRROR_FLIP, HI847_REG_VALUE_16BIT, &val); if (ret) return ret; ret = hi847_grbg_shift(hi847); if (ret) return ret; return hi847_write_reg(hi847, HI847_REG_MIRROR_FLIP, HI847_REG_VALUE_16BIT, ctrl_val ? val | BIT(8) : val & ~BIT(8)); } static int hi847_set_ctrl_vflip(struct hi847 *hi847, u8 ctrl_val) { int ret; u32 val; ret = hi847_read_reg(hi847, HI847_REG_MIRROR_FLIP, HI847_REG_VALUE_16BIT, &val); if (ret) return ret; ret = hi847_grbg_shift(hi847); if (ret) return ret; return hi847_write_reg(hi847, HI847_REG_MIRROR_FLIP, HI847_REG_VALUE_16BIT, ctrl_val ? val | BIT(9) : val & ~BIT(9)); } static int hi847_set_ctrl(struct v4l2_ctrl *ctrl) { struct hi847 *hi847 = container_of(ctrl->handler, struct hi847, ctrl_handler); struct i2c_client *client = v4l2_get_subdevdata(&hi847->sd); s64 exposure_max; int ret = 0; /* Propagate change of current control to all related controls */ if (ctrl->id == V4L2_CID_VBLANK) { /* Update max exposure while meeting expected vblanking */ exposure_max = hi847->cur_mode->height + ctrl->val - HI847_EXPOSURE_MAX_MARGIN; __v4l2_ctrl_modify_range(hi847->exposure, hi847->exposure->minimum, exposure_max, hi847->exposure->step, exposure_max); } /* V4L2 controls values will be applied only when power is already up */ if (!pm_runtime_get_if_in_use(&client->dev)) return 0; switch (ctrl->id) { case V4L2_CID_ANALOGUE_GAIN: ret = hi847_write_reg(hi847, HI847_REG_ANALOG_GAIN, HI847_REG_VALUE_16BIT, ctrl->val); break; case V4L2_CID_DIGITAL_GAIN: ret = hi847_update_digital_gain(hi847, ctrl->val); break; case V4L2_CID_EXPOSURE: ret = hi847_write_reg(hi847, HI847_REG_EXPOSURE, HI847_REG_VALUE_16BIT, ctrl->val); break; case V4L2_CID_VBLANK: /* Update FLL that meets expected vertical blanking */ ret = hi847_write_reg(hi847, HI847_REG_FLL, HI847_REG_VALUE_16BIT, hi847->cur_mode->height + ctrl->val); break; case V4L2_CID_TEST_PATTERN: ret = hi847_test_pattern(hi847, ctrl->val); break; case V4L2_CID_HFLIP: hi847_set_ctrl_hflip(hi847, ctrl->val); break; case V4L2_CID_VFLIP: hi847_set_ctrl_vflip(hi847, ctrl->val); break; default: ret = -EINVAL; break; } pm_runtime_put(&client->dev); return ret; } static const struct v4l2_ctrl_ops hi847_ctrl_ops = { .s_ctrl = hi847_set_ctrl, }; static int hi847_init_controls(struct hi847 *hi847) { struct v4l2_ctrl_handler *ctrl_hdlr; s64 exposure_max, h_blank; int ret; ctrl_hdlr = &hi847->ctrl_handler; ret = v4l2_ctrl_handler_init(ctrl_hdlr, 8); if (ret) return ret; ctrl_hdlr->lock = &hi847->mutex; hi847->link_freq = v4l2_ctrl_new_int_menu(ctrl_hdlr, &hi847_ctrl_ops, V4L2_CID_LINK_FREQ, ARRAY_SIZE(link_freq_menu_items) - 1, 0, link_freq_menu_items); if (hi847->link_freq) hi847->link_freq->flags |= V4L2_CTRL_FLAG_READ_ONLY; hi847->pixel_rate = v4l2_ctrl_new_std (ctrl_hdlr, &hi847_ctrl_ops, V4L2_CID_PIXEL_RATE, 0, to_pixel_rate(HI847_LINK_FREQ_400MHZ_INDEX), 1, to_pixel_rate(HI847_LINK_FREQ_400MHZ_INDEX)); hi847->vblank = v4l2_ctrl_new_std(ctrl_hdlr, &hi847_ctrl_ops, V4L2_CID_VBLANK, hi847->cur_mode->fll_min - hi847->cur_mode->height, HI847_FLL_MAX - hi847->cur_mode->height, 1, hi847->cur_mode->fll_def - hi847->cur_mode->height); h_blank = hi847->cur_mode->llp - hi847->cur_mode->width; hi847->hblank = v4l2_ctrl_new_std(ctrl_hdlr, &hi847_ctrl_ops, V4L2_CID_HBLANK, h_blank, h_blank, 1, h_blank); if (hi847->hblank) hi847->hblank->flags |= V4L2_CTRL_FLAG_READ_ONLY; v4l2_ctrl_new_std(ctrl_hdlr, &hi847_ctrl_ops, V4L2_CID_ANALOGUE_GAIN, HI847_ANAL_GAIN_MIN, HI847_ANAL_GAIN_MAX, HI847_ANAL_GAIN_STEP, HI847_ANAL_GAIN_MIN); v4l2_ctrl_new_std(ctrl_hdlr, &hi847_ctrl_ops, V4L2_CID_DIGITAL_GAIN, HI847_DGTL_GAIN_MIN, HI847_DGTL_GAIN_MAX, HI847_DGTL_GAIN_STEP, HI847_DGTL_GAIN_DEFAULT); exposure_max = hi847->cur_mode->fll_def - HI847_EXPOSURE_MAX_MARGIN; hi847->exposure = v4l2_ctrl_new_std(ctrl_hdlr, &hi847_ctrl_ops, V4L2_CID_EXPOSURE, HI847_EXPOSURE_MIN, exposure_max, HI847_EXPOSURE_STEP, exposure_max); v4l2_ctrl_new_std_menu_items(ctrl_hdlr, &hi847_ctrl_ops, V4L2_CID_TEST_PATTERN, ARRAY_SIZE(hi847_test_pattern_menu) - 1, 0, 0, hi847_test_pattern_menu); hi847->hflip = v4l2_ctrl_new_std(ctrl_hdlr, &hi847_ctrl_ops, V4L2_CID_HFLIP, 0, 1, 1, 0); hi847->vflip = v4l2_ctrl_new_std(ctrl_hdlr, &hi847_ctrl_ops, V4L2_CID_VFLIP, 0, 1, 1, 0); if (ctrl_hdlr->error) return ctrl_hdlr->error; hi847->sd.ctrl_handler = ctrl_hdlr; return 0; } static void hi847_assign_pad_format(const struct hi847_mode *mode, struct v4l2_mbus_framefmt *fmt) { fmt->width = mode->width; fmt->height = mode->height; fmt->code = MEDIA_BUS_FMT_SGRBG10_1X10; fmt->field = V4L2_FIELD_NONE; } static int hi847_start_streaming(struct hi847 *hi847) { struct i2c_client *client = v4l2_get_subdevdata(&hi847->sd); const struct hi847_reg_list *reg_list; int link_freq_index, ret; link_freq_index = hi847->cur_mode->link_freq_index; reg_list = &link_freq_configs[link_freq_index].reg_list; ret = hi847_write_reg_list(hi847, reg_list); if (ret) { dev_err(&client->dev, "failed to set plls"); return ret; } reg_list = &hi847->cur_mode->reg_list; ret = hi847_write_reg_list(hi847, reg_list); if (ret) { dev_err(&client->dev, "failed to set mode"); return ret; } ret = __v4l2_ctrl_handler_setup(hi847->sd.ctrl_handler); if (ret) return ret; ret = hi847_write_reg(hi847, HI847_REG_MODE_TG, HI847_REG_VALUE_16BIT, HI847_REG_MODE_TG_ENABLE); ret = hi847_write_reg(hi847, HI847_REG_MODE_SELECT, HI847_REG_VALUE_16BIT, HI847_MODE_STREAMING); if (ret) { dev_err(&client->dev, "failed to set stream"); return ret; } return 0; } static void hi847_stop_streaming(struct hi847 *hi847) { struct i2c_client *client = v4l2_get_subdevdata(&hi847->sd); if (hi847_write_reg(hi847, HI847_REG_MODE_TG, HI847_REG_VALUE_16BIT, HI847_REG_MODE_TG_DISABLE)) dev_err(&client->dev, "failed to set stream 0x%x", HI847_REG_MODE_TG); if (hi847_write_reg(hi847, HI847_REG_MODE_SELECT, HI847_REG_VALUE_16BIT, HI847_MODE_STANDBY)) dev_err(&client->dev, "failed to set stream 0x%x", HI847_REG_MODE_SELECT); } static int hi847_set_stream(struct v4l2_subdev *sd, int enable) { struct hi847 *hi847 = to_hi847(sd); struct i2c_client *client = v4l2_get_subdevdata(sd); int ret = 0; if (hi847->streaming == enable) return 0; mutex_lock(&hi847->mutex); if (enable) { ret = pm_runtime_get_sync(&client->dev); if (ret < 0) { pm_runtime_put_noidle(&client->dev); mutex_unlock(&hi847->mutex); return ret; } ret = hi847_start_streaming(hi847); if (ret) { enable = 0; hi847_stop_streaming(hi847); pm_runtime_put(&client->dev); } } else { hi847_stop_streaming(hi847); pm_runtime_put(&client->dev); } hi847->streaming = enable; mutex_unlock(&hi847->mutex); return ret; } static int __maybe_unused hi847_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct v4l2_subdev *sd = i2c_get_clientdata(client); struct hi847 *hi847 = to_hi847(sd); mutex_lock(&hi847->mutex); if (hi847->streaming) hi847_stop_streaming(hi847); mutex_unlock(&hi847->mutex); return 0; } static int __maybe_unused hi847_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct v4l2_subdev *sd = i2c_get_clientdata(client); struct hi847 *hi847 = to_hi847(sd); int ret; mutex_lock(&hi847->mutex); if (hi847->streaming) { ret = hi847_start_streaming(hi847); if (ret) goto error; } mutex_unlock(&hi847->mutex); return 0; error: hi847_stop_streaming(hi847); hi847->streaming = 0; mutex_unlock(&hi847->mutex); return ret; } static int hi847_set_format(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *fmt) { struct hi847 *hi847 = to_hi847(sd); const struct hi847_mode *mode; s32 vblank_def, h_blank; mode = v4l2_find_nearest_size(supported_modes, ARRAY_SIZE(supported_modes), width, height, fmt->format.width, fmt->format.height); mutex_lock(&hi847->mutex); hi847_assign_pad_format(mode, &fmt->format); if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) { *v4l2_subdev_get_try_format(sd, sd_state, fmt->pad) = fmt->format; } else { hi847->cur_mode = mode; __v4l2_ctrl_s_ctrl(hi847->link_freq, mode->link_freq_index); __v4l2_ctrl_s_ctrl_int64(hi847->pixel_rate, to_pixel_rate(mode->link_freq_index)); /* Update limits and set FPS to default */ vblank_def = mode->fll_def - mode->height; __v4l2_ctrl_modify_range(hi847->vblank, mode->fll_min - mode->height, HI847_FLL_MAX - mode->height, 1, vblank_def); __v4l2_ctrl_s_ctrl(hi847->vblank, vblank_def); h_blank = hi847->cur_mode->llp - hi847->cur_mode->width; __v4l2_ctrl_modify_range(hi847->hblank, h_blank, h_blank, 1, h_blank); } mutex_unlock(&hi847->mutex); return 0; } static int hi847_get_format(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *fmt) { struct hi847 *hi847 = to_hi847(sd); mutex_lock(&hi847->mutex); if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) fmt->format = *v4l2_subdev_get_try_format(&hi847->sd, sd_state, fmt->pad); else hi847_assign_pad_format(hi847->cur_mode, &fmt->format); mutex_unlock(&hi847->mutex); return 0; } static int hi847_enum_mbus_code(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_mbus_code_enum *code) { if (code->index > 0) return -EINVAL; code->code = MEDIA_BUS_FMT_SGRBG10_1X10; return 0; } static int hi847_enum_frame_size(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_frame_size_enum *fse) { if (fse->index >= ARRAY_SIZE(supported_modes)) return -EINVAL; if (fse->code != MEDIA_BUS_FMT_SGRBG10_1X10) return -EINVAL; fse->min_width = supported_modes[fse->index].width; fse->max_width = fse->min_width; fse->min_height = supported_modes[fse->index].height; fse->max_height = fse->min_height; return 0; } static int hi847_open(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh) { struct hi847 *hi847 = to_hi847(sd); mutex_lock(&hi847->mutex); hi847_assign_pad_format(&supported_modes[0], v4l2_subdev_get_try_format(sd, fh->state, 0)); mutex_unlock(&hi847->mutex); return 0; } static const struct v4l2_subdev_video_ops hi847_video_ops = { .s_stream = hi847_set_stream, }; static const struct v4l2_subdev_pad_ops hi847_pad_ops = { .set_fmt = hi847_set_format, .get_fmt = hi847_get_format, .enum_mbus_code = hi847_enum_mbus_code, .enum_frame_size = hi847_enum_frame_size, }; static const struct v4l2_subdev_ops hi847_subdev_ops = { .video = &hi847_video_ops, .pad = &hi847_pad_ops, }; static const struct media_entity_operations hi847_subdev_entity_ops = { .link_validate = v4l2_subdev_link_validate, }; static const struct v4l2_subdev_internal_ops hi847_internal_ops = { .open = hi847_open, }; static int hi847_identify_module(struct hi847 *hi847) { struct i2c_client *client = v4l2_get_subdevdata(&hi847->sd); int ret; u32 val; ret = hi847_read_reg(hi847, HI847_REG_CHIP_ID, HI847_REG_VALUE_16BIT, &val); if (ret) return ret; if (val != HI847_CHIP_ID) { dev_err(&client->dev, "chip id mismatch: %x!=%x", HI847_CHIP_ID, val); return -ENXIO; } return 0; } static int hi847_check_hwcfg(struct device *dev) { struct fwnode_handle *ep; struct fwnode_handle *fwnode = dev_fwnode(dev); struct v4l2_fwnode_endpoint bus_cfg = { .bus_type = V4L2_MBUS_CSI2_DPHY }; u32 mclk; int ret; unsigned int i, j; if (!fwnode) return -ENXIO; ret = fwnode_property_read_u32(fwnode, "clock-frequency", &mclk); if (ret) { dev_err(dev, "can't get clock frequency"); return ret; } if (mclk != HI847_MCLK) { dev_err(dev, "external clock %d is not supported", mclk); return -EINVAL; } ep = fwnode_graph_get_next_endpoint(fwnode, NULL); if (!ep) return -ENXIO; ret = v4l2_fwnode_endpoint_alloc_parse(ep, &bus_cfg); fwnode_handle_put(ep); if (ret) return ret; if (bus_cfg.bus.mipi_csi2.num_data_lanes != HI847_DATA_LANES) { dev_err(dev, "number of CSI2 data lanes %d is not supported", bus_cfg.bus.mipi_csi2.num_data_lanes); ret = -EINVAL; goto check_hwcfg_error; } if (!bus_cfg.nr_of_link_frequencies) { dev_err(dev, "no link frequencies defined"); ret = -EINVAL; goto check_hwcfg_error; } for (i = 0; i < ARRAY_SIZE(link_freq_menu_items); i++) { for (j = 0; j < bus_cfg.nr_of_link_frequencies; j++) { if (link_freq_menu_items[i] == bus_cfg.link_frequencies[j]) break; } if (j == bus_cfg.nr_of_link_frequencies) { dev_err(dev, "no link frequency %lld supported", link_freq_menu_items[i]); ret = -EINVAL; goto check_hwcfg_error; } } check_hwcfg_error: v4l2_fwnode_endpoint_free(&bus_cfg); return ret; } static void hi847_remove(struct i2c_client *client) { struct v4l2_subdev *sd = i2c_get_clientdata(client); struct hi847 *hi847 = to_hi847(sd); v4l2_async_unregister_subdev(sd); media_entity_cleanup(&sd->entity); v4l2_ctrl_handler_free(sd->ctrl_handler); pm_runtime_disable(&client->dev); mutex_destroy(&hi847->mutex); } static int hi847_probe(struct i2c_client *client) { struct hi847 *hi847; int ret; hi847 = devm_kzalloc(&client->dev, sizeof(*hi847), GFP_KERNEL); if (!hi847) return -ENOMEM; ret = hi847_check_hwcfg(&client->dev); if (ret) { dev_err(&client->dev, "failed to get HW configuration: %d", ret); return ret; } v4l2_i2c_subdev_init(&hi847->sd, client, &hi847_subdev_ops); ret = hi847_identify_module(hi847); if (ret) { dev_err(&client->dev, "failed to find sensor: %d", ret); return ret; } mutex_init(&hi847->mutex); hi847->cur_mode = &supported_modes[0]; ret = hi847_init_controls(hi847); if (ret) { dev_err(&client->dev, "failed to init controls: %d", ret); goto probe_error_v4l2_ctrl_handler_free; } hi847->sd.internal_ops = &hi847_internal_ops; hi847->sd.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE; hi847->sd.entity.ops = &hi847_subdev_entity_ops; hi847->sd.entity.function = MEDIA_ENT_F_CAM_SENSOR; hi847->pad.flags = MEDIA_PAD_FL_SOURCE; ret = media_entity_pads_init(&hi847->sd.entity, 1, &hi847->pad); if (ret) { dev_err(&client->dev, "failed to init entity pads: %d", ret); goto probe_error_v4l2_ctrl_handler_free; } ret = v4l2_async_register_subdev_sensor(&hi847->sd); if (ret < 0) { dev_err(&client->dev, "failed to register V4L2 subdev: %d", ret); goto probe_error_media_entity_cleanup; } pm_runtime_set_active(&client->dev); pm_runtime_enable(&client->dev); pm_runtime_idle(&client->dev); return 0; probe_error_media_entity_cleanup: media_entity_cleanup(&hi847->sd.entity); probe_error_v4l2_ctrl_handler_free: v4l2_ctrl_handler_free(hi847->sd.ctrl_handler); mutex_destroy(&hi847->mutex); return ret; } static const struct dev_pm_ops hi847_pm_ops = { SET_SYSTEM_SLEEP_PM_OPS(hi847_suspend, hi847_resume) }; #ifdef CONFIG_ACPI static const struct acpi_device_id hi847_acpi_ids[] = { {"HYV0847"}, {} }; MODULE_DEVICE_TABLE(acpi, hi847_acpi_ids); #endif static struct i2c_driver hi847_i2c_driver = { .driver = { .name = "hi847", .pm = &hi847_pm_ops, .acpi_match_table = ACPI_PTR(hi847_acpi_ids), }, .probe = hi847_probe, .remove = hi847_remove, }; module_i2c_driver(hi847_i2c_driver); MODULE_AUTHOR("Shawn Tu"); MODULE_DESCRIPTION("Hynix HI847 sensor driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/media/i2c/hi847.c
// SPDX-License-Identifier: GPL-2.0 /* * Driver for ST MIPID02 CSI-2 to PARALLEL bridge * * Copyright (C) STMicroelectronics SA 2019 * Authors: Mickael Guene <[email protected]> * for STMicroelectronics. * * */ #include <linux/clk.h> #include <linux/delay.h> #include <linux/gpio/consumer.h> #include <linux/i2c.h> #include <linux/module.h> #include <linux/of_graph.h> #include <linux/regulator/consumer.h> #include <media/v4l2-async.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-device.h> #include <media/v4l2-fwnode.h> #include <media/v4l2-subdev.h> #define MIPID02_CLK_LANE_WR_REG1 0x01 #define MIPID02_CLK_LANE_REG1 0x02 #define MIPID02_CLK_LANE_REG3 0x04 #define MIPID02_DATA_LANE0_REG1 0x05 #define MIPID02_DATA_LANE0_REG2 0x06 #define MIPID02_DATA_LANE1_REG1 0x09 #define MIPID02_DATA_LANE1_REG2 0x0a #define MIPID02_MODE_REG1 0x14 #define MIPID02_MODE_REG2 0x15 #define MIPID02_DATA_ID_RREG 0x17 #define MIPID02_DATA_SELECTION_CTRL 0x19 #define MIPID02_PIX_WIDTH_CTRL 0x1e #define MIPID02_PIX_WIDTH_CTRL_EMB 0x1f /* Bits definition for MIPID02_CLK_LANE_REG1 */ #define CLK_ENABLE BIT(0) /* Bits definition for MIPID02_CLK_LANE_REG3 */ #define CLK_MIPI_CSI BIT(1) /* Bits definition for MIPID02_DATA_LANE0_REG1 */ #define DATA_ENABLE BIT(0) /* Bits definition for MIPID02_DATA_LANEx_REG2 */ #define DATA_MIPI_CSI BIT(0) /* Bits definition for MIPID02_MODE_REG1 */ #define MODE_DATA_SWAP BIT(2) #define MODE_NO_BYPASS BIT(6) /* Bits definition for MIPID02_MODE_REG2 */ #define MODE_HSYNC_ACTIVE_HIGH BIT(1) #define MODE_VSYNC_ACTIVE_HIGH BIT(2) #define MODE_PCLK_SAMPLE_RISING BIT(3) /* Bits definition for MIPID02_DATA_SELECTION_CTRL */ #define SELECTION_MANUAL_DATA BIT(2) #define SELECTION_MANUAL_WIDTH BIT(3) static const u32 mipid02_supported_fmt_codes[] = { MEDIA_BUS_FMT_SBGGR8_1X8, MEDIA_BUS_FMT_SGBRG8_1X8, MEDIA_BUS_FMT_SGRBG8_1X8, MEDIA_BUS_FMT_SRGGB8_1X8, MEDIA_BUS_FMT_SBGGR10_1X10, MEDIA_BUS_FMT_SGBRG10_1X10, MEDIA_BUS_FMT_SGRBG10_1X10, MEDIA_BUS_FMT_SRGGB10_1X10, MEDIA_BUS_FMT_SBGGR12_1X12, MEDIA_BUS_FMT_SGBRG12_1X12, MEDIA_BUS_FMT_SGRBG12_1X12, MEDIA_BUS_FMT_SRGGB12_1X12, MEDIA_BUS_FMT_YUYV8_1X16, MEDIA_BUS_FMT_YVYU8_1X16, MEDIA_BUS_FMT_UYVY8_1X16, MEDIA_BUS_FMT_VYUY8_1X16, MEDIA_BUS_FMT_RGB565_1X16, MEDIA_BUS_FMT_BGR888_1X24, MEDIA_BUS_FMT_RGB565_2X8_LE, MEDIA_BUS_FMT_RGB565_2X8_BE, MEDIA_BUS_FMT_YUYV8_2X8, MEDIA_BUS_FMT_YVYU8_2X8, MEDIA_BUS_FMT_UYVY8_2X8, MEDIA_BUS_FMT_VYUY8_2X8, MEDIA_BUS_FMT_JPEG_1X8 }; /* regulator supplies */ static const char * const mipid02_supply_name[] = { "VDDE", /* 1.8V digital I/O supply */ "VDDIN", /* 1V8 voltage regulator supply */ }; #define MIPID02_NUM_SUPPLIES ARRAY_SIZE(mipid02_supply_name) #define MIPID02_SINK_0 0 #define MIPID02_SINK_1 1 #define MIPID02_SOURCE 2 #define MIPID02_PAD_NB 3 struct mipid02_dev { struct i2c_client *i2c_client; struct regulator_bulk_data supplies[MIPID02_NUM_SUPPLIES]; struct v4l2_subdev sd; struct media_pad pad[MIPID02_PAD_NB]; struct clk *xclk; struct gpio_desc *reset_gpio; /* endpoints info */ struct v4l2_fwnode_endpoint rx; u64 link_frequency; struct v4l2_fwnode_endpoint tx; /* remote source */ struct v4l2_async_notifier notifier; struct v4l2_subdev *s_subdev; /* registers */ struct { u8 clk_lane_reg1; u8 data_lane0_reg1; u8 data_lane1_reg1; u8 mode_reg1; u8 mode_reg2; u8 data_selection_ctrl; u8 data_id_rreg; u8 pix_width_ctrl; u8 pix_width_ctrl_emb; } r; /* lock to protect all members below */ struct mutex lock; bool streaming; struct v4l2_mbus_framefmt fmt; }; static int bpp_from_code(__u32 code) { switch (code) { case MEDIA_BUS_FMT_SBGGR8_1X8: case MEDIA_BUS_FMT_SGBRG8_1X8: case MEDIA_BUS_FMT_SGRBG8_1X8: case MEDIA_BUS_FMT_SRGGB8_1X8: return 8; case MEDIA_BUS_FMT_SBGGR10_1X10: case MEDIA_BUS_FMT_SGBRG10_1X10: case MEDIA_BUS_FMT_SGRBG10_1X10: case MEDIA_BUS_FMT_SRGGB10_1X10: return 10; case MEDIA_BUS_FMT_SBGGR12_1X12: case MEDIA_BUS_FMT_SGBRG12_1X12: case MEDIA_BUS_FMT_SGRBG12_1X12: case MEDIA_BUS_FMT_SRGGB12_1X12: return 12; case MEDIA_BUS_FMT_YUYV8_1X16: case MEDIA_BUS_FMT_YVYU8_1X16: case MEDIA_BUS_FMT_UYVY8_1X16: case MEDIA_BUS_FMT_VYUY8_1X16: case MEDIA_BUS_FMT_RGB565_1X16: case MEDIA_BUS_FMT_YUYV8_2X8: case MEDIA_BUS_FMT_YVYU8_2X8: case MEDIA_BUS_FMT_UYVY8_2X8: case MEDIA_BUS_FMT_VYUY8_2X8: case MEDIA_BUS_FMT_RGB565_2X8_LE: case MEDIA_BUS_FMT_RGB565_2X8_BE: return 16; case MEDIA_BUS_FMT_BGR888_1X24: return 24; default: return 0; } } static u8 data_type_from_code(__u32 code) { switch (code) { case MEDIA_BUS_FMT_SBGGR8_1X8: case MEDIA_BUS_FMT_SGBRG8_1X8: case MEDIA_BUS_FMT_SGRBG8_1X8: case MEDIA_BUS_FMT_SRGGB8_1X8: return 0x2a; case MEDIA_BUS_FMT_SBGGR10_1X10: case MEDIA_BUS_FMT_SGBRG10_1X10: case MEDIA_BUS_FMT_SGRBG10_1X10: case MEDIA_BUS_FMT_SRGGB10_1X10: return 0x2b; case MEDIA_BUS_FMT_SBGGR12_1X12: case MEDIA_BUS_FMT_SGBRG12_1X12: case MEDIA_BUS_FMT_SGRBG12_1X12: case MEDIA_BUS_FMT_SRGGB12_1X12: return 0x2c; case MEDIA_BUS_FMT_YUYV8_1X16: case MEDIA_BUS_FMT_YVYU8_1X16: case MEDIA_BUS_FMT_UYVY8_1X16: case MEDIA_BUS_FMT_VYUY8_1X16: case MEDIA_BUS_FMT_YUYV8_2X8: case MEDIA_BUS_FMT_YVYU8_2X8: case MEDIA_BUS_FMT_UYVY8_2X8: case MEDIA_BUS_FMT_VYUY8_2X8: return 0x1e; case MEDIA_BUS_FMT_BGR888_1X24: return 0x24; case MEDIA_BUS_FMT_RGB565_1X16: case MEDIA_BUS_FMT_RGB565_2X8_LE: case MEDIA_BUS_FMT_RGB565_2X8_BE: return 0x22; default: return 0; } } static void init_format(struct v4l2_mbus_framefmt *fmt) { fmt->code = MEDIA_BUS_FMT_SBGGR8_1X8; fmt->field = V4L2_FIELD_NONE; fmt->colorspace = V4L2_COLORSPACE_SRGB; fmt->ycbcr_enc = V4L2_MAP_YCBCR_ENC_DEFAULT(V4L2_COLORSPACE_SRGB); fmt->quantization = V4L2_QUANTIZATION_FULL_RANGE; fmt->xfer_func = V4L2_MAP_XFER_FUNC_DEFAULT(V4L2_COLORSPACE_SRGB); fmt->width = 640; fmt->height = 480; } static __u32 get_fmt_code(__u32 code) { unsigned int i; for (i = 0; i < ARRAY_SIZE(mipid02_supported_fmt_codes); i++) { if (code == mipid02_supported_fmt_codes[i]) return code; } return mipid02_supported_fmt_codes[0]; } static __u32 serial_to_parallel_code(__u32 serial) { if (serial == MEDIA_BUS_FMT_RGB565_1X16) return MEDIA_BUS_FMT_RGB565_2X8_LE; if (serial == MEDIA_BUS_FMT_YUYV8_1X16) return MEDIA_BUS_FMT_YUYV8_2X8; if (serial == MEDIA_BUS_FMT_YVYU8_1X16) return MEDIA_BUS_FMT_YVYU8_2X8; if (serial == MEDIA_BUS_FMT_UYVY8_1X16) return MEDIA_BUS_FMT_UYVY8_2X8; if (serial == MEDIA_BUS_FMT_VYUY8_1X16) return MEDIA_BUS_FMT_VYUY8_2X8; if (serial == MEDIA_BUS_FMT_BGR888_1X24) return MEDIA_BUS_FMT_BGR888_3X8; return serial; } static inline struct mipid02_dev *to_mipid02_dev(struct v4l2_subdev *sd) { return container_of(sd, struct mipid02_dev, sd); } static int mipid02_read_reg(struct mipid02_dev *bridge, u16 reg, u8 *val) { struct i2c_client *client = bridge->i2c_client; struct i2c_msg msg[2]; u8 buf[2]; int ret; buf[0] = reg >> 8; buf[1] = reg & 0xff; msg[0].addr = client->addr; msg[0].flags = client->flags; msg[0].buf = buf; msg[0].len = sizeof(buf); msg[1].addr = client->addr; msg[1].flags = client->flags | I2C_M_RD; msg[1].buf = val; msg[1].len = 1; ret = i2c_transfer(client->adapter, msg, 2); if (ret < 0) { dev_dbg(&client->dev, "%s: %x i2c_transfer, reg: %x => %d\n", __func__, client->addr, reg, ret); return ret; } return 0; } static int mipid02_write_reg(struct mipid02_dev *bridge, u16 reg, u8 val) { struct i2c_client *client = bridge->i2c_client; struct i2c_msg msg; u8 buf[3]; int ret; buf[0] = reg >> 8; buf[1] = reg & 0xff; buf[2] = val; msg.addr = client->addr; msg.flags = client->flags; msg.buf = buf; msg.len = sizeof(buf); ret = i2c_transfer(client->adapter, &msg, 1); if (ret < 0) { dev_dbg(&client->dev, "%s: i2c_transfer, reg: %x => %d\n", __func__, reg, ret); return ret; } return 0; } static int mipid02_get_regulators(struct mipid02_dev *bridge) { unsigned int i; for (i = 0; i < MIPID02_NUM_SUPPLIES; i++) bridge->supplies[i].supply = mipid02_supply_name[i]; return devm_regulator_bulk_get(&bridge->i2c_client->dev, MIPID02_NUM_SUPPLIES, bridge->supplies); } static void mipid02_apply_reset(struct mipid02_dev *bridge) { gpiod_set_value_cansleep(bridge->reset_gpio, 0); usleep_range(5000, 10000); gpiod_set_value_cansleep(bridge->reset_gpio, 1); usleep_range(5000, 10000); gpiod_set_value_cansleep(bridge->reset_gpio, 0); usleep_range(5000, 10000); } static int mipid02_set_power_on(struct mipid02_dev *bridge) { struct i2c_client *client = bridge->i2c_client; int ret; ret = clk_prepare_enable(bridge->xclk); if (ret) { dev_err(&client->dev, "%s: failed to enable clock\n", __func__); return ret; } ret = regulator_bulk_enable(MIPID02_NUM_SUPPLIES, bridge->supplies); if (ret) { dev_err(&client->dev, "%s: failed to enable regulators\n", __func__); goto xclk_off; } if (bridge->reset_gpio) { dev_dbg(&client->dev, "apply reset"); mipid02_apply_reset(bridge); } else { dev_dbg(&client->dev, "don't apply reset"); usleep_range(5000, 10000); } return 0; xclk_off: clk_disable_unprepare(bridge->xclk); return ret; } static void mipid02_set_power_off(struct mipid02_dev *bridge) { regulator_bulk_disable(MIPID02_NUM_SUPPLIES, bridge->supplies); clk_disable_unprepare(bridge->xclk); } static int mipid02_detect(struct mipid02_dev *bridge) { u8 reg; /* * There is no version registers. Just try to read register * MIPID02_CLK_LANE_WR_REG1. */ return mipid02_read_reg(bridge, MIPID02_CLK_LANE_WR_REG1, &reg); } static u32 mipid02_get_link_freq_from_cid_link_freq(struct mipid02_dev *bridge, struct v4l2_subdev *subdev) { struct v4l2_querymenu qm = {.id = V4L2_CID_LINK_FREQ, }; struct v4l2_ctrl *ctrl; int ret; ctrl = v4l2_ctrl_find(subdev->ctrl_handler, V4L2_CID_LINK_FREQ); if (!ctrl) return 0; qm.index = v4l2_ctrl_g_ctrl(ctrl); ret = v4l2_querymenu(subdev->ctrl_handler, &qm); if (ret) return 0; return qm.value; } static u32 mipid02_get_link_freq_from_cid_pixel_rate(struct mipid02_dev *bridge, struct v4l2_subdev *subdev) { struct v4l2_fwnode_endpoint *ep = &bridge->rx; struct v4l2_ctrl *ctrl; u32 pixel_clock; u32 bpp = bpp_from_code(bridge->fmt.code); ctrl = v4l2_ctrl_find(subdev->ctrl_handler, V4L2_CID_PIXEL_RATE); if (!ctrl) return 0; pixel_clock = v4l2_ctrl_g_ctrl_int64(ctrl); return pixel_clock * bpp / (2 * ep->bus.mipi_csi2.num_data_lanes); } /* * We need to know link frequency to setup clk_lane_reg1 timings. Link frequency * will be computed using connected device V4L2_CID_PIXEL_RATE, bit per pixel * and number of lanes. */ static int mipid02_configure_from_rx_speed(struct mipid02_dev *bridge) { struct i2c_client *client = bridge->i2c_client; struct v4l2_subdev *subdev = bridge->s_subdev; u32 link_freq; link_freq = mipid02_get_link_freq_from_cid_link_freq(bridge, subdev); if (!link_freq) { link_freq = mipid02_get_link_freq_from_cid_pixel_rate(bridge, subdev); if (!link_freq) { dev_err(&client->dev, "Failed to get link frequency"); return -EINVAL; } } dev_dbg(&client->dev, "detect link_freq = %d Hz", link_freq); bridge->r.clk_lane_reg1 |= (2000000000 / link_freq) << 2; return 0; } static int mipid02_configure_clk_lane(struct mipid02_dev *bridge) { struct i2c_client *client = bridge->i2c_client; struct v4l2_fwnode_endpoint *ep = &bridge->rx; bool *polarities = ep->bus.mipi_csi2.lane_polarities; /* midid02 doesn't support clock lane remapping */ if (ep->bus.mipi_csi2.clock_lane != 0) { dev_err(&client->dev, "clk lane must be map to lane 0\n"); return -EINVAL; } bridge->r.clk_lane_reg1 |= (polarities[0] << 1) | CLK_ENABLE; return 0; } static int mipid02_configure_data0_lane(struct mipid02_dev *bridge, int nb, bool are_lanes_swap, bool *polarities) { bool are_pin_swap = are_lanes_swap ? polarities[2] : polarities[1]; if (nb == 1 && are_lanes_swap) return 0; /* * data lane 0 as pin swap polarity reversed compared to clock and * data lane 1 */ if (!are_pin_swap) bridge->r.data_lane0_reg1 = 1 << 1; bridge->r.data_lane0_reg1 |= DATA_ENABLE; return 0; } static int mipid02_configure_data1_lane(struct mipid02_dev *bridge, int nb, bool are_lanes_swap, bool *polarities) { bool are_pin_swap = are_lanes_swap ? polarities[1] : polarities[2]; if (nb == 1 && !are_lanes_swap) return 0; if (are_pin_swap) bridge->r.data_lane1_reg1 = 1 << 1; bridge->r.data_lane1_reg1 |= DATA_ENABLE; return 0; } static int mipid02_configure_from_rx(struct mipid02_dev *bridge) { struct v4l2_fwnode_endpoint *ep = &bridge->rx; bool are_lanes_swap = ep->bus.mipi_csi2.data_lanes[0] == 2; bool *polarities = ep->bus.mipi_csi2.lane_polarities; int nb = ep->bus.mipi_csi2.num_data_lanes; int ret; ret = mipid02_configure_clk_lane(bridge); if (ret) return ret; ret = mipid02_configure_data0_lane(bridge, nb, are_lanes_swap, polarities); if (ret) return ret; ret = mipid02_configure_data1_lane(bridge, nb, are_lanes_swap, polarities); if (ret) return ret; bridge->r.mode_reg1 |= are_lanes_swap ? MODE_DATA_SWAP : 0; bridge->r.mode_reg1 |= (nb - 1) << 1; return mipid02_configure_from_rx_speed(bridge); } static int mipid02_configure_from_tx(struct mipid02_dev *bridge) { struct v4l2_fwnode_endpoint *ep = &bridge->tx; bridge->r.data_selection_ctrl = SELECTION_MANUAL_WIDTH; bridge->r.pix_width_ctrl = ep->bus.parallel.bus_width; bridge->r.pix_width_ctrl_emb = ep->bus.parallel.bus_width; if (ep->bus.parallel.flags & V4L2_MBUS_HSYNC_ACTIVE_HIGH) bridge->r.mode_reg2 |= MODE_HSYNC_ACTIVE_HIGH; if (ep->bus.parallel.flags & V4L2_MBUS_VSYNC_ACTIVE_HIGH) bridge->r.mode_reg2 |= MODE_VSYNC_ACTIVE_HIGH; if (ep->bus.parallel.flags & V4L2_MBUS_PCLK_SAMPLE_RISING) bridge->r.mode_reg2 |= MODE_PCLK_SAMPLE_RISING; return 0; } static int mipid02_configure_from_code(struct mipid02_dev *bridge) { u8 data_type; bridge->r.data_id_rreg = 0; if (bridge->fmt.code != MEDIA_BUS_FMT_JPEG_1X8) { bridge->r.data_selection_ctrl |= SELECTION_MANUAL_DATA; data_type = data_type_from_code(bridge->fmt.code); if (!data_type) return -EINVAL; bridge->r.data_id_rreg = data_type; } return 0; } static int mipid02_stream_disable(struct mipid02_dev *bridge) { struct i2c_client *client = bridge->i2c_client; int ret = -EINVAL; if (!bridge->s_subdev) goto error; ret = v4l2_subdev_call(bridge->s_subdev, video, s_stream, 0); if (ret) goto error; /* Disable all lanes */ ret = mipid02_write_reg(bridge, MIPID02_CLK_LANE_REG1, 0); if (ret) goto error; ret = mipid02_write_reg(bridge, MIPID02_DATA_LANE0_REG1, 0); if (ret) goto error; ret = mipid02_write_reg(bridge, MIPID02_DATA_LANE1_REG1, 0); if (ret) goto error; error: if (ret) dev_err(&client->dev, "failed to stream off %d", ret); return ret; } static int mipid02_stream_enable(struct mipid02_dev *bridge) { struct i2c_client *client = bridge->i2c_client; int ret = -EINVAL; if (!bridge->s_subdev) goto error; memset(&bridge->r, 0, sizeof(bridge->r)); /* build registers content */ ret = mipid02_configure_from_rx(bridge); if (ret) goto error; ret = mipid02_configure_from_tx(bridge); if (ret) goto error; ret = mipid02_configure_from_code(bridge); if (ret) goto error; /* write mipi registers */ ret = mipid02_write_reg(bridge, MIPID02_CLK_LANE_REG1, bridge->r.clk_lane_reg1); if (ret) goto error; ret = mipid02_write_reg(bridge, MIPID02_CLK_LANE_REG3, CLK_MIPI_CSI); if (ret) goto error; ret = mipid02_write_reg(bridge, MIPID02_DATA_LANE0_REG1, bridge->r.data_lane0_reg1); if (ret) goto error; ret = mipid02_write_reg(bridge, MIPID02_DATA_LANE0_REG2, DATA_MIPI_CSI); if (ret) goto error; ret = mipid02_write_reg(bridge, MIPID02_DATA_LANE1_REG1, bridge->r.data_lane1_reg1); if (ret) goto error; ret = mipid02_write_reg(bridge, MIPID02_DATA_LANE1_REG2, DATA_MIPI_CSI); if (ret) goto error; ret = mipid02_write_reg(bridge, MIPID02_MODE_REG1, MODE_NO_BYPASS | bridge->r.mode_reg1); if (ret) goto error; ret = mipid02_write_reg(bridge, MIPID02_MODE_REG2, bridge->r.mode_reg2); if (ret) goto error; ret = mipid02_write_reg(bridge, MIPID02_DATA_ID_RREG, bridge->r.data_id_rreg); if (ret) goto error; ret = mipid02_write_reg(bridge, MIPID02_DATA_SELECTION_CTRL, bridge->r.data_selection_ctrl); if (ret) goto error; ret = mipid02_write_reg(bridge, MIPID02_PIX_WIDTH_CTRL, bridge->r.pix_width_ctrl); if (ret) goto error; ret = mipid02_write_reg(bridge, MIPID02_PIX_WIDTH_CTRL_EMB, bridge->r.pix_width_ctrl_emb); if (ret) goto error; ret = v4l2_subdev_call(bridge->s_subdev, video, s_stream, 1); if (ret) goto error; return 0; error: dev_err(&client->dev, "failed to stream on %d", ret); mipid02_stream_disable(bridge); return ret; } static int mipid02_s_stream(struct v4l2_subdev *sd, int enable) { struct mipid02_dev *bridge = to_mipid02_dev(sd); struct i2c_client *client = bridge->i2c_client; int ret = 0; dev_dbg(&client->dev, "%s : requested %d / current = %d", __func__, enable, bridge->streaming); mutex_lock(&bridge->lock); if (bridge->streaming == enable) goto out; ret = enable ? mipid02_stream_enable(bridge) : mipid02_stream_disable(bridge); if (!ret) bridge->streaming = enable; out: dev_dbg(&client->dev, "%s current now = %d / %d", __func__, bridge->streaming, ret); mutex_unlock(&bridge->lock); return ret; } static int mipid02_enum_mbus_code(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_mbus_code_enum *code) { struct mipid02_dev *bridge = to_mipid02_dev(sd); int ret = 0; switch (code->pad) { case MIPID02_SINK_0: if (code->index >= ARRAY_SIZE(mipid02_supported_fmt_codes)) ret = -EINVAL; else code->code = mipid02_supported_fmt_codes[code->index]; break; case MIPID02_SOURCE: if (code->index == 0) code->code = serial_to_parallel_code(bridge->fmt.code); else ret = -EINVAL; break; default: ret = -EINVAL; } return ret; } static int mipid02_get_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *format) { struct v4l2_mbus_framefmt *mbus_fmt = &format->format; struct mipid02_dev *bridge = to_mipid02_dev(sd); struct i2c_client *client = bridge->i2c_client; struct v4l2_mbus_framefmt *fmt; dev_dbg(&client->dev, "%s probe %d", __func__, format->pad); if (format->pad >= MIPID02_PAD_NB) return -EINVAL; /* second CSI-2 pad not yet supported */ if (format->pad == MIPID02_SINK_1) return -EINVAL; if (format->which == V4L2_SUBDEV_FORMAT_TRY) fmt = v4l2_subdev_get_try_format(&bridge->sd, sd_state, format->pad); else fmt = &bridge->fmt; mutex_lock(&bridge->lock); *mbus_fmt = *fmt; /* code may need to be converted for source */ if (format->pad == MIPID02_SOURCE) mbus_fmt->code = serial_to_parallel_code(mbus_fmt->code); mutex_unlock(&bridge->lock); return 0; } static void mipid02_set_fmt_source(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *format) { struct mipid02_dev *bridge = to_mipid02_dev(sd); /* source pad mirror sink pad */ if (format->which == V4L2_SUBDEV_FORMAT_ACTIVE) format->format = bridge->fmt; else format->format = *v4l2_subdev_get_try_format(sd, sd_state, MIPID02_SINK_0); /* but code may need to be converted */ format->format.code = serial_to_parallel_code(format->format.code); /* only apply format for V4L2_SUBDEV_FORMAT_TRY case */ if (format->which != V4L2_SUBDEV_FORMAT_TRY) return; *v4l2_subdev_get_try_format(sd, sd_state, MIPID02_SOURCE) = format->format; } static void mipid02_set_fmt_sink(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *format) { struct mipid02_dev *bridge = to_mipid02_dev(sd); struct v4l2_mbus_framefmt *fmt; format->format.code = get_fmt_code(format->format.code); if (format->which == V4L2_SUBDEV_FORMAT_TRY) fmt = v4l2_subdev_get_try_format(sd, sd_state, format->pad); else fmt = &bridge->fmt; *fmt = format->format; /* Propagate the format change to the source pad */ mipid02_set_fmt_source(sd, sd_state, format); } static int mipid02_set_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *format) { struct mipid02_dev *bridge = to_mipid02_dev(sd); struct i2c_client *client = bridge->i2c_client; int ret = 0; dev_dbg(&client->dev, "%s for %d", __func__, format->pad); if (format->pad >= MIPID02_PAD_NB) return -EINVAL; /* second CSI-2 pad not yet supported */ if (format->pad == MIPID02_SINK_1) return -EINVAL; mutex_lock(&bridge->lock); if (bridge->streaming) { ret = -EBUSY; goto error; } if (format->pad == MIPID02_SOURCE) mipid02_set_fmt_source(sd, sd_state, format); else mipid02_set_fmt_sink(sd, sd_state, format); error: mutex_unlock(&bridge->lock); return ret; } static const struct v4l2_subdev_video_ops mipid02_video_ops = { .s_stream = mipid02_s_stream, }; static const struct v4l2_subdev_pad_ops mipid02_pad_ops = { .enum_mbus_code = mipid02_enum_mbus_code, .get_fmt = mipid02_get_fmt, .set_fmt = mipid02_set_fmt, }; static const struct v4l2_subdev_ops mipid02_subdev_ops = { .video = &mipid02_video_ops, .pad = &mipid02_pad_ops, }; static const struct media_entity_operations mipid02_subdev_entity_ops = { .link_validate = v4l2_subdev_link_validate, }; static int mipid02_async_bound(struct v4l2_async_notifier *notifier, struct v4l2_subdev *s_subdev, struct v4l2_async_connection *asd) { struct mipid02_dev *bridge = to_mipid02_dev(notifier->sd); struct i2c_client *client = bridge->i2c_client; int source_pad; int ret; dev_dbg(&client->dev, "sensor_async_bound call %p", s_subdev); source_pad = media_entity_get_fwnode_pad(&s_subdev->entity, s_subdev->fwnode, MEDIA_PAD_FL_SOURCE); if (source_pad < 0) { dev_err(&client->dev, "Couldn't find output pad for subdev %s\n", s_subdev->name); return source_pad; } ret = media_create_pad_link(&s_subdev->entity, source_pad, &bridge->sd.entity, 0, MEDIA_LNK_FL_ENABLED | MEDIA_LNK_FL_IMMUTABLE); if (ret) { dev_err(&client->dev, "Couldn't create media link %d", ret); return ret; } bridge->s_subdev = s_subdev; return 0; } static void mipid02_async_unbind(struct v4l2_async_notifier *notifier, struct v4l2_subdev *s_subdev, struct v4l2_async_connection *asd) { struct mipid02_dev *bridge = to_mipid02_dev(notifier->sd); bridge->s_subdev = NULL; } static const struct v4l2_async_notifier_operations mipid02_notifier_ops = { .bound = mipid02_async_bound, .unbind = mipid02_async_unbind, }; static int mipid02_parse_rx_ep(struct mipid02_dev *bridge) { struct v4l2_fwnode_endpoint ep = { .bus_type = V4L2_MBUS_CSI2_DPHY }; struct i2c_client *client = bridge->i2c_client; struct v4l2_async_connection *asd; struct device_node *ep_node; int ret; /* parse rx (endpoint 0) */ ep_node = of_graph_get_endpoint_by_regs(bridge->i2c_client->dev.of_node, 0, 0); if (!ep_node) { dev_err(&client->dev, "unable to find port0 ep"); ret = -EINVAL; goto error; } ret = v4l2_fwnode_endpoint_parse(of_fwnode_handle(ep_node), &ep); if (ret) { dev_err(&client->dev, "Could not parse v4l2 endpoint %d\n", ret); goto error_of_node_put; } /* do some sanity checks */ if (ep.bus.mipi_csi2.num_data_lanes > 2) { dev_err(&client->dev, "max supported data lanes is 2 / got %d", ep.bus.mipi_csi2.num_data_lanes); ret = -EINVAL; goto error_of_node_put; } /* register it for later use */ bridge->rx = ep; /* register async notifier so we get noticed when sensor is connected */ v4l2_async_subdev_nf_init(&bridge->notifier, &bridge->sd); asd = v4l2_async_nf_add_fwnode_remote(&bridge->notifier, of_fwnode_handle(ep_node), struct v4l2_async_connection); of_node_put(ep_node); if (IS_ERR(asd)) { dev_err(&client->dev, "fail to register asd to notifier %ld", PTR_ERR(asd)); return PTR_ERR(asd); } bridge->notifier.ops = &mipid02_notifier_ops; ret = v4l2_async_nf_register(&bridge->notifier); if (ret) v4l2_async_nf_cleanup(&bridge->notifier); return ret; error_of_node_put: of_node_put(ep_node); error: return ret; } static int mipid02_parse_tx_ep(struct mipid02_dev *bridge) { struct v4l2_fwnode_endpoint ep = { .bus_type = V4L2_MBUS_PARALLEL }; struct i2c_client *client = bridge->i2c_client; struct device_node *ep_node; int ret; /* parse tx (endpoint 2) */ ep_node = of_graph_get_endpoint_by_regs(bridge->i2c_client->dev.of_node, 2, 0); if (!ep_node) { dev_err(&client->dev, "unable to find port1 ep"); ret = -EINVAL; goto error; } ret = v4l2_fwnode_endpoint_parse(of_fwnode_handle(ep_node), &ep); if (ret) { dev_err(&client->dev, "Could not parse v4l2 endpoint\n"); goto error_of_node_put; } of_node_put(ep_node); bridge->tx = ep; return 0; error_of_node_put: of_node_put(ep_node); error: return -EINVAL; } static int mipid02_probe(struct i2c_client *client) { struct device *dev = &client->dev; struct mipid02_dev *bridge; u32 clk_freq; int ret; bridge = devm_kzalloc(dev, sizeof(*bridge), GFP_KERNEL); if (!bridge) return -ENOMEM; init_format(&bridge->fmt); bridge->i2c_client = client; v4l2_i2c_subdev_init(&bridge->sd, client, &mipid02_subdev_ops); /* got and check clock */ bridge->xclk = devm_clk_get(dev, "xclk"); if (IS_ERR(bridge->xclk)) { dev_err(dev, "failed to get xclk\n"); return PTR_ERR(bridge->xclk); } clk_freq = clk_get_rate(bridge->xclk); if (clk_freq < 6000000 || clk_freq > 27000000) { dev_err(dev, "xclk freq must be in 6-27 Mhz range. got %d Hz\n", clk_freq); return -EINVAL; } bridge->reset_gpio = devm_gpiod_get_optional(dev, "reset", GPIOD_OUT_HIGH); if (IS_ERR(bridge->reset_gpio)) { dev_err(dev, "failed to get reset GPIO\n"); return PTR_ERR(bridge->reset_gpio); } ret = mipid02_get_regulators(bridge); if (ret) { dev_err(dev, "failed to get regulators %d", ret); return ret; } mutex_init(&bridge->lock); bridge->sd.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE; bridge->sd.entity.function = MEDIA_ENT_F_VID_IF_BRIDGE; bridge->sd.entity.ops = &mipid02_subdev_entity_ops; bridge->pad[0].flags = MEDIA_PAD_FL_SINK; bridge->pad[1].flags = MEDIA_PAD_FL_SINK; bridge->pad[2].flags = MEDIA_PAD_FL_SOURCE; ret = media_entity_pads_init(&bridge->sd.entity, MIPID02_PAD_NB, bridge->pad); if (ret) { dev_err(&client->dev, "pads init failed %d", ret); goto mutex_cleanup; } /* enable clock, power and reset device if available */ ret = mipid02_set_power_on(bridge); if (ret) goto entity_cleanup; ret = mipid02_detect(bridge); if (ret) { dev_err(&client->dev, "failed to detect mipid02 %d", ret); goto power_off; } ret = mipid02_parse_tx_ep(bridge); if (ret) { dev_err(&client->dev, "failed to parse tx %d", ret); goto power_off; } ret = mipid02_parse_rx_ep(bridge); if (ret) { dev_err(&client->dev, "failed to parse rx %d", ret); goto power_off; } ret = v4l2_async_register_subdev(&bridge->sd); if (ret < 0) { dev_err(&client->dev, "v4l2_async_register_subdev failed %d", ret); goto unregister_notifier; } dev_info(&client->dev, "mipid02 device probe successfully"); return 0; unregister_notifier: v4l2_async_nf_unregister(&bridge->notifier); v4l2_async_nf_cleanup(&bridge->notifier); power_off: mipid02_set_power_off(bridge); entity_cleanup: media_entity_cleanup(&bridge->sd.entity); mutex_cleanup: mutex_destroy(&bridge->lock); return ret; } static void mipid02_remove(struct i2c_client *client) { struct v4l2_subdev *sd = i2c_get_clientdata(client); struct mipid02_dev *bridge = to_mipid02_dev(sd); v4l2_async_nf_unregister(&bridge->notifier); v4l2_async_nf_cleanup(&bridge->notifier); v4l2_async_unregister_subdev(&bridge->sd); mipid02_set_power_off(bridge); media_entity_cleanup(&bridge->sd.entity); mutex_destroy(&bridge->lock); } static const struct of_device_id mipid02_dt_ids[] = { { .compatible = "st,st-mipid02" }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(of, mipid02_dt_ids); static struct i2c_driver mipid02_i2c_driver = { .driver = { .name = "st-mipid02", .of_match_table = mipid02_dt_ids, }, .probe = mipid02_probe, .remove = mipid02_remove, }; module_i2c_driver(mipid02_i2c_driver); MODULE_AUTHOR("Mickael Guene <[email protected]>"); MODULE_DESCRIPTION("STMicroelectronics MIPID02 CSI-2 bridge driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/media/i2c/st-mipid02.c
// SPDX-License-Identifier: GPL-2.0-only /* * Driver for the Sony IMX415 CMOS Image Sensor. * * Copyright (C) 2023 WolfVision GmbH. */ #include <linux/clk.h> #include <linux/gpio/consumer.h> #include <linux/i2c.h> #include <linux/module.h> #include <linux/of.h> #include <linux/pm_runtime.h> #include <linux/regmap.h> #include <linux/regulator/consumer.h> #include <linux/slab.h> #include <linux/videodev2.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-fwnode.h> #include <media/v4l2-subdev.h> #define IMX415_PIXEL_ARRAY_TOP 0 #define IMX415_PIXEL_ARRAY_LEFT 0 #define IMX415_PIXEL_ARRAY_WIDTH 3864 #define IMX415_PIXEL_ARRAY_HEIGHT 2192 #define IMX415_PIXEL_ARRAY_VBLANK 58 #define IMX415_NUM_CLK_PARAM_REGS 11 #define IMX415_REG_8BIT(n) ((1 << 16) | (n)) #define IMX415_REG_16BIT(n) ((2 << 16) | (n)) #define IMX415_REG_24BIT(n) ((3 << 16) | (n)) #define IMX415_REG_SIZE_SHIFT 16 #define IMX415_REG_ADDR_MASK 0xffff #define IMX415_MODE IMX415_REG_8BIT(0x3000) #define IMX415_MODE_OPERATING (0) #define IMX415_MODE_STANDBY BIT(0) #define IMX415_REGHOLD IMX415_REG_8BIT(0x3001) #define IMX415_REGHOLD_INVALID (0) #define IMX415_REGHOLD_VALID BIT(0) #define IMX415_XMSTA IMX415_REG_8BIT(0x3002) #define IMX415_XMSTA_START (0) #define IMX415_XMSTA_STOP BIT(0) #define IMX415_BCWAIT_TIME IMX415_REG_16BIT(0x3008) #define IMX415_CPWAIT_TIME IMX415_REG_16BIT(0x300A) #define IMX415_WINMODE IMX415_REG_8BIT(0x301C) #define IMX415_ADDMODE IMX415_REG_8BIT(0x3022) #define IMX415_REVERSE IMX415_REG_8BIT(0x3030) #define IMX415_HREVERSE_SHIFT (0) #define IMX415_VREVERSE_SHIFT BIT(0) #define IMX415_ADBIT IMX415_REG_8BIT(0x3031) #define IMX415_MDBIT IMX415_REG_8BIT(0x3032) #define IMX415_SYS_MODE IMX415_REG_8BIT(0x3033) #define IMX415_OUTSEL IMX415_REG_8BIT(0x30C0) #define IMX415_DRV IMX415_REG_8BIT(0x30C1) #define IMX415_VMAX IMX415_REG_24BIT(0x3024) #define IMX415_HMAX IMX415_REG_16BIT(0x3028) #define IMX415_SHR0 IMX415_REG_24BIT(0x3050) #define IMX415_GAIN_PCG_0 IMX415_REG_16BIT(0x3090) #define IMX415_AGAIN_MIN 0 #define IMX415_AGAIN_MAX 100 #define IMX415_AGAIN_STEP 1 #define IMX415_BLKLEVEL IMX415_REG_16BIT(0x30E2) #define IMX415_BLKLEVEL_DEFAULT 50 #define IMX415_TPG_EN_DUOUT IMX415_REG_8BIT(0x30E4) #define IMX415_TPG_PATSEL_DUOUT IMX415_REG_8BIT(0x30E6) #define IMX415_TPG_COLORWIDTH IMX415_REG_8BIT(0x30E8) #define IMX415_TESTCLKEN_MIPI IMX415_REG_8BIT(0x3110) #define IMX415_INCKSEL1 IMX415_REG_8BIT(0x3115) #define IMX415_INCKSEL2 IMX415_REG_8BIT(0x3116) #define IMX415_INCKSEL3 IMX415_REG_16BIT(0x3118) #define IMX415_INCKSEL4 IMX415_REG_16BIT(0x311A) #define IMX415_INCKSEL5 IMX415_REG_8BIT(0x311E) #define IMX415_DIG_CLP_MODE IMX415_REG_8BIT(0x32C8) #define IMX415_WRJ_OPEN IMX415_REG_8BIT(0x3390) #define IMX415_SENSOR_INFO IMX415_REG_16BIT(0x3F12) #define IMX415_SENSOR_INFO_MASK 0xFFF #define IMX415_CHIP_ID 0x514 #define IMX415_LANEMODE IMX415_REG_16BIT(0x4001) #define IMX415_LANEMODE_2 1 #define IMX415_LANEMODE_4 3 #define IMX415_TXCLKESC_FREQ IMX415_REG_16BIT(0x4004) #define IMX415_INCKSEL6 IMX415_REG_8BIT(0x400C) #define IMX415_TCLKPOST IMX415_REG_16BIT(0x4018) #define IMX415_TCLKPREPARE IMX415_REG_16BIT(0x401A) #define IMX415_TCLKTRAIL IMX415_REG_16BIT(0x401C) #define IMX415_TCLKZERO IMX415_REG_16BIT(0x401E) #define IMX415_THSPREPARE IMX415_REG_16BIT(0x4020) #define IMX415_THSZERO IMX415_REG_16BIT(0x4022) #define IMX415_THSTRAIL IMX415_REG_16BIT(0x4024) #define IMX415_THSEXIT IMX415_REG_16BIT(0x4026) #define IMX415_TLPX IMX415_REG_16BIT(0x4028) #define IMX415_INCKSEL7 IMX415_REG_8BIT(0x4074) struct imx415_reg { u32 address; u32 val; }; static const char *const imx415_supply_names[] = { "dvdd", "ovdd", "avdd", }; /* * The IMX415 data sheet uses lane rates but v4l2 uses link frequency to * describe MIPI CSI-2 speed. This driver uses lane rates wherever possible * and converts them to link frequencies by a factor of two when needed. */ static const s64 link_freq_menu_items[] = { 594000000 / 2, 720000000 / 2, 891000000 / 2, 1440000000 / 2, 1485000000 / 2, }; struct imx415_clk_params { u64 lane_rate; u64 inck; struct imx415_reg regs[IMX415_NUM_CLK_PARAM_REGS]; }; /* INCK Settings - includes all lane rate and INCK dependent registers */ static const struct imx415_clk_params imx415_clk_params[] = { { .lane_rate = 594000000, .inck = 27000000, .regs[0] = { IMX415_BCWAIT_TIME, 0x05D }, .regs[1] = { IMX415_CPWAIT_TIME, 0x042 }, .regs[2] = { IMX415_SYS_MODE, 0x7 }, .regs[3] = { IMX415_INCKSEL1, 0x00 }, .regs[4] = { IMX415_INCKSEL2, 0x23 }, .regs[5] = { IMX415_INCKSEL3, 0x084 }, .regs[6] = { IMX415_INCKSEL4, 0x0E7 }, .regs[7] = { IMX415_INCKSEL5, 0x23 }, .regs[8] = { IMX415_INCKSEL6, 0x0 }, .regs[9] = { IMX415_INCKSEL7, 0x1 }, .regs[10] = { IMX415_TXCLKESC_FREQ, 0x06C0 }, }, { .lane_rate = 720000000, .inck = 24000000, .regs[0] = { IMX415_BCWAIT_TIME, 0x054 }, .regs[1] = { IMX415_CPWAIT_TIME, 0x03B }, .regs[2] = { IMX415_SYS_MODE, 0x9 }, .regs[3] = { IMX415_INCKSEL1, 0x00 }, .regs[4] = { IMX415_INCKSEL2, 0x23 }, .regs[5] = { IMX415_INCKSEL3, 0x0B4 }, .regs[6] = { IMX415_INCKSEL4, 0x0FC }, .regs[7] = { IMX415_INCKSEL5, 0x23 }, .regs[8] = { IMX415_INCKSEL6, 0x0 }, .regs[9] = { IMX415_INCKSEL7, 0x1 }, .regs[10] = { IMX415_TXCLKESC_FREQ, 0x0600 }, }, { .lane_rate = 891000000, .inck = 27000000, .regs[0] = { IMX415_BCWAIT_TIME, 0x05D }, .regs[1] = { IMX415_CPWAIT_TIME, 0x042 }, .regs[2] = { IMX415_SYS_MODE, 0x5 }, .regs[3] = { IMX415_INCKSEL1, 0x00 }, .regs[4] = { IMX415_INCKSEL2, 0x23 }, .regs[5] = { IMX415_INCKSEL3, 0x0C6 }, .regs[6] = { IMX415_INCKSEL4, 0x0E7 }, .regs[7] = { IMX415_INCKSEL5, 0x23 }, .regs[8] = { IMX415_INCKSEL6, 0x0 }, .regs[9] = { IMX415_INCKSEL7, 0x1 }, .regs[10] = { IMX415_TXCLKESC_FREQ, 0x06C0 }, }, { .lane_rate = 1440000000, .inck = 24000000, .regs[0] = { IMX415_BCWAIT_TIME, 0x054 }, .regs[1] = { IMX415_CPWAIT_TIME, 0x03B }, .regs[2] = { IMX415_SYS_MODE, 0x8 }, .regs[3] = { IMX415_INCKSEL1, 0x00 }, .regs[4] = { IMX415_INCKSEL2, 0x23 }, .regs[5] = { IMX415_INCKSEL3, 0x0B4 }, .regs[6] = { IMX415_INCKSEL4, 0x0FC }, .regs[7] = { IMX415_INCKSEL5, 0x23 }, .regs[8] = { IMX415_INCKSEL6, 0x1 }, .regs[9] = { IMX415_INCKSEL7, 0x0 }, .regs[10] = { IMX415_TXCLKESC_FREQ, 0x0600 }, }, { .lane_rate = 1485000000, .inck = 27000000, .regs[0] = { IMX415_BCWAIT_TIME, 0x05D }, .regs[1] = { IMX415_CPWAIT_TIME, 0x042 }, .regs[2] = { IMX415_SYS_MODE, 0x8 }, .regs[3] = { IMX415_INCKSEL1, 0x00 }, .regs[4] = { IMX415_INCKSEL2, 0x23 }, .regs[5] = { IMX415_INCKSEL3, 0x0A5 }, .regs[6] = { IMX415_INCKSEL4, 0x0E7 }, .regs[7] = { IMX415_INCKSEL5, 0x23 }, .regs[8] = { IMX415_INCKSEL6, 0x1 }, .regs[9] = { IMX415_INCKSEL7, 0x0 }, .regs[10] = { IMX415_TXCLKESC_FREQ, 0x06C0 }, }, }; /* all-pixel 2-lane 720 Mbps 15.74 Hz mode */ static const struct imx415_reg imx415_mode_2_720[] = { { IMX415_VMAX, 0x08CA }, { IMX415_HMAX, 0x07F0 }, { IMX415_LANEMODE, IMX415_LANEMODE_2 }, { IMX415_TCLKPOST, 0x006F }, { IMX415_TCLKPREPARE, 0x002F }, { IMX415_TCLKTRAIL, 0x002F }, { IMX415_TCLKZERO, 0x00BF }, { IMX415_THSPREPARE, 0x002F }, { IMX415_THSZERO, 0x0057 }, { IMX415_THSTRAIL, 0x002F }, { IMX415_THSEXIT, 0x004F }, { IMX415_TLPX, 0x0027 }, }; /* all-pixel 2-lane 1440 Mbps 30.01 Hz mode */ static const struct imx415_reg imx415_mode_2_1440[] = { { IMX415_VMAX, 0x08CA }, { IMX415_HMAX, 0x042A }, { IMX415_LANEMODE, IMX415_LANEMODE_2 }, { IMX415_TCLKPOST, 0x009F }, { IMX415_TCLKPREPARE, 0x0057 }, { IMX415_TCLKTRAIL, 0x0057 }, { IMX415_TCLKZERO, 0x0187 }, { IMX415_THSPREPARE, 0x005F }, { IMX415_THSZERO, 0x00A7 }, { IMX415_THSTRAIL, 0x005F }, { IMX415_THSEXIT, 0x0097 }, { IMX415_TLPX, 0x004F }, }; /* all-pixel 4-lane 891 Mbps 30 Hz mode */ static const struct imx415_reg imx415_mode_4_891[] = { { IMX415_VMAX, 0x08CA }, { IMX415_HMAX, 0x044C }, { IMX415_LANEMODE, IMX415_LANEMODE_4 }, { IMX415_TCLKPOST, 0x007F }, { IMX415_TCLKPREPARE, 0x0037 }, { IMX415_TCLKTRAIL, 0x0037 }, { IMX415_TCLKZERO, 0x00F7 }, { IMX415_THSPREPARE, 0x003F }, { IMX415_THSZERO, 0x006F }, { IMX415_THSTRAIL, 0x003F }, { IMX415_THSEXIT, 0x005F }, { IMX415_TLPX, 0x002F }, }; struct imx415_mode_reg_list { u32 num_of_regs; const struct imx415_reg *regs; }; /* * Mode : number of lanes, lane rate and frame rate dependent settings * * pixel_rate and hmax_pix are needed to calculate hblank for the v4l2 ctrl * interface. These values can not be found in the data sheet and should be * treated as virtual values. Use following table when adding new modes. * * lane_rate lanes fps hmax_pix pixel_rate * * 594 2 10.000 4400 99000000 * 891 2 15.000 4400 148500000 * 720 2 15.748 4064 144000000 * 1782 2 30.000 4400 297000000 * 2079 2 30.000 4400 297000000 * 1440 2 30.019 4510 304615385 * * 594 4 20.000 5500 247500000 * 594 4 25.000 4400 247500000 * 720 4 25.000 4400 247500000 * 720 4 30.019 4510 304615385 * 891 4 30.000 4400 297000000 * 1440 4 30.019 4510 304615385 * 1440 4 60.038 4510 609230769 * 1485 4 60.000 4400 594000000 * 1782 4 60.000 4400 594000000 * 2079 4 60.000 4400 594000000 * 2376 4 90.164 4392 891000000 */ struct imx415_mode { u64 lane_rate; u32 lanes; u32 hmax_pix; u64 pixel_rate; struct imx415_mode_reg_list reg_list; }; /* mode configs */ static const struct imx415_mode supported_modes[] = { { .lane_rate = 720000000, .lanes = 2, .hmax_pix = 4064, .pixel_rate = 144000000, .reg_list = { .num_of_regs = ARRAY_SIZE(imx415_mode_2_720), .regs = imx415_mode_2_720, }, }, { .lane_rate = 1440000000, .lanes = 2, .hmax_pix = 4510, .pixel_rate = 304615385, .reg_list = { .num_of_regs = ARRAY_SIZE(imx415_mode_2_1440), .regs = imx415_mode_2_1440, }, }, { .lane_rate = 891000000, .lanes = 4, .hmax_pix = 4400, .pixel_rate = 297000000, .reg_list = { .num_of_regs = ARRAY_SIZE(imx415_mode_4_891), .regs = imx415_mode_4_891, }, }, }; static const struct regmap_config imx415_regmap_config = { .reg_bits = 16, .val_bits = 8, }; static const char *const imx415_test_pattern_menu[] = { "disabled", "solid black", "solid white", "solid dark gray", "solid light gray", "stripes light/dark grey", "stripes dark/light grey", "stripes black/dark grey", "stripes dark grey/black", "stripes black/white", "stripes white/black", "horizontal color bar", "vertical color bar", }; struct imx415 { struct device *dev; struct clk *clk; struct regulator_bulk_data supplies[ARRAY_SIZE(imx415_supply_names)]; struct gpio_desc *reset; struct regmap *regmap; const struct imx415_clk_params *clk_params; bool streaming; struct v4l2_subdev subdev; struct media_pad pad; struct v4l2_ctrl_handler ctrls; struct v4l2_ctrl *vblank; struct v4l2_ctrl *hflip; struct v4l2_ctrl *vflip; unsigned int cur_mode; unsigned int num_data_lanes; }; /* * This table includes fixed register settings and a bunch of undocumented * registers that have to be set to another value than default. */ static const struct imx415_reg imx415_init_table[] = { /* use all-pixel readout mode, no flip */ { IMX415_WINMODE, 0x00 }, { IMX415_ADDMODE, 0x00 }, { IMX415_REVERSE, 0x00 }, /* use RAW 10-bit mode */ { IMX415_ADBIT, 0x00 }, { IMX415_MDBIT, 0x00 }, /* output VSYNC on XVS and low on XHS */ { IMX415_OUTSEL, 0x22 }, { IMX415_DRV, 0x00 }, /* SONY magic registers */ { IMX415_REG_8BIT(0x32D4), 0x21 }, { IMX415_REG_8BIT(0x32EC), 0xA1 }, { IMX415_REG_8BIT(0x3452), 0x7F }, { IMX415_REG_8BIT(0x3453), 0x03 }, { IMX415_REG_8BIT(0x358A), 0x04 }, { IMX415_REG_8BIT(0x35A1), 0x02 }, { IMX415_REG_8BIT(0x36BC), 0x0C }, { IMX415_REG_8BIT(0x36CC), 0x53 }, { IMX415_REG_8BIT(0x36CD), 0x00 }, { IMX415_REG_8BIT(0x36CE), 0x3C }, { IMX415_REG_8BIT(0x36D0), 0x8C }, { IMX415_REG_8BIT(0x36D1), 0x00 }, { IMX415_REG_8BIT(0x36D2), 0x71 }, { IMX415_REG_8BIT(0x36D4), 0x3C }, { IMX415_REG_8BIT(0x36D6), 0x53 }, { IMX415_REG_8BIT(0x36D7), 0x00 }, { IMX415_REG_8BIT(0x36D8), 0x71 }, { IMX415_REG_8BIT(0x36DA), 0x8C }, { IMX415_REG_8BIT(0x36DB), 0x00 }, { IMX415_REG_8BIT(0x3724), 0x02 }, { IMX415_REG_8BIT(0x3726), 0x02 }, { IMX415_REG_8BIT(0x3732), 0x02 }, { IMX415_REG_8BIT(0x3734), 0x03 }, { IMX415_REG_8BIT(0x3736), 0x03 }, { IMX415_REG_8BIT(0x3742), 0x03 }, { IMX415_REG_8BIT(0x3862), 0xE0 }, { IMX415_REG_8BIT(0x38CC), 0x30 }, { IMX415_REG_8BIT(0x38CD), 0x2F }, { IMX415_REG_8BIT(0x395C), 0x0C }, { IMX415_REG_8BIT(0x3A42), 0xD1 }, { IMX415_REG_8BIT(0x3A4C), 0x77 }, { IMX415_REG_8BIT(0x3AE0), 0x02 }, { IMX415_REG_8BIT(0x3AEC), 0x0C }, { IMX415_REG_8BIT(0x3B00), 0x2E }, { IMX415_REG_8BIT(0x3B06), 0x29 }, { IMX415_REG_8BIT(0x3B98), 0x25 }, { IMX415_REG_8BIT(0x3B99), 0x21 }, { IMX415_REG_8BIT(0x3B9B), 0x13 }, { IMX415_REG_8BIT(0x3B9C), 0x13 }, { IMX415_REG_8BIT(0x3B9D), 0x13 }, { IMX415_REG_8BIT(0x3B9E), 0x13 }, { IMX415_REG_8BIT(0x3BA1), 0x00 }, { IMX415_REG_8BIT(0x3BA2), 0x06 }, { IMX415_REG_8BIT(0x3BA3), 0x0B }, { IMX415_REG_8BIT(0x3BA4), 0x10 }, { IMX415_REG_8BIT(0x3BA5), 0x14 }, { IMX415_REG_8BIT(0x3BA6), 0x18 }, { IMX415_REG_8BIT(0x3BA7), 0x1A }, { IMX415_REG_8BIT(0x3BA8), 0x1A }, { IMX415_REG_8BIT(0x3BA9), 0x1A }, { IMX415_REG_8BIT(0x3BAC), 0xED }, { IMX415_REG_8BIT(0x3BAD), 0x01 }, { IMX415_REG_8BIT(0x3BAE), 0xF6 }, { IMX415_REG_8BIT(0x3BAF), 0x02 }, { IMX415_REG_8BIT(0x3BB0), 0xA2 }, { IMX415_REG_8BIT(0x3BB1), 0x03 }, { IMX415_REG_8BIT(0x3BB2), 0xE0 }, { IMX415_REG_8BIT(0x3BB3), 0x03 }, { IMX415_REG_8BIT(0x3BB4), 0xE0 }, { IMX415_REG_8BIT(0x3BB5), 0x03 }, { IMX415_REG_8BIT(0x3BB6), 0xE0 }, { IMX415_REG_8BIT(0x3BB7), 0x03 }, { IMX415_REG_8BIT(0x3BB8), 0xE0 }, { IMX415_REG_8BIT(0x3BBA), 0xE0 }, { IMX415_REG_8BIT(0x3BBC), 0xDA }, { IMX415_REG_8BIT(0x3BBE), 0x88 }, { IMX415_REG_8BIT(0x3BC0), 0x44 }, { IMX415_REG_8BIT(0x3BC2), 0x7B }, { IMX415_REG_8BIT(0x3BC4), 0xA2 }, { IMX415_REG_8BIT(0x3BC8), 0xBD }, { IMX415_REG_8BIT(0x3BCA), 0xBD }, }; static inline struct imx415 *to_imx415(struct v4l2_subdev *sd) { return container_of(sd, struct imx415, subdev); } static int imx415_read(struct imx415 *sensor, u32 addr) { u8 data[3] = { 0 }; int ret; ret = regmap_raw_read(sensor->regmap, addr & IMX415_REG_ADDR_MASK, data, (addr >> IMX415_REG_SIZE_SHIFT) & 3); if (ret < 0) return ret; return (data[2] << 16) | (data[1] << 8) | data[0]; } static int imx415_write(struct imx415 *sensor, u32 addr, u32 value) { u8 data[3] = { value & 0xff, (value >> 8) & 0xff, value >> 16 }; int ret; ret = regmap_raw_write(sensor->regmap, addr & IMX415_REG_ADDR_MASK, data, (addr >> IMX415_REG_SIZE_SHIFT) & 3); if (ret < 0) dev_err_ratelimited(sensor->dev, "%u-bit write to 0x%04x failed: %d\n", ((addr >> IMX415_REG_SIZE_SHIFT) & 3) * 8, addr & IMX415_REG_ADDR_MASK, ret); return 0; } static int imx415_set_testpattern(struct imx415 *sensor, int val) { int ret; if (val) { ret = imx415_write(sensor, IMX415_BLKLEVEL, 0x00); if (ret) return ret; ret = imx415_write(sensor, IMX415_TPG_EN_DUOUT, 0x01); if (ret) return ret; ret = imx415_write(sensor, IMX415_TPG_PATSEL_DUOUT, val - 1); if (ret) return ret; ret = imx415_write(sensor, IMX415_TPG_COLORWIDTH, 0x01); if (ret) return ret; ret = imx415_write(sensor, IMX415_TESTCLKEN_MIPI, 0x20); if (ret) return ret; ret = imx415_write(sensor, IMX415_DIG_CLP_MODE, 0x00); if (ret) return ret; ret = imx415_write(sensor, IMX415_WRJ_OPEN, 0x00); } else { ret = imx415_write(sensor, IMX415_BLKLEVEL, IMX415_BLKLEVEL_DEFAULT); if (ret) return ret; ret = imx415_write(sensor, IMX415_TPG_EN_DUOUT, 0x00); if (ret) return ret; ret = imx415_write(sensor, IMX415_TESTCLKEN_MIPI, 0x00); if (ret) return ret; ret = imx415_write(sensor, IMX415_DIG_CLP_MODE, 0x01); if (ret) return ret; ret = imx415_write(sensor, IMX415_WRJ_OPEN, 0x01); } return 0; } static int imx415_s_ctrl(struct v4l2_ctrl *ctrl) { struct imx415 *sensor = container_of(ctrl->handler, struct imx415, ctrls); const struct v4l2_mbus_framefmt *format; struct v4l2_subdev_state *state; unsigned int vmax; unsigned int flip; if (!sensor->streaming) return 0; state = v4l2_subdev_get_locked_active_state(&sensor->subdev); format = v4l2_subdev_get_pad_format(&sensor->subdev, state, 0); switch (ctrl->id) { case V4L2_CID_EXPOSURE: /* clamp the exposure value to VMAX. */ vmax = format->height + sensor->vblank->cur.val; ctrl->val = min_t(int, ctrl->val, vmax); return imx415_write(sensor, IMX415_SHR0, vmax - ctrl->val); case V4L2_CID_ANALOGUE_GAIN: /* analogue gain in 0.3 dB step size */ return imx415_write(sensor, IMX415_GAIN_PCG_0, ctrl->val); case V4L2_CID_HFLIP: case V4L2_CID_VFLIP: flip = (sensor->hflip->val << IMX415_HREVERSE_SHIFT) | (sensor->vflip->val << IMX415_VREVERSE_SHIFT); return imx415_write(sensor, IMX415_REVERSE, flip); case V4L2_CID_TEST_PATTERN: return imx415_set_testpattern(sensor, ctrl->val); default: return -EINVAL; } } static const struct v4l2_ctrl_ops imx415_ctrl_ops = { .s_ctrl = imx415_s_ctrl, }; static int imx415_ctrls_init(struct imx415 *sensor) { struct v4l2_fwnode_device_properties props; struct v4l2_ctrl *ctrl; u64 pixel_rate = supported_modes[sensor->cur_mode].pixel_rate; u64 lane_rate = supported_modes[sensor->cur_mode].lane_rate; u32 exposure_max = IMX415_PIXEL_ARRAY_HEIGHT + IMX415_PIXEL_ARRAY_VBLANK - 8; u32 hblank; unsigned int i; int ret; ret = v4l2_fwnode_device_parse(sensor->dev, &props); if (ret < 0) return ret; v4l2_ctrl_handler_init(&sensor->ctrls, 10); for (i = 0; i < ARRAY_SIZE(link_freq_menu_items); ++i) { if (lane_rate == link_freq_menu_items[i] * 2) break; } if (i == ARRAY_SIZE(link_freq_menu_items)) { return dev_err_probe(sensor->dev, -EINVAL, "lane rate %llu not supported\n", lane_rate); } ctrl = v4l2_ctrl_new_int_menu(&sensor->ctrls, &imx415_ctrl_ops, V4L2_CID_LINK_FREQ, ARRAY_SIZE(link_freq_menu_items) - 1, i, link_freq_menu_items); if (ctrl) ctrl->flags |= V4L2_CTRL_FLAG_READ_ONLY; v4l2_ctrl_new_std(&sensor->ctrls, &imx415_ctrl_ops, V4L2_CID_EXPOSURE, 4, exposure_max, 1, exposure_max); v4l2_ctrl_new_std(&sensor->ctrls, &imx415_ctrl_ops, V4L2_CID_ANALOGUE_GAIN, IMX415_AGAIN_MIN, IMX415_AGAIN_MAX, IMX415_AGAIN_STEP, IMX415_AGAIN_MIN); hblank = supported_modes[sensor->cur_mode].hmax_pix - IMX415_PIXEL_ARRAY_WIDTH; ctrl = v4l2_ctrl_new_std(&sensor->ctrls, &imx415_ctrl_ops, V4L2_CID_HBLANK, hblank, hblank, 1, hblank); if (ctrl) ctrl->flags |= V4L2_CTRL_FLAG_READ_ONLY; sensor->vblank = v4l2_ctrl_new_std(&sensor->ctrls, &imx415_ctrl_ops, V4L2_CID_VBLANK, IMX415_PIXEL_ARRAY_VBLANK, IMX415_PIXEL_ARRAY_VBLANK, 1, IMX415_PIXEL_ARRAY_VBLANK); if (sensor->vblank) sensor->vblank->flags |= V4L2_CTRL_FLAG_READ_ONLY; /* * The pixel rate used here is a virtual value and can be used for * calculating the frame rate together with hblank. It may not * necessarily be the physically correct pixel clock. */ v4l2_ctrl_new_std(&sensor->ctrls, NULL, V4L2_CID_PIXEL_RATE, pixel_rate, pixel_rate, 1, pixel_rate); sensor->hflip = v4l2_ctrl_new_std(&sensor->ctrls, &imx415_ctrl_ops, V4L2_CID_HFLIP, 0, 1, 1, 0); sensor->vflip = v4l2_ctrl_new_std(&sensor->ctrls, &imx415_ctrl_ops, V4L2_CID_VFLIP, 0, 1, 1, 0); v4l2_ctrl_new_std_menu_items(&sensor->ctrls, &imx415_ctrl_ops, V4L2_CID_TEST_PATTERN, ARRAY_SIZE(imx415_test_pattern_menu) - 1, 0, 0, imx415_test_pattern_menu); v4l2_ctrl_new_fwnode_properties(&sensor->ctrls, &imx415_ctrl_ops, &props); if (sensor->ctrls.error) { dev_err_probe(sensor->dev, sensor->ctrls.error, "failed to add controls\n"); v4l2_ctrl_handler_free(&sensor->ctrls); return sensor->ctrls.error; } sensor->subdev.ctrl_handler = &sensor->ctrls; return 0; } static int imx415_set_mode(struct imx415 *sensor, int mode) { const struct imx415_reg *reg; unsigned int i; int ret = 0; if (mode >= ARRAY_SIZE(supported_modes)) { dev_err(sensor->dev, "Mode %d not supported\n", mode); return -EINVAL; } for (i = 0; i < supported_modes[mode].reg_list.num_of_regs; ++i) { reg = &supported_modes[mode].reg_list.regs[i]; ret = imx415_write(sensor, reg->address, reg->val); if (ret) return ret; } for (i = 0; i < IMX415_NUM_CLK_PARAM_REGS; ++i) { reg = &sensor->clk_params->regs[i]; ret = imx415_write(sensor, reg->address, reg->val); if (ret) return ret; } return 0; } static int imx415_setup(struct imx415 *sensor, struct v4l2_subdev_state *state) { unsigned int i; int ret; for (i = 0; i < ARRAY_SIZE(imx415_init_table); ++i) { ret = imx415_write(sensor, imx415_init_table[i].address, imx415_init_table[i].val); if (ret) return ret; } return imx415_set_mode(sensor, sensor->cur_mode); } static int imx415_wakeup(struct imx415 *sensor) { int ret; ret = imx415_write(sensor, IMX415_MODE, IMX415_MODE_OPERATING); if (ret) return ret; /* * According to the datasheet we have to wait at least 63 us after * leaving standby mode. But this doesn't work even after 30 ms. * So probably this should be 63 ms and therefore we wait for 80 ms. */ msleep(80); return 0; } static int imx415_stream_on(struct imx415 *sensor) { int ret; ret = imx415_wakeup(sensor); if (ret) return ret; return imx415_write(sensor, IMX415_XMSTA, IMX415_XMSTA_START); } static int imx415_stream_off(struct imx415 *sensor) { int ret; ret = imx415_write(sensor, IMX415_XMSTA, IMX415_XMSTA_STOP); if (ret) return ret; return imx415_write(sensor, IMX415_MODE, IMX415_MODE_STANDBY); } static int imx415_s_stream(struct v4l2_subdev *sd, int enable) { struct imx415 *sensor = to_imx415(sd); struct v4l2_subdev_state *state; int ret; state = v4l2_subdev_lock_and_get_active_state(sd); if (!enable) { ret = imx415_stream_off(sensor); pm_runtime_mark_last_busy(sensor->dev); pm_runtime_put_autosuspend(sensor->dev); sensor->streaming = false; goto unlock; } ret = pm_runtime_resume_and_get(sensor->dev); if (ret < 0) goto unlock; ret = imx415_setup(sensor, state); if (ret) goto err_pm; /* * Set streaming to true to ensure __v4l2_ctrl_handler_setup() will set * the controls. The flag is reset to false further down if an error * occurs. */ sensor->streaming = true; ret = __v4l2_ctrl_handler_setup(&sensor->ctrls); if (ret < 0) goto err_pm; ret = imx415_stream_on(sensor); if (ret) goto err_pm; ret = 0; unlock: v4l2_subdev_unlock_state(state); return ret; err_pm: /* * In case of error, turn the power off synchronously as the device * likely has no other chance to recover. */ pm_runtime_put_sync(sensor->dev); sensor->streaming = false; goto unlock; } static int imx415_enum_mbus_code(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, struct v4l2_subdev_mbus_code_enum *code) { if (code->index != 0) return -EINVAL; code->code = MEDIA_BUS_FMT_SGBRG10_1X10; return 0; } static int imx415_enum_frame_size(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, struct v4l2_subdev_frame_size_enum *fse) { const struct v4l2_mbus_framefmt *format; format = v4l2_subdev_get_pad_format(sd, state, fse->pad); if (fse->index > 0 || fse->code != format->code) return -EINVAL; fse->min_width = IMX415_PIXEL_ARRAY_WIDTH; fse->max_width = fse->min_width; fse->min_height = IMX415_PIXEL_ARRAY_HEIGHT; fse->max_height = fse->min_height; return 0; } static int imx415_get_format(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, struct v4l2_subdev_format *fmt) { fmt->format = *v4l2_subdev_get_pad_format(sd, state, fmt->pad); return 0; } static int imx415_set_format(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, struct v4l2_subdev_format *fmt) { struct v4l2_mbus_framefmt *format; format = v4l2_subdev_get_pad_format(sd, state, fmt->pad); format->width = fmt->format.width; format->height = fmt->format.height; format->code = MEDIA_BUS_FMT_SGBRG10_1X10; format->field = V4L2_FIELD_NONE; format->colorspace = V4L2_COLORSPACE_RAW; format->ycbcr_enc = V4L2_YCBCR_ENC_DEFAULT; format->quantization = V4L2_QUANTIZATION_DEFAULT; format->xfer_func = V4L2_XFER_FUNC_NONE; fmt->format = *format; return 0; } static int imx415_get_selection(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_selection *sel) { switch (sel->target) { case V4L2_SEL_TGT_CROP: case V4L2_SEL_TGT_CROP_DEFAULT: case V4L2_SEL_TGT_CROP_BOUNDS: sel->r.top = IMX415_PIXEL_ARRAY_TOP; sel->r.left = IMX415_PIXEL_ARRAY_LEFT; sel->r.width = IMX415_PIXEL_ARRAY_WIDTH; sel->r.height = IMX415_PIXEL_ARRAY_HEIGHT; return 0; } return -EINVAL; } static int imx415_init_cfg(struct v4l2_subdev *sd, struct v4l2_subdev_state *state) { struct v4l2_subdev_format format = { .format = { .width = IMX415_PIXEL_ARRAY_WIDTH, .height = IMX415_PIXEL_ARRAY_HEIGHT, }, }; imx415_set_format(sd, state, &format); return 0; } static const struct v4l2_subdev_video_ops imx415_subdev_video_ops = { .s_stream = imx415_s_stream, }; static const struct v4l2_subdev_pad_ops imx415_subdev_pad_ops = { .enum_mbus_code = imx415_enum_mbus_code, .enum_frame_size = imx415_enum_frame_size, .get_fmt = imx415_get_format, .set_fmt = imx415_set_format, .get_selection = imx415_get_selection, .init_cfg = imx415_init_cfg, }; static const struct v4l2_subdev_ops imx415_subdev_ops = { .video = &imx415_subdev_video_ops, .pad = &imx415_subdev_pad_ops, }; static int imx415_subdev_init(struct imx415 *sensor) { struct i2c_client *client = to_i2c_client(sensor->dev); int ret; v4l2_i2c_subdev_init(&sensor->subdev, client, &imx415_subdev_ops); ret = imx415_ctrls_init(sensor); if (ret) return ret; sensor->subdev.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE | V4L2_SUBDEV_FL_HAS_EVENTS; sensor->pad.flags = MEDIA_PAD_FL_SOURCE; sensor->subdev.entity.function = MEDIA_ENT_F_CAM_SENSOR; ret = media_entity_pads_init(&sensor->subdev.entity, 1, &sensor->pad); if (ret < 0) { v4l2_ctrl_handler_free(&sensor->ctrls); return ret; } sensor->subdev.state_lock = sensor->subdev.ctrl_handler->lock; v4l2_subdev_init_finalize(&sensor->subdev); return 0; } static void imx415_subdev_cleanup(struct imx415 *sensor) { media_entity_cleanup(&sensor->subdev.entity); v4l2_ctrl_handler_free(&sensor->ctrls); } static int imx415_power_on(struct imx415 *sensor) { int ret; ret = regulator_bulk_enable(ARRAY_SIZE(sensor->supplies), sensor->supplies); if (ret < 0) return ret; gpiod_set_value_cansleep(sensor->reset, 0); udelay(1); ret = clk_prepare_enable(sensor->clk); if (ret < 0) goto err_reset; /* * Data sheet states that 20 us are required before communication start, * but this doesn't work in all cases. Use 100 us to be on the safe * side. */ usleep_range(100, 200); return 0; err_reset: gpiod_set_value_cansleep(sensor->reset, 1); regulator_bulk_disable(ARRAY_SIZE(sensor->supplies), sensor->supplies); return ret; } static void imx415_power_off(struct imx415 *sensor) { clk_disable_unprepare(sensor->clk); gpiod_set_value_cansleep(sensor->reset, 1); regulator_bulk_disable(ARRAY_SIZE(sensor->supplies), sensor->supplies); } static int imx415_identify_model(struct imx415 *sensor) { int model, ret; /* * While most registers can be read when the sensor is in standby, this * is not the case of the sensor info register :-( */ ret = imx415_wakeup(sensor); if (ret) return dev_err_probe(sensor->dev, ret, "failed to get sensor out of standby\n"); ret = imx415_read(sensor, IMX415_SENSOR_INFO); if (ret < 0) { dev_err_probe(sensor->dev, ret, "failed to read sensor information\n"); goto done; } model = ret & IMX415_SENSOR_INFO_MASK; switch (model) { case IMX415_CHIP_ID: dev_info(sensor->dev, "Detected IMX415 image sensor\n"); break; default: ret = dev_err_probe(sensor->dev, -ENODEV, "invalid device model 0x%04x\n", model); goto done; } ret = 0; done: imx415_write(sensor, IMX415_MODE, IMX415_MODE_STANDBY); return ret; } static int imx415_check_inck(unsigned long inck, u64 link_frequency) { unsigned int i; for (i = 0; i < ARRAY_SIZE(imx415_clk_params); ++i) { if ((imx415_clk_params[i].lane_rate == link_frequency * 2) && imx415_clk_params[i].inck == inck) break; } if (i == ARRAY_SIZE(imx415_clk_params)) return -EINVAL; else return 0; } static int imx415_parse_hw_config(struct imx415 *sensor) { struct v4l2_fwnode_endpoint bus_cfg = { .bus_type = V4L2_MBUS_CSI2_DPHY, }; struct fwnode_handle *ep; u64 lane_rate; unsigned long inck; unsigned int i, j; int ret; for (i = 0; i < ARRAY_SIZE(sensor->supplies); ++i) sensor->supplies[i].supply = imx415_supply_names[i]; ret = devm_regulator_bulk_get(sensor->dev, ARRAY_SIZE(sensor->supplies), sensor->supplies); if (ret) return dev_err_probe(sensor->dev, ret, "failed to get supplies\n"); sensor->reset = devm_gpiod_get_optional(sensor->dev, "reset", GPIOD_OUT_HIGH); if (IS_ERR(sensor->reset)) return dev_err_probe(sensor->dev, PTR_ERR(sensor->reset), "failed to get reset GPIO\n"); sensor->clk = devm_clk_get(sensor->dev, "inck"); if (IS_ERR(sensor->clk)) return dev_err_probe(sensor->dev, PTR_ERR(sensor->clk), "failed to get clock\n"); ep = fwnode_graph_get_next_endpoint(dev_fwnode(sensor->dev), NULL); if (!ep) return -ENXIO; ret = v4l2_fwnode_endpoint_alloc_parse(ep, &bus_cfg); fwnode_handle_put(ep); if (ret) return ret; switch (bus_cfg.bus.mipi_csi2.num_data_lanes) { case 2: case 4: sensor->num_data_lanes = bus_cfg.bus.mipi_csi2.num_data_lanes; break; default: ret = dev_err_probe(sensor->dev, -EINVAL, "invalid number of CSI2 data lanes %d\n", bus_cfg.bus.mipi_csi2.num_data_lanes); goto done_endpoint_free; } if (!bus_cfg.nr_of_link_frequencies) { ret = dev_err_probe(sensor->dev, -EINVAL, "no link frequencies defined"); goto done_endpoint_free; } /* * Check if there exists a sensor mode defined for current INCK, * number of lanes and given lane rates. */ inck = clk_get_rate(sensor->clk); for (i = 0; i < bus_cfg.nr_of_link_frequencies; ++i) { if (imx415_check_inck(inck, bus_cfg.link_frequencies[i])) { dev_dbg(sensor->dev, "INCK %lu Hz not supported for this link freq", inck); continue; } for (j = 0; j < ARRAY_SIZE(supported_modes); ++j) { if (sensor->num_data_lanes != supported_modes[j].lanes) continue; if (bus_cfg.link_frequencies[i] * 2 != supported_modes[j].lane_rate) continue; sensor->cur_mode = j; break; } if (j < ARRAY_SIZE(supported_modes)) break; } if (i == bus_cfg.nr_of_link_frequencies) { ret = dev_err_probe(sensor->dev, -EINVAL, "no valid sensor mode defined\n"); goto done_endpoint_free; } lane_rate = supported_modes[sensor->cur_mode].lane_rate; for (i = 0; i < ARRAY_SIZE(imx415_clk_params); ++i) { if (lane_rate == imx415_clk_params[i].lane_rate && inck == imx415_clk_params[i].inck) { sensor->clk_params = &imx415_clk_params[i]; break; } } if (i == ARRAY_SIZE(imx415_clk_params)) { ret = dev_err_probe(sensor->dev, -EINVAL, "Mode %d not supported\n", sensor->cur_mode); goto done_endpoint_free; } ret = 0; dev_dbg(sensor->dev, "clock: %lu Hz, lane_rate: %llu bps, lanes: %d\n", inck, lane_rate, sensor->num_data_lanes); done_endpoint_free: v4l2_fwnode_endpoint_free(&bus_cfg); return ret; } static int imx415_probe(struct i2c_client *client) { struct imx415 *sensor; int ret; sensor = devm_kzalloc(&client->dev, sizeof(*sensor), GFP_KERNEL); if (!sensor) return -ENOMEM; sensor->dev = &client->dev; ret = imx415_parse_hw_config(sensor); if (ret) return ret; sensor->regmap = devm_regmap_init_i2c(client, &imx415_regmap_config); if (IS_ERR(sensor->regmap)) return PTR_ERR(sensor->regmap); /* * Enable power management. The driver supports runtime PM, but needs to * work when runtime PM is disabled in the kernel. To that end, power * the sensor on manually here, identify it, and fully initialize it. */ ret = imx415_power_on(sensor); if (ret) return ret; ret = imx415_identify_model(sensor); if (ret) goto err_power; ret = imx415_subdev_init(sensor); if (ret) goto err_power; /* * Enable runtime PM. As the device has been powered manually, mark it * as active, and increase the usage count without resuming the device. */ pm_runtime_set_active(sensor->dev); pm_runtime_get_noresume(sensor->dev); pm_runtime_enable(sensor->dev); ret = v4l2_async_register_subdev_sensor(&sensor->subdev); if (ret < 0) goto err_pm; /* * Finally, enable autosuspend and decrease the usage count. The device * will get suspended after the autosuspend delay, turning the power * off. */ pm_runtime_set_autosuspend_delay(sensor->dev, 1000); pm_runtime_use_autosuspend(sensor->dev); pm_runtime_put_autosuspend(sensor->dev); return 0; err_pm: pm_runtime_disable(sensor->dev); pm_runtime_put_noidle(sensor->dev); imx415_subdev_cleanup(sensor); err_power: imx415_power_off(sensor); return ret; } static void imx415_remove(struct i2c_client *client) { struct v4l2_subdev *subdev = i2c_get_clientdata(client); struct imx415 *sensor = to_imx415(subdev); v4l2_async_unregister_subdev(subdev); imx415_subdev_cleanup(sensor); /* * Disable runtime PM. In case runtime PM is disabled in the kernel, * make sure to turn power off manually. */ pm_runtime_disable(sensor->dev); if (!pm_runtime_status_suspended(sensor->dev)) imx415_power_off(sensor); pm_runtime_set_suspended(sensor->dev); } static int imx415_runtime_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct v4l2_subdev *subdev = i2c_get_clientdata(client); struct imx415 *sensor = to_imx415(subdev); return imx415_power_on(sensor); } static int imx415_runtime_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct v4l2_subdev *subdev = i2c_get_clientdata(client); struct imx415 *sensor = to_imx415(subdev); imx415_power_off(sensor); return 0; } static DEFINE_RUNTIME_DEV_PM_OPS(imx415_pm_ops, imx415_runtime_suspend, imx415_runtime_resume, NULL); static const struct of_device_id imx415_of_match[] = { { .compatible = "sony,imx415" }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(of, imx415_of_match); static struct i2c_driver imx415_driver = { .probe = imx415_probe, .remove = imx415_remove, .driver = { .name = "imx415", .of_match_table = imx415_of_match, .pm = pm_ptr(&imx415_pm_ops), }, }; module_i2c_driver(imx415_driver); MODULE_DESCRIPTION("Sony IMX415 image sensor driver"); MODULE_AUTHOR("Gerald Loacker <[email protected]>"); MODULE_AUTHOR("Michael Riesch <[email protected]>"); MODULE_LICENSE("GPL");
linux-master
drivers/media/i2c/imx415.c
// SPDX-License-Identifier: GPL-2.0 /* * Driver for the Texas Instruments DS90UB913 video serializer * * Based on a driver from Luca Ceresoli <[email protected]> * * Copyright (c) 2019 Luca Ceresoli <[email protected]> * Copyright (c) 2023 Tomi Valkeinen <[email protected]> */ #include <linux/clk-provider.h> #include <linux/clk.h> #include <linux/delay.h> #include <linux/fwnode.h> #include <linux/gpio/driver.h> #include <linux/i2c-atr.h> #include <linux/i2c.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/property.h> #include <linux/regmap.h> #include <media/i2c/ds90ub9xx.h> #include <media/v4l2-fwnode.h> #include <media/v4l2-mediabus.h> #include <media/v4l2-subdev.h> #define UB913_PAD_SINK 0 #define UB913_PAD_SOURCE 1 /* * UB913 has 4 gpios, but gpios 3 and 4 are reserved for external oscillator * mode. Thus we only support 2 gpios for now. */ #define UB913_NUM_GPIOS 2 #define UB913_REG_RESET_CTL 0x01 #define UB913_REG_RESET_CTL_DIGITAL_RESET_1 BIT(1) #define UB913_REG_RESET_CTL_DIGITAL_RESET_0 BIT(0) #define UB913_REG_GENERAL_CFG 0x03 #define UB913_REG_GENERAL_CFG_CRC_ERR_RESET BIT(5) #define UB913_REG_GENERAL_CFG_PCLK_RISING BIT(0) #define UB913_REG_MODE_SEL 0x05 #define UB913_REG_MODE_SEL_MODE_OVERRIDE BIT(5) #define UB913_REG_MODE_SEL_MODE_UP_TO_DATE BIT(4) #define UB913_REG_MODE_SEL_MODE_MASK GENMASK(3, 0) #define UB913_REG_CRC_ERRORS_LSB 0x0a #define UB913_REG_CRC_ERRORS_MSB 0x0b #define UB913_REG_GENERAL_STATUS 0x0c #define UB913_REG_GPIO_CFG(n) (0x0d + (n)) #define UB913_REG_GPIO_CFG_ENABLE(n) BIT(0 + (n) * 4) #define UB913_REG_GPIO_CFG_DIR_INPUT(n) BIT(1 + (n) * 4) #define UB913_REG_GPIO_CFG_REMOTE_EN(n) BIT(2 + (n) * 4) #define UB913_REG_GPIO_CFG_OUT_VAL(n) BIT(3 + (n) * 4) #define UB913_REG_GPIO_CFG_MASK(n) (0xf << ((n) * 4)) #define UB913_REG_SCL_HIGH_TIME 0x11 #define UB913_REG_SCL_LOW_TIME 0x12 #define UB913_REG_PLL_OVR 0x35 struct ub913_data { struct i2c_client *client; struct regmap *regmap; struct clk *clkin; struct gpio_chip gpio_chip; struct v4l2_subdev sd; struct media_pad pads[2]; struct v4l2_async_notifier notifier; struct v4l2_subdev *source_sd; u16 source_sd_pad; u64 enabled_source_streams; struct clk_hw *clkout_clk_hw; struct ds90ub9xx_platform_data *plat_data; bool pclk_polarity_rising; }; static inline struct ub913_data *sd_to_ub913(struct v4l2_subdev *sd) { return container_of(sd, struct ub913_data, sd); } struct ub913_format_info { u32 incode; u32 outcode; }; static const struct ub913_format_info ub913_formats[] = { /* Only RAW10 with 8-bit payload is supported at the moment */ { .incode = MEDIA_BUS_FMT_YUYV8_2X8, .outcode = MEDIA_BUS_FMT_YUYV8_1X16 }, { .incode = MEDIA_BUS_FMT_UYVY8_2X8, .outcode = MEDIA_BUS_FMT_UYVY8_1X16 }, { .incode = MEDIA_BUS_FMT_VYUY8_2X8, .outcode = MEDIA_BUS_FMT_VYUY8_1X16 }, { .incode = MEDIA_BUS_FMT_YVYU8_2X8, .outcode = MEDIA_BUS_FMT_YVYU8_1X16 }, }; static const struct ub913_format_info *ub913_find_format(u32 incode) { unsigned int i; for (i = 0; i < ARRAY_SIZE(ub913_formats); i++) { if (ub913_formats[i].incode == incode) return &ub913_formats[i]; } return NULL; } static int ub913_read(const struct ub913_data *priv, u8 reg, u8 *val) { unsigned int v; int ret; ret = regmap_read(priv->regmap, reg, &v); if (ret < 0) { dev_err(&priv->client->dev, "Cannot read register 0x%02x: %d!\n", reg, ret); return ret; } *val = v; return 0; } static int ub913_write(const struct ub913_data *priv, u8 reg, u8 val) { int ret; ret = regmap_write(priv->regmap, reg, val); if (ret < 0) dev_err(&priv->client->dev, "Cannot write register 0x%02x: %d!\n", reg, ret); return ret; } /* * GPIO chip */ static int ub913_gpio_get_direction(struct gpio_chip *gc, unsigned int offset) { return GPIO_LINE_DIRECTION_OUT; } static int ub913_gpio_direction_out(struct gpio_chip *gc, unsigned int offset, int value) { struct ub913_data *priv = gpiochip_get_data(gc); unsigned int reg_idx = offset / 2; unsigned int field_idx = offset % 2; return regmap_update_bits(priv->regmap, UB913_REG_GPIO_CFG(reg_idx), UB913_REG_GPIO_CFG_MASK(field_idx), UB913_REG_GPIO_CFG_ENABLE(field_idx) | (value ? UB913_REG_GPIO_CFG_OUT_VAL(field_idx) : 0)); } static void ub913_gpio_set(struct gpio_chip *gc, unsigned int offset, int value) { ub913_gpio_direction_out(gc, offset, value); } static int ub913_gpio_of_xlate(struct gpio_chip *gc, const struct of_phandle_args *gpiospec, u32 *flags) { if (flags) *flags = gpiospec->args[1]; return gpiospec->args[0]; } static int ub913_gpiochip_probe(struct ub913_data *priv) { struct device *dev = &priv->client->dev; struct gpio_chip *gc = &priv->gpio_chip; int ret; /* Initialize GPIOs 0 and 1 to local control, tri-state */ ub913_write(priv, UB913_REG_GPIO_CFG(0), 0); gc->label = dev_name(dev); gc->parent = dev; gc->owner = THIS_MODULE; gc->base = -1; gc->can_sleep = true; gc->ngpio = UB913_NUM_GPIOS; gc->get_direction = ub913_gpio_get_direction; gc->direction_output = ub913_gpio_direction_out; gc->set = ub913_gpio_set; gc->of_xlate = ub913_gpio_of_xlate; gc->of_gpio_n_cells = 2; ret = gpiochip_add_data(gc, priv); if (ret) { dev_err(dev, "Failed to add GPIOs: %d\n", ret); return ret; } return 0; } static void ub913_gpiochip_remove(struct ub913_data *priv) { gpiochip_remove(&priv->gpio_chip); } static const struct regmap_config ub913_regmap_config = { .name = "ds90ub913", .reg_bits = 8, .val_bits = 8, .reg_format_endian = REGMAP_ENDIAN_DEFAULT, .val_format_endian = REGMAP_ENDIAN_DEFAULT, }; /* * V4L2 */ static int ub913_enable_streams(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, u32 pad, u64 streams_mask) { struct ub913_data *priv = sd_to_ub913(sd); u64 sink_streams; int ret; sink_streams = v4l2_subdev_state_xlate_streams(state, UB913_PAD_SOURCE, UB913_PAD_SINK, &streams_mask); ret = v4l2_subdev_enable_streams(priv->source_sd, priv->source_sd_pad, sink_streams); if (ret) return ret; priv->enabled_source_streams |= streams_mask; return 0; } static int ub913_disable_streams(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, u32 pad, u64 streams_mask) { struct ub913_data *priv = sd_to_ub913(sd); u64 sink_streams; int ret; sink_streams = v4l2_subdev_state_xlate_streams(state, UB913_PAD_SOURCE, UB913_PAD_SINK, &streams_mask); ret = v4l2_subdev_disable_streams(priv->source_sd, priv->source_sd_pad, sink_streams); if (ret) return ret; priv->enabled_source_streams &= ~streams_mask; return 0; } static int _ub913_set_routing(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, struct v4l2_subdev_krouting *routing) { static const struct v4l2_mbus_framefmt in_format = { .width = 640, .height = 480, .code = MEDIA_BUS_FMT_UYVY8_2X8, .field = V4L2_FIELD_NONE, .colorspace = V4L2_COLORSPACE_SRGB, .ycbcr_enc = V4L2_YCBCR_ENC_601, .quantization = V4L2_QUANTIZATION_LIM_RANGE, .xfer_func = V4L2_XFER_FUNC_SRGB, }; static const struct v4l2_mbus_framefmt out_format = { .width = 640, .height = 480, .code = MEDIA_BUS_FMT_UYVY8_1X16, .field = V4L2_FIELD_NONE, .colorspace = V4L2_COLORSPACE_SRGB, .ycbcr_enc = V4L2_YCBCR_ENC_601, .quantization = V4L2_QUANTIZATION_LIM_RANGE, .xfer_func = V4L2_XFER_FUNC_SRGB, }; struct v4l2_subdev_stream_configs *stream_configs; unsigned int i; int ret; /* * Note: we can only support up to V4L2_FRAME_DESC_ENTRY_MAX, until * frame desc is made dynamically allocated. */ if (routing->num_routes > V4L2_FRAME_DESC_ENTRY_MAX) return -EINVAL; ret = v4l2_subdev_routing_validate(sd, routing, V4L2_SUBDEV_ROUTING_ONLY_1_TO_1); if (ret) return ret; ret = v4l2_subdev_set_routing(sd, state, routing); if (ret) return ret; stream_configs = &state->stream_configs; for (i = 0; i < stream_configs->num_configs; i++) { if (stream_configs->configs[i].pad == UB913_PAD_SINK) stream_configs->configs[i].fmt = in_format; else stream_configs->configs[i].fmt = out_format; } return 0; } static int ub913_set_routing(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, enum v4l2_subdev_format_whence which, struct v4l2_subdev_krouting *routing) { struct ub913_data *priv = sd_to_ub913(sd); if (which == V4L2_SUBDEV_FORMAT_ACTIVE && priv->enabled_source_streams) return -EBUSY; return _ub913_set_routing(sd, state, routing); } static int ub913_get_frame_desc(struct v4l2_subdev *sd, unsigned int pad, struct v4l2_mbus_frame_desc *fd) { struct ub913_data *priv = sd_to_ub913(sd); const struct v4l2_subdev_krouting *routing; struct v4l2_mbus_frame_desc source_fd; struct v4l2_subdev_route *route; struct v4l2_subdev_state *state; int ret; if (pad != UB913_PAD_SOURCE) return -EINVAL; ret = v4l2_subdev_call(priv->source_sd, pad, get_frame_desc, priv->source_sd_pad, &source_fd); if (ret) return ret; memset(fd, 0, sizeof(*fd)); fd->type = V4L2_MBUS_FRAME_DESC_TYPE_PARALLEL; state = v4l2_subdev_lock_and_get_active_state(sd); routing = &state->routing; for_each_active_route(routing, route) { unsigned int i; if (route->source_pad != pad) continue; for (i = 0; i < source_fd.num_entries; i++) { if (source_fd.entry[i].stream == route->sink_stream) break; } if (i == source_fd.num_entries) { dev_err(&priv->client->dev, "Failed to find stream from source frame desc\n"); ret = -EPIPE; goto out_unlock; } fd->entry[fd->num_entries].stream = route->source_stream; fd->entry[fd->num_entries].flags = source_fd.entry[i].flags; fd->entry[fd->num_entries].length = source_fd.entry[i].length; fd->entry[fd->num_entries].pixelcode = source_fd.entry[i].pixelcode; fd->num_entries++; } out_unlock: v4l2_subdev_unlock_state(state); return ret; } static int ub913_set_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_state *state, struct v4l2_subdev_format *format) { struct ub913_data *priv = sd_to_ub913(sd); struct v4l2_mbus_framefmt *fmt; const struct ub913_format_info *finfo; if (format->which == V4L2_SUBDEV_FORMAT_ACTIVE && priv->enabled_source_streams) return -EBUSY; /* Source format is fully defined by the sink format, so not settable */ if (format->pad == UB913_PAD_SOURCE) return v4l2_subdev_get_fmt(sd, state, format); finfo = ub913_find_format(format->format.code); if (!finfo) { finfo = &ub913_formats[0]; format->format.code = finfo->incode; } /* Set sink format */ fmt = v4l2_subdev_state_get_stream_format(state, format->pad, format->stream); if (!fmt) return -EINVAL; *fmt = format->format; /* Propagate to source format, and adjust the mbus code */ fmt = v4l2_subdev_state_get_opposite_stream_format(state, format->pad, format->stream); if (!fmt) return -EINVAL; format->format.code = finfo->outcode; *fmt = format->format; return 0; } static int ub913_init_cfg(struct v4l2_subdev *sd, struct v4l2_subdev_state *state) { struct v4l2_subdev_route routes[] = { { .sink_pad = UB913_PAD_SINK, .sink_stream = 0, .source_pad = UB913_PAD_SOURCE, .source_stream = 0, .flags = V4L2_SUBDEV_ROUTE_FL_ACTIVE, }, }; struct v4l2_subdev_krouting routing = { .num_routes = ARRAY_SIZE(routes), .routes = routes, }; return _ub913_set_routing(sd, state, &routing); } static int ub913_log_status(struct v4l2_subdev *sd) { struct ub913_data *priv = sd_to_ub913(sd); struct device *dev = &priv->client->dev; u8 v = 0, v1 = 0, v2 = 0; ub913_read(priv, UB913_REG_MODE_SEL, &v); dev_info(dev, "MODE_SEL %#02x\n", v); ub913_read(priv, UB913_REG_CRC_ERRORS_LSB, &v1); ub913_read(priv, UB913_REG_CRC_ERRORS_MSB, &v2); dev_info(dev, "CRC errors %u\n", v1 | (v2 << 8)); /* clear CRC errors */ ub913_read(priv, UB913_REG_GENERAL_CFG, &v); ub913_write(priv, UB913_REG_GENERAL_CFG, v | UB913_REG_GENERAL_CFG_CRC_ERR_RESET); ub913_write(priv, UB913_REG_GENERAL_CFG, v); ub913_read(priv, UB913_REG_GENERAL_STATUS, &v); dev_info(dev, "GENERAL_STATUS %#02x\n", v); ub913_read(priv, UB913_REG_PLL_OVR, &v); dev_info(dev, "PLL_OVR %#02x\n", v); return 0; } static const struct v4l2_subdev_core_ops ub913_subdev_core_ops = { .log_status = ub913_log_status, }; static const struct v4l2_subdev_pad_ops ub913_pad_ops = { .enable_streams = ub913_enable_streams, .disable_streams = ub913_disable_streams, .set_routing = ub913_set_routing, .get_frame_desc = ub913_get_frame_desc, .get_fmt = v4l2_subdev_get_fmt, .set_fmt = ub913_set_fmt, .init_cfg = ub913_init_cfg, }; static const struct v4l2_subdev_ops ub913_subdev_ops = { .core = &ub913_subdev_core_ops, .pad = &ub913_pad_ops, }; static const struct media_entity_operations ub913_entity_ops = { .link_validate = v4l2_subdev_link_validate, }; static int ub913_notify_bound(struct v4l2_async_notifier *notifier, struct v4l2_subdev *source_subdev, struct v4l2_async_connection *asd) { struct ub913_data *priv = sd_to_ub913(notifier->sd); struct device *dev = &priv->client->dev; int ret; ret = media_entity_get_fwnode_pad(&source_subdev->entity, source_subdev->fwnode, MEDIA_PAD_FL_SOURCE); if (ret < 0) { dev_err(dev, "Failed to find pad for %s\n", source_subdev->name); return ret; } priv->source_sd = source_subdev; priv->source_sd_pad = ret; ret = media_create_pad_link(&source_subdev->entity, priv->source_sd_pad, &priv->sd.entity, UB913_PAD_SINK, MEDIA_LNK_FL_ENABLED | MEDIA_LNK_FL_IMMUTABLE); if (ret) { dev_err(dev, "Unable to link %s:%u -> %s:0\n", source_subdev->name, priv->source_sd_pad, priv->sd.name); return ret; } return 0; } static const struct v4l2_async_notifier_operations ub913_notify_ops = { .bound = ub913_notify_bound, }; static int ub913_v4l2_notifier_register(struct ub913_data *priv) { struct device *dev = &priv->client->dev; struct v4l2_async_connection *asd; struct fwnode_handle *ep_fwnode; int ret; ep_fwnode = fwnode_graph_get_endpoint_by_id(dev_fwnode(dev), UB913_PAD_SINK, 0, 0); if (!ep_fwnode) { dev_err(dev, "No graph endpoint\n"); return -ENODEV; } v4l2_async_subdev_nf_init(&priv->notifier, &priv->sd); asd = v4l2_async_nf_add_fwnode_remote(&priv->notifier, ep_fwnode, struct v4l2_async_connection); fwnode_handle_put(ep_fwnode); if (IS_ERR(asd)) { dev_err(dev, "Failed to add subdev: %ld", PTR_ERR(asd)); v4l2_async_nf_cleanup(&priv->notifier); return PTR_ERR(asd); } priv->notifier.ops = &ub913_notify_ops; ret = v4l2_async_nf_register(&priv->notifier); if (ret) { dev_err(dev, "Failed to register subdev_notifier"); v4l2_async_nf_cleanup(&priv->notifier); return ret; } return 0; } static void ub913_v4l2_nf_unregister(struct ub913_data *priv) { v4l2_async_nf_unregister(&priv->notifier); v4l2_async_nf_cleanup(&priv->notifier); } static int ub913_register_clkout(struct ub913_data *priv) { struct device *dev = &priv->client->dev; const char *name; int ret; name = kasprintf(GFP_KERNEL, "ds90ub913.%s.clk_out", dev_name(dev)); if (!name) return -ENOMEM; priv->clkout_clk_hw = devm_clk_hw_register_fixed_factor(dev, name, __clk_get_name(priv->clkin), 0, 1, 2); kfree(name); if (IS_ERR(priv->clkout_clk_hw)) return dev_err_probe(dev, PTR_ERR(priv->clkout_clk_hw), "Cannot register clkout hw\n"); ret = devm_of_clk_add_hw_provider(dev, of_clk_hw_simple_get, priv->clkout_clk_hw); if (ret) return dev_err_probe(dev, ret, "Cannot add OF clock provider\n"); return 0; } static int ub913_i2c_master_init(struct ub913_data *priv) { /* i2c fast mode */ u32 scl_high = 600 + 300; /* high period + rise time, ns */ u32 scl_low = 1300 + 300; /* low period + fall time, ns */ unsigned long ref; int ret; ref = clk_get_rate(priv->clkin) / 2; scl_high = div64_u64((u64)scl_high * ref, 1000000000); scl_low = div64_u64((u64)scl_low * ref, 1000000000); ret = ub913_write(priv, UB913_REG_SCL_HIGH_TIME, scl_high); if (ret) return ret; ret = ub913_write(priv, UB913_REG_SCL_LOW_TIME, scl_low); if (ret) return ret; return 0; } static int ub913_add_i2c_adapter(struct ub913_data *priv) { struct device *dev = &priv->client->dev; struct fwnode_handle *i2c_handle; int ret; i2c_handle = device_get_named_child_node(dev, "i2c"); if (!i2c_handle) return 0; ret = i2c_atr_add_adapter(priv->plat_data->atr, priv->plat_data->port, dev, i2c_handle); fwnode_handle_put(i2c_handle); if (ret) return ret; return 0; } static int ub913_parse_dt(struct ub913_data *priv) { struct device *dev = &priv->client->dev; struct v4l2_fwnode_endpoint vep = { .bus_type = V4L2_MBUS_PARALLEL, }; struct fwnode_handle *ep_fwnode; int ret; ep_fwnode = fwnode_graph_get_endpoint_by_id(dev_fwnode(dev), UB913_PAD_SINK, 0, 0); if (!ep_fwnode) return dev_err_probe(dev, -ENOENT, "No sink endpoint\n"); ret = v4l2_fwnode_endpoint_parse(ep_fwnode, &vep); fwnode_handle_put(ep_fwnode); if (ret) return dev_err_probe(dev, ret, "failed to parse sink endpoint data\n"); if (vep.bus.parallel.flags & V4L2_MBUS_PCLK_SAMPLE_RISING) priv->pclk_polarity_rising = true; else if (vep.bus.parallel.flags & V4L2_MBUS_PCLK_SAMPLE_FALLING) priv->pclk_polarity_rising = false; else return dev_err_probe(dev, -EINVAL, "bad value for 'pclk-sample'\n"); return 0; } static int ub913_hw_init(struct ub913_data *priv) { struct device *dev = &priv->client->dev; bool mode_override; u8 mode; int ret; u8 v; ret = ub913_read(priv, UB913_REG_MODE_SEL, &v); if (ret) return ret; if (!(v & UB913_REG_MODE_SEL_MODE_UP_TO_DATE)) return dev_err_probe(dev, -ENODEV, "Mode value not stabilized\n"); mode_override = v & UB913_REG_MODE_SEL_MODE_OVERRIDE; mode = v & UB913_REG_MODE_SEL_MODE_MASK; dev_dbg(dev, "mode from %s: %#x\n", mode_override ? "reg" : "deserializer", mode); ret = ub913_i2c_master_init(priv); if (ret) return dev_err_probe(dev, ret, "i2c master init failed\n"); ub913_read(priv, UB913_REG_GENERAL_CFG, &v); v &= ~UB913_REG_GENERAL_CFG_PCLK_RISING; v |= priv->pclk_polarity_rising ? UB913_REG_GENERAL_CFG_PCLK_RISING : 0; ub913_write(priv, UB913_REG_GENERAL_CFG, v); return 0; } static int ub913_subdev_init(struct ub913_data *priv) { struct device *dev = &priv->client->dev; int ret; v4l2_i2c_subdev_init(&priv->sd, priv->client, &ub913_subdev_ops); priv->sd.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE | V4L2_SUBDEV_FL_STREAMS; priv->sd.entity.function = MEDIA_ENT_F_VID_IF_BRIDGE; priv->sd.entity.ops = &ub913_entity_ops; priv->pads[0].flags = MEDIA_PAD_FL_SINK; priv->pads[1].flags = MEDIA_PAD_FL_SOURCE; ret = media_entity_pads_init(&priv->sd.entity, 2, priv->pads); if (ret) return dev_err_probe(dev, ret, "Failed to init pads\n"); ret = v4l2_subdev_init_finalize(&priv->sd); if (ret) goto err_entity_cleanup; ret = ub913_v4l2_notifier_register(priv); if (ret) { dev_err_probe(dev, ret, "v4l2 subdev notifier register failed\n"); goto err_subdev_cleanup; } ret = v4l2_async_register_subdev(&priv->sd); if (ret) { dev_err_probe(dev, ret, "v4l2_async_register_subdev error\n"); goto err_unreg_notif; } return 0; err_unreg_notif: ub913_v4l2_nf_unregister(priv); err_subdev_cleanup: v4l2_subdev_cleanup(&priv->sd); err_entity_cleanup: media_entity_cleanup(&priv->sd.entity); return ret; } static void ub913_subdev_uninit(struct ub913_data *priv) { v4l2_async_unregister_subdev(&priv->sd); ub913_v4l2_nf_unregister(priv); v4l2_subdev_cleanup(&priv->sd); fwnode_handle_put(priv->sd.fwnode); media_entity_cleanup(&priv->sd.entity); } static int ub913_probe(struct i2c_client *client) { struct device *dev = &client->dev; struct ub913_data *priv; int ret; priv = devm_kzalloc(dev, sizeof(*priv), GFP_KERNEL); if (!priv) return -ENOMEM; priv->client = client; priv->plat_data = dev_get_platdata(&client->dev); if (!priv->plat_data) return dev_err_probe(dev, -ENODEV, "Platform data missing\n"); priv->regmap = devm_regmap_init_i2c(client, &ub913_regmap_config); if (IS_ERR(priv->regmap)) return dev_err_probe(dev, PTR_ERR(priv->regmap), "Failed to init regmap\n"); /* * ub913 can also work without ext clock, but that is not supported by * the driver yet. */ priv->clkin = devm_clk_get(dev, "clkin"); if (IS_ERR(priv->clkin)) return dev_err_probe(dev, PTR_ERR(priv->clkin), "Cannot get CLKIN\n"); ret = ub913_parse_dt(priv); if (ret) return ret; ret = ub913_hw_init(priv); if (ret) return ret; ret = ub913_gpiochip_probe(priv); if (ret) return dev_err_probe(dev, ret, "Failed to init gpiochip\n"); ret = ub913_register_clkout(priv); if (ret) { dev_err_probe(dev, ret, "Failed to register clkout\n"); goto err_gpiochip_remove; } ret = ub913_subdev_init(priv); if (ret) goto err_gpiochip_remove; ret = ub913_add_i2c_adapter(priv); if (ret) { dev_err_probe(dev, ret, "failed to add remote i2c adapter\n"); goto err_subdev_uninit; } return 0; err_subdev_uninit: ub913_subdev_uninit(priv); err_gpiochip_remove: ub913_gpiochip_remove(priv); return ret; } static void ub913_remove(struct i2c_client *client) { struct v4l2_subdev *sd = i2c_get_clientdata(client); struct ub913_data *priv = sd_to_ub913(sd); i2c_atr_del_adapter(priv->plat_data->atr, priv->plat_data->port); ub913_subdev_uninit(priv); ub913_gpiochip_remove(priv); } static const struct i2c_device_id ub913_id[] = { { "ds90ub913a-q1", 0 }, {} }; MODULE_DEVICE_TABLE(i2c, ub913_id); static const struct of_device_id ub913_dt_ids[] = { { .compatible = "ti,ds90ub913a-q1" }, {} }; MODULE_DEVICE_TABLE(of, ub913_dt_ids); static struct i2c_driver ds90ub913_driver = { .probe = ub913_probe, .remove = ub913_remove, .id_table = ub913_id, .driver = { .name = "ds90ub913a", .of_match_table = ub913_dt_ids, }, }; module_i2c_driver(ds90ub913_driver); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Texas Instruments DS90UB913 FPD-Link III Serializer Driver"); MODULE_AUTHOR("Luca Ceresoli <[email protected]>"); MODULE_AUTHOR("Tomi Valkeinen <[email protected]>"); MODULE_IMPORT_NS(I2C_ATR);
linux-master
drivers/media/i2c/ds90ub913.c
/* * ths8200 - Texas Instruments THS8200 video encoder driver * * Copyright 2013 Cisco Systems, Inc. and/or its affiliates. * * This program is free software; you may redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation version 2. * * This program is distributed .as is. WITHOUT ANY WARRANTY of any * kind, whether express or implied; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <linux/i2c.h> #include <linux/module.h> #include <linux/of.h> #include <linux/v4l2-dv-timings.h> #include <media/v4l2-dv-timings.h> #include <media/v4l2-async.h> #include <media/v4l2-device.h> #include "ths8200_regs.h" static int debug; module_param(debug, int, 0644); MODULE_PARM_DESC(debug, "debug level (0-2)"); MODULE_DESCRIPTION("Texas Instruments THS8200 video encoder driver"); MODULE_AUTHOR("Mats Randgaard <[email protected]>"); MODULE_AUTHOR("Martin Bugge <[email protected]>"); MODULE_LICENSE("GPL v2"); struct ths8200_state { struct v4l2_subdev sd; uint8_t chip_version; /* Is the ths8200 powered on? */ bool power_on; struct v4l2_dv_timings dv_timings; }; static const struct v4l2_dv_timings_cap ths8200_timings_cap = { .type = V4L2_DV_BT_656_1120, /* keep this initialization for compatibility with GCC < 4.4.6 */ .reserved = { 0 }, V4L2_INIT_BT_TIMINGS(640, 1920, 350, 1080, 25000000, 148500000, V4L2_DV_BT_STD_CEA861, V4L2_DV_BT_CAP_PROGRESSIVE) }; static inline struct ths8200_state *to_state(struct v4l2_subdev *sd) { return container_of(sd, struct ths8200_state, sd); } static inline unsigned htotal(const struct v4l2_bt_timings *t) { return V4L2_DV_BT_FRAME_WIDTH(t); } static inline unsigned vtotal(const struct v4l2_bt_timings *t) { return V4L2_DV_BT_FRAME_HEIGHT(t); } static int ths8200_read(struct v4l2_subdev *sd, u8 reg) { struct i2c_client *client = v4l2_get_subdevdata(sd); return i2c_smbus_read_byte_data(client, reg); } static int ths8200_write(struct v4l2_subdev *sd, u8 reg, u8 val) { struct i2c_client *client = v4l2_get_subdevdata(sd); int ret; int i; for (i = 0; i < 3; i++) { ret = i2c_smbus_write_byte_data(client, reg, val); if (ret == 0) return 0; } v4l2_err(sd, "I2C Write Problem\n"); return ret; } /* To set specific bits in the register, a clear-mask is given (to be AND-ed), * and then the value-mask (to be OR-ed). */ static inline void ths8200_write_and_or(struct v4l2_subdev *sd, u8 reg, uint8_t clr_mask, uint8_t val_mask) { ths8200_write(sd, reg, (ths8200_read(sd, reg) & clr_mask) | val_mask); } #ifdef CONFIG_VIDEO_ADV_DEBUG static int ths8200_g_register(struct v4l2_subdev *sd, struct v4l2_dbg_register *reg) { reg->val = ths8200_read(sd, reg->reg & 0xff); reg->size = 1; return 0; } static int ths8200_s_register(struct v4l2_subdev *sd, const struct v4l2_dbg_register *reg) { ths8200_write(sd, reg->reg & 0xff, reg->val & 0xff); return 0; } #endif static int ths8200_log_status(struct v4l2_subdev *sd) { struct ths8200_state *state = to_state(sd); uint8_t reg_03 = ths8200_read(sd, THS8200_CHIP_CTL); v4l2_info(sd, "----- Chip status -----\n"); v4l2_info(sd, "version: %u\n", state->chip_version); v4l2_info(sd, "power: %s\n", (reg_03 & 0x0c) ? "off" : "on"); v4l2_info(sd, "reset: %s\n", (reg_03 & 0x01) ? "off" : "on"); v4l2_info(sd, "test pattern: %s\n", (reg_03 & 0x20) ? "enabled" : "disabled"); v4l2_info(sd, "format: %ux%u\n", ths8200_read(sd, THS8200_DTG2_PIXEL_CNT_MSB) * 256 + ths8200_read(sd, THS8200_DTG2_PIXEL_CNT_LSB), (ths8200_read(sd, THS8200_DTG2_LINE_CNT_MSB) & 0x07) * 256 + ths8200_read(sd, THS8200_DTG2_LINE_CNT_LSB)); v4l2_print_dv_timings(sd->name, "Configured format:", &state->dv_timings, true); return 0; } /* Power up/down ths8200 */ static int ths8200_s_power(struct v4l2_subdev *sd, int on) { struct ths8200_state *state = to_state(sd); v4l2_dbg(1, debug, sd, "%s: power %s\n", __func__, on ? "on" : "off"); state->power_on = on; /* Power up/down - leave in reset state until input video is present */ ths8200_write_and_or(sd, THS8200_CHIP_CTL, 0xf2, (on ? 0x00 : 0x0c)); return 0; } static const struct v4l2_subdev_core_ops ths8200_core_ops = { .log_status = ths8200_log_status, .s_power = ths8200_s_power, #ifdef CONFIG_VIDEO_ADV_DEBUG .g_register = ths8200_g_register, .s_register = ths8200_s_register, #endif }; /* ----------------------------------------------------------------------------- * V4L2 subdev video operations */ static int ths8200_s_stream(struct v4l2_subdev *sd, int enable) { struct ths8200_state *state = to_state(sd); if (enable && !state->power_on) ths8200_s_power(sd, true); ths8200_write_and_or(sd, THS8200_CHIP_CTL, 0xfe, (enable ? 0x01 : 0x00)); v4l2_dbg(1, debug, sd, "%s: %sable\n", __func__, (enable ? "en" : "dis")); return 0; } static void ths8200_core_init(struct v4l2_subdev *sd) { /* setup clocks */ ths8200_write_and_or(sd, THS8200_CHIP_CTL, 0x3f, 0xc0); /**** Data path control (DATA) ****/ /* Set FSADJ 700 mV, * bypass 422-444 interpolation, * input format 30 bit RGB444 */ ths8200_write(sd, THS8200_DATA_CNTL, 0x70); /* DTG Mode (Video blocked during blanking * VESA slave */ ths8200_write(sd, THS8200_DTG1_MODE, 0x87); /**** Display Timing Generator Control, Part 1 (DTG1). ****/ /* Disable embedded syncs on the output by setting * the amplitude to zero for all channels. */ ths8200_write(sd, THS8200_DTG1_Y_SYNC_MSB, 0x00); ths8200_write(sd, THS8200_DTG1_CBCR_SYNC_MSB, 0x00); } static void ths8200_setup(struct v4l2_subdev *sd, struct v4l2_bt_timings *bt) { uint8_t polarity = 0; uint16_t line_start_active_video = (bt->vsync + bt->vbackporch); uint16_t line_start_front_porch = (vtotal(bt) - bt->vfrontporch); /*** System ****/ /* Set chip in reset while it is configured */ ths8200_s_stream(sd, false); /* configure video output timings */ ths8200_write(sd, THS8200_DTG1_SPEC_A, bt->hsync); ths8200_write(sd, THS8200_DTG1_SPEC_B, bt->hfrontporch); /* Zero for progressive scan formats.*/ if (!bt->interlaced) ths8200_write(sd, THS8200_DTG1_SPEC_C, 0x00); /* Distance from leading edge of h sync to start of active video. * MSB in 0x2b */ ths8200_write(sd, THS8200_DTG1_SPEC_D_LSB, (bt->hbackporch + bt->hsync) & 0xff); /* Zero for SDTV-mode. MSB in 0x2b */ ths8200_write(sd, THS8200_DTG1_SPEC_E_LSB, 0x00); /* * MSB for dtg1_spec(d/e/h). See comment for * corresponding LSB registers. */ ths8200_write(sd, THS8200_DTG1_SPEC_DEH_MSB, ((bt->hbackporch + bt->hsync) & 0x100) >> 1); /* h front porch */ ths8200_write(sd, THS8200_DTG1_SPEC_K_LSB, (bt->hfrontporch) & 0xff); ths8200_write(sd, THS8200_DTG1_SPEC_K_MSB, ((bt->hfrontporch) & 0x700) >> 8); /* Half the line length. Used to calculate SDTV line types. */ ths8200_write(sd, THS8200_DTG1_SPEC_G_LSB, (htotal(bt)/2) & 0xff); ths8200_write(sd, THS8200_DTG1_SPEC_G_MSB, ((htotal(bt)/2) >> 8) & 0x0f); /* Total pixels per line (ex. 720p: 1650) */ ths8200_write(sd, THS8200_DTG1_TOT_PIXELS_MSB, htotal(bt) >> 8); ths8200_write(sd, THS8200_DTG1_TOT_PIXELS_LSB, htotal(bt) & 0xff); /* Frame height and field height */ /* Field height should be programmed higher than frame_size for * progressive scan formats */ ths8200_write(sd, THS8200_DTG1_FRAME_FIELD_SZ_MSB, ((vtotal(bt) >> 4) & 0xf0) + 0x7); ths8200_write(sd, THS8200_DTG1_FRAME_SZ_LSB, vtotal(bt) & 0xff); /* Should be programmed higher than frame_size * for progressive formats */ if (!bt->interlaced) ths8200_write(sd, THS8200_DTG1_FIELD_SZ_LSB, 0xff); /**** Display Timing Generator Control, Part 2 (DTG2). ****/ /* Set breakpoint line numbers and types * THS8200 generates line types with different properties. A line type * that sets all the RGB-outputs to zero is used in the blanking areas, * while a line type that enable the RGB-outputs is used in active video * area. The line numbers for start of active video, start of front * porch and after the last line in the frame must be set with the * corresponding line types. * * Line types: * 0x9 - Full normal sync pulse: Blocks data when dtg1_pass is off. * Used in blanking area. * 0x0 - Active video: Video data is always passed. Used in active * video area. */ ths8200_write_and_or(sd, THS8200_DTG2_BP1_2_MSB, 0x88, ((line_start_active_video >> 4) & 0x70) + ((line_start_front_porch >> 8) & 0x07)); ths8200_write(sd, THS8200_DTG2_BP3_4_MSB, ((vtotal(bt)) >> 4) & 0x70); ths8200_write(sd, THS8200_DTG2_BP1_LSB, line_start_active_video & 0xff); ths8200_write(sd, THS8200_DTG2_BP2_LSB, line_start_front_porch & 0xff); ths8200_write(sd, THS8200_DTG2_BP3_LSB, (vtotal(bt)) & 0xff); /* line types */ ths8200_write(sd, THS8200_DTG2_LINETYPE1, 0x90); ths8200_write(sd, THS8200_DTG2_LINETYPE2, 0x90); /* h sync width transmitted */ ths8200_write(sd, THS8200_DTG2_HLENGTH_LSB, bt->hsync & 0xff); ths8200_write_and_or(sd, THS8200_DTG2_HLENGTH_LSB_HDLY_MSB, 0x3f, (bt->hsync >> 2) & 0xc0); /* The pixel value h sync is asserted on */ ths8200_write_and_or(sd, THS8200_DTG2_HLENGTH_LSB_HDLY_MSB, 0xe0, (htotal(bt) >> 8) & 0x1f); ths8200_write(sd, THS8200_DTG2_HLENGTH_HDLY_LSB, htotal(bt)); /* v sync width transmitted (must add 1 to get correct output) */ ths8200_write(sd, THS8200_DTG2_VLENGTH1_LSB, (bt->vsync + 1) & 0xff); ths8200_write_and_or(sd, THS8200_DTG2_VLENGTH1_MSB_VDLY1_MSB, 0x3f, ((bt->vsync + 1) >> 2) & 0xc0); /* The pixel value v sync is asserted on (must add 1 to get correct output) */ ths8200_write_and_or(sd, THS8200_DTG2_VLENGTH1_MSB_VDLY1_MSB, 0xf8, ((vtotal(bt) + 1) >> 8) & 0x7); ths8200_write(sd, THS8200_DTG2_VDLY1_LSB, vtotal(bt) + 1); /* For progressive video vlength2 must be set to all 0 and vdly2 must * be set to all 1. */ ths8200_write(sd, THS8200_DTG2_VLENGTH2_LSB, 0x00); ths8200_write(sd, THS8200_DTG2_VLENGTH2_MSB_VDLY2_MSB, 0x07); ths8200_write(sd, THS8200_DTG2_VDLY2_LSB, 0xff); /* Internal delay factors to synchronize the sync pulses and the data */ /* Experimental values delays (hor 0, ver 0) */ ths8200_write(sd, THS8200_DTG2_HS_IN_DLY_MSB, 0); ths8200_write(sd, THS8200_DTG2_HS_IN_DLY_LSB, 0); ths8200_write(sd, THS8200_DTG2_VS_IN_DLY_MSB, 0); ths8200_write(sd, THS8200_DTG2_VS_IN_DLY_LSB, 0); /* Polarity of received and transmitted sync signals */ if (bt->polarities & V4L2_DV_HSYNC_POS_POL) { polarity |= 0x01; /* HS_IN */ polarity |= 0x08; /* HS_OUT */ } if (bt->polarities & V4L2_DV_VSYNC_POS_POL) { polarity |= 0x02; /* VS_IN */ polarity |= 0x10; /* VS_OUT */ } /* RGB mode, no embedded timings */ /* Timing of video input bus is derived from HS, VS, and FID dedicated * inputs */ ths8200_write(sd, THS8200_DTG2_CNTL, 0x44 | polarity); /* leave reset */ ths8200_s_stream(sd, true); v4l2_dbg(1, debug, sd, "%s: frame %dx%d, polarity %d\n" "horizontal: front porch %d, back porch %d, sync %d\n" "vertical: sync %d\n", __func__, htotal(bt), vtotal(bt), polarity, bt->hfrontporch, bt->hbackporch, bt->hsync, bt->vsync); } static int ths8200_s_dv_timings(struct v4l2_subdev *sd, struct v4l2_dv_timings *timings) { struct ths8200_state *state = to_state(sd); v4l2_dbg(1, debug, sd, "%s:\n", __func__); if (!v4l2_valid_dv_timings(timings, &ths8200_timings_cap, NULL, NULL)) return -EINVAL; if (!v4l2_find_dv_timings_cap(timings, &ths8200_timings_cap, 10, NULL, NULL)) { v4l2_dbg(1, debug, sd, "Unsupported format\n"); return -EINVAL; } timings->bt.flags &= ~V4L2_DV_FL_REDUCED_FPS; /* save timings */ state->dv_timings = *timings; ths8200_setup(sd, &timings->bt); return 0; } static int ths8200_g_dv_timings(struct v4l2_subdev *sd, struct v4l2_dv_timings *timings) { struct ths8200_state *state = to_state(sd); v4l2_dbg(1, debug, sd, "%s:\n", __func__); *timings = state->dv_timings; return 0; } static int ths8200_enum_dv_timings(struct v4l2_subdev *sd, struct v4l2_enum_dv_timings *timings) { if (timings->pad != 0) return -EINVAL; return v4l2_enum_dv_timings_cap(timings, &ths8200_timings_cap, NULL, NULL); } static int ths8200_dv_timings_cap(struct v4l2_subdev *sd, struct v4l2_dv_timings_cap *cap) { if (cap->pad != 0) return -EINVAL; *cap = ths8200_timings_cap; return 0; } /* Specific video subsystem operation handlers */ static const struct v4l2_subdev_video_ops ths8200_video_ops = { .s_stream = ths8200_s_stream, .s_dv_timings = ths8200_s_dv_timings, .g_dv_timings = ths8200_g_dv_timings, }; static const struct v4l2_subdev_pad_ops ths8200_pad_ops = { .enum_dv_timings = ths8200_enum_dv_timings, .dv_timings_cap = ths8200_dv_timings_cap, }; /* V4L2 top level operation handlers */ static const struct v4l2_subdev_ops ths8200_ops = { .core = &ths8200_core_ops, .video = &ths8200_video_ops, .pad = &ths8200_pad_ops, }; static int ths8200_probe(struct i2c_client *client) { struct ths8200_state *state; struct v4l2_subdev *sd; int error; /* Check if the adapter supports the needed features */ if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE_DATA)) return -EIO; state = devm_kzalloc(&client->dev, sizeof(*state), GFP_KERNEL); if (!state) return -ENOMEM; sd = &state->sd; v4l2_i2c_subdev_init(sd, client, &ths8200_ops); state->chip_version = ths8200_read(sd, THS8200_VERSION); v4l2_dbg(1, debug, sd, "chip version 0x%x\n", state->chip_version); ths8200_core_init(sd); error = v4l2_async_register_subdev(&state->sd); if (error) return error; v4l2_info(sd, "%s found @ 0x%x (%s)\n", client->name, client->addr << 1, client->adapter->name); return 0; } static void ths8200_remove(struct i2c_client *client) { struct v4l2_subdev *sd = i2c_get_clientdata(client); struct ths8200_state *decoder = to_state(sd); v4l2_dbg(1, debug, sd, "%s removed @ 0x%x (%s)\n", client->name, client->addr << 1, client->adapter->name); ths8200_s_power(sd, false); v4l2_async_unregister_subdev(&decoder->sd); } static const struct i2c_device_id ths8200_id[] = { { "ths8200", 0 }, {}, }; MODULE_DEVICE_TABLE(i2c, ths8200_id); #if IS_ENABLED(CONFIG_OF) static const struct of_device_id ths8200_of_match[] = { { .compatible = "ti,ths8200", }, { /* sentinel */ }, }; MODULE_DEVICE_TABLE(of, ths8200_of_match); #endif static struct i2c_driver ths8200_driver = { .driver = { .name = "ths8200", .of_match_table = of_match_ptr(ths8200_of_match), }, .probe = ths8200_probe, .remove = ths8200_remove, .id_table = ths8200_id, }; module_i2c_driver(ths8200_driver);
linux-master
drivers/media/i2c/ths8200.c
// SPDX-License-Identifier: GPL-2.0 /* * mt9t112 Camera Driver * * Copyright (C) 2018 Jacopo Mondi <[email protected]> * * Copyright (C) 2009 Renesas Solutions Corp. * Kuninori Morimoto <[email protected]> * * Based on ov772x driver, mt9m111 driver, * * Copyright (C) 2008 Kuninori Morimoto <[email protected]> * Copyright (C) 2008, Robert Jarzmik <[email protected]> * Copyright 2006-7 Jonathan Corbet <[email protected]> * Copyright (C) 2008 Magnus Damm * Copyright (C) 2008, Guennadi Liakhovetski <[email protected]> * * TODO: This driver lacks support for frame rate control due to missing * register level documentation and suitable hardware for testing. * v4l-utils compliance tools will report errors. */ #include <linux/clk.h> #include <linux/delay.h> #include <linux/gpio/consumer.h> #include <linux/i2c.h> #include <linux/init.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/v4l2-mediabus.h> #include <linux/videodev2.h> #include <media/i2c/mt9t112.h> #include <media/v4l2-common.h> #include <media/v4l2-image-sizes.h> #include <media/v4l2-subdev.h> /* you can check PLL/clock info */ /* #define EXT_CLOCK 24000000 */ /************************************************************************ * macro ***********************************************************************/ /* * frame size */ #define MAX_WIDTH 2048 #define MAX_HEIGHT 1536 /* * macro of read/write */ #define ECHECKER(ret, x) \ do { \ (ret) = (x); \ if ((ret) < 0) \ return (ret); \ } while (0) #define mt9t112_reg_write(ret, client, a, b) \ ECHECKER(ret, __mt9t112_reg_write(client, a, b)) #define mt9t112_mcu_write(ret, client, a, b) \ ECHECKER(ret, __mt9t112_mcu_write(client, a, b)) #define mt9t112_reg_mask_set(ret, client, a, b, c) \ ECHECKER(ret, __mt9t112_reg_mask_set(client, a, b, c)) #define mt9t112_mcu_mask_set(ret, client, a, b, c) \ ECHECKER(ret, __mt9t112_mcu_mask_set(client, a, b, c)) #define mt9t112_reg_read(ret, client, a) \ ECHECKER(ret, __mt9t112_reg_read(client, a)) /* * Logical address */ #define _VAR(id, offset, base) (base | (id & 0x1f) << 10 | (offset & 0x3ff)) #define VAR(id, offset) _VAR(id, offset, 0x0000) #define VAR8(id, offset) _VAR(id, offset, 0x8000) /************************************************************************ * struct ***********************************************************************/ struct mt9t112_format { u32 code; enum v4l2_colorspace colorspace; u16 fmt; u16 order; }; struct mt9t112_priv { struct v4l2_subdev subdev; struct mt9t112_platform_data *info; struct i2c_client *client; struct v4l2_rect frame; struct clk *clk; struct gpio_desc *standby_gpio; const struct mt9t112_format *format; int num_formats; bool init_done; }; /************************************************************************ * supported format ***********************************************************************/ static const struct mt9t112_format mt9t112_cfmts[] = { { .code = MEDIA_BUS_FMT_UYVY8_2X8, .colorspace = V4L2_COLORSPACE_SRGB, .fmt = 1, .order = 0, }, { .code = MEDIA_BUS_FMT_VYUY8_2X8, .colorspace = V4L2_COLORSPACE_SRGB, .fmt = 1, .order = 1, }, { .code = MEDIA_BUS_FMT_YUYV8_2X8, .colorspace = V4L2_COLORSPACE_SRGB, .fmt = 1, .order = 2, }, { .code = MEDIA_BUS_FMT_YVYU8_2X8, .colorspace = V4L2_COLORSPACE_SRGB, .fmt = 1, .order = 3, }, { .code = MEDIA_BUS_FMT_RGB555_2X8_PADHI_LE, .colorspace = V4L2_COLORSPACE_SRGB, .fmt = 8, .order = 2, }, { .code = MEDIA_BUS_FMT_RGB565_2X8_LE, .colorspace = V4L2_COLORSPACE_SRGB, .fmt = 4, .order = 2, }, }; /************************************************************************ * general function ***********************************************************************/ static struct mt9t112_priv *to_mt9t112(const struct i2c_client *client) { return container_of(i2c_get_clientdata(client), struct mt9t112_priv, subdev); } static int __mt9t112_reg_read(const struct i2c_client *client, u16 command) { struct i2c_msg msg[2]; u8 buf[2]; int ret; command = swab16(command); msg[0].addr = client->addr; msg[0].flags = 0; msg[0].len = 2; msg[0].buf = (u8 *)&command; msg[1].addr = client->addr; msg[1].flags = I2C_M_RD; msg[1].len = 2; msg[1].buf = buf; /* * If return value of this function is < 0, it means error, else, * below 16bit is valid data. */ ret = i2c_transfer(client->adapter, msg, 2); if (ret < 0) return ret; memcpy(&ret, buf, 2); return swab16(ret); } static int __mt9t112_reg_write(const struct i2c_client *client, u16 command, u16 data) { struct i2c_msg msg; u8 buf[4]; int ret; command = swab16(command); data = swab16(data); memcpy(buf + 0, &command, 2); memcpy(buf + 2, &data, 2); msg.addr = client->addr; msg.flags = 0; msg.len = 4; msg.buf = buf; /* * i2c_transfer return message length, but this function should * return 0 if correct case. */ ret = i2c_transfer(client->adapter, &msg, 1); return ret >= 0 ? 0 : ret; } static int __mt9t112_reg_mask_set(const struct i2c_client *client, u16 command, u16 mask, u16 set) { int val = __mt9t112_reg_read(client, command); if (val < 0) return val; val &= ~mask; val |= set & mask; return __mt9t112_reg_write(client, command, val); } /* mcu access */ static int __mt9t112_mcu_read(const struct i2c_client *client, u16 command) { int ret; ret = __mt9t112_reg_write(client, 0x098E, command); if (ret < 0) return ret; return __mt9t112_reg_read(client, 0x0990); } static int __mt9t112_mcu_write(const struct i2c_client *client, u16 command, u16 data) { int ret; ret = __mt9t112_reg_write(client, 0x098E, command); if (ret < 0) return ret; return __mt9t112_reg_write(client, 0x0990, data); } static int __mt9t112_mcu_mask_set(const struct i2c_client *client, u16 command, u16 mask, u16 set) { int val = __mt9t112_mcu_read(client, command); if (val < 0) return val; val &= ~mask; val |= set & mask; return __mt9t112_mcu_write(client, command, val); } static int mt9t112_reset(const struct i2c_client *client) { int ret; mt9t112_reg_mask_set(ret, client, 0x001a, 0x0001, 0x0001); usleep_range(1000, 5000); mt9t112_reg_mask_set(ret, client, 0x001a, 0x0001, 0x0000); return ret; } #ifndef EXT_CLOCK #define CLOCK_INFO(a, b) #else #define CLOCK_INFO(a, b) mt9t112_clock_info(a, b) static int mt9t112_clock_info(const struct i2c_client *client, u32 ext) { int m, n, p1, p2, p3, p4, p5, p6, p7; u32 vco, clk; char *enable; ext /= 1000; /* kbyte order */ mt9t112_reg_read(n, client, 0x0012); p1 = n & 0x000f; n = n >> 4; p2 = n & 0x000f; n = n >> 4; p3 = n & 0x000f; mt9t112_reg_read(n, client, 0x002a); p4 = n & 0x000f; n = n >> 4; p5 = n & 0x000f; n = n >> 4; p6 = n & 0x000f; mt9t112_reg_read(n, client, 0x002c); p7 = n & 0x000f; mt9t112_reg_read(n, client, 0x0010); m = n & 0x00ff; n = (n >> 8) & 0x003f; enable = ((ext < 6000) || (ext > 54000)) ? "X" : ""; dev_dbg(&client->dev, "EXTCLK : %10u K %s\n", ext, enable); vco = 2 * m * ext / (n + 1); enable = ((vco < 384000) || (vco > 768000)) ? "X" : ""; dev_dbg(&client->dev, "VCO : %10u K %s\n", vco, enable); clk = vco / (p1 + 1) / (p2 + 1); enable = (clk > 96000) ? "X" : ""; dev_dbg(&client->dev, "PIXCLK : %10u K %s\n", clk, enable); clk = vco / (p3 + 1); enable = (clk > 768000) ? "X" : ""; dev_dbg(&client->dev, "MIPICLK : %10u K %s\n", clk, enable); clk = vco / (p6 + 1); enable = (clk > 96000) ? "X" : ""; dev_dbg(&client->dev, "MCU CLK : %10u K %s\n", clk, enable); clk = vco / (p5 + 1); enable = (clk > 54000) ? "X" : ""; dev_dbg(&client->dev, "SOC CLK : %10u K %s\n", clk, enable); clk = vco / (p4 + 1); enable = (clk > 70000) ? "X" : ""; dev_dbg(&client->dev, "Sensor CLK : %10u K %s\n", clk, enable); clk = vco / (p7 + 1); dev_dbg(&client->dev, "External sensor : %10u K\n", clk); clk = ext / (n + 1); enable = ((clk < 2000) || (clk > 24000)) ? "X" : ""; dev_dbg(&client->dev, "PFD : %10u K %s\n", clk, enable); return 0; } #endif static int mt9t112_set_a_frame_size(const struct i2c_client *client, u16 width, u16 height) { int ret; u16 wstart = (MAX_WIDTH - width) / 2; u16 hstart = (MAX_HEIGHT - height) / 2; /* (Context A) Image Width/Height. */ mt9t112_mcu_write(ret, client, VAR(26, 0), width); mt9t112_mcu_write(ret, client, VAR(26, 2), height); /* (Context A) Output Width/Height. */ mt9t112_mcu_write(ret, client, VAR(18, 43), 8 + width); mt9t112_mcu_write(ret, client, VAR(18, 45), 8 + height); /* (Context A) Start Row/Column. */ mt9t112_mcu_write(ret, client, VAR(18, 2), 4 + hstart); mt9t112_mcu_write(ret, client, VAR(18, 4), 4 + wstart); /* (Context A) End Row/Column. */ mt9t112_mcu_write(ret, client, VAR(18, 6), 11 + height + hstart); mt9t112_mcu_write(ret, client, VAR(18, 8), 11 + width + wstart); mt9t112_mcu_write(ret, client, VAR8(1, 0), 0x06); return ret; } static int mt9t112_set_pll_dividers(const struct i2c_client *client, u8 m, u8 n, u8 p1, u8 p2, u8 p3, u8 p4, u8 p5, u8 p6, u8 p7) { int ret; u16 val; /* N/M */ val = (n << 8) | (m << 0); mt9t112_reg_mask_set(ret, client, 0x0010, 0x3fff, val); /* P1/P2/P3 */ val = ((p3 & 0x0F) << 8) | ((p2 & 0x0F) << 4) | ((p1 & 0x0F) << 0); mt9t112_reg_mask_set(ret, client, 0x0012, 0x0fff, val); /* P4/P5/P6 */ val = (0x7 << 12) | ((p6 & 0x0F) << 8) | ((p5 & 0x0F) << 4) | ((p4 & 0x0F) << 0); mt9t112_reg_mask_set(ret, client, 0x002A, 0x7fff, val); /* P7 */ val = (0x1 << 12) | ((p7 & 0x0F) << 0); mt9t112_reg_mask_set(ret, client, 0x002C, 0x100f, val); return ret; } static int mt9t112_init_pll(const struct i2c_client *client) { struct mt9t112_priv *priv = to_mt9t112(client); int data, i, ret; mt9t112_reg_mask_set(ret, client, 0x0014, 0x003, 0x0001); /* PLL control: BYPASS PLL = 8517. */ mt9t112_reg_write(ret, client, 0x0014, 0x2145); /* Replace these registers when new timing parameters are generated. */ mt9t112_set_pll_dividers(client, priv->info->divider.m, priv->info->divider.n, priv->info->divider.p1, priv->info->divider.p2, priv->info->divider.p3, priv->info->divider.p4, priv->info->divider.p5, priv->info->divider.p6, priv->info->divider.p7); /* * TEST_BYPASS on * PLL_ENABLE on * SEL_LOCK_DET on * TEST_BYPASS off */ mt9t112_reg_write(ret, client, 0x0014, 0x2525); mt9t112_reg_write(ret, client, 0x0014, 0x2527); mt9t112_reg_write(ret, client, 0x0014, 0x3427); mt9t112_reg_write(ret, client, 0x0014, 0x3027); mdelay(10); /* * PLL_BYPASS off * Reference clock count * I2C Master Clock Divider */ mt9t112_reg_write(ret, client, 0x0014, 0x3046); /* JPEG initialization workaround */ mt9t112_reg_write(ret, client, 0x0016, 0x0400); mt9t112_reg_write(ret, client, 0x0022, 0x0190); mt9t112_reg_write(ret, client, 0x3B84, 0x0212); /* External sensor clock is PLL bypass. */ mt9t112_reg_write(ret, client, 0x002E, 0x0500); mt9t112_reg_mask_set(ret, client, 0x0018, 0x0002, 0x0002); mt9t112_reg_mask_set(ret, client, 0x3B82, 0x0004, 0x0004); /* MCU disabled. */ mt9t112_reg_mask_set(ret, client, 0x0018, 0x0004, 0x0004); /* Out of standby. */ mt9t112_reg_mask_set(ret, client, 0x0018, 0x0001, 0); mdelay(50); /* * Standby Workaround * Disable Secondary I2C Pads */ mt9t112_reg_write(ret, client, 0x0614, 0x0001); mdelay(1); mt9t112_reg_write(ret, client, 0x0614, 0x0001); mdelay(1); mt9t112_reg_write(ret, client, 0x0614, 0x0001); mdelay(1); mt9t112_reg_write(ret, client, 0x0614, 0x0001); mdelay(1); mt9t112_reg_write(ret, client, 0x0614, 0x0001); mdelay(1); mt9t112_reg_write(ret, client, 0x0614, 0x0001); mdelay(1); /* Poll to verify out of standby. Must Poll this bit. */ for (i = 0; i < 100; i++) { mt9t112_reg_read(data, client, 0x0018); if (!(data & 0x4000)) break; mdelay(10); } return ret; } static int mt9t112_init_setting(const struct i2c_client *client) { int ret; /* Adaptive Output Clock (A) */ mt9t112_mcu_mask_set(ret, client, VAR(26, 160), 0x0040, 0x0000); /* Read Mode (A) */ mt9t112_mcu_write(ret, client, VAR(18, 12), 0x0024); /* Fine Correction (A) */ mt9t112_mcu_write(ret, client, VAR(18, 15), 0x00CC); /* Fine IT Min (A) */ mt9t112_mcu_write(ret, client, VAR(18, 17), 0x01f1); /* Fine IT Max Margin (A) */ mt9t112_mcu_write(ret, client, VAR(18, 19), 0x00fF); /* Base Frame Lines (A) */ mt9t112_mcu_write(ret, client, VAR(18, 29), 0x032D); /* Min Line Length (A) */ mt9t112_mcu_write(ret, client, VAR(18, 31), 0x073a); /* Line Length (A) */ mt9t112_mcu_write(ret, client, VAR(18, 37), 0x07d0); /* Adaptive Output Clock (B) */ mt9t112_mcu_mask_set(ret, client, VAR(27, 160), 0x0040, 0x0000); /* Row Start (B) */ mt9t112_mcu_write(ret, client, VAR(18, 74), 0x004); /* Column Start (B) */ mt9t112_mcu_write(ret, client, VAR(18, 76), 0x004); /* Row End (B) */ mt9t112_mcu_write(ret, client, VAR(18, 78), 0x60B); /* Column End (B) */ mt9t112_mcu_write(ret, client, VAR(18, 80), 0x80B); /* Fine Correction (B) */ mt9t112_mcu_write(ret, client, VAR(18, 87), 0x008C); /* Fine IT Min (B) */ mt9t112_mcu_write(ret, client, VAR(18, 89), 0x01F1); /* Fine IT Max Margin (B) */ mt9t112_mcu_write(ret, client, VAR(18, 91), 0x00FF); /* Base Frame Lines (B) */ mt9t112_mcu_write(ret, client, VAR(18, 101), 0x0668); /* Min Line Length (B) */ mt9t112_mcu_write(ret, client, VAR(18, 103), 0x0AF0); /* Line Length (B) */ mt9t112_mcu_write(ret, client, VAR(18, 109), 0x0AF0); /* * Flicker Detection registers. * This section should be replaced whenever new timing file is * generated. All the following registers need to be replaced. * Following registers are generated from Register Wizard but user can * modify them. For detail see auto flicker detection tuning. */ /* FD_FDPERIOD_SELECT */ mt9t112_mcu_write(ret, client, VAR8(8, 5), 0x01); /* PRI_B_CONFIG_FD_ALGO_RUN */ mt9t112_mcu_write(ret, client, VAR(27, 17), 0x0003); /* PRI_A_CONFIG_FD_ALGO_RUN */ mt9t112_mcu_write(ret, client, VAR(26, 17), 0x0003); /* * AFD range detection tuning registers. */ /* Search_f1_50 */ mt9t112_mcu_write(ret, client, VAR8(18, 165), 0x25); /* Search_f2_50 */ mt9t112_mcu_write(ret, client, VAR8(18, 166), 0x28); /* Search_f1_60 */ mt9t112_mcu_write(ret, client, VAR8(18, 167), 0x2C); /* Search_f2_60 */ mt9t112_mcu_write(ret, client, VAR8(18, 168), 0x2F); /* Period_50Hz (A) */ mt9t112_mcu_write(ret, client, VAR8(18, 68), 0xBA); /* Secret register by Aptina. */ /* Period_50Hz (A MSB) */ mt9t112_mcu_write(ret, client, VAR8(18, 303), 0x00); /* Period_60Hz (A) */ mt9t112_mcu_write(ret, client, VAR8(18, 69), 0x9B); /* Secret register by Aptina. */ /* Period_60Hz (A MSB) */ mt9t112_mcu_write(ret, client, VAR8(18, 301), 0x00); /* Period_50Hz (B) */ mt9t112_mcu_write(ret, client, VAR8(18, 140), 0x82); /* Secret register by Aptina. */ /* Period_50Hz (B) MSB */ mt9t112_mcu_write(ret, client, VAR8(18, 304), 0x00); /* Period_60Hz (B) */ mt9t112_mcu_write(ret, client, VAR8(18, 141), 0x6D); /* Secret register by Aptina. */ /* Period_60Hz (B) MSB */ mt9t112_mcu_write(ret, client, VAR8(18, 302), 0x00); /* FD Mode */ mt9t112_mcu_write(ret, client, VAR8(8, 2), 0x10); /* Stat_min */ mt9t112_mcu_write(ret, client, VAR8(8, 9), 0x02); /* Stat_max */ mt9t112_mcu_write(ret, client, VAR8(8, 10), 0x03); /* Min_amplitude */ mt9t112_mcu_write(ret, client, VAR8(8, 12), 0x0A); /* RX FIFO Watermark (A) */ mt9t112_mcu_write(ret, client, VAR(18, 70), 0x0014); /* RX FIFO Watermark (B) */ mt9t112_mcu_write(ret, client, VAR(18, 142), 0x0014); /* MCLK: 16MHz * PCLK: 73MHz * CorePixCLK: 36.5 MHz */ mt9t112_mcu_write(ret, client, VAR8(18, 0x0044), 133); mt9t112_mcu_write(ret, client, VAR8(18, 0x0045), 110); mt9t112_mcu_write(ret, client, VAR8(18, 0x008c), 130); mt9t112_mcu_write(ret, client, VAR8(18, 0x008d), 108); mt9t112_mcu_write(ret, client, VAR8(18, 0x00A5), 27); mt9t112_mcu_write(ret, client, VAR8(18, 0x00a6), 30); mt9t112_mcu_write(ret, client, VAR8(18, 0x00a7), 32); mt9t112_mcu_write(ret, client, VAR8(18, 0x00a8), 35); return ret; } static int mt9t112_auto_focus_setting(const struct i2c_client *client) { int ret; mt9t112_mcu_write(ret, client, VAR(12, 13), 0x000F); mt9t112_mcu_write(ret, client, VAR(12, 23), 0x0F0F); mt9t112_mcu_write(ret, client, VAR8(1, 0), 0x06); mt9t112_reg_write(ret, client, 0x0614, 0x0000); mt9t112_mcu_write(ret, client, VAR8(1, 0), 0x05); mt9t112_mcu_write(ret, client, VAR8(12, 2), 0x02); mt9t112_mcu_write(ret, client, VAR(12, 3), 0x0002); mt9t112_mcu_write(ret, client, VAR(17, 3), 0x8001); mt9t112_mcu_write(ret, client, VAR(17, 11), 0x0025); mt9t112_mcu_write(ret, client, VAR(17, 13), 0x0193); mt9t112_mcu_write(ret, client, VAR8(17, 33), 0x18); mt9t112_mcu_write(ret, client, VAR8(1, 0), 0x05); return ret; } static int mt9t112_auto_focus_trigger(const struct i2c_client *client) { int ret; mt9t112_mcu_write(ret, client, VAR8(12, 25), 0x01); return ret; } static int mt9t112_init_camera(const struct i2c_client *client) { int ret; ECHECKER(ret, mt9t112_reset(client)); ECHECKER(ret, mt9t112_init_pll(client)); ECHECKER(ret, mt9t112_init_setting(client)); ECHECKER(ret, mt9t112_auto_focus_setting(client)); mt9t112_reg_mask_set(ret, client, 0x0018, 0x0004, 0); /* Analog setting B.*/ mt9t112_reg_write(ret, client, 0x3084, 0x2409); mt9t112_reg_write(ret, client, 0x3092, 0x0A49); mt9t112_reg_write(ret, client, 0x3094, 0x4949); mt9t112_reg_write(ret, client, 0x3096, 0x4950); /* * Disable adaptive clock. * PRI_A_CONFIG_JPEG_OB_TX_CONTROL_VAR * PRI_B_CONFIG_JPEG_OB_TX_CONTROL_VAR */ mt9t112_mcu_write(ret, client, VAR(26, 160), 0x0A2E); mt9t112_mcu_write(ret, client, VAR(27, 160), 0x0A2E); /* * Configure Status in Status_before_length Format and enable header. * PRI_B_CONFIG_JPEG_OB_TX_CONTROL_VAR */ mt9t112_mcu_write(ret, client, VAR(27, 144), 0x0CB4); /* * Enable JPEG in context B. * PRI_B_CONFIG_JPEG_OB_TX_CONTROL_VAR */ mt9t112_mcu_write(ret, client, VAR8(27, 142), 0x01); /* Disable Dac_TXLO. */ mt9t112_reg_write(ret, client, 0x316C, 0x350F); /* Set max slew rates. */ mt9t112_reg_write(ret, client, 0x1E, 0x777); return ret; } /************************************************************************ * v4l2_subdev_core_ops ***********************************************************************/ #ifdef CONFIG_VIDEO_ADV_DEBUG static int mt9t112_g_register(struct v4l2_subdev *sd, struct v4l2_dbg_register *reg) { struct i2c_client *client = v4l2_get_subdevdata(sd); int ret; reg->size = 2; mt9t112_reg_read(ret, client, reg->reg); reg->val = (__u64)ret; return 0; } static int mt9t112_s_register(struct v4l2_subdev *sd, const struct v4l2_dbg_register *reg) { struct i2c_client *client = v4l2_get_subdevdata(sd); int ret; mt9t112_reg_write(ret, client, reg->reg, reg->val); return ret; } #endif static int mt9t112_power_on(struct mt9t112_priv *priv) { int ret; ret = clk_prepare_enable(priv->clk); if (ret) return ret; if (priv->standby_gpio) { gpiod_set_value(priv->standby_gpio, 0); msleep(100); } return 0; } static int mt9t112_power_off(struct mt9t112_priv *priv) { clk_disable_unprepare(priv->clk); if (priv->standby_gpio) { gpiod_set_value(priv->standby_gpio, 1); msleep(100); } return 0; } static int mt9t112_s_power(struct v4l2_subdev *sd, int on) { struct i2c_client *client = v4l2_get_subdevdata(sd); struct mt9t112_priv *priv = to_mt9t112(client); return on ? mt9t112_power_on(priv) : mt9t112_power_off(priv); } static const struct v4l2_subdev_core_ops mt9t112_subdev_core_ops = { #ifdef CONFIG_VIDEO_ADV_DEBUG .g_register = mt9t112_g_register, .s_register = mt9t112_s_register, #endif .s_power = mt9t112_s_power, }; /************************************************************************ * v4l2_subdev_video_ops **********************************************************************/ static int mt9t112_s_stream(struct v4l2_subdev *sd, int enable) { struct i2c_client *client = v4l2_get_subdevdata(sd); struct mt9t112_priv *priv = to_mt9t112(client); int ret = 0; if (!enable) { /* FIXME * * If user selected large output size, and used it long time, * mt9t112 camera will be very warm. * * But current driver can not stop mt9t112 camera. * So, set small size here to solve this problem. */ mt9t112_set_a_frame_size(client, VGA_WIDTH, VGA_HEIGHT); return ret; } if (!priv->init_done) { u16 param = MT9T112_FLAG_PCLK_RISING_EDGE & priv->info->flags ? 0x0001 : 0x0000; ECHECKER(ret, mt9t112_init_camera(client)); /* Invert PCLK (Data sampled on falling edge of pixclk). */ mt9t112_reg_write(ret, client, 0x3C20, param); mdelay(5); priv->init_done = true; } mt9t112_mcu_write(ret, client, VAR(26, 7), priv->format->fmt); mt9t112_mcu_write(ret, client, VAR(26, 9), priv->format->order); mt9t112_mcu_write(ret, client, VAR8(1, 0), 0x06); mt9t112_set_a_frame_size(client, priv->frame.width, priv->frame.height); ECHECKER(ret, mt9t112_auto_focus_trigger(client)); dev_dbg(&client->dev, "format : %d\n", priv->format->code); dev_dbg(&client->dev, "size : %d x %d\n", priv->frame.width, priv->frame.height); CLOCK_INFO(client, EXT_CLOCK); return ret; } static int mt9t112_set_params(struct mt9t112_priv *priv, const struct v4l2_rect *rect, u32 code) { int i; /* * get color format */ for (i = 0; i < priv->num_formats; i++) if (mt9t112_cfmts[i].code == code) break; if (i == priv->num_formats) return -EINVAL; priv->frame = *rect; /* * frame size check */ v4l_bound_align_image(&priv->frame.width, 0, MAX_WIDTH, 0, &priv->frame.height, 0, MAX_HEIGHT, 0, 0); priv->format = mt9t112_cfmts + i; return 0; } static int mt9t112_get_selection(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_selection *sel) { struct i2c_client *client = v4l2_get_subdevdata(sd); struct mt9t112_priv *priv = to_mt9t112(client); if (sel->which != V4L2_SUBDEV_FORMAT_ACTIVE) return -EINVAL; switch (sel->target) { case V4L2_SEL_TGT_CROP_BOUNDS: sel->r.left = 0; sel->r.top = 0; sel->r.width = MAX_WIDTH; sel->r.height = MAX_HEIGHT; return 0; case V4L2_SEL_TGT_CROP: sel->r = priv->frame; return 0; default: return -EINVAL; } } static int mt9t112_set_selection(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_selection *sel) { struct i2c_client *client = v4l2_get_subdevdata(sd); struct mt9t112_priv *priv = to_mt9t112(client); const struct v4l2_rect *rect = &sel->r; if (sel->which != V4L2_SUBDEV_FORMAT_ACTIVE || sel->target != V4L2_SEL_TGT_CROP) return -EINVAL; return mt9t112_set_params(priv, rect, priv->format->code); } static int mt9t112_get_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *format) { struct v4l2_mbus_framefmt *mf = &format->format; struct i2c_client *client = v4l2_get_subdevdata(sd); struct mt9t112_priv *priv = to_mt9t112(client); if (format->pad) return -EINVAL; mf->width = priv->frame.width; mf->height = priv->frame.height; mf->colorspace = priv->format->colorspace; mf->code = priv->format->code; mf->field = V4L2_FIELD_NONE; return 0; } static int mt9t112_s_fmt(struct v4l2_subdev *sd, struct v4l2_mbus_framefmt *mf) { struct i2c_client *client = v4l2_get_subdevdata(sd); struct mt9t112_priv *priv = to_mt9t112(client); struct v4l2_rect rect = { .width = mf->width, .height = mf->height, .left = priv->frame.left, .top = priv->frame.top, }; int ret; ret = mt9t112_set_params(priv, &rect, mf->code); if (!ret) mf->colorspace = priv->format->colorspace; return ret; } static int mt9t112_set_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *format) { struct i2c_client *client = v4l2_get_subdevdata(sd); struct v4l2_mbus_framefmt *mf = &format->format; struct mt9t112_priv *priv = to_mt9t112(client); int i; if (format->pad) return -EINVAL; for (i = 0; i < priv->num_formats; i++) if (mt9t112_cfmts[i].code == mf->code) break; if (i == priv->num_formats) { mf->code = MEDIA_BUS_FMT_UYVY8_2X8; mf->colorspace = V4L2_COLORSPACE_JPEG; } else { mf->colorspace = mt9t112_cfmts[i].colorspace; } v4l_bound_align_image(&mf->width, 0, MAX_WIDTH, 0, &mf->height, 0, MAX_HEIGHT, 0, 0); mf->field = V4L2_FIELD_NONE; if (format->which == V4L2_SUBDEV_FORMAT_ACTIVE) return mt9t112_s_fmt(sd, mf); sd_state->pads->try_fmt = *mf; return 0; } static int mt9t112_enum_mbus_code(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_mbus_code_enum *code) { struct i2c_client *client = v4l2_get_subdevdata(sd); struct mt9t112_priv *priv = to_mt9t112(client); if (code->pad || code->index >= priv->num_formats) return -EINVAL; code->code = mt9t112_cfmts[code->index].code; return 0; } static const struct v4l2_subdev_video_ops mt9t112_subdev_video_ops = { .s_stream = mt9t112_s_stream, }; static const struct v4l2_subdev_pad_ops mt9t112_subdev_pad_ops = { .enum_mbus_code = mt9t112_enum_mbus_code, .get_selection = mt9t112_get_selection, .set_selection = mt9t112_set_selection, .get_fmt = mt9t112_get_fmt, .set_fmt = mt9t112_set_fmt, }; /************************************************************************ * i2c driver ***********************************************************************/ static const struct v4l2_subdev_ops mt9t112_subdev_ops = { .core = &mt9t112_subdev_core_ops, .video = &mt9t112_subdev_video_ops, .pad = &mt9t112_subdev_pad_ops, }; static int mt9t112_camera_probe(struct i2c_client *client) { struct mt9t112_priv *priv = to_mt9t112(client); const char *devname; int chipid; int ret; ret = mt9t112_s_power(&priv->subdev, 1); if (ret < 0) return ret; /* Check and show chip ID. */ mt9t112_reg_read(chipid, client, 0x0000); switch (chipid) { case 0x2680: devname = "mt9t111"; priv->num_formats = 1; break; case 0x2682: devname = "mt9t112"; priv->num_formats = ARRAY_SIZE(mt9t112_cfmts); break; default: dev_err(&client->dev, "Product ID error %04x\n", chipid); ret = -ENODEV; goto done; } dev_info(&client->dev, "%s chip ID %04x\n", devname, chipid); done: mt9t112_s_power(&priv->subdev, 0); return ret; } static int mt9t112_probe(struct i2c_client *client) { struct mt9t112_priv *priv; int ret; if (!client->dev.platform_data) { dev_err(&client->dev, "mt9t112: missing platform data!\n"); return -EINVAL; } priv = devm_kzalloc(&client->dev, sizeof(*priv), GFP_KERNEL); if (!priv) return -ENOMEM; priv->info = client->dev.platform_data; priv->init_done = false; v4l2_i2c_subdev_init(&priv->subdev, client, &mt9t112_subdev_ops); priv->clk = devm_clk_get(&client->dev, "extclk"); if (PTR_ERR(priv->clk) == -ENOENT) { priv->clk = NULL; } else if (IS_ERR(priv->clk)) { dev_err(&client->dev, "Unable to get clock \"extclk\"\n"); return PTR_ERR(priv->clk); } priv->standby_gpio = devm_gpiod_get_optional(&client->dev, "standby", GPIOD_OUT_HIGH); if (IS_ERR(priv->standby_gpio)) { dev_err(&client->dev, "Unable to get gpio \"standby\"\n"); return PTR_ERR(priv->standby_gpio); } ret = mt9t112_camera_probe(client); if (ret) return ret; return v4l2_async_register_subdev(&priv->subdev); } static void mt9t112_remove(struct i2c_client *client) { struct mt9t112_priv *priv = to_mt9t112(client); clk_disable_unprepare(priv->clk); v4l2_async_unregister_subdev(&priv->subdev); } static const struct i2c_device_id mt9t112_id[] = { { "mt9t112", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, mt9t112_id); static struct i2c_driver mt9t112_i2c_driver = { .driver = { .name = "mt9t112", }, .probe = mt9t112_probe, .remove = mt9t112_remove, .id_table = mt9t112_id, }; module_i2c_driver(mt9t112_i2c_driver); MODULE_DESCRIPTION("V4L2 driver for MT9T111/MT9T112 camera sensor"); MODULE_AUTHOR("Kuninori Morimoto"); MODULE_LICENSE("GPL v2");
linux-master
drivers/media/i2c/mt9t112.c
// SPDX-License-Identifier: GPL-2.0 // // tvp5150 - Texas Instruments TVP5150A/AM1 and TVP5151 video decoder driver // // Copyright (c) 2005,2006 Mauro Carvalho Chehab <[email protected]> #include <dt-bindings/media/tvp5150.h> #include <linux/i2c.h> #include <linux/slab.h> #include <linux/videodev2.h> #include <linux/delay.h> #include <linux/gpio/consumer.h> #include <linux/interrupt.h> #include <linux/module.h> #include <linux/of_graph.h> #include <linux/pm_runtime.h> #include <linux/regmap.h> #include <media/v4l2-async.h> #include <media/v4l2-device.h> #include <media/v4l2-event.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-fwnode.h> #include <media/v4l2-mc.h> #include <media/v4l2-rect.h> #include "tvp5150_reg.h" #define TVP5150_H_MAX 720U #define TVP5150_V_MAX_525_60 480U #define TVP5150_V_MAX_OTHERS 576U #define TVP5150_MAX_CROP_LEFT 511 #define TVP5150_MAX_CROP_TOP 127 #define TVP5150_CROP_SHIFT 2 #define TVP5150_MBUS_FMT MEDIA_BUS_FMT_UYVY8_2X8 #define TVP5150_FIELD V4L2_FIELD_ALTERNATE #define TVP5150_COLORSPACE V4L2_COLORSPACE_SMPTE170M #define TVP5150_STD_MASK (V4L2_STD_NTSC | \ V4L2_STD_NTSC_443 | \ V4L2_STD_PAL | \ V4L2_STD_PAL_M | \ V4L2_STD_PAL_N | \ V4L2_STD_PAL_Nc | \ V4L2_STD_SECAM) #define TVP5150_MAX_CONNECTORS 3 /* Check dt-bindings for more information */ MODULE_DESCRIPTION("Texas Instruments TVP5150A/TVP5150AM1/TVP5151 video decoder driver"); MODULE_AUTHOR("Mauro Carvalho Chehab"); MODULE_LICENSE("GPL v2"); static int debug; module_param(debug, int, 0644); MODULE_PARM_DESC(debug, "Debug level (0-2)"); #define dprintk0(__dev, __arg...) dev_dbg_lvl(__dev, 0, 0, __arg) enum tvp5150_pads { TVP5150_PAD_AIP1A, TVP5150_PAD_AIP1B, TVP5150_PAD_VID_OUT, TVP5150_NUM_PADS }; struct tvp5150_connector { struct v4l2_fwnode_connector base; struct media_entity ent; struct media_pad pad; }; struct tvp5150 { struct v4l2_subdev sd; struct media_pad pads[TVP5150_NUM_PADS]; struct tvp5150_connector connectors[TVP5150_MAX_CONNECTORS]; struct tvp5150_connector *cur_connector; unsigned int connectors_num; struct v4l2_ctrl_handler hdl; struct v4l2_rect rect; struct regmap *regmap; int irq; v4l2_std_id norm; /* Current set standard */ v4l2_std_id detected_norm; u32 input; u32 output; u32 oe; int enable; bool lock; u16 dev_id; u16 rom_ver; enum v4l2_mbus_type mbus_type; }; static inline struct tvp5150 *to_tvp5150(struct v4l2_subdev *sd) { return container_of(sd, struct tvp5150, sd); } static inline struct v4l2_subdev *to_sd(struct v4l2_ctrl *ctrl) { return &container_of(ctrl->handler, struct tvp5150, hdl)->sd; } static int tvp5150_read(struct v4l2_subdev *sd, unsigned char addr) { struct tvp5150 *decoder = to_tvp5150(sd); int ret, val; ret = regmap_read(decoder->regmap, addr, &val); if (ret < 0) return ret; return val; } static void dump_reg_range(struct v4l2_subdev *sd, char *s, u8 init, const u8 end, int max_line) { u8 buf[16]; int i = 0, j, len; if (max_line > 16) { dprintk0(sd->dev, "too much data to dump\n"); return; } for (i = init; i < end; i += max_line) { len = (end - i > max_line) ? max_line : end - i; for (j = 0; j < len; j++) buf[j] = tvp5150_read(sd, i + j); dprintk0(sd->dev, "%s reg %02x = %*ph\n", s, i, len, buf); } } static int tvp5150_log_status(struct v4l2_subdev *sd) { dprintk0(sd->dev, "tvp5150: Video input source selection #1 = 0x%02x\n", tvp5150_read(sd, TVP5150_VD_IN_SRC_SEL_1)); dprintk0(sd->dev, "tvp5150: Analog channel controls = 0x%02x\n", tvp5150_read(sd, TVP5150_ANAL_CHL_CTL)); dprintk0(sd->dev, "tvp5150: Operation mode controls = 0x%02x\n", tvp5150_read(sd, TVP5150_OP_MODE_CTL)); dprintk0(sd->dev, "tvp5150: Miscellaneous controls = 0x%02x\n", tvp5150_read(sd, TVP5150_MISC_CTL)); dprintk0(sd->dev, "tvp5150: Autoswitch mask= 0x%02x\n", tvp5150_read(sd, TVP5150_AUTOSW_MSK)); dprintk0(sd->dev, "tvp5150: Color killer threshold control = 0x%02x\n", tvp5150_read(sd, TVP5150_COLOR_KIL_THSH_CTL)); dprintk0(sd->dev, "tvp5150: Luminance processing controls #1 #2 and #3 = %02x %02x %02x\n", tvp5150_read(sd, TVP5150_LUMA_PROC_CTL_1), tvp5150_read(sd, TVP5150_LUMA_PROC_CTL_2), tvp5150_read(sd, TVP5150_LUMA_PROC_CTL_3)); dprintk0(sd->dev, "tvp5150: Brightness control = 0x%02x\n", tvp5150_read(sd, TVP5150_BRIGHT_CTL)); dprintk0(sd->dev, "tvp5150: Color saturation control = 0x%02x\n", tvp5150_read(sd, TVP5150_SATURATION_CTL)); dprintk0(sd->dev, "tvp5150: Hue control = 0x%02x\n", tvp5150_read(sd, TVP5150_HUE_CTL)); dprintk0(sd->dev, "tvp5150: Contrast control = 0x%02x\n", tvp5150_read(sd, TVP5150_CONTRAST_CTL)); dprintk0(sd->dev, "tvp5150: Outputs and data rates select = 0x%02x\n", tvp5150_read(sd, TVP5150_DATA_RATE_SEL)); dprintk0(sd->dev, "tvp5150: Configuration shared pins = 0x%02x\n", tvp5150_read(sd, TVP5150_CONF_SHARED_PIN)); dprintk0(sd->dev, "tvp5150: Active video cropping start = 0x%02x%02x\n", tvp5150_read(sd, TVP5150_ACT_VD_CROP_ST_MSB), tvp5150_read(sd, TVP5150_ACT_VD_CROP_ST_LSB)); dprintk0(sd->dev, "tvp5150: Active video cropping stop = 0x%02x%02x\n", tvp5150_read(sd, TVP5150_ACT_VD_CROP_STP_MSB), tvp5150_read(sd, TVP5150_ACT_VD_CROP_STP_LSB)); dprintk0(sd->dev, "tvp5150: Genlock/RTC = 0x%02x\n", tvp5150_read(sd, TVP5150_GENLOCK)); dprintk0(sd->dev, "tvp5150: Horizontal sync start = 0x%02x\n", tvp5150_read(sd, TVP5150_HORIZ_SYNC_START)); dprintk0(sd->dev, "tvp5150: Vertical blanking start = 0x%02x\n", tvp5150_read(sd, TVP5150_VERT_BLANKING_START)); dprintk0(sd->dev, "tvp5150: Vertical blanking stop = 0x%02x\n", tvp5150_read(sd, TVP5150_VERT_BLANKING_STOP)); dprintk0(sd->dev, "tvp5150: Chrominance processing control #1 and #2 = %02x %02x\n", tvp5150_read(sd, TVP5150_CHROMA_PROC_CTL_1), tvp5150_read(sd, TVP5150_CHROMA_PROC_CTL_2)); dprintk0(sd->dev, "tvp5150: Interrupt reset register B = 0x%02x\n", tvp5150_read(sd, TVP5150_INT_RESET_REG_B)); dprintk0(sd->dev, "tvp5150: Interrupt enable register B = 0x%02x\n", tvp5150_read(sd, TVP5150_INT_ENABLE_REG_B)); dprintk0(sd->dev, "tvp5150: Interrupt configuration register B = 0x%02x\n", tvp5150_read(sd, TVP5150_INTT_CONFIG_REG_B)); dprintk0(sd->dev, "tvp5150: Video standard = 0x%02x\n", tvp5150_read(sd, TVP5150_VIDEO_STD)); dprintk0(sd->dev, "tvp5150: Chroma gain factor: Cb=0x%02x Cr=0x%02x\n", tvp5150_read(sd, TVP5150_CB_GAIN_FACT), tvp5150_read(sd, TVP5150_CR_GAIN_FACTOR)); dprintk0(sd->dev, "tvp5150: Macrovision on counter = 0x%02x\n", tvp5150_read(sd, TVP5150_MACROVISION_ON_CTR)); dprintk0(sd->dev, "tvp5150: Macrovision off counter = 0x%02x\n", tvp5150_read(sd, TVP5150_MACROVISION_OFF_CTR)); dprintk0(sd->dev, "tvp5150: ITU-R BT.656.%d timing(TVP5150AM1 only)\n", (tvp5150_read(sd, TVP5150_REV_SELECT) & 1) ? 3 : 4); dprintk0(sd->dev, "tvp5150: Device ID = %02x%02x\n", tvp5150_read(sd, TVP5150_MSB_DEV_ID), tvp5150_read(sd, TVP5150_LSB_DEV_ID)); dprintk0(sd->dev, "tvp5150: ROM version = (hex) %02x.%02x\n", tvp5150_read(sd, TVP5150_ROM_MAJOR_VER), tvp5150_read(sd, TVP5150_ROM_MINOR_VER)); dprintk0(sd->dev, "tvp5150: Vertical line count = 0x%02x%02x\n", tvp5150_read(sd, TVP5150_VERT_LN_COUNT_MSB), tvp5150_read(sd, TVP5150_VERT_LN_COUNT_LSB)); dprintk0(sd->dev, "tvp5150: Interrupt status register B = 0x%02x\n", tvp5150_read(sd, TVP5150_INT_STATUS_REG_B)); dprintk0(sd->dev, "tvp5150: Interrupt active register B = 0x%02x\n", tvp5150_read(sd, TVP5150_INT_ACTIVE_REG_B)); dprintk0(sd->dev, "tvp5150: Status regs #1 to #5 = %02x %02x %02x %02x %02x\n", tvp5150_read(sd, TVP5150_STATUS_REG_1), tvp5150_read(sd, TVP5150_STATUS_REG_2), tvp5150_read(sd, TVP5150_STATUS_REG_3), tvp5150_read(sd, TVP5150_STATUS_REG_4), tvp5150_read(sd, TVP5150_STATUS_REG_5)); dump_reg_range(sd, "Teletext filter 1", TVP5150_TELETEXT_FIL1_INI, TVP5150_TELETEXT_FIL1_END, 8); dump_reg_range(sd, "Teletext filter 2", TVP5150_TELETEXT_FIL2_INI, TVP5150_TELETEXT_FIL2_END, 8); dprintk0(sd->dev, "tvp5150: Teletext filter enable = 0x%02x\n", tvp5150_read(sd, TVP5150_TELETEXT_FIL_ENA)); dprintk0(sd->dev, "tvp5150: Interrupt status register A = 0x%02x\n", tvp5150_read(sd, TVP5150_INT_STATUS_REG_A)); dprintk0(sd->dev, "tvp5150: Interrupt enable register A = 0x%02x\n", tvp5150_read(sd, TVP5150_INT_ENABLE_REG_A)); dprintk0(sd->dev, "tvp5150: Interrupt configuration = 0x%02x\n", tvp5150_read(sd, TVP5150_INT_CONF)); dprintk0(sd->dev, "tvp5150: VDP status register = 0x%02x\n", tvp5150_read(sd, TVP5150_VDP_STATUS_REG)); dprintk0(sd->dev, "tvp5150: FIFO word count = 0x%02x\n", tvp5150_read(sd, TVP5150_FIFO_WORD_COUNT)); dprintk0(sd->dev, "tvp5150: FIFO interrupt threshold = 0x%02x\n", tvp5150_read(sd, TVP5150_FIFO_INT_THRESHOLD)); dprintk0(sd->dev, "tvp5150: FIFO reset = 0x%02x\n", tvp5150_read(sd, TVP5150_FIFO_RESET)); dprintk0(sd->dev, "tvp5150: Line number interrupt = 0x%02x\n", tvp5150_read(sd, TVP5150_LINE_NUMBER_INT)); dprintk0(sd->dev, "tvp5150: Pixel alignment register = 0x%02x%02x\n", tvp5150_read(sd, TVP5150_PIX_ALIGN_REG_HIGH), tvp5150_read(sd, TVP5150_PIX_ALIGN_REG_LOW)); dprintk0(sd->dev, "tvp5150: FIFO output control = 0x%02x\n", tvp5150_read(sd, TVP5150_FIFO_OUT_CTRL)); dprintk0(sd->dev, "tvp5150: Full field enable = 0x%02x\n", tvp5150_read(sd, TVP5150_FULL_FIELD_ENA)); dprintk0(sd->dev, "tvp5150: Full field mode register = 0x%02x\n", tvp5150_read(sd, TVP5150_FULL_FIELD_MODE_REG)); dump_reg_range(sd, "CC data", TVP5150_CC_DATA_INI, TVP5150_CC_DATA_END, 8); dump_reg_range(sd, "WSS data", TVP5150_WSS_DATA_INI, TVP5150_WSS_DATA_END, 8); dump_reg_range(sd, "VPS data", TVP5150_VPS_DATA_INI, TVP5150_VPS_DATA_END, 8); dump_reg_range(sd, "VITC data", TVP5150_VITC_DATA_INI, TVP5150_VITC_DATA_END, 10); dump_reg_range(sd, "Line mode", TVP5150_LINE_MODE_INI, TVP5150_LINE_MODE_END, 8); return 0; } /**************************************************************************** Basic functions ****************************************************************************/ static void tvp5150_selmux(struct v4l2_subdev *sd) { int opmode = 0; struct tvp5150 *decoder = to_tvp5150(sd); unsigned int mask, val; int input = 0; /* Only tvp5150am1 and tvp5151 have signal generator support */ if ((decoder->dev_id == 0x5150 && decoder->rom_ver == 0x0400) || (decoder->dev_id == 0x5151 && decoder->rom_ver == 0x0100)) { if (!decoder->enable) input = 8; } switch (decoder->input) { case TVP5150_COMPOSITE1: input |= 2; fallthrough; case TVP5150_COMPOSITE0: break; case TVP5150_SVIDEO: default: input |= 1; break; } dev_dbg_lvl(sd->dev, 1, debug, "Selecting video route: route input=%s, output=%s => tvp5150 input=0x%02x, opmode=0x%02x\n", decoder->input == 0 ? "aip1a" : decoder->input == 2 ? "aip1b" : "svideo", decoder->output == 0 ? "normal" : "black-frame-gen", input, opmode); regmap_write(decoder->regmap, TVP5150_OP_MODE_CTL, opmode); regmap_write(decoder->regmap, TVP5150_VD_IN_SRC_SEL_1, input); /* * Setup the FID/GLCO/VLK/HVLK and INTREQ/GPCL/VBLK output signals. For * S-Video we output the vertical lock (VLK) signal on FID/GLCO/VLK/HVLK * and set INTREQ/GPCL/VBLK to logic 0. For composite we output the * field indicator (FID) signal on FID/GLCO/VLK/HVLK and set * INTREQ/GPCL/VBLK to logic 1. */ mask = TVP5150_MISC_CTL_GPCL | TVP5150_MISC_CTL_HVLK; if (decoder->input == TVP5150_SVIDEO) val = TVP5150_MISC_CTL_HVLK; else val = TVP5150_MISC_CTL_GPCL; regmap_update_bits(decoder->regmap, TVP5150_MISC_CTL, mask, val); }; struct i2c_reg_value { unsigned char reg; unsigned char value; }; /* Default values as sugested at TVP5150AM1 datasheet */ static const struct i2c_reg_value tvp5150_init_default[] = { { /* 0x00 */ TVP5150_VD_IN_SRC_SEL_1, 0x00 }, { /* 0x01 */ TVP5150_ANAL_CHL_CTL, 0x15 }, { /* 0x02 */ TVP5150_OP_MODE_CTL, 0x00 }, { /* 0x03 */ TVP5150_MISC_CTL, 0x01 }, { /* 0x06 */ TVP5150_COLOR_KIL_THSH_CTL, 0x10 }, { /* 0x07 */ TVP5150_LUMA_PROC_CTL_1, 0x60 }, { /* 0x08 */ TVP5150_LUMA_PROC_CTL_2, 0x00 }, { /* 0x09 */ TVP5150_BRIGHT_CTL, 0x80 }, { /* 0x0a */ TVP5150_SATURATION_CTL, 0x80 }, { /* 0x0b */ TVP5150_HUE_CTL, 0x00 }, { /* 0x0c */ TVP5150_CONTRAST_CTL, 0x80 }, { /* 0x0d */ TVP5150_DATA_RATE_SEL, 0x47 }, { /* 0x0e */ TVP5150_LUMA_PROC_CTL_3, 0x00 }, { /* 0x0f */ TVP5150_CONF_SHARED_PIN, 0x08 }, { /* 0x11 */ TVP5150_ACT_VD_CROP_ST_MSB, 0x00 }, { /* 0x12 */ TVP5150_ACT_VD_CROP_ST_LSB, 0x00 }, { /* 0x13 */ TVP5150_ACT_VD_CROP_STP_MSB, 0x00 }, { /* 0x14 */ TVP5150_ACT_VD_CROP_STP_LSB, 0x00 }, { /* 0x15 */ TVP5150_GENLOCK, 0x01 }, { /* 0x16 */ TVP5150_HORIZ_SYNC_START, 0x80 }, { /* 0x18 */ TVP5150_VERT_BLANKING_START, 0x00 }, { /* 0x19 */ TVP5150_VERT_BLANKING_STOP, 0x00 }, { /* 0x1a */ TVP5150_CHROMA_PROC_CTL_1, 0x0c }, { /* 0x1b */ TVP5150_CHROMA_PROC_CTL_2, 0x14 }, { /* 0x1c */ TVP5150_INT_RESET_REG_B, 0x00 }, { /* 0x1d */ TVP5150_INT_ENABLE_REG_B, 0x00 }, { /* 0x1e */ TVP5150_INTT_CONFIG_REG_B, 0x00 }, { /* 0x28 */ TVP5150_VIDEO_STD, 0x00 }, { /* 0x2e */ TVP5150_MACROVISION_ON_CTR, 0x0f }, { /* 0x2f */ TVP5150_MACROVISION_OFF_CTR, 0x01 }, { /* 0xbb */ TVP5150_TELETEXT_FIL_ENA, 0x00 }, { /* 0xc0 */ TVP5150_INT_STATUS_REG_A, 0x00 }, { /* 0xc1 */ TVP5150_INT_ENABLE_REG_A, 0x00 }, { /* 0xc2 */ TVP5150_INT_CONF, 0x04 }, { /* 0xc8 */ TVP5150_FIFO_INT_THRESHOLD, 0x80 }, { /* 0xc9 */ TVP5150_FIFO_RESET, 0x00 }, { /* 0xca */ TVP5150_LINE_NUMBER_INT, 0x00 }, { /* 0xcb */ TVP5150_PIX_ALIGN_REG_LOW, 0x4e }, { /* 0xcc */ TVP5150_PIX_ALIGN_REG_HIGH, 0x00 }, { /* 0xcd */ TVP5150_FIFO_OUT_CTRL, 0x01 }, { /* 0xcf */ TVP5150_FULL_FIELD_ENA, 0x00 }, { /* 0xd0 */ TVP5150_LINE_MODE_INI, 0x00 }, { /* 0xfc */ TVP5150_FULL_FIELD_MODE_REG, 0x7f }, { /* end of data */ 0xff, 0xff } }; /* Default values as sugested at TVP5150AM1 datasheet */ static const struct i2c_reg_value tvp5150_init_enable[] = { { /* Automatic offset and AGC enabled */ TVP5150_ANAL_CHL_CTL, 0x15 }, { /* Activate YCrCb output 0x9 or 0xd ? */ TVP5150_MISC_CTL, TVP5150_MISC_CTL_GPCL | TVP5150_MISC_CTL_INTREQ_OE | TVP5150_MISC_CTL_YCBCR_OE | TVP5150_MISC_CTL_SYNC_OE | TVP5150_MISC_CTL_VBLANK | TVP5150_MISC_CTL_CLOCK_OE, }, { /* Activates video std autodetection for all standards */ TVP5150_AUTOSW_MSK, 0x0 }, { /* Default format: 0x47. For 4:2:2: 0x40 */ TVP5150_DATA_RATE_SEL, 0x47 }, { TVP5150_CHROMA_PROC_CTL_1, 0x0c }, { TVP5150_CHROMA_PROC_CTL_2, 0x54 }, { /* Non documented, but initialized on WinTV USB2 */ 0x27, 0x20 }, { 0xff, 0xff } }; struct tvp5150_vbi_type { unsigned int vbi_type; unsigned int ini_line; unsigned int end_line; unsigned int by_field :1; }; struct i2c_vbi_ram_value { u16 reg; struct tvp5150_vbi_type type; unsigned char values[16]; }; /* This struct have the values for each supported VBI Standard * by tvp5150_vbi_types should follow the same order as vbi_ram_default * value 0 means rom position 0x10, value 1 means rom position 0x30 * and so on. There are 16 possible locations from 0 to 15. */ static struct i2c_vbi_ram_value vbi_ram_default[] = { /* * FIXME: Current api doesn't handle all VBI types, those not * yet supported are placed under #if 0 */ #if 0 [0] = {0x010, /* Teletext, SECAM, WST System A */ {V4L2_SLICED_TELETEXT_SECAM, 6, 23, 1}, { 0xaa, 0xaa, 0xff, 0xff, 0xe7, 0x2e, 0x20, 0x26, 0xe6, 0xb4, 0x0e, 0x00, 0x00, 0x00, 0x10, 0x00 } }, #endif [1] = {0x030, /* Teletext, PAL, WST System B */ {V4L2_SLICED_TELETEXT_B, 6, 22, 1}, { 0xaa, 0xaa, 0xff, 0xff, 0x27, 0x2e, 0x20, 0x2b, 0xa6, 0x72, 0x10, 0x00, 0x00, 0x00, 0x10, 0x00 } }, #if 0 [2] = {0x050, /* Teletext, PAL, WST System C */ {V4L2_SLICED_TELETEXT_PAL_C, 6, 22, 1}, { 0xaa, 0xaa, 0xff, 0xff, 0xe7, 0x2e, 0x20, 0x22, 0xa6, 0x98, 0x0d, 0x00, 0x00, 0x00, 0x10, 0x00 } }, [3] = {0x070, /* Teletext, NTSC, WST System B */ {V4L2_SLICED_TELETEXT_NTSC_B, 10, 21, 1}, { 0xaa, 0xaa, 0xff, 0xff, 0x27, 0x2e, 0x20, 0x23, 0x69, 0x93, 0x0d, 0x00, 0x00, 0x00, 0x10, 0x00 } }, [4] = {0x090, /* Tetetext, NTSC NABTS System C */ {V4L2_SLICED_TELETEXT_NTSC_C, 10, 21, 1}, { 0xaa, 0xaa, 0xff, 0xff, 0xe7, 0x2e, 0x20, 0x22, 0x69, 0x93, 0x0d, 0x00, 0x00, 0x00, 0x15, 0x00 } }, [5] = {0x0b0, /* Teletext, NTSC-J, NABTS System D */ {V4L2_SLICED_TELETEXT_NTSC_D, 10, 21, 1}, { 0xaa, 0xaa, 0xff, 0xff, 0xa7, 0x2e, 0x20, 0x23, 0x69, 0x93, 0x0d, 0x00, 0x00, 0x00, 0x10, 0x00 } }, [6] = {0x0d0, /* Closed Caption, PAL/SECAM */ {V4L2_SLICED_CAPTION_625, 22, 22, 1}, { 0xaa, 0x2a, 0xff, 0x3f, 0x04, 0x51, 0x6e, 0x02, 0xa6, 0x7b, 0x09, 0x00, 0x00, 0x00, 0x27, 0x00 } }, #endif [7] = {0x0f0, /* Closed Caption, NTSC */ {V4L2_SLICED_CAPTION_525, 21, 21, 1}, { 0xaa, 0x2a, 0xff, 0x3f, 0x04, 0x51, 0x6e, 0x02, 0x69, 0x8c, 0x09, 0x00, 0x00, 0x00, 0x27, 0x00 } }, [8] = {0x110, /* Wide Screen Signal, PAL/SECAM */ {V4L2_SLICED_WSS_625, 23, 23, 1}, { 0x5b, 0x55, 0xc5, 0xff, 0x00, 0x71, 0x6e, 0x42, 0xa6, 0xcd, 0x0f, 0x00, 0x00, 0x00, 0x3a, 0x00 } }, #if 0 [9] = {0x130, /* Wide Screen Signal, NTSC C */ {V4L2_SLICED_WSS_525, 20, 20, 1}, { 0x38, 0x00, 0x3f, 0x00, 0x00, 0x71, 0x6e, 0x43, 0x69, 0x7c, 0x08, 0x00, 0x00, 0x00, 0x39, 0x00 } }, [10] = {0x150, /* Vertical Interval Timecode (VITC), PAL/SECAM */ {V4l2_SLICED_VITC_625, 6, 22, 0}, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x8f, 0x6d, 0x49, 0xa6, 0x85, 0x08, 0x00, 0x00, 0x00, 0x4c, 0x00 } }, [11] = {0x170, /* Vertical Interval Timecode (VITC), NTSC */ {V4l2_SLICED_VITC_525, 10, 20, 0}, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x8f, 0x6d, 0x49, 0x69, 0x94, 0x08, 0x00, 0x00, 0x00, 0x4c, 0x00 } }, #endif [12] = {0x190, /* Video Program System (VPS), PAL */ {V4L2_SLICED_VPS, 16, 16, 0}, { 0xaa, 0xaa, 0xff, 0xff, 0xba, 0xce, 0x2b, 0x0d, 0xa6, 0xda, 0x0b, 0x00, 0x00, 0x00, 0x60, 0x00 } }, /* 0x1d0 User programmable */ }; static int tvp5150_write_inittab(struct v4l2_subdev *sd, const struct i2c_reg_value *regs) { struct tvp5150 *decoder = to_tvp5150(sd); while (regs->reg != 0xff) { regmap_write(decoder->regmap, regs->reg, regs->value); regs++; } return 0; } static int tvp5150_vdp_init(struct v4l2_subdev *sd) { struct tvp5150 *decoder = to_tvp5150(sd); struct regmap *map = decoder->regmap; unsigned int i; int j; /* Disable Full Field */ regmap_write(map, TVP5150_FULL_FIELD_ENA, 0); /* Before programming, Line mode should be at 0xff */ for (i = TVP5150_LINE_MODE_INI; i <= TVP5150_LINE_MODE_END; i++) regmap_write(map, i, 0xff); /* Load Ram Table */ for (j = 0; j < ARRAY_SIZE(vbi_ram_default); j++) { const struct i2c_vbi_ram_value *regs = &vbi_ram_default[j]; if (!regs->type.vbi_type) continue; regmap_write(map, TVP5150_CONF_RAM_ADDR_HIGH, regs->reg >> 8); regmap_write(map, TVP5150_CONF_RAM_ADDR_LOW, regs->reg); for (i = 0; i < 16; i++) regmap_write(map, TVP5150_VDP_CONF_RAM_DATA, regs->values[i]); } return 0; } /* Fills VBI capabilities based on i2c_vbi_ram_value struct */ static int tvp5150_g_sliced_vbi_cap(struct v4l2_subdev *sd, struct v4l2_sliced_vbi_cap *cap) { int line, i; dev_dbg_lvl(sd->dev, 1, debug, "g_sliced_vbi_cap\n"); memset(cap, 0, sizeof(*cap)); for (i = 0; i < ARRAY_SIZE(vbi_ram_default); i++) { const struct i2c_vbi_ram_value *regs = &vbi_ram_default[i]; if (!regs->type.vbi_type) continue; for (line = regs->type.ini_line; line <= regs->type.end_line; line++) { cap->service_lines[0][line] |= regs->type.vbi_type; } cap->service_set |= regs->type.vbi_type; } return 0; } /* Set vbi processing * type - one of tvp5150_vbi_types * line - line to gather data * fields: bit 0 field1, bit 1, field2 * flags (default=0xf0) is a bitmask, were set means: * bit 7: enable filtering null bytes on CC * bit 6: send data also to FIFO * bit 5: don't allow data with errors on FIFO * bit 4: enable ECC when possible * pix_align = pix alignment: * LSB = field1 * MSB = field2 */ static int tvp5150_set_vbi(struct v4l2_subdev *sd, unsigned int type, u8 flags, int line, const int fields) { struct tvp5150 *decoder = to_tvp5150(sd); v4l2_std_id std = decoder->norm; u8 reg; int i, pos = 0; if (std == V4L2_STD_ALL) { dev_err(sd->dev, "VBI can't be configured without knowing number of lines\n"); return 0; } else if (std & V4L2_STD_625_50) { /* Don't follow NTSC Line number convension */ line += 3; } if (line < 6 || line > 27) return 0; for (i = 0; i < ARRAY_SIZE(vbi_ram_default); i++) { const struct i2c_vbi_ram_value *regs = &vbi_ram_default[i]; if (!regs->type.vbi_type) continue; if ((type & regs->type.vbi_type) && (line >= regs->type.ini_line) && (line <= regs->type.end_line)) break; pos++; } type = pos | (flags & 0xf0); reg = ((line - 6) << 1) + TVP5150_LINE_MODE_INI; if (fields & 1) regmap_write(decoder->regmap, reg, type); if (fields & 2) regmap_write(decoder->regmap, reg + 1, type); return type; } static int tvp5150_get_vbi(struct v4l2_subdev *sd, int line) { struct tvp5150 *decoder = to_tvp5150(sd); v4l2_std_id std = decoder->norm; u8 reg; int pos, type = 0; int i, ret = 0; if (std == V4L2_STD_ALL) { dev_err(sd->dev, "VBI can't be configured without knowing number of lines\n"); return 0; } else if (std & V4L2_STD_625_50) { /* Don't follow NTSC Line number convension */ line += 3; } if (line < 6 || line > 27) return 0; reg = ((line - 6) << 1) + TVP5150_LINE_MODE_INI; for (i = 0; i <= 1; i++) { ret = tvp5150_read(sd, reg + i); if (ret < 0) { dev_err(sd->dev, "%s: failed with error = %d\n", __func__, ret); return 0; } pos = ret & 0x0f; if (pos < ARRAY_SIZE(vbi_ram_default)) type |= vbi_ram_default[pos].type.vbi_type; } return type; } static int tvp5150_set_std(struct v4l2_subdev *sd, v4l2_std_id std) { struct tvp5150 *decoder = to_tvp5150(sd); int fmt = 0; /* First tests should be against specific std */ if (std == V4L2_STD_NTSC_443) { fmt = VIDEO_STD_NTSC_4_43_BIT; } else if (std == V4L2_STD_PAL_M) { fmt = VIDEO_STD_PAL_M_BIT; } else if (std == V4L2_STD_PAL_N || std == V4L2_STD_PAL_Nc) { fmt = VIDEO_STD_PAL_COMBINATION_N_BIT; } else { /* Then, test against generic ones */ if (std & V4L2_STD_NTSC) fmt = VIDEO_STD_NTSC_MJ_BIT; else if (std & V4L2_STD_PAL) fmt = VIDEO_STD_PAL_BDGHIN_BIT; else if (std & V4L2_STD_SECAM) fmt = VIDEO_STD_SECAM_BIT; } dev_dbg_lvl(sd->dev, 1, debug, "Set video std register to %d.\n", fmt); regmap_write(decoder->regmap, TVP5150_VIDEO_STD, fmt); return 0; } static int tvp5150_g_std(struct v4l2_subdev *sd, v4l2_std_id *std) { struct tvp5150 *decoder = to_tvp5150(sd); *std = decoder->norm; return 0; } static int tvp5150_s_std(struct v4l2_subdev *sd, v4l2_std_id std) { struct tvp5150 *decoder = to_tvp5150(sd); struct tvp5150_connector *cur_con = decoder->cur_connector; v4l2_std_id supported_stds; if (decoder->norm == std) return 0; /* In case of no of-connectors are available no limitations are made */ if (!decoder->connectors_num) supported_stds = V4L2_STD_ALL; else supported_stds = cur_con->base.connector.analog.sdtv_stds; /* * Check if requested std or group of std's is/are supported by the * connector. */ if ((supported_stds & std) == 0) return -EINVAL; /* Change cropping height limits */ if (std & V4L2_STD_525_60) decoder->rect.height = TVP5150_V_MAX_525_60; else decoder->rect.height = TVP5150_V_MAX_OTHERS; /* Set only the specific supported std in case of group of std's. */ decoder->norm = supported_stds & std; return tvp5150_set_std(sd, std); } static v4l2_std_id tvp5150_read_std(struct v4l2_subdev *sd) { int val = tvp5150_read(sd, TVP5150_STATUS_REG_5); switch (val & 0x0F) { case 0x01: return V4L2_STD_NTSC; case 0x03: return V4L2_STD_PAL; case 0x05: return V4L2_STD_PAL_M; case 0x07: return V4L2_STD_PAL_N | V4L2_STD_PAL_Nc; case 0x09: return V4L2_STD_NTSC_443; case 0xb: return V4L2_STD_SECAM; default: return V4L2_STD_UNKNOWN; } } static int query_lock(struct v4l2_subdev *sd) { struct tvp5150 *decoder = to_tvp5150(sd); int status; if (decoder->irq) return decoder->lock; regmap_read(decoder->regmap, TVP5150_STATUS_REG_1, &status); /* For standard detection, we need the 3 locks */ return (status & 0x0e) == 0x0e; } static int tvp5150_querystd(struct v4l2_subdev *sd, v4l2_std_id *std_id) { *std_id = query_lock(sd) ? tvp5150_read_std(sd) : V4L2_STD_UNKNOWN; return 0; } static const struct v4l2_event tvp5150_ev_fmt = { .type = V4L2_EVENT_SOURCE_CHANGE, .u.src_change.changes = V4L2_EVENT_SRC_CH_RESOLUTION, }; static irqreturn_t tvp5150_isr(int irq, void *dev_id) { struct tvp5150 *decoder = dev_id; struct regmap *map = decoder->regmap; unsigned int mask, active = 0, status = 0; mask = TVP5150_MISC_CTL_YCBCR_OE | TVP5150_MISC_CTL_SYNC_OE | TVP5150_MISC_CTL_CLOCK_OE; regmap_read(map, TVP5150_INT_STATUS_REG_A, &status); if (status) { regmap_write(map, TVP5150_INT_STATUS_REG_A, status); if (status & TVP5150_INT_A_LOCK) { decoder->lock = !!(status & TVP5150_INT_A_LOCK_STATUS); dev_dbg_lvl(decoder->sd.dev, 1, debug, "sync lo%s signal\n", decoder->lock ? "ck" : "ss"); v4l2_subdev_notify_event(&decoder->sd, &tvp5150_ev_fmt); regmap_update_bits(map, TVP5150_MISC_CTL, mask, decoder->lock ? decoder->oe : 0); } return IRQ_HANDLED; } regmap_read(map, TVP5150_INT_ACTIVE_REG_B, &active); if (active) { status = 0; regmap_read(map, TVP5150_INT_STATUS_REG_B, &status); if (status) regmap_write(map, TVP5150_INT_RESET_REG_B, status); } return IRQ_HANDLED; } static int tvp5150_reset(struct v4l2_subdev *sd, u32 val) { struct tvp5150 *decoder = to_tvp5150(sd); struct regmap *map = decoder->regmap; /* Initializes TVP5150 to its default values */ tvp5150_write_inittab(sd, tvp5150_init_default); if (decoder->irq) { /* Configure pins: FID, VSYNC, INTREQ, SCLK */ regmap_write(map, TVP5150_CONF_SHARED_PIN, 0x0); /* Set interrupt polarity to active high */ regmap_write(map, TVP5150_INT_CONF, TVP5150_VDPOE | 0x1); regmap_write(map, TVP5150_INTT_CONFIG_REG_B, 0x1); } else { /* Configure pins: FID, VSYNC, GPCL/VBLK, SCLK */ regmap_write(map, TVP5150_CONF_SHARED_PIN, 0x2); /* Keep interrupt polarity active low */ regmap_write(map, TVP5150_INT_CONF, TVP5150_VDPOE); regmap_write(map, TVP5150_INTT_CONFIG_REG_B, 0x0); } /* Initializes VDP registers */ tvp5150_vdp_init(sd); /* Selects decoder input */ tvp5150_selmux(sd); /* Initialize image preferences */ v4l2_ctrl_handler_setup(&decoder->hdl); return 0; } static int tvp5150_enable(struct v4l2_subdev *sd) { struct tvp5150 *decoder = to_tvp5150(sd); v4l2_std_id std; /* Initializes TVP5150 to stream enabled values */ tvp5150_write_inittab(sd, tvp5150_init_enable); if (decoder->norm == V4L2_STD_ALL) std = tvp5150_read_std(sd); else std = decoder->norm; /* Disable autoswitch mode */ tvp5150_set_std(sd, std); /* * Enable the YCbCr and clock outputs. In discrete sync mode * (non-BT.656) additionally enable the sync outputs. */ switch (decoder->mbus_type) { case V4L2_MBUS_PARALLEL: /* 8-bit 4:2:2 YUV with discrete sync output */ regmap_update_bits(decoder->regmap, TVP5150_DATA_RATE_SEL, 0x7, 0x0); decoder->oe = TVP5150_MISC_CTL_YCBCR_OE | TVP5150_MISC_CTL_CLOCK_OE | TVP5150_MISC_CTL_SYNC_OE; break; case V4L2_MBUS_BT656: decoder->oe = TVP5150_MISC_CTL_YCBCR_OE | TVP5150_MISC_CTL_CLOCK_OE; break; default: return -EINVAL; } return 0; }; static int tvp5150_s_ctrl(struct v4l2_ctrl *ctrl) { struct v4l2_subdev *sd = to_sd(ctrl); struct tvp5150 *decoder = to_tvp5150(sd); switch (ctrl->id) { case V4L2_CID_BRIGHTNESS: regmap_write(decoder->regmap, TVP5150_BRIGHT_CTL, ctrl->val); return 0; case V4L2_CID_CONTRAST: regmap_write(decoder->regmap, TVP5150_CONTRAST_CTL, ctrl->val); return 0; case V4L2_CID_SATURATION: regmap_write(decoder->regmap, TVP5150_SATURATION_CTL, ctrl->val); return 0; case V4L2_CID_HUE: regmap_write(decoder->regmap, TVP5150_HUE_CTL, ctrl->val); return 0; case V4L2_CID_TEST_PATTERN: decoder->enable = ctrl->val ? false : true; tvp5150_selmux(sd); return 0; } return -EINVAL; } static void tvp5150_set_default(v4l2_std_id std, struct v4l2_rect *crop) { /* Default is no cropping */ crop->top = 0; crop->left = 0; crop->width = TVP5150_H_MAX; if (std & V4L2_STD_525_60) crop->height = TVP5150_V_MAX_525_60; else crop->height = TVP5150_V_MAX_OTHERS; } static struct v4l2_rect * tvp5150_get_pad_crop(struct tvp5150 *decoder, struct v4l2_subdev_state *sd_state, unsigned int pad, enum v4l2_subdev_format_whence which) { switch (which) { case V4L2_SUBDEV_FORMAT_ACTIVE: return &decoder->rect; case V4L2_SUBDEV_FORMAT_TRY: #if defined(CONFIG_VIDEO_V4L2_SUBDEV_API) return v4l2_subdev_get_try_crop(&decoder->sd, sd_state, pad); #else return ERR_PTR(-EINVAL); #endif default: return ERR_PTR(-EINVAL); } } static int tvp5150_fill_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *format) { struct v4l2_mbus_framefmt *f; struct tvp5150 *decoder = to_tvp5150(sd); if (!format || (format->pad != TVP5150_PAD_VID_OUT)) return -EINVAL; f = &format->format; f->width = decoder->rect.width; f->height = decoder->rect.height / 2; f->code = TVP5150_MBUS_FMT; f->field = TVP5150_FIELD; f->colorspace = TVP5150_COLORSPACE; dev_dbg_lvl(sd->dev, 1, debug, "width = %d, height = %d\n", f->width, f->height); return 0; } static unsigned int tvp5150_get_hmax(struct v4l2_subdev *sd) { struct tvp5150 *decoder = to_tvp5150(sd); v4l2_std_id std; /* Calculate height based on current standard */ if (decoder->norm == V4L2_STD_ALL) std = tvp5150_read_std(sd); else std = decoder->norm; return (std & V4L2_STD_525_60) ? TVP5150_V_MAX_525_60 : TVP5150_V_MAX_OTHERS; } static void tvp5150_set_hw_selection(struct v4l2_subdev *sd, struct v4l2_rect *rect) { struct tvp5150 *decoder = to_tvp5150(sd); unsigned int hmax = tvp5150_get_hmax(sd); regmap_write(decoder->regmap, TVP5150_VERT_BLANKING_START, rect->top); regmap_write(decoder->regmap, TVP5150_VERT_BLANKING_STOP, rect->top + rect->height - hmax); regmap_write(decoder->regmap, TVP5150_ACT_VD_CROP_ST_MSB, rect->left >> TVP5150_CROP_SHIFT); regmap_write(decoder->regmap, TVP5150_ACT_VD_CROP_ST_LSB, rect->left | (1 << TVP5150_CROP_SHIFT)); regmap_write(decoder->regmap, TVP5150_ACT_VD_CROP_STP_MSB, (rect->left + rect->width - TVP5150_MAX_CROP_LEFT) >> TVP5150_CROP_SHIFT); regmap_write(decoder->regmap, TVP5150_ACT_VD_CROP_STP_LSB, rect->left + rect->width - TVP5150_MAX_CROP_LEFT); } static int tvp5150_set_selection(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_selection *sel) { struct tvp5150 *decoder = to_tvp5150(sd); struct v4l2_rect *rect = &sel->r; struct v4l2_rect *crop; unsigned int hmax; if (sel->target != V4L2_SEL_TGT_CROP) return -EINVAL; dev_dbg_lvl(sd->dev, 1, debug, "%s left=%d, top=%d, width=%d, height=%d\n", __func__, rect->left, rect->top, rect->width, rect->height); /* tvp5150 has some special limits */ rect->left = clamp(rect->left, 0, TVP5150_MAX_CROP_LEFT); rect->top = clamp(rect->top, 0, TVP5150_MAX_CROP_TOP); hmax = tvp5150_get_hmax(sd); /* * alignments: * - width = 2 due to UYVY colorspace * - height, image = no special alignment */ v4l_bound_align_image(&rect->width, TVP5150_H_MAX - TVP5150_MAX_CROP_LEFT - rect->left, TVP5150_H_MAX - rect->left, 1, &rect->height, hmax - TVP5150_MAX_CROP_TOP - rect->top, hmax - rect->top, 0, 0); if (!IS_ENABLED(CONFIG_VIDEO_V4L2_SUBDEV_API) && sel->which == V4L2_SUBDEV_FORMAT_TRY) return 0; crop = tvp5150_get_pad_crop(decoder, sd_state, sel->pad, sel->which); if (IS_ERR(crop)) return PTR_ERR(crop); /* * Update output image size if the selection (crop) rectangle size or * position has been modified. */ if (sel->which == V4L2_SUBDEV_FORMAT_ACTIVE && !v4l2_rect_equal(rect, crop)) tvp5150_set_hw_selection(sd, rect); *crop = *rect; return 0; } static int tvp5150_get_selection(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_selection *sel) { struct tvp5150 *decoder = container_of(sd, struct tvp5150, sd); struct v4l2_rect *crop; v4l2_std_id std; switch (sel->target) { case V4L2_SEL_TGT_CROP_BOUNDS: sel->r.left = 0; sel->r.top = 0; sel->r.width = TVP5150_H_MAX; /* Calculate height based on current standard */ if (decoder->norm == V4L2_STD_ALL) std = tvp5150_read_std(sd); else std = decoder->norm; if (std & V4L2_STD_525_60) sel->r.height = TVP5150_V_MAX_525_60; else sel->r.height = TVP5150_V_MAX_OTHERS; return 0; case V4L2_SEL_TGT_CROP: crop = tvp5150_get_pad_crop(decoder, sd_state, sel->pad, sel->which); if (IS_ERR(crop)) return PTR_ERR(crop); sel->r = *crop; return 0; default: return -EINVAL; } } static int tvp5150_get_mbus_config(struct v4l2_subdev *sd, unsigned int pad, struct v4l2_mbus_config *cfg) { struct tvp5150 *decoder = to_tvp5150(sd); cfg->type = decoder->mbus_type; cfg->bus.parallel.flags = V4L2_MBUS_MASTER | V4L2_MBUS_PCLK_SAMPLE_RISING | V4L2_MBUS_FIELD_EVEN_LOW | V4L2_MBUS_DATA_ACTIVE_HIGH; return 0; } /**************************************************************************** V4L2 subdev pad ops ****************************************************************************/ static int tvp5150_init_cfg(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state) { struct tvp5150 *decoder = to_tvp5150(sd); v4l2_std_id std; /* * Reset selection to maximum on subdev_open() if autodetection is on * and a standard change is detected. */ if (decoder->norm == V4L2_STD_ALL) { std = tvp5150_read_std(sd); if (std != decoder->detected_norm) { decoder->detected_norm = std; tvp5150_set_default(std, &decoder->rect); } } return 0; } static int tvp5150_enum_mbus_code(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_mbus_code_enum *code) { if (code->pad || code->index) return -EINVAL; code->code = TVP5150_MBUS_FMT; return 0; } static int tvp5150_enum_frame_size(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_frame_size_enum *fse) { struct tvp5150 *decoder = to_tvp5150(sd); if (fse->index >= 8 || fse->code != TVP5150_MBUS_FMT) return -EINVAL; fse->code = TVP5150_MBUS_FMT; fse->min_width = decoder->rect.width; fse->max_width = decoder->rect.width; fse->min_height = decoder->rect.height / 2; fse->max_height = decoder->rect.height / 2; return 0; } /**************************************************************************** * Media entity ops ****************************************************************************/ #if defined(CONFIG_MEDIA_CONTROLLER) static int tvp5150_set_link(struct media_pad *connector_pad, struct media_pad *tvp5150_pad, u32 flags) { struct media_link *link; link = media_entity_find_link(connector_pad, tvp5150_pad); if (!link) return -EINVAL; link->flags = flags; link->reverse->flags = link->flags; return 0; } static int tvp5150_disable_all_input_links(struct tvp5150 *decoder) { struct media_pad *connector_pad; unsigned int i; int err; for (i = 0; i < TVP5150_NUM_PADS - 1; i++) { connector_pad = media_pad_remote_pad_first(&decoder->pads[i]); if (!connector_pad) continue; err = tvp5150_set_link(connector_pad, &decoder->pads[i], 0); if (err) return err; } return 0; } static int tvp5150_s_routing(struct v4l2_subdev *sd, u32 input, u32 output, u32 config); static int tvp5150_link_setup(struct media_entity *entity, const struct media_pad *tvp5150_pad, const struct media_pad *remote, u32 flags) { struct v4l2_subdev *sd = media_entity_to_v4l2_subdev(entity); struct tvp5150 *decoder = to_tvp5150(sd); struct media_pad *other_tvp5150_pad = &decoder->pads[tvp5150_pad->index ^ 1]; struct v4l2_fwnode_connector *v4l2c; bool is_svideo = false; unsigned int i; int err; /* * The TVP5150 state is determined by the enabled sink pad link(s). * Enabling or disabling the source pad link has no effect. */ if (tvp5150_pad->flags & MEDIA_PAD_FL_SOURCE) return 0; /* Check if the svideo connector should be enabled */ for (i = 0; i < decoder->connectors_num; i++) { if (remote->entity == &decoder->connectors[i].ent) { v4l2c = &decoder->connectors[i].base; is_svideo = v4l2c->type == V4L2_CONN_SVIDEO; break; } } dev_dbg_lvl(sd->dev, 1, debug, "link setup '%s':%d->'%s':%d[%d]", remote->entity->name, remote->index, tvp5150_pad->entity->name, tvp5150_pad->index, flags & MEDIA_LNK_FL_ENABLED); if (is_svideo) dev_dbg_lvl(sd->dev, 1, debug, "link setup '%s':%d->'%s':%d[%d]", remote->entity->name, remote->index, other_tvp5150_pad->entity->name, other_tvp5150_pad->index, flags & MEDIA_LNK_FL_ENABLED); /* * The TVP5150 has an internal mux which allows the following setup: * * comp-connector1 --\ * |---> AIP1A * / * svideo-connector -| * \ * |---> AIP1B * comp-connector2 --/ * * We can't rely on user space that the current connector gets disabled * first before enabling the new connector. Disable all active * connector links to be on the safe side. */ err = tvp5150_disable_all_input_links(decoder); if (err) return err; tvp5150_s_routing(sd, is_svideo ? TVP5150_SVIDEO : tvp5150_pad->index, flags & MEDIA_LNK_FL_ENABLED ? TVP5150_NORMAL : TVP5150_BLACK_SCREEN, 0); if (flags & MEDIA_LNK_FL_ENABLED) { struct v4l2_fwnode_connector_analog *v4l2ca; u32 new_norm; /* * S-Video connector is conneted to both ports AIP1A and AIP1B. * Both links must be enabled in one-shot regardless which link * the user requests. */ if (is_svideo) { err = tvp5150_set_link((struct media_pad *)remote, other_tvp5150_pad, flags); if (err) return err; } if (!decoder->connectors_num) return 0; /* Update the current connector */ decoder->cur_connector = container_of(remote, struct tvp5150_connector, pad); /* * Do nothing if the new connector supports the same tv-norms as * the old one. */ v4l2ca = &decoder->cur_connector->base.connector.analog; new_norm = decoder->norm & v4l2ca->sdtv_stds; if (decoder->norm == new_norm) return 0; /* * Fallback to the new connector tv-norms if we can't find any * common between the current tv-norm and the new one. */ tvp5150_s_std(sd, new_norm ? new_norm : v4l2ca->sdtv_stds); } return 0; } static const struct media_entity_operations tvp5150_sd_media_ops = { .link_setup = tvp5150_link_setup, }; #endif /**************************************************************************** I2C Command ****************************************************************************/ static int __maybe_unused tvp5150_runtime_suspend(struct device *dev) { struct v4l2_subdev *sd = dev_get_drvdata(dev); struct tvp5150 *decoder = to_tvp5150(sd); if (decoder->irq) /* Disable lock interrupt */ return regmap_update_bits(decoder->regmap, TVP5150_INT_ENABLE_REG_A, TVP5150_INT_A_LOCK, 0); return 0; } static int __maybe_unused tvp5150_runtime_resume(struct device *dev) { struct v4l2_subdev *sd = dev_get_drvdata(dev); struct tvp5150 *decoder = to_tvp5150(sd); if (decoder->irq) /* Enable lock interrupt */ return regmap_update_bits(decoder->regmap, TVP5150_INT_ENABLE_REG_A, TVP5150_INT_A_LOCK, TVP5150_INT_A_LOCK); return 0; } static int tvp5150_s_stream(struct v4l2_subdev *sd, int enable) { struct tvp5150 *decoder = to_tvp5150(sd); unsigned int mask, val = 0; int ret; mask = TVP5150_MISC_CTL_YCBCR_OE | TVP5150_MISC_CTL_SYNC_OE | TVP5150_MISC_CTL_CLOCK_OE; if (enable) { ret = pm_runtime_resume_and_get(sd->dev); if (ret < 0) return ret; tvp5150_enable(sd); /* Enable outputs if decoder is locked */ if (decoder->irq) val = decoder->lock ? decoder->oe : 0; else val = decoder->oe; v4l2_subdev_notify_event(&decoder->sd, &tvp5150_ev_fmt); } else { pm_runtime_put(sd->dev); } regmap_update_bits(decoder->regmap, TVP5150_MISC_CTL, mask, val); return 0; } static int tvp5150_s_routing(struct v4l2_subdev *sd, u32 input, u32 output, u32 config) { struct tvp5150 *decoder = to_tvp5150(sd); decoder->input = input; decoder->output = output; if (output == TVP5150_BLACK_SCREEN) decoder->enable = false; else decoder->enable = true; tvp5150_selmux(sd); return 0; } static int tvp5150_s_raw_fmt(struct v4l2_subdev *sd, struct v4l2_vbi_format *fmt) { struct tvp5150 *decoder = to_tvp5150(sd); /* * this is for capturing 36 raw vbi lines * if there's a way to cut off the beginning 2 vbi lines * with the tvp5150 then the vbi line count could be lowered * to 17 lines/field again, although I couldn't find a register * which could do that cropping */ if (fmt->sample_format == V4L2_PIX_FMT_GREY) regmap_write(decoder->regmap, TVP5150_LUMA_PROC_CTL_1, 0x70); if (fmt->count[0] == 18 && fmt->count[1] == 18) { regmap_write(decoder->regmap, TVP5150_VERT_BLANKING_START, 0x00); regmap_write(decoder->regmap, TVP5150_VERT_BLANKING_STOP, 0x01); } return 0; } static int tvp5150_s_sliced_fmt(struct v4l2_subdev *sd, struct v4l2_sliced_vbi_format *svbi) { struct tvp5150 *decoder = to_tvp5150(sd); int i; if (svbi->service_set != 0) { for (i = 0; i <= 23; i++) { svbi->service_lines[1][i] = 0; svbi->service_lines[0][i] = tvp5150_set_vbi(sd, svbi->service_lines[0][i], 0xf0, i, 3); } /* Enables FIFO */ regmap_write(decoder->regmap, TVP5150_FIFO_OUT_CTRL, 1); } else { /* Disables FIFO*/ regmap_write(decoder->regmap, TVP5150_FIFO_OUT_CTRL, 0); /* Disable Full Field */ regmap_write(decoder->regmap, TVP5150_FULL_FIELD_ENA, 0); /* Disable Line modes */ for (i = TVP5150_LINE_MODE_INI; i <= TVP5150_LINE_MODE_END; i++) regmap_write(decoder->regmap, i, 0xff); } return 0; } static int tvp5150_g_sliced_fmt(struct v4l2_subdev *sd, struct v4l2_sliced_vbi_format *svbi) { int i, mask = 0; memset(svbi->service_lines, 0, sizeof(svbi->service_lines)); for (i = 0; i <= 23; i++) { svbi->service_lines[0][i] = tvp5150_get_vbi(sd, i); mask |= svbi->service_lines[0][i]; } svbi->service_set = mask; return 0; } #ifdef CONFIG_VIDEO_ADV_DEBUG static int tvp5150_g_register(struct v4l2_subdev *sd, struct v4l2_dbg_register *reg) { int res; res = tvp5150_read(sd, reg->reg & 0xff); if (res < 0) { dev_err(sd->dev, "%s: failed with error = %d\n", __func__, res); return res; } reg->val = res; reg->size = 1; return 0; } static int tvp5150_s_register(struct v4l2_subdev *sd, const struct v4l2_dbg_register *reg) { struct tvp5150 *decoder = to_tvp5150(sd); return regmap_write(decoder->regmap, reg->reg & 0xff, reg->val & 0xff); } #endif static int tvp5150_subscribe_event(struct v4l2_subdev *sd, struct v4l2_fh *fh, struct v4l2_event_subscription *sub) { switch (sub->type) { case V4L2_EVENT_SOURCE_CHANGE: return v4l2_src_change_event_subdev_subscribe(sd, fh, sub); case V4L2_EVENT_CTRL: return v4l2_ctrl_subdev_subscribe_event(sd, fh, sub); default: return -EINVAL; } } static int tvp5150_g_tuner(struct v4l2_subdev *sd, struct v4l2_tuner *vt) { int status = tvp5150_read(sd, 0x88); vt->signal = ((status & 0x04) && (status & 0x02)) ? 0xffff : 0x0; return 0; } static int tvp5150_registered(struct v4l2_subdev *sd) { #if defined(CONFIG_MEDIA_CONTROLLER) struct tvp5150 *decoder = to_tvp5150(sd); unsigned int i; int ret; /* * Setup connector pads and links. Enable the link to the first * available connector per default. */ for (i = 0; i < decoder->connectors_num; i++) { struct media_entity *con = &decoder->connectors[i].ent; struct media_pad *pad = &decoder->connectors[i].pad; struct v4l2_fwnode_connector *v4l2c = &decoder->connectors[i].base; struct v4l2_connector_link *link = v4l2_connector_first_link(v4l2c); unsigned int port = link->fwnode_link.remote_port; unsigned int flags = i ? 0 : MEDIA_LNK_FL_ENABLED; bool is_svideo = v4l2c->type == V4L2_CONN_SVIDEO; pad->flags = MEDIA_PAD_FL_SOURCE; ret = media_entity_pads_init(con, 1, pad); if (ret < 0) goto err; ret = media_device_register_entity(sd->v4l2_dev->mdev, con); if (ret < 0) goto err; ret = media_create_pad_link(con, 0, &sd->entity, port, flags); if (ret < 0) goto err; if (is_svideo) { /* * Check tvp5150_link_setup() comments for more * information. */ link = v4l2_connector_last_link(v4l2c); port = link->fwnode_link.remote_port; ret = media_create_pad_link(con, 0, &sd->entity, port, flags); if (ret < 0) goto err; } /* Enable default input. */ if (flags == MEDIA_LNK_FL_ENABLED) { decoder->input = is_svideo ? TVP5150_SVIDEO : port == 0 ? TVP5150_COMPOSITE0 : TVP5150_COMPOSITE1; tvp5150_selmux(sd); decoder->cur_connector = &decoder->connectors[i]; tvp5150_s_std(sd, v4l2c->connector.analog.sdtv_stds); } } return 0; err: for (i = 0; i < decoder->connectors_num; i++) { media_device_unregister_entity(&decoder->connectors[i].ent); media_entity_cleanup(&decoder->connectors[i].ent); } return ret; #endif return 0; } static int tvp5150_open(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh) { return pm_runtime_resume_and_get(sd->dev); } static int tvp5150_close(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh) { pm_runtime_put(sd->dev); return 0; } /* ----------------------------------------------------------------------- */ static const struct v4l2_ctrl_ops tvp5150_ctrl_ops = { .s_ctrl = tvp5150_s_ctrl, }; static const struct v4l2_subdev_core_ops tvp5150_core_ops = { .log_status = tvp5150_log_status, .reset = tvp5150_reset, #ifdef CONFIG_VIDEO_ADV_DEBUG .g_register = tvp5150_g_register, .s_register = tvp5150_s_register, #endif .subscribe_event = tvp5150_subscribe_event, .unsubscribe_event = v4l2_event_subdev_unsubscribe, }; static const struct v4l2_subdev_tuner_ops tvp5150_tuner_ops = { .g_tuner = tvp5150_g_tuner, }; static const struct v4l2_subdev_video_ops tvp5150_video_ops = { .s_std = tvp5150_s_std, .g_std = tvp5150_g_std, .querystd = tvp5150_querystd, .s_stream = tvp5150_s_stream, .s_routing = tvp5150_s_routing, }; static const struct v4l2_subdev_vbi_ops tvp5150_vbi_ops = { .g_sliced_vbi_cap = tvp5150_g_sliced_vbi_cap, .g_sliced_fmt = tvp5150_g_sliced_fmt, .s_sliced_fmt = tvp5150_s_sliced_fmt, .s_raw_fmt = tvp5150_s_raw_fmt, }; static const struct v4l2_subdev_pad_ops tvp5150_pad_ops = { .init_cfg = tvp5150_init_cfg, .enum_mbus_code = tvp5150_enum_mbus_code, .enum_frame_size = tvp5150_enum_frame_size, .set_fmt = tvp5150_fill_fmt, .get_fmt = tvp5150_fill_fmt, .get_selection = tvp5150_get_selection, .set_selection = tvp5150_set_selection, .get_mbus_config = tvp5150_get_mbus_config, }; static const struct v4l2_subdev_ops tvp5150_ops = { .core = &tvp5150_core_ops, .tuner = &tvp5150_tuner_ops, .video = &tvp5150_video_ops, .vbi = &tvp5150_vbi_ops, .pad = &tvp5150_pad_ops, }; static const struct v4l2_subdev_internal_ops tvp5150_internal_ops = { .registered = tvp5150_registered, .open = tvp5150_open, .close = tvp5150_close, }; /**************************************************************************** I2C Client & Driver ****************************************************************************/ static const struct regmap_range tvp5150_readable_ranges[] = { { .range_min = TVP5150_VD_IN_SRC_SEL_1, .range_max = TVP5150_AUTOSW_MSK, }, { .range_min = TVP5150_COLOR_KIL_THSH_CTL, .range_max = TVP5150_CONF_SHARED_PIN, }, { .range_min = TVP5150_ACT_VD_CROP_ST_MSB, .range_max = TVP5150_HORIZ_SYNC_START, }, { .range_min = TVP5150_VERT_BLANKING_START, .range_max = TVP5150_INTT_CONFIG_REG_B, }, { .range_min = TVP5150_VIDEO_STD, .range_max = TVP5150_VIDEO_STD, }, { .range_min = TVP5150_CB_GAIN_FACT, .range_max = TVP5150_REV_SELECT, }, { .range_min = TVP5150_MSB_DEV_ID, .range_max = TVP5150_STATUS_REG_5, }, { .range_min = TVP5150_CC_DATA_INI, .range_max = TVP5150_TELETEXT_FIL_ENA, }, { .range_min = TVP5150_INT_STATUS_REG_A, .range_max = TVP5150_FIFO_OUT_CTRL, }, { .range_min = TVP5150_FULL_FIELD_ENA, .range_max = TVP5150_FULL_FIELD_MODE_REG, }, }; static bool tvp5150_volatile_reg(struct device *dev, unsigned int reg) { switch (reg) { case TVP5150_VERT_LN_COUNT_MSB: case TVP5150_VERT_LN_COUNT_LSB: case TVP5150_INT_STATUS_REG_A: case TVP5150_INT_STATUS_REG_B: case TVP5150_INT_ACTIVE_REG_B: case TVP5150_STATUS_REG_1: case TVP5150_STATUS_REG_2: case TVP5150_STATUS_REG_3: case TVP5150_STATUS_REG_4: case TVP5150_STATUS_REG_5: /* CC, WSS, VPS, VITC data? */ case TVP5150_VBI_FIFO_READ_DATA: case TVP5150_VDP_STATUS_REG: case TVP5150_FIFO_WORD_COUNT: return true; default: return false; } } static const struct regmap_access_table tvp5150_readable_table = { .yes_ranges = tvp5150_readable_ranges, .n_yes_ranges = ARRAY_SIZE(tvp5150_readable_ranges), }; static struct regmap_config tvp5150_config = { .reg_bits = 8, .val_bits = 8, .max_register = 0xff, .cache_type = REGCACHE_RBTREE, .rd_table = &tvp5150_readable_table, .volatile_reg = tvp5150_volatile_reg, }; static int tvp5150_detect_version(struct tvp5150 *core) { struct v4l2_subdev *sd = &core->sd; struct i2c_client *c = v4l2_get_subdevdata(sd); u8 regs[4]; int res; /* * Read consequent registers - TVP5150_MSB_DEV_ID, TVP5150_LSB_DEV_ID, * TVP5150_ROM_MAJOR_VER, TVP5150_ROM_MINOR_VER */ res = regmap_bulk_read(core->regmap, TVP5150_MSB_DEV_ID, regs, 4); if (res < 0) { dev_err(&c->dev, "reading ID registers failed: %d\n", res); return res; } core->dev_id = (regs[0] << 8) | regs[1]; core->rom_ver = (regs[2] << 8) | regs[3]; dev_info(sd->dev, "tvp%04x (%u.%u) chip found @ 0x%02x (%s)\n", core->dev_id, regs[2], regs[3], c->addr << 1, c->adapter->name); if (core->dev_id == 0x5150 && core->rom_ver == 0x0321) { dev_info(sd->dev, "tvp5150a detected.\n"); } else if (core->dev_id == 0x5150 && core->rom_ver == 0x0400) { dev_info(sd->dev, "tvp5150am1 detected.\n"); /* ITU-T BT.656.4 timing */ regmap_write(core->regmap, TVP5150_REV_SELECT, 0); } else if (core->dev_id == 0x5151 && core->rom_ver == 0x0100) { dev_info(sd->dev, "tvp5151 detected.\n"); } else { dev_info(sd->dev, "*** unknown tvp%04x chip detected.\n", core->dev_id); } return 0; } static int tvp5150_init(struct i2c_client *c) { struct gpio_desc *pdn_gpio; struct gpio_desc *reset_gpio; pdn_gpio = devm_gpiod_get_optional(&c->dev, "pdn", GPIOD_OUT_HIGH); if (IS_ERR(pdn_gpio)) return PTR_ERR(pdn_gpio); if (pdn_gpio) { gpiod_set_value_cansleep(pdn_gpio, 0); /* Delay time between power supplies active and reset */ msleep(20); } reset_gpio = devm_gpiod_get_optional(&c->dev, "reset", GPIOD_OUT_HIGH); if (IS_ERR(reset_gpio)) return PTR_ERR(reset_gpio); if (reset_gpio) { /* RESETB pulse duration */ ndelay(500); gpiod_set_value_cansleep(reset_gpio, 0); /* Delay time between end of reset to I2C active */ usleep_range(200, 250); } return 0; } #if defined(CONFIG_MEDIA_CONTROLLER) static int tvp5150_mc_init(struct tvp5150 *decoder) { struct v4l2_subdev *sd = &decoder->sd; unsigned int i; sd->entity.ops = &tvp5150_sd_media_ops; sd->entity.function = MEDIA_ENT_F_ATV_DECODER; for (i = 0; i < TVP5150_NUM_PADS - 1; i++) { decoder->pads[i].flags = MEDIA_PAD_FL_SINK; decoder->pads[i].sig_type = PAD_SIGNAL_ANALOG; } decoder->pads[i].flags = MEDIA_PAD_FL_SOURCE; decoder->pads[i].sig_type = PAD_SIGNAL_DV; return media_entity_pads_init(&sd->entity, TVP5150_NUM_PADS, decoder->pads); } #else /* !defined(CONFIG_MEDIA_CONTROLLER) */ static inline int tvp5150_mc_init(struct tvp5150 *decoder) { return 0; } #endif /* defined(CONFIG_MEDIA_CONTROLLER) */ static int tvp5150_validate_connectors(struct tvp5150 *decoder) { struct device *dev = decoder->sd.dev; struct tvp5150_connector *tvpc; struct v4l2_fwnode_connector *v4l2c; unsigned int i; if (!decoder->connectors_num) { dev_err(dev, "No valid connector found\n"); return -ENODEV; } for (i = 0; i < decoder->connectors_num; i++) { struct v4l2_connector_link *link0 = NULL; struct v4l2_connector_link *link1; tvpc = &decoder->connectors[i]; v4l2c = &tvpc->base; if (v4l2c->type == V4L2_CONN_COMPOSITE) { if (v4l2c->nr_of_links != 1) { dev_err(dev, "Composite: connector needs 1 link\n"); return -EINVAL; } link0 = v4l2_connector_first_link(v4l2c); if (!link0) { dev_err(dev, "Composite: invalid first link\n"); return -EINVAL; } if (link0->fwnode_link.remote_id == 1) { dev_err(dev, "Composite: invalid endpoint id\n"); return -EINVAL; } } if (v4l2c->type == V4L2_CONN_SVIDEO) { if (v4l2c->nr_of_links != 2) { dev_err(dev, "SVideo: connector needs 2 links\n"); return -EINVAL; } link0 = v4l2_connector_first_link(v4l2c); if (!link0) { dev_err(dev, "SVideo: invalid first link\n"); return -EINVAL; } link1 = v4l2_connector_last_link(v4l2c); if (link0->fwnode_link.remote_port == link1->fwnode_link.remote_port) { dev_err(dev, "SVideo: invalid link setup\n"); return -EINVAL; } } if (!(v4l2c->connector.analog.sdtv_stds & TVP5150_STD_MASK)) { dev_err(dev, "Unsupported tv-norm on connector %s\n", v4l2c->name); return -EINVAL; } } return 0; } static int tvp5150_parse_dt(struct tvp5150 *decoder, struct device_node *np) { struct device *dev = decoder->sd.dev; struct v4l2_fwnode_endpoint bus_cfg = { .bus_type = V4L2_MBUS_UNKNOWN }; struct device_node *ep_np; struct tvp5150_connector *tvpc; struct v4l2_fwnode_connector *v4l2c; unsigned int flags, ep_num; unsigned int i; int ret; /* At least 1 output and 1 input */ ep_num = of_graph_get_endpoint_count(np); if (ep_num < 2 || ep_num > 5) { dev_err(dev, "At least 1 input and 1 output must be connected to the device.\n"); return -EINVAL; } /* Layout if all connectors are used: * * tvp-5150 port@0 (AIP1A) * endpoint@0 -----------> Comp0-Con port * endpoint@1 --------+--> Svideo-Con port * tvp-5150 port@1 (AIP1B) | * endpoint@1 --------+ * endpoint@0 -----------> Comp1-Con port * tvp-5150 port@2 * endpoint (video bitstream output at YOUT[0-7] parallel bus) */ for_each_endpoint_of_node(np, ep_np) { struct fwnode_handle *ep_fwnode = of_fwnode_handle(ep_np); unsigned int next_connector = decoder->connectors_num; struct of_endpoint ep; of_graph_parse_endpoint(ep_np, &ep); if (ep.port > 1 || ep.id > 1) { dev_dbg(dev, "Ignore connector on port@%u/ep@%u\n", ep.port, ep.id); continue; } tvpc = &decoder->connectors[next_connector]; v4l2c = &tvpc->base; if (ep.port == 0 || (ep.port == 1 && ep.id == 0)) { ret = v4l2_fwnode_connector_parse(ep_fwnode, v4l2c); if (ret) goto err_put; ret = v4l2_fwnode_connector_add_link(ep_fwnode, v4l2c); if (ret) goto err_put; decoder->connectors_num++; } else { /* Adding the 2nd svideo link */ for (i = 0; i < TVP5150_MAX_CONNECTORS; i++) { tvpc = &decoder->connectors[i]; v4l2c = &tvpc->base; if (v4l2c->type == V4L2_CONN_SVIDEO) break; } ret = v4l2_fwnode_connector_add_link(ep_fwnode, v4l2c); if (ret) goto err_put; } } ret = tvp5150_validate_connectors(decoder); if (ret) goto err_free; for (i = 0; i < decoder->connectors_num; i++) { tvpc = &decoder->connectors[i]; v4l2c = &tvpc->base; tvpc->ent.flags = MEDIA_ENT_FL_CONNECTOR; tvpc->ent.function = v4l2c->type == V4L2_CONN_SVIDEO ? MEDIA_ENT_F_CONN_SVIDEO : MEDIA_ENT_F_CONN_COMPOSITE; tvpc->ent.name = devm_kasprintf(dev, GFP_KERNEL, "%s %s", v4l2c->name, v4l2c->label ? v4l2c->label : ""); if (!tvpc->ent.name) { ret = -ENOMEM; goto err_free; } } ep_np = of_graph_get_endpoint_by_regs(np, TVP5150_PAD_VID_OUT, 0); if (!ep_np) { ret = -EINVAL; dev_err(dev, "Error no output endpoint available\n"); goto err_free; } ret = v4l2_fwnode_endpoint_parse(of_fwnode_handle(ep_np), &bus_cfg); of_node_put(ep_np); if (ret) goto err_free; flags = bus_cfg.bus.parallel.flags; if (bus_cfg.bus_type == V4L2_MBUS_PARALLEL && !(flags & V4L2_MBUS_HSYNC_ACTIVE_HIGH && flags & V4L2_MBUS_VSYNC_ACTIVE_HIGH && flags & V4L2_MBUS_FIELD_EVEN_LOW)) { ret = -EINVAL; goto err_free; } decoder->mbus_type = bus_cfg.bus_type; return 0; err_put: of_node_put(ep_np); err_free: for (i = 0; i < TVP5150_MAX_CONNECTORS; i++) v4l2_fwnode_connector_free(&decoder->connectors[i].base); return ret; } static const char * const tvp5150_test_patterns[2] = { "Disabled", "Black screen" }; static int tvp5150_probe(struct i2c_client *c) { struct tvp5150 *core; struct v4l2_subdev *sd; struct device_node *np = c->dev.of_node; struct regmap *map; unsigned int i; int res; /* Check if the adapter supports the needed features */ if (!i2c_check_functionality(c->adapter, I2C_FUNC_SMBUS_READ_BYTE | I2C_FUNC_SMBUS_WRITE_BYTE_DATA)) return -EIO; res = tvp5150_init(c); if (res) return res; core = devm_kzalloc(&c->dev, sizeof(*core), GFP_KERNEL); if (!core) return -ENOMEM; map = devm_regmap_init_i2c(c, &tvp5150_config); if (IS_ERR(map)) return PTR_ERR(map); core->regmap = map; sd = &core->sd; v4l2_i2c_subdev_init(sd, c, &tvp5150_ops); sd->internal_ops = &tvp5150_internal_ops; sd->flags |= V4L2_SUBDEV_FL_HAS_DEVNODE | V4L2_SUBDEV_FL_HAS_EVENTS; if (IS_ENABLED(CONFIG_OF) && np) { res = tvp5150_parse_dt(core, np); if (res) { dev_err(sd->dev, "DT parsing error: %d\n", res); return res; } } else { /* Default to BT.656 embedded sync */ core->mbus_type = V4L2_MBUS_BT656; } res = tvp5150_mc_init(core); if (res) return res; res = tvp5150_detect_version(core); if (res < 0) return res; /* * Iterate over all available connectors in case they are supported and * successfully parsed. Fallback to default autodetect in case they * aren't supported. */ for (i = 0; i < core->connectors_num; i++) { struct v4l2_fwnode_connector *v4l2c; v4l2c = &core->connectors[i].base; core->norm |= v4l2c->connector.analog.sdtv_stds; } if (!core->connectors_num) core->norm = V4L2_STD_ALL; core->detected_norm = V4L2_STD_UNKNOWN; core->input = TVP5150_COMPOSITE1; core->enable = true; v4l2_ctrl_handler_init(&core->hdl, 5); v4l2_ctrl_new_std(&core->hdl, &tvp5150_ctrl_ops, V4L2_CID_BRIGHTNESS, 0, 255, 1, 128); v4l2_ctrl_new_std(&core->hdl, &tvp5150_ctrl_ops, V4L2_CID_CONTRAST, 0, 255, 1, 128); v4l2_ctrl_new_std(&core->hdl, &tvp5150_ctrl_ops, V4L2_CID_SATURATION, 0, 255, 1, 128); v4l2_ctrl_new_std(&core->hdl, &tvp5150_ctrl_ops, V4L2_CID_HUE, -128, 127, 1, 0); v4l2_ctrl_new_std(&core->hdl, &tvp5150_ctrl_ops, V4L2_CID_PIXEL_RATE, 27000000, 27000000, 1, 27000000); v4l2_ctrl_new_std_menu_items(&core->hdl, &tvp5150_ctrl_ops, V4L2_CID_TEST_PATTERN, ARRAY_SIZE(tvp5150_test_patterns) - 1, 0, 0, tvp5150_test_patterns); sd->ctrl_handler = &core->hdl; if (core->hdl.error) { res = core->hdl.error; goto err; } tvp5150_set_default(tvp5150_read_std(sd), &core->rect); core->irq = c->irq; tvp5150_reset(sd, 0); /* Calls v4l2_ctrl_handler_setup() */ if (c->irq) { res = devm_request_threaded_irq(&c->dev, c->irq, NULL, tvp5150_isr, IRQF_TRIGGER_HIGH | IRQF_ONESHOT, "tvp5150", core); if (res) goto err; } res = v4l2_async_register_subdev(sd); if (res < 0) goto err; if (debug > 1) tvp5150_log_status(sd); pm_runtime_set_active(&c->dev); pm_runtime_enable(&c->dev); pm_runtime_idle(&c->dev); return 0; err: v4l2_ctrl_handler_free(&core->hdl); return res; } static void tvp5150_remove(struct i2c_client *c) { struct v4l2_subdev *sd = i2c_get_clientdata(c); struct tvp5150 *decoder = to_tvp5150(sd); unsigned int i; dev_dbg_lvl(sd->dev, 1, debug, "tvp5150.c: removing tvp5150 adapter on address 0x%x\n", c->addr << 1); for (i = 0; i < decoder->connectors_num; i++) v4l2_fwnode_connector_free(&decoder->connectors[i].base); for (i = 0; i < decoder->connectors_num; i++) { media_device_unregister_entity(&decoder->connectors[i].ent); media_entity_cleanup(&decoder->connectors[i].ent); } v4l2_async_unregister_subdev(sd); v4l2_ctrl_handler_free(&decoder->hdl); pm_runtime_disable(&c->dev); pm_runtime_set_suspended(&c->dev); } /* ----------------------------------------------------------------------- */ static const struct dev_pm_ops tvp5150_pm_ops = { SET_RUNTIME_PM_OPS(tvp5150_runtime_suspend, tvp5150_runtime_resume, NULL) }; static const struct i2c_device_id tvp5150_id[] = { { "tvp5150", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, tvp5150_id); #if IS_ENABLED(CONFIG_OF) static const struct of_device_id tvp5150_of_match[] = { { .compatible = "ti,tvp5150", }, { /* sentinel */ }, }; MODULE_DEVICE_TABLE(of, tvp5150_of_match); #endif static struct i2c_driver tvp5150_driver = { .driver = { .of_match_table = of_match_ptr(tvp5150_of_match), .name = "tvp5150", .pm = &tvp5150_pm_ops, }, .probe = tvp5150_probe, .remove = tvp5150_remove, .id_table = tvp5150_id, }; module_i2c_driver(tvp5150_driver);
linux-master
drivers/media/i2c/tvp5150.c
// SPDX-License-Identifier: GPL-2.0 // Copyright (c) 2019 Intel Corporation. #include <asm/unaligned.h> #include <linux/acpi.h> #include <linux/delay.h> #include <linux/i2c.h> #include <linux/module.h> #include <linux/pm_runtime.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-device.h> #include <media/v4l2-fwnode.h> #define HI556_REG_VALUE_08BIT 1 #define HI556_REG_VALUE_16BIT 2 #define HI556_REG_VALUE_24BIT 3 #define HI556_LINK_FREQ_437MHZ 437000000ULL #define HI556_MCLK 19200000 #define HI556_DATA_LANES 2 #define HI556_RGB_DEPTH 10 #define HI556_REG_CHIP_ID 0x0f16 #define HI556_CHIP_ID 0x0556 #define HI556_REG_MODE_SELECT 0x0a00 #define HI556_MODE_STANDBY 0x0000 #define HI556_MODE_STREAMING 0x0100 /* vertical-timings from sensor */ #define HI556_REG_FLL 0x0006 #define HI556_FLL_30FPS 0x0814 #define HI556_FLL_30FPS_MIN 0x0814 #define HI556_FLL_MAX 0x7fff /* horizontal-timings from sensor */ #define HI556_REG_LLP 0x0008 /* Exposure controls from sensor */ #define HI556_REG_EXPOSURE 0x0074 #define HI556_EXPOSURE_MIN 6 #define HI556_EXPOSURE_MAX_MARGIN 2 #define HI556_EXPOSURE_STEP 1 /* Analog gain controls from sensor */ #define HI556_REG_ANALOG_GAIN 0x0077 #define HI556_ANAL_GAIN_MIN 0 #define HI556_ANAL_GAIN_MAX 240 #define HI556_ANAL_GAIN_STEP 1 /* Digital gain controls from sensor */ #define HI556_REG_MWB_GR_GAIN 0x0078 #define HI556_REG_MWB_GB_GAIN 0x007a #define HI556_REG_MWB_R_GAIN 0x007c #define HI556_REG_MWB_B_GAIN 0x007e #define HI556_DGTL_GAIN_MIN 0 #define HI556_DGTL_GAIN_MAX 2048 #define HI556_DGTL_GAIN_STEP 1 #define HI556_DGTL_GAIN_DEFAULT 256 /* Test Pattern Control */ #define HI556_REG_ISP 0X0a05 #define HI556_REG_ISP_TPG_EN 0x01 #define HI556_REG_TEST_PATTERN 0x0201 /* HI556 native and active pixel array size. */ #define HI556_NATIVE_WIDTH 2592U #define HI556_NATIVE_HEIGHT 1944U #define HI556_PIXEL_ARRAY_LEFT 0U #define HI556_PIXEL_ARRAY_TOP 0U #define HI556_PIXEL_ARRAY_WIDTH 2592U #define HI556_PIXEL_ARRAY_HEIGHT 1944U enum { HI556_LINK_FREQ_437MHZ_INDEX, }; struct hi556_reg { u16 address; u16 val; }; struct hi556_reg_list { u32 num_of_regs; const struct hi556_reg *regs; }; struct hi556_link_freq_config { const struct hi556_reg_list reg_list; }; struct hi556_mode { /* Frame width in pixels */ u32 width; /* Frame height in pixels */ u32 height; /* Analog crop rectangle. */ struct v4l2_rect crop; /* Horizontal timining size */ u32 llp; /* Default vertical timining size */ u32 fll_def; /* Min vertical timining size */ u32 fll_min; /* Link frequency needed for this resolution */ u32 link_freq_index; /* Sensor register settings for this resolution */ const struct hi556_reg_list reg_list; }; #define to_hi556(_sd) container_of(_sd, struct hi556, sd) //SENSOR_INITIALIZATION static const struct hi556_reg mipi_data_rate_874mbps[] = { {0x0e00, 0x0102}, {0x0e02, 0x0102}, {0x0e0c, 0x0100}, {0x2000, 0x7400}, {0x2002, 0x001c}, {0x2004, 0x0242}, {0x2006, 0x0942}, {0x2008, 0x7007}, {0x200a, 0x0fd9}, {0x200c, 0x0259}, {0x200e, 0x7008}, {0x2010, 0x160e}, {0x2012, 0x0047}, {0x2014, 0x2118}, {0x2016, 0x0041}, {0x2018, 0x00d8}, {0x201a, 0x0145}, {0x201c, 0x0006}, {0x201e, 0x0181}, {0x2020, 0x13cc}, {0x2022, 0x2057}, {0x2024, 0x7001}, {0x2026, 0x0fca}, {0x2028, 0x00cb}, {0x202a, 0x009f}, {0x202c, 0x7002}, {0x202e, 0x13cc}, {0x2030, 0x019b}, {0x2032, 0x014d}, {0x2034, 0x2987}, {0x2036, 0x2766}, {0x2038, 0x0020}, {0x203a, 0x2060}, {0x203c, 0x0e5d}, {0x203e, 0x181d}, {0x2040, 0x2066}, {0x2042, 0x20c4}, {0x2044, 0x5000}, {0x2046, 0x0005}, {0x2048, 0x0000}, {0x204a, 0x01db}, {0x204c, 0x025a}, {0x204e, 0x00c0}, {0x2050, 0x0005}, {0x2052, 0x0006}, {0x2054, 0x0ad9}, {0x2056, 0x0259}, {0x2058, 0x0618}, {0x205a, 0x0258}, {0x205c, 0x2266}, {0x205e, 0x20c8}, {0x2060, 0x2060}, {0x2062, 0x707b}, {0x2064, 0x0fdd}, {0x2066, 0x81b8}, {0x2068, 0x5040}, {0x206a, 0x0020}, {0x206c, 0x5060}, {0x206e, 0x3143}, {0x2070, 0x5081}, {0x2072, 0x025c}, {0x2074, 0x7800}, {0x2076, 0x7400}, {0x2078, 0x001c}, {0x207a, 0x0242}, {0x207c, 0x0942}, {0x207e, 0x0bd9}, {0x2080, 0x0259}, {0x2082, 0x7008}, {0x2084, 0x160e}, {0x2086, 0x0047}, {0x2088, 0x2118}, {0x208a, 0x0041}, {0x208c, 0x00d8}, {0x208e, 0x0145}, {0x2090, 0x0006}, {0x2092, 0x0181}, {0x2094, 0x13cc}, {0x2096, 0x2057}, {0x2098, 0x7001}, {0x209a, 0x0fca}, {0x209c, 0x00cb}, {0x209e, 0x009f}, {0x20a0, 0x7002}, {0x20a2, 0x13cc}, {0x20a4, 0x019b}, {0x20a6, 0x014d}, {0x20a8, 0x2987}, {0x20aa, 0x2766}, {0x20ac, 0x0020}, {0x20ae, 0x2060}, {0x20b0, 0x0e5d}, {0x20b2, 0x181d}, {0x20b4, 0x2066}, {0x20b6, 0x20c4}, {0x20b8, 0x50a0}, {0x20ba, 0x0005}, {0x20bc, 0x0000}, {0x20be, 0x01db}, {0x20c0, 0x025a}, {0x20c2, 0x00c0}, {0x20c4, 0x0005}, {0x20c6, 0x0006}, {0x20c8, 0x0ad9}, {0x20ca, 0x0259}, {0x20cc, 0x0618}, {0x20ce, 0x0258}, {0x20d0, 0x2266}, {0x20d2, 0x20c8}, {0x20d4, 0x2060}, {0x20d6, 0x707b}, {0x20d8, 0x0fdd}, {0x20da, 0x86b8}, {0x20dc, 0x50e0}, {0x20de, 0x0020}, {0x20e0, 0x5100}, {0x20e2, 0x3143}, {0x20e4, 0x5121}, {0x20e6, 0x7800}, {0x20e8, 0x3140}, {0x20ea, 0x01c4}, {0x20ec, 0x01c1}, {0x20ee, 0x01c0}, {0x20f0, 0x01c4}, {0x20f2, 0x2700}, {0x20f4, 0x3d40}, {0x20f6, 0x7800}, {0x20f8, 0xffff}, {0x27fe, 0xe000}, {0x3000, 0x60f8}, {0x3002, 0x187f}, {0x3004, 0x7060}, {0x3006, 0x0114}, {0x3008, 0x60b0}, {0x300a, 0x1473}, {0x300c, 0x0013}, {0x300e, 0x140f}, {0x3010, 0x0040}, {0x3012, 0x100f}, {0x3014, 0x60f8}, {0x3016, 0x187f}, {0x3018, 0x7060}, {0x301a, 0x0114}, {0x301c, 0x60b0}, {0x301e, 0x1473}, {0x3020, 0x0013}, {0x3022, 0x140f}, {0x3024, 0x0040}, {0x3026, 0x000f}, {0x0b00, 0x0000}, {0x0b02, 0x0045}, {0x0b04, 0xb405}, {0x0b06, 0xc403}, {0x0b08, 0x0081}, {0x0b0a, 0x8252}, {0x0b0c, 0xf814}, {0x0b0e, 0xc618}, {0x0b10, 0xa828}, {0x0b12, 0x004c}, {0x0b14, 0x4068}, {0x0b16, 0x0000}, {0x0f30, 0x5b15}, {0x0f32, 0x7067}, {0x0954, 0x0009}, {0x0956, 0x0000}, {0x0958, 0xbb80}, {0x095a, 0x5140}, {0x0c00, 0x1110}, {0x0c02, 0x0011}, {0x0c04, 0x0000}, {0x0c06, 0x0200}, {0x0c10, 0x0040}, {0x0c12, 0x0040}, {0x0c14, 0x0040}, {0x0c16, 0x0040}, {0x0a10, 0x4000}, {0x3068, 0xf800}, {0x306a, 0xf876}, {0x006c, 0x0000}, {0x005e, 0x0200}, {0x000e, 0x0100}, {0x0e0a, 0x0001}, {0x004a, 0x0100}, {0x004c, 0x0000}, {0x004e, 0x0100}, {0x000c, 0x0022}, {0x0008, 0x0b00}, {0x005a, 0x0202}, {0x0012, 0x000e}, {0x0018, 0x0a33}, {0x0022, 0x0008}, {0x0028, 0x0017}, {0x0024, 0x0028}, {0x002a, 0x002d}, {0x0026, 0x0030}, {0x002c, 0x07c9}, {0x002e, 0x1111}, {0x0030, 0x1111}, {0x0032, 0x1111}, {0x0006, 0x07bc}, {0x0a22, 0x0000}, {0x0a12, 0x0a20}, {0x0a14, 0x0798}, {0x003e, 0x0000}, {0x0074, 0x080e}, {0x0070, 0x0407}, {0x0002, 0x0000}, {0x0a02, 0x0100}, {0x0a24, 0x0100}, {0x0046, 0x0000}, {0x0076, 0x0000}, {0x0060, 0x0000}, {0x0062, 0x0530}, {0x0064, 0x0500}, {0x0066, 0x0530}, {0x0068, 0x0500}, {0x0122, 0x0300}, {0x015a, 0xff08}, {0x0804, 0x0300}, {0x0806, 0x0100}, {0x005c, 0x0102}, {0x0a1a, 0x0800}, }; static const struct hi556_reg mode_2592x1944_regs[] = { {0x0a00, 0x0000}, {0x0b0a, 0x8252}, {0x0f30, 0x5b15}, {0x0f32, 0x7067}, {0x004a, 0x0100}, {0x004c, 0x0000}, {0x004e, 0x0100}, {0x000c, 0x0022}, {0x0008, 0x0b00}, {0x005a, 0x0202}, {0x0012, 0x000e}, {0x0018, 0x0a33}, {0x0022, 0x0008}, {0x0028, 0x0017}, {0x0024, 0x0028}, {0x002a, 0x002d}, {0x0026, 0x0030}, {0x002c, 0x07c9}, {0x002e, 0x1111}, {0x0030, 0x1111}, {0x0032, 0x1111}, {0x0006, 0x0814}, {0x0a22, 0x0000}, {0x0a12, 0x0a20}, {0x0a14, 0x0798}, {0x003e, 0x0000}, {0x0074, 0x0812}, {0x0070, 0x0409}, {0x0804, 0x0300}, {0x0806, 0x0100}, {0x0a04, 0x014a}, {0x090c, 0x0fdc}, {0x090e, 0x002d}, {0x0902, 0x4319}, {0x0914, 0xc10a}, {0x0916, 0x071f}, {0x0918, 0x0408}, {0x091a, 0x0c0d}, {0x091c, 0x0f09}, {0x091e, 0x0a00}, {0x0958, 0xbb80}, }; static const struct hi556_reg mode_2592x1444_regs[] = { {0x0a00, 0x0000}, {0x0b0a, 0x8252}, {0x0f30, 0xe545}, {0x0f32, 0x7067}, {0x004a, 0x0100}, {0x004c, 0x0000}, {0x000c, 0x0022}, {0x0008, 0x0b00}, {0x005a, 0x0202}, {0x0012, 0x000e}, {0x0018, 0x0a33}, {0x0022, 0x0008}, {0x0028, 0x0017}, {0x0024, 0x0122}, {0x002a, 0x0127}, {0x0026, 0x012a}, {0x002c, 0x06cf}, {0x002e, 0x1111}, {0x0030, 0x1111}, {0x0032, 0x1111}, {0x0006, 0x0821}, {0x0a22, 0x0000}, {0x0a12, 0x0a20}, {0x0a14, 0x05a4}, {0x003e, 0x0000}, {0x0074, 0x081f}, {0x0070, 0x040f}, {0x0804, 0x0300}, {0x0806, 0x0100}, {0x0a04, 0x014a}, {0x090c, 0x0fdc}, {0x090e, 0x002d}, {0x0902, 0x4319}, {0x0914, 0xc10a}, {0x0916, 0x071f}, {0x0918, 0x0408}, {0x091a, 0x0c0d}, {0x091c, 0x0f09}, {0x091e, 0x0a00}, {0x0958, 0xbb80}, }; static const struct hi556_reg mode_1296x972_regs[] = { {0x0a00, 0x0000}, {0x0b0a, 0x8259}, {0x0f30, 0x5b15}, {0x0f32, 0x7167}, {0x004a, 0x0100}, {0x004c, 0x0000}, {0x004e, 0x0100}, {0x000c, 0x0122}, {0x0008, 0x0b00}, {0x005a, 0x0404}, {0x0012, 0x000c}, {0x0018, 0x0a33}, {0x0022, 0x0008}, {0x0028, 0x0017}, {0x0024, 0x0022}, {0x002a, 0x002b}, {0x0026, 0x0030}, {0x002c, 0x07c9}, {0x002e, 0x3311}, {0x0030, 0x3311}, {0x0032, 0x3311}, {0x0006, 0x0814}, {0x0a22, 0x0000}, {0x0a12, 0x0510}, {0x0a14, 0x03cc}, {0x003e, 0x0000}, {0x0074, 0x0812}, {0x0070, 0x0409}, {0x0804, 0x0308}, {0x0806, 0x0100}, {0x0a04, 0x016a}, {0x090e, 0x0010}, {0x090c, 0x09c0}, {0x0902, 0x4319}, {0x0914, 0xc106}, {0x0916, 0x040e}, {0x0918, 0x0304}, {0x091a, 0x0708}, {0x091c, 0x0e06}, {0x091e, 0x0300}, {0x0958, 0xbb80}, }; static const char * const hi556_test_pattern_menu[] = { "Disabled", "Solid Colour", "100% Colour Bars", "Fade To Grey Colour Bars", "PN9", "Gradient Horizontal", "Gradient Vertical", "Check Board", "Slant Pattern", }; static const s64 link_freq_menu_items[] = { HI556_LINK_FREQ_437MHZ, }; static const struct hi556_link_freq_config link_freq_configs[] = { [HI556_LINK_FREQ_437MHZ_INDEX] = { .reg_list = { .num_of_regs = ARRAY_SIZE(mipi_data_rate_874mbps), .regs = mipi_data_rate_874mbps, } } }; static const struct hi556_mode supported_modes[] = { { .width = HI556_PIXEL_ARRAY_WIDTH, .height = HI556_PIXEL_ARRAY_HEIGHT, .crop = { .left = HI556_PIXEL_ARRAY_LEFT, .top = HI556_PIXEL_ARRAY_TOP, .width = HI556_PIXEL_ARRAY_WIDTH, .height = HI556_PIXEL_ARRAY_HEIGHT }, .fll_def = HI556_FLL_30FPS, .fll_min = HI556_FLL_30FPS_MIN, .llp = 0x0b00, .reg_list = { .num_of_regs = ARRAY_SIZE(mode_2592x1944_regs), .regs = mode_2592x1944_regs, }, .link_freq_index = HI556_LINK_FREQ_437MHZ_INDEX, }, { .width = HI556_PIXEL_ARRAY_WIDTH, .height = 1444, .crop = { .left = HI556_PIXEL_ARRAY_LEFT, .top = 250, .width = HI556_PIXEL_ARRAY_WIDTH, .height = 1444 }, .fll_def = 0x821, .fll_min = 0x821, .llp = 0x0b00, .reg_list = { .num_of_regs = ARRAY_SIZE(mode_2592x1444_regs), .regs = mode_2592x1444_regs, }, .link_freq_index = HI556_LINK_FREQ_437MHZ_INDEX, }, { .width = 1296, .height = 972, .crop = { .left = HI556_PIXEL_ARRAY_LEFT, .top = HI556_PIXEL_ARRAY_TOP, .width = HI556_PIXEL_ARRAY_WIDTH, .height = HI556_PIXEL_ARRAY_HEIGHT }, .fll_def = HI556_FLL_30FPS, .fll_min = HI556_FLL_30FPS_MIN, .llp = 0x0b00, .reg_list = { .num_of_regs = ARRAY_SIZE(mode_1296x972_regs), .regs = mode_1296x972_regs, }, .link_freq_index = HI556_LINK_FREQ_437MHZ_INDEX, } }; struct hi556 { struct v4l2_subdev sd; struct media_pad pad; struct v4l2_ctrl_handler ctrl_handler; /* V4L2 Controls */ struct v4l2_ctrl *link_freq; struct v4l2_ctrl *pixel_rate; struct v4l2_ctrl *vblank; struct v4l2_ctrl *hblank; struct v4l2_ctrl *exposure; /* Current mode */ const struct hi556_mode *cur_mode; /* To serialize asynchronus callbacks */ struct mutex mutex; /* Streaming on/off */ bool streaming; /* True if the device has been identified */ bool identified; }; static u64 to_pixel_rate(u32 f_index) { u64 pixel_rate = link_freq_menu_items[f_index] * 2 * HI556_DATA_LANES; do_div(pixel_rate, HI556_RGB_DEPTH); return pixel_rate; } static int hi556_read_reg(struct hi556 *hi556, u16 reg, u16 len, u32 *val) { struct i2c_client *client = v4l2_get_subdevdata(&hi556->sd); struct i2c_msg msgs[2]; u8 addr_buf[2]; u8 data_buf[4] = {0}; int ret; if (len > 4) return -EINVAL; put_unaligned_be16(reg, addr_buf); msgs[0].addr = client->addr; msgs[0].flags = 0; msgs[0].len = sizeof(addr_buf); msgs[0].buf = addr_buf; msgs[1].addr = client->addr; msgs[1].flags = I2C_M_RD; msgs[1].len = len; msgs[1].buf = &data_buf[4 - len]; ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs)); if (ret != ARRAY_SIZE(msgs)) return -EIO; *val = get_unaligned_be32(data_buf); return 0; } static int hi556_write_reg(struct hi556 *hi556, u16 reg, u16 len, u32 val) { struct i2c_client *client = v4l2_get_subdevdata(&hi556->sd); u8 buf[6]; if (len > 4) return -EINVAL; put_unaligned_be16(reg, buf); put_unaligned_be32(val << 8 * (4 - len), buf + 2); if (i2c_master_send(client, buf, len + 2) != len + 2) return -EIO; return 0; } static int hi556_write_reg_list(struct hi556 *hi556, const struct hi556_reg_list *r_list) { struct i2c_client *client = v4l2_get_subdevdata(&hi556->sd); unsigned int i; int ret; for (i = 0; i < r_list->num_of_regs; i++) { ret = hi556_write_reg(hi556, r_list->regs[i].address, HI556_REG_VALUE_16BIT, r_list->regs[i].val); if (ret) { dev_err_ratelimited(&client->dev, "failed to write reg 0x%4.4x. error = %d", r_list->regs[i].address, ret); return ret; } } return 0; } static int hi556_update_digital_gain(struct hi556 *hi556, u32 d_gain) { int ret; ret = hi556_write_reg(hi556, HI556_REG_MWB_GR_GAIN, HI556_REG_VALUE_16BIT, d_gain); if (ret) return ret; ret = hi556_write_reg(hi556, HI556_REG_MWB_GB_GAIN, HI556_REG_VALUE_16BIT, d_gain); if (ret) return ret; ret = hi556_write_reg(hi556, HI556_REG_MWB_R_GAIN, HI556_REG_VALUE_16BIT, d_gain); if (ret) return ret; return hi556_write_reg(hi556, HI556_REG_MWB_B_GAIN, HI556_REG_VALUE_16BIT, d_gain); } static int hi556_test_pattern(struct hi556 *hi556, u32 pattern) { int ret; u32 val; if (pattern) { ret = hi556_read_reg(hi556, HI556_REG_ISP, HI556_REG_VALUE_08BIT, &val); if (ret) return ret; ret = hi556_write_reg(hi556, HI556_REG_ISP, HI556_REG_VALUE_08BIT, val | HI556_REG_ISP_TPG_EN); if (ret) return ret; } return hi556_write_reg(hi556, HI556_REG_TEST_PATTERN, HI556_REG_VALUE_08BIT, pattern); } static int hi556_set_ctrl(struct v4l2_ctrl *ctrl) { struct hi556 *hi556 = container_of(ctrl->handler, struct hi556, ctrl_handler); struct i2c_client *client = v4l2_get_subdevdata(&hi556->sd); s64 exposure_max; int ret = 0; /* Propagate change of current control to all related controls */ if (ctrl->id == V4L2_CID_VBLANK) { /* Update max exposure while meeting expected vblanking */ exposure_max = hi556->cur_mode->height + ctrl->val - HI556_EXPOSURE_MAX_MARGIN; __v4l2_ctrl_modify_range(hi556->exposure, hi556->exposure->minimum, exposure_max, hi556->exposure->step, exposure_max); } /* V4L2 controls values will be applied only when power is already up */ if (!pm_runtime_get_if_in_use(&client->dev)) return 0; switch (ctrl->id) { case V4L2_CID_ANALOGUE_GAIN: ret = hi556_write_reg(hi556, HI556_REG_ANALOG_GAIN, HI556_REG_VALUE_16BIT, ctrl->val); break; case V4L2_CID_DIGITAL_GAIN: ret = hi556_update_digital_gain(hi556, ctrl->val); break; case V4L2_CID_EXPOSURE: ret = hi556_write_reg(hi556, HI556_REG_EXPOSURE, HI556_REG_VALUE_16BIT, ctrl->val); break; case V4L2_CID_VBLANK: /* Update FLL that meets expected vertical blanking */ ret = hi556_write_reg(hi556, HI556_REG_FLL, HI556_REG_VALUE_16BIT, hi556->cur_mode->height + ctrl->val); break; case V4L2_CID_TEST_PATTERN: ret = hi556_test_pattern(hi556, ctrl->val); break; default: ret = -EINVAL; break; } pm_runtime_put(&client->dev); return ret; } static const struct v4l2_ctrl_ops hi556_ctrl_ops = { .s_ctrl = hi556_set_ctrl, }; static int hi556_init_controls(struct hi556 *hi556) { struct v4l2_ctrl_handler *ctrl_hdlr; s64 exposure_max, h_blank; int ret; ctrl_hdlr = &hi556->ctrl_handler; ret = v4l2_ctrl_handler_init(ctrl_hdlr, 8); if (ret) return ret; ctrl_hdlr->lock = &hi556->mutex; hi556->link_freq = v4l2_ctrl_new_int_menu(ctrl_hdlr, &hi556_ctrl_ops, V4L2_CID_LINK_FREQ, ARRAY_SIZE(link_freq_menu_items) - 1, 0, link_freq_menu_items); if (hi556->link_freq) hi556->link_freq->flags |= V4L2_CTRL_FLAG_READ_ONLY; hi556->pixel_rate = v4l2_ctrl_new_std (ctrl_hdlr, &hi556_ctrl_ops, V4L2_CID_PIXEL_RATE, 0, to_pixel_rate(HI556_LINK_FREQ_437MHZ_INDEX), 1, to_pixel_rate(HI556_LINK_FREQ_437MHZ_INDEX)); hi556->vblank = v4l2_ctrl_new_std(ctrl_hdlr, &hi556_ctrl_ops, V4L2_CID_VBLANK, hi556->cur_mode->fll_min - hi556->cur_mode->height, HI556_FLL_MAX - hi556->cur_mode->height, 1, hi556->cur_mode->fll_def - hi556->cur_mode->height); h_blank = hi556->cur_mode->llp - hi556->cur_mode->width; hi556->hblank = v4l2_ctrl_new_std(ctrl_hdlr, &hi556_ctrl_ops, V4L2_CID_HBLANK, h_blank, h_blank, 1, h_blank); if (hi556->hblank) hi556->hblank->flags |= V4L2_CTRL_FLAG_READ_ONLY; v4l2_ctrl_new_std(ctrl_hdlr, &hi556_ctrl_ops, V4L2_CID_ANALOGUE_GAIN, HI556_ANAL_GAIN_MIN, HI556_ANAL_GAIN_MAX, HI556_ANAL_GAIN_STEP, HI556_ANAL_GAIN_MIN); v4l2_ctrl_new_std(ctrl_hdlr, &hi556_ctrl_ops, V4L2_CID_DIGITAL_GAIN, HI556_DGTL_GAIN_MIN, HI556_DGTL_GAIN_MAX, HI556_DGTL_GAIN_STEP, HI556_DGTL_GAIN_DEFAULT); exposure_max = hi556->cur_mode->fll_def - HI556_EXPOSURE_MAX_MARGIN; hi556->exposure = v4l2_ctrl_new_std(ctrl_hdlr, &hi556_ctrl_ops, V4L2_CID_EXPOSURE, HI556_EXPOSURE_MIN, exposure_max, HI556_EXPOSURE_STEP, exposure_max); v4l2_ctrl_new_std_menu_items(ctrl_hdlr, &hi556_ctrl_ops, V4L2_CID_TEST_PATTERN, ARRAY_SIZE(hi556_test_pattern_menu) - 1, 0, 0, hi556_test_pattern_menu); if (ctrl_hdlr->error) return ctrl_hdlr->error; hi556->sd.ctrl_handler = ctrl_hdlr; return 0; } static void hi556_assign_pad_format(const struct hi556_mode *mode, struct v4l2_mbus_framefmt *fmt) { fmt->width = mode->width; fmt->height = mode->height; fmt->code = MEDIA_BUS_FMT_SGRBG10_1X10; fmt->field = V4L2_FIELD_NONE; } static int hi556_identify_module(struct hi556 *hi556) { struct i2c_client *client = v4l2_get_subdevdata(&hi556->sd); int ret; u32 val; if (hi556->identified) return 0; ret = hi556_read_reg(hi556, HI556_REG_CHIP_ID, HI556_REG_VALUE_16BIT, &val); if (ret) return ret; if (val != HI556_CHIP_ID) { dev_err(&client->dev, "chip id mismatch: %x!=%x", HI556_CHIP_ID, val); return -ENXIO; } hi556->identified = true; return 0; } static const struct v4l2_rect * __hi556_get_pad_crop(struct hi556 *hi556, struct v4l2_subdev_state *sd_state, unsigned int pad, enum v4l2_subdev_format_whence which) { switch (which) { case V4L2_SUBDEV_FORMAT_TRY: return v4l2_subdev_get_try_crop(&hi556->sd, sd_state, pad); case V4L2_SUBDEV_FORMAT_ACTIVE: return &hi556->cur_mode->crop; } return NULL; } static int hi556_get_selection(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_selection *sel) { switch (sel->target) { case V4L2_SEL_TGT_CROP: { struct hi556 *hi556 = to_hi556(sd); mutex_lock(&hi556->mutex); sel->r = *__hi556_get_pad_crop(hi556, sd_state, sel->pad, sel->which); mutex_unlock(&hi556->mutex); return 0; } case V4L2_SEL_TGT_NATIVE_SIZE: sel->r.top = 0; sel->r.left = 0; sel->r.width = HI556_NATIVE_WIDTH; sel->r.height = HI556_NATIVE_HEIGHT; return 0; case V4L2_SEL_TGT_CROP_DEFAULT: case V4L2_SEL_TGT_CROP_BOUNDS: sel->r.top = HI556_PIXEL_ARRAY_TOP; sel->r.left = HI556_PIXEL_ARRAY_LEFT; sel->r.width = HI556_PIXEL_ARRAY_WIDTH; sel->r.height = HI556_PIXEL_ARRAY_HEIGHT; return 0; } return -EINVAL; } static int hi556_start_streaming(struct hi556 *hi556) { struct i2c_client *client = v4l2_get_subdevdata(&hi556->sd); const struct hi556_reg_list *reg_list; int link_freq_index, ret; ret = hi556_identify_module(hi556); if (ret) return ret; link_freq_index = hi556->cur_mode->link_freq_index; reg_list = &link_freq_configs[link_freq_index].reg_list; ret = hi556_write_reg_list(hi556, reg_list); if (ret) { dev_err(&client->dev, "failed to set plls"); return ret; } reg_list = &hi556->cur_mode->reg_list; ret = hi556_write_reg_list(hi556, reg_list); if (ret) { dev_err(&client->dev, "failed to set mode"); return ret; } ret = __v4l2_ctrl_handler_setup(hi556->sd.ctrl_handler); if (ret) return ret; ret = hi556_write_reg(hi556, HI556_REG_MODE_SELECT, HI556_REG_VALUE_16BIT, HI556_MODE_STREAMING); if (ret) { dev_err(&client->dev, "failed to set stream"); return ret; } return 0; } static void hi556_stop_streaming(struct hi556 *hi556) { struct i2c_client *client = v4l2_get_subdevdata(&hi556->sd); if (hi556_write_reg(hi556, HI556_REG_MODE_SELECT, HI556_REG_VALUE_16BIT, HI556_MODE_STANDBY)) dev_err(&client->dev, "failed to set stream"); } static int hi556_set_stream(struct v4l2_subdev *sd, int enable) { struct hi556 *hi556 = to_hi556(sd); struct i2c_client *client = v4l2_get_subdevdata(sd); int ret = 0; if (hi556->streaming == enable) return 0; mutex_lock(&hi556->mutex); if (enable) { ret = pm_runtime_resume_and_get(&client->dev); if (ret < 0) { mutex_unlock(&hi556->mutex); return ret; } ret = hi556_start_streaming(hi556); if (ret) { enable = 0; hi556_stop_streaming(hi556); pm_runtime_put(&client->dev); } } else { hi556_stop_streaming(hi556); pm_runtime_put(&client->dev); } hi556->streaming = enable; mutex_unlock(&hi556->mutex); return ret; } static int __maybe_unused hi556_suspend(struct device *dev) { struct v4l2_subdev *sd = dev_get_drvdata(dev); struct hi556 *hi556 = to_hi556(sd); mutex_lock(&hi556->mutex); if (hi556->streaming) hi556_stop_streaming(hi556); mutex_unlock(&hi556->mutex); return 0; } static int __maybe_unused hi556_resume(struct device *dev) { struct v4l2_subdev *sd = dev_get_drvdata(dev); struct hi556 *hi556 = to_hi556(sd); int ret; mutex_lock(&hi556->mutex); if (hi556->streaming) { ret = hi556_start_streaming(hi556); if (ret) goto error; } mutex_unlock(&hi556->mutex); return 0; error: hi556_stop_streaming(hi556); hi556->streaming = 0; mutex_unlock(&hi556->mutex); return ret; } static int hi556_set_format(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *fmt) { struct hi556 *hi556 = to_hi556(sd); const struct hi556_mode *mode; s32 vblank_def, h_blank; mode = v4l2_find_nearest_size(supported_modes, ARRAY_SIZE(supported_modes), width, height, fmt->format.width, fmt->format.height); mutex_lock(&hi556->mutex); hi556_assign_pad_format(mode, &fmt->format); if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) { *v4l2_subdev_get_try_format(sd, sd_state, fmt->pad) = fmt->format; } else { hi556->cur_mode = mode; __v4l2_ctrl_s_ctrl(hi556->link_freq, mode->link_freq_index); __v4l2_ctrl_s_ctrl_int64(hi556->pixel_rate, to_pixel_rate(mode->link_freq_index)); /* Update limits and set FPS to default */ vblank_def = mode->fll_def - mode->height; __v4l2_ctrl_modify_range(hi556->vblank, mode->fll_min - mode->height, HI556_FLL_MAX - mode->height, 1, vblank_def); __v4l2_ctrl_s_ctrl(hi556->vblank, vblank_def); h_blank = hi556->cur_mode->llp - hi556->cur_mode->width; __v4l2_ctrl_modify_range(hi556->hblank, h_blank, h_blank, 1, h_blank); } mutex_unlock(&hi556->mutex); return 0; } static int hi556_get_format(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *fmt) { struct hi556 *hi556 = to_hi556(sd); mutex_lock(&hi556->mutex); if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) fmt->format = *v4l2_subdev_get_try_format(&hi556->sd, sd_state, fmt->pad); else hi556_assign_pad_format(hi556->cur_mode, &fmt->format); mutex_unlock(&hi556->mutex); return 0; } static int hi556_enum_mbus_code(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_mbus_code_enum *code) { if (code->index > 0) return -EINVAL; code->code = MEDIA_BUS_FMT_SGRBG10_1X10; return 0; } static int hi556_enum_frame_size(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_frame_size_enum *fse) { if (fse->index >= ARRAY_SIZE(supported_modes)) return -EINVAL; if (fse->code != MEDIA_BUS_FMT_SGRBG10_1X10) return -EINVAL; fse->min_width = supported_modes[fse->index].width; fse->max_width = fse->min_width; fse->min_height = supported_modes[fse->index].height; fse->max_height = fse->min_height; return 0; } static int hi556_open(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh) { struct hi556 *hi556 = to_hi556(sd); struct v4l2_rect *try_crop; mutex_lock(&hi556->mutex); hi556_assign_pad_format(&supported_modes[0], v4l2_subdev_get_try_format(sd, fh->state, 0)); /* Initialize try_crop rectangle. */ try_crop = v4l2_subdev_get_try_crop(sd, fh->state, 0); try_crop->top = HI556_PIXEL_ARRAY_TOP; try_crop->left = HI556_PIXEL_ARRAY_LEFT; try_crop->width = HI556_PIXEL_ARRAY_WIDTH; try_crop->height = HI556_PIXEL_ARRAY_HEIGHT; mutex_unlock(&hi556->mutex); return 0; } static const struct v4l2_subdev_video_ops hi556_video_ops = { .s_stream = hi556_set_stream, }; static const struct v4l2_subdev_pad_ops hi556_pad_ops = { .set_fmt = hi556_set_format, .get_fmt = hi556_get_format, .get_selection = hi556_get_selection, .enum_mbus_code = hi556_enum_mbus_code, .enum_frame_size = hi556_enum_frame_size, }; static const struct v4l2_subdev_ops hi556_subdev_ops = { .video = &hi556_video_ops, .pad = &hi556_pad_ops, }; static const struct media_entity_operations hi556_subdev_entity_ops = { .link_validate = v4l2_subdev_link_validate, }; static const struct v4l2_subdev_internal_ops hi556_internal_ops = { .open = hi556_open, }; static int hi556_check_hwcfg(struct device *dev) { struct fwnode_handle *ep; struct fwnode_handle *fwnode = dev_fwnode(dev); struct v4l2_fwnode_endpoint bus_cfg = { .bus_type = V4L2_MBUS_CSI2_DPHY }; u32 mclk; int ret = 0; unsigned int i, j; if (!fwnode) return -ENXIO; ret = fwnode_property_read_u32(fwnode, "clock-frequency", &mclk); if (ret) { dev_err(dev, "can't get clock frequency"); return ret; } if (mclk != HI556_MCLK) { dev_err(dev, "external clock %d is not supported", mclk); return -EINVAL; } ep = fwnode_graph_get_next_endpoint(fwnode, NULL); if (!ep) return -ENXIO; ret = v4l2_fwnode_endpoint_alloc_parse(ep, &bus_cfg); fwnode_handle_put(ep); if (ret) return ret; if (bus_cfg.bus.mipi_csi2.num_data_lanes != 2) { dev_err(dev, "number of CSI2 data lanes %d is not supported", bus_cfg.bus.mipi_csi2.num_data_lanes); ret = -EINVAL; goto check_hwcfg_error; } if (!bus_cfg.nr_of_link_frequencies) { dev_err(dev, "no link frequencies defined"); ret = -EINVAL; goto check_hwcfg_error; } for (i = 0; i < ARRAY_SIZE(link_freq_menu_items); i++) { for (j = 0; j < bus_cfg.nr_of_link_frequencies; j++) { if (link_freq_menu_items[i] == bus_cfg.link_frequencies[j]) break; } if (j == bus_cfg.nr_of_link_frequencies) { dev_err(dev, "no link frequency %lld supported", link_freq_menu_items[i]); ret = -EINVAL; goto check_hwcfg_error; } } check_hwcfg_error: v4l2_fwnode_endpoint_free(&bus_cfg); return ret; } static void hi556_remove(struct i2c_client *client) { struct v4l2_subdev *sd = i2c_get_clientdata(client); struct hi556 *hi556 = to_hi556(sd); v4l2_async_unregister_subdev(sd); media_entity_cleanup(&sd->entity); v4l2_ctrl_handler_free(sd->ctrl_handler); pm_runtime_disable(&client->dev); mutex_destroy(&hi556->mutex); } static int hi556_probe(struct i2c_client *client) { struct hi556 *hi556; bool full_power; int ret; ret = hi556_check_hwcfg(&client->dev); if (ret) { dev_err(&client->dev, "failed to check HW configuration: %d", ret); return ret; } hi556 = devm_kzalloc(&client->dev, sizeof(*hi556), GFP_KERNEL); if (!hi556) return -ENOMEM; v4l2_i2c_subdev_init(&hi556->sd, client, &hi556_subdev_ops); full_power = acpi_dev_state_d0(&client->dev); if (full_power) { ret = hi556_identify_module(hi556); if (ret) { dev_err(&client->dev, "failed to find sensor: %d", ret); return ret; } } mutex_init(&hi556->mutex); hi556->cur_mode = &supported_modes[0]; ret = hi556_init_controls(hi556); if (ret) { dev_err(&client->dev, "failed to init controls: %d", ret); goto probe_error_v4l2_ctrl_handler_free; } hi556->sd.internal_ops = &hi556_internal_ops; hi556->sd.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE; hi556->sd.entity.ops = &hi556_subdev_entity_ops; hi556->sd.entity.function = MEDIA_ENT_F_CAM_SENSOR; hi556->pad.flags = MEDIA_PAD_FL_SOURCE; ret = media_entity_pads_init(&hi556->sd.entity, 1, &hi556->pad); if (ret) { dev_err(&client->dev, "failed to init entity pads: %d", ret); goto probe_error_v4l2_ctrl_handler_free; } ret = v4l2_async_register_subdev_sensor(&hi556->sd); if (ret < 0) { dev_err(&client->dev, "failed to register V4L2 subdev: %d", ret); goto probe_error_media_entity_cleanup; } /* Set the device's state to active if it's in D0 state. */ if (full_power) pm_runtime_set_active(&client->dev); pm_runtime_enable(&client->dev); pm_runtime_idle(&client->dev); return 0; probe_error_media_entity_cleanup: media_entity_cleanup(&hi556->sd.entity); probe_error_v4l2_ctrl_handler_free: v4l2_ctrl_handler_free(hi556->sd.ctrl_handler); mutex_destroy(&hi556->mutex); return ret; } static const struct dev_pm_ops hi556_pm_ops = { SET_SYSTEM_SLEEP_PM_OPS(hi556_suspend, hi556_resume) }; #ifdef CONFIG_ACPI static const struct acpi_device_id hi556_acpi_ids[] = { {"INT3537"}, {} }; MODULE_DEVICE_TABLE(acpi, hi556_acpi_ids); #endif static struct i2c_driver hi556_i2c_driver = { .driver = { .name = "hi556", .pm = &hi556_pm_ops, .acpi_match_table = ACPI_PTR(hi556_acpi_ids), }, .probe = hi556_probe, .remove = hi556_remove, .flags = I2C_DRV_ACPI_WAIVE_D0_PROBE, }; module_i2c_driver(hi556_i2c_driver); MODULE_AUTHOR("Shawn Tu"); MODULE_DESCRIPTION("Hynix HI556 sensor driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/media/i2c/hi556.c
// SPDX-License-Identifier: GPL-2.0-only /* * et8ek8_driver.c * * Copyright (C) 2008 Nokia Corporation * * Contact: Sakari Ailus <[email protected]> * Tuukka Toivonen <[email protected]> * Pavel Machek <[email protected]> * * Based on code from Toni Leinonen <[email protected]>. * * This driver is based on the Micron MT9T012 camera imager driver * (C) Texas Instruments. */ #include <linux/clk.h> #include <linux/delay.h> #include <linux/gpio/consumer.h> #include <linux/i2c.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/mutex.h> #include <linux/regulator/consumer.h> #include <linux/slab.h> #include <linux/sort.h> #include <linux/v4l2-mediabus.h> #include <media/media-entity.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-device.h> #include <media/v4l2-subdev.h> #include "et8ek8_reg.h" #define ET8EK8_NAME "et8ek8" #define ET8EK8_PRIV_MEM_SIZE 128 #define ET8EK8_MAX_MSG 8 struct et8ek8_sensor { struct v4l2_subdev subdev; struct media_pad pad; struct v4l2_mbus_framefmt format; struct gpio_desc *reset; struct regulator *vana; struct clk *ext_clk; u32 xclk_freq; u16 version; struct v4l2_ctrl_handler ctrl_handler; struct v4l2_ctrl *exposure; struct v4l2_ctrl *pixel_rate; struct et8ek8_reglist *current_reglist; u8 priv_mem[ET8EK8_PRIV_MEM_SIZE]; struct mutex power_lock; int power_count; }; #define to_et8ek8_sensor(sd) container_of(sd, struct et8ek8_sensor, subdev) enum et8ek8_versions { ET8EK8_REV_1 = 0x0001, ET8EK8_REV_2, }; /* * This table describes what should be written to the sensor register * for each gain value. The gain(index in the table) is in terms of * 0.1EV, i.e. 10 indexes in the table give 2 time more gain [0] in * the *analog gain, [1] in the digital gain * * Analog gain [dB] = 20*log10(regvalue/32); 0x20..0x100 */ static struct et8ek8_gain { u16 analog; u16 digital; } const et8ek8_gain_table[] = { { 32, 0}, /* x1 */ { 34, 0}, { 37, 0}, { 39, 0}, { 42, 0}, { 45, 0}, { 49, 0}, { 52, 0}, { 56, 0}, { 60, 0}, { 64, 0}, /* x2 */ { 69, 0}, { 74, 0}, { 79, 0}, { 84, 0}, { 91, 0}, { 97, 0}, {104, 0}, {111, 0}, {119, 0}, {128, 0}, /* x4 */ {137, 0}, {147, 0}, {158, 0}, {169, 0}, {181, 0}, {194, 0}, {208, 0}, {223, 0}, {239, 0}, {256, 0}, /* x8 */ {256, 73}, {256, 152}, {256, 236}, {256, 327}, {256, 424}, {256, 528}, {256, 639}, {256, 758}, {256, 886}, {256, 1023}, /* x16 */ }; /* Register definitions */ #define REG_REVISION_NUMBER_L 0x1200 #define REG_REVISION_NUMBER_H 0x1201 #define PRIV_MEM_START_REG 0x0008 #define PRIV_MEM_WIN_SIZE 8 #define ET8EK8_I2C_DELAY 3 /* msec delay b/w accesses */ #define USE_CRC 1 /* * Register access helpers * * Read a 8/16/32-bit i2c register. The value is returned in 'val'. * Returns zero if successful, or non-zero otherwise. */ static int et8ek8_i2c_read_reg(struct i2c_client *client, u16 data_length, u16 reg, u32 *val) { int r; struct i2c_msg msg; unsigned char data[4]; if (!client->adapter) return -ENODEV; if (data_length != ET8EK8_REG_8BIT && data_length != ET8EK8_REG_16BIT) return -EINVAL; msg.addr = client->addr; msg.flags = 0; msg.len = 2; msg.buf = data; /* high byte goes out first */ data[0] = (u8) (reg >> 8); data[1] = (u8) (reg & 0xff); r = i2c_transfer(client->adapter, &msg, 1); if (r < 0) goto err; msg.len = data_length; msg.flags = I2C_M_RD; r = i2c_transfer(client->adapter, &msg, 1); if (r < 0) goto err; *val = 0; /* high byte comes first */ if (data_length == ET8EK8_REG_8BIT) *val = data[0]; else *val = (data[1] << 8) + data[0]; return 0; err: dev_err(&client->dev, "read from offset 0x%x error %d\n", reg, r); return r; } static void et8ek8_i2c_create_msg(struct i2c_client *client, u16 len, u16 reg, u32 val, struct i2c_msg *msg, unsigned char *buf) { msg->addr = client->addr; msg->flags = 0; /* Write */ msg->len = 2 + len; msg->buf = buf; /* high byte goes out first */ buf[0] = (u8) (reg >> 8); buf[1] = (u8) (reg & 0xff); switch (len) { case ET8EK8_REG_8BIT: buf[2] = (u8) (val) & 0xff; break; case ET8EK8_REG_16BIT: buf[2] = (u8) (val) & 0xff; buf[3] = (u8) (val >> 8) & 0xff; break; default: WARN_ONCE(1, ET8EK8_NAME ": %s: invalid message length.\n", __func__); } } /* * A buffered write method that puts the wanted register write * commands in smaller number of message lists and passes the lists to * the i2c framework */ static int et8ek8_i2c_buffered_write_regs(struct i2c_client *client, const struct et8ek8_reg *wnext, int cnt) { struct i2c_msg msg[ET8EK8_MAX_MSG]; unsigned char data[ET8EK8_MAX_MSG][6]; int wcnt = 0; u16 reg, data_length; u32 val; int rval; /* Create new write messages for all writes */ while (wcnt < cnt) { data_length = wnext->type; reg = wnext->reg; val = wnext->val; wnext++; et8ek8_i2c_create_msg(client, data_length, reg, val, &msg[wcnt], &data[wcnt][0]); /* Update write count */ wcnt++; if (wcnt < ET8EK8_MAX_MSG) continue; rval = i2c_transfer(client->adapter, msg, wcnt); if (rval < 0) return rval; cnt -= wcnt; wcnt = 0; } rval = i2c_transfer(client->adapter, msg, wcnt); return rval < 0 ? rval : 0; } /* * Write a list of registers to i2c device. * * The list of registers is terminated by ET8EK8_REG_TERM. * Returns zero if successful, or non-zero otherwise. */ static int et8ek8_i2c_write_regs(struct i2c_client *client, const struct et8ek8_reg *regs) { int r, cnt = 0; const struct et8ek8_reg *next; if (!client->adapter) return -ENODEV; if (!regs) return -EINVAL; /* Initialize list pointers to the start of the list */ next = regs; do { /* * We have to go through the list to figure out how * many regular writes we have in a row */ while (next->type != ET8EK8_REG_TERM && next->type != ET8EK8_REG_DELAY) { /* * Here we check that the actual length fields * are valid */ if (WARN(next->type != ET8EK8_REG_8BIT && next->type != ET8EK8_REG_16BIT, "Invalid type = %d", next->type)) { return -EINVAL; } /* * Increment count of successive writes and * read pointer */ cnt++; next++; } /* Now we start writing ... */ r = et8ek8_i2c_buffered_write_regs(client, regs, cnt); /* ... and then check that everything was OK */ if (r < 0) { dev_err(&client->dev, "i2c transfer error!\n"); return r; } /* * If we ran into a sleep statement when going through * the list, this is where we snooze for the required time */ if (next->type == ET8EK8_REG_DELAY) { msleep(next->val); /* * ZZZ ... * Update list pointers and cnt and start over ... */ next++; regs = next; cnt = 0; } } while (next->type != ET8EK8_REG_TERM); return 0; } /* * Write to a 8/16-bit register. * Returns zero if successful, or non-zero otherwise. */ static int et8ek8_i2c_write_reg(struct i2c_client *client, u16 data_length, u16 reg, u32 val) { int r; struct i2c_msg msg; unsigned char data[6]; if (!client->adapter) return -ENODEV; if (data_length != ET8EK8_REG_8BIT && data_length != ET8EK8_REG_16BIT) return -EINVAL; et8ek8_i2c_create_msg(client, data_length, reg, val, &msg, data); r = i2c_transfer(client->adapter, &msg, 1); if (r < 0) { dev_err(&client->dev, "wrote 0x%x to offset 0x%x error %d\n", val, reg, r); return r; } return 0; } static struct et8ek8_reglist *et8ek8_reglist_find_type( struct et8ek8_meta_reglist *meta, u16 type) { struct et8ek8_reglist **next = &meta->reglist[0].ptr; while (*next) { if ((*next)->type == type) return *next; next++; } return NULL; } static int et8ek8_i2c_reglist_find_write(struct i2c_client *client, struct et8ek8_meta_reglist *meta, u16 type) { struct et8ek8_reglist *reglist; reglist = et8ek8_reglist_find_type(meta, type); if (!reglist) return -EINVAL; return et8ek8_i2c_write_regs(client, reglist->regs); } static struct et8ek8_reglist **et8ek8_reglist_first( struct et8ek8_meta_reglist *meta) { return &meta->reglist[0].ptr; } static void et8ek8_reglist_to_mbus(const struct et8ek8_reglist *reglist, struct v4l2_mbus_framefmt *fmt) { fmt->width = reglist->mode.window_width; fmt->height = reglist->mode.window_height; fmt->code = reglist->mode.bus_format; } static struct et8ek8_reglist *et8ek8_reglist_find_mode_fmt( struct et8ek8_meta_reglist *meta, struct v4l2_mbus_framefmt *fmt) { struct et8ek8_reglist **list = et8ek8_reglist_first(meta); struct et8ek8_reglist *best_match = NULL; struct et8ek8_reglist *best_other = NULL; struct v4l2_mbus_framefmt format; unsigned int max_dist_match = (unsigned int)-1; unsigned int max_dist_other = (unsigned int)-1; /* * Find the mode with the closest image size. The distance between * image sizes is the size in pixels of the non-overlapping regions * between the requested size and the frame-specified size. * * Store both the closest mode that matches the requested format, and * the closest mode for all other formats. The best match is returned * if found, otherwise the best mode with a non-matching format is * returned. */ for (; *list; list++) { unsigned int dist; if ((*list)->type != ET8EK8_REGLIST_MODE) continue; et8ek8_reglist_to_mbus(*list, &format); dist = min(fmt->width, format.width) * min(fmt->height, format.height); dist = format.width * format.height + fmt->width * fmt->height - 2 * dist; if (fmt->code == format.code) { if (dist < max_dist_match || !best_match) { best_match = *list; max_dist_match = dist; } } else { if (dist < max_dist_other || !best_other) { best_other = *list; max_dist_other = dist; } } } return best_match ? best_match : best_other; } #define TIMEPERFRAME_AVG_FPS(t) \ (((t).denominator + ((t).numerator >> 1)) / (t).numerator) static struct et8ek8_reglist *et8ek8_reglist_find_mode_ival( struct et8ek8_meta_reglist *meta, struct et8ek8_reglist *current_reglist, struct v4l2_fract *timeperframe) { int fps = TIMEPERFRAME_AVG_FPS(*timeperframe); struct et8ek8_reglist **list = et8ek8_reglist_first(meta); struct et8ek8_mode *current_mode = &current_reglist->mode; for (; *list; list++) { struct et8ek8_mode *mode = &(*list)->mode; if ((*list)->type != ET8EK8_REGLIST_MODE) continue; if (mode->window_width != current_mode->window_width || mode->window_height != current_mode->window_height) continue; if (TIMEPERFRAME_AVG_FPS(mode->timeperframe) == fps) return *list; } return NULL; } static int et8ek8_reglist_cmp(const void *a, const void *b) { const struct et8ek8_reglist **list1 = (const struct et8ek8_reglist **)a, **list2 = (const struct et8ek8_reglist **)b; /* Put real modes in the beginning. */ if ((*list1)->type == ET8EK8_REGLIST_MODE && (*list2)->type != ET8EK8_REGLIST_MODE) return -1; if ((*list1)->type != ET8EK8_REGLIST_MODE && (*list2)->type == ET8EK8_REGLIST_MODE) return 1; /* Descending width. */ if ((*list1)->mode.window_width > (*list2)->mode.window_width) return -1; if ((*list1)->mode.window_width < (*list2)->mode.window_width) return 1; if ((*list1)->mode.window_height > (*list2)->mode.window_height) return -1; if ((*list1)->mode.window_height < (*list2)->mode.window_height) return 1; return 0; } static int et8ek8_reglist_import(struct i2c_client *client, struct et8ek8_meta_reglist *meta) { int nlists = 0, i; dev_info(&client->dev, "meta_reglist version %s\n", meta->version); while (meta->reglist[nlists].ptr) nlists++; if (!nlists) return -EINVAL; sort(&meta->reglist[0].ptr, nlists, sizeof(meta->reglist[0].ptr), et8ek8_reglist_cmp, NULL); i = nlists; nlists = 0; while (i--) { struct et8ek8_reglist *list; list = meta->reglist[nlists].ptr; dev_dbg(&client->dev, "%s: type %d\tw %d\th %d\tfmt %x\tival %d/%d\tptr %p\n", __func__, list->type, list->mode.window_width, list->mode.window_height, list->mode.bus_format, list->mode.timeperframe.numerator, list->mode.timeperframe.denominator, (void *)meta->reglist[nlists].ptr); nlists++; } return 0; } /* Called to change the V4L2 gain control value. This function * rounds and clamps the given value and updates the V4L2 control value. * If power is on, also updates the sensor analog and digital gains. * gain is in 0.1 EV (exposure value) units. */ static int et8ek8_set_gain(struct et8ek8_sensor *sensor, s32 gain) { struct i2c_client *client = v4l2_get_subdevdata(&sensor->subdev); struct et8ek8_gain new; int r; new = et8ek8_gain_table[gain]; /* FIXME: optimise I2C writes! */ r = et8ek8_i2c_write_reg(client, ET8EK8_REG_8BIT, 0x124a, new.analog >> 8); if (r) return r; r = et8ek8_i2c_write_reg(client, ET8EK8_REG_8BIT, 0x1249, new.analog & 0xff); if (r) return r; r = et8ek8_i2c_write_reg(client, ET8EK8_REG_8BIT, 0x124d, new.digital >> 8); if (r) return r; r = et8ek8_i2c_write_reg(client, ET8EK8_REG_8BIT, 0x124c, new.digital & 0xff); return r; } static int et8ek8_set_test_pattern(struct et8ek8_sensor *sensor, s32 mode) { struct i2c_client *client = v4l2_get_subdevdata(&sensor->subdev); int cbh_mode, cbv_mode, tp_mode, din_sw, r1420, rval; /* Values for normal mode */ cbh_mode = 0; cbv_mode = 0; tp_mode = 0; din_sw = 0x00; r1420 = 0xF0; if (mode) { /* Test pattern mode */ if (mode < 5) { cbh_mode = 1; cbv_mode = 1; tp_mode = mode + 3; } else { cbh_mode = 0; cbv_mode = 0; tp_mode = mode - 4 + 3; } din_sw = 0x01; r1420 = 0xE0; } rval = et8ek8_i2c_write_reg(client, ET8EK8_REG_8BIT, 0x111B, tp_mode << 4); if (rval) return rval; rval = et8ek8_i2c_write_reg(client, ET8EK8_REG_8BIT, 0x1121, cbh_mode << 7); if (rval) return rval; rval = et8ek8_i2c_write_reg(client, ET8EK8_REG_8BIT, 0x1124, cbv_mode << 7); if (rval) return rval; rval = et8ek8_i2c_write_reg(client, ET8EK8_REG_8BIT, 0x112C, din_sw); if (rval) return rval; return et8ek8_i2c_write_reg(client, ET8EK8_REG_8BIT, 0x1420, r1420); } /* ----------------------------------------------------------------------------- * V4L2 controls */ static int et8ek8_set_ctrl(struct v4l2_ctrl *ctrl) { struct et8ek8_sensor *sensor = container_of(ctrl->handler, struct et8ek8_sensor, ctrl_handler); switch (ctrl->id) { case V4L2_CID_GAIN: return et8ek8_set_gain(sensor, ctrl->val); case V4L2_CID_EXPOSURE: { struct i2c_client *client = v4l2_get_subdevdata(&sensor->subdev); return et8ek8_i2c_write_reg(client, ET8EK8_REG_16BIT, 0x1243, ctrl->val); } case V4L2_CID_TEST_PATTERN: return et8ek8_set_test_pattern(sensor, ctrl->val); case V4L2_CID_PIXEL_RATE: return 0; default: return -EINVAL; } } static const struct v4l2_ctrl_ops et8ek8_ctrl_ops = { .s_ctrl = et8ek8_set_ctrl, }; static const char * const et8ek8_test_pattern_menu[] = { "Normal", "Vertical colorbar", "Horizontal colorbar", "Scale", "Ramp", "Small vertical colorbar", "Small horizontal colorbar", "Small scale", "Small ramp", }; static int et8ek8_init_controls(struct et8ek8_sensor *sensor) { s32 max_rows; v4l2_ctrl_handler_init(&sensor->ctrl_handler, 4); /* V4L2_CID_GAIN */ v4l2_ctrl_new_std(&sensor->ctrl_handler, &et8ek8_ctrl_ops, V4L2_CID_GAIN, 0, ARRAY_SIZE(et8ek8_gain_table) - 1, 1, 0); max_rows = sensor->current_reglist->mode.max_exp; { u32 min = 1, max = max_rows; sensor->exposure = v4l2_ctrl_new_std(&sensor->ctrl_handler, &et8ek8_ctrl_ops, V4L2_CID_EXPOSURE, min, max, min, max); } /* V4L2_CID_PIXEL_RATE */ sensor->pixel_rate = v4l2_ctrl_new_std(&sensor->ctrl_handler, &et8ek8_ctrl_ops, V4L2_CID_PIXEL_RATE, 1, INT_MAX, 1, 1); /* V4L2_CID_TEST_PATTERN */ v4l2_ctrl_new_std_menu_items(&sensor->ctrl_handler, &et8ek8_ctrl_ops, V4L2_CID_TEST_PATTERN, ARRAY_SIZE(et8ek8_test_pattern_menu) - 1, 0, 0, et8ek8_test_pattern_menu); if (sensor->ctrl_handler.error) return sensor->ctrl_handler.error; sensor->subdev.ctrl_handler = &sensor->ctrl_handler; return 0; } static void et8ek8_update_controls(struct et8ek8_sensor *sensor) { struct v4l2_ctrl *ctrl; struct et8ek8_mode *mode = &sensor->current_reglist->mode; u32 min, max, pixel_rate; static const int S = 8; ctrl = sensor->exposure; min = 1; max = mode->max_exp; /* * Calculate average pixel clock per line. Assume buffers can spread * the data over horizontal blanking time. Rounding upwards. * Formula taken from stock Nokia N900 kernel. */ pixel_rate = ((mode->pixel_clock + (1 << S) - 1) >> S) + mode->width; pixel_rate = mode->window_width * (pixel_rate - 1) / mode->width; __v4l2_ctrl_modify_range(ctrl, min, max, min, max); __v4l2_ctrl_s_ctrl_int64(sensor->pixel_rate, pixel_rate << S); } static int et8ek8_configure(struct et8ek8_sensor *sensor) { struct v4l2_subdev *subdev = &sensor->subdev; struct i2c_client *client = v4l2_get_subdevdata(subdev); int rval; rval = et8ek8_i2c_write_regs(client, sensor->current_reglist->regs); if (rval) goto fail; /* Controls set while the power to the sensor is turned off are saved * but not applied to the hardware. Now that we're about to start * streaming apply all the current values to the hardware. */ rval = v4l2_ctrl_handler_setup(&sensor->ctrl_handler); if (rval) goto fail; return 0; fail: dev_err(&client->dev, "sensor configuration failed\n"); return rval; } static int et8ek8_stream_on(struct et8ek8_sensor *sensor) { struct i2c_client *client = v4l2_get_subdevdata(&sensor->subdev); return et8ek8_i2c_write_reg(client, ET8EK8_REG_8BIT, 0x1252, 0xb0); } static int et8ek8_stream_off(struct et8ek8_sensor *sensor) { struct i2c_client *client = v4l2_get_subdevdata(&sensor->subdev); return et8ek8_i2c_write_reg(client, ET8EK8_REG_8BIT, 0x1252, 0x30); } static int et8ek8_s_stream(struct v4l2_subdev *subdev, int streaming) { struct et8ek8_sensor *sensor = to_et8ek8_sensor(subdev); int ret; if (!streaming) return et8ek8_stream_off(sensor); ret = et8ek8_configure(sensor); if (ret < 0) return ret; return et8ek8_stream_on(sensor); } /* -------------------------------------------------------------------------- * V4L2 subdev operations */ static int et8ek8_power_off(struct et8ek8_sensor *sensor) { gpiod_set_value(sensor->reset, 0); udelay(1); clk_disable_unprepare(sensor->ext_clk); return regulator_disable(sensor->vana); } static int et8ek8_power_on(struct et8ek8_sensor *sensor) { struct v4l2_subdev *subdev = &sensor->subdev; struct i2c_client *client = v4l2_get_subdevdata(subdev); unsigned int xclk_freq; int val, rval; rval = regulator_enable(sensor->vana); if (rval) { dev_err(&client->dev, "failed to enable vana regulator\n"); return rval; } if (sensor->current_reglist) xclk_freq = sensor->current_reglist->mode.ext_clock; else xclk_freq = sensor->xclk_freq; rval = clk_set_rate(sensor->ext_clk, xclk_freq); if (rval < 0) { dev_err(&client->dev, "unable to set extclk clock freq to %u\n", xclk_freq); goto out; } rval = clk_prepare_enable(sensor->ext_clk); if (rval < 0) { dev_err(&client->dev, "failed to enable extclk\n"); goto out; } if (rval) goto out; udelay(10); /* I wish this is a good value */ gpiod_set_value(sensor->reset, 1); msleep(5000 * 1000 / xclk_freq + 1); /* Wait 5000 cycles */ rval = et8ek8_i2c_reglist_find_write(client, &meta_reglist, ET8EK8_REGLIST_POWERON); if (rval) goto out; #ifdef USE_CRC rval = et8ek8_i2c_read_reg(client, ET8EK8_REG_8BIT, 0x1263, &val); if (rval) goto out; #if USE_CRC /* TODO get crc setting from DT */ val |= BIT(4); #else val &= ~BIT(4); #endif rval = et8ek8_i2c_write_reg(client, ET8EK8_REG_8BIT, 0x1263, val); if (rval) goto out; #endif out: if (rval) et8ek8_power_off(sensor); return rval; } /* -------------------------------------------------------------------------- * V4L2 subdev video operations */ #define MAX_FMTS 4 static int et8ek8_enum_mbus_code(struct v4l2_subdev *subdev, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_mbus_code_enum *code) { struct et8ek8_reglist **list = et8ek8_reglist_first(&meta_reglist); u32 pixelformat[MAX_FMTS]; int npixelformat = 0; if (code->index >= MAX_FMTS) return -EINVAL; for (; *list; list++) { struct et8ek8_mode *mode = &(*list)->mode; int i; if ((*list)->type != ET8EK8_REGLIST_MODE) continue; for (i = 0; i < npixelformat; i++) { if (pixelformat[i] == mode->bus_format) break; } if (i != npixelformat) continue; if (code->index == npixelformat) { code->code = mode->bus_format; return 0; } pixelformat[npixelformat] = mode->bus_format; npixelformat++; } return -EINVAL; } static int et8ek8_enum_frame_size(struct v4l2_subdev *subdev, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_frame_size_enum *fse) { struct et8ek8_reglist **list = et8ek8_reglist_first(&meta_reglist); struct v4l2_mbus_framefmt format; int cmp_width = INT_MAX; int cmp_height = INT_MAX; int index = fse->index; for (; *list; list++) { if ((*list)->type != ET8EK8_REGLIST_MODE) continue; et8ek8_reglist_to_mbus(*list, &format); if (fse->code != format.code) continue; /* Assume that the modes are grouped by frame size. */ if (format.width == cmp_width && format.height == cmp_height) continue; cmp_width = format.width; cmp_height = format.height; if (index-- == 0) { fse->min_width = format.width; fse->min_height = format.height; fse->max_width = format.width; fse->max_height = format.height; return 0; } } return -EINVAL; } static int et8ek8_enum_frame_ival(struct v4l2_subdev *subdev, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_frame_interval_enum *fie) { struct et8ek8_reglist **list = et8ek8_reglist_first(&meta_reglist); struct v4l2_mbus_framefmt format; int index = fie->index; for (; *list; list++) { struct et8ek8_mode *mode = &(*list)->mode; if ((*list)->type != ET8EK8_REGLIST_MODE) continue; et8ek8_reglist_to_mbus(*list, &format); if (fie->code != format.code) continue; if (fie->width != format.width || fie->height != format.height) continue; if (index-- == 0) { fie->interval = mode->timeperframe; return 0; } } return -EINVAL; } static struct v4l2_mbus_framefmt * __et8ek8_get_pad_format(struct et8ek8_sensor *sensor, struct v4l2_subdev_state *sd_state, unsigned int pad, enum v4l2_subdev_format_whence which) { switch (which) { case V4L2_SUBDEV_FORMAT_TRY: return v4l2_subdev_get_try_format(&sensor->subdev, sd_state, pad); case V4L2_SUBDEV_FORMAT_ACTIVE: return &sensor->format; default: return NULL; } } static int et8ek8_get_pad_format(struct v4l2_subdev *subdev, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *fmt) { struct et8ek8_sensor *sensor = to_et8ek8_sensor(subdev); struct v4l2_mbus_framefmt *format; format = __et8ek8_get_pad_format(sensor, sd_state, fmt->pad, fmt->which); if (!format) return -EINVAL; fmt->format = *format; return 0; } static int et8ek8_set_pad_format(struct v4l2_subdev *subdev, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *fmt) { struct et8ek8_sensor *sensor = to_et8ek8_sensor(subdev); struct v4l2_mbus_framefmt *format; struct et8ek8_reglist *reglist; format = __et8ek8_get_pad_format(sensor, sd_state, fmt->pad, fmt->which); if (!format) return -EINVAL; reglist = et8ek8_reglist_find_mode_fmt(&meta_reglist, &fmt->format); et8ek8_reglist_to_mbus(reglist, &fmt->format); *format = fmt->format; if (fmt->which == V4L2_SUBDEV_FORMAT_ACTIVE) { sensor->current_reglist = reglist; et8ek8_update_controls(sensor); } return 0; } static int et8ek8_get_frame_interval(struct v4l2_subdev *subdev, struct v4l2_subdev_frame_interval *fi) { struct et8ek8_sensor *sensor = to_et8ek8_sensor(subdev); memset(fi, 0, sizeof(*fi)); fi->interval = sensor->current_reglist->mode.timeperframe; return 0; } static int et8ek8_set_frame_interval(struct v4l2_subdev *subdev, struct v4l2_subdev_frame_interval *fi) { struct et8ek8_sensor *sensor = to_et8ek8_sensor(subdev); struct et8ek8_reglist *reglist; reglist = et8ek8_reglist_find_mode_ival(&meta_reglist, sensor->current_reglist, &fi->interval); if (!reglist) return -EINVAL; if (sensor->current_reglist->mode.ext_clock != reglist->mode.ext_clock) return -EINVAL; sensor->current_reglist = reglist; et8ek8_update_controls(sensor); return 0; } static int et8ek8_g_priv_mem(struct v4l2_subdev *subdev) { struct et8ek8_sensor *sensor = to_et8ek8_sensor(subdev); struct i2c_client *client = v4l2_get_subdevdata(subdev); unsigned int length = ET8EK8_PRIV_MEM_SIZE; unsigned int offset = 0; u8 *ptr = sensor->priv_mem; int rval = 0; /* Read the EEPROM window-by-window, each window 8 bytes */ do { u8 buffer[PRIV_MEM_WIN_SIZE]; struct i2c_msg msg; int bytes, i; int ofs; /* Set the current window */ rval = et8ek8_i2c_write_reg(client, ET8EK8_REG_8BIT, 0x0001, 0xe0 | (offset >> 3)); if (rval < 0) return rval; /* Wait for status bit */ for (i = 0; i < 1000; ++i) { u32 status; rval = et8ek8_i2c_read_reg(client, ET8EK8_REG_8BIT, 0x0003, &status); if (rval < 0) return rval; if (!(status & 0x08)) break; usleep_range(1000, 2000); } if (i == 1000) return -EIO; /* Read window, 8 bytes at once, and copy to user space */ ofs = offset & 0x07; /* Offset within this window */ bytes = length + ofs > 8 ? 8-ofs : length; msg.addr = client->addr; msg.flags = 0; msg.len = 2; msg.buf = buffer; ofs += PRIV_MEM_START_REG; buffer[0] = (u8)(ofs >> 8); buffer[1] = (u8)(ofs & 0xFF); rval = i2c_transfer(client->adapter, &msg, 1); if (rval < 0) return rval; mdelay(ET8EK8_I2C_DELAY); msg.addr = client->addr; msg.len = bytes; msg.flags = I2C_M_RD; msg.buf = buffer; memset(buffer, 0, sizeof(buffer)); rval = i2c_transfer(client->adapter, &msg, 1); if (rval < 0) return rval; rval = 0; memcpy(ptr, buffer, bytes); length -= bytes; offset += bytes; ptr += bytes; } while (length > 0); return rval; } static int et8ek8_dev_init(struct v4l2_subdev *subdev) { struct et8ek8_sensor *sensor = to_et8ek8_sensor(subdev); struct i2c_client *client = v4l2_get_subdevdata(subdev); int rval, rev_l, rev_h; rval = et8ek8_power_on(sensor); if (rval) { dev_err(&client->dev, "could not power on\n"); return rval; } rval = et8ek8_i2c_read_reg(client, ET8EK8_REG_8BIT, REG_REVISION_NUMBER_L, &rev_l); if (!rval) rval = et8ek8_i2c_read_reg(client, ET8EK8_REG_8BIT, REG_REVISION_NUMBER_H, &rev_h); if (rval) { dev_err(&client->dev, "no et8ek8 sensor detected\n"); goto out_poweroff; } sensor->version = (rev_h << 8) + rev_l; if (sensor->version != ET8EK8_REV_1 && sensor->version != ET8EK8_REV_2) dev_info(&client->dev, "unknown version 0x%x detected, continuing anyway\n", sensor->version); rval = et8ek8_reglist_import(client, &meta_reglist); if (rval) { dev_err(&client->dev, "invalid register list %s, import failed\n", ET8EK8_NAME); goto out_poweroff; } sensor->current_reglist = et8ek8_reglist_find_type(&meta_reglist, ET8EK8_REGLIST_MODE); if (!sensor->current_reglist) { dev_err(&client->dev, "invalid register list %s, no mode found\n", ET8EK8_NAME); rval = -ENODEV; goto out_poweroff; } et8ek8_reglist_to_mbus(sensor->current_reglist, &sensor->format); rval = et8ek8_i2c_reglist_find_write(client, &meta_reglist, ET8EK8_REGLIST_POWERON); if (rval) { dev_err(&client->dev, "invalid register list %s, no POWERON mode found\n", ET8EK8_NAME); goto out_poweroff; } rval = et8ek8_stream_on(sensor); /* Needed to be able to read EEPROM */ if (rval) goto out_poweroff; rval = et8ek8_g_priv_mem(subdev); if (rval) dev_warn(&client->dev, "can not read OTP (EEPROM) memory from sensor\n"); rval = et8ek8_stream_off(sensor); if (rval) goto out_poweroff; rval = et8ek8_power_off(sensor); if (rval) goto out_poweroff; return 0; out_poweroff: et8ek8_power_off(sensor); return rval; } /* -------------------------------------------------------------------------- * sysfs attributes */ static ssize_t priv_mem_show(struct device *dev, struct device_attribute *attr, char *buf) { struct v4l2_subdev *subdev = dev_get_drvdata(dev); struct et8ek8_sensor *sensor = to_et8ek8_sensor(subdev); #if PAGE_SIZE < ET8EK8_PRIV_MEM_SIZE #error PAGE_SIZE too small! #endif memcpy(buf, sensor->priv_mem, ET8EK8_PRIV_MEM_SIZE); return ET8EK8_PRIV_MEM_SIZE; } static DEVICE_ATTR_RO(priv_mem); /* -------------------------------------------------------------------------- * V4L2 subdev core operations */ static int et8ek8_registered(struct v4l2_subdev *subdev) { struct et8ek8_sensor *sensor = to_et8ek8_sensor(subdev); struct i2c_client *client = v4l2_get_subdevdata(subdev); int rval; dev_dbg(&client->dev, "registered!"); rval = device_create_file(&client->dev, &dev_attr_priv_mem); if (rval) { dev_err(&client->dev, "could not register sysfs entry\n"); return rval; } rval = et8ek8_dev_init(subdev); if (rval) goto err_file; rval = et8ek8_init_controls(sensor); if (rval) { dev_err(&client->dev, "controls initialization failed\n"); goto err_file; } __et8ek8_get_pad_format(sensor, NULL, 0, V4L2_SUBDEV_FORMAT_ACTIVE); return 0; err_file: device_remove_file(&client->dev, &dev_attr_priv_mem); return rval; } static int __et8ek8_set_power(struct et8ek8_sensor *sensor, bool on) { return on ? et8ek8_power_on(sensor) : et8ek8_power_off(sensor); } static int et8ek8_set_power(struct v4l2_subdev *subdev, int on) { struct et8ek8_sensor *sensor = to_et8ek8_sensor(subdev); int ret = 0; mutex_lock(&sensor->power_lock); /* If the power count is modified from 0 to != 0 or from != 0 to 0, * update the power state. */ if (sensor->power_count == !on) { ret = __et8ek8_set_power(sensor, !!on); if (ret < 0) goto done; } /* Update the power count. */ sensor->power_count += on ? 1 : -1; WARN_ON(sensor->power_count < 0); done: mutex_unlock(&sensor->power_lock); return ret; } static int et8ek8_open(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh) { struct et8ek8_sensor *sensor = to_et8ek8_sensor(sd); struct v4l2_mbus_framefmt *format; struct et8ek8_reglist *reglist; reglist = et8ek8_reglist_find_type(&meta_reglist, ET8EK8_REGLIST_MODE); format = __et8ek8_get_pad_format(sensor, fh->state, 0, V4L2_SUBDEV_FORMAT_TRY); et8ek8_reglist_to_mbus(reglist, format); return et8ek8_set_power(sd, true); } static int et8ek8_close(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh) { return et8ek8_set_power(sd, false); } static const struct v4l2_subdev_video_ops et8ek8_video_ops = { .s_stream = et8ek8_s_stream, .g_frame_interval = et8ek8_get_frame_interval, .s_frame_interval = et8ek8_set_frame_interval, }; static const struct v4l2_subdev_core_ops et8ek8_core_ops = { .s_power = et8ek8_set_power, }; static const struct v4l2_subdev_pad_ops et8ek8_pad_ops = { .enum_mbus_code = et8ek8_enum_mbus_code, .enum_frame_size = et8ek8_enum_frame_size, .enum_frame_interval = et8ek8_enum_frame_ival, .get_fmt = et8ek8_get_pad_format, .set_fmt = et8ek8_set_pad_format, }; static const struct v4l2_subdev_ops et8ek8_ops = { .core = &et8ek8_core_ops, .video = &et8ek8_video_ops, .pad = &et8ek8_pad_ops, }; static const struct v4l2_subdev_internal_ops et8ek8_internal_ops = { .registered = et8ek8_registered, .open = et8ek8_open, .close = et8ek8_close, }; /* -------------------------------------------------------------------------- * I2C driver */ static int __maybe_unused et8ek8_suspend(struct device *dev) { struct v4l2_subdev *subdev = dev_get_drvdata(dev); struct et8ek8_sensor *sensor = to_et8ek8_sensor(subdev); if (!sensor->power_count) return 0; return __et8ek8_set_power(sensor, false); } static int __maybe_unused et8ek8_resume(struct device *dev) { struct v4l2_subdev *subdev = dev_get_drvdata(dev); struct et8ek8_sensor *sensor = to_et8ek8_sensor(subdev); if (!sensor->power_count) return 0; return __et8ek8_set_power(sensor, true); } static int et8ek8_probe(struct i2c_client *client) { struct et8ek8_sensor *sensor; struct device *dev = &client->dev; int ret; sensor = devm_kzalloc(&client->dev, sizeof(*sensor), GFP_KERNEL); if (!sensor) return -ENOMEM; sensor->reset = devm_gpiod_get(dev, "reset", GPIOD_OUT_LOW); if (IS_ERR(sensor->reset)) { dev_dbg(&client->dev, "could not request reset gpio\n"); return PTR_ERR(sensor->reset); } sensor->vana = devm_regulator_get(dev, "vana"); if (IS_ERR(sensor->vana)) { dev_err(&client->dev, "could not get regulator for vana\n"); return PTR_ERR(sensor->vana); } sensor->ext_clk = devm_clk_get(dev, NULL); if (IS_ERR(sensor->ext_clk)) { dev_err(&client->dev, "could not get clock\n"); return PTR_ERR(sensor->ext_clk); } ret = of_property_read_u32(dev->of_node, "clock-frequency", &sensor->xclk_freq); if (ret) { dev_warn(dev, "can't get clock-frequency\n"); return ret; } mutex_init(&sensor->power_lock); v4l2_i2c_subdev_init(&sensor->subdev, client, &et8ek8_ops); sensor->subdev.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE; sensor->subdev.internal_ops = &et8ek8_internal_ops; sensor->subdev.entity.function = MEDIA_ENT_F_CAM_SENSOR; sensor->pad.flags = MEDIA_PAD_FL_SOURCE; ret = media_entity_pads_init(&sensor->subdev.entity, 1, &sensor->pad); if (ret < 0) { dev_err(&client->dev, "media entity init failed!\n"); goto err_mutex; } ret = v4l2_async_register_subdev_sensor(&sensor->subdev); if (ret < 0) goto err_entity; dev_dbg(dev, "initialized!\n"); return 0; err_entity: media_entity_cleanup(&sensor->subdev.entity); err_mutex: mutex_destroy(&sensor->power_lock); return ret; } static void __exit et8ek8_remove(struct i2c_client *client) { struct v4l2_subdev *subdev = i2c_get_clientdata(client); struct et8ek8_sensor *sensor = to_et8ek8_sensor(subdev); if (sensor->power_count) { WARN_ON(1); et8ek8_power_off(sensor); sensor->power_count = 0; } v4l2_device_unregister_subdev(&sensor->subdev); device_remove_file(&client->dev, &dev_attr_priv_mem); v4l2_ctrl_handler_free(&sensor->ctrl_handler); v4l2_async_unregister_subdev(&sensor->subdev); media_entity_cleanup(&sensor->subdev.entity); mutex_destroy(&sensor->power_lock); } static const struct of_device_id et8ek8_of_table[] = { { .compatible = "toshiba,et8ek8" }, { }, }; MODULE_DEVICE_TABLE(of, et8ek8_of_table); static const struct i2c_device_id et8ek8_id_table[] = { { ET8EK8_NAME, 0 }, { } }; MODULE_DEVICE_TABLE(i2c, et8ek8_id_table); static const struct dev_pm_ops et8ek8_pm_ops = { SET_SYSTEM_SLEEP_PM_OPS(et8ek8_suspend, et8ek8_resume) }; static struct i2c_driver et8ek8_i2c_driver = { .driver = { .name = ET8EK8_NAME, .pm = &et8ek8_pm_ops, .of_match_table = et8ek8_of_table, }, .probe = et8ek8_probe, .remove = __exit_p(et8ek8_remove), .id_table = et8ek8_id_table, }; module_i2c_driver(et8ek8_i2c_driver); MODULE_AUTHOR("Sakari Ailus <[email protected]>, Pavel Machek <[email protected]"); MODULE_DESCRIPTION("Toshiba ET8EK8 camera sensor driver"); MODULE_LICENSE("GPL");
linux-master
drivers/media/i2c/et8ek8/et8ek8_driver.c
// SPDX-License-Identifier: GPL-2.0-only /* * et8ek8_mode.c * * Copyright (C) 2008 Nokia Corporation * * Contact: Sakari Ailus <[email protected]> * Tuukka Toivonen <[email protected]> */ #include "et8ek8_reg.h" /* * Stingray sensor mode settings for Scooby */ /* Mode1_poweron_Mode2_16VGA_2592x1968_12.07fps */ static struct et8ek8_reglist mode1_poweron_mode2_16vga_2592x1968_12_07fps = { /* (without the +1) * SPCK = 80 MHz * CCP2 = 640 MHz * VCO = 640 MHz * VCOUNT = 84 (2016) * HCOUNT = 137 (3288) * CKREF_DIV = 2 * CKVAR_DIV = 200 * VCO_DIV = 0 * SPCK_DIV = 7 * MRCK_DIV = 7 * LVDSCK_DIV = 0 */ .type = ET8EK8_REGLIST_POWERON, .mode = { .sensor_width = 2592, .sensor_height = 1968, .sensor_window_origin_x = 0, .sensor_window_origin_y = 0, .sensor_window_width = 2592, .sensor_window_height = 1968, .width = 3288, .height = 2016, .window_origin_x = 0, .window_origin_y = 0, .window_width = 2592, .window_height = 1968, .pixel_clock = 80000000, .ext_clock = 9600000, .timeperframe = { .numerator = 100, .denominator = 1207 }, .max_exp = 2012, /* .max_gain = 0, */ .bus_format = MEDIA_BUS_FMT_SGRBG10_1X10, .sensitivity = 65536 }, .regs = { /* Need to set firstly */ { ET8EK8_REG_8BIT, 0x126C, 0xCC }, /* Strobe and Data of CCP2 delay are minimized. */ { ET8EK8_REG_8BIT, 0x1269, 0x00 }, /* Refined value of Min H_COUNT */ { ET8EK8_REG_8BIT, 0x1220, 0x89 }, /* Frequency of SPCK setting (SPCK=MRCK) */ { ET8EK8_REG_8BIT, 0x123A, 0x07 }, { ET8EK8_REG_8BIT, 0x1241, 0x94 }, { ET8EK8_REG_8BIT, 0x1242, 0x02 }, { ET8EK8_REG_8BIT, 0x124B, 0x00 }, { ET8EK8_REG_8BIT, 0x1255, 0xFF }, { ET8EK8_REG_8BIT, 0x1256, 0x9F }, { ET8EK8_REG_8BIT, 0x1258, 0x00 }, /* From parallel out to serial out */ { ET8EK8_REG_8BIT, 0x125D, 0x88 }, /* From w/ embedded data to w/o embedded data */ { ET8EK8_REG_8BIT, 0x125E, 0xC0 }, /* CCP2 out is from STOP to ACTIVE */ { ET8EK8_REG_8BIT, 0x1263, 0x98 }, { ET8EK8_REG_8BIT, 0x1268, 0xC6 }, { ET8EK8_REG_8BIT, 0x1434, 0x00 }, { ET8EK8_REG_8BIT, 0x1163, 0x44 }, { ET8EK8_REG_8BIT, 0x1166, 0x29 }, { ET8EK8_REG_8BIT, 0x1140, 0x02 }, { ET8EK8_REG_8BIT, 0x1011, 0x24 }, { ET8EK8_REG_8BIT, 0x1151, 0x80 }, { ET8EK8_REG_8BIT, 0x1152, 0x23 }, /* Initial setting for improvement2 of lower frequency noise */ { ET8EK8_REG_8BIT, 0x1014, 0x05 }, { ET8EK8_REG_8BIT, 0x1033, 0x06 }, { ET8EK8_REG_8BIT, 0x1034, 0x79 }, { ET8EK8_REG_8BIT, 0x1423, 0x3F }, { ET8EK8_REG_8BIT, 0x1424, 0x3F }, { ET8EK8_REG_8BIT, 0x1426, 0x00 }, /* Switch of Preset-White-balance (0d:disable / 1d:enable) */ { ET8EK8_REG_8BIT, 0x1439, 0x00 }, /* Switch of blemish correction (0d:disable / 1d:enable) */ { ET8EK8_REG_8BIT, 0x161F, 0x60 }, /* Switch of auto noise correction (0d:disable / 1d:enable) */ { ET8EK8_REG_8BIT, 0x1634, 0x00 }, { ET8EK8_REG_8BIT, 0x1646, 0x00 }, { ET8EK8_REG_8BIT, 0x1648, 0x00 }, { ET8EK8_REG_8BIT, 0x113E, 0x01 }, { ET8EK8_REG_8BIT, 0x113F, 0x22 }, { ET8EK8_REG_8BIT, 0x1239, 0x64 }, { ET8EK8_REG_8BIT, 0x1238, 0x02 }, { ET8EK8_REG_8BIT, 0x123B, 0x70 }, { ET8EK8_REG_8BIT, 0x123A, 0x07 }, { ET8EK8_REG_8BIT, 0x121B, 0x64 }, { ET8EK8_REG_8BIT, 0x121D, 0x64 }, { ET8EK8_REG_8BIT, 0x1221, 0x00 }, { ET8EK8_REG_8BIT, 0x1220, 0x89 }, { ET8EK8_REG_8BIT, 0x1223, 0x00 }, { ET8EK8_REG_8BIT, 0x1222, 0x54 }, { ET8EK8_REG_8BIT, 0x125D, 0x88 }, /* CCP_LVDS_MODE/ */ { ET8EK8_REG_TERM, 0, 0} } }; /* Mode1_16VGA_2592x1968_13.12fps_DPCM10-8 */ static struct et8ek8_reglist mode1_16vga_2592x1968_13_12fps_dpcm10_8 = { /* (without the +1) * SPCK = 80 MHz * CCP2 = 560 MHz * VCO = 560 MHz * VCOUNT = 84 (2016) * HCOUNT = 128 (3072) * CKREF_DIV = 2 * CKVAR_DIV = 175 * VCO_DIV = 0 * SPCK_DIV = 6 * MRCK_DIV = 7 * LVDSCK_DIV = 0 */ .type = ET8EK8_REGLIST_MODE, .mode = { .sensor_width = 2592, .sensor_height = 1968, .sensor_window_origin_x = 0, .sensor_window_origin_y = 0, .sensor_window_width = 2592, .sensor_window_height = 1968, .width = 3072, .height = 2016, .window_origin_x = 0, .window_origin_y = 0, .window_width = 2592, .window_height = 1968, .pixel_clock = 80000000, .ext_clock = 9600000, .timeperframe = { .numerator = 100, .denominator = 1292 }, .max_exp = 2012, /* .max_gain = 0, */ .bus_format = MEDIA_BUS_FMT_SGRBG10_DPCM8_1X8, .sensitivity = 65536 }, .regs = { { ET8EK8_REG_8BIT, 0x1239, 0x57 }, { ET8EK8_REG_8BIT, 0x1238, 0x82 }, { ET8EK8_REG_8BIT, 0x123B, 0x70 }, { ET8EK8_REG_8BIT, 0x123A, 0x06 }, { ET8EK8_REG_8BIT, 0x121B, 0x64 }, { ET8EK8_REG_8BIT, 0x121D, 0x64 }, { ET8EK8_REG_8BIT, 0x1221, 0x00 }, { ET8EK8_REG_8BIT, 0x1220, 0x80 }, /* <-changed to v14 7E->80 */ { ET8EK8_REG_8BIT, 0x1223, 0x00 }, { ET8EK8_REG_8BIT, 0x1222, 0x54 }, { ET8EK8_REG_8BIT, 0x125D, 0x83 }, /* CCP_LVDS_MODE/ */ { ET8EK8_REG_TERM, 0, 0} } }; /* Mode3_4VGA_1296x984_29.99fps_DPCM10-8 */ static struct et8ek8_reglist mode3_4vga_1296x984_29_99fps_dpcm10_8 = { /* (without the +1) * SPCK = 96.5333333333333 MHz * CCP2 = 579.2 MHz * VCO = 579.2 MHz * VCOUNT = 84 (2016) * HCOUNT = 133 (3192) * CKREF_DIV = 2 * CKVAR_DIV = 181 * VCO_DIV = 0 * SPCK_DIV = 5 * MRCK_DIV = 7 * LVDSCK_DIV = 0 */ .type = ET8EK8_REGLIST_MODE, .mode = { .sensor_width = 2592, .sensor_height = 1968, .sensor_window_origin_x = 0, .sensor_window_origin_y = 0, .sensor_window_width = 2592, .sensor_window_height = 1968, .width = 3192, .height = 1008, .window_origin_x = 0, .window_origin_y = 0, .window_width = 1296, .window_height = 984, .pixel_clock = 96533333, .ext_clock = 9600000, .timeperframe = { .numerator = 100, .denominator = 3000 }, .max_exp = 1004, /* .max_gain = 0, */ .bus_format = MEDIA_BUS_FMT_SGRBG10_DPCM8_1X8, .sensitivity = 65536 }, .regs = { { ET8EK8_REG_8BIT, 0x1239, 0x5A }, { ET8EK8_REG_8BIT, 0x1238, 0x82 }, { ET8EK8_REG_8BIT, 0x123B, 0x70 }, { ET8EK8_REG_8BIT, 0x123A, 0x05 }, { ET8EK8_REG_8BIT, 0x121B, 0x63 }, { ET8EK8_REG_8BIT, 0x1220, 0x85 }, { ET8EK8_REG_8BIT, 0x1221, 0x00 }, { ET8EK8_REG_8BIT, 0x1222, 0x54 }, { ET8EK8_REG_8BIT, 0x1223, 0x00 }, { ET8EK8_REG_8BIT, 0x121D, 0x63 }, { ET8EK8_REG_8BIT, 0x125D, 0x83 }, /* CCP_LVDS_MODE/ */ { ET8EK8_REG_TERM, 0, 0} } }; /* Mode4_SVGA_864x656_29.88fps */ static struct et8ek8_reglist mode4_svga_864x656_29_88fps = { /* (without the +1) * SPCK = 80 MHz * CCP2 = 320 MHz * VCO = 640 MHz * VCOUNT = 84 (2016) * HCOUNT = 166 (3984) * CKREF_DIV = 2 * CKVAR_DIV = 200 * VCO_DIV = 0 * SPCK_DIV = 7 * MRCK_DIV = 7 * LVDSCK_DIV = 1 */ .type = ET8EK8_REGLIST_MODE, .mode = { .sensor_width = 2592, .sensor_height = 1968, .sensor_window_origin_x = 0, .sensor_window_origin_y = 0, .sensor_window_width = 2592, .sensor_window_height = 1968, .width = 3984, .height = 672, .window_origin_x = 0, .window_origin_y = 0, .window_width = 864, .window_height = 656, .pixel_clock = 80000000, .ext_clock = 9600000, .timeperframe = { .numerator = 100, .denominator = 2988 }, .max_exp = 668, /* .max_gain = 0, */ .bus_format = MEDIA_BUS_FMT_SGRBG10_1X10, .sensitivity = 65536 }, .regs = { { ET8EK8_REG_8BIT, 0x1239, 0x64 }, { ET8EK8_REG_8BIT, 0x1238, 0x02 }, { ET8EK8_REG_8BIT, 0x123B, 0x71 }, { ET8EK8_REG_8BIT, 0x123A, 0x07 }, { ET8EK8_REG_8BIT, 0x121B, 0x62 }, { ET8EK8_REG_8BIT, 0x121D, 0x62 }, { ET8EK8_REG_8BIT, 0x1221, 0x00 }, { ET8EK8_REG_8BIT, 0x1220, 0xA6 }, { ET8EK8_REG_8BIT, 0x1223, 0x00 }, { ET8EK8_REG_8BIT, 0x1222, 0x54 }, { ET8EK8_REG_8BIT, 0x125D, 0x88 }, /* CCP_LVDS_MODE/ */ { ET8EK8_REG_TERM, 0, 0} } }; /* Mode5_VGA_648x492_29.93fps */ static struct et8ek8_reglist mode5_vga_648x492_29_93fps = { /* (without the +1) * SPCK = 80 MHz * CCP2 = 320 MHz * VCO = 640 MHz * VCOUNT = 84 (2016) * HCOUNT = 221 (5304) * CKREF_DIV = 2 * CKVAR_DIV = 200 * VCO_DIV = 0 * SPCK_DIV = 7 * MRCK_DIV = 7 * LVDSCK_DIV = 1 */ .type = ET8EK8_REGLIST_MODE, .mode = { .sensor_width = 2592, .sensor_height = 1968, .sensor_window_origin_x = 0, .sensor_window_origin_y = 0, .sensor_window_width = 2592, .sensor_window_height = 1968, .width = 5304, .height = 504, .window_origin_x = 0, .window_origin_y = 0, .window_width = 648, .window_height = 492, .pixel_clock = 80000000, .ext_clock = 9600000, .timeperframe = { .numerator = 100, .denominator = 2993 }, .max_exp = 500, /* .max_gain = 0, */ .bus_format = MEDIA_BUS_FMT_SGRBG10_1X10, .sensitivity = 65536 }, .regs = { { ET8EK8_REG_8BIT, 0x1239, 0x64 }, { ET8EK8_REG_8BIT, 0x1238, 0x02 }, { ET8EK8_REG_8BIT, 0x123B, 0x71 }, { ET8EK8_REG_8BIT, 0x123A, 0x07 }, { ET8EK8_REG_8BIT, 0x121B, 0x61 }, { ET8EK8_REG_8BIT, 0x121D, 0x61 }, { ET8EK8_REG_8BIT, 0x1221, 0x00 }, { ET8EK8_REG_8BIT, 0x1220, 0xDD }, { ET8EK8_REG_8BIT, 0x1223, 0x00 }, { ET8EK8_REG_8BIT, 0x1222, 0x54 }, { ET8EK8_REG_8BIT, 0x125D, 0x88 }, /* CCP_LVDS_MODE/ */ { ET8EK8_REG_TERM, 0, 0} } }; /* Mode2_16VGA_2592x1968_3.99fps */ static struct et8ek8_reglist mode2_16vga_2592x1968_3_99fps = { /* (without the +1) * SPCK = 80 MHz * CCP2 = 640 MHz * VCO = 640 MHz * VCOUNT = 254 (6096) * HCOUNT = 137 (3288) * CKREF_DIV = 2 * CKVAR_DIV = 200 * VCO_DIV = 0 * SPCK_DIV = 7 * MRCK_DIV = 7 * LVDSCK_DIV = 0 */ .type = ET8EK8_REGLIST_MODE, .mode = { .sensor_width = 2592, .sensor_height = 1968, .sensor_window_origin_x = 0, .sensor_window_origin_y = 0, .sensor_window_width = 2592, .sensor_window_height = 1968, .width = 3288, .height = 6096, .window_origin_x = 0, .window_origin_y = 0, .window_width = 2592, .window_height = 1968, .pixel_clock = 80000000, .ext_clock = 9600000, .timeperframe = { .numerator = 100, .denominator = 399 }, .max_exp = 6092, /* .max_gain = 0, */ .bus_format = MEDIA_BUS_FMT_SGRBG10_1X10, .sensitivity = 65536 }, .regs = { { ET8EK8_REG_8BIT, 0x1239, 0x64 }, { ET8EK8_REG_8BIT, 0x1238, 0x02 }, { ET8EK8_REG_8BIT, 0x123B, 0x70 }, { ET8EK8_REG_8BIT, 0x123A, 0x07 }, { ET8EK8_REG_8BIT, 0x121B, 0x64 }, { ET8EK8_REG_8BIT, 0x121D, 0x64 }, { ET8EK8_REG_8BIT, 0x1221, 0x00 }, { ET8EK8_REG_8BIT, 0x1220, 0x89 }, { ET8EK8_REG_8BIT, 0x1223, 0x00 }, { ET8EK8_REG_8BIT, 0x1222, 0xFE }, { ET8EK8_REG_TERM, 0, 0} } }; /* Mode_648x492_5fps */ static struct et8ek8_reglist mode_648x492_5fps = { /* (without the +1) * SPCK = 13.3333333333333 MHz * CCP2 = 53.3333333333333 MHz * VCO = 640 MHz * VCOUNT = 84 (2016) * HCOUNT = 221 (5304) * CKREF_DIV = 2 * CKVAR_DIV = 200 * VCO_DIV = 5 * SPCK_DIV = 7 * MRCK_DIV = 7 * LVDSCK_DIV = 1 */ .type = ET8EK8_REGLIST_MODE, .mode = { .sensor_width = 2592, .sensor_height = 1968, .sensor_window_origin_x = 0, .sensor_window_origin_y = 0, .sensor_window_width = 2592, .sensor_window_height = 1968, .width = 5304, .height = 504, .window_origin_x = 0, .window_origin_y = 0, .window_width = 648, .window_height = 492, .pixel_clock = 13333333, .ext_clock = 9600000, .timeperframe = { .numerator = 100, .denominator = 499 }, .max_exp = 500, /* .max_gain = 0, */ .bus_format = MEDIA_BUS_FMT_SGRBG10_1X10, .sensitivity = 65536 }, .regs = { { ET8EK8_REG_8BIT, 0x1239, 0x64 }, { ET8EK8_REG_8BIT, 0x1238, 0x02 }, { ET8EK8_REG_8BIT, 0x123B, 0x71 }, { ET8EK8_REG_8BIT, 0x123A, 0x57 }, { ET8EK8_REG_8BIT, 0x121B, 0x61 }, { ET8EK8_REG_8BIT, 0x121D, 0x61 }, { ET8EK8_REG_8BIT, 0x1221, 0x00 }, { ET8EK8_REG_8BIT, 0x1220, 0xDD }, { ET8EK8_REG_8BIT, 0x1223, 0x00 }, { ET8EK8_REG_8BIT, 0x1222, 0x54 }, { ET8EK8_REG_8BIT, 0x125D, 0x88 }, /* CCP_LVDS_MODE/ */ { ET8EK8_REG_TERM, 0, 0} } }; /* Mode3_4VGA_1296x984_5fps */ static struct et8ek8_reglist mode3_4vga_1296x984_5fps = { /* (without the +1) * SPCK = 49.4 MHz * CCP2 = 395.2 MHz * VCO = 790.4 MHz * VCOUNT = 250 (6000) * HCOUNT = 137 (3288) * CKREF_DIV = 2 * CKVAR_DIV = 247 * VCO_DIV = 1 * SPCK_DIV = 7 * MRCK_DIV = 7 * LVDSCK_DIV = 0 */ .type = ET8EK8_REGLIST_MODE, .mode = { .sensor_width = 2592, .sensor_height = 1968, .sensor_window_origin_x = 0, .sensor_window_origin_y = 0, .sensor_window_width = 2592, .sensor_window_height = 1968, .width = 3288, .height = 3000, .window_origin_x = 0, .window_origin_y = 0, .window_width = 1296, .window_height = 984, .pixel_clock = 49400000, .ext_clock = 9600000, .timeperframe = { .numerator = 100, .denominator = 501 }, .max_exp = 2996, /* .max_gain = 0, */ .bus_format = MEDIA_BUS_FMT_SGRBG10_1X10, .sensitivity = 65536 }, .regs = { { ET8EK8_REG_8BIT, 0x1239, 0x7B }, { ET8EK8_REG_8BIT, 0x1238, 0x82 }, { ET8EK8_REG_8BIT, 0x123B, 0x70 }, { ET8EK8_REG_8BIT, 0x123A, 0x17 }, { ET8EK8_REG_8BIT, 0x121B, 0x63 }, { ET8EK8_REG_8BIT, 0x121D, 0x63 }, { ET8EK8_REG_8BIT, 0x1221, 0x00 }, { ET8EK8_REG_8BIT, 0x1220, 0x89 }, { ET8EK8_REG_8BIT, 0x1223, 0x00 }, { ET8EK8_REG_8BIT, 0x1222, 0xFA }, { ET8EK8_REG_8BIT, 0x125D, 0x88 }, /* CCP_LVDS_MODE/ */ { ET8EK8_REG_TERM, 0, 0} } }; /* Mode_4VGA_1296x984_25fps_DPCM10-8 */ static struct et8ek8_reglist mode_4vga_1296x984_25fps_dpcm10_8 = { /* (without the +1) * SPCK = 84.2666666666667 MHz * CCP2 = 505.6 MHz * VCO = 505.6 MHz * VCOUNT = 88 (2112) * HCOUNT = 133 (3192) * CKREF_DIV = 2 * CKVAR_DIV = 158 * VCO_DIV = 0 * SPCK_DIV = 5 * MRCK_DIV = 7 * LVDSCK_DIV = 0 */ .type = ET8EK8_REGLIST_MODE, .mode = { .sensor_width = 2592, .sensor_height = 1968, .sensor_window_origin_x = 0, .sensor_window_origin_y = 0, .sensor_window_width = 2592, .sensor_window_height = 1968, .width = 3192, .height = 1056, .window_origin_x = 0, .window_origin_y = 0, .window_width = 1296, .window_height = 984, .pixel_clock = 84266667, .ext_clock = 9600000, .timeperframe = { .numerator = 100, .denominator = 2500 }, .max_exp = 1052, /* .max_gain = 0, */ .bus_format = MEDIA_BUS_FMT_SGRBG10_DPCM8_1X8, .sensitivity = 65536 }, .regs = { { ET8EK8_REG_8BIT, 0x1239, 0x4F }, { ET8EK8_REG_8BIT, 0x1238, 0x02 }, { ET8EK8_REG_8BIT, 0x123B, 0x70 }, { ET8EK8_REG_8BIT, 0x123A, 0x05 }, { ET8EK8_REG_8BIT, 0x121B, 0x63 }, { ET8EK8_REG_8BIT, 0x1220, 0x85 }, { ET8EK8_REG_8BIT, 0x1221, 0x00 }, { ET8EK8_REG_8BIT, 0x1222, 0x58 }, { ET8EK8_REG_8BIT, 0x1223, 0x00 }, { ET8EK8_REG_8BIT, 0x121D, 0x63 }, { ET8EK8_REG_8BIT, 0x125D, 0x83 }, { ET8EK8_REG_TERM, 0, 0} } }; struct et8ek8_meta_reglist meta_reglist = { .version = "V14 03-June-2008", .reglist = { { .ptr = &mode1_poweron_mode2_16vga_2592x1968_12_07fps }, { .ptr = &mode1_16vga_2592x1968_13_12fps_dpcm10_8 }, { .ptr = &mode3_4vga_1296x984_29_99fps_dpcm10_8 }, { .ptr = &mode4_svga_864x656_29_88fps }, { .ptr = &mode5_vga_648x492_29_93fps }, { .ptr = &mode2_16vga_2592x1968_3_99fps }, { .ptr = &mode_648x492_5fps }, { .ptr = &mode3_4vga_1296x984_5fps }, { .ptr = &mode_4vga_1296x984_25fps_dpcm10_8 }, { .ptr = NULL } } };
linux-master
drivers/media/i2c/et8ek8/et8ek8_mode.c
// SPDX-License-Identifier: GPL-2.0+ /* * Driver for Analog Devices ADV748X 8 channel analog front end (AFE) receiver * with standard definition processor (SDP) * * Copyright (C) 2017 Renesas Electronics Corp. */ #include <linux/delay.h> #include <linux/module.h> #include <linux/mutex.h> #include <linux/v4l2-dv-timings.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-device.h> #include <media/v4l2-dv-timings.h> #include <media/v4l2-ioctl.h> #include "adv748x.h" /* ----------------------------------------------------------------------------- * SDP */ #define ADV748X_AFE_STD_AD_PAL_BG_NTSC_J_SECAM 0x0 #define ADV748X_AFE_STD_AD_PAL_BG_NTSC_J_SECAM_PED 0x1 #define ADV748X_AFE_STD_AD_PAL_N_NTSC_J_SECAM 0x2 #define ADV748X_AFE_STD_AD_PAL_N_NTSC_M_SECAM 0x3 #define ADV748X_AFE_STD_NTSC_J 0x4 #define ADV748X_AFE_STD_NTSC_M 0x5 #define ADV748X_AFE_STD_PAL60 0x6 #define ADV748X_AFE_STD_NTSC_443 0x7 #define ADV748X_AFE_STD_PAL_BG 0x8 #define ADV748X_AFE_STD_PAL_N 0x9 #define ADV748X_AFE_STD_PAL_M 0xa #define ADV748X_AFE_STD_PAL_M_PED 0xb #define ADV748X_AFE_STD_PAL_COMB_N 0xc #define ADV748X_AFE_STD_PAL_COMB_N_PED 0xd #define ADV748X_AFE_STD_PAL_SECAM 0xe #define ADV748X_AFE_STD_PAL_SECAM_PED 0xf static int adv748x_afe_read_ro_map(struct adv748x_state *state, u8 reg) { int ret; /* Select SDP Read-Only Main Map */ ret = sdp_write(state, ADV748X_SDP_MAP_SEL, ADV748X_SDP_MAP_SEL_RO_MAIN); if (ret < 0) return ret; return sdp_read(state, reg); } static int adv748x_afe_status(struct adv748x_afe *afe, u32 *signal, v4l2_std_id *std) { struct adv748x_state *state = adv748x_afe_to_state(afe); int info; /* Read status from reg 0x10 of SDP RO Map */ info = adv748x_afe_read_ro_map(state, ADV748X_SDP_RO_10); if (info < 0) return info; if (signal) *signal = info & ADV748X_SDP_RO_10_IN_LOCK ? 0 : V4L2_IN_ST_NO_SIGNAL; if (!std) return 0; /* Standard not valid if there is no signal */ if (!(info & ADV748X_SDP_RO_10_IN_LOCK)) { *std = V4L2_STD_UNKNOWN; return 0; } switch (info & 0x70) { case 0x00: *std = V4L2_STD_NTSC; break; case 0x10: *std = V4L2_STD_NTSC_443; break; case 0x20: *std = V4L2_STD_PAL_M; break; case 0x30: *std = V4L2_STD_PAL_60; break; case 0x40: *std = V4L2_STD_PAL; break; case 0x50: *std = V4L2_STD_SECAM; break; case 0x60: *std = V4L2_STD_PAL_Nc | V4L2_STD_PAL_N; break; case 0x70: *std = V4L2_STD_SECAM; break; default: *std = V4L2_STD_UNKNOWN; break; } return 0; } static void adv748x_afe_fill_format(struct adv748x_afe *afe, struct v4l2_mbus_framefmt *fmt) { memset(fmt, 0, sizeof(*fmt)); fmt->code = MEDIA_BUS_FMT_UYVY8_2X8; fmt->colorspace = V4L2_COLORSPACE_SMPTE170M; fmt->field = V4L2_FIELD_ALTERNATE; fmt->width = 720; fmt->height = afe->curr_norm & V4L2_STD_525_60 ? 480 : 576; /* Field height */ fmt->height /= 2; } static int adv748x_afe_std(v4l2_std_id std) { if (std == V4L2_STD_PAL_60) return ADV748X_AFE_STD_PAL60; if (std == V4L2_STD_NTSC_443) return ADV748X_AFE_STD_NTSC_443; if (std == V4L2_STD_PAL_N) return ADV748X_AFE_STD_PAL_N; if (std == V4L2_STD_PAL_M) return ADV748X_AFE_STD_PAL_M; if (std == V4L2_STD_PAL_Nc) return ADV748X_AFE_STD_PAL_COMB_N; if (std & V4L2_STD_NTSC) return ADV748X_AFE_STD_NTSC_M; if (std & V4L2_STD_PAL) return ADV748X_AFE_STD_PAL_BG; if (std & V4L2_STD_SECAM) return ADV748X_AFE_STD_PAL_SECAM; return -EINVAL; } static void adv748x_afe_set_video_standard(struct adv748x_state *state, int sdpstd) { sdp_clrset(state, ADV748X_SDP_VID_SEL, ADV748X_SDP_VID_SEL_MASK, (sdpstd & 0xf) << ADV748X_SDP_VID_SEL_SHIFT); } int adv748x_afe_s_input(struct adv748x_afe *afe, unsigned int input) { struct adv748x_state *state = adv748x_afe_to_state(afe); return sdp_write(state, ADV748X_SDP_INSEL, input); } static int adv748x_afe_g_pixelaspect(struct v4l2_subdev *sd, struct v4l2_fract *aspect) { struct adv748x_afe *afe = adv748x_sd_to_afe(sd); if (afe->curr_norm & V4L2_STD_525_60) { aspect->numerator = 11; aspect->denominator = 10; } else { aspect->numerator = 54; aspect->denominator = 59; } return 0; } /* ----------------------------------------------------------------------------- * v4l2_subdev_video_ops */ static int adv748x_afe_g_std(struct v4l2_subdev *sd, v4l2_std_id *norm) { struct adv748x_afe *afe = adv748x_sd_to_afe(sd); *norm = afe->curr_norm; return 0; } static int adv748x_afe_s_std(struct v4l2_subdev *sd, v4l2_std_id std) { struct adv748x_afe *afe = adv748x_sd_to_afe(sd); struct adv748x_state *state = adv748x_afe_to_state(afe); int afe_std = adv748x_afe_std(std); if (afe_std < 0) return afe_std; mutex_lock(&state->mutex); adv748x_afe_set_video_standard(state, afe_std); afe->curr_norm = std; mutex_unlock(&state->mutex); return 0; } static int adv748x_afe_querystd(struct v4l2_subdev *sd, v4l2_std_id *std) { struct adv748x_afe *afe = adv748x_sd_to_afe(sd); struct adv748x_state *state = adv748x_afe_to_state(afe); int afe_std; int ret; mutex_lock(&state->mutex); if (afe->streaming) { ret = -EBUSY; goto unlock; } /* Set auto detect mode */ adv748x_afe_set_video_standard(state, ADV748X_AFE_STD_AD_PAL_BG_NTSC_J_SECAM); msleep(100); /* Read detected standard */ ret = adv748x_afe_status(afe, NULL, std); afe_std = adv748x_afe_std(afe->curr_norm); if (afe_std < 0) goto unlock; /* Restore original state */ adv748x_afe_set_video_standard(state, afe_std); unlock: mutex_unlock(&state->mutex); return ret; } static int adv748x_afe_g_tvnorms(struct v4l2_subdev *sd, v4l2_std_id *norm) { *norm = V4L2_STD_ALL; return 0; } static int adv748x_afe_g_input_status(struct v4l2_subdev *sd, u32 *status) { struct adv748x_afe *afe = adv748x_sd_to_afe(sd); struct adv748x_state *state = adv748x_afe_to_state(afe); int ret; mutex_lock(&state->mutex); ret = adv748x_afe_status(afe, status, NULL); mutex_unlock(&state->mutex); return ret; } static int adv748x_afe_s_stream(struct v4l2_subdev *sd, int enable) { struct adv748x_afe *afe = adv748x_sd_to_afe(sd); struct adv748x_state *state = adv748x_afe_to_state(afe); u32 signal = V4L2_IN_ST_NO_SIGNAL; int ret; mutex_lock(&state->mutex); if (enable) { ret = adv748x_afe_s_input(afe, afe->input); if (ret) goto unlock; } ret = adv748x_tx_power(afe->tx, enable); if (ret) goto unlock; afe->streaming = enable; adv748x_afe_status(afe, &signal, NULL); if (signal != V4L2_IN_ST_NO_SIGNAL) adv_dbg(state, "Detected SDP signal\n"); else adv_dbg(state, "Couldn't detect SDP video signal\n"); unlock: mutex_unlock(&state->mutex); return ret; } static const struct v4l2_subdev_video_ops adv748x_afe_video_ops = { .g_std = adv748x_afe_g_std, .s_std = adv748x_afe_s_std, .querystd = adv748x_afe_querystd, .g_tvnorms = adv748x_afe_g_tvnorms, .g_input_status = adv748x_afe_g_input_status, .s_stream = adv748x_afe_s_stream, .g_pixelaspect = adv748x_afe_g_pixelaspect, }; /* ----------------------------------------------------------------------------- * v4l2_subdev_pad_ops */ static int adv748x_afe_propagate_pixelrate(struct adv748x_afe *afe) { struct v4l2_subdev *tx; tx = adv748x_get_remote_sd(&afe->pads[ADV748X_AFE_SOURCE]); if (!tx) return -ENOLINK; /* * The ADV748x ADC sampling frequency is twice the externally supplied * clock whose frequency is required to be 28.63636 MHz. It oversamples * with a factor of 4 resulting in a pixel rate of 14.3180180 MHz. */ return adv748x_csi2_set_pixelrate(tx, 14318180); } static int adv748x_afe_enum_mbus_code(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_mbus_code_enum *code) { if (code->index != 0) return -EINVAL; code->code = MEDIA_BUS_FMT_UYVY8_2X8; return 0; } static int adv748x_afe_get_format(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *sdformat) { struct adv748x_afe *afe = adv748x_sd_to_afe(sd); struct v4l2_mbus_framefmt *mbusformat; /* It makes no sense to get the format of the analog sink pads */ if (sdformat->pad != ADV748X_AFE_SOURCE) return -EINVAL; if (sdformat->which == V4L2_SUBDEV_FORMAT_TRY) { mbusformat = v4l2_subdev_get_try_format(sd, sd_state, sdformat->pad); sdformat->format = *mbusformat; } else { adv748x_afe_fill_format(afe, &sdformat->format); adv748x_afe_propagate_pixelrate(afe); } return 0; } static int adv748x_afe_set_format(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *sdformat) { struct v4l2_mbus_framefmt *mbusformat; /* It makes no sense to get the format of the analog sink pads */ if (sdformat->pad != ADV748X_AFE_SOURCE) return -EINVAL; if (sdformat->which == V4L2_SUBDEV_FORMAT_ACTIVE) return adv748x_afe_get_format(sd, sd_state, sdformat); mbusformat = v4l2_subdev_get_try_format(sd, sd_state, sdformat->pad); *mbusformat = sdformat->format; return 0; } static const struct v4l2_subdev_pad_ops adv748x_afe_pad_ops = { .enum_mbus_code = adv748x_afe_enum_mbus_code, .set_fmt = adv748x_afe_set_format, .get_fmt = adv748x_afe_get_format, }; /* ----------------------------------------------------------------------------- * v4l2_subdev_ops */ static const struct v4l2_subdev_ops adv748x_afe_ops = { .video = &adv748x_afe_video_ops, .pad = &adv748x_afe_pad_ops, }; /* ----------------------------------------------------------------------------- * Controls */ static const char * const afe_ctrl_frp_menu[] = { "Disabled", "Solid Blue", "Color Bars", "Grey Ramp", "Cb Ramp", "Cr Ramp", "Boundary" }; static int adv748x_afe_s_ctrl(struct v4l2_ctrl *ctrl) { struct adv748x_afe *afe = adv748x_ctrl_to_afe(ctrl); struct adv748x_state *state = adv748x_afe_to_state(afe); bool enable; int ret; ret = sdp_write(state, 0x0e, 0x00); if (ret < 0) return ret; switch (ctrl->id) { case V4L2_CID_BRIGHTNESS: ret = sdp_write(state, ADV748X_SDP_BRI, ctrl->val); break; case V4L2_CID_HUE: /* Hue is inverted according to HSL chart */ ret = sdp_write(state, ADV748X_SDP_HUE, -ctrl->val); break; case V4L2_CID_CONTRAST: ret = sdp_write(state, ADV748X_SDP_CON, ctrl->val); break; case V4L2_CID_SATURATION: ret = sdp_write(state, ADV748X_SDP_SD_SAT_U, ctrl->val); if (ret) break; ret = sdp_write(state, ADV748X_SDP_SD_SAT_V, ctrl->val); break; case V4L2_CID_TEST_PATTERN: enable = !!ctrl->val; /* Enable/Disable Color bar test patterns */ ret = sdp_clrset(state, ADV748X_SDP_DEF, ADV748X_SDP_DEF_VAL_EN, enable); if (ret) break; ret = sdp_clrset(state, ADV748X_SDP_FRP, ADV748X_SDP_FRP_MASK, enable ? ctrl->val - 1 : 0); break; default: return -EINVAL; } return ret; } static const struct v4l2_ctrl_ops adv748x_afe_ctrl_ops = { .s_ctrl = adv748x_afe_s_ctrl, }; static int adv748x_afe_init_controls(struct adv748x_afe *afe) { struct adv748x_state *state = adv748x_afe_to_state(afe); v4l2_ctrl_handler_init(&afe->ctrl_hdl, 5); /* Use our mutex for the controls */ afe->ctrl_hdl.lock = &state->mutex; v4l2_ctrl_new_std(&afe->ctrl_hdl, &adv748x_afe_ctrl_ops, V4L2_CID_BRIGHTNESS, ADV748X_SDP_BRI_MIN, ADV748X_SDP_BRI_MAX, 1, ADV748X_SDP_BRI_DEF); v4l2_ctrl_new_std(&afe->ctrl_hdl, &adv748x_afe_ctrl_ops, V4L2_CID_CONTRAST, ADV748X_SDP_CON_MIN, ADV748X_SDP_CON_MAX, 1, ADV748X_SDP_CON_DEF); v4l2_ctrl_new_std(&afe->ctrl_hdl, &adv748x_afe_ctrl_ops, V4L2_CID_SATURATION, ADV748X_SDP_SAT_MIN, ADV748X_SDP_SAT_MAX, 1, ADV748X_SDP_SAT_DEF); v4l2_ctrl_new_std(&afe->ctrl_hdl, &adv748x_afe_ctrl_ops, V4L2_CID_HUE, ADV748X_SDP_HUE_MIN, ADV748X_SDP_HUE_MAX, 1, ADV748X_SDP_HUE_DEF); v4l2_ctrl_new_std_menu_items(&afe->ctrl_hdl, &adv748x_afe_ctrl_ops, V4L2_CID_TEST_PATTERN, ARRAY_SIZE(afe_ctrl_frp_menu) - 1, 0, 0, afe_ctrl_frp_menu); afe->sd.ctrl_handler = &afe->ctrl_hdl; if (afe->ctrl_hdl.error) { v4l2_ctrl_handler_free(&afe->ctrl_hdl); return afe->ctrl_hdl.error; } return v4l2_ctrl_handler_setup(&afe->ctrl_hdl); } int adv748x_afe_init(struct adv748x_afe *afe) { struct adv748x_state *state = adv748x_afe_to_state(afe); int ret; unsigned int i; afe->input = 0; afe->streaming = false; afe->curr_norm = V4L2_STD_NTSC_M; adv748x_subdev_init(&afe->sd, state, &adv748x_afe_ops, MEDIA_ENT_F_ATV_DECODER, "afe"); /* Identify the first connector found as a default input if set */ for (i = ADV748X_PORT_AIN0; i <= ADV748X_PORT_AIN7; i++) { /* Inputs and ports are 1-indexed to match the data sheet */ if (state->endpoints[i]) { afe->input = i; break; } } adv748x_afe_s_input(afe, afe->input); adv_dbg(state, "AFE Default input set to %d\n", afe->input); /* Entity pads and sinks are 0-indexed to match the pads */ for (i = ADV748X_AFE_SINK_AIN0; i <= ADV748X_AFE_SINK_AIN7; i++) afe->pads[i].flags = MEDIA_PAD_FL_SINK; afe->pads[ADV748X_AFE_SOURCE].flags = MEDIA_PAD_FL_SOURCE; ret = media_entity_pads_init(&afe->sd.entity, ADV748X_AFE_NR_PADS, afe->pads); if (ret) return ret; ret = adv748x_afe_init_controls(afe); if (ret) goto error; return 0; error: media_entity_cleanup(&afe->sd.entity); return ret; } void adv748x_afe_cleanup(struct adv748x_afe *afe) { v4l2_device_unregister_subdev(&afe->sd); media_entity_cleanup(&afe->sd.entity); v4l2_ctrl_handler_free(&afe->ctrl_hdl); }
linux-master
drivers/media/i2c/adv748x/adv748x-afe.c
// SPDX-License-Identifier: GPL-2.0+ /* * Driver for Analog Devices ADV748X HDMI receiver with AFE * * Copyright (C) 2017 Renesas Electronics Corp. * * Authors: * Koji Matsuoka <[email protected]> * Niklas Söderlund <[email protected]> * Kieran Bingham <[email protected]> */ #include <linux/delay.h> #include <linux/errno.h> #include <linux/i2c.h> #include <linux/module.h> #include <linux/mutex.h> #include <linux/of_graph.h> #include <linux/regmap.h> #include <linux/slab.h> #include <linux/v4l2-dv-timings.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-device.h> #include <media/v4l2-dv-timings.h> #include <media/v4l2-fwnode.h> #include <media/v4l2-ioctl.h> #include "adv748x.h" /* ----------------------------------------------------------------------------- * Register manipulation */ #define ADV748X_REGMAP_CONF(n) \ { \ .name = n, \ .reg_bits = 8, \ .val_bits = 8, \ .max_register = 0xff, \ .cache_type = REGCACHE_NONE, \ } static const struct regmap_config adv748x_regmap_cnf[] = { ADV748X_REGMAP_CONF("io"), ADV748X_REGMAP_CONF("dpll"), ADV748X_REGMAP_CONF("cp"), ADV748X_REGMAP_CONF("hdmi"), ADV748X_REGMAP_CONF("edid"), ADV748X_REGMAP_CONF("repeater"), ADV748X_REGMAP_CONF("infoframe"), ADV748X_REGMAP_CONF("cbus"), ADV748X_REGMAP_CONF("cec"), ADV748X_REGMAP_CONF("sdp"), ADV748X_REGMAP_CONF("txa"), ADV748X_REGMAP_CONF("txb"), }; static int adv748x_configure_regmap(struct adv748x_state *state, int region) { int err; if (!state->i2c_clients[region]) return -ENODEV; state->regmap[region] = devm_regmap_init_i2c(state->i2c_clients[region], &adv748x_regmap_cnf[region]); if (IS_ERR(state->regmap[region])) { err = PTR_ERR(state->regmap[region]); adv_err(state, "Error initializing regmap %d with error %d\n", region, err); return -EINVAL; } return 0; } struct adv748x_register_map { const char *name; u8 default_addr; }; static const struct adv748x_register_map adv748x_default_addresses[] = { [ADV748X_PAGE_IO] = { "main", 0x70 }, [ADV748X_PAGE_DPLL] = { "dpll", 0x26 }, [ADV748X_PAGE_CP] = { "cp", 0x22 }, [ADV748X_PAGE_HDMI] = { "hdmi", 0x34 }, [ADV748X_PAGE_EDID] = { "edid", 0x36 }, [ADV748X_PAGE_REPEATER] = { "repeater", 0x32 }, [ADV748X_PAGE_INFOFRAME] = { "infoframe", 0x31 }, [ADV748X_PAGE_CBUS] = { "cbus", 0x30 }, [ADV748X_PAGE_CEC] = { "cec", 0x41 }, [ADV748X_PAGE_SDP] = { "sdp", 0x79 }, [ADV748X_PAGE_TXB] = { "txb", 0x48 }, [ADV748X_PAGE_TXA] = { "txa", 0x4a }, }; static int adv748x_read_check(struct adv748x_state *state, int client_page, u8 reg) { struct i2c_client *client = state->i2c_clients[client_page]; int err; unsigned int val; err = regmap_read(state->regmap[client_page], reg, &val); if (err) { adv_err(state, "error reading %02x, %02x\n", client->addr, reg); return err; } return val; } int adv748x_read(struct adv748x_state *state, u8 page, u8 reg) { return adv748x_read_check(state, page, reg); } int adv748x_write(struct adv748x_state *state, u8 page, u8 reg, u8 value) { return regmap_write(state->regmap[page], reg, value); } static int adv748x_write_check(struct adv748x_state *state, u8 page, u8 reg, u8 value, int *error) { if (*error) return *error; *error = adv748x_write(state, page, reg, value); return *error; } /* adv748x_write_block(): Write raw data with a maximum of I2C_SMBUS_BLOCK_MAX * size to one or more registers. * * A value of zero will be returned on success, a negative errno will * be returned in error cases. */ int adv748x_write_block(struct adv748x_state *state, int client_page, unsigned int init_reg, const void *val, size_t val_len) { struct regmap *regmap = state->regmap[client_page]; if (val_len > I2C_SMBUS_BLOCK_MAX) val_len = I2C_SMBUS_BLOCK_MAX; return regmap_raw_write(regmap, init_reg, val, val_len); } static int adv748x_set_slave_addresses(struct adv748x_state *state) { struct i2c_client *client; unsigned int i; u8 io_reg; for (i = ADV748X_PAGE_DPLL; i < ADV748X_PAGE_MAX; ++i) { io_reg = ADV748X_IO_SLAVE_ADDR_BASE + i; client = state->i2c_clients[i]; io_write(state, io_reg, client->addr << 1); } return 0; } static void adv748x_unregister_clients(struct adv748x_state *state) { unsigned int i; for (i = 1; i < ARRAY_SIZE(state->i2c_clients); ++i) i2c_unregister_device(state->i2c_clients[i]); } static int adv748x_initialise_clients(struct adv748x_state *state) { unsigned int i; int ret; for (i = ADV748X_PAGE_DPLL; i < ADV748X_PAGE_MAX; ++i) { state->i2c_clients[i] = i2c_new_ancillary_device( state->client, adv748x_default_addresses[i].name, adv748x_default_addresses[i].default_addr); if (IS_ERR(state->i2c_clients[i])) { adv_err(state, "failed to create i2c client %u\n", i); return PTR_ERR(state->i2c_clients[i]); } ret = adv748x_configure_regmap(state, i); if (ret) return ret; } return 0; } /** * struct adv748x_reg_value - Register write instruction * @page: Regmap page identifier * @reg: I2C register * @value: value to write to @page at @reg */ struct adv748x_reg_value { u8 page; u8 reg; u8 value; }; static int adv748x_write_regs(struct adv748x_state *state, const struct adv748x_reg_value *regs) { int ret; for (; regs->page != ADV748X_PAGE_EOR; regs++) { ret = adv748x_write(state, regs->page, regs->reg, regs->value); if (ret < 0) { adv_err(state, "Error regs page: 0x%02x reg: 0x%02x\n", regs->page, regs->reg); return ret; } } return 0; } /* ----------------------------------------------------------------------------- * TXA and TXB */ static int adv748x_power_up_tx(struct adv748x_csi2 *tx) { struct adv748x_state *state = tx->state; u8 page = is_txa(tx) ? ADV748X_PAGE_TXA : ADV748X_PAGE_TXB; int ret = 0; /* Enable n-lane MIPI */ adv748x_write_check(state, page, 0x00, 0x80 | tx->active_lanes, &ret); /* Set Auto DPHY Timing */ adv748x_write_check(state, page, 0x00, 0xa0 | tx->active_lanes, &ret); /* ADI Required Write */ if (tx->src == &state->hdmi.sd) { adv748x_write_check(state, page, 0xdb, 0x10, &ret); adv748x_write_check(state, page, 0xd6, 0x07, &ret); } else { adv748x_write_check(state, page, 0xd2, 0x40, &ret); } adv748x_write_check(state, page, 0xc4, 0x0a, &ret); adv748x_write_check(state, page, 0x71, 0x33, &ret); adv748x_write_check(state, page, 0x72, 0x11, &ret); /* i2c_dphy_pwdn - 1'b0 */ adv748x_write_check(state, page, 0xf0, 0x00, &ret); /* ADI Required Writes*/ adv748x_write_check(state, page, 0x31, 0x82, &ret); adv748x_write_check(state, page, 0x1e, 0x40, &ret); /* i2c_mipi_pll_en - 1'b1 */ adv748x_write_check(state, page, 0xda, 0x01, &ret); usleep_range(2000, 2500); /* Power-up CSI-TX */ adv748x_write_check(state, page, 0x00, 0x20 | tx->active_lanes, &ret); usleep_range(1000, 1500); /* ADI Required Writes */ adv748x_write_check(state, page, 0xc1, 0x2b, &ret); usleep_range(1000, 1500); adv748x_write_check(state, page, 0x31, 0x80, &ret); return ret; } static int adv748x_power_down_tx(struct adv748x_csi2 *tx) { struct adv748x_state *state = tx->state; u8 page = is_txa(tx) ? ADV748X_PAGE_TXA : ADV748X_PAGE_TXB; int ret = 0; /* ADI Required Writes */ adv748x_write_check(state, page, 0x31, 0x82, &ret); adv748x_write_check(state, page, 0x1e, 0x00, &ret); /* Enable n-lane MIPI */ adv748x_write_check(state, page, 0x00, 0x80 | tx->active_lanes, &ret); /* i2c_mipi_pll_en - 1'b1 */ adv748x_write_check(state, page, 0xda, 0x01, &ret); /* ADI Required Write */ adv748x_write_check(state, page, 0xc1, 0x3b, &ret); return ret; } int adv748x_tx_power(struct adv748x_csi2 *tx, bool on) { int val; if (!is_tx_enabled(tx)) return 0; val = tx_read(tx, ADV748X_CSI_FS_AS_LS); if (val < 0) return val; /* * This test against BIT(6) is not documented by the datasheet, but was * specified in the downstream driver. * Track with a WARN_ONCE to determine if it is ever set by HW. */ WARN_ONCE((on && val & ADV748X_CSI_FS_AS_LS_UNKNOWN), "Enabling with unknown bit set"); return on ? adv748x_power_up_tx(tx) : adv748x_power_down_tx(tx); } /* ----------------------------------------------------------------------------- * Media Operations */ static int adv748x_link_setup(struct media_entity *entity, const struct media_pad *local, const struct media_pad *remote, u32 flags) { struct v4l2_subdev *rsd = media_entity_to_v4l2_subdev(remote->entity); struct v4l2_subdev *sd = media_entity_to_v4l2_subdev(entity); struct adv748x_state *state = v4l2_get_subdevdata(sd); struct adv748x_csi2 *tx = adv748x_sd_to_csi2(sd); bool enable = flags & MEDIA_LNK_FL_ENABLED; u8 io10_mask = ADV748X_IO_10_CSI1_EN | ADV748X_IO_10_CSI4_EN | ADV748X_IO_10_CSI4_IN_SEL_AFE; u8 io10 = 0; /* Refuse to enable multiple links to the same TX at the same time. */ if (enable && tx->src) return -EINVAL; /* Set or clear the source (HDMI or AFE) and the current TX. */ if (rsd == &state->afe.sd) state->afe.tx = enable ? tx : NULL; else state->hdmi.tx = enable ? tx : NULL; tx->src = enable ? rsd : NULL; if (state->afe.tx) { /* AFE Requires TXA enabled, even when output to TXB */ io10 |= ADV748X_IO_10_CSI4_EN; if (is_txa(tx)) { /* * Output from the SD-core (480i and 576i) from the TXA * interface requires reducing the number of enabled * data lanes in order to guarantee a valid link * frequency. */ tx->active_lanes = min(tx->num_lanes, 2U); io10 |= ADV748X_IO_10_CSI4_IN_SEL_AFE; } else { /* TXB has a single data lane, no need to adjust. */ io10 |= ADV748X_IO_10_CSI1_EN; } } if (state->hdmi.tx) { /* * Restore the number of active lanes, in case we have gone * through an AFE->TXA streaming sessions. */ tx->active_lanes = tx->num_lanes; io10 |= ADV748X_IO_10_CSI4_EN; } return io_clrset(state, ADV748X_IO_10, io10_mask, io10); } static const struct media_entity_operations adv748x_tx_media_ops = { .link_setup = adv748x_link_setup, .link_validate = v4l2_subdev_link_validate, }; static const struct media_entity_operations adv748x_media_ops = { .link_validate = v4l2_subdev_link_validate, }; /* ----------------------------------------------------------------------------- * HW setup */ /* Initialize CP Core with RGB888 format. */ static const struct adv748x_reg_value adv748x_init_hdmi[] = { /* Disable chip powerdown & Enable HDMI Rx block */ {ADV748X_PAGE_IO, 0x00, 0x40}, {ADV748X_PAGE_REPEATER, 0x40, 0x83}, /* Enable HDCP 1.1 */ {ADV748X_PAGE_HDMI, 0x00, 0x08},/* Foreground Channel = A */ {ADV748X_PAGE_HDMI, 0x98, 0xff},/* ADI Required Write */ {ADV748X_PAGE_HDMI, 0x99, 0xa3},/* ADI Required Write */ {ADV748X_PAGE_HDMI, 0x9a, 0x00},/* ADI Required Write */ {ADV748X_PAGE_HDMI, 0x9b, 0x0a},/* ADI Required Write */ {ADV748X_PAGE_HDMI, 0x9d, 0x40},/* ADI Required Write */ {ADV748X_PAGE_HDMI, 0xcb, 0x09},/* ADI Required Write */ {ADV748X_PAGE_HDMI, 0x3d, 0x10},/* ADI Required Write */ {ADV748X_PAGE_HDMI, 0x3e, 0x7b},/* ADI Required Write */ {ADV748X_PAGE_HDMI, 0x3f, 0x5e},/* ADI Required Write */ {ADV748X_PAGE_HDMI, 0x4e, 0xfe},/* ADI Required Write */ {ADV748X_PAGE_HDMI, 0x4f, 0x18},/* ADI Required Write */ {ADV748X_PAGE_HDMI, 0x57, 0xa3},/* ADI Required Write */ {ADV748X_PAGE_HDMI, 0x58, 0x04},/* ADI Required Write */ {ADV748X_PAGE_HDMI, 0x85, 0x10},/* ADI Required Write */ {ADV748X_PAGE_HDMI, 0x83, 0x00},/* Enable All Terminations */ {ADV748X_PAGE_HDMI, 0xa3, 0x01},/* ADI Required Write */ {ADV748X_PAGE_HDMI, 0xbe, 0x00},/* ADI Required Write */ {ADV748X_PAGE_HDMI, 0x6c, 0x01},/* HPA Manual Enable */ {ADV748X_PAGE_HDMI, 0xf8, 0x01},/* HPA Asserted */ {ADV748X_PAGE_HDMI, 0x0f, 0x00},/* Audio Mute Speed Set to Fastest */ /* (Smallest Step Size) */ {ADV748X_PAGE_IO, 0x04, 0x02}, /* RGB Out of CP */ {ADV748X_PAGE_IO, 0x12, 0xf0}, /* CSC Depends on ip Packets, SDR 444 */ {ADV748X_PAGE_IO, 0x17, 0x80}, /* Luma & Chroma can reach 254d */ {ADV748X_PAGE_IO, 0x03, 0x86}, /* CP-Insert_AV_Code */ {ADV748X_PAGE_CP, 0x7c, 0x00}, /* ADI Required Write */ {ADV748X_PAGE_IO, 0x0c, 0xe0}, /* Enable LLC_DLL & Double LLC Timing */ {ADV748X_PAGE_IO, 0x0e, 0xdd}, /* LLC/PIX/SPI PINS TRISTATED AUD */ {ADV748X_PAGE_EOR, 0xff, 0xff} /* End of register table */ }; /* Initialize AFE core with YUV8 format. */ static const struct adv748x_reg_value adv748x_init_afe[] = { {ADV748X_PAGE_IO, 0x00, 0x30}, /* Disable chip powerdown Rx */ {ADV748X_PAGE_IO, 0xf2, 0x01}, /* Enable I2C Read Auto-Increment */ {ADV748X_PAGE_IO, 0x0e, 0xff}, /* LLC/PIX/AUD/SPI PINS TRISTATED */ {ADV748X_PAGE_SDP, 0x0f, 0x00}, /* Exit Power Down Mode */ {ADV748X_PAGE_SDP, 0x52, 0xcd}, /* ADI Required Write */ {ADV748X_PAGE_SDP, 0x0e, 0x80}, /* ADI Required Write */ {ADV748X_PAGE_SDP, 0x9c, 0x00}, /* ADI Required Write */ {ADV748X_PAGE_SDP, 0x9c, 0xff}, /* ADI Required Write */ {ADV748X_PAGE_SDP, 0x0e, 0x00}, /* ADI Required Write */ /* ADI recommended writes for improved video quality */ {ADV748X_PAGE_SDP, 0x80, 0x51}, /* ADI Required Write */ {ADV748X_PAGE_SDP, 0x81, 0x51}, /* ADI Required Write */ {ADV748X_PAGE_SDP, 0x82, 0x68}, /* ADI Required Write */ {ADV748X_PAGE_SDP, 0x03, 0x42}, /* Tri-S Output , PwrDwn 656 pads */ {ADV748X_PAGE_SDP, 0x04, 0xb5}, /* ITU-R BT.656-4 compatible */ {ADV748X_PAGE_SDP, 0x13, 0x00}, /* ADI Required Write */ {ADV748X_PAGE_SDP, 0x17, 0x41}, /* Select SH1 */ {ADV748X_PAGE_SDP, 0x31, 0x12}, /* ADI Required Write */ {ADV748X_PAGE_SDP, 0xe6, 0x4f}, /* V bit end pos manually in NTSC */ {ADV748X_PAGE_EOR, 0xff, 0xff} /* End of register table */ }; static int adv748x_sw_reset(struct adv748x_state *state) { int ret; ret = io_write(state, ADV748X_IO_REG_FF, ADV748X_IO_REG_FF_MAIN_RESET); if (ret) return ret; usleep_range(5000, 6000); /* Disable CEC Wakeup from power-down mode */ ret = io_clrset(state, ADV748X_IO_REG_01, ADV748X_IO_REG_01_PWRDN_MASK, ADV748X_IO_REG_01_PWRDNB); if (ret) return ret; /* Enable I2C Read Auto-Increment for consecutive reads */ return io_write(state, ADV748X_IO_REG_F2, ADV748X_IO_REG_F2_READ_AUTO_INC); } static int adv748x_reset(struct adv748x_state *state) { int ret; u8 regval = 0; ret = adv748x_sw_reset(state); if (ret < 0) return ret; ret = adv748x_set_slave_addresses(state); if (ret < 0) return ret; /* Initialize CP and AFE cores. */ ret = adv748x_write_regs(state, adv748x_init_hdmi); if (ret) return ret; ret = adv748x_write_regs(state, adv748x_init_afe); if (ret) return ret; adv748x_afe_s_input(&state->afe, state->afe.input); adv_dbg(state, "AFE Default input set to %d\n", state->afe.input); /* Reset TXA and TXB */ adv748x_tx_power(&state->txa, 1); adv748x_tx_power(&state->txa, 0); adv748x_tx_power(&state->txb, 1); adv748x_tx_power(&state->txb, 0); /* Disable chip powerdown & Enable HDMI Rx block */ io_write(state, ADV748X_IO_PD, ADV748X_IO_PD_RX_EN); /* Conditionally enable TXa and TXb. */ if (is_tx_enabled(&state->txa)) { regval |= ADV748X_IO_10_CSI4_EN; adv748x_csi2_set_virtual_channel(&state->txa, 0); } if (is_tx_enabled(&state->txb)) { regval |= ADV748X_IO_10_CSI1_EN; adv748x_csi2_set_virtual_channel(&state->txb, 0); } io_write(state, ADV748X_IO_10, regval); /* Use vid_std and v_freq as freerun resolution for CP */ cp_clrset(state, ADV748X_CP_CLMP_POS, ADV748X_CP_CLMP_POS_DIS_AUTO, ADV748X_CP_CLMP_POS_DIS_AUTO); return 0; } static int adv748x_identify_chip(struct adv748x_state *state) { int msb, lsb; lsb = io_read(state, ADV748X_IO_CHIP_REV_ID_1); msb = io_read(state, ADV748X_IO_CHIP_REV_ID_2); if (lsb < 0 || msb < 0) { adv_err(state, "Failed to read chip revision\n"); return -EIO; } adv_info(state, "chip found @ 0x%02x revision %02x%02x\n", state->client->addr << 1, lsb, msb); return 0; } /* ----------------------------------------------------------------------------- * Suspend / Resume */ static int __maybe_unused adv748x_resume_early(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct adv748x_state *state = i2c_get_clientdata(client); return adv748x_reset(state); } /* ----------------------------------------------------------------------------- * i2c driver */ void adv748x_subdev_init(struct v4l2_subdev *sd, struct adv748x_state *state, const struct v4l2_subdev_ops *ops, u32 function, const char *ident) { v4l2_subdev_init(sd, ops); sd->flags |= V4L2_SUBDEV_FL_HAS_DEVNODE; /* the owner is the same as the i2c_client's driver owner */ sd->owner = state->dev->driver->owner; sd->dev = state->dev; v4l2_set_subdevdata(sd, state); /* initialize name */ snprintf(sd->name, sizeof(sd->name), "%s %d-%04x %s", state->dev->driver->name, i2c_adapter_id(state->client->adapter), state->client->addr, ident); sd->entity.function = function; sd->entity.ops = is_tx(adv748x_sd_to_csi2(sd)) ? &adv748x_tx_media_ops : &adv748x_media_ops; } static int adv748x_parse_csi2_lanes(struct adv748x_state *state, unsigned int port, struct device_node *ep) { struct v4l2_fwnode_endpoint vep = { .bus_type = V4L2_MBUS_CSI2_DPHY }; unsigned int num_lanes; int ret; if (port != ADV748X_PORT_TXA && port != ADV748X_PORT_TXB) return 0; ret = v4l2_fwnode_endpoint_parse(of_fwnode_handle(ep), &vep); if (ret) return ret; num_lanes = vep.bus.mipi_csi2.num_data_lanes; if (vep.base.port == ADV748X_PORT_TXA) { if (num_lanes != 1 && num_lanes != 2 && num_lanes != 4) { adv_err(state, "TXA: Invalid number (%u) of lanes\n", num_lanes); return -EINVAL; } state->txa.num_lanes = num_lanes; state->txa.active_lanes = num_lanes; adv_dbg(state, "TXA: using %u lanes\n", state->txa.num_lanes); } if (vep.base.port == ADV748X_PORT_TXB) { if (num_lanes != 1) { adv_err(state, "TXB: Invalid number (%u) of lanes\n", num_lanes); return -EINVAL; } state->txb.num_lanes = num_lanes; state->txb.active_lanes = num_lanes; adv_dbg(state, "TXB: using %u lanes\n", state->txb.num_lanes); } return 0; } static int adv748x_parse_dt(struct adv748x_state *state) { struct device_node *ep_np = NULL; struct of_endpoint ep; bool out_found = false; bool in_found = false; int ret; for_each_endpoint_of_node(state->dev->of_node, ep_np) { of_graph_parse_endpoint(ep_np, &ep); adv_info(state, "Endpoint %pOF on port %d", ep.local_node, ep.port); if (ep.port >= ADV748X_PORT_MAX) { adv_err(state, "Invalid endpoint %pOF on port %d", ep.local_node, ep.port); continue; } if (state->endpoints[ep.port]) { adv_err(state, "Multiple port endpoints are not supported"); continue; } of_node_get(ep_np); state->endpoints[ep.port] = ep_np; /* * At least one input endpoint and one output endpoint shall * be defined. */ if (ep.port < ADV748X_PORT_TXA) in_found = true; else out_found = true; /* Store number of CSI-2 lanes used for TXA and TXB. */ ret = adv748x_parse_csi2_lanes(state, ep.port, ep_np); if (ret) return ret; } return in_found && out_found ? 0 : -ENODEV; } static void adv748x_dt_cleanup(struct adv748x_state *state) { unsigned int i; for (i = 0; i < ADV748X_PORT_MAX; i++) of_node_put(state->endpoints[i]); } static int adv748x_probe(struct i2c_client *client) { struct adv748x_state *state; int ret; /* Check if the adapter supports the needed features */ if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE_DATA)) return -EIO; state = devm_kzalloc(&client->dev, sizeof(*state), GFP_KERNEL); if (!state) return -ENOMEM; mutex_init(&state->mutex); state->dev = &client->dev; state->client = client; state->i2c_clients[ADV748X_PAGE_IO] = client; i2c_set_clientdata(client, state); /* * We can not use container_of to get back to the state with two TXs; * Initialize the TXs's fields unconditionally on the endpoint * presence to access them later. */ state->txa.state = state->txb.state = state; state->txa.page = ADV748X_PAGE_TXA; state->txb.page = ADV748X_PAGE_TXB; state->txa.port = ADV748X_PORT_TXA; state->txb.port = ADV748X_PORT_TXB; /* Discover and process ports declared by the Device tree endpoints */ ret = adv748x_parse_dt(state); if (ret) { adv_err(state, "Failed to parse device tree"); goto err_free_mutex; } /* Configure IO Regmap region */ ret = adv748x_configure_regmap(state, ADV748X_PAGE_IO); if (ret) { adv_err(state, "Error configuring IO regmap region"); goto err_cleanup_dt; } ret = adv748x_identify_chip(state); if (ret) { adv_err(state, "Failed to identify chip"); goto err_cleanup_dt; } /* Configure remaining pages as I2C clients with regmap access */ ret = adv748x_initialise_clients(state); if (ret) { adv_err(state, "Failed to setup client regmap pages"); goto err_cleanup_clients; } /* SW reset ADV748X to its default values */ ret = adv748x_reset(state); if (ret) { adv_err(state, "Failed to reset hardware"); goto err_cleanup_clients; } /* Initialise HDMI */ ret = adv748x_hdmi_init(&state->hdmi); if (ret) { adv_err(state, "Failed to probe HDMI"); goto err_cleanup_clients; } /* Initialise AFE */ ret = adv748x_afe_init(&state->afe); if (ret) { adv_err(state, "Failed to probe AFE"); goto err_cleanup_hdmi; } /* Initialise TXA */ ret = adv748x_csi2_init(state, &state->txa); if (ret) { adv_err(state, "Failed to probe TXA"); goto err_cleanup_afe; } /* Initialise TXB */ ret = adv748x_csi2_init(state, &state->txb); if (ret) { adv_err(state, "Failed to probe TXB"); goto err_cleanup_txa; } return 0; err_cleanup_txa: adv748x_csi2_cleanup(&state->txa); err_cleanup_afe: adv748x_afe_cleanup(&state->afe); err_cleanup_hdmi: adv748x_hdmi_cleanup(&state->hdmi); err_cleanup_clients: adv748x_unregister_clients(state); err_cleanup_dt: adv748x_dt_cleanup(state); err_free_mutex: mutex_destroy(&state->mutex); return ret; } static void adv748x_remove(struct i2c_client *client) { struct adv748x_state *state = i2c_get_clientdata(client); adv748x_afe_cleanup(&state->afe); adv748x_hdmi_cleanup(&state->hdmi); adv748x_csi2_cleanup(&state->txa); adv748x_csi2_cleanup(&state->txb); adv748x_unregister_clients(state); adv748x_dt_cleanup(state); mutex_destroy(&state->mutex); } static const struct of_device_id adv748x_of_table[] = { { .compatible = "adi,adv7481", }, { .compatible = "adi,adv7482", }, { } }; MODULE_DEVICE_TABLE(of, adv748x_of_table); static const struct dev_pm_ops adv748x_pm_ops = { SET_LATE_SYSTEM_SLEEP_PM_OPS(NULL, adv748x_resume_early) }; static struct i2c_driver adv748x_driver = { .driver = { .name = "adv748x", .of_match_table = adv748x_of_table, .pm = &adv748x_pm_ops, }, .probe = adv748x_probe, .remove = adv748x_remove, }; module_i2c_driver(adv748x_driver); MODULE_AUTHOR("Kieran Bingham <[email protected]>"); MODULE_DESCRIPTION("ADV748X video decoder"); MODULE_LICENSE("GPL");
linux-master
drivers/media/i2c/adv748x/adv748x-core.c
// SPDX-License-Identifier: GPL-2.0+ /* * Driver for Analog Devices ADV748X CSI-2 Transmitter * * Copyright (C) 2017 Renesas Electronics Corp. */ #include <linux/module.h> #include <linux/mutex.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-device.h> #include <media/v4l2-ioctl.h> #include "adv748x.h" int adv748x_csi2_set_virtual_channel(struct adv748x_csi2 *tx, unsigned int vc) { return tx_write(tx, ADV748X_CSI_VC_REF, vc << ADV748X_CSI_VC_REF_SHIFT); } /** * adv748x_csi2_register_link : Register and link internal entities * * @tx: CSI2 private entity * @v4l2_dev: Video registration device * @src: Source subdevice to establish link * @src_pad: Pad number of source to link to this @tx * @enable: Link enabled flag * * Ensure that the subdevice is registered against the v4l2_device, and link the * source pad to the sink pad of the CSI2 bus entity. */ static int adv748x_csi2_register_link(struct adv748x_csi2 *tx, struct v4l2_device *v4l2_dev, struct v4l2_subdev *src, unsigned int src_pad, bool enable) { int ret; if (!src->v4l2_dev) { ret = v4l2_device_register_subdev(v4l2_dev, src); if (ret) return ret; } ret = media_create_pad_link(&src->entity, src_pad, &tx->sd.entity, ADV748X_CSI2_SINK, enable ? MEDIA_LNK_FL_ENABLED : 0); if (ret) return ret; if (enable) tx->src = src; return 0; } /* ----------------------------------------------------------------------------- * v4l2_subdev_internal_ops * * We use the internal registered operation to be able to ensure that our * incremental subdevices (not connected in the forward path) can be registered * against the resulting video path and media device. */ static int adv748x_csi2_registered(struct v4l2_subdev *sd) { struct adv748x_csi2 *tx = adv748x_sd_to_csi2(sd); struct adv748x_state *state = tx->state; int ret; adv_dbg(state, "Registered %s (%s)", is_txa(tx) ? "TXA":"TXB", sd->name); /* * Link TXA to AFE and HDMI, and TXB to AFE only as TXB cannot output * HDMI. * * The HDMI->TXA link is enabled by default, as is the AFE->TXB one. */ if (is_afe_enabled(state)) { ret = adv748x_csi2_register_link(tx, sd->v4l2_dev, &state->afe.sd, ADV748X_AFE_SOURCE, is_txb(tx)); if (ret) return ret; /* TXB can output AFE signals only. */ if (is_txb(tx)) state->afe.tx = tx; } /* Register link to HDMI for TXA only. */ if (is_txb(tx) || !is_hdmi_enabled(state)) return 0; ret = adv748x_csi2_register_link(tx, sd->v4l2_dev, &state->hdmi.sd, ADV748X_HDMI_SOURCE, true); if (ret) return ret; /* The default HDMI output is TXA. */ state->hdmi.tx = tx; return 0; } static const struct v4l2_subdev_internal_ops adv748x_csi2_internal_ops = { .registered = adv748x_csi2_registered, }; /* ----------------------------------------------------------------------------- * v4l2_subdev_video_ops */ static int adv748x_csi2_s_stream(struct v4l2_subdev *sd, int enable) { struct adv748x_csi2 *tx = adv748x_sd_to_csi2(sd); struct v4l2_subdev *src; src = adv748x_get_remote_sd(&tx->pads[ADV748X_CSI2_SINK]); if (!src) return -EPIPE; return v4l2_subdev_call(src, video, s_stream, enable); } static const struct v4l2_subdev_video_ops adv748x_csi2_video_ops = { .s_stream = adv748x_csi2_s_stream, }; /* ----------------------------------------------------------------------------- * v4l2_subdev_pad_ops * * The CSI2 bus pads are ignorant to the data sizes or formats. * But we must support setting the pad formats for format propagation. */ static struct v4l2_mbus_framefmt * adv748x_csi2_get_pad_format(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, unsigned int pad, u32 which) { struct adv748x_csi2 *tx = adv748x_sd_to_csi2(sd); if (which == V4L2_SUBDEV_FORMAT_TRY) return v4l2_subdev_get_try_format(sd, sd_state, pad); return &tx->format; } static int adv748x_csi2_get_format(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *sdformat) { struct adv748x_csi2 *tx = adv748x_sd_to_csi2(sd); struct adv748x_state *state = tx->state; struct v4l2_mbus_framefmt *mbusformat; mbusformat = adv748x_csi2_get_pad_format(sd, sd_state, sdformat->pad, sdformat->which); if (!mbusformat) return -EINVAL; mutex_lock(&state->mutex); sdformat->format = *mbusformat; mutex_unlock(&state->mutex); return 0; } static int adv748x_csi2_set_format(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *sdformat) { struct adv748x_csi2 *tx = adv748x_sd_to_csi2(sd); struct adv748x_state *state = tx->state; struct v4l2_mbus_framefmt *mbusformat; int ret = 0; mbusformat = adv748x_csi2_get_pad_format(sd, sd_state, sdformat->pad, sdformat->which); if (!mbusformat) return -EINVAL; mutex_lock(&state->mutex); if (sdformat->pad == ADV748X_CSI2_SOURCE) { const struct v4l2_mbus_framefmt *sink_fmt; sink_fmt = adv748x_csi2_get_pad_format(sd, sd_state, ADV748X_CSI2_SINK, sdformat->which); if (!sink_fmt) { ret = -EINVAL; goto unlock; } sdformat->format = *sink_fmt; } *mbusformat = sdformat->format; unlock: mutex_unlock(&state->mutex); return ret; } static int adv748x_csi2_get_mbus_config(struct v4l2_subdev *sd, unsigned int pad, struct v4l2_mbus_config *config) { struct adv748x_csi2 *tx = adv748x_sd_to_csi2(sd); if (pad != ADV748X_CSI2_SOURCE) return -EINVAL; config->type = V4L2_MBUS_CSI2_DPHY; config->bus.mipi_csi2.num_data_lanes = tx->active_lanes; return 0; } static const struct v4l2_subdev_pad_ops adv748x_csi2_pad_ops = { .get_fmt = adv748x_csi2_get_format, .set_fmt = adv748x_csi2_set_format, .get_mbus_config = adv748x_csi2_get_mbus_config, }; /* ----------------------------------------------------------------------------- * v4l2_subdev_ops */ static const struct v4l2_subdev_ops adv748x_csi2_ops = { .video = &adv748x_csi2_video_ops, .pad = &adv748x_csi2_pad_ops, }; /* ----------------------------------------------------------------------------- * Subdev module and controls */ int adv748x_csi2_set_pixelrate(struct v4l2_subdev *sd, s64 rate) { struct adv748x_csi2 *tx = adv748x_sd_to_csi2(sd); if (!tx->pixel_rate) return -EINVAL; return v4l2_ctrl_s_ctrl_int64(tx->pixel_rate, rate); } static int adv748x_csi2_s_ctrl(struct v4l2_ctrl *ctrl) { switch (ctrl->id) { case V4L2_CID_PIXEL_RATE: return 0; default: return -EINVAL; } } static const struct v4l2_ctrl_ops adv748x_csi2_ctrl_ops = { .s_ctrl = adv748x_csi2_s_ctrl, }; static int adv748x_csi2_init_controls(struct adv748x_csi2 *tx) { v4l2_ctrl_handler_init(&tx->ctrl_hdl, 1); tx->pixel_rate = v4l2_ctrl_new_std(&tx->ctrl_hdl, &adv748x_csi2_ctrl_ops, V4L2_CID_PIXEL_RATE, 1, INT_MAX, 1, 1); tx->sd.ctrl_handler = &tx->ctrl_hdl; if (tx->ctrl_hdl.error) { v4l2_ctrl_handler_free(&tx->ctrl_hdl); return tx->ctrl_hdl.error; } return v4l2_ctrl_handler_setup(&tx->ctrl_hdl); } int adv748x_csi2_init(struct adv748x_state *state, struct adv748x_csi2 *tx) { int ret; if (!is_tx_enabled(tx)) return 0; adv748x_subdev_init(&tx->sd, state, &adv748x_csi2_ops, MEDIA_ENT_F_VID_IF_BRIDGE, is_txa(tx) ? "txa" : "txb"); /* Register internal ops for incremental subdev registration */ tx->sd.internal_ops = &adv748x_csi2_internal_ops; tx->pads[ADV748X_CSI2_SINK].flags = MEDIA_PAD_FL_SINK; tx->pads[ADV748X_CSI2_SOURCE].flags = MEDIA_PAD_FL_SOURCE; ret = media_entity_pads_init(&tx->sd.entity, ADV748X_CSI2_NR_PADS, tx->pads); if (ret) return ret; ret = v4l2_async_subdev_endpoint_add(&tx->sd, of_fwnode_handle(state->endpoints[tx->port])); if (ret) goto err_free_media; ret = adv748x_csi2_init_controls(tx); if (ret) goto err_cleanup_subdev; ret = v4l2_async_register_subdev(&tx->sd); if (ret) goto err_free_ctrl; return 0; err_free_ctrl: v4l2_ctrl_handler_free(&tx->ctrl_hdl); err_cleanup_subdev: v4l2_subdev_cleanup(&tx->sd); err_free_media: media_entity_cleanup(&tx->sd.entity); return ret; } void adv748x_csi2_cleanup(struct adv748x_csi2 *tx) { if (!is_tx_enabled(tx)) return; v4l2_async_unregister_subdev(&tx->sd); media_entity_cleanup(&tx->sd.entity); v4l2_ctrl_handler_free(&tx->ctrl_hdl); v4l2_subdev_cleanup(&tx->sd); }
linux-master
drivers/media/i2c/adv748x/adv748x-csi2.c
// SPDX-License-Identifier: GPL-2.0+ /* * Driver for Analog Devices ADV748X HDMI receiver and Component Processor (CP) * * Copyright (C) 2017 Renesas Electronics Corp. */ #include <linux/module.h> #include <linux/mutex.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-device.h> #include <media/v4l2-dv-timings.h> #include <media/v4l2-ioctl.h> #include <uapi/linux/v4l2-dv-timings.h> #include "adv748x.h" /* ----------------------------------------------------------------------------- * HDMI and CP */ #define ADV748X_HDMI_MIN_WIDTH 640 #define ADV748X_HDMI_MAX_WIDTH 1920 #define ADV748X_HDMI_MIN_HEIGHT 480 #define ADV748X_HDMI_MAX_HEIGHT 1200 /* V4L2_DV_BT_CEA_720X480I59_94 - 0.5 MHz */ #define ADV748X_HDMI_MIN_PIXELCLOCK 13000000 /* V4L2_DV_BT_DMT_1600X1200P60 */ #define ADV748X_HDMI_MAX_PIXELCLOCK 162000000 static const struct v4l2_dv_timings_cap adv748x_hdmi_timings_cap = { .type = V4L2_DV_BT_656_1120, /* keep this initialization for compatibility with GCC < 4.4.6 */ .reserved = { 0 }, V4L2_INIT_BT_TIMINGS(ADV748X_HDMI_MIN_WIDTH, ADV748X_HDMI_MAX_WIDTH, ADV748X_HDMI_MIN_HEIGHT, ADV748X_HDMI_MAX_HEIGHT, ADV748X_HDMI_MIN_PIXELCLOCK, ADV748X_HDMI_MAX_PIXELCLOCK, V4L2_DV_BT_STD_CEA861 | V4L2_DV_BT_STD_DMT, V4L2_DV_BT_CAP_PROGRESSIVE) }; struct adv748x_hdmi_video_standards { struct v4l2_dv_timings timings; u8 vid_std; u8 v_freq; }; static const struct adv748x_hdmi_video_standards adv748x_hdmi_video_standards[] = { { V4L2_DV_BT_CEA_720X480P59_94, 0x4a, 0x00 }, { V4L2_DV_BT_CEA_720X576P50, 0x4b, 0x00 }, { V4L2_DV_BT_CEA_1280X720P60, 0x53, 0x00 }, { V4L2_DV_BT_CEA_1280X720P50, 0x53, 0x01 }, { V4L2_DV_BT_CEA_1280X720P30, 0x53, 0x02 }, { V4L2_DV_BT_CEA_1280X720P25, 0x53, 0x03 }, { V4L2_DV_BT_CEA_1280X720P24, 0x53, 0x04 }, { V4L2_DV_BT_CEA_1920X1080P60, 0x5e, 0x00 }, { V4L2_DV_BT_CEA_1920X1080P50, 0x5e, 0x01 }, { V4L2_DV_BT_CEA_1920X1080P30, 0x5e, 0x02 }, { V4L2_DV_BT_CEA_1920X1080P25, 0x5e, 0x03 }, { V4L2_DV_BT_CEA_1920X1080P24, 0x5e, 0x04 }, /* SVGA */ { V4L2_DV_BT_DMT_800X600P56, 0x80, 0x00 }, { V4L2_DV_BT_DMT_800X600P60, 0x81, 0x00 }, { V4L2_DV_BT_DMT_800X600P72, 0x82, 0x00 }, { V4L2_DV_BT_DMT_800X600P75, 0x83, 0x00 }, { V4L2_DV_BT_DMT_800X600P85, 0x84, 0x00 }, /* SXGA */ { V4L2_DV_BT_DMT_1280X1024P60, 0x85, 0x00 }, { V4L2_DV_BT_DMT_1280X1024P75, 0x86, 0x00 }, /* VGA */ { V4L2_DV_BT_DMT_640X480P60, 0x88, 0x00 }, { V4L2_DV_BT_DMT_640X480P72, 0x89, 0x00 }, { V4L2_DV_BT_DMT_640X480P75, 0x8a, 0x00 }, { V4L2_DV_BT_DMT_640X480P85, 0x8b, 0x00 }, /* XGA */ { V4L2_DV_BT_DMT_1024X768P60, 0x8c, 0x00 }, { V4L2_DV_BT_DMT_1024X768P70, 0x8d, 0x00 }, { V4L2_DV_BT_DMT_1024X768P75, 0x8e, 0x00 }, { V4L2_DV_BT_DMT_1024X768P85, 0x8f, 0x00 }, /* UXGA */ { V4L2_DV_BT_DMT_1600X1200P60, 0x96, 0x00 }, }; static void adv748x_hdmi_fill_format(struct adv748x_hdmi *hdmi, struct v4l2_mbus_framefmt *fmt) { memset(fmt, 0, sizeof(*fmt)); fmt->code = MEDIA_BUS_FMT_RGB888_1X24; fmt->field = hdmi->timings.bt.interlaced ? V4L2_FIELD_ALTERNATE : V4L2_FIELD_NONE; /* TODO: The colorspace depends on the AVI InfoFrame contents */ fmt->colorspace = V4L2_COLORSPACE_SRGB; fmt->width = hdmi->timings.bt.width; fmt->height = hdmi->timings.bt.height; if (fmt->field == V4L2_FIELD_ALTERNATE) fmt->height /= 2; } static void adv748x_fill_optional_dv_timings(struct v4l2_dv_timings *timings) { v4l2_find_dv_timings_cap(timings, &adv748x_hdmi_timings_cap, 250000, NULL, NULL); } static bool adv748x_hdmi_has_signal(struct adv748x_state *state) { int val; /* Check that VERT_FILTER and DE_REGEN is locked */ val = hdmi_read(state, ADV748X_HDMI_LW1); return (val & ADV748X_HDMI_LW1_VERT_FILTER) && (val & ADV748X_HDMI_LW1_DE_REGEN); } static int adv748x_hdmi_read_pixelclock(struct adv748x_state *state) { int a, b; a = hdmi_read(state, ADV748X_HDMI_TMDS_1); b = hdmi_read(state, ADV748X_HDMI_TMDS_2); if (a < 0 || b < 0) return -ENODATA; /* * The high 9 bits store TMDS frequency measurement in MHz * The low 7 bits of TMDS_2 store the 7-bit TMDS fractional frequency * measurement in 1/128 MHz */ return ((a << 1) | (b >> 7)) * 1000000 + (b & 0x7f) * 1000000 / 128; } /* * adv748x_hdmi_set_de_timings: Adjust horizontal picture offset through DE * * HDMI CP uses a Data Enable synchronisation timing reference * * Vary the leading and trailing edge position of the DE signal output by the CP * core. Values are stored as signed-twos-complement in one-pixel-clock units * * The start and end are shifted equally by the 10-bit shift value. */ static void adv748x_hdmi_set_de_timings(struct adv748x_state *state, int shift) { u8 high, low; /* POS_HIGH stores bits 8 and 9 of both the start and end */ high = ADV748X_CP_DE_POS_HIGH_SET; high |= (shift & 0x300) >> 8; low = shift & 0xff; /* The sequence of the writes is important and must be followed */ cp_write(state, ADV748X_CP_DE_POS_HIGH, high); cp_write(state, ADV748X_CP_DE_POS_END_LOW, low); high |= (shift & 0x300) >> 6; cp_write(state, ADV748X_CP_DE_POS_HIGH, high); cp_write(state, ADV748X_CP_DE_POS_START_LOW, low); } static int adv748x_hdmi_set_video_timings(struct adv748x_state *state, const struct v4l2_dv_timings *timings) { const struct adv748x_hdmi_video_standards *stds = adv748x_hdmi_video_standards; unsigned int i; for (i = 0; i < ARRAY_SIZE(adv748x_hdmi_video_standards); i++) { if (v4l2_match_dv_timings(timings, &stds[i].timings, 250000, false)) break; } if (i >= ARRAY_SIZE(adv748x_hdmi_video_standards)) return -EINVAL; /* * When setting cp_vid_std to either 720p, 1080i, or 1080p, the video * will get shifted horizontally to the left in active video mode. * The de_h_start and de_h_end controls are used to centre the picture * correctly */ switch (stds[i].vid_std) { case 0x53: /* 720p */ adv748x_hdmi_set_de_timings(state, -40); break; case 0x54: /* 1080i */ case 0x5e: /* 1080p */ adv748x_hdmi_set_de_timings(state, -44); break; default: adv748x_hdmi_set_de_timings(state, 0); break; } io_write(state, ADV748X_IO_VID_STD, stds[i].vid_std); io_clrset(state, ADV748X_IO_DATAPATH, ADV748X_IO_DATAPATH_VFREQ_M, stds[i].v_freq << ADV748X_IO_DATAPATH_VFREQ_SHIFT); return 0; } /* ----------------------------------------------------------------------------- * v4l2_subdev_video_ops */ static int adv748x_hdmi_s_dv_timings(struct v4l2_subdev *sd, struct v4l2_dv_timings *timings) { struct adv748x_hdmi *hdmi = adv748x_sd_to_hdmi(sd); struct adv748x_state *state = adv748x_hdmi_to_state(hdmi); int ret; if (!timings) return -EINVAL; if (v4l2_match_dv_timings(&hdmi->timings, timings, 0, false)) return 0; if (!v4l2_valid_dv_timings(timings, &adv748x_hdmi_timings_cap, NULL, NULL)) return -ERANGE; adv748x_fill_optional_dv_timings(timings); mutex_lock(&state->mutex); ret = adv748x_hdmi_set_video_timings(state, timings); if (ret) goto error; hdmi->timings = *timings; cp_clrset(state, ADV748X_CP_VID_ADJ_2, ADV748X_CP_VID_ADJ_2_INTERLACED, timings->bt.interlaced ? ADV748X_CP_VID_ADJ_2_INTERLACED : 0); mutex_unlock(&state->mutex); return 0; error: mutex_unlock(&state->mutex); return ret; } static int adv748x_hdmi_g_dv_timings(struct v4l2_subdev *sd, struct v4l2_dv_timings *timings) { struct adv748x_hdmi *hdmi = adv748x_sd_to_hdmi(sd); struct adv748x_state *state = adv748x_hdmi_to_state(hdmi); mutex_lock(&state->mutex); *timings = hdmi->timings; mutex_unlock(&state->mutex); return 0; } static int adv748x_hdmi_query_dv_timings(struct v4l2_subdev *sd, struct v4l2_dv_timings *timings) { struct adv748x_hdmi *hdmi = adv748x_sd_to_hdmi(sd); struct adv748x_state *state = adv748x_hdmi_to_state(hdmi); struct v4l2_bt_timings *bt = &timings->bt; int pixelclock; int polarity; if (!timings) return -EINVAL; memset(timings, 0, sizeof(struct v4l2_dv_timings)); /* * If the pattern generator is enabled the device shall not be queried * for timings. Instead the timings programmed shall be reported as they * are the ones being used to generate the pattern. */ if (cp_read(state, ADV748X_CP_PAT_GEN) & ADV748X_CP_PAT_GEN_EN) { *timings = hdmi->timings; return 0; } if (!adv748x_hdmi_has_signal(state)) return -ENOLINK; pixelclock = adv748x_hdmi_read_pixelclock(state); if (pixelclock < 0) return -ENODATA; timings->type = V4L2_DV_BT_656_1120; bt->pixelclock = pixelclock; bt->interlaced = hdmi_read(state, ADV748X_HDMI_F1H1) & ADV748X_HDMI_F1H1_INTERLACED ? V4L2_DV_INTERLACED : V4L2_DV_PROGRESSIVE; bt->width = hdmi_read16(state, ADV748X_HDMI_LW1, ADV748X_HDMI_LW1_WIDTH_MASK); bt->height = hdmi_read16(state, ADV748X_HDMI_F0H1, ADV748X_HDMI_F0H1_HEIGHT_MASK); bt->hfrontporch = hdmi_read16(state, ADV748X_HDMI_HFRONT_PORCH, ADV748X_HDMI_HFRONT_PORCH_MASK); bt->hsync = hdmi_read16(state, ADV748X_HDMI_HSYNC_WIDTH, ADV748X_HDMI_HSYNC_WIDTH_MASK); bt->hbackporch = hdmi_read16(state, ADV748X_HDMI_HBACK_PORCH, ADV748X_HDMI_HBACK_PORCH_MASK); bt->vfrontporch = hdmi_read16(state, ADV748X_HDMI_VFRONT_PORCH, ADV748X_HDMI_VFRONT_PORCH_MASK) / 2; bt->vsync = hdmi_read16(state, ADV748X_HDMI_VSYNC_WIDTH, ADV748X_HDMI_VSYNC_WIDTH_MASK) / 2; bt->vbackporch = hdmi_read16(state, ADV748X_HDMI_VBACK_PORCH, ADV748X_HDMI_VBACK_PORCH_MASK) / 2; polarity = hdmi_read(state, 0x05); bt->polarities = (polarity & BIT(4) ? V4L2_DV_VSYNC_POS_POL : 0) | (polarity & BIT(5) ? V4L2_DV_HSYNC_POS_POL : 0); if (bt->interlaced == V4L2_DV_INTERLACED) { bt->height += hdmi_read16(state, 0x0b, 0x1fff); bt->il_vfrontporch = hdmi_read16(state, 0x2c, 0x3fff) / 2; bt->il_vsync = hdmi_read16(state, 0x30, 0x3fff) / 2; bt->il_vbackporch = hdmi_read16(state, 0x34, 0x3fff) / 2; } adv748x_fill_optional_dv_timings(timings); /* * No interrupt handling is implemented yet. * There should be an IRQ when a cable is plugged and the new timings * should be figured out and stored to state. */ hdmi->timings = *timings; return 0; } static int adv748x_hdmi_g_input_status(struct v4l2_subdev *sd, u32 *status) { struct adv748x_hdmi *hdmi = adv748x_sd_to_hdmi(sd); struct adv748x_state *state = adv748x_hdmi_to_state(hdmi); mutex_lock(&state->mutex); *status = adv748x_hdmi_has_signal(state) ? 0 : V4L2_IN_ST_NO_SIGNAL; mutex_unlock(&state->mutex); return 0; } static int adv748x_hdmi_s_stream(struct v4l2_subdev *sd, int enable) { struct adv748x_hdmi *hdmi = adv748x_sd_to_hdmi(sd); struct adv748x_state *state = adv748x_hdmi_to_state(hdmi); int ret; mutex_lock(&state->mutex); ret = adv748x_tx_power(hdmi->tx, enable); if (ret) goto done; if (adv748x_hdmi_has_signal(state)) adv_dbg(state, "Detected HDMI signal\n"); else adv_dbg(state, "Couldn't detect HDMI video signal\n"); done: mutex_unlock(&state->mutex); return ret; } static int adv748x_hdmi_g_pixelaspect(struct v4l2_subdev *sd, struct v4l2_fract *aspect) { aspect->numerator = 1; aspect->denominator = 1; return 0; } static const struct v4l2_subdev_video_ops adv748x_video_ops_hdmi = { .s_dv_timings = adv748x_hdmi_s_dv_timings, .g_dv_timings = adv748x_hdmi_g_dv_timings, .query_dv_timings = adv748x_hdmi_query_dv_timings, .g_input_status = adv748x_hdmi_g_input_status, .s_stream = adv748x_hdmi_s_stream, .g_pixelaspect = adv748x_hdmi_g_pixelaspect, }; /* ----------------------------------------------------------------------------- * v4l2_subdev_pad_ops */ static int adv748x_hdmi_propagate_pixelrate(struct adv748x_hdmi *hdmi) { struct v4l2_subdev *tx; struct v4l2_dv_timings timings; tx = adv748x_get_remote_sd(&hdmi->pads[ADV748X_HDMI_SOURCE]); if (!tx) return -ENOLINK; adv748x_hdmi_query_dv_timings(&hdmi->sd, &timings); return adv748x_csi2_set_pixelrate(tx, timings.bt.pixelclock); } static int adv748x_hdmi_enum_mbus_code(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_mbus_code_enum *code) { if (code->index != 0) return -EINVAL; code->code = MEDIA_BUS_FMT_RGB888_1X24; return 0; } static int adv748x_hdmi_get_format(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *sdformat) { struct adv748x_hdmi *hdmi = adv748x_sd_to_hdmi(sd); struct v4l2_mbus_framefmt *mbusformat; if (sdformat->pad != ADV748X_HDMI_SOURCE) return -EINVAL; if (sdformat->which == V4L2_SUBDEV_FORMAT_TRY) { mbusformat = v4l2_subdev_get_try_format(sd, sd_state, sdformat->pad); sdformat->format = *mbusformat; } else { adv748x_hdmi_fill_format(hdmi, &sdformat->format); adv748x_hdmi_propagate_pixelrate(hdmi); } return 0; } static int adv748x_hdmi_set_format(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *sdformat) { struct v4l2_mbus_framefmt *mbusformat; if (sdformat->pad != ADV748X_HDMI_SOURCE) return -EINVAL; if (sdformat->which == V4L2_SUBDEV_FORMAT_ACTIVE) return adv748x_hdmi_get_format(sd, sd_state, sdformat); mbusformat = v4l2_subdev_get_try_format(sd, sd_state, sdformat->pad); *mbusformat = sdformat->format; return 0; } static int adv748x_hdmi_get_edid(struct v4l2_subdev *sd, struct v4l2_edid *edid) { struct adv748x_hdmi *hdmi = adv748x_sd_to_hdmi(sd); memset(edid->reserved, 0, sizeof(edid->reserved)); if (!hdmi->edid.present) return -ENODATA; if (edid->start_block == 0 && edid->blocks == 0) { edid->blocks = hdmi->edid.blocks; return 0; } if (edid->start_block >= hdmi->edid.blocks) return -EINVAL; if (edid->start_block + edid->blocks > hdmi->edid.blocks) edid->blocks = hdmi->edid.blocks - edid->start_block; memcpy(edid->edid, hdmi->edid.edid + edid->start_block * 128, edid->blocks * 128); return 0; } static inline int adv748x_hdmi_edid_write_block(struct adv748x_hdmi *hdmi, unsigned int total_len, const u8 *val) { struct adv748x_state *state = adv748x_hdmi_to_state(hdmi); int err = 0; int i = 0; int len = 0; adv_dbg(state, "%s: write EDID block (%d byte)\n", __func__, total_len); while (!err && i < total_len) { len = (total_len - i) > I2C_SMBUS_BLOCK_MAX ? I2C_SMBUS_BLOCK_MAX : (total_len - i); err = adv748x_write_block(state, ADV748X_PAGE_EDID, i, val + i, len); i += len; } return err; } static int adv748x_hdmi_set_edid(struct v4l2_subdev *sd, struct v4l2_edid *edid) { struct adv748x_hdmi *hdmi = adv748x_sd_to_hdmi(sd); struct adv748x_state *state = adv748x_hdmi_to_state(hdmi); int err; memset(edid->reserved, 0, sizeof(edid->reserved)); if (edid->start_block != 0) return -EINVAL; if (edid->blocks == 0) { hdmi->edid.blocks = 0; hdmi->edid.present = 0; /* Fall back to a 16:9 aspect ratio */ hdmi->aspect_ratio.numerator = 16; hdmi->aspect_ratio.denominator = 9; /* Disable the EDID */ repeater_write(state, ADV748X_REPEATER_EDID_SZ, edid->blocks << ADV748X_REPEATER_EDID_SZ_SHIFT); repeater_write(state, ADV748X_REPEATER_EDID_CTL, 0); return 0; } if (edid->blocks > 4) { edid->blocks = 4; return -E2BIG; } memcpy(hdmi->edid.edid, edid->edid, 128 * edid->blocks); hdmi->edid.blocks = edid->blocks; hdmi->edid.present = true; hdmi->aspect_ratio = v4l2_calc_aspect_ratio(edid->edid[0x15], edid->edid[0x16]); err = adv748x_hdmi_edid_write_block(hdmi, 128 * edid->blocks, hdmi->edid.edid); if (err < 0) { v4l2_err(sd, "error %d writing edid pad %d\n", err, edid->pad); return err; } repeater_write(state, ADV748X_REPEATER_EDID_SZ, edid->blocks << ADV748X_REPEATER_EDID_SZ_SHIFT); repeater_write(state, ADV748X_REPEATER_EDID_CTL, ADV748X_REPEATER_EDID_CTL_EN); return 0; } static bool adv748x_hdmi_check_dv_timings(const struct v4l2_dv_timings *timings, void *hdl) { const struct adv748x_hdmi_video_standards *stds = adv748x_hdmi_video_standards; unsigned int i; for (i = 0; stds[i].timings.bt.width; i++) if (v4l2_match_dv_timings(timings, &stds[i].timings, 0, false)) return true; return false; } static int adv748x_hdmi_enum_dv_timings(struct v4l2_subdev *sd, struct v4l2_enum_dv_timings *timings) { return v4l2_enum_dv_timings_cap(timings, &adv748x_hdmi_timings_cap, adv748x_hdmi_check_dv_timings, NULL); } static int adv748x_hdmi_dv_timings_cap(struct v4l2_subdev *sd, struct v4l2_dv_timings_cap *cap) { *cap = adv748x_hdmi_timings_cap; return 0; } static const struct v4l2_subdev_pad_ops adv748x_pad_ops_hdmi = { .enum_mbus_code = adv748x_hdmi_enum_mbus_code, .set_fmt = adv748x_hdmi_set_format, .get_fmt = adv748x_hdmi_get_format, .get_edid = adv748x_hdmi_get_edid, .set_edid = adv748x_hdmi_set_edid, .dv_timings_cap = adv748x_hdmi_dv_timings_cap, .enum_dv_timings = adv748x_hdmi_enum_dv_timings, }; /* ----------------------------------------------------------------------------- * v4l2_subdev_ops */ static const struct v4l2_subdev_ops adv748x_ops_hdmi = { .video = &adv748x_video_ops_hdmi, .pad = &adv748x_pad_ops_hdmi, }; /* ----------------------------------------------------------------------------- * Controls */ static const char * const hdmi_ctrl_patgen_menu[] = { "Disabled", "Solid Color", "Color Bars", "Ramp Grey", "Ramp Blue", "Ramp Red", "Checkered" }; static int adv748x_hdmi_s_ctrl(struct v4l2_ctrl *ctrl) { struct adv748x_hdmi *hdmi = adv748x_ctrl_to_hdmi(ctrl); struct adv748x_state *state = adv748x_hdmi_to_state(hdmi); int ret; u8 pattern; /* Enable video adjustment first */ ret = cp_clrset(state, ADV748X_CP_VID_ADJ, ADV748X_CP_VID_ADJ_ENABLE, ADV748X_CP_VID_ADJ_ENABLE); if (ret < 0) return ret; switch (ctrl->id) { case V4L2_CID_BRIGHTNESS: ret = cp_write(state, ADV748X_CP_BRI, ctrl->val); break; case V4L2_CID_HUE: ret = cp_write(state, ADV748X_CP_HUE, ctrl->val); break; case V4L2_CID_CONTRAST: ret = cp_write(state, ADV748X_CP_CON, ctrl->val); break; case V4L2_CID_SATURATION: ret = cp_write(state, ADV748X_CP_SAT, ctrl->val); break; case V4L2_CID_TEST_PATTERN: pattern = ctrl->val; /* Pattern is 0-indexed. Ctrl Menu is 1-indexed */ if (pattern) { pattern--; pattern |= ADV748X_CP_PAT_GEN_EN; } ret = cp_write(state, ADV748X_CP_PAT_GEN, pattern); break; default: return -EINVAL; } return ret; } static const struct v4l2_ctrl_ops adv748x_hdmi_ctrl_ops = { .s_ctrl = adv748x_hdmi_s_ctrl, }; static int adv748x_hdmi_init_controls(struct adv748x_hdmi *hdmi) { struct adv748x_state *state = adv748x_hdmi_to_state(hdmi); v4l2_ctrl_handler_init(&hdmi->ctrl_hdl, 5); /* Use our mutex for the controls */ hdmi->ctrl_hdl.lock = &state->mutex; v4l2_ctrl_new_std(&hdmi->ctrl_hdl, &adv748x_hdmi_ctrl_ops, V4L2_CID_BRIGHTNESS, ADV748X_CP_BRI_MIN, ADV748X_CP_BRI_MAX, 1, ADV748X_CP_BRI_DEF); v4l2_ctrl_new_std(&hdmi->ctrl_hdl, &adv748x_hdmi_ctrl_ops, V4L2_CID_CONTRAST, ADV748X_CP_CON_MIN, ADV748X_CP_CON_MAX, 1, ADV748X_CP_CON_DEF); v4l2_ctrl_new_std(&hdmi->ctrl_hdl, &adv748x_hdmi_ctrl_ops, V4L2_CID_SATURATION, ADV748X_CP_SAT_MIN, ADV748X_CP_SAT_MAX, 1, ADV748X_CP_SAT_DEF); v4l2_ctrl_new_std(&hdmi->ctrl_hdl, &adv748x_hdmi_ctrl_ops, V4L2_CID_HUE, ADV748X_CP_HUE_MIN, ADV748X_CP_HUE_MAX, 1, ADV748X_CP_HUE_DEF); /* * Todo: V4L2_CID_DV_RX_POWER_PRESENT should also be supported when * interrupts are handled correctly */ v4l2_ctrl_new_std_menu_items(&hdmi->ctrl_hdl, &adv748x_hdmi_ctrl_ops, V4L2_CID_TEST_PATTERN, ARRAY_SIZE(hdmi_ctrl_patgen_menu) - 1, 0, 0, hdmi_ctrl_patgen_menu); hdmi->sd.ctrl_handler = &hdmi->ctrl_hdl; if (hdmi->ctrl_hdl.error) { v4l2_ctrl_handler_free(&hdmi->ctrl_hdl); return hdmi->ctrl_hdl.error; } return v4l2_ctrl_handler_setup(&hdmi->ctrl_hdl); } int adv748x_hdmi_init(struct adv748x_hdmi *hdmi) { struct adv748x_state *state = adv748x_hdmi_to_state(hdmi); struct v4l2_dv_timings cea1280x720 = V4L2_DV_BT_CEA_1280X720P30; int ret; adv748x_hdmi_s_dv_timings(&hdmi->sd, &cea1280x720); /* Initialise a default 16:9 aspect ratio */ hdmi->aspect_ratio.numerator = 16; hdmi->aspect_ratio.denominator = 9; adv748x_subdev_init(&hdmi->sd, state, &adv748x_ops_hdmi, MEDIA_ENT_F_IO_DTV, "hdmi"); hdmi->pads[ADV748X_HDMI_SINK].flags = MEDIA_PAD_FL_SINK; hdmi->pads[ADV748X_HDMI_SOURCE].flags = MEDIA_PAD_FL_SOURCE; ret = media_entity_pads_init(&hdmi->sd.entity, ADV748X_HDMI_NR_PADS, hdmi->pads); if (ret) return ret; ret = adv748x_hdmi_init_controls(hdmi); if (ret) goto err_free_media; return 0; err_free_media: media_entity_cleanup(&hdmi->sd.entity); return ret; } void adv748x_hdmi_cleanup(struct adv748x_hdmi *hdmi) { v4l2_device_unregister_subdev(&hdmi->sd); media_entity_cleanup(&hdmi->sd.entity); v4l2_ctrl_handler_free(&hdmi->ctrl_hdl); }
linux-master
drivers/media/i2c/adv748x/adv748x-hdmi.c
// SPDX-License-Identifier: GPL-2.0-or-later /* cx25840 - Conexant CX25840 audio/video decoder driver * * Copyright (C) 2004 Ulf Eklund * * Based on the saa7115 driver and on the first version of Chris Kennedy's * cx25840 driver. * * Changes by Tyler Trafford <[email protected]> * - cleanup/rewrite for V4L2 API (2005) * * VBI support by Hans Verkuil <[email protected]>. * * NTSC sliced VBI support by Christopher Neufeld <[email protected]> * with additional fixes by Hans Verkuil <[email protected]>. * * CX23885 support by Steven Toth <[email protected]>. * * CX2388[578] IRQ handling, IO Pin mux configuration and other small fixes are * Copyright (C) 2010 Andy Walls <[email protected]> * * CX23888 DIF support for the HVR1850 * Copyright (C) 2011 Steven Toth <[email protected]> * * CX2584x pin to pad mapping and output format configuration support are * Copyright (C) 2011 Maciej S. Szmigiero <[email protected]> */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/videodev2.h> #include <linux/i2c.h> #include <linux/delay.h> #include <linux/math64.h> #include <media/v4l2-common.h> #include <media/drv-intf/cx25840.h> #include "cx25840-core.h" MODULE_DESCRIPTION("Conexant CX25840 audio/video decoder driver"); MODULE_AUTHOR("Ulf Eklund, Chris Kennedy, Hans Verkuil, Tyler Trafford"); MODULE_LICENSE("GPL"); #define CX25840_VID_INT_STAT_REG 0x410 #define CX25840_VID_INT_STAT_BITS 0x0000ffff #define CX25840_VID_INT_MASK_BITS 0xffff0000 #define CX25840_VID_INT_MASK_SHFT 16 #define CX25840_VID_INT_MASK_REG 0x412 #define CX23885_AUD_MC_INT_MASK_REG 0x80c #define CX23885_AUD_MC_INT_STAT_BITS 0xffff0000 #define CX23885_AUD_MC_INT_CTRL_BITS 0x0000ffff #define CX23885_AUD_MC_INT_STAT_SHFT 16 #define CX25840_AUD_INT_CTRL_REG 0x812 #define CX25840_AUD_INT_STAT_REG 0x813 #define CX23885_PIN_CTRL_IRQ_REG 0x123 #define CX23885_PIN_CTRL_IRQ_IR_STAT 0x40 #define CX23885_PIN_CTRL_IRQ_AUD_STAT 0x20 #define CX23885_PIN_CTRL_IRQ_VID_STAT 0x10 #define CX25840_IR_STATS_REG 0x210 #define CX25840_IR_IRQEN_REG 0x214 static int cx25840_debug; module_param_named(debug, cx25840_debug, int, 0644); MODULE_PARM_DESC(debug, "Debugging messages [0=Off (default) 1=On]"); /* ----------------------------------------------------------------------- */ static void cx23888_std_setup(struct i2c_client *client); int cx25840_write(struct i2c_client *client, u16 addr, u8 value) { u8 buffer[3]; buffer[0] = addr >> 8; buffer[1] = addr & 0xff; buffer[2] = value; return i2c_master_send(client, buffer, 3); } int cx25840_write4(struct i2c_client *client, u16 addr, u32 value) { u8 buffer[6]; buffer[0] = addr >> 8; buffer[1] = addr & 0xff; buffer[2] = value & 0xff; buffer[3] = (value >> 8) & 0xff; buffer[4] = (value >> 16) & 0xff; buffer[5] = value >> 24; return i2c_master_send(client, buffer, 6); } u8 cx25840_read(struct i2c_client *client, u16 addr) { struct i2c_msg msgs[2]; u8 tx_buf[2], rx_buf[1]; /* Write register address */ tx_buf[0] = addr >> 8; tx_buf[1] = addr & 0xff; msgs[0].addr = client->addr; msgs[0].flags = 0; msgs[0].len = 2; msgs[0].buf = (char *)tx_buf; /* Read data from register */ msgs[1].addr = client->addr; msgs[1].flags = I2C_M_RD; msgs[1].len = 1; msgs[1].buf = (char *)rx_buf; if (i2c_transfer(client->adapter, msgs, 2) < 2) return 0; return rx_buf[0]; } u32 cx25840_read4(struct i2c_client *client, u16 addr) { struct i2c_msg msgs[2]; u8 tx_buf[2], rx_buf[4]; /* Write register address */ tx_buf[0] = addr >> 8; tx_buf[1] = addr & 0xff; msgs[0].addr = client->addr; msgs[0].flags = 0; msgs[0].len = 2; msgs[0].buf = (char *)tx_buf; /* Read data from registers */ msgs[1].addr = client->addr; msgs[1].flags = I2C_M_RD; msgs[1].len = 4; msgs[1].buf = (char *)rx_buf; if (i2c_transfer(client->adapter, msgs, 2) < 2) return 0; return (rx_buf[3] << 24) | (rx_buf[2] << 16) | (rx_buf[1] << 8) | rx_buf[0]; } int cx25840_and_or(struct i2c_client *client, u16 addr, unsigned int and_mask, u8 or_value) { return cx25840_write(client, addr, (cx25840_read(client, addr) & and_mask) | or_value); } int cx25840_and_or4(struct i2c_client *client, u16 addr, u32 and_mask, u32 or_value) { return cx25840_write4(client, addr, (cx25840_read4(client, addr) & and_mask) | or_value); } /* ----------------------------------------------------------------------- */ static int set_input(struct i2c_client *client, enum cx25840_video_input vid_input, enum cx25840_audio_input aud_input); /* ----------------------------------------------------------------------- */ static int cx23885_s_io_pin_config(struct v4l2_subdev *sd, size_t n, struct v4l2_subdev_io_pin_config *p) { struct i2c_client *client = v4l2_get_subdevdata(sd); int i; u32 pin_ctrl; u8 gpio_oe, gpio_data, strength; pin_ctrl = cx25840_read4(client, 0x120); gpio_oe = cx25840_read(client, 0x160); gpio_data = cx25840_read(client, 0x164); for (i = 0; i < n; i++) { strength = p[i].strength; if (strength > CX25840_PIN_DRIVE_FAST) strength = CX25840_PIN_DRIVE_FAST; switch (p[i].pin) { case CX23885_PIN_IRQ_N_GPIO16: if (p[i].function != CX23885_PAD_IRQ_N) { /* GPIO16 */ pin_ctrl &= ~(0x1 << 25); } else { /* IRQ_N */ if (p[i].flags & (BIT(V4L2_SUBDEV_IO_PIN_DISABLE) | BIT(V4L2_SUBDEV_IO_PIN_INPUT))) { pin_ctrl &= ~(0x1 << 25); } else { pin_ctrl |= (0x1 << 25); } if (p[i].flags & BIT(V4L2_SUBDEV_IO_PIN_ACTIVE_LOW)) { pin_ctrl &= ~(0x1 << 24); } else { pin_ctrl |= (0x1 << 24); } } break; case CX23885_PIN_IR_RX_GPIO19: if (p[i].function != CX23885_PAD_GPIO19) { /* IR_RX */ gpio_oe |= (0x1 << 0); pin_ctrl &= ~(0x3 << 18); pin_ctrl |= (strength << 18); } else { /* GPIO19 */ gpio_oe &= ~(0x1 << 0); if (p[i].flags & BIT(V4L2_SUBDEV_IO_PIN_SET_VALUE)) { gpio_data &= ~(0x1 << 0); gpio_data |= ((p[i].value & 0x1) << 0); } pin_ctrl &= ~(0x3 << 12); pin_ctrl |= (strength << 12); } break; case CX23885_PIN_IR_TX_GPIO20: if (p[i].function != CX23885_PAD_GPIO20) { /* IR_TX */ gpio_oe |= (0x1 << 1); if (p[i].flags & BIT(V4L2_SUBDEV_IO_PIN_DISABLE)) pin_ctrl &= ~(0x1 << 10); else pin_ctrl |= (0x1 << 10); pin_ctrl &= ~(0x3 << 18); pin_ctrl |= (strength << 18); } else { /* GPIO20 */ gpio_oe &= ~(0x1 << 1); if (p[i].flags & BIT(V4L2_SUBDEV_IO_PIN_SET_VALUE)) { gpio_data &= ~(0x1 << 1); gpio_data |= ((p[i].value & 0x1) << 1); } pin_ctrl &= ~(0x3 << 12); pin_ctrl |= (strength << 12); } break; case CX23885_PIN_I2S_SDAT_GPIO21: if (p[i].function != CX23885_PAD_GPIO21) { /* I2S_SDAT */ /* TODO: Input or Output config */ gpio_oe |= (0x1 << 2); pin_ctrl &= ~(0x3 << 22); pin_ctrl |= (strength << 22); } else { /* GPIO21 */ gpio_oe &= ~(0x1 << 2); if (p[i].flags & BIT(V4L2_SUBDEV_IO_PIN_SET_VALUE)) { gpio_data &= ~(0x1 << 2); gpio_data |= ((p[i].value & 0x1) << 2); } pin_ctrl &= ~(0x3 << 12); pin_ctrl |= (strength << 12); } break; case CX23885_PIN_I2S_WCLK_GPIO22: if (p[i].function != CX23885_PAD_GPIO22) { /* I2S_WCLK */ /* TODO: Input or Output config */ gpio_oe |= (0x1 << 3); pin_ctrl &= ~(0x3 << 22); pin_ctrl |= (strength << 22); } else { /* GPIO22 */ gpio_oe &= ~(0x1 << 3); if (p[i].flags & BIT(V4L2_SUBDEV_IO_PIN_SET_VALUE)) { gpio_data &= ~(0x1 << 3); gpio_data |= ((p[i].value & 0x1) << 3); } pin_ctrl &= ~(0x3 << 12); pin_ctrl |= (strength << 12); } break; case CX23885_PIN_I2S_BCLK_GPIO23: if (p[i].function != CX23885_PAD_GPIO23) { /* I2S_BCLK */ /* TODO: Input or Output config */ gpio_oe |= (0x1 << 4); pin_ctrl &= ~(0x3 << 22); pin_ctrl |= (strength << 22); } else { /* GPIO23 */ gpio_oe &= ~(0x1 << 4); if (p[i].flags & BIT(V4L2_SUBDEV_IO_PIN_SET_VALUE)) { gpio_data &= ~(0x1 << 4); gpio_data |= ((p[i].value & 0x1) << 4); } pin_ctrl &= ~(0x3 << 12); pin_ctrl |= (strength << 12); } break; } } cx25840_write(client, 0x164, gpio_data); cx25840_write(client, 0x160, gpio_oe); cx25840_write4(client, 0x120, pin_ctrl); return 0; } static u8 cx25840_function_to_pad(struct i2c_client *client, u8 function) { if (function > CX25840_PAD_VRESET) { v4l_err(client, "invalid function %u, assuming default\n", (unsigned int)function); return 0; } return function; } static void cx25840_set_invert(u8 *pinctrl3, u8 *voutctrl4, u8 function, u8 pin, bool invert) { switch (function) { case CX25840_PAD_IRQ_N: if (invert) *pinctrl3 &= ~2; else *pinctrl3 |= 2; break; case CX25840_PAD_ACTIVE: if (invert) *voutctrl4 |= BIT(2); else *voutctrl4 &= ~BIT(2); break; case CX25840_PAD_VACTIVE: if (invert) *voutctrl4 |= BIT(5); else *voutctrl4 &= ~BIT(5); break; case CX25840_PAD_CBFLAG: if (invert) *voutctrl4 |= BIT(4); else *voutctrl4 &= ~BIT(4); break; case CX25840_PAD_VRESET: if (invert) *voutctrl4 |= BIT(0); else *voutctrl4 &= ~BIT(0); break; } if (function != CX25840_PAD_DEFAULT) return; switch (pin) { case CX25840_PIN_DVALID_PRGM0: if (invert) *voutctrl4 |= BIT(6); else *voutctrl4 &= ~BIT(6); break; case CX25840_PIN_HRESET_PRGM2: if (invert) *voutctrl4 |= BIT(1); else *voutctrl4 &= ~BIT(1); break; } } static int cx25840_s_io_pin_config(struct v4l2_subdev *sd, size_t n, struct v4l2_subdev_io_pin_config *p) { struct i2c_client *client = v4l2_get_subdevdata(sd); unsigned int i; u8 pinctrl[6], pinconf[10], voutctrl4; for (i = 0; i < 6; i++) pinctrl[i] = cx25840_read(client, 0x114 + i); for (i = 0; i < 10; i++) pinconf[i] = cx25840_read(client, 0x11c + i); voutctrl4 = cx25840_read(client, 0x407); for (i = 0; i < n; i++) { u8 strength = p[i].strength; if (strength != CX25840_PIN_DRIVE_SLOW && strength != CX25840_PIN_DRIVE_MEDIUM && strength != CX25840_PIN_DRIVE_FAST) { v4l_err(client, "invalid drive speed for pin %u (%u), assuming fast\n", (unsigned int)p[i].pin, (unsigned int)strength); strength = CX25840_PIN_DRIVE_FAST; } switch (p[i].pin) { case CX25840_PIN_DVALID_PRGM0: if (p[i].flags & BIT(V4L2_SUBDEV_IO_PIN_DISABLE)) pinctrl[0] &= ~BIT(6); else pinctrl[0] |= BIT(6); pinconf[3] &= 0xf0; pinconf[3] |= cx25840_function_to_pad(client, p[i].function); cx25840_set_invert(&pinctrl[3], &voutctrl4, p[i].function, CX25840_PIN_DVALID_PRGM0, p[i].flags & BIT(V4L2_SUBDEV_IO_PIN_ACTIVE_LOW)); pinctrl[4] &= ~(3 << 2); /* CX25840_PIN_DRIVE_MEDIUM */ switch (strength) { case CX25840_PIN_DRIVE_SLOW: pinctrl[4] |= 1 << 2; break; case CX25840_PIN_DRIVE_FAST: pinctrl[4] |= 2 << 2; break; } break; case CX25840_PIN_HRESET_PRGM2: if (p[i].flags & BIT(V4L2_SUBDEV_IO_PIN_DISABLE)) pinctrl[1] &= ~BIT(0); else pinctrl[1] |= BIT(0); pinconf[4] &= 0xf0; pinconf[4] |= cx25840_function_to_pad(client, p[i].function); cx25840_set_invert(&pinctrl[3], &voutctrl4, p[i].function, CX25840_PIN_HRESET_PRGM2, p[i].flags & BIT(V4L2_SUBDEV_IO_PIN_ACTIVE_LOW)); pinctrl[4] &= ~(3 << 2); /* CX25840_PIN_DRIVE_MEDIUM */ switch (strength) { case CX25840_PIN_DRIVE_SLOW: pinctrl[4] |= 1 << 2; break; case CX25840_PIN_DRIVE_FAST: pinctrl[4] |= 2 << 2; break; } break; case CX25840_PIN_PLL_CLK_PRGM7: if (p[i].flags & BIT(V4L2_SUBDEV_IO_PIN_DISABLE)) pinctrl[2] &= ~BIT(2); else pinctrl[2] |= BIT(2); switch (p[i].function) { case CX25840_PAD_XTI_X5_DLL: pinconf[6] = 0; break; case CX25840_PAD_AUX_PLL: pinconf[6] = 1; break; case CX25840_PAD_VID_PLL: pinconf[6] = 5; break; case CX25840_PAD_XTI: pinconf[6] = 2; break; default: pinconf[6] = 3; pinconf[6] |= cx25840_function_to_pad(client, p[i].function) << 4; } break; default: v4l_err(client, "invalid or unsupported pin %u\n", (unsigned int)p[i].pin); break; } } cx25840_write(client, 0x407, voutctrl4); for (i = 0; i < 6; i++) cx25840_write(client, 0x114 + i, pinctrl[i]); for (i = 0; i < 10; i++) cx25840_write(client, 0x11c + i, pinconf[i]); return 0; } static int common_s_io_pin_config(struct v4l2_subdev *sd, size_t n, struct v4l2_subdev_io_pin_config *pincfg) { struct cx25840_state *state = to_state(sd); if (is_cx2388x(state)) return cx23885_s_io_pin_config(sd, n, pincfg); else if (is_cx2584x(state)) return cx25840_s_io_pin_config(sd, n, pincfg); return 0; } /* ----------------------------------------------------------------------- */ static void init_dll1(struct i2c_client *client) { /* * This is the Hauppauge sequence used to * initialize the Delay Lock Loop 1 (ADC DLL). */ cx25840_write(client, 0x159, 0x23); cx25840_write(client, 0x15a, 0x87); cx25840_write(client, 0x15b, 0x06); udelay(10); cx25840_write(client, 0x159, 0xe1); udelay(10); cx25840_write(client, 0x15a, 0x86); cx25840_write(client, 0x159, 0xe0); cx25840_write(client, 0x159, 0xe1); cx25840_write(client, 0x15b, 0x10); } static void init_dll2(struct i2c_client *client) { /* * This is the Hauppauge sequence used to * initialize the Delay Lock Loop 2 (ADC DLL). */ cx25840_write(client, 0x15d, 0xe3); cx25840_write(client, 0x15e, 0x86); cx25840_write(client, 0x15f, 0x06); udelay(10); cx25840_write(client, 0x15d, 0xe1); cx25840_write(client, 0x15d, 0xe0); cx25840_write(client, 0x15d, 0xe1); } static void cx25836_initialize(struct i2c_client *client) { /* *reset configuration is described on page 3-77 * of the CX25836 datasheet */ /* 2. */ cx25840_and_or(client, 0x000, ~0x01, 0x01); cx25840_and_or(client, 0x000, ~0x01, 0x00); /* 3a. */ cx25840_and_or(client, 0x15a, ~0x70, 0x00); /* 3b. */ cx25840_and_or(client, 0x15b, ~0x1e, 0x06); /* 3c. */ cx25840_and_or(client, 0x159, ~0x02, 0x02); /* 3d. */ udelay(10); /* 3e. */ cx25840_and_or(client, 0x159, ~0x02, 0x00); /* 3f. */ cx25840_and_or(client, 0x159, ~0xc0, 0xc0); /* 3g. */ cx25840_and_or(client, 0x159, ~0x01, 0x00); cx25840_and_or(client, 0x159, ~0x01, 0x01); /* 3h. */ cx25840_and_or(client, 0x15b, ~0x1e, 0x10); } static void cx25840_work_handler(struct work_struct *work) { struct cx25840_state *state = container_of(work, struct cx25840_state, fw_work); cx25840_loadfw(state->c); wake_up(&state->fw_wait); } #define CX25840_VCONFIG_SET_BIT(state, opt_msk, voc, idx, bit, oneval) \ do { \ if ((state)->vid_config & (opt_msk)) { \ if (((state)->vid_config & (opt_msk)) == \ (oneval)) \ (voc)[idx] |= BIT(bit); \ else \ (voc)[idx] &= ~BIT(bit); \ } \ } while (0) /* apply current vconfig to hardware regs */ static void cx25840_vconfig_apply(struct i2c_client *client) { struct cx25840_state *state = to_state(i2c_get_clientdata(client)); u8 voutctrl[3]; unsigned int i; for (i = 0; i < 3; i++) voutctrl[i] = cx25840_read(client, 0x404 + i); if (state->vid_config & CX25840_VCONFIG_FMT_MASK) voutctrl[0] &= ~3; switch (state->vid_config & CX25840_VCONFIG_FMT_MASK) { case CX25840_VCONFIG_FMT_BT656: voutctrl[0] |= 1; break; case CX25840_VCONFIG_FMT_VIP11: voutctrl[0] |= 2; break; case CX25840_VCONFIG_FMT_VIP2: voutctrl[0] |= 3; break; case CX25840_VCONFIG_FMT_BT601: /* zero */ default: break; } CX25840_VCONFIG_SET_BIT(state, CX25840_VCONFIG_RES_MASK, voutctrl, 0, 2, CX25840_VCONFIG_RES_10BIT); CX25840_VCONFIG_SET_BIT(state, CX25840_VCONFIG_VBIRAW_MASK, voutctrl, 0, 3, CX25840_VCONFIG_VBIRAW_ENABLED); CX25840_VCONFIG_SET_BIT(state, CX25840_VCONFIG_ANCDATA_MASK, voutctrl, 0, 4, CX25840_VCONFIG_ANCDATA_ENABLED); CX25840_VCONFIG_SET_BIT(state, CX25840_VCONFIG_TASKBIT_MASK, voutctrl, 0, 5, CX25840_VCONFIG_TASKBIT_ONE); CX25840_VCONFIG_SET_BIT(state, CX25840_VCONFIG_ACTIVE_MASK, voutctrl, 1, 2, CX25840_VCONFIG_ACTIVE_HORIZONTAL); CX25840_VCONFIG_SET_BIT(state, CX25840_VCONFIG_VALID_MASK, voutctrl, 1, 3, CX25840_VCONFIG_VALID_ANDACTIVE); CX25840_VCONFIG_SET_BIT(state, CX25840_VCONFIG_HRESETW_MASK, voutctrl, 1, 4, CX25840_VCONFIG_HRESETW_PIXCLK); if (state->vid_config & CX25840_VCONFIG_CLKGATE_MASK) voutctrl[1] &= ~(3 << 6); switch (state->vid_config & CX25840_VCONFIG_CLKGATE_MASK) { case CX25840_VCONFIG_CLKGATE_VALID: voutctrl[1] |= 2; break; case CX25840_VCONFIG_CLKGATE_VALIDACTIVE: voutctrl[1] |= 3; break; case CX25840_VCONFIG_CLKGATE_NONE: /* zero */ default: break; } CX25840_VCONFIG_SET_BIT(state, CX25840_VCONFIG_DCMODE_MASK, voutctrl, 2, 0, CX25840_VCONFIG_DCMODE_BYTES); CX25840_VCONFIG_SET_BIT(state, CX25840_VCONFIG_IDID0S_MASK, voutctrl, 2, 1, CX25840_VCONFIG_IDID0S_LINECNT); CX25840_VCONFIG_SET_BIT(state, CX25840_VCONFIG_VIPCLAMP_MASK, voutctrl, 2, 4, CX25840_VCONFIG_VIPCLAMP_ENABLED); for (i = 0; i < 3; i++) cx25840_write(client, 0x404 + i, voutctrl[i]); } static void cx25840_initialize(struct i2c_client *client) { DEFINE_WAIT(wait); struct cx25840_state *state = to_state(i2c_get_clientdata(client)); struct workqueue_struct *q; /* datasheet startup in numbered steps, refer to page 3-77 */ /* 2. */ cx25840_and_or(client, 0x803, ~0x10, 0x00); /* * The default of this register should be 4, but I get 0 instead. * Set this register to 4 manually. */ cx25840_write(client, 0x000, 0x04); /* 3. */ init_dll1(client); init_dll2(client); cx25840_write(client, 0x136, 0x0a); /* 4. */ cx25840_write(client, 0x13c, 0x01); cx25840_write(client, 0x13c, 0x00); /* 5. */ /* * Do the firmware load in a work handler to prevent. * Otherwise the kernel is blocked waiting for the * bit-banging i2c interface to finish uploading the * firmware. */ INIT_WORK(&state->fw_work, cx25840_work_handler); init_waitqueue_head(&state->fw_wait); q = create_singlethread_workqueue("cx25840_fw"); if (q) { prepare_to_wait(&state->fw_wait, &wait, TASK_UNINTERRUPTIBLE); queue_work(q, &state->fw_work); schedule(); finish_wait(&state->fw_wait, &wait); destroy_workqueue(q); } /* 6. */ cx25840_write(client, 0x115, 0x8c); cx25840_write(client, 0x116, 0x07); cx25840_write(client, 0x118, 0x02); /* 7. */ cx25840_write(client, 0x4a5, 0x80); cx25840_write(client, 0x4a5, 0x00); cx25840_write(client, 0x402, 0x00); /* 8. */ cx25840_and_or(client, 0x401, ~0x18, 0); cx25840_and_or(client, 0x4a2, ~0x10, 0x10); /* steps 8c and 8d are done in change_input() */ /* 10. */ cx25840_write(client, 0x8d3, 0x1f); cx25840_write(client, 0x8e3, 0x03); cx25840_std_setup(client); /* trial and error says these are needed to get audio */ cx25840_write(client, 0x914, 0xa0); cx25840_write(client, 0x918, 0xa0); cx25840_write(client, 0x919, 0x01); /* stereo preferred */ cx25840_write(client, 0x809, 0x04); /* AC97 shift */ cx25840_write(client, 0x8cf, 0x0f); /* (re)set input */ set_input(client, state->vid_input, state->aud_input); if (state->generic_mode) cx25840_vconfig_apply(client); /* start microcontroller */ cx25840_and_or(client, 0x803, ~0x10, 0x10); } static void cx23885_initialize(struct i2c_client *client) { DEFINE_WAIT(wait); struct cx25840_state *state = to_state(i2c_get_clientdata(client)); u32 clk_freq = 0; struct workqueue_struct *q; /* cx23885 sets hostdata to clk_freq pointer */ if (v4l2_get_subdev_hostdata(&state->sd)) clk_freq = *((u32 *)v4l2_get_subdev_hostdata(&state->sd)); /* * Come out of digital power down * The CX23888, at least, needs this, otherwise registers aside from * 0x0-0x2 can't be read or written. */ cx25840_write(client, 0x000, 0); /* Internal Reset */ cx25840_and_or(client, 0x102, ~0x01, 0x01); cx25840_and_or(client, 0x102, ~0x01, 0x00); /* Stop microcontroller */ cx25840_and_or(client, 0x803, ~0x10, 0x00); /* DIF in reset? */ cx25840_write(client, 0x398, 0); /* * Trust the default xtal, no division * '885: 28.636363... MHz * '887: 25.000000 MHz * '888: 50.000000 MHz */ cx25840_write(client, 0x2, 0x76); /* Power up all the PLL's and DLL */ cx25840_write(client, 0x1, 0x40); /* Sys PLL */ switch (state->id) { case CX23888_AV: /* * 50.0 MHz * (0xb + 0xe8ba26/0x2000000)/4 = 5 * 28.636363 MHz * 572.73 MHz before post divide */ if (clk_freq == 25000000) { /* 888/ImpactVCBe or 25Mhz xtal */ ; /* nothing to do */ } else { /* HVR1850 or 50MHz xtal */ cx25840_write(client, 0x2, 0x71); } cx25840_write4(client, 0x11c, 0x01d1744c); cx25840_write4(client, 0x118, 0x00000416); cx25840_write4(client, 0x404, 0x0010253e); cx25840_write4(client, 0x42c, 0x42600000); cx25840_write4(client, 0x44c, 0x161f1000); break; case CX23887_AV: /* * 25.0 MHz * (0x16 + 0x1d1744c/0x2000000)/4 = 5 * 28.636363 MHz * 572.73 MHz before post divide */ cx25840_write4(client, 0x11c, 0x01d1744c); cx25840_write4(client, 0x118, 0x00000416); break; case CX23885_AV: default: /* * 28.636363 MHz * (0x14 + 0x0/0x2000000)/4 = 5 * 28.636363 MHz * 572.73 MHz before post divide */ cx25840_write4(client, 0x11c, 0x00000000); cx25840_write4(client, 0x118, 0x00000414); break; } /* Disable DIF bypass */ cx25840_write4(client, 0x33c, 0x00000001); /* DIF Src phase inc */ cx25840_write4(client, 0x340, 0x0df7df83); /* * Vid PLL * Setup for a BT.656 pixel clock of 13.5 Mpixels/second * * 28.636363 MHz * (0xf + 0x02be2c9/0x2000000)/4 = 8 * 13.5 MHz * 432.0 MHz before post divide */ /* HVR1850 */ switch (state->id) { case CX23888_AV: if (clk_freq == 25000000) { /* 888/ImpactVCBe or 25MHz xtal */ cx25840_write4(client, 0x10c, 0x01b6db7b); cx25840_write4(client, 0x108, 0x00000512); } else { /* 888/HVR1250 or 50MHz xtal */ cx25840_write4(client, 0x10c, 0x13333333); cx25840_write4(client, 0x108, 0x00000515); } break; default: cx25840_write4(client, 0x10c, 0x002be2c9); cx25840_write4(client, 0x108, 0x0000040f); } /* Luma */ cx25840_write4(client, 0x414, 0x00107d12); /* Chroma */ if (is_cx23888(state)) cx25840_write4(client, 0x418, 0x1d008282); else cx25840_write4(client, 0x420, 0x3d008282); /* * Aux PLL * Initial setup for audio sample clock: * 48 ksps, 16 bits/sample, x160 multiplier = 122.88 MHz * Initial I2S output/master clock(?): * 48 ksps, 16 bits/sample, x16 multiplier = 12.288 MHz */ switch (state->id) { case CX23888_AV: /* * 50.0 MHz * (0x7 + 0x0bedfa4/0x2000000)/3 = 122.88 MHz * 368.64 MHz before post divide * 122.88 MHz / 0xa = 12.288 MHz */ /* HVR1850 or 50MHz xtal or 25MHz xtal */ cx25840_write4(client, 0x114, 0x017dbf48); cx25840_write4(client, 0x110, 0x000a030e); break; case CX23887_AV: /* * 25.0 MHz * (0xe + 0x17dbf48/0x2000000)/3 = 122.88 MHz * 368.64 MHz before post divide * 122.88 MHz / 0xa = 12.288 MHz */ cx25840_write4(client, 0x114, 0x017dbf48); cx25840_write4(client, 0x110, 0x000a030e); break; case CX23885_AV: default: /* * 28.636363 MHz * (0xc + 0x1bf0c9e/0x2000000)/3 = 122.88 MHz * 368.64 MHz before post divide * 122.88 MHz / 0xa = 12.288 MHz */ cx25840_write4(client, 0x114, 0x01bf0c9e); cx25840_write4(client, 0x110, 0x000a030c); break; } /* ADC2 input select */ cx25840_write(client, 0x102, 0x10); /* VIN1 & VIN5 */ cx25840_write(client, 0x103, 0x11); /* Enable format auto detect */ cx25840_write(client, 0x400, 0); /* Fast subchroma lock */ /* White crush, Chroma AGC & Chroma Killer enabled */ cx25840_write(client, 0x401, 0xe8); /* Select AFE clock pad output source */ cx25840_write(client, 0x144, 0x05); /* Drive GPIO2 direction and values for HVR1700 * where an onboard mux selects the output of demodulator * vs the 417. Failure to set this results in no DTV. * It's safe to set this across all Hauppauge boards * currently, regardless of the board type. */ cx25840_write(client, 0x160, 0x1d); cx25840_write(client, 0x164, 0x00); /* * Do the firmware load in a work handler to prevent. * Otherwise the kernel is blocked waiting for the * bit-banging i2c interface to finish uploading the * firmware. */ INIT_WORK(&state->fw_work, cx25840_work_handler); init_waitqueue_head(&state->fw_wait); q = create_singlethread_workqueue("cx25840_fw"); if (q) { prepare_to_wait(&state->fw_wait, &wait, TASK_UNINTERRUPTIBLE); queue_work(q, &state->fw_work); schedule(); finish_wait(&state->fw_wait, &wait); destroy_workqueue(q); } /* * Call the cx23888 specific std setup func, we no longer rely on * the generic cx24840 func. */ if (is_cx23888(state)) cx23888_std_setup(client); else cx25840_std_setup(client); /* (re)set input */ set_input(client, state->vid_input, state->aud_input); /* start microcontroller */ cx25840_and_or(client, 0x803, ~0x10, 0x10); /* Disable and clear video interrupts - we don't use them */ cx25840_write4(client, CX25840_VID_INT_STAT_REG, 0xffffffff); /* Disable and clear audio interrupts - we don't use them */ cx25840_write(client, CX25840_AUD_INT_CTRL_REG, 0xff); cx25840_write(client, CX25840_AUD_INT_STAT_REG, 0xff); /* CC raw enable */ /* * - VIP 1.1 control codes - 10bit, blue field enable. * - enable raw data during vertical blanking. * - enable ancillary Data insertion for 656 or VIP. */ cx25840_write4(client, 0x404, 0x0010253e); /* CC on - VBI_LINE_CTRL3, FLD_VBI_MD_LINE12 */ cx25840_write(client, state->vbi_regs_offset + 0x42f, 0x66); /* HVR-1250 / HVR1850 DIF related */ /* Power everything up */ cx25840_write4(client, 0x130, 0x0); /* SRC_COMB_CFG */ if (is_cx23888(state)) cx25840_write4(client, 0x454, 0x6628021F); else cx25840_write4(client, 0x478, 0x6628021F); /* AFE_CLK_OUT_CTRL - Select the clock output source as output */ cx25840_write4(client, 0x144, 0x5); /* I2C_OUT_CTL - I2S output configuration as * Master, Sony, Left justified, left sample on WS=1 */ cx25840_write4(client, 0x918, 0x1a0); /* AFE_DIAG_CTRL1 */ cx25840_write4(client, 0x134, 0x000a1800); /* AFE_DIAG_CTRL3 - Inverted Polarity for Audio and Video */ cx25840_write4(client, 0x13c, 0x00310000); } /* ----------------------------------------------------------------------- */ static void cx231xx_initialize(struct i2c_client *client) { DEFINE_WAIT(wait); struct cx25840_state *state = to_state(i2c_get_clientdata(client)); struct workqueue_struct *q; /* Internal Reset */ cx25840_and_or(client, 0x102, ~0x01, 0x01); cx25840_and_or(client, 0x102, ~0x01, 0x00); /* Stop microcontroller */ cx25840_and_or(client, 0x803, ~0x10, 0x00); /* DIF in reset? */ cx25840_write(client, 0x398, 0); /* Trust the default xtal, no division */ /* This changes for the cx23888 products */ cx25840_write(client, 0x2, 0x76); /* Bring down the regulator for AUX clk */ cx25840_write(client, 0x1, 0x40); /* Disable DIF bypass */ cx25840_write4(client, 0x33c, 0x00000001); /* DIF Src phase inc */ cx25840_write4(client, 0x340, 0x0df7df83); /* Luma */ cx25840_write4(client, 0x414, 0x00107d12); /* Chroma */ cx25840_write4(client, 0x420, 0x3d008282); /* ADC2 input select */ cx25840_write(client, 0x102, 0x10); /* VIN1 & VIN5 */ cx25840_write(client, 0x103, 0x11); /* Enable format auto detect */ cx25840_write(client, 0x400, 0); /* Fast subchroma lock */ /* White crush, Chroma AGC & Chroma Killer enabled */ cx25840_write(client, 0x401, 0xe8); /* * Do the firmware load in a work handler to prevent. * Otherwise the kernel is blocked waiting for the * bit-banging i2c interface to finish uploading the * firmware. */ INIT_WORK(&state->fw_work, cx25840_work_handler); init_waitqueue_head(&state->fw_wait); q = create_singlethread_workqueue("cx25840_fw"); if (q) { prepare_to_wait(&state->fw_wait, &wait, TASK_UNINTERRUPTIBLE); queue_work(q, &state->fw_work); schedule(); finish_wait(&state->fw_wait, &wait); destroy_workqueue(q); } cx25840_std_setup(client); /* (re)set input */ set_input(client, state->vid_input, state->aud_input); /* start microcontroller */ cx25840_and_or(client, 0x803, ~0x10, 0x10); /* CC raw enable */ cx25840_write(client, 0x404, 0x0b); /* CC on */ cx25840_write(client, 0x42f, 0x66); cx25840_write4(client, 0x474, 0x1e1e601a); } /* ----------------------------------------------------------------------- */ void cx25840_std_setup(struct i2c_client *client) { struct cx25840_state *state = to_state(i2c_get_clientdata(client)); v4l2_std_id std = state->std; int hblank, hactive, burst, vblank, vactive, sc; int vblank656, src_decimation; int luma_lpf, uv_lpf, comb; u32 pll_int, pll_frac, pll_post; /* datasheet startup, step 8d */ if (std & ~V4L2_STD_NTSC) cx25840_write(client, 0x49f, 0x11); else cx25840_write(client, 0x49f, 0x14); /* generic mode uses the values that the chip autoconfig would set */ if (std & V4L2_STD_625_50) { hblank = 132; hactive = 720; burst = 93; if (state->generic_mode) { vblank = 34; vactive = 576; vblank656 = 38; } else { vblank = 36; vactive = 580; vblank656 = 40; } src_decimation = 0x21f; luma_lpf = 2; if (std & V4L2_STD_SECAM) { uv_lpf = 0; comb = 0; sc = 0x0a425f; } else if (std == V4L2_STD_PAL_Nc) { if (state->generic_mode) { burst = 95; luma_lpf = 1; } uv_lpf = 1; comb = 0x20; sc = 556453; } else { uv_lpf = 1; comb = 0x20; sc = 688739; } } else { hactive = 720; hblank = 122; vactive = 487; luma_lpf = 1; uv_lpf = 1; if (state->generic_mode) { vblank = 20; vblank656 = 24; } src_decimation = 0x21f; if (std == V4L2_STD_PAL_60) { if (!state->generic_mode) { vblank = 26; vblank656 = 26; burst = 0x5b; } else { burst = 0x59; } luma_lpf = 2; comb = 0x20; sc = 688739; } else if (std == V4L2_STD_PAL_M) { vblank = 20; vblank656 = 24; burst = 0x61; comb = 0x20; sc = 555452; } else { if (!state->generic_mode) { vblank = 26; vblank656 = 26; } burst = 0x5b; comb = 0x66; sc = 556063; } } /* DEBUG: Displays configured PLL frequency */ if (!is_cx231xx(state)) { pll_int = cx25840_read(client, 0x108); pll_frac = cx25840_read4(client, 0x10c) & 0x1ffffff; pll_post = cx25840_read(client, 0x109); v4l_dbg(1, cx25840_debug, client, "PLL regs = int: %u, frac: %u, post: %u\n", pll_int, pll_frac, pll_post); if (pll_post) { int fin, fsc; int pll = (28636363L * ((((u64)pll_int) << 25L) + pll_frac)) >> 25L; pll /= pll_post; v4l_dbg(1, cx25840_debug, client, "PLL = %d.%06d MHz\n", pll / 1000000, pll % 1000000); v4l_dbg(1, cx25840_debug, client, "PLL/8 = %d.%06d MHz\n", pll / 8000000, (pll / 8) % 1000000); fin = ((u64)src_decimation * pll) >> 12; v4l_dbg(1, cx25840_debug, client, "ADC Sampling freq = %d.%06d MHz\n", fin / 1000000, fin % 1000000); fsc = (((u64)sc) * pll) >> 24L; v4l_dbg(1, cx25840_debug, client, "Chroma sub-carrier freq = %d.%06d MHz\n", fsc / 1000000, fsc % 1000000); v4l_dbg(1, cx25840_debug, client, "hblank %i, hactive %i, vblank %i, vactive %i, vblank656 %i, src_dec %i, burst 0x%02x, luma_lpf %i, uv_lpf %i, comb 0x%02x, sc 0x%06x\n", hblank, hactive, vblank, vactive, vblank656, src_decimation, burst, luma_lpf, uv_lpf, comb, sc); } } /* Sets horizontal blanking delay and active lines */ cx25840_write(client, 0x470, hblank); cx25840_write(client, 0x471, (((hblank >> 8) & 0x3) | (hactive << 4)) & 0xff); cx25840_write(client, 0x472, hactive >> 4); /* Sets burst gate delay */ cx25840_write(client, 0x473, burst); /* Sets vertical blanking delay and active duration */ cx25840_write(client, 0x474, vblank); cx25840_write(client, 0x475, (((vblank >> 8) & 0x3) | (vactive << 4)) & 0xff); cx25840_write(client, 0x476, vactive >> 4); cx25840_write(client, 0x477, vblank656); /* Sets src decimation rate */ cx25840_write(client, 0x478, src_decimation & 0xff); cx25840_write(client, 0x479, (src_decimation >> 8) & 0xff); /* Sets Luma and UV Low pass filters */ cx25840_write(client, 0x47a, luma_lpf << 6 | ((uv_lpf << 4) & 0x30)); /* Enables comb filters */ cx25840_write(client, 0x47b, comb); /* Sets SC Step*/ cx25840_write(client, 0x47c, sc); cx25840_write(client, 0x47d, (sc >> 8) & 0xff); cx25840_write(client, 0x47e, (sc >> 16) & 0xff); /* Sets VBI parameters */ if (std & V4L2_STD_625_50) { cx25840_write(client, 0x47f, 0x01); state->vbi_line_offset = 5; } else { cx25840_write(client, 0x47f, 0x00); state->vbi_line_offset = 8; } } /* ----------------------------------------------------------------------- */ static void input_change(struct i2c_client *client) { struct cx25840_state *state = to_state(i2c_get_clientdata(client)); v4l2_std_id std = state->std; /* Follow step 8c and 8d of section 3.16 in the cx25840 datasheet */ if (std & V4L2_STD_SECAM) { cx25840_write(client, 0x402, 0); } else { cx25840_write(client, 0x402, 0x04); cx25840_write(client, 0x49f, (std & V4L2_STD_NTSC) ? 0x14 : 0x11); } cx25840_and_or(client, 0x401, ~0x60, 0); cx25840_and_or(client, 0x401, ~0x60, 0x60); /* Don't write into audio registers on cx2583x chips */ if (is_cx2583x(state)) return; cx25840_and_or(client, 0x810, ~0x01, 1); if (state->radio) { cx25840_write(client, 0x808, 0xf9); cx25840_write(client, 0x80b, 0x00); } else if (std & V4L2_STD_525_60) { /* * Certain Hauppauge PVR150 models have a hardware bug * that causes audio to drop out. For these models the * audio standard must be set explicitly. * To be precise: it affects cards with tuner models * 85, 99 and 112 (model numbers from tveeprom). */ int hw_fix = state->pvr150_workaround; if (std == V4L2_STD_NTSC_M_JP) { /* Japan uses EIAJ audio standard */ cx25840_write(client, 0x808, hw_fix ? 0x2f : 0xf7); } else if (std == V4L2_STD_NTSC_M_KR) { /* South Korea uses A2 audio standard */ cx25840_write(client, 0x808, hw_fix ? 0x3f : 0xf8); } else { /* Others use the BTSC audio standard */ cx25840_write(client, 0x808, hw_fix ? 0x1f : 0xf6); } cx25840_write(client, 0x80b, 0x00); } else if (std & V4L2_STD_PAL) { /* Autodetect audio standard and audio system */ cx25840_write(client, 0x808, 0xff); /* * Since system PAL-L is pretty much non-existent and * not used by any public broadcast network, force * 6.5 MHz carrier to be interpreted as System DK, * this avoids DK audio detection instability */ cx25840_write(client, 0x80b, 0x00); } else if (std & V4L2_STD_SECAM) { /* Autodetect audio standard and audio system */ cx25840_write(client, 0x808, 0xff); /* * If only one of SECAM-DK / SECAM-L is required, then force * 6.5MHz carrier, else autodetect it */ if ((std & V4L2_STD_SECAM_DK) && !(std & (V4L2_STD_SECAM_L | V4L2_STD_SECAM_LC))) { /* 6.5 MHz carrier to be interpreted as System DK */ cx25840_write(client, 0x80b, 0x00); } else if (!(std & V4L2_STD_SECAM_DK) && (std & (V4L2_STD_SECAM_L | V4L2_STD_SECAM_LC))) { /* 6.5 MHz carrier to be interpreted as System L */ cx25840_write(client, 0x80b, 0x08); } else { /* 6.5 MHz carrier to be autodetected */ cx25840_write(client, 0x80b, 0x10); } } cx25840_and_or(client, 0x810, ~0x01, 0); } static int set_input(struct i2c_client *client, enum cx25840_video_input vid_input, enum cx25840_audio_input aud_input) { struct cx25840_state *state = to_state(i2c_get_clientdata(client)); u8 is_composite = (vid_input >= CX25840_COMPOSITE1 && vid_input <= CX25840_COMPOSITE8); u8 is_component = (vid_input & CX25840_COMPONENT_ON) == CX25840_COMPONENT_ON; u8 is_dif = (vid_input & CX25840_DIF_ON) == CX25840_DIF_ON; u8 is_svideo = (vid_input & CX25840_SVIDEO_ON) == CX25840_SVIDEO_ON; int luma = vid_input & 0xf0; int chroma = vid_input & 0xf00; u8 reg; u32 val; v4l_dbg(1, cx25840_debug, client, "decoder set video input %d, audio input %d\n", vid_input, aud_input); if (vid_input >= CX25840_VIN1_CH1) { v4l_dbg(1, cx25840_debug, client, "vid_input 0x%x\n", vid_input); reg = vid_input & 0xff; is_composite = !is_component && ((vid_input & CX25840_SVIDEO_ON) != CX25840_SVIDEO_ON); v4l_dbg(1, cx25840_debug, client, "mux cfg 0x%x comp=%d\n", reg, is_composite); } else if (is_composite) { reg = 0xf0 + (vid_input - CX25840_COMPOSITE1); } else { if ((vid_input & ~0xff0) || luma < CX25840_SVIDEO_LUMA1 || luma > CX25840_SVIDEO_LUMA8 || chroma < CX25840_SVIDEO_CHROMA4 || chroma > CX25840_SVIDEO_CHROMA8) { v4l_err(client, "0x%04x is not a valid video input!\n", vid_input); return -EINVAL; } reg = 0xf0 + ((luma - CX25840_SVIDEO_LUMA1) >> 4); if (chroma >= CX25840_SVIDEO_CHROMA7) { reg &= 0x3f; reg |= (chroma - CX25840_SVIDEO_CHROMA7) >> 2; } else { reg &= 0xcf; reg |= (chroma - CX25840_SVIDEO_CHROMA4) >> 4; } } /* The caller has previously prepared the correct routing * configuration in reg (for the cx23885) so we have no * need to attempt to flip bits for earlier av decoders. */ if (!is_cx2388x(state) && !is_cx231xx(state)) { switch (aud_input) { case CX25840_AUDIO_SERIAL: /* do nothing, use serial audio input */ break; case CX25840_AUDIO4: reg &= ~0x30; break; case CX25840_AUDIO5: reg &= ~0x30; reg |= 0x10; break; case CX25840_AUDIO6: reg &= ~0x30; reg |= 0x20; break; case CX25840_AUDIO7: reg &= ~0xc0; break; case CX25840_AUDIO8: reg &= ~0xc0; reg |= 0x40; break; default: v4l_err(client, "0x%04x is not a valid audio input!\n", aud_input); return -EINVAL; } } cx25840_write(client, 0x103, reg); /* Set INPUT_MODE to Composite, S-Video or Component */ if (is_component) cx25840_and_or(client, 0x401, ~0x6, 0x6); else cx25840_and_or(client, 0x401, ~0x6, is_composite ? 0 : 0x02); if (is_cx2388x(state)) { /* Enable or disable the DIF for tuner use */ if (is_dif) { cx25840_and_or(client, 0x102, ~0x80, 0x80); /* Set of defaults for NTSC and PAL */ cx25840_write4(client, 0x31c, 0xc2262600); cx25840_write4(client, 0x320, 0xc2262600); /* 18271 IF - Nobody else yet uses a different * tuner with the DIF, so these are reasonable * assumptions (HVR1250 and HVR1850 specific). */ cx25840_write4(client, 0x318, 0xda262600); cx25840_write4(client, 0x33c, 0x2a24c800); cx25840_write4(client, 0x104, 0x0704dd00); } else { cx25840_write4(client, 0x300, 0x015c28f5); cx25840_and_or(client, 0x102, ~0x80, 0); cx25840_write4(client, 0x340, 0xdf7df83); cx25840_write4(client, 0x104, 0x0704dd80); cx25840_write4(client, 0x314, 0x22400600); cx25840_write4(client, 0x318, 0x40002600); cx25840_write4(client, 0x324, 0x40002600); cx25840_write4(client, 0x32c, 0x0250e620); cx25840_write4(client, 0x39c, 0x01FF0B00); cx25840_write4(client, 0x410, 0xffff0dbf); cx25840_write4(client, 0x414, 0x00137d03); if (is_cx23888(state)) { /* 888 MISC_TIM_CTRL */ cx25840_write4(client, 0x42c, 0x42600000); /* 888 FIELD_COUNT */ cx25840_write4(client, 0x430, 0x0000039b); /* 888 VSCALE_CTRL */ cx25840_write4(client, 0x438, 0x00000000); /* 888 DFE_CTRL1 */ cx25840_write4(client, 0x440, 0xF8E3E824); /* 888 DFE_CTRL2 */ cx25840_write4(client, 0x444, 0x401040dc); /* 888 DFE_CTRL3 */ cx25840_write4(client, 0x448, 0xcd3f02a0); /* 888 PLL_CTRL */ cx25840_write4(client, 0x44c, 0x161f1000); /* 888 HTL_CTRL */ cx25840_write4(client, 0x450, 0x00000802); } cx25840_write4(client, 0x91c, 0x01000000); cx25840_write4(client, 0x8e0, 0x03063870); cx25840_write4(client, 0x8d4, 0x7FFF0024); cx25840_write4(client, 0x8d0, 0x00063073); cx25840_write4(client, 0x8c8, 0x00010000); cx25840_write4(client, 0x8cc, 0x00080023); /* DIF BYPASS */ cx25840_write4(client, 0x33c, 0x2a04c800); } /* Reset the DIF */ cx25840_write4(client, 0x398, 0); } if (!is_cx2388x(state) && !is_cx231xx(state)) { /* Set CH_SEL_ADC2 to 1 if input comes from CH3 */ cx25840_and_or(client, 0x102, ~0x2, (reg & 0x80) == 0 ? 2 : 0); /* Set DUAL_MODE_ADC2 to 1 if input comes from both CH2&CH3 */ if ((reg & 0xc0) != 0xc0 && (reg & 0x30) != 0x30) cx25840_and_or(client, 0x102, ~0x4, 4); else cx25840_and_or(client, 0x102, ~0x4, 0); } else { /* Set DUAL_MODE_ADC2 to 1 if component*/ cx25840_and_or(client, 0x102, ~0x4, is_component ? 0x4 : 0x0); if (is_composite) { /* ADC2 input select channel 2 */ cx25840_and_or(client, 0x102, ~0x2, 0); } else if (!is_component) { /* S-Video */ if (chroma >= CX25840_SVIDEO_CHROMA7) { /* ADC2 input select channel 3 */ cx25840_and_or(client, 0x102, ~0x2, 2); } else { /* ADC2 input select channel 2 */ cx25840_and_or(client, 0x102, ~0x2, 0); } } /* cx23885 / SVIDEO */ if (is_cx2388x(state) && is_svideo) { #define AFE_CTRL (0x104) #define MODE_CTRL (0x400) cx25840_and_or(client, 0x102, ~0x2, 0x2); val = cx25840_read4(client, MODE_CTRL); val &= 0xFFFFF9FF; /* YC */ val |= 0x00000200; val &= ~0x2000; cx25840_write4(client, MODE_CTRL, val); val = cx25840_read4(client, AFE_CTRL); /* Chroma in select */ val |= 0x00001000; val &= 0xfffffe7f; /* Clear VGA_SEL_CH2 and VGA_SEL_CH3 (bits 7 and 8). * This sets them to use video rather than audio. * Only one of the two will be in use. */ cx25840_write4(client, AFE_CTRL, val); } else { cx25840_and_or(client, 0x102, ~0x2, 0); } } state->vid_input = vid_input; state->aud_input = aud_input; cx25840_audio_set_path(client); input_change(client); if (is_cx2388x(state)) { /* Audio channel 1 src : Parallel 1 */ cx25840_write(client, 0x124, 0x03); /* Select AFE clock pad output source */ cx25840_write(client, 0x144, 0x05); /* I2S_IN_CTL: I2S_IN_SONY_MODE, LEFT SAMPLE on WS=1 */ cx25840_write(client, 0x914, 0xa0); /* I2S_OUT_CTL: * I2S_IN_SONY_MODE, LEFT SAMPLE on WS=1 * I2S_OUT_MASTER_MODE = Master */ cx25840_write(client, 0x918, 0xa0); cx25840_write(client, 0x919, 0x01); } else if (is_cx231xx(state)) { /* Audio channel 1 src : Parallel 1 */ cx25840_write(client, 0x124, 0x03); /* I2S_IN_CTL: I2S_IN_SONY_MODE, LEFT SAMPLE on WS=1 */ cx25840_write(client, 0x914, 0xa0); /* I2S_OUT_CTL: * I2S_IN_SONY_MODE, LEFT SAMPLE on WS=1 * I2S_OUT_MASTER_MODE = Master */ cx25840_write(client, 0x918, 0xa0); cx25840_write(client, 0x919, 0x01); } if (is_cx2388x(state) && ((aud_input == CX25840_AUDIO7) || (aud_input == CX25840_AUDIO6))) { /* Configure audio from LR1 or LR2 input */ cx25840_write4(client, 0x910, 0); cx25840_write4(client, 0x8d0, 0x63073); } else if (is_cx2388x(state) && (aud_input == CX25840_AUDIO8)) { /* Configure audio from tuner/sif input */ cx25840_write4(client, 0x910, 0x12b000c9); cx25840_write4(client, 0x8d0, 0x1f063870); } if (is_cx23888(state)) { /* * HVR1850 * * AUD_IO_CTRL - I2S Input, Parallel1 * - Channel 1 src - Parallel1 (Merlin out) * - Channel 2 src - Parallel2 (Merlin out) * - Channel 3 src - Parallel3 (Merlin AC97 out) * - I2S source and dir - Merlin, output */ cx25840_write4(client, 0x124, 0x100); if (!is_dif) { /* * Stop microcontroller if we don't need it * to avoid audio popping on svideo/composite use. */ cx25840_and_or(client, 0x803, ~0x10, 0x00); } } return 0; } /* ----------------------------------------------------------------------- */ static int set_v4lstd(struct i2c_client *client) { struct cx25840_state *state = to_state(i2c_get_clientdata(client)); u8 fmt = 0; /* zero is autodetect */ u8 pal_m = 0; /* First tests should be against specific std */ if (state->std == V4L2_STD_NTSC_M_JP) { fmt = 0x2; } else if (state->std == V4L2_STD_NTSC_443) { fmt = 0x3; } else if (state->std == V4L2_STD_PAL_M) { pal_m = 1; fmt = 0x5; } else if (state->std == V4L2_STD_PAL_N) { fmt = 0x6; } else if (state->std == V4L2_STD_PAL_Nc) { fmt = 0x7; } else if (state->std == V4L2_STD_PAL_60) { fmt = 0x8; } else { /* Then, test against generic ones */ if (state->std & V4L2_STD_NTSC) fmt = 0x1; else if (state->std & V4L2_STD_PAL) fmt = 0x4; else if (state->std & V4L2_STD_SECAM) fmt = 0xc; } v4l_dbg(1, cx25840_debug, client, "changing video std to fmt %i\n", fmt); /* * Follow step 9 of section 3.16 in the cx25840 datasheet. * Without this PAL may display a vertical ghosting effect. * This happens for example with the Yuan MPC622. */ if (fmt >= 4 && fmt < 8) { /* Set format to NTSC-M */ cx25840_and_or(client, 0x400, ~0xf, 1); /* Turn off LCOMB */ cx25840_and_or(client, 0x47b, ~6, 0); } cx25840_and_or(client, 0x400, ~0xf, fmt); cx25840_and_or(client, 0x403, ~0x3, pal_m); if (is_cx23888(state)) cx23888_std_setup(client); else cx25840_std_setup(client); if (!is_cx2583x(state)) input_change(client); return 0; } /* ----------------------------------------------------------------------- */ static int cx25840_s_ctrl(struct v4l2_ctrl *ctrl) { struct v4l2_subdev *sd = to_sd(ctrl); struct cx25840_state *state = to_state(sd); struct i2c_client *client = v4l2_get_subdevdata(sd); switch (ctrl->id) { case V4L2_CID_BRIGHTNESS: cx25840_write(client, 0x414, ctrl->val - 128); break; case V4L2_CID_CONTRAST: cx25840_write(client, 0x415, ctrl->val << 1); break; case V4L2_CID_SATURATION: if (is_cx23888(state)) { cx25840_write(client, 0x418, ctrl->val << 1); cx25840_write(client, 0x419, ctrl->val << 1); } else { cx25840_write(client, 0x420, ctrl->val << 1); cx25840_write(client, 0x421, ctrl->val << 1); } break; case V4L2_CID_HUE: if (is_cx23888(state)) cx25840_write(client, 0x41a, ctrl->val); else cx25840_write(client, 0x422, ctrl->val); break; default: return -EINVAL; } return 0; } /* ----------------------------------------------------------------------- */ static int cx25840_set_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *format) { struct v4l2_mbus_framefmt *fmt = &format->format; struct cx25840_state *state = to_state(sd); struct i2c_client *client = v4l2_get_subdevdata(sd); u32 hsc, vsc, v_src, h_src, v_add; int filter; int is_50hz = !(state->std & V4L2_STD_525_60); if (format->pad || fmt->code != MEDIA_BUS_FMT_FIXED) return -EINVAL; fmt->field = V4L2_FIELD_INTERLACED; fmt->colorspace = V4L2_COLORSPACE_SMPTE170M; if (is_cx23888(state)) { v_src = (cx25840_read(client, 0x42a) & 0x3f) << 4; v_src |= (cx25840_read(client, 0x429) & 0xf0) >> 4; } else { v_src = (cx25840_read(client, 0x476) & 0x3f) << 4; v_src |= (cx25840_read(client, 0x475) & 0xf0) >> 4; } if (is_cx23888(state)) { h_src = (cx25840_read(client, 0x426) & 0x3f) << 4; h_src |= (cx25840_read(client, 0x425) & 0xf0) >> 4; } else { h_src = (cx25840_read(client, 0x472) & 0x3f) << 4; h_src |= (cx25840_read(client, 0x471) & 0xf0) >> 4; } if (!state->generic_mode) { v_add = is_50hz ? 4 : 7; /* * cx23888 in 525-line mode is programmed for 486 active lines * while other chips use 487 active lines. * * See reg 0x428 bits [21:12] in cx23888_std_setup() vs * vactive in cx25840_std_setup(). */ if (is_cx23888(state) && !is_50hz) v_add--; } else { v_add = 0; } if (h_src == 0 || v_src <= v_add) { v4l_err(client, "chip reported picture size (%u x %u) is far too small\n", (unsigned int)h_src, (unsigned int)v_src); /* * that's the best we can do since the output picture * size is completely unknown in this case */ return -EINVAL; } fmt->width = clamp(fmt->width, (h_src + 15) / 16, h_src); if (v_add * 8 >= v_src) fmt->height = clamp(fmt->height, (u32)1, v_src - v_add); else fmt->height = clamp(fmt->height, (v_src - v_add * 8 + 7) / 8, v_src - v_add); if (format->which == V4L2_SUBDEV_FORMAT_TRY) return 0; hsc = (h_src * (1 << 20)) / fmt->width - (1 << 20); vsc = (1 << 16) - (v_src * (1 << 9) / (fmt->height + v_add) - (1 << 9)); vsc &= 0x1fff; if (fmt->width >= 385) filter = 0; else if (fmt->width > 192) filter = 1; else if (fmt->width > 96) filter = 2; else filter = 3; v4l_dbg(1, cx25840_debug, client, "decoder set size %u x %u with scale %x x %x\n", (unsigned int)fmt->width, (unsigned int)fmt->height, (unsigned int)hsc, (unsigned int)vsc); /* HSCALE=hsc */ if (is_cx23888(state)) { cx25840_write4(client, 0x434, hsc | (1 << 24)); /* VSCALE=vsc VS_INTRLACE=1 VFILT=filter */ cx25840_write4(client, 0x438, vsc | (1 << 19) | (filter << 16)); } else { cx25840_write(client, 0x418, hsc & 0xff); cx25840_write(client, 0x419, (hsc >> 8) & 0xff); cx25840_write(client, 0x41a, hsc >> 16); /* VSCALE=vsc */ cx25840_write(client, 0x41c, vsc & 0xff); cx25840_write(client, 0x41d, vsc >> 8); /* VS_INTRLACE=1 VFILT=filter */ cx25840_write(client, 0x41e, 0x8 | filter); } return 0; } /* ----------------------------------------------------------------------- */ static void log_video_status(struct i2c_client *client) { static const char *const fmt_strs[] = { "0x0", "NTSC-M", "NTSC-J", "NTSC-4.43", "PAL-BDGHI", "PAL-M", "PAL-N", "PAL-Nc", "PAL-60", "0x9", "0xA", "0xB", "SECAM", "0xD", "0xE", "0xF" }; struct cx25840_state *state = to_state(i2c_get_clientdata(client)); u8 vidfmt_sel = cx25840_read(client, 0x400) & 0xf; u8 gen_stat1 = cx25840_read(client, 0x40d); u8 gen_stat2 = cx25840_read(client, 0x40e); int vid_input = state->vid_input; v4l_info(client, "Video signal: %spresent\n", (gen_stat2 & 0x20) ? "" : "not "); v4l_info(client, "Detected format: %s\n", fmt_strs[gen_stat1 & 0xf]); v4l_info(client, "Specified standard: %s\n", vidfmt_sel ? fmt_strs[vidfmt_sel] : "automatic detection"); if (vid_input >= CX25840_COMPOSITE1 && vid_input <= CX25840_COMPOSITE8) { v4l_info(client, "Specified video input: Composite %d\n", vid_input - CX25840_COMPOSITE1 + 1); } else { v4l_info(client, "Specified video input: S-Video (Luma In%d, Chroma In%d)\n", (vid_input & 0xf0) >> 4, (vid_input & 0xf00) >> 8); } v4l_info(client, "Specified audioclock freq: %d Hz\n", state->audclk_freq); } /* ----------------------------------------------------------------------- */ static void log_audio_status(struct i2c_client *client) { struct cx25840_state *state = to_state(i2c_get_clientdata(client)); u8 download_ctl = cx25840_read(client, 0x803); u8 mod_det_stat0 = cx25840_read(client, 0x804); u8 mod_det_stat1 = cx25840_read(client, 0x805); u8 audio_config = cx25840_read(client, 0x808); u8 pref_mode = cx25840_read(client, 0x809); u8 afc0 = cx25840_read(client, 0x80b); u8 mute_ctl = cx25840_read(client, 0x8d3); int aud_input = state->aud_input; char *p; switch (mod_det_stat0) { case 0x00: p = "mono"; break; case 0x01: p = "stereo"; break; case 0x02: p = "dual"; break; case 0x04: p = "tri"; break; case 0x10: p = "mono with SAP"; break; case 0x11: p = "stereo with SAP"; break; case 0x12: p = "dual with SAP"; break; case 0x14: p = "tri with SAP"; break; case 0xfe: p = "forced mode"; break; default: p = "not defined"; } v4l_info(client, "Detected audio mode: %s\n", p); switch (mod_det_stat1) { case 0x00: p = "not defined"; break; case 0x01: p = "EIAJ"; break; case 0x02: p = "A2-M"; break; case 0x03: p = "A2-BG"; break; case 0x04: p = "A2-DK1"; break; case 0x05: p = "A2-DK2"; break; case 0x06: p = "A2-DK3"; break; case 0x07: p = "A1 (6.0 MHz FM Mono)"; break; case 0x08: p = "AM-L"; break; case 0x09: p = "NICAM-BG"; break; case 0x0a: p = "NICAM-DK"; break; case 0x0b: p = "NICAM-I"; break; case 0x0c: p = "NICAM-L"; break; case 0x0d: p = "BTSC/EIAJ/A2-M Mono (4.5 MHz FMMono)"; break; case 0x0e: p = "IF FM Radio"; break; case 0x0f: p = "BTSC"; break; case 0x10: p = "high-deviation FM"; break; case 0x11: p = "very high-deviation FM"; break; case 0xfd: p = "unknown audio standard"; break; case 0xfe: p = "forced audio standard"; break; case 0xff: p = "no detected audio standard"; break; default: p = "not defined"; } v4l_info(client, "Detected audio standard: %s\n", p); v4l_info(client, "Audio microcontroller: %s\n", (download_ctl & 0x10) ? ((mute_ctl & 0x2) ? "detecting" : "running") : "stopped"); switch (audio_config >> 4) { case 0x00: p = "undefined"; break; case 0x01: p = "BTSC"; break; case 0x02: p = "EIAJ"; break; case 0x03: p = "A2-M"; break; case 0x04: p = "A2-BG"; break; case 0x05: p = "A2-DK1"; break; case 0x06: p = "A2-DK2"; break; case 0x07: p = "A2-DK3"; break; case 0x08: p = "A1 (6.0 MHz FM Mono)"; break; case 0x09: p = "AM-L"; break; case 0x0a: p = "NICAM-BG"; break; case 0x0b: p = "NICAM-DK"; break; case 0x0c: p = "NICAM-I"; break; case 0x0d: p = "NICAM-L"; break; case 0x0e: p = "FM radio"; break; case 0x0f: p = "automatic detection"; break; default: p = "undefined"; } v4l_info(client, "Configured audio standard: %s\n", p); if ((audio_config >> 4) < 0xF) { switch (audio_config & 0xF) { case 0x00: p = "MONO1 (LANGUAGE A/Mono L+R channel for BTSC, EIAJ, A2)"; break; case 0x01: p = "MONO2 (LANGUAGE B)"; break; case 0x02: p = "MONO3 (STEREO forced MONO)"; break; case 0x03: p = "MONO4 (NICAM ANALOG-Language C/Analog Fallback)"; break; case 0x04: p = "STEREO"; break; case 0x05: p = "DUAL1 (AB)"; break; case 0x06: p = "DUAL2 (AC) (FM)"; break; case 0x07: p = "DUAL3 (BC) (FM)"; break; case 0x08: p = "DUAL4 (AC) (AM)"; break; case 0x09: p = "DUAL5 (BC) (AM)"; break; case 0x0a: p = "SAP"; break; default: p = "undefined"; } v4l_info(client, "Configured audio mode: %s\n", p); } else { switch (audio_config & 0xF) { case 0x00: p = "BG"; break; case 0x01: p = "DK1"; break; case 0x02: p = "DK2"; break; case 0x03: p = "DK3"; break; case 0x04: p = "I"; break; case 0x05: p = "L"; break; case 0x06: p = "BTSC"; break; case 0x07: p = "EIAJ"; break; case 0x08: p = "A2-M"; break; case 0x09: p = "FM Radio"; break; case 0x0f: p = "automatic standard and mode detection"; break; default: p = "undefined"; } v4l_info(client, "Configured audio system: %s\n", p); } if (aud_input) { v4l_info(client, "Specified audio input: Tuner (In%d)\n", aud_input); } else { v4l_info(client, "Specified audio input: External\n"); } switch (pref_mode & 0xf) { case 0: p = "mono/language A"; break; case 1: p = "language B"; break; case 2: p = "language C"; break; case 3: p = "analog fallback"; break; case 4: p = "stereo"; break; case 5: p = "language AC"; break; case 6: p = "language BC"; break; case 7: p = "language AB"; break; default: p = "undefined"; } v4l_info(client, "Preferred audio mode: %s\n", p); if ((audio_config & 0xf) == 0xf) { switch ((afc0 >> 3) & 0x3) { case 0: p = "system DK"; break; case 1: p = "system L"; break; case 2: p = "autodetect"; break; default: p = "undefined"; } v4l_info(client, "Selected 65 MHz format: %s\n", p); switch (afc0 & 0x7) { case 0: p = "chroma"; break; case 1: p = "BTSC"; break; case 2: p = "EIAJ"; break; case 3: p = "A2-M"; break; case 4: p = "autodetect"; break; default: p = "undefined"; } v4l_info(client, "Selected 45 MHz format: %s\n", p); } } #define CX25840_VCONFIG_OPTION(state, cfg_in, opt_msk) \ do { \ if ((cfg_in) & (opt_msk)) { \ (state)->vid_config &= ~(opt_msk); \ (state)->vid_config |= (cfg_in) & (opt_msk); \ } \ } while (0) /* apply incoming options to the current vconfig */ static void cx25840_vconfig_add(struct cx25840_state *state, u32 cfg_in) { CX25840_VCONFIG_OPTION(state, cfg_in, CX25840_VCONFIG_FMT_MASK); CX25840_VCONFIG_OPTION(state, cfg_in, CX25840_VCONFIG_RES_MASK); CX25840_VCONFIG_OPTION(state, cfg_in, CX25840_VCONFIG_VBIRAW_MASK); CX25840_VCONFIG_OPTION(state, cfg_in, CX25840_VCONFIG_ANCDATA_MASK); CX25840_VCONFIG_OPTION(state, cfg_in, CX25840_VCONFIG_TASKBIT_MASK); CX25840_VCONFIG_OPTION(state, cfg_in, CX25840_VCONFIG_ACTIVE_MASK); CX25840_VCONFIG_OPTION(state, cfg_in, CX25840_VCONFIG_VALID_MASK); CX25840_VCONFIG_OPTION(state, cfg_in, CX25840_VCONFIG_HRESETW_MASK); CX25840_VCONFIG_OPTION(state, cfg_in, CX25840_VCONFIG_CLKGATE_MASK); CX25840_VCONFIG_OPTION(state, cfg_in, CX25840_VCONFIG_DCMODE_MASK); CX25840_VCONFIG_OPTION(state, cfg_in, CX25840_VCONFIG_IDID0S_MASK); CX25840_VCONFIG_OPTION(state, cfg_in, CX25840_VCONFIG_VIPCLAMP_MASK); } /* ----------------------------------------------------------------------- */ /* * Initializes the device in the generic mode. * For cx2584x chips also adds additional video output settings provided * in @val parameter (CX25840_VCONFIG_*). * * The generic mode disables some of the ivtv-related hacks in this driver. * For cx2584x chips it also enables setting video output configuration while * setting it according to datasheet defaults by default. */ static int cx25840_init(struct v4l2_subdev *sd, u32 val) { struct cx25840_state *state = to_state(sd); state->generic_mode = true; if (is_cx2584x(state)) { /* set datasheet video output defaults */ state->vid_config = CX25840_VCONFIG_FMT_BT656 | CX25840_VCONFIG_RES_8BIT | CX25840_VCONFIG_VBIRAW_DISABLED | CX25840_VCONFIG_ANCDATA_ENABLED | CX25840_VCONFIG_TASKBIT_ONE | CX25840_VCONFIG_ACTIVE_HORIZONTAL | CX25840_VCONFIG_VALID_NORMAL | CX25840_VCONFIG_HRESETW_NORMAL | CX25840_VCONFIG_CLKGATE_NONE | CX25840_VCONFIG_DCMODE_DWORDS | CX25840_VCONFIG_IDID0S_NORMAL | CX25840_VCONFIG_VIPCLAMP_DISABLED; /* add additional settings */ cx25840_vconfig_add(state, val); } else { /* TODO: generic mode needs to be developed for other chips */ WARN_ON(1); } return 0; } static int cx25840_reset(struct v4l2_subdev *sd, u32 val) { struct cx25840_state *state = to_state(sd); struct i2c_client *client = v4l2_get_subdevdata(sd); if (is_cx2583x(state)) cx25836_initialize(client); else if (is_cx2388x(state)) cx23885_initialize(client); else if (is_cx231xx(state)) cx231xx_initialize(client); else cx25840_initialize(client); state->is_initialized = 1; return 0; } /* * This load_fw operation must be called to load the driver's firmware. * This will load the firmware on the first invocation (further ones are NOP). * Without this the audio standard detection will fail and you will * only get mono. * Alternatively, you can call the reset operation instead of this one. * * Since loading the firmware is often problematic when the driver is * compiled into the kernel I recommend postponing calling this function * until the first open of the video device. Another reason for * postponing it is that loading this firmware takes a long time (seconds) * due to the slow i2c bus speed. So it will speed up the boot process if * you can avoid loading the fw as long as the video device isn't used. */ static int cx25840_load_fw(struct v4l2_subdev *sd) { struct cx25840_state *state = to_state(sd); if (!state->is_initialized) { /* initialize and load firmware */ cx25840_reset(sd, 0); } return 0; } #ifdef CONFIG_VIDEO_ADV_DEBUG static int cx25840_g_register(struct v4l2_subdev *sd, struct v4l2_dbg_register *reg) { struct i2c_client *client = v4l2_get_subdevdata(sd); reg->size = 1; reg->val = cx25840_read(client, reg->reg & 0x0fff); return 0; } static int cx25840_s_register(struct v4l2_subdev *sd, const struct v4l2_dbg_register *reg) { struct i2c_client *client = v4l2_get_subdevdata(sd); cx25840_write(client, reg->reg & 0x0fff, reg->val & 0xff); return 0; } #endif static int cx25840_s_audio_stream(struct v4l2_subdev *sd, int enable) { struct cx25840_state *state = to_state(sd); struct i2c_client *client = v4l2_get_subdevdata(sd); u8 v; if (is_cx2583x(state) || is_cx2388x(state) || is_cx231xx(state)) return 0; v4l_dbg(1, cx25840_debug, client, "%s audio output\n", enable ? "enable" : "disable"); if (enable) { v = cx25840_read(client, 0x115) | 0x80; cx25840_write(client, 0x115, v); v = cx25840_read(client, 0x116) | 0x03; cx25840_write(client, 0x116, v); } else { v = cx25840_read(client, 0x115) & ~(0x80); cx25840_write(client, 0x115, v); v = cx25840_read(client, 0x116) & ~(0x03); cx25840_write(client, 0x116, v); } return 0; } static int cx25840_s_stream(struct v4l2_subdev *sd, int enable) { struct cx25840_state *state = to_state(sd); struct i2c_client *client = v4l2_get_subdevdata(sd); u8 v; v4l_dbg(1, cx25840_debug, client, "%s video output\n", enable ? "enable" : "disable"); /* * It's not clear what should be done for these devices. * The original code used the same addresses as for the cx25840, but * those addresses do something else entirely on the cx2388x and * cx231xx. Since it never did anything in the first place, just do * nothing. */ if (is_cx2388x(state) || is_cx231xx(state)) return 0; if (enable) { v = cx25840_read(client, 0x115) | 0x0c; cx25840_write(client, 0x115, v); v = cx25840_read(client, 0x116) | 0x04; cx25840_write(client, 0x116, v); } else { v = cx25840_read(client, 0x115) & ~(0x0c); cx25840_write(client, 0x115, v); v = cx25840_read(client, 0x116) & ~(0x04); cx25840_write(client, 0x116, v); } return 0; } /* Query the current detected video format */ static int cx25840_querystd(struct v4l2_subdev *sd, v4l2_std_id *std) { struct i2c_client *client = v4l2_get_subdevdata(sd); static const v4l2_std_id stds[] = { /* 0000 */ V4L2_STD_UNKNOWN, /* 0001 */ V4L2_STD_NTSC_M, /* 0010 */ V4L2_STD_NTSC_M_JP, /* 0011 */ V4L2_STD_NTSC_443, /* 0100 */ V4L2_STD_PAL, /* 0101 */ V4L2_STD_PAL_M, /* 0110 */ V4L2_STD_PAL_N, /* 0111 */ V4L2_STD_PAL_Nc, /* 1000 */ V4L2_STD_PAL_60, /* 1001 */ V4L2_STD_UNKNOWN, /* 1010 */ V4L2_STD_UNKNOWN, /* 1011 */ V4L2_STD_UNKNOWN, /* 1100 */ V4L2_STD_SECAM, /* 1101 */ V4L2_STD_UNKNOWN, /* 1110 */ V4L2_STD_UNKNOWN, /* 1111 */ V4L2_STD_UNKNOWN }; u32 fmt = (cx25840_read4(client, 0x40c) >> 8) & 0xf; *std = stds[fmt]; v4l_dbg(1, cx25840_debug, client, "querystd fmt = %x, v4l2_std_id = 0x%x\n", fmt, (unsigned int)stds[fmt]); return 0; } static int cx25840_g_input_status(struct v4l2_subdev *sd, u32 *status) { struct i2c_client *client = v4l2_get_subdevdata(sd); /* * A limited function that checks for signal status and returns * the state. */ /* Check for status of Horizontal lock (SRC lock isn't reliable) */ if ((cx25840_read4(client, 0x40c) & 0x00010000) == 0) *status |= V4L2_IN_ST_NO_SIGNAL; return 0; } static int cx25840_g_std(struct v4l2_subdev *sd, v4l2_std_id *std) { struct cx25840_state *state = to_state(sd); *std = state->std; return 0; } static int cx25840_s_std(struct v4l2_subdev *sd, v4l2_std_id std) { struct cx25840_state *state = to_state(sd); struct i2c_client *client = v4l2_get_subdevdata(sd); if (state->radio == 0 && state->std == std) return 0; state->radio = 0; state->std = std; return set_v4lstd(client); } static int cx25840_s_radio(struct v4l2_subdev *sd) { struct cx25840_state *state = to_state(sd); state->radio = 1; return 0; } static int cx25840_s_video_routing(struct v4l2_subdev *sd, u32 input, u32 output, u32 config) { struct cx25840_state *state = to_state(sd); struct i2c_client *client = v4l2_get_subdevdata(sd); if (is_cx23888(state)) cx23888_std_setup(client); if (is_cx2584x(state) && state->generic_mode && config) { cx25840_vconfig_add(state, config); cx25840_vconfig_apply(client); } return set_input(client, input, state->aud_input); } static int cx25840_s_audio_routing(struct v4l2_subdev *sd, u32 input, u32 output, u32 config) { struct cx25840_state *state = to_state(sd); struct i2c_client *client = v4l2_get_subdevdata(sd); if (is_cx23888(state)) cx23888_std_setup(client); return set_input(client, state->vid_input, input); } static int cx25840_s_frequency(struct v4l2_subdev *sd, const struct v4l2_frequency *freq) { struct i2c_client *client = v4l2_get_subdevdata(sd); input_change(client); return 0; } static int cx25840_g_tuner(struct v4l2_subdev *sd, struct v4l2_tuner *vt) { struct cx25840_state *state = to_state(sd); struct i2c_client *client = v4l2_get_subdevdata(sd); u8 vpres = cx25840_read(client, 0x40e) & 0x20; u8 mode; int val = 0; if (state->radio) return 0; vt->signal = vpres ? 0xffff : 0x0; if (is_cx2583x(state)) return 0; vt->capability |= V4L2_TUNER_CAP_STEREO | V4L2_TUNER_CAP_LANG1 | V4L2_TUNER_CAP_LANG2 | V4L2_TUNER_CAP_SAP; mode = cx25840_read(client, 0x804); /* get rxsubchans and audmode */ if ((mode & 0xf) == 1) val |= V4L2_TUNER_SUB_STEREO; else val |= V4L2_TUNER_SUB_MONO; if (mode == 2 || mode == 4) val = V4L2_TUNER_SUB_LANG1 | V4L2_TUNER_SUB_LANG2; if (mode & 0x10) val |= V4L2_TUNER_SUB_SAP; vt->rxsubchans = val; vt->audmode = state->audmode; return 0; } static int cx25840_s_tuner(struct v4l2_subdev *sd, const struct v4l2_tuner *vt) { struct cx25840_state *state = to_state(sd); struct i2c_client *client = v4l2_get_subdevdata(sd); if (state->radio || is_cx2583x(state)) return 0; switch (vt->audmode) { case V4L2_TUNER_MODE_MONO: /* * mono -> mono * stereo -> mono * bilingual -> lang1 */ cx25840_and_or(client, 0x809, ~0xf, 0x00); break; case V4L2_TUNER_MODE_STEREO: case V4L2_TUNER_MODE_LANG1: /* * mono -> mono * stereo -> stereo * bilingual -> lang1 */ cx25840_and_or(client, 0x809, ~0xf, 0x04); break; case V4L2_TUNER_MODE_LANG1_LANG2: /* * mono -> mono * stereo -> stereo * bilingual -> lang1/lang2 */ cx25840_and_or(client, 0x809, ~0xf, 0x07); break; case V4L2_TUNER_MODE_LANG2: /* * mono -> mono * stereo -> stereo * bilingual -> lang2 */ cx25840_and_or(client, 0x809, ~0xf, 0x01); break; default: return -EINVAL; } state->audmode = vt->audmode; return 0; } static int cx25840_log_status(struct v4l2_subdev *sd) { struct cx25840_state *state = to_state(sd); struct i2c_client *client = v4l2_get_subdevdata(sd); log_video_status(client); if (!is_cx2583x(state)) log_audio_status(client); cx25840_ir_log_status(sd); v4l2_ctrl_handler_log_status(&state->hdl, sd->name); return 0; } static int cx23885_irq_handler(struct v4l2_subdev *sd, u32 status, bool *handled) { struct cx25840_state *state = to_state(sd); struct i2c_client *c = v4l2_get_subdevdata(sd); u8 irq_stat, aud_stat, aud_en, ir_stat, ir_en; u32 vid_stat, aud_mc_stat; bool block_handled; int ret = 0; irq_stat = cx25840_read(c, CX23885_PIN_CTRL_IRQ_REG); v4l_dbg(2, cx25840_debug, c, "AV Core IRQ status (entry): %s %s %s\n", irq_stat & CX23885_PIN_CTRL_IRQ_IR_STAT ? "ir" : " ", irq_stat & CX23885_PIN_CTRL_IRQ_AUD_STAT ? "aud" : " ", irq_stat & CX23885_PIN_CTRL_IRQ_VID_STAT ? "vid" : " "); if ((is_cx23885(state) || is_cx23887(state))) { ir_stat = cx25840_read(c, CX25840_IR_STATS_REG); ir_en = cx25840_read(c, CX25840_IR_IRQEN_REG); v4l_dbg(2, cx25840_debug, c, "AV Core ir IRQ status: %#04x disables: %#04x\n", ir_stat, ir_en); if (irq_stat & CX23885_PIN_CTRL_IRQ_IR_STAT) { block_handled = false; ret = cx25840_ir_irq_handler(sd, status, &block_handled); if (block_handled) *handled = true; } } aud_stat = cx25840_read(c, CX25840_AUD_INT_STAT_REG); aud_en = cx25840_read(c, CX25840_AUD_INT_CTRL_REG); v4l_dbg(2, cx25840_debug, c, "AV Core audio IRQ status: %#04x disables: %#04x\n", aud_stat, aud_en); aud_mc_stat = cx25840_read4(c, CX23885_AUD_MC_INT_MASK_REG); v4l_dbg(2, cx25840_debug, c, "AV Core audio MC IRQ status: %#06x enables: %#06x\n", aud_mc_stat >> CX23885_AUD_MC_INT_STAT_SHFT, aud_mc_stat & CX23885_AUD_MC_INT_CTRL_BITS); if (irq_stat & CX23885_PIN_CTRL_IRQ_AUD_STAT) { if (aud_stat) { cx25840_write(c, CX25840_AUD_INT_STAT_REG, aud_stat); *handled = true; } } vid_stat = cx25840_read4(c, CX25840_VID_INT_STAT_REG); v4l_dbg(2, cx25840_debug, c, "AV Core video IRQ status: %#06x disables: %#06x\n", vid_stat & CX25840_VID_INT_STAT_BITS, vid_stat >> CX25840_VID_INT_MASK_SHFT); if (irq_stat & CX23885_PIN_CTRL_IRQ_VID_STAT) { if (vid_stat & CX25840_VID_INT_STAT_BITS) { cx25840_write4(c, CX25840_VID_INT_STAT_REG, vid_stat); *handled = true; } } irq_stat = cx25840_read(c, CX23885_PIN_CTRL_IRQ_REG); v4l_dbg(2, cx25840_debug, c, "AV Core IRQ status (exit): %s %s %s\n", irq_stat & CX23885_PIN_CTRL_IRQ_IR_STAT ? "ir" : " ", irq_stat & CX23885_PIN_CTRL_IRQ_AUD_STAT ? "aud" : " ", irq_stat & CX23885_PIN_CTRL_IRQ_VID_STAT ? "vid" : " "); return ret; } static int cx25840_irq_handler(struct v4l2_subdev *sd, u32 status, bool *handled) { struct cx25840_state *state = to_state(sd); *handled = false; /* Only support the CX2388[578] AV Core for now */ if (is_cx2388x(state)) return cx23885_irq_handler(sd, status, handled); return -ENODEV; } /* ----------------------------------------------------------------------- */ #define DIF_PLL_FREQ_WORD (0x300) #define DIF_BPF_COEFF01 (0x348) #define DIF_BPF_COEFF23 (0x34c) #define DIF_BPF_COEFF45 (0x350) #define DIF_BPF_COEFF67 (0x354) #define DIF_BPF_COEFF89 (0x358) #define DIF_BPF_COEFF1011 (0x35c) #define DIF_BPF_COEFF1213 (0x360) #define DIF_BPF_COEFF1415 (0x364) #define DIF_BPF_COEFF1617 (0x368) #define DIF_BPF_COEFF1819 (0x36c) #define DIF_BPF_COEFF2021 (0x370) #define DIF_BPF_COEFF2223 (0x374) #define DIF_BPF_COEFF2425 (0x378) #define DIF_BPF_COEFF2627 (0x37c) #define DIF_BPF_COEFF2829 (0x380) #define DIF_BPF_COEFF3031 (0x384) #define DIF_BPF_COEFF3233 (0x388) #define DIF_BPF_COEFF3435 (0x38c) #define DIF_BPF_COEFF36 (0x390) static void cx23885_dif_setup(struct i2c_client *client, u32 ifHz) { u64 pll_freq; u32 pll_freq_word; v4l_dbg(1, cx25840_debug, client, "%s(%d)\n", __func__, ifHz); /* Assuming TV */ /* Calculate the PLL frequency word based on the adjusted ifHz */ pll_freq = div_u64((u64)ifHz * 268435456, 50000000); pll_freq_word = (u32)pll_freq; cx25840_write4(client, DIF_PLL_FREQ_WORD, pll_freq_word); /* Round down to the nearest 100KHz */ ifHz = (ifHz / 100000) * 100000; if (ifHz < 3000000) ifHz = 3000000; if (ifHz > 16000000) ifHz = 16000000; v4l_dbg(1, cx25840_debug, client, "%s(%d) again\n", __func__, ifHz); switch (ifHz) { case 3000000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000002); cx25840_write4(client, DIF_BPF_COEFF23, 0x00080012); cx25840_write4(client, DIF_BPF_COEFF45, 0x001e0024); cx25840_write4(client, DIF_BPF_COEFF67, 0x001bfff8); cx25840_write4(client, DIF_BPF_COEFF89, 0xffb4ff50); cx25840_write4(client, DIF_BPF_COEFF1011, 0xfed8fe68); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe24fe34); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfebaffc7); cx25840_write4(client, DIF_BPF_COEFF1617, 0x014d031f); cx25840_write4(client, DIF_BPF_COEFF1819, 0x04f0065d); cx25840_write4(client, DIF_BPF_COEFF2021, 0x07010688); cx25840_write4(client, DIF_BPF_COEFF2223, 0x04c901d6); cx25840_write4(client, DIF_BPF_COEFF2425, 0xfe00f9d3); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf600f342); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf235f337); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf64efb22); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0105070f); cx25840_write4(client, DIF_BPF_COEFF3435, 0x0c460fce); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 3100000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000001); cx25840_write4(client, DIF_BPF_COEFF23, 0x00070012); cx25840_write4(client, DIF_BPF_COEFF45, 0x00220032); cx25840_write4(client, DIF_BPF_COEFF67, 0x00370026); cx25840_write4(client, DIF_BPF_COEFF89, 0xfff0ff91); cx25840_write4(client, DIF_BPF_COEFF1011, 0xff0efe7c); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe01fdcc); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfe0afedb); cx25840_write4(client, DIF_BPF_COEFF1617, 0x00440224); cx25840_write4(client, DIF_BPF_COEFF1819, 0x0434060c); cx25840_write4(client, DIF_BPF_COEFF2021, 0x0738074e); cx25840_write4(client, DIF_BPF_COEFF2223, 0x06090361); cx25840_write4(client, DIF_BPF_COEFF2425, 0xff99fb39); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf6fef3b6); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf21af2a5); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf573fa33); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0034067d); cx25840_write4(client, DIF_BPF_COEFF3435, 0x0bfb0fb9); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 3200000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000000); cx25840_write4(client, DIF_BPF_COEFF23, 0x0004000e); cx25840_write4(client, DIF_BPF_COEFF45, 0x00200038); cx25840_write4(client, DIF_BPF_COEFF67, 0x004c004f); cx25840_write4(client, DIF_BPF_COEFF89, 0x002fffdf); cx25840_write4(client, DIF_BPF_COEFF1011, 0xff5cfeb6); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe0dfd92); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfd7ffe03); cx25840_write4(client, DIF_BPF_COEFF1617, 0xff36010a); cx25840_write4(client, DIF_BPF_COEFF1819, 0x03410575); cx25840_write4(client, DIF_BPF_COEFF2021, 0x072607d2); cx25840_write4(client, DIF_BPF_COEFF2223, 0x071804d5); cx25840_write4(client, DIF_BPF_COEFF2425, 0x0134fcb7); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf81ff451); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf223f22e); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf4a7f94b); cx25840_write4(client, DIF_BPF_COEFF3233, 0xff6405e8); cx25840_write4(client, DIF_BPF_COEFF3435, 0x0bae0fa4); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 3300000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0000ffff); cx25840_write4(client, DIF_BPF_COEFF23, 0x00000008); cx25840_write4(client, DIF_BPF_COEFF45, 0x001a0036); cx25840_write4(client, DIF_BPF_COEFF67, 0x0056006d); cx25840_write4(client, DIF_BPF_COEFF89, 0x00670030); cx25840_write4(client, DIF_BPF_COEFF1011, 0xffbdff10); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe46fd8d); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfd25fd4f); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfe35ffe0); cx25840_write4(client, DIF_BPF_COEFF1819, 0x0224049f); cx25840_write4(client, DIF_BPF_COEFF2021, 0x06c9080e); cx25840_write4(client, DIF_BPF_COEFF2223, 0x07ef0627); cx25840_write4(client, DIF_BPF_COEFF2425, 0x02c9fe45); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf961f513); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf250f1d2); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf3ecf869); cx25840_write4(client, DIF_BPF_COEFF3233, 0xfe930552); cx25840_write4(client, DIF_BPF_COEFF3435, 0x0b5f0f8f); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 3400000: cx25840_write4(client, DIF_BPF_COEFF01, 0xfffffffe); cx25840_write4(client, DIF_BPF_COEFF23, 0xfffd0001); cx25840_write4(client, DIF_BPF_COEFF45, 0x000f002c); cx25840_write4(client, DIF_BPF_COEFF67, 0x0054007d); cx25840_write4(client, DIF_BPF_COEFF89, 0x0093007c); cx25840_write4(client, DIF_BPF_COEFF1011, 0x0024ff82); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfea6fdbb); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfd03fcca); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfd51feb9); cx25840_write4(client, DIF_BPF_COEFF1819, 0x00eb0392); cx25840_write4(client, DIF_BPF_COEFF2021, 0x06270802); cx25840_write4(client, DIF_BPF_COEFF2223, 0x08880750); cx25840_write4(client, DIF_BPF_COEFF2425, 0x044dffdb); cx25840_write4(client, DIF_BPF_COEFF2627, 0xfabdf5f8); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf2a0f193); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf342f78f); cx25840_write4(client, DIF_BPF_COEFF3233, 0xfdc404b9); cx25840_write4(client, DIF_BPF_COEFF3435, 0x0b0e0f78); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 3500000: cx25840_write4(client, DIF_BPF_COEFF01, 0xfffffffd); cx25840_write4(client, DIF_BPF_COEFF23, 0xfffafff9); cx25840_write4(client, DIF_BPF_COEFF45, 0x0002001b); cx25840_write4(client, DIF_BPF_COEFF67, 0x0046007d); cx25840_write4(client, DIF_BPF_COEFF89, 0x00ad00ba); cx25840_write4(client, DIF_BPF_COEFF1011, 0x00870000); cx25840_write4(client, DIF_BPF_COEFF1213, 0xff26fe1a); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfd1bfc7e); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfc99fda4); cx25840_write4(client, DIF_BPF_COEFF1819, 0xffa5025c); cx25840_write4(client, DIF_BPF_COEFF2021, 0x054507ad); cx25840_write4(client, DIF_BPF_COEFF2223, 0x08dd0847); cx25840_write4(client, DIF_BPF_COEFF2425, 0x05b80172); cx25840_write4(client, DIF_BPF_COEFF2627, 0xfc2ef6ff); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf313f170); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf2abf6bd); cx25840_write4(client, DIF_BPF_COEFF3233, 0xfcf6041f); cx25840_write4(client, DIF_BPF_COEFF3435, 0x0abc0f61); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 3600000: cx25840_write4(client, DIF_BPF_COEFF01, 0xfffffffd); cx25840_write4(client, DIF_BPF_COEFF23, 0xfff8fff3); cx25840_write4(client, DIF_BPF_COEFF45, 0xfff50006); cx25840_write4(client, DIF_BPF_COEFF67, 0x002f006c); cx25840_write4(client, DIF_BPF_COEFF89, 0x00b200e3); cx25840_write4(client, DIF_BPF_COEFF1011, 0x00dc007e); cx25840_write4(client, DIF_BPF_COEFF1213, 0xffb9fea0); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfd6bfc71); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfc17fcb1); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfe65010b); cx25840_write4(client, DIF_BPF_COEFF2021, 0x042d0713); cx25840_write4(client, DIF_BPF_COEFF2223, 0x08ec0906); cx25840_write4(client, DIF_BPF_COEFF2425, 0x07020302); cx25840_write4(client, DIF_BPF_COEFF2627, 0xfdaff823); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf3a7f16a); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf228f5f5); cx25840_write4(client, DIF_BPF_COEFF3233, 0xfc2a0384); cx25840_write4(client, DIF_BPF_COEFF3435, 0x0a670f4a); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 3700000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0000fffd); cx25840_write4(client, DIF_BPF_COEFF23, 0xfff7ffef); cx25840_write4(client, DIF_BPF_COEFF45, 0xffe9fff1); cx25840_write4(client, DIF_BPF_COEFF67, 0x0010004d); cx25840_write4(client, DIF_BPF_COEFF89, 0x00a100f2); cx25840_write4(client, DIF_BPF_COEFF1011, 0x011a00f0); cx25840_write4(client, DIF_BPF_COEFF1213, 0x0053ff44); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfdedfca2); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfbd3fbef); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfd39ffae); cx25840_write4(client, DIF_BPF_COEFF2021, 0x02ea0638); cx25840_write4(client, DIF_BPF_COEFF2223, 0x08b50987); cx25840_write4(client, DIF_BPF_COEFF2425, 0x08230483); cx25840_write4(client, DIF_BPF_COEFF2627, 0xff39f960); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf45bf180); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf1b8f537); cx25840_write4(client, DIF_BPF_COEFF3233, 0xfb6102e7); cx25840_write4(client, DIF_BPF_COEFF3435, 0x0a110f32); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 3800000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0000fffe); cx25840_write4(client, DIF_BPF_COEFF23, 0xfff9ffee); cx25840_write4(client, DIF_BPF_COEFF45, 0xffe1ffdd); cx25840_write4(client, DIF_BPF_COEFF67, 0xfff00024); cx25840_write4(client, DIF_BPF_COEFF89, 0x007c00e5); cx25840_write4(client, DIF_BPF_COEFF1011, 0x013a014a); cx25840_write4(client, DIF_BPF_COEFF1213, 0x00e6fff8); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfe98fd0f); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfbd3fb67); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfc32fe54); cx25840_write4(client, DIF_BPF_COEFF2021, 0x01880525); cx25840_write4(client, DIF_BPF_COEFF2223, 0x083909c7); cx25840_write4(client, DIF_BPF_COEFF2425, 0x091505ee); cx25840_write4(client, DIF_BPF_COEFF2627, 0x00c7fab3); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf52df1b4); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf15df484); cx25840_write4(client, DIF_BPF_COEFF3233, 0xfa9b0249); cx25840_write4(client, DIF_BPF_COEFF3435, 0x09ba0f19); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 3900000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000000); cx25840_write4(client, DIF_BPF_COEFF23, 0xfffbfff0); cx25840_write4(client, DIF_BPF_COEFF45, 0xffdeffcf); cx25840_write4(client, DIF_BPF_COEFF67, 0xffd1fff6); cx25840_write4(client, DIF_BPF_COEFF89, 0x004800be); cx25840_write4(client, DIF_BPF_COEFF1011, 0x01390184); cx25840_write4(client, DIF_BPF_COEFF1213, 0x016300ac); cx25840_write4(client, DIF_BPF_COEFF1415, 0xff5efdb1); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfc17fb23); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfb5cfd0d); cx25840_write4(client, DIF_BPF_COEFF2021, 0x001703e4); cx25840_write4(client, DIF_BPF_COEFF2223, 0x077b09c4); cx25840_write4(client, DIF_BPF_COEFF2425, 0x09d2073c); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0251fc18); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf61cf203); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf118f3dc); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf9d801aa); cx25840_write4(client, DIF_BPF_COEFF3435, 0x09600eff); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 4000000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000001); cx25840_write4(client, DIF_BPF_COEFF23, 0xfffefff4); cx25840_write4(client, DIF_BPF_COEFF45, 0xffe1ffc8); cx25840_write4(client, DIF_BPF_COEFF67, 0xffbaffca); cx25840_write4(client, DIF_BPF_COEFF89, 0x000b0082); cx25840_write4(client, DIF_BPF_COEFF1011, 0x01170198); cx25840_write4(client, DIF_BPF_COEFF1213, 0x01c10152); cx25840_write4(client, DIF_BPF_COEFF1415, 0x0030fe7b); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfc99fb24); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfac3fbe9); cx25840_write4(client, DIF_BPF_COEFF2021, 0xfea5027f); cx25840_write4(client, DIF_BPF_COEFF2223, 0x0683097f); cx25840_write4(client, DIF_BPF_COEFF2425, 0x0a560867); cx25840_write4(client, DIF_BPF_COEFF2627, 0x03d2fd89); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf723f26f); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf0e8f341); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf919010a); cx25840_write4(client, DIF_BPF_COEFF3435, 0x09060ee5); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 4100000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00010002); cx25840_write4(client, DIF_BPF_COEFF23, 0x0002fffb); cx25840_write4(client, DIF_BPF_COEFF45, 0xffe8ffca); cx25840_write4(client, DIF_BPF_COEFF67, 0xffacffa4); cx25840_write4(client, DIF_BPF_COEFF89, 0xffcd0036); cx25840_write4(client, DIF_BPF_COEFF1011, 0x00d70184); cx25840_write4(client, DIF_BPF_COEFF1213, 0x01f601dc); cx25840_write4(client, DIF_BPF_COEFF1415, 0x00ffff60); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfd51fb6d); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfa6efaf5); cx25840_write4(client, DIF_BPF_COEFF2021, 0xfd410103); cx25840_write4(client, DIF_BPF_COEFF2223, 0x055708f9); cx25840_write4(client, DIF_BPF_COEFF2425, 0x0a9e0969); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0543ff02); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf842f2f5); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf0cef2b2); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf85e006b); cx25840_write4(client, DIF_BPF_COEFF3435, 0x08aa0ecb); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 4200000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00010003); cx25840_write4(client, DIF_BPF_COEFF23, 0x00050003); cx25840_write4(client, DIF_BPF_COEFF45, 0xfff3ffd3); cx25840_write4(client, DIF_BPF_COEFF67, 0xffaaff8b); cx25840_write4(client, DIF_BPF_COEFF89, 0xff95ffe5); cx25840_write4(client, DIF_BPF_COEFF1011, 0x0080014a); cx25840_write4(client, DIF_BPF_COEFF1213, 0x01fe023f); cx25840_write4(client, DIF_BPF_COEFF1415, 0x01ba0050); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfe35fbf8); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfa62fa3b); cx25840_write4(client, DIF_BPF_COEFF2021, 0xfbf9ff7e); cx25840_write4(client, DIF_BPF_COEFF2223, 0x04010836); cx25840_write4(client, DIF_BPF_COEFF2425, 0x0aa90a3d); cx25840_write4(client, DIF_BPF_COEFF2627, 0x069f007f); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf975f395); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf0cbf231); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf7a9ffcb); cx25840_write4(client, DIF_BPF_COEFF3435, 0x084c0eaf); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 4300000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00010003); cx25840_write4(client, DIF_BPF_COEFF23, 0x0008000a); cx25840_write4(client, DIF_BPF_COEFF45, 0x0000ffe4); cx25840_write4(client, DIF_BPF_COEFF67, 0xffb4ff81); cx25840_write4(client, DIF_BPF_COEFF89, 0xff6aff96); cx25840_write4(client, DIF_BPF_COEFF1011, 0x001c00f0); cx25840_write4(client, DIF_BPF_COEFF1213, 0x01d70271); cx25840_write4(client, DIF_BPF_COEFF1415, 0x0254013b); cx25840_write4(client, DIF_BPF_COEFF1617, 0xff36fcbd); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfa9ff9c5); cx25840_write4(client, DIF_BPF_COEFF2021, 0xfadbfdfe); cx25840_write4(client, DIF_BPF_COEFF2223, 0x028c073b); cx25840_write4(client, DIF_BPF_COEFF2425, 0x0a750adf); cx25840_write4(client, DIF_BPF_COEFF2627, 0x07e101fa); cx25840_write4(client, DIF_BPF_COEFF2829, 0xfab8f44e); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf0ddf1be); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf6f9ff2b); cx25840_write4(client, DIF_BPF_COEFF3435, 0x07ed0e94); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 4400000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000003); cx25840_write4(client, DIF_BPF_COEFF23, 0x0009000f); cx25840_write4(client, DIF_BPF_COEFF45, 0x000efff8); cx25840_write4(client, DIF_BPF_COEFF67, 0xffc9ff87); cx25840_write4(client, DIF_BPF_COEFF89, 0xff52ff54); cx25840_write4(client, DIF_BPF_COEFF1011, 0xffb5007e); cx25840_write4(client, DIF_BPF_COEFF1213, 0x01860270); cx25840_write4(client, DIF_BPF_COEFF1415, 0x02c00210); cx25840_write4(client, DIF_BPF_COEFF1617, 0x0044fdb2); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfb22f997); cx25840_write4(client, DIF_BPF_COEFF2021, 0xf9f2fc90); cx25840_write4(client, DIF_BPF_COEFF2223, 0x0102060f); cx25840_write4(client, DIF_BPF_COEFF2425, 0x0a050b4c); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0902036e); cx25840_write4(client, DIF_BPF_COEFF2829, 0xfc0af51e); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf106f15a); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf64efe8b); cx25840_write4(client, DIF_BPF_COEFF3435, 0x078d0e77); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 4500000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000002); cx25840_write4(client, DIF_BPF_COEFF23, 0x00080012); cx25840_write4(client, DIF_BPF_COEFF45, 0x0019000e); cx25840_write4(client, DIF_BPF_COEFF67, 0xffe5ff9e); cx25840_write4(client, DIF_BPF_COEFF89, 0xff4fff25); cx25840_write4(client, DIF_BPF_COEFF1011, 0xff560000); cx25840_write4(client, DIF_BPF_COEFF1213, 0x0112023b); cx25840_write4(client, DIF_BPF_COEFF1415, 0x02f702c0); cx25840_write4(client, DIF_BPF_COEFF1617, 0x014dfec8); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfbe5f9b3); cx25840_write4(client, DIF_BPF_COEFF2021, 0xf947fb41); cx25840_write4(client, DIF_BPF_COEFF2223, 0xff7004b9); cx25840_write4(client, DIF_BPF_COEFF2425, 0x095a0b81); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0a0004d8); cx25840_write4(client, DIF_BPF_COEFF2829, 0xfd65f603); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf144f104); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf5aafdec); cx25840_write4(client, DIF_BPF_COEFF3435, 0x072b0e5a); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 4600000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000001); cx25840_write4(client, DIF_BPF_COEFF23, 0x00060012); cx25840_write4(client, DIF_BPF_COEFF45, 0x00200022); cx25840_write4(client, DIF_BPF_COEFF67, 0x0005ffc1); cx25840_write4(client, DIF_BPF_COEFF89, 0xff61ff10); cx25840_write4(client, DIF_BPF_COEFF1011, 0xff09ff82); cx25840_write4(client, DIF_BPF_COEFF1213, 0x008601d7); cx25840_write4(client, DIF_BPF_COEFF1415, 0x02f50340); cx25840_write4(client, DIF_BPF_COEFF1617, 0x0241fff0); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfcddfa19); cx25840_write4(client, DIF_BPF_COEFF2021, 0xf8e2fa1e); cx25840_write4(client, DIF_BPF_COEFF2223, 0xfde30343); cx25840_write4(client, DIF_BPF_COEFF2425, 0x08790b7f); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0ad50631); cx25840_write4(client, DIF_BPF_COEFF2829, 0xfec7f6fc); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf198f0bd); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf50dfd4e); cx25840_write4(client, DIF_BPF_COEFF3435, 0x06c90e3d); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 4700000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0000ffff); cx25840_write4(client, DIF_BPF_COEFF23, 0x0003000f); cx25840_write4(client, DIF_BPF_COEFF45, 0x00220030); cx25840_write4(client, DIF_BPF_COEFF67, 0x0025ffed); cx25840_write4(client, DIF_BPF_COEFF89, 0xff87ff15); cx25840_write4(client, DIF_BPF_COEFF1011, 0xfed6ff10); cx25840_write4(client, DIF_BPF_COEFF1213, 0xffed014c); cx25840_write4(client, DIF_BPF_COEFF1415, 0x02b90386); cx25840_write4(client, DIF_BPF_COEFF1617, 0x03110119); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfdfefac4); cx25840_write4(client, DIF_BPF_COEFF2021, 0xf8c6f92f); cx25840_write4(client, DIF_BPF_COEFF2223, 0xfc6701b7); cx25840_write4(client, DIF_BPF_COEFF2425, 0x07670b44); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0b7e0776); cx25840_write4(client, DIF_BPF_COEFF2829, 0x002df807); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf200f086); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf477fcb1); cx25840_write4(client, DIF_BPF_COEFF3435, 0x06650e1e); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 4800000: cx25840_write4(client, DIF_BPF_COEFF01, 0xfffffffe); cx25840_write4(client, DIF_BPF_COEFF23, 0xffff0009); cx25840_write4(client, DIF_BPF_COEFF45, 0x001e0038); cx25840_write4(client, DIF_BPF_COEFF67, 0x003f001b); cx25840_write4(client, DIF_BPF_COEFF89, 0xffbcff36); cx25840_write4(client, DIF_BPF_COEFF1011, 0xfec2feb6); cx25840_write4(client, DIF_BPF_COEFF1213, 0xff5600a5); cx25840_write4(client, DIF_BPF_COEFF1415, 0x0248038d); cx25840_write4(client, DIF_BPF_COEFF1617, 0x03b00232); cx25840_write4(client, DIF_BPF_COEFF1819, 0xff39fbab); cx25840_write4(client, DIF_BPF_COEFF2021, 0xf8f4f87f); cx25840_write4(client, DIF_BPF_COEFF2223, 0xfb060020); cx25840_write4(client, DIF_BPF_COEFF2425, 0x062a0ad2); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0bf908a3); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0192f922); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf27df05e); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf3e8fc14); cx25840_write4(client, DIF_BPF_COEFF3435, 0x06000e00); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 4900000: cx25840_write4(client, DIF_BPF_COEFF01, 0xfffffffd); cx25840_write4(client, DIF_BPF_COEFF23, 0xfffc0002); cx25840_write4(client, DIF_BPF_COEFF45, 0x00160037); cx25840_write4(client, DIF_BPF_COEFF67, 0x00510046); cx25840_write4(client, DIF_BPF_COEFF89, 0xfff9ff6d); cx25840_write4(client, DIF_BPF_COEFF1011, 0xfed0fe7c); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfecefff0); cx25840_write4(client, DIF_BPF_COEFF1415, 0x01aa0356); cx25840_write4(client, DIF_BPF_COEFF1617, 0x0413032b); cx25840_write4(client, DIF_BPF_COEFF1819, 0x007ffcc5); cx25840_write4(client, DIF_BPF_COEFF2021, 0xf96cf812); cx25840_write4(client, DIF_BPF_COEFF2223, 0xf9cefe87); cx25840_write4(client, DIF_BPF_COEFF2425, 0x04c90a2c); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0c4309b4); cx25840_write4(client, DIF_BPF_COEFF2829, 0x02f3fa4a); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf30ef046); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf361fb7a); cx25840_write4(client, DIF_BPF_COEFF3435, 0x059b0de0); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 5000000: cx25840_write4(client, DIF_BPF_COEFF01, 0xfffffffd); cx25840_write4(client, DIF_BPF_COEFF23, 0xfff9fffa); cx25840_write4(client, DIF_BPF_COEFF45, 0x000a002d); cx25840_write4(client, DIF_BPF_COEFF67, 0x00570067); cx25840_write4(client, DIF_BPF_COEFF89, 0x0037ffb5); cx25840_write4(client, DIF_BPF_COEFF1011, 0xfefffe68); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe62ff3d); cx25840_write4(client, DIF_BPF_COEFF1415, 0x00ec02e3); cx25840_write4(client, DIF_BPF_COEFF1617, 0x043503f6); cx25840_write4(client, DIF_BPF_COEFF1819, 0x01befe05); cx25840_write4(client, DIF_BPF_COEFF2021, 0xfa27f7ee); cx25840_write4(client, DIF_BPF_COEFF2223, 0xf8c6fcf8); cx25840_write4(client, DIF_BPF_COEFF2425, 0x034c0954); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0c5c0aa4); cx25840_write4(client, DIF_BPF_COEFF2829, 0x044cfb7e); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf3b1f03f); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf2e2fae1); cx25840_write4(client, DIF_BPF_COEFF3435, 0x05340dc0); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 5100000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0000fffd); cx25840_write4(client, DIF_BPF_COEFF23, 0xfff8fff4); cx25840_write4(client, DIF_BPF_COEFF45, 0xfffd001e); cx25840_write4(client, DIF_BPF_COEFF67, 0x0051007b); cx25840_write4(client, DIF_BPF_COEFF89, 0x006e0006); cx25840_write4(client, DIF_BPF_COEFF1011, 0xff48fe7c); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe1bfe9a); cx25840_write4(client, DIF_BPF_COEFF1415, 0x001d023e); cx25840_write4(client, DIF_BPF_COEFF1617, 0x04130488); cx25840_write4(client, DIF_BPF_COEFF1819, 0x02e6ff5b); cx25840_write4(client, DIF_BPF_COEFF2021, 0xfb1ef812); cx25840_write4(client, DIF_BPF_COEFF2223, 0xf7f7fb7f); cx25840_write4(client, DIF_BPF_COEFF2425, 0x01bc084e); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0c430b72); cx25840_write4(client, DIF_BPF_COEFF2829, 0x059afcba); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf467f046); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf26cfa4a); cx25840_write4(client, DIF_BPF_COEFF3435, 0x04cd0da0); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 5200000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0000fffe); cx25840_write4(client, DIF_BPF_COEFF23, 0xfff8ffef); cx25840_write4(client, DIF_BPF_COEFF45, 0xfff00009); cx25840_write4(client, DIF_BPF_COEFF67, 0x003f007f); cx25840_write4(client, DIF_BPF_COEFF89, 0x00980056); cx25840_write4(client, DIF_BPF_COEFF1011, 0xffa5feb6); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe00fe15); cx25840_write4(client, DIF_BPF_COEFF1415, 0xff4b0170); cx25840_write4(client, DIF_BPF_COEFF1617, 0x03b004d7); cx25840_write4(client, DIF_BPF_COEFF1819, 0x03e800b9); cx25840_write4(client, DIF_BPF_COEFF2021, 0xfc48f87f); cx25840_write4(client, DIF_BPF_COEFF2223, 0xf768fa23); cx25840_write4(client, DIF_BPF_COEFF2425, 0x0022071f); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0bf90c1b); cx25840_write4(client, DIF_BPF_COEFF2829, 0x06dafdfd); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf52df05e); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf1fef9b5); cx25840_write4(client, DIF_BPF_COEFF3435, 0x04640d7f); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 5300000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0000ffff); cx25840_write4(client, DIF_BPF_COEFF23, 0xfff9ffee); cx25840_write4(client, DIF_BPF_COEFF45, 0xffe6fff3); cx25840_write4(client, DIF_BPF_COEFF67, 0x00250072); cx25840_write4(client, DIF_BPF_COEFF89, 0x00af009c); cx25840_write4(client, DIF_BPF_COEFF1011, 0x000cff10); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe13fdb8); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfe870089); cx25840_write4(client, DIF_BPF_COEFF1617, 0x031104e1); cx25840_write4(client, DIF_BPF_COEFF1819, 0x04b8020f); cx25840_write4(client, DIF_BPF_COEFF2021, 0xfd98f92f); cx25840_write4(client, DIF_BPF_COEFF2223, 0xf71df8f0); cx25840_write4(client, DIF_BPF_COEFF2425, 0xfe8805ce); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0b7e0c9c); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0808ff44); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf603f086); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf19af922); cx25840_write4(client, DIF_BPF_COEFF3435, 0x03fb0d5e); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 5400000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000001); cx25840_write4(client, DIF_BPF_COEFF23, 0xfffcffef); cx25840_write4(client, DIF_BPF_COEFF45, 0xffe0ffe0); cx25840_write4(client, DIF_BPF_COEFF67, 0x00050056); cx25840_write4(client, DIF_BPF_COEFF89, 0x00b000d1); cx25840_write4(client, DIF_BPF_COEFF1011, 0x0071ff82); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe53fd8c); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfddfff99); cx25840_write4(client, DIF_BPF_COEFF1617, 0x024104a3); cx25840_write4(client, DIF_BPF_COEFF1819, 0x054a034d); cx25840_write4(client, DIF_BPF_COEFF2021, 0xff01fa1e); cx25840_write4(client, DIF_BPF_COEFF2223, 0xf717f7ed); cx25840_write4(client, DIF_BPF_COEFF2425, 0xfcf50461); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0ad50cf4); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0921008d); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf6e7f0bd); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf13ff891); cx25840_write4(client, DIF_BPF_COEFF3435, 0x03920d3b); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 5500000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00010002); cx25840_write4(client, DIF_BPF_COEFF23, 0xfffffff3); cx25840_write4(client, DIF_BPF_COEFF45, 0xffdeffd1); cx25840_write4(client, DIF_BPF_COEFF67, 0xffe5002f); cx25840_write4(client, DIF_BPF_COEFF89, 0x009c00ed); cx25840_write4(client, DIF_BPF_COEFF1011, 0x00cb0000); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfebafd94); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfd61feb0); cx25840_write4(client, DIF_BPF_COEFF1617, 0x014d0422); cx25840_write4(client, DIF_BPF_COEFF1819, 0x05970464); cx25840_write4(client, DIF_BPF_COEFF2021, 0x0074fb41); cx25840_write4(client, DIF_BPF_COEFF2223, 0xf759f721); cx25840_write4(client, DIF_BPF_COEFF2425, 0xfb7502de); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0a000d21); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0a2201d4); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf7d9f104); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf0edf804); cx25840_write4(client, DIF_BPF_COEFF3435, 0x03280d19); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 5600000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00010003); cx25840_write4(client, DIF_BPF_COEFF23, 0x0003fffa); cx25840_write4(client, DIF_BPF_COEFF45, 0xffe3ffc9); cx25840_write4(client, DIF_BPF_COEFF67, 0xffc90002); cx25840_write4(client, DIF_BPF_COEFF89, 0x007500ef); cx25840_write4(client, DIF_BPF_COEFF1011, 0x010e007e); cx25840_write4(client, DIF_BPF_COEFF1213, 0xff3dfdcf); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfd16fddd); cx25840_write4(client, DIF_BPF_COEFF1617, 0x00440365); cx25840_write4(client, DIF_BPF_COEFF1819, 0x059b0548); cx25840_write4(client, DIF_BPF_COEFF2021, 0x01e3fc90); cx25840_write4(client, DIF_BPF_COEFF2223, 0xf7dff691); cx25840_write4(client, DIF_BPF_COEFF2425, 0xfa0f014d); cx25840_write4(client, DIF_BPF_COEFF2627, 0x09020d23); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0b0a0318); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf8d7f15a); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf0a5f779); cx25840_write4(client, DIF_BPF_COEFF3435, 0x02bd0cf6); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 5700000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00010003); cx25840_write4(client, DIF_BPF_COEFF23, 0x00060001); cx25840_write4(client, DIF_BPF_COEFF45, 0xffecffc9); cx25840_write4(client, DIF_BPF_COEFF67, 0xffb4ffd4); cx25840_write4(client, DIF_BPF_COEFF89, 0x004000d5); cx25840_write4(client, DIF_BPF_COEFF1011, 0x013600f0); cx25840_write4(client, DIF_BPF_COEFF1213, 0xffd3fe39); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfd04fd31); cx25840_write4(client, DIF_BPF_COEFF1617, 0xff360277); cx25840_write4(client, DIF_BPF_COEFF1819, 0x055605ef); cx25840_write4(client, DIF_BPF_COEFF2021, 0x033efdfe); cx25840_write4(client, DIF_BPF_COEFF2223, 0xf8a5f642); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf8cbffb6); cx25840_write4(client, DIF_BPF_COEFF2627, 0x07e10cfb); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0bd50456); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf9dff1be); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf067f6f2); cx25840_write4(client, DIF_BPF_COEFF3435, 0x02520cd2); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 5800000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000003); cx25840_write4(client, DIF_BPF_COEFF23, 0x00080009); cx25840_write4(client, DIF_BPF_COEFF45, 0xfff8ffd2); cx25840_write4(client, DIF_BPF_COEFF67, 0xffaaffac); cx25840_write4(client, DIF_BPF_COEFF89, 0x000200a3); cx25840_write4(client, DIF_BPF_COEFF1011, 0x013c014a); cx25840_write4(client, DIF_BPF_COEFF1213, 0x006dfec9); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfd2bfcb7); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfe350165); cx25840_write4(client, DIF_BPF_COEFF1819, 0x04cb0651); cx25840_write4(client, DIF_BPF_COEFF2021, 0x0477ff7e); cx25840_write4(client, DIF_BPF_COEFF2223, 0xf9a5f635); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf7b1fe20); cx25840_write4(client, DIF_BPF_COEFF2627, 0x069f0ca8); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0c81058b); cx25840_write4(client, DIF_BPF_COEFF3031, 0xfaf0f231); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf033f66d); cx25840_write4(client, DIF_BPF_COEFF3435, 0x01e60cae); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 5900000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000002); cx25840_write4(client, DIF_BPF_COEFF23, 0x0009000e); cx25840_write4(client, DIF_BPF_COEFF45, 0x0005ffe1); cx25840_write4(client, DIF_BPF_COEFF67, 0xffacff90); cx25840_write4(client, DIF_BPF_COEFF89, 0xffc5005f); cx25840_write4(client, DIF_BPF_COEFF1011, 0x01210184); cx25840_write4(client, DIF_BPF_COEFF1213, 0x00fcff72); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfd8afc77); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfd51003f); cx25840_write4(client, DIF_BPF_COEFF1819, 0x04020669); cx25840_write4(client, DIF_BPF_COEFF2021, 0x05830103); cx25840_write4(client, DIF_BPF_COEFF2223, 0xfad7f66b); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf6c8fc93); cx25840_write4(client, DIF_BPF_COEFF2627, 0x05430c2b); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0d0d06b5); cx25840_write4(client, DIF_BPF_COEFF3031, 0xfc08f2b2); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf00af5ec); cx25840_write4(client, DIF_BPF_COEFF3435, 0x017b0c89); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 6000000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000001); cx25840_write4(client, DIF_BPF_COEFF23, 0x00070012); cx25840_write4(client, DIF_BPF_COEFF45, 0x0012fff5); cx25840_write4(client, DIF_BPF_COEFF67, 0xffbaff82); cx25840_write4(client, DIF_BPF_COEFF89, 0xff8e000f); cx25840_write4(client, DIF_BPF_COEFF1011, 0x00e80198); cx25840_write4(client, DIF_BPF_COEFF1213, 0x01750028); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfe18fc75); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfc99ff15); cx25840_write4(client, DIF_BPF_COEFF1819, 0x03050636); cx25840_write4(client, DIF_BPF_COEFF2021, 0x0656027f); cx25840_write4(client, DIF_BPF_COEFF2223, 0xfc32f6e2); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf614fb17); cx25840_write4(client, DIF_BPF_COEFF2627, 0x03d20b87); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0d7707d2); cx25840_write4(client, DIF_BPF_COEFF3031, 0xfd26f341); cx25840_write4(client, DIF_BPF_COEFF3233, 0xefeaf56f); cx25840_write4(client, DIF_BPF_COEFF3435, 0x010f0c64); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 6100000: cx25840_write4(client, DIF_BPF_COEFF01, 0xffff0000); cx25840_write4(client, DIF_BPF_COEFF23, 0x00050012); cx25840_write4(client, DIF_BPF_COEFF45, 0x001c000b); cx25840_write4(client, DIF_BPF_COEFF67, 0xffd1ff84); cx25840_write4(client, DIF_BPF_COEFF89, 0xff66ffbe); cx25840_write4(client, DIF_BPF_COEFF1011, 0x00960184); cx25840_write4(client, DIF_BPF_COEFF1213, 0x01cd00da); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfeccfcb2); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfc17fdf9); cx25840_write4(client, DIF_BPF_COEFF1819, 0x01e005bc); cx25840_write4(client, DIF_BPF_COEFF2021, 0x06e703e4); cx25840_write4(client, DIF_BPF_COEFF2223, 0xfdabf798); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf599f9b3); cx25840_write4(client, DIF_BPF_COEFF2627, 0x02510abd); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0dbf08df); cx25840_write4(client, DIF_BPF_COEFF3031, 0xfe48f3dc); cx25840_write4(client, DIF_BPF_COEFF3233, 0xefd5f4f6); cx25840_write4(client, DIF_BPF_COEFF3435, 0x00a20c3e); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 6200000: cx25840_write4(client, DIF_BPF_COEFF01, 0xfffffffe); cx25840_write4(client, DIF_BPF_COEFF23, 0x0002000f); cx25840_write4(client, DIF_BPF_COEFF45, 0x0021001f); cx25840_write4(client, DIF_BPF_COEFF67, 0xfff0ff97); cx25840_write4(client, DIF_BPF_COEFF89, 0xff50ff74); cx25840_write4(client, DIF_BPF_COEFF1011, 0x0034014a); cx25840_write4(client, DIF_BPF_COEFF1213, 0x01fa0179); cx25840_write4(client, DIF_BPF_COEFF1415, 0xff97fd2a); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfbd3fcfa); cx25840_write4(client, DIF_BPF_COEFF1819, 0x00a304fe); cx25840_write4(client, DIF_BPF_COEFF2021, 0x07310525); cx25840_write4(client, DIF_BPF_COEFF2223, 0xff37f886); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf55cf86e); cx25840_write4(client, DIF_BPF_COEFF2627, 0x00c709d0); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0de209db); cx25840_write4(client, DIF_BPF_COEFF3031, 0xff6df484); cx25840_write4(client, DIF_BPF_COEFF3233, 0xefcbf481); cx25840_write4(client, DIF_BPF_COEFF3435, 0x00360c18); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 6300000: cx25840_write4(client, DIF_BPF_COEFF01, 0xfffffffd); cx25840_write4(client, DIF_BPF_COEFF23, 0xfffe000a); cx25840_write4(client, DIF_BPF_COEFF45, 0x0021002f); cx25840_write4(client, DIF_BPF_COEFF67, 0x0010ffb8); cx25840_write4(client, DIF_BPF_COEFF89, 0xff50ff3b); cx25840_write4(client, DIF_BPF_COEFF1011, 0xffcc00f0); cx25840_write4(client, DIF_BPF_COEFF1213, 0x01fa01fa); cx25840_write4(client, DIF_BPF_COEFF1415, 0x0069fdd4); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfbd3fc26); cx25840_write4(client, DIF_BPF_COEFF1819, 0xff5d0407); cx25840_write4(client, DIF_BPF_COEFF2021, 0x07310638); cx25840_write4(client, DIF_BPF_COEFF2223, 0x00c9f9a8); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf55cf74e); cx25840_write4(client, DIF_BPF_COEFF2627, 0xff3908c3); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0de20ac3); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0093f537); cx25840_write4(client, DIF_BPF_COEFF3233, 0xefcbf410); cx25840_write4(client, DIF_BPF_COEFF3435, 0xffca0bf2); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 6400000: cx25840_write4(client, DIF_BPF_COEFF01, 0xfffffffd); cx25840_write4(client, DIF_BPF_COEFF23, 0xfffb0003); cx25840_write4(client, DIF_BPF_COEFF45, 0x001c0037); cx25840_write4(client, DIF_BPF_COEFF67, 0x002fffe2); cx25840_write4(client, DIF_BPF_COEFF89, 0xff66ff17); cx25840_write4(client, DIF_BPF_COEFF1011, 0xff6a007e); cx25840_write4(client, DIF_BPF_COEFF1213, 0x01cd0251); cx25840_write4(client, DIF_BPF_COEFF1415, 0x0134fea5); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfc17fb8b); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfe2002e0); cx25840_write4(client, DIF_BPF_COEFF2021, 0x06e70713); cx25840_write4(client, DIF_BPF_COEFF2223, 0x0255faf5); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf599f658); cx25840_write4(client, DIF_BPF_COEFF2627, 0xfdaf0799); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0dbf0b96); cx25840_write4(client, DIF_BPF_COEFF3031, 0x01b8f5f5); cx25840_write4(client, DIF_BPF_COEFF3233, 0xefd5f3a3); cx25840_write4(client, DIF_BPF_COEFF3435, 0xff5e0bca); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 6500000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0000fffd); cx25840_write4(client, DIF_BPF_COEFF23, 0xfff9fffb); cx25840_write4(client, DIF_BPF_COEFF45, 0x00120037); cx25840_write4(client, DIF_BPF_COEFF67, 0x00460010); cx25840_write4(client, DIF_BPF_COEFF89, 0xff8eff0f); cx25840_write4(client, DIF_BPF_COEFF1011, 0xff180000); cx25840_write4(client, DIF_BPF_COEFF1213, 0x01750276); cx25840_write4(client, DIF_BPF_COEFF1415, 0x01e8ff8d); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfc99fb31); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfcfb0198); cx25840_write4(client, DIF_BPF_COEFF2021, 0x065607ad); cx25840_write4(client, DIF_BPF_COEFF2223, 0x03cefc64); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf614f592); cx25840_write4(client, DIF_BPF_COEFF2627, 0xfc2e0656); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0d770c52); cx25840_write4(client, DIF_BPF_COEFF3031, 0x02daf6bd); cx25840_write4(client, DIF_BPF_COEFF3233, 0xefeaf33b); cx25840_write4(client, DIF_BPF_COEFF3435, 0xfef10ba3); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 6600000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0000fffe); cx25840_write4(client, DIF_BPF_COEFF23, 0xfff7fff5); cx25840_write4(client, DIF_BPF_COEFF45, 0x0005002f); cx25840_write4(client, DIF_BPF_COEFF67, 0x0054003c); cx25840_write4(client, DIF_BPF_COEFF89, 0xffc5ff22); cx25840_write4(client, DIF_BPF_COEFF1011, 0xfedfff82); cx25840_write4(client, DIF_BPF_COEFF1213, 0x00fc0267); cx25840_write4(client, DIF_BPF_COEFF1415, 0x0276007e); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfd51fb1c); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfbfe003e); cx25840_write4(client, DIF_BPF_COEFF2021, 0x05830802); cx25840_write4(client, DIF_BPF_COEFF2223, 0x0529fdec); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf6c8f4fe); cx25840_write4(client, DIF_BPF_COEFF2627, 0xfabd04ff); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0d0d0cf6); cx25840_write4(client, DIF_BPF_COEFF3031, 0x03f8f78f); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf00af2d7); cx25840_write4(client, DIF_BPF_COEFF3435, 0xfe850b7b); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 6700000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0000ffff); cx25840_write4(client, DIF_BPF_COEFF23, 0xfff8fff0); cx25840_write4(client, DIF_BPF_COEFF45, 0xfff80020); cx25840_write4(client, DIF_BPF_COEFF67, 0x00560060); cx25840_write4(client, DIF_BPF_COEFF89, 0x0002ff4e); cx25840_write4(client, DIF_BPF_COEFF1011, 0xfec4ff10); cx25840_write4(client, DIF_BPF_COEFF1213, 0x006d0225); cx25840_write4(client, DIF_BPF_COEFF1415, 0x02d50166); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfe35fb4e); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfb35fee1); cx25840_write4(client, DIF_BPF_COEFF2021, 0x0477080e); cx25840_write4(client, DIF_BPF_COEFF2223, 0x065bff82); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf7b1f4a0); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf9610397); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0c810d80); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0510f869); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf033f278); cx25840_write4(client, DIF_BPF_COEFF3435, 0xfe1a0b52); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 6800000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00010000); cx25840_write4(client, DIF_BPF_COEFF23, 0xfffaffee); cx25840_write4(client, DIF_BPF_COEFF45, 0xffec000c); cx25840_write4(client, DIF_BPF_COEFF67, 0x004c0078); cx25840_write4(client, DIF_BPF_COEFF89, 0x0040ff8e); cx25840_write4(client, DIF_BPF_COEFF1011, 0xfecafeb6); cx25840_write4(client, DIF_BPF_COEFF1213, 0xffd301b6); cx25840_write4(client, DIF_BPF_COEFF1415, 0x02fc0235); cx25840_write4(client, DIF_BPF_COEFF1617, 0xff36fbc5); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfaaafd90); cx25840_write4(client, DIF_BPF_COEFF2021, 0x033e07d2); cx25840_write4(client, DIF_BPF_COEFF2223, 0x075b011b); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf8cbf47a); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf81f0224); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0bd50def); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0621f94b); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf067f21e); cx25840_write4(client, DIF_BPF_COEFF3435, 0xfdae0b29); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 6900000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00010001); cx25840_write4(client, DIF_BPF_COEFF23, 0xfffdffef); cx25840_write4(client, DIF_BPF_COEFF45, 0xffe3fff6); cx25840_write4(client, DIF_BPF_COEFF67, 0x0037007f); cx25840_write4(client, DIF_BPF_COEFF89, 0x0075ffdc); cx25840_write4(client, DIF_BPF_COEFF1011, 0xfef2fe7c); cx25840_write4(client, DIF_BPF_COEFF1213, 0xff3d0122); cx25840_write4(client, DIF_BPF_COEFF1415, 0x02ea02dd); cx25840_write4(client, DIF_BPF_COEFF1617, 0x0044fc79); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfa65fc5d); cx25840_write4(client, DIF_BPF_COEFF2021, 0x01e3074e); cx25840_write4(client, DIF_BPF_COEFF2223, 0x082102ad); cx25840_write4(client, DIF_BPF_COEFF2425, 0xfa0ff48c); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf6fe00a9); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0b0a0e43); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0729fa33); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf0a5f1c9); cx25840_write4(client, DIF_BPF_COEFF3435, 0xfd430b00); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 7000000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00010002); cx25840_write4(client, DIF_BPF_COEFF23, 0x0001fff3); cx25840_write4(client, DIF_BPF_COEFF45, 0xffdeffe2); cx25840_write4(client, DIF_BPF_COEFF67, 0x001b0076); cx25840_write4(client, DIF_BPF_COEFF89, 0x009c002d); cx25840_write4(client, DIF_BPF_COEFF1011, 0xff35fe68); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfeba0076); cx25840_write4(client, DIF_BPF_COEFF1415, 0x029f0352); cx25840_write4(client, DIF_BPF_COEFF1617, 0x014dfd60); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfa69fb53); cx25840_write4(client, DIF_BPF_COEFF2021, 0x00740688); cx25840_write4(client, DIF_BPF_COEFF2223, 0x08a7042d); cx25840_write4(client, DIF_BPF_COEFF2425, 0xfb75f4d6); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf600ff2d); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0a220e7a); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0827fb22); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf0edf17a); cx25840_write4(client, DIF_BPF_COEFF3435, 0xfcd80ad6); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 7100000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000003); cx25840_write4(client, DIF_BPF_COEFF23, 0x0004fff9); cx25840_write4(client, DIF_BPF_COEFF45, 0xffe0ffd2); cx25840_write4(client, DIF_BPF_COEFF67, 0xfffb005e); cx25840_write4(client, DIF_BPF_COEFF89, 0x00b0007a); cx25840_write4(client, DIF_BPF_COEFF1011, 0xff8ffe7c); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe53ffc1); cx25840_write4(client, DIF_BPF_COEFF1415, 0x0221038c); cx25840_write4(client, DIF_BPF_COEFF1617, 0x0241fe6e); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfab6fa80); cx25840_write4(client, DIF_BPF_COEFF2021, 0xff010587); cx25840_write4(client, DIF_BPF_COEFF2223, 0x08e90590); cx25840_write4(client, DIF_BPF_COEFF2425, 0xfcf5f556); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf52bfdb3); cx25840_write4(client, DIF_BPF_COEFF2829, 0x09210e95); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0919fc15); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf13ff12f); cx25840_write4(client, DIF_BPF_COEFF3435, 0xfc6e0aab); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 7200000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000003); cx25840_write4(client, DIF_BPF_COEFF23, 0x00070000); cx25840_write4(client, DIF_BPF_COEFF45, 0xffe6ffc9); cx25840_write4(client, DIF_BPF_COEFF67, 0xffdb0039); cx25840_write4(client, DIF_BPF_COEFF89, 0x00af00b8); cx25840_write4(client, DIF_BPF_COEFF1011, 0xfff4feb6); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe13ff10); cx25840_write4(client, DIF_BPF_COEFF1415, 0x01790388); cx25840_write4(client, DIF_BPF_COEFF1617, 0x0311ff92); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfb48f9ed); cx25840_write4(client, DIF_BPF_COEFF2021, 0xfd980453); cx25840_write4(client, DIF_BPF_COEFF2223, 0x08e306cd); cx25840_write4(client, DIF_BPF_COEFF2425, 0xfe88f60a); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf482fc40); cx25840_write4(client, DIF_BPF_COEFF2829, 0x08080e93); cx25840_write4(client, DIF_BPF_COEFF3031, 0x09fdfd0c); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf19af0ea); cx25840_write4(client, DIF_BPF_COEFF3435, 0xfc050a81); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 7300000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000002); cx25840_write4(client, DIF_BPF_COEFF23, 0x00080008); cx25840_write4(client, DIF_BPF_COEFF45, 0xfff0ffc9); cx25840_write4(client, DIF_BPF_COEFF67, 0xffc1000d); cx25840_write4(client, DIF_BPF_COEFF89, 0x009800e2); cx25840_write4(client, DIF_BPF_COEFF1011, 0x005bff10); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe00fe74); cx25840_write4(client, DIF_BPF_COEFF1415, 0x00b50345); cx25840_write4(client, DIF_BPF_COEFF1617, 0x03b000bc); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfc18f9a1); cx25840_write4(client, DIF_BPF_COEFF2021, 0xfc4802f9); cx25840_write4(client, DIF_BPF_COEFF2223, 0x089807dc); cx25840_write4(client, DIF_BPF_COEFF2425, 0x0022f6f0); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf407fada); cx25840_write4(client, DIF_BPF_COEFF2829, 0x06da0e74); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0ad3fe06); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf1fef0ab); cx25840_write4(client, DIF_BPF_COEFF3435, 0xfb9c0a55); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 7400000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000001); cx25840_write4(client, DIF_BPF_COEFF23, 0x0008000e); cx25840_write4(client, DIF_BPF_COEFF45, 0xfffdffd0); cx25840_write4(client, DIF_BPF_COEFF67, 0xffafffdf); cx25840_write4(client, DIF_BPF_COEFF89, 0x006e00f2); cx25840_write4(client, DIF_BPF_COEFF1011, 0x00b8ff82); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe1bfdf8); cx25840_write4(client, DIF_BPF_COEFF1415, 0xffe302c8); cx25840_write4(client, DIF_BPF_COEFF1617, 0x041301dc); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfd1af99e); cx25840_write4(client, DIF_BPF_COEFF2021, 0xfb1e0183); cx25840_write4(client, DIF_BPF_COEFF2223, 0x080908b5); cx25840_write4(client, DIF_BPF_COEFF2425, 0x01bcf801); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf3bdf985); cx25840_write4(client, DIF_BPF_COEFF2829, 0x059a0e38); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0b99ff03); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf26cf071); cx25840_write4(client, DIF_BPF_COEFF3435, 0xfb330a2a); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 7500000: cx25840_write4(client, DIF_BPF_COEFF01, 0xffff0000); cx25840_write4(client, DIF_BPF_COEFF23, 0x00070011); cx25840_write4(client, DIF_BPF_COEFF45, 0x000affdf); cx25840_write4(client, DIF_BPF_COEFF67, 0xffa9ffb5); cx25840_write4(client, DIF_BPF_COEFF89, 0x003700e6); cx25840_write4(client, DIF_BPF_COEFF1011, 0x01010000); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe62fda8); cx25840_write4(client, DIF_BPF_COEFF1415, 0xff140219); cx25840_write4(client, DIF_BPF_COEFF1617, 0x043502e1); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfe42f9e6); cx25840_write4(client, DIF_BPF_COEFF2021, 0xfa270000); cx25840_write4(client, DIF_BPF_COEFF2223, 0x073a0953); cx25840_write4(client, DIF_BPF_COEFF2425, 0x034cf939); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf3a4f845); cx25840_write4(client, DIF_BPF_COEFF2829, 0x044c0de1); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0c4f0000); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf2e2f03c); cx25840_write4(client, DIF_BPF_COEFF3435, 0xfacc09fe); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 7600000: cx25840_write4(client, DIF_BPF_COEFF01, 0xffffffff); cx25840_write4(client, DIF_BPF_COEFF23, 0x00040012); cx25840_write4(client, DIF_BPF_COEFF45, 0x0016fff3); cx25840_write4(client, DIF_BPF_COEFF67, 0xffafff95); cx25840_write4(client, DIF_BPF_COEFF89, 0xfff900c0); cx25840_write4(client, DIF_BPF_COEFF1011, 0x0130007e); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfecefd89); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfe560146); cx25840_write4(client, DIF_BPF_COEFF1617, 0x041303bc); cx25840_write4(client, DIF_BPF_COEFF1819, 0xff81fa76); cx25840_write4(client, DIF_BPF_COEFF2021, 0xf96cfe7d); cx25840_write4(client, DIF_BPF_COEFF2223, 0x063209b1); cx25840_write4(client, DIF_BPF_COEFF2425, 0x04c9fa93); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf3bdf71e); cx25840_write4(client, DIF_BPF_COEFF2829, 0x02f30d6e); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0cf200fd); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf361f00e); cx25840_write4(client, DIF_BPF_COEFF3435, 0xfa6509d1); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 7700000: cx25840_write4(client, DIF_BPF_COEFF01, 0xfffffffe); cx25840_write4(client, DIF_BPF_COEFF23, 0x00010010); cx25840_write4(client, DIF_BPF_COEFF45, 0x001e0008); cx25840_write4(client, DIF_BPF_COEFF67, 0xffc1ff84); cx25840_write4(client, DIF_BPF_COEFF89, 0xffbc0084); cx25840_write4(client, DIF_BPF_COEFF1011, 0x013e00f0); cx25840_write4(client, DIF_BPF_COEFF1213, 0xff56fd9f); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfdb8005c); cx25840_write4(client, DIF_BPF_COEFF1617, 0x03b00460); cx25840_write4(client, DIF_BPF_COEFF1819, 0x00c7fb45); cx25840_write4(client, DIF_BPF_COEFF2021, 0xf8f4fd07); cx25840_write4(client, DIF_BPF_COEFF2223, 0x04fa09ce); cx25840_write4(client, DIF_BPF_COEFF2425, 0x062afc07); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf407f614); cx25840_write4(client, DIF_BPF_COEFF2829, 0x01920ce0); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0d8301fa); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf3e8efe5); cx25840_write4(client, DIF_BPF_COEFF3435, 0xfa0009a4); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 7800000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0000fffd); cx25840_write4(client, DIF_BPF_COEFF23, 0xfffd000b); cx25840_write4(client, DIF_BPF_COEFF45, 0x0022001d); cx25840_write4(client, DIF_BPF_COEFF67, 0xffdbff82); cx25840_write4(client, DIF_BPF_COEFF89, 0xff870039); cx25840_write4(client, DIF_BPF_COEFF1011, 0x012a014a); cx25840_write4(client, DIF_BPF_COEFF1213, 0xffedfde7); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfd47ff6b); cx25840_write4(client, DIF_BPF_COEFF1617, 0x031104c6); cx25840_write4(client, DIF_BPF_COEFF1819, 0x0202fc4c); cx25840_write4(client, DIF_BPF_COEFF2021, 0xf8c6fbad); cx25840_write4(client, DIF_BPF_COEFF2223, 0x039909a7); cx25840_write4(client, DIF_BPF_COEFF2425, 0x0767fd8e); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf482f52b); cx25840_write4(client, DIF_BPF_COEFF2829, 0x002d0c39); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0e0002f4); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf477efc2); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf99b0977); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 7900000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0000fffd); cx25840_write4(client, DIF_BPF_COEFF23, 0xfffa0004); cx25840_write4(client, DIF_BPF_COEFF45, 0x0020002d); cx25840_write4(client, DIF_BPF_COEFF67, 0xfffbff91); cx25840_write4(client, DIF_BPF_COEFF89, 0xff61ffe8); cx25840_write4(client, DIF_BPF_COEFF1011, 0x00f70184); cx25840_write4(client, DIF_BPF_COEFF1213, 0x0086fe5c); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfd0bfe85); cx25840_write4(client, DIF_BPF_COEFF1617, 0x024104e5); cx25840_write4(client, DIF_BPF_COEFF1819, 0x0323fd7d); cx25840_write4(client, DIF_BPF_COEFF2021, 0xf8e2fa79); cx25840_write4(client, DIF_BPF_COEFF2223, 0x021d093f); cx25840_write4(client, DIF_BPF_COEFF2425, 0x0879ff22); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf52bf465); cx25840_write4(client, DIF_BPF_COEFF2829, 0xfec70b79); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0e6803eb); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf50defa5); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf937094a); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 8000000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0000fffe); cx25840_write4(client, DIF_BPF_COEFF23, 0xfff8fffd); cx25840_write4(client, DIF_BPF_COEFF45, 0x00190036); cx25840_write4(client, DIF_BPF_COEFF67, 0x001bffaf); cx25840_write4(client, DIF_BPF_COEFF89, 0xff4fff99); cx25840_write4(client, DIF_BPF_COEFF1011, 0x00aa0198); cx25840_write4(client, DIF_BPF_COEFF1213, 0x0112fef3); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfd09fdb9); cx25840_write4(client, DIF_BPF_COEFF1617, 0x014d04be); cx25840_write4(client, DIF_BPF_COEFF1819, 0x041bfecc); cx25840_write4(client, DIF_BPF_COEFF2021, 0xf947f978); cx25840_write4(client, DIF_BPF_COEFF2223, 0x00900897); cx25840_write4(client, DIF_BPF_COEFF2425, 0x095a00b9); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf600f3c5); cx25840_write4(client, DIF_BPF_COEFF2829, 0xfd650aa3); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0ebc04de); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf5aaef8e); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf8d5091c); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 8100000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0000ffff); cx25840_write4(client, DIF_BPF_COEFF23, 0xfff7fff6); cx25840_write4(client, DIF_BPF_COEFF45, 0x000e0038); cx25840_write4(client, DIF_BPF_COEFF67, 0x0037ffd7); cx25840_write4(client, DIF_BPF_COEFF89, 0xff52ff56); cx25840_write4(client, DIF_BPF_COEFF1011, 0x004b0184); cx25840_write4(client, DIF_BPF_COEFF1213, 0x0186ffa1); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfd40fd16); cx25840_write4(client, DIF_BPF_COEFF1617, 0x00440452); cx25840_write4(client, DIF_BPF_COEFF1819, 0x04de0029); cx25840_write4(client, DIF_BPF_COEFF2021, 0xf9f2f8b2); cx25840_write4(client, DIF_BPF_COEFF2223, 0xfefe07b5); cx25840_write4(client, DIF_BPF_COEFF2425, 0x0a05024d); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf6fef34d); cx25840_write4(client, DIF_BPF_COEFF2829, 0xfc0a09b8); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0efa05cd); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf64eef7d); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf87308ed); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 8200000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00010000); cx25840_write4(client, DIF_BPF_COEFF23, 0xfff8fff0); cx25840_write4(client, DIF_BPF_COEFF45, 0x00000031); cx25840_write4(client, DIF_BPF_COEFF67, 0x004c0005); cx25840_write4(client, DIF_BPF_COEFF89, 0xff6aff27); cx25840_write4(client, DIF_BPF_COEFF1011, 0xffe4014a); cx25840_write4(client, DIF_BPF_COEFF1213, 0x01d70057); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfdacfca6); cx25840_write4(client, DIF_BPF_COEFF1617, 0xff3603a7); cx25840_write4(client, DIF_BPF_COEFF1819, 0x05610184); cx25840_write4(client, DIF_BPF_COEFF2021, 0xfadbf82e); cx25840_write4(client, DIF_BPF_COEFF2223, 0xfd74069f); cx25840_write4(client, DIF_BPF_COEFF2425, 0x0a7503d6); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf81ff2ff); cx25840_write4(client, DIF_BPF_COEFF2829, 0xfab808b9); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0f2306b5); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf6f9ef72); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf81308bf); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 8300000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00010001); cx25840_write4(client, DIF_BPF_COEFF23, 0xfffbffee); cx25840_write4(client, DIF_BPF_COEFF45, 0xfff30022); cx25840_write4(client, DIF_BPF_COEFF67, 0x00560032); cx25840_write4(client, DIF_BPF_COEFF89, 0xff95ff10); cx25840_write4(client, DIF_BPF_COEFF1011, 0xff8000f0); cx25840_write4(client, DIF_BPF_COEFF1213, 0x01fe0106); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfe46fc71); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfe3502c7); cx25840_write4(client, DIF_BPF_COEFF1819, 0x059e02ce); cx25840_write4(client, DIF_BPF_COEFF2021, 0xfbf9f7f2); cx25840_write4(client, DIF_BPF_COEFF2223, 0xfbff055b); cx25840_write4(client, DIF_BPF_COEFF2425, 0x0aa9054c); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf961f2db); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf97507aa); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0f350797); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf7a9ef6d); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf7b40890); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 8400000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00010002); cx25840_write4(client, DIF_BPF_COEFF23, 0xfffeffee); cx25840_write4(client, DIF_BPF_COEFF45, 0xffe8000f); cx25840_write4(client, DIF_BPF_COEFF67, 0x00540058); cx25840_write4(client, DIF_BPF_COEFF89, 0xffcdff14); cx25840_write4(client, DIF_BPF_COEFF1011, 0xff29007e); cx25840_write4(client, DIF_BPF_COEFF1213, 0x01f6019e); cx25840_write4(client, DIF_BPF_COEFF1415, 0xff01fc7c); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfd5101bf); cx25840_write4(client, DIF_BPF_COEFF1819, 0x059203f6); cx25840_write4(client, DIF_BPF_COEFF2021, 0xfd41f7fe); cx25840_write4(client, DIF_BPF_COEFF2223, 0xfaa903f3); cx25840_write4(client, DIF_BPF_COEFF2425, 0x0a9e06a9); cx25840_write4(client, DIF_BPF_COEFF2627, 0xfabdf2e2); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf842068b); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0f320871); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf85eef6e); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf7560860); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 8500000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000003); cx25840_write4(client, DIF_BPF_COEFF23, 0x0002fff2); cx25840_write4(client, DIF_BPF_COEFF45, 0xffe1fff9); cx25840_write4(client, DIF_BPF_COEFF67, 0x00460073); cx25840_write4(client, DIF_BPF_COEFF89, 0x000bff34); cx25840_write4(client, DIF_BPF_COEFF1011, 0xfee90000); cx25840_write4(client, DIF_BPF_COEFF1213, 0x01c10215); cx25840_write4(client, DIF_BPF_COEFF1415, 0xffd0fcc5); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfc99009d); cx25840_write4(client, DIF_BPF_COEFF1819, 0x053d04f1); cx25840_write4(client, DIF_BPF_COEFF2021, 0xfea5f853); cx25840_write4(client, DIF_BPF_COEFF2223, 0xf97d0270); cx25840_write4(client, DIF_BPF_COEFF2425, 0x0a5607e4); cx25840_write4(client, DIF_BPF_COEFF2627, 0xfc2ef314); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf723055f); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0f180943); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf919ef75); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf6fa0830); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 8600000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000003); cx25840_write4(client, DIF_BPF_COEFF23, 0x0005fff8); cx25840_write4(client, DIF_BPF_COEFF45, 0xffdeffe4); cx25840_write4(client, DIF_BPF_COEFF67, 0x002f007f); cx25840_write4(client, DIF_BPF_COEFF89, 0x0048ff6b); cx25840_write4(client, DIF_BPF_COEFF1011, 0xfec7ff82); cx25840_write4(client, DIF_BPF_COEFF1213, 0x0163025f); cx25840_write4(client, DIF_BPF_COEFF1415, 0x00a2fd47); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfc17ff73); cx25840_write4(client, DIF_BPF_COEFF1819, 0x04a405b2); cx25840_write4(client, DIF_BPF_COEFF2021, 0x0017f8ed); cx25840_write4(client, DIF_BPF_COEFF2223, 0xf88500dc); cx25840_write4(client, DIF_BPF_COEFF2425, 0x09d208f9); cx25840_write4(client, DIF_BPF_COEFF2627, 0xfdaff370); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf61c0429); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0ee80a0b); cx25840_write4(client, DIF_BPF_COEFF3233, 0xf9d8ef82); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf6a00800); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 8700000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000003); cx25840_write4(client, DIF_BPF_COEFF23, 0x0007ffff); cx25840_write4(client, DIF_BPF_COEFF45, 0xffe1ffd4); cx25840_write4(client, DIF_BPF_COEFF67, 0x0010007a); cx25840_write4(client, DIF_BPF_COEFF89, 0x007cffb2); cx25840_write4(client, DIF_BPF_COEFF1011, 0xfec6ff10); cx25840_write4(client, DIF_BPF_COEFF1213, 0x00e60277); cx25840_write4(client, DIF_BPF_COEFF1415, 0x0168fdf9); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfbd3fe50); cx25840_write4(client, DIF_BPF_COEFF1819, 0x03ce0631); cx25840_write4(client, DIF_BPF_COEFF2021, 0x0188f9c8); cx25840_write4(client, DIF_BPF_COEFF2223, 0xf7c7ff43); cx25840_write4(client, DIF_BPF_COEFF2425, 0x091509e3); cx25840_write4(client, DIF_BPF_COEFF2627, 0xff39f3f6); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf52d02ea); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0ea30ac9); cx25840_write4(client, DIF_BPF_COEFF3233, 0xfa9bef95); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf64607d0); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 8800000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000002); cx25840_write4(client, DIF_BPF_COEFF23, 0x00090007); cx25840_write4(client, DIF_BPF_COEFF45, 0xffe9ffca); cx25840_write4(client, DIF_BPF_COEFF67, 0xfff00065); cx25840_write4(client, DIF_BPF_COEFF89, 0x00a10003); cx25840_write4(client, DIF_BPF_COEFF1011, 0xfee6feb6); cx25840_write4(client, DIF_BPF_COEFF1213, 0x0053025b); cx25840_write4(client, DIF_BPF_COEFF1415, 0x0213fed0); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfbd3fd46); cx25840_write4(client, DIF_BPF_COEFF1819, 0x02c70668); cx25840_write4(client, DIF_BPF_COEFF2021, 0x02eafadb); cx25840_write4(client, DIF_BPF_COEFF2223, 0xf74bfdae); cx25840_write4(client, DIF_BPF_COEFF2425, 0x08230a9c); cx25840_write4(client, DIF_BPF_COEFF2627, 0x00c7f4a3); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf45b01a6); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0e480b7c); cx25840_write4(client, DIF_BPF_COEFF3233, 0xfb61efae); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf5ef079f); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 8900000: cx25840_write4(client, DIF_BPF_COEFF01, 0xffff0000); cx25840_write4(client, DIF_BPF_COEFF23, 0x0008000d); cx25840_write4(client, DIF_BPF_COEFF45, 0xfff5ffc8); cx25840_write4(client, DIF_BPF_COEFF67, 0xffd10043); cx25840_write4(client, DIF_BPF_COEFF89, 0x00b20053); cx25840_write4(client, DIF_BPF_COEFF1011, 0xff24fe7c); cx25840_write4(client, DIF_BPF_COEFF1213, 0xffb9020c); cx25840_write4(client, DIF_BPF_COEFF1415, 0x0295ffbb); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfc17fc64); cx25840_write4(client, DIF_BPF_COEFF1819, 0x019b0654); cx25840_write4(client, DIF_BPF_COEFF2021, 0x042dfc1c); cx25840_write4(client, DIF_BPF_COEFF2223, 0xf714fc2a); cx25840_write4(client, DIF_BPF_COEFF2425, 0x07020b21); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0251f575); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf3a7005e); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0dd80c24); cx25840_write4(client, DIF_BPF_COEFF3233, 0xfc2aefcd); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf599076e); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 9000000: cx25840_write4(client, DIF_BPF_COEFF01, 0xffffffff); cx25840_write4(client, DIF_BPF_COEFF23, 0x00060011); cx25840_write4(client, DIF_BPF_COEFF45, 0x0002ffcf); cx25840_write4(client, DIF_BPF_COEFF67, 0xffba0018); cx25840_write4(client, DIF_BPF_COEFF89, 0x00ad009a); cx25840_write4(client, DIF_BPF_COEFF1011, 0xff79fe68); cx25840_write4(client, DIF_BPF_COEFF1213, 0xff260192); cx25840_write4(client, DIF_BPF_COEFF1415, 0x02e500ab); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfc99fbb6); cx25840_write4(client, DIF_BPF_COEFF1819, 0x005b05f7); cx25840_write4(client, DIF_BPF_COEFF2021, 0x0545fd81); cx25840_write4(client, DIF_BPF_COEFF2223, 0xf723fabf); cx25840_write4(client, DIF_BPF_COEFF2425, 0x05b80b70); cx25840_write4(client, DIF_BPF_COEFF2627, 0x03d2f669); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf313ff15); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0d550cbf); cx25840_write4(client, DIF_BPF_COEFF3233, 0xfcf6eff2); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf544073d); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 9100000: cx25840_write4(client, DIF_BPF_COEFF01, 0xfffffffe); cx25840_write4(client, DIF_BPF_COEFF23, 0x00030012); cx25840_write4(client, DIF_BPF_COEFF45, 0x000fffdd); cx25840_write4(client, DIF_BPF_COEFF67, 0xffacffea); cx25840_write4(client, DIF_BPF_COEFF89, 0x009300cf); cx25840_write4(client, DIF_BPF_COEFF1011, 0xffdcfe7c); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfea600f7); cx25840_write4(client, DIF_BPF_COEFF1415, 0x02fd0190); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfd51fb46); cx25840_write4(client, DIF_BPF_COEFF1819, 0xff150554); cx25840_write4(client, DIF_BPF_COEFF2021, 0x0627fefd); cx25840_write4(client, DIF_BPF_COEFF2223, 0xf778f978); cx25840_write4(client, DIF_BPF_COEFF2425, 0x044d0b87); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0543f77d); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf2a0fdcf); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0cbe0d4e); cx25840_write4(client, DIF_BPF_COEFF3233, 0xfdc4f01d); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf4f2070b); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 9200000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0000fffd); cx25840_write4(client, DIF_BPF_COEFF23, 0x00000010); cx25840_write4(client, DIF_BPF_COEFF45, 0x001afff0); cx25840_write4(client, DIF_BPF_COEFF67, 0xffaaffbf); cx25840_write4(client, DIF_BPF_COEFF89, 0x006700ed); cx25840_write4(client, DIF_BPF_COEFF1011, 0x0043feb6); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe460047); cx25840_write4(client, DIF_BPF_COEFF1415, 0x02db0258); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfe35fb1b); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfddc0473); cx25840_write4(client, DIF_BPF_COEFF2021, 0x06c90082); cx25840_write4(client, DIF_BPF_COEFF2223, 0xf811f85e); cx25840_write4(client, DIF_BPF_COEFF2425, 0x02c90b66); cx25840_write4(client, DIF_BPF_COEFF2627, 0x069ff8ad); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf250fc8d); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0c140dcf); cx25840_write4(client, DIF_BPF_COEFF3233, 0xfe93f04d); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf4a106d9); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 9300000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0000fffd); cx25840_write4(client, DIF_BPF_COEFF23, 0xfffc000c); cx25840_write4(client, DIF_BPF_COEFF45, 0x00200006); cx25840_write4(client, DIF_BPF_COEFF67, 0xffb4ff9c); cx25840_write4(client, DIF_BPF_COEFF89, 0x002f00ef); cx25840_write4(client, DIF_BPF_COEFF1011, 0x00a4ff10); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe0dff92); cx25840_write4(client, DIF_BPF_COEFF1415, 0x028102f7); cx25840_write4(client, DIF_BPF_COEFF1617, 0xff36fb37); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfcbf035e); cx25840_write4(client, DIF_BPF_COEFF2021, 0x07260202); cx25840_write4(client, DIF_BPF_COEFF2223, 0xf8e8f778); cx25840_write4(client, DIF_BPF_COEFF2425, 0x01340b0d); cx25840_write4(client, DIF_BPF_COEFF2627, 0x07e1f9f4); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf223fb51); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0b590e42); cx25840_write4(client, DIF_BPF_COEFF3233, 0xff64f083); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf45206a7); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 9400000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0000fffd); cx25840_write4(client, DIF_BPF_COEFF23, 0xfff90005); cx25840_write4(client, DIF_BPF_COEFF45, 0x0022001a); cx25840_write4(client, DIF_BPF_COEFF67, 0xffc9ff86); cx25840_write4(client, DIF_BPF_COEFF89, 0xfff000d7); cx25840_write4(client, DIF_BPF_COEFF1011, 0x00f2ff82); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe01fee5); cx25840_write4(client, DIF_BPF_COEFF1415, 0x01f60362); cx25840_write4(client, DIF_BPF_COEFF1617, 0x0044fb99); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfbcc0222); cx25840_write4(client, DIF_BPF_COEFF2021, 0x07380370); cx25840_write4(client, DIF_BPF_COEFF2223, 0xf9f7f6cc); cx25840_write4(client, DIF_BPF_COEFF2425, 0xff990a7e); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0902fb50); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf21afa1f); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0a8d0ea6); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0034f0bf); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf4050675); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 9500000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0000fffe); cx25840_write4(client, DIF_BPF_COEFF23, 0xfff8fffe); cx25840_write4(client, DIF_BPF_COEFF45, 0x001e002b); cx25840_write4(client, DIF_BPF_COEFF67, 0xffe5ff81); cx25840_write4(client, DIF_BPF_COEFF89, 0xffb400a5); cx25840_write4(client, DIF_BPF_COEFF1011, 0x01280000); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe24fe50); cx25840_write4(client, DIF_BPF_COEFF1415, 0x01460390); cx25840_write4(client, DIF_BPF_COEFF1617, 0x014dfc3a); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfb1000ce); cx25840_write4(client, DIF_BPF_COEFF2021, 0x070104bf); cx25840_write4(client, DIF_BPF_COEFF2223, 0xfb37f65f); cx25840_write4(client, DIF_BPF_COEFF2425, 0xfe0009bc); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0a00fcbb); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf235f8f8); cx25840_write4(client, DIF_BPF_COEFF3031, 0x09b20efc); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0105f101); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf3ba0642); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 9600000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0001ffff); cx25840_write4(client, DIF_BPF_COEFF23, 0xfff8fff7); cx25840_write4(client, DIF_BPF_COEFF45, 0x00150036); cx25840_write4(client, DIF_BPF_COEFF67, 0x0005ff8c); cx25840_write4(client, DIF_BPF_COEFF89, 0xff810061); cx25840_write4(client, DIF_BPF_COEFF1011, 0x013d007e); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe71fddf); cx25840_write4(client, DIF_BPF_COEFF1415, 0x007c0380); cx25840_write4(client, DIF_BPF_COEFF1617, 0x0241fd13); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfa94ff70); cx25840_write4(client, DIF_BPF_COEFF2021, 0x068005e2); cx25840_write4(client, DIF_BPF_COEFF2223, 0xfc9bf633); cx25840_write4(client, DIF_BPF_COEFF2425, 0xfc7308ca); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0ad5fe30); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf274f7e0); cx25840_write4(client, DIF_BPF_COEFF3031, 0x08c90f43); cx25840_write4(client, DIF_BPF_COEFF3233, 0x01d4f147); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf371060f); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 9700000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00010001); cx25840_write4(client, DIF_BPF_COEFF23, 0xfff9fff1); cx25840_write4(client, DIF_BPF_COEFF45, 0x00090038); cx25840_write4(client, DIF_BPF_COEFF67, 0x0025ffa7); cx25840_write4(client, DIF_BPF_COEFF89, 0xff5e0012); cx25840_write4(client, DIF_BPF_COEFF1011, 0x013200f0); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfee3fd9b); cx25840_write4(client, DIF_BPF_COEFF1415, 0xffaa0331); cx25840_write4(client, DIF_BPF_COEFF1617, 0x0311fe15); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfa60fe18); cx25840_write4(client, DIF_BPF_COEFF2021, 0x05bd06d1); cx25840_write4(client, DIF_BPF_COEFF2223, 0xfe1bf64a); cx25840_write4(client, DIF_BPF_COEFF2425, 0xfafa07ae); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0b7effab); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf2d5f6d7); cx25840_write4(client, DIF_BPF_COEFF3031, 0x07d30f7a); cx25840_write4(client, DIF_BPF_COEFF3233, 0x02a3f194); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf32905dc); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 9800000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00010002); cx25840_write4(client, DIF_BPF_COEFF23, 0xfffcffee); cx25840_write4(client, DIF_BPF_COEFF45, 0xfffb0032); cx25840_write4(client, DIF_BPF_COEFF67, 0x003fffcd); cx25840_write4(client, DIF_BPF_COEFF89, 0xff4effc1); cx25840_write4(client, DIF_BPF_COEFF1011, 0x0106014a); cx25840_write4(client, DIF_BPF_COEFF1213, 0xff6efd8a); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfedd02aa); cx25840_write4(client, DIF_BPF_COEFF1617, 0x03b0ff34); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfa74fcd7); cx25840_write4(client, DIF_BPF_COEFF2021, 0x04bf0781); cx25840_write4(client, DIF_BPF_COEFF2223, 0xffaaf6a3); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf99e066b); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0bf90128); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf359f5e1); cx25840_write4(client, DIF_BPF_COEFF3031, 0x06d20fa2); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0370f1e5); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf2e405a8); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 9900000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000003); cx25840_write4(client, DIF_BPF_COEFF23, 0xffffffee); cx25840_write4(client, DIF_BPF_COEFF45, 0xffef0024); cx25840_write4(client, DIF_BPF_COEFF67, 0x0051fffa); cx25840_write4(client, DIF_BPF_COEFF89, 0xff54ff77); cx25840_write4(client, DIF_BPF_COEFF1011, 0x00be0184); cx25840_write4(client, DIF_BPF_COEFF1213, 0x0006fdad); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfe2701f3); cx25840_write4(client, DIF_BPF_COEFF1617, 0x0413005e); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfad1fbba); cx25840_write4(client, DIF_BPF_COEFF2021, 0x039007ee); cx25840_write4(client, DIF_BPF_COEFF2223, 0x013bf73d); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf868050a); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0c4302a1); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf3fdf4fe); cx25840_write4(client, DIF_BPF_COEFF3031, 0x05c70fba); cx25840_write4(client, DIF_BPF_COEFF3233, 0x043bf23c); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf2a10575); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 10000000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000003); cx25840_write4(client, DIF_BPF_COEFF23, 0x0003fff1); cx25840_write4(client, DIF_BPF_COEFF45, 0xffe50011); cx25840_write4(client, DIF_BPF_COEFF67, 0x00570027); cx25840_write4(client, DIF_BPF_COEFF89, 0xff70ff3c); cx25840_write4(client, DIF_BPF_COEFF1011, 0x00620198); cx25840_write4(client, DIF_BPF_COEFF1213, 0x009efe01); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfd95011a); cx25840_write4(client, DIF_BPF_COEFF1617, 0x04350183); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfb71fad0); cx25840_write4(client, DIF_BPF_COEFF2021, 0x023c0812); cx25840_write4(client, DIF_BPF_COEFF2223, 0x02c3f811); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf75e0390); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0c5c0411); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf4c1f432); cx25840_write4(client, DIF_BPF_COEFF3031, 0x04b30fc1); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0503f297); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf2610541); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 10100000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000003); cx25840_write4(client, DIF_BPF_COEFF23, 0x0006fff7); cx25840_write4(client, DIF_BPF_COEFF45, 0xffdffffc); cx25840_write4(client, DIF_BPF_COEFF67, 0x00510050); cx25840_write4(client, DIF_BPF_COEFF89, 0xff9dff18); cx25840_write4(client, DIF_BPF_COEFF1011, 0xfffc0184); cx25840_write4(client, DIF_BPF_COEFF1213, 0x0128fe80); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfd32002e); cx25840_write4(client, DIF_BPF_COEFF1617, 0x04130292); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfc4dfa21); cx25840_write4(client, DIF_BPF_COEFF2021, 0x00d107ee); cx25840_write4(client, DIF_BPF_COEFF2223, 0x0435f91c); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf6850205); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0c430573); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf5a1f37d); cx25840_write4(client, DIF_BPF_COEFF3031, 0x03990fba); cx25840_write4(client, DIF_BPF_COEFF3233, 0x05c7f2f8); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf222050d); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 10200000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000002); cx25840_write4(client, DIF_BPF_COEFF23, 0x0008fffe); cx25840_write4(client, DIF_BPF_COEFF45, 0xffdfffe7); cx25840_write4(client, DIF_BPF_COEFF67, 0x003f006e); cx25840_write4(client, DIF_BPF_COEFF89, 0xffd6ff0f); cx25840_write4(client, DIF_BPF_COEFF1011, 0xff96014a); cx25840_write4(client, DIF_BPF_COEFF1213, 0x0197ff1f); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfd05ff3e); cx25840_write4(client, DIF_BPF_COEFF1617, 0x03b0037c); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfd59f9b7); cx25840_write4(client, DIF_BPF_COEFF2021, 0xff5d0781); cx25840_write4(client, DIF_BPF_COEFF2223, 0x0585fa56); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf5e4006f); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0bf906c4); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf69df2e0); cx25840_write4(client, DIF_BPF_COEFF3031, 0x02790fa2); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0688f35d); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf1e604d8); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 10300000: cx25840_write4(client, DIF_BPF_COEFF01, 0xffff0001); cx25840_write4(client, DIF_BPF_COEFF23, 0x00090005); cx25840_write4(client, DIF_BPF_COEFF45, 0xffe4ffd6); cx25840_write4(client, DIF_BPF_COEFF67, 0x0025007e); cx25840_write4(client, DIF_BPF_COEFF89, 0x0014ff20); cx25840_write4(client, DIF_BPF_COEFF1011, 0xff3c00f0); cx25840_write4(client, DIF_BPF_COEFF1213, 0x01e1ffd0); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfd12fe5c); cx25840_write4(client, DIF_BPF_COEFF1617, 0x03110433); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfe88f996); cx25840_write4(client, DIF_BPF_COEFF2021, 0xfdf106d1); cx25840_write4(client, DIF_BPF_COEFF2223, 0x06aafbb7); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf57efed8); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0b7e07ff); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf7b0f25e); cx25840_write4(client, DIF_BPF_COEFF3031, 0x01560f7a); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0745f3c7); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf1ac04a4); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 10400000: cx25840_write4(client, DIF_BPF_COEFF01, 0xffffffff); cx25840_write4(client, DIF_BPF_COEFF23, 0x0008000c); cx25840_write4(client, DIF_BPF_COEFF45, 0xffedffcb); cx25840_write4(client, DIF_BPF_COEFF67, 0x0005007d); cx25840_write4(client, DIF_BPF_COEFF89, 0x0050ff4c); cx25840_write4(client, DIF_BPF_COEFF1011, 0xfef6007e); cx25840_write4(client, DIF_BPF_COEFF1213, 0x01ff0086); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfd58fd97); cx25840_write4(client, DIF_BPF_COEFF1617, 0x024104ad); cx25840_write4(client, DIF_BPF_COEFF1819, 0xffcaf9c0); cx25840_write4(client, DIF_BPF_COEFF2021, 0xfc9905e2); cx25840_write4(client, DIF_BPF_COEFF2223, 0x079afd35); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf555fd46); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0ad50920); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf8d9f1f6); cx25840_write4(client, DIF_BPF_COEFF3031, 0x00310f43); cx25840_write4(client, DIF_BPF_COEFF3233, 0x07fdf435); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf174046f); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 10500000: cx25840_write4(client, DIF_BPF_COEFF01, 0xfffffffe); cx25840_write4(client, DIF_BPF_COEFF23, 0x00050011); cx25840_write4(client, DIF_BPF_COEFF45, 0xfffaffc8); cx25840_write4(client, DIF_BPF_COEFF67, 0xffe5006b); cx25840_write4(client, DIF_BPF_COEFF89, 0x0082ff8c); cx25840_write4(client, DIF_BPF_COEFF1011, 0xfecc0000); cx25840_write4(client, DIF_BPF_COEFF1213, 0x01f00130); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfdd2fcfc); cx25840_write4(client, DIF_BPF_COEFF1617, 0x014d04e3); cx25840_write4(client, DIF_BPF_COEFF1819, 0x010efa32); cx25840_write4(client, DIF_BPF_COEFF2021, 0xfb6404bf); cx25840_write4(client, DIF_BPF_COEFF2223, 0x084efec5); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf569fbc2); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0a000a23); cx25840_write4(client, DIF_BPF_COEFF2829, 0xfa15f1ab); cx25840_write4(client, DIF_BPF_COEFF3031, 0xff0b0efc); cx25840_write4(client, DIF_BPF_COEFF3233, 0x08b0f4a7); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf13f043a); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 10600000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0000fffd); cx25840_write4(client, DIF_BPF_COEFF23, 0x00020012); cx25840_write4(client, DIF_BPF_COEFF45, 0x0007ffcd); cx25840_write4(client, DIF_BPF_COEFF67, 0xffc9004c); cx25840_write4(client, DIF_BPF_COEFF89, 0x00a4ffd9); cx25840_write4(client, DIF_BPF_COEFF1011, 0xfec3ff82); cx25840_write4(client, DIF_BPF_COEFF1213, 0x01b401c1); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfe76fc97); cx25840_write4(client, DIF_BPF_COEFF1617, 0x004404d2); cx25840_write4(client, DIF_BPF_COEFF1819, 0x0245fae8); cx25840_write4(client, DIF_BPF_COEFF2021, 0xfa5f0370); cx25840_write4(client, DIF_BPF_COEFF2223, 0x08c1005f); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf5bcfa52); cx25840_write4(client, DIF_BPF_COEFF2627, 0x09020b04); cx25840_write4(client, DIF_BPF_COEFF2829, 0xfb60f17b); cx25840_write4(client, DIF_BPF_COEFF3031, 0xfde70ea6); cx25840_write4(client, DIF_BPF_COEFF3233, 0x095df51e); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf10c0405); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 10700000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0000fffd); cx25840_write4(client, DIF_BPF_COEFF23, 0xffff0011); cx25840_write4(client, DIF_BPF_COEFF45, 0x0014ffdb); cx25840_write4(client, DIF_BPF_COEFF67, 0xffb40023); cx25840_write4(client, DIF_BPF_COEFF89, 0x00b2002a); cx25840_write4(client, DIF_BPF_COEFF1011, 0xfedbff10); cx25840_write4(client, DIF_BPF_COEFF1213, 0x0150022d); cx25840_write4(client, DIF_BPF_COEFF1415, 0xff38fc6f); cx25840_write4(client, DIF_BPF_COEFF1617, 0xff36047b); cx25840_write4(client, DIF_BPF_COEFF1819, 0x035efbda); cx25840_write4(client, DIF_BPF_COEFF2021, 0xf9940202); cx25840_write4(client, DIF_BPF_COEFF2223, 0x08ee01f5); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf649f8fe); cx25840_write4(client, DIF_BPF_COEFF2627, 0x07e10bc2); cx25840_write4(client, DIF_BPF_COEFF2829, 0xfcb6f169); cx25840_write4(client, DIF_BPF_COEFF3031, 0xfcc60e42); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0a04f599); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf0db03d0); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 10800000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0000fffd); cx25840_write4(client, DIF_BPF_COEFF23, 0xfffb000d); cx25840_write4(client, DIF_BPF_COEFF45, 0x001dffed); cx25840_write4(client, DIF_BPF_COEFF67, 0xffaafff5); cx25840_write4(client, DIF_BPF_COEFF89, 0x00aa0077); cx25840_write4(client, DIF_BPF_COEFF1011, 0xff13feb6); cx25840_write4(client, DIF_BPF_COEFF1213, 0x00ce026b); cx25840_write4(client, DIF_BPF_COEFF1415, 0x000afc85); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfe3503e3); cx25840_write4(client, DIF_BPF_COEFF1819, 0x044cfcfb); cx25840_write4(client, DIF_BPF_COEFF2021, 0xf90c0082); cx25840_write4(client, DIF_BPF_COEFF2223, 0x08d5037f); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf710f7cc); cx25840_write4(client, DIF_BPF_COEFF2627, 0x069f0c59); cx25840_write4(client, DIF_BPF_COEFF2829, 0xfe16f173); cx25840_write4(client, DIF_BPF_COEFF3031, 0xfbaa0dcf); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0aa5f617); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf0ad039b); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 10900000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0000fffe); cx25840_write4(client, DIF_BPF_COEFF23, 0xfff90006); cx25840_write4(client, DIF_BPF_COEFF45, 0x00210003); cx25840_write4(client, DIF_BPF_COEFF67, 0xffacffc8); cx25840_write4(client, DIF_BPF_COEFF89, 0x008e00b6); cx25840_write4(client, DIF_BPF_COEFF1011, 0xff63fe7c); cx25840_write4(client, DIF_BPF_COEFF1213, 0x003a0275); cx25840_write4(client, DIF_BPF_COEFF1415, 0x00dafcda); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfd510313); cx25840_write4(client, DIF_BPF_COEFF1819, 0x0501fe40); cx25840_write4(client, DIF_BPF_COEFF2021, 0xf8cbfefd); cx25840_write4(client, DIF_BPF_COEFF2223, 0x087604f0); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf80af6c2); cx25840_write4(client, DIF_BPF_COEFF2627, 0x05430cc8); cx25840_write4(client, DIF_BPF_COEFF2829, 0xff7af19a); cx25840_write4(client, DIF_BPF_COEFF3031, 0xfa940d4e); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0b3ff699); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf0810365); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 11000000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0001ffff); cx25840_write4(client, DIF_BPF_COEFF23, 0xfff8ffff); cx25840_write4(client, DIF_BPF_COEFF45, 0x00210018); cx25840_write4(client, DIF_BPF_COEFF67, 0xffbaffa3); cx25840_write4(client, DIF_BPF_COEFF89, 0x006000e1); cx25840_write4(client, DIF_BPF_COEFF1011, 0xffc4fe68); cx25840_write4(client, DIF_BPF_COEFF1213, 0xffa0024b); cx25840_write4(client, DIF_BPF_COEFF1415, 0x019afd66); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfc990216); cx25840_write4(client, DIF_BPF_COEFF1819, 0x0575ff99); cx25840_write4(client, DIF_BPF_COEFF2021, 0xf8d4fd81); cx25840_write4(client, DIF_BPF_COEFF2223, 0x07d40640); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf932f5e6); cx25840_write4(client, DIF_BPF_COEFF2627, 0x03d20d0d); cx25840_write4(client, DIF_BPF_COEFF2829, 0x00dff1de); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf9860cbf); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0bd1f71e); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf058032f); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 11100000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00010000); cx25840_write4(client, DIF_BPF_COEFF23, 0xfff8fff8); cx25840_write4(client, DIF_BPF_COEFF45, 0x001b0029); cx25840_write4(client, DIF_BPF_COEFF67, 0xffd1ff8a); cx25840_write4(client, DIF_BPF_COEFF89, 0x002600f2); cx25840_write4(client, DIF_BPF_COEFF1011, 0x002cfe7c); cx25840_write4(client, DIF_BPF_COEFF1213, 0xff0f01f0); cx25840_write4(client, DIF_BPF_COEFF1415, 0x023bfe20); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfc1700fa); cx25840_write4(client, DIF_BPF_COEFF1819, 0x05a200f7); cx25840_write4(client, DIF_BPF_COEFF2021, 0xf927fc1c); cx25840_write4(client, DIF_BPF_COEFF2223, 0x06f40765); cx25840_write4(client, DIF_BPF_COEFF2425, 0xfa82f53b); cx25840_write4(client, DIF_BPF_COEFF2627, 0x02510d27); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0243f23d); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf8810c24); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0c5cf7a7); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf03102fa); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 11200000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00010002); cx25840_write4(client, DIF_BPF_COEFF23, 0xfffafff2); cx25840_write4(client, DIF_BPF_COEFF45, 0x00110035); cx25840_write4(client, DIF_BPF_COEFF67, 0xfff0ff81); cx25840_write4(client, DIF_BPF_COEFF89, 0xffe700e7); cx25840_write4(client, DIF_BPF_COEFF1011, 0x008ffeb6); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe94016d); cx25840_write4(client, DIF_BPF_COEFF1415, 0x02b0fefb); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfbd3ffd1); cx25840_write4(client, DIF_BPF_COEFF1819, 0x05850249); cx25840_write4(client, DIF_BPF_COEFF2021, 0xf9c1fadb); cx25840_write4(client, DIF_BPF_COEFF2223, 0x05de0858); cx25840_write4(client, DIF_BPF_COEFF2425, 0xfbf2f4c4); cx25840_write4(client, DIF_BPF_COEFF2627, 0x00c70d17); cx25840_write4(client, DIF_BPF_COEFF2829, 0x03a0f2b8); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf7870b7c); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0cdff833); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf00d02c4); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 11300000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000003); cx25840_write4(client, DIF_BPF_COEFF23, 0xfffdffee); cx25840_write4(client, DIF_BPF_COEFF45, 0x00040038); cx25840_write4(client, DIF_BPF_COEFF67, 0x0010ff88); cx25840_write4(client, DIF_BPF_COEFF89, 0xffac00c2); cx25840_write4(client, DIF_BPF_COEFF1011, 0x00e2ff10); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe3900cb); cx25840_write4(client, DIF_BPF_COEFF1415, 0x02f1ffe9); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfbd3feaa); cx25840_write4(client, DIF_BPF_COEFF1819, 0x05210381); cx25840_write4(client, DIF_BPF_COEFF2021, 0xfa9cf9c8); cx25840_write4(client, DIF_BPF_COEFF2223, 0x04990912); cx25840_write4(client, DIF_BPF_COEFF2425, 0xfd7af484); cx25840_write4(client, DIF_BPF_COEFF2627, 0xff390cdb); cx25840_write4(client, DIF_BPF_COEFF2829, 0x04f4f34d); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf69a0ac9); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0d5af8c1); cx25840_write4(client, DIF_BPF_COEFF3435, 0xefec028e); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 11400000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000003); cx25840_write4(client, DIF_BPF_COEFF23, 0x0000ffee); cx25840_write4(client, DIF_BPF_COEFF45, 0xfff60033); cx25840_write4(client, DIF_BPF_COEFF67, 0x002fff9f); cx25840_write4(client, DIF_BPF_COEFF89, 0xff7b0087); cx25840_write4(client, DIF_BPF_COEFF1011, 0x011eff82); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe080018); cx25840_write4(client, DIF_BPF_COEFF1415, 0x02f900d8); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfc17fd96); cx25840_write4(client, DIF_BPF_COEFF1819, 0x04790490); cx25840_write4(client, DIF_BPF_COEFF2021, 0xfbadf8ed); cx25840_write4(client, DIF_BPF_COEFF2223, 0x032f098e); cx25840_write4(client, DIF_BPF_COEFF2425, 0xff10f47d); cx25840_write4(client, DIF_BPF_COEFF2627, 0xfdaf0c75); cx25840_write4(client, DIF_BPF_COEFF2829, 0x063cf3fc); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf5ba0a0b); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0dccf952); cx25840_write4(client, DIF_BPF_COEFF3435, 0xefcd0258); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 11500000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000003); cx25840_write4(client, DIF_BPF_COEFF23, 0x0004fff1); cx25840_write4(client, DIF_BPF_COEFF45, 0xffea0026); cx25840_write4(client, DIF_BPF_COEFF67, 0x0046ffc3); cx25840_write4(client, DIF_BPF_COEFF89, 0xff5a003c); cx25840_write4(client, DIF_BPF_COEFF1011, 0x013b0000); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe04ff63); cx25840_write4(client, DIF_BPF_COEFF1415, 0x02c801b8); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfc99fca6); cx25840_write4(client, DIF_BPF_COEFF1819, 0x0397056a); cx25840_write4(client, DIF_BPF_COEFF2021, 0xfcecf853); cx25840_write4(client, DIF_BPF_COEFF2223, 0x01ad09c9); cx25840_write4(client, DIF_BPF_COEFF2425, 0x00acf4ad); cx25840_write4(client, DIF_BPF_COEFF2627, 0xfc2e0be7); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0773f4c2); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf4e90943); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0e35f9e6); cx25840_write4(client, DIF_BPF_COEFF3435, 0xefb10221); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 11600000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000002); cx25840_write4(client, DIF_BPF_COEFF23, 0x0007fff6); cx25840_write4(client, DIF_BPF_COEFF45, 0xffe20014); cx25840_write4(client, DIF_BPF_COEFF67, 0x0054ffee); cx25840_write4(client, DIF_BPF_COEFF89, 0xff4effeb); cx25840_write4(client, DIF_BPF_COEFF1011, 0x0137007e); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe2efebb); cx25840_write4(client, DIF_BPF_COEFF1415, 0x0260027a); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfd51fbe6); cx25840_write4(client, DIF_BPF_COEFF1819, 0x02870605); cx25840_write4(client, DIF_BPF_COEFF2021, 0xfe4af7fe); cx25840_write4(client, DIF_BPF_COEFF2223, 0x001d09c1); cx25840_write4(client, DIF_BPF_COEFF2425, 0x0243f515); cx25840_write4(client, DIF_BPF_COEFF2627, 0xfabd0b32); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0897f59e); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf4280871); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0e95fa7c); cx25840_write4(client, DIF_BPF_COEFF3435, 0xef9701eb); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 11700000: cx25840_write4(client, DIF_BPF_COEFF01, 0xffff0001); cx25840_write4(client, DIF_BPF_COEFF23, 0x0008fffd); cx25840_write4(client, DIF_BPF_COEFF45, 0xffdeffff); cx25840_write4(client, DIF_BPF_COEFF67, 0x0056001d); cx25840_write4(client, DIF_BPF_COEFF89, 0xff57ff9c); cx25840_write4(client, DIF_BPF_COEFF1011, 0x011300f0); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe82fe2e); cx25840_write4(client, DIF_BPF_COEFF1415, 0x01ca0310); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfe35fb62); cx25840_write4(client, DIF_BPF_COEFF1819, 0x0155065a); cx25840_write4(client, DIF_BPF_COEFF2021, 0xffbaf7f2); cx25840_write4(client, DIF_BPF_COEFF2223, 0xfe8c0977); cx25840_write4(client, DIF_BPF_COEFF2425, 0x03cef5b2); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf9610a58); cx25840_write4(client, DIF_BPF_COEFF2829, 0x09a5f68f); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf3790797); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0eebfb14); cx25840_write4(client, DIF_BPF_COEFF3435, 0xef8001b5); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 11800000: cx25840_write4(client, DIF_BPF_COEFF01, 0xffff0000); cx25840_write4(client, DIF_BPF_COEFF23, 0x00080004); cx25840_write4(client, DIF_BPF_COEFF45, 0xffe0ffe9); cx25840_write4(client, DIF_BPF_COEFF67, 0x004c0047); cx25840_write4(client, DIF_BPF_COEFF89, 0xff75ff58); cx25840_write4(client, DIF_BPF_COEFF1011, 0x00d1014a); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfef9fdc8); cx25840_write4(client, DIF_BPF_COEFF1415, 0x0111036f); cx25840_write4(client, DIF_BPF_COEFF1617, 0xff36fb21); cx25840_write4(client, DIF_BPF_COEFF1819, 0x00120665); cx25840_write4(client, DIF_BPF_COEFF2021, 0x012df82e); cx25840_write4(client, DIF_BPF_COEFF2223, 0xfd0708ec); cx25840_write4(client, DIF_BPF_COEFF2425, 0x0542f682); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf81f095c); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0a9af792); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf2db06b5); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0f38fbad); cx25840_write4(client, DIF_BPF_COEFF3435, 0xef6c017e); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 11900000: cx25840_write4(client, DIF_BPF_COEFF01, 0xffffffff); cx25840_write4(client, DIF_BPF_COEFF23, 0x0007000b); cx25840_write4(client, DIF_BPF_COEFF45, 0xffe7ffd8); cx25840_write4(client, DIF_BPF_COEFF67, 0x00370068); cx25840_write4(client, DIF_BPF_COEFF89, 0xffa4ff28); cx25840_write4(client, DIF_BPF_COEFF1011, 0x00790184); cx25840_write4(client, DIF_BPF_COEFF1213, 0xff87fd91); cx25840_write4(client, DIF_BPF_COEFF1415, 0x00430392); cx25840_write4(client, DIF_BPF_COEFF1617, 0x0044fb26); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfece0626); cx25840_write4(client, DIF_BPF_COEFF2021, 0x0294f8b2); cx25840_write4(client, DIF_BPF_COEFF2223, 0xfb990825); cx25840_write4(client, DIF_BPF_COEFF2425, 0x0698f77f); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf6fe0842); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0b73f8a7); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf25105cd); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0f7bfc48); cx25840_write4(client, DIF_BPF_COEFF3435, 0xef5a0148); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 12000000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0000fffe); cx25840_write4(client, DIF_BPF_COEFF23, 0x00050010); cx25840_write4(client, DIF_BPF_COEFF45, 0xfff2ffcc); cx25840_write4(client, DIF_BPF_COEFF67, 0x001b007b); cx25840_write4(client, DIF_BPF_COEFF89, 0xffdfff10); cx25840_write4(client, DIF_BPF_COEFF1011, 0x00140198); cx25840_write4(client, DIF_BPF_COEFF1213, 0x0020fd8e); cx25840_write4(client, DIF_BPF_COEFF1415, 0xff710375); cx25840_write4(client, DIF_BPF_COEFF1617, 0x014dfb73); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfd9a059f); cx25840_write4(client, DIF_BPF_COEFF2021, 0x03e0f978); cx25840_write4(client, DIF_BPF_COEFF2223, 0xfa4e0726); cx25840_write4(client, DIF_BPF_COEFF2425, 0x07c8f8a7); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf600070c); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0c2ff9c9); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf1db04de); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0fb4fce5); cx25840_write4(client, DIF_BPF_COEFF3435, 0xef4b0111); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 12100000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0000fffd); cx25840_write4(client, DIF_BPF_COEFF23, 0x00010012); cx25840_write4(client, DIF_BPF_COEFF45, 0xffffffc8); cx25840_write4(client, DIF_BPF_COEFF67, 0xfffb007e); cx25840_write4(client, DIF_BPF_COEFF89, 0x001dff14); cx25840_write4(client, DIF_BPF_COEFF1011, 0xffad0184); cx25840_write4(client, DIF_BPF_COEFF1213, 0x00b7fdbe); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfea9031b); cx25840_write4(client, DIF_BPF_COEFF1617, 0x0241fc01); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfc8504d6); cx25840_write4(client, DIF_BPF_COEFF2021, 0x0504fa79); cx25840_write4(client, DIF_BPF_COEFF2223, 0xf93005f6); cx25840_write4(client, DIF_BPF_COEFF2425, 0x08caf9f2); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf52b05c0); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0ccbfaf9); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf17903eb); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0fe3fd83); cx25840_write4(client, DIF_BPF_COEFF3435, 0xef3f00db); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 12200000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0000fffd); cx25840_write4(client, DIF_BPF_COEFF23, 0xfffe0011); cx25840_write4(client, DIF_BPF_COEFF45, 0x000cffcc); cx25840_write4(client, DIF_BPF_COEFF67, 0xffdb0071); cx25840_write4(client, DIF_BPF_COEFF89, 0x0058ff32); cx25840_write4(client, DIF_BPF_COEFF1011, 0xff4f014a); cx25840_write4(client, DIF_BPF_COEFF1213, 0x013cfe1f); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfdfb028a); cx25840_write4(client, DIF_BPF_COEFF1617, 0x0311fcc9); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfb9d03d6); cx25840_write4(client, DIF_BPF_COEFF2021, 0x05f4fbad); cx25840_write4(client, DIF_BPF_COEFF2223, 0xf848049d); cx25840_write4(client, DIF_BPF_COEFF2425, 0x0999fb5b); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf4820461); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0d46fc32); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf12d02f4); cx25840_write4(client, DIF_BPF_COEFF3233, 0x1007fe21); cx25840_write4(client, DIF_BPF_COEFF3435, 0xef3600a4); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 12300000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0000fffe); cx25840_write4(client, DIF_BPF_COEFF23, 0xfffa000e); cx25840_write4(client, DIF_BPF_COEFF45, 0x0017ffd9); cx25840_write4(client, DIF_BPF_COEFF67, 0xffc10055); cx25840_write4(client, DIF_BPF_COEFF89, 0x0088ff68); cx25840_write4(client, DIF_BPF_COEFF1011, 0xff0400f0); cx25840_write4(client, DIF_BPF_COEFF1213, 0x01a6fea7); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfd7501cc); cx25840_write4(client, DIF_BPF_COEFF1617, 0x03b0fdc0); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfaef02a8); cx25840_write4(client, DIF_BPF_COEFF2021, 0x06a7fd07); cx25840_write4(client, DIF_BPF_COEFF2223, 0xf79d0326); cx25840_write4(client, DIF_BPF_COEFF2425, 0x0a31fcda); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf40702f3); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0d9ffd72); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf0f601fa); cx25840_write4(client, DIF_BPF_COEFF3233, 0x1021fec0); cx25840_write4(client, DIF_BPF_COEFF3435, 0xef2f006d); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 12400000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0001ffff); cx25840_write4(client, DIF_BPF_COEFF23, 0xfff80007); cx25840_write4(client, DIF_BPF_COEFF45, 0x001fffeb); cx25840_write4(client, DIF_BPF_COEFF67, 0xffaf002d); cx25840_write4(client, DIF_BPF_COEFF89, 0x00a8ffb0); cx25840_write4(client, DIF_BPF_COEFF1011, 0xfed3007e); cx25840_write4(client, DIF_BPF_COEFF1213, 0x01e9ff4c); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfd2000ee); cx25840_write4(client, DIF_BPF_COEFF1617, 0x0413fed8); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfa82015c); cx25840_write4(client, DIF_BPF_COEFF2021, 0x0715fe7d); cx25840_write4(client, DIF_BPF_COEFF2223, 0xf7340198); cx25840_write4(client, DIF_BPF_COEFF2425, 0x0a8dfe69); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf3bd017c); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0dd5feb8); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf0d500fd); cx25840_write4(client, DIF_BPF_COEFF3233, 0x1031ff60); cx25840_write4(client, DIF_BPF_COEFF3435, 0xef2b0037); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 12500000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00010000); cx25840_write4(client, DIF_BPF_COEFF23, 0xfff70000); cx25840_write4(client, DIF_BPF_COEFF45, 0x00220000); cx25840_write4(client, DIF_BPF_COEFF67, 0xffa90000); cx25840_write4(client, DIF_BPF_COEFF89, 0x00b30000); cx25840_write4(client, DIF_BPF_COEFF1011, 0xfec20000); cx25840_write4(client, DIF_BPF_COEFF1213, 0x02000000); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfd030000); cx25840_write4(client, DIF_BPF_COEFF1617, 0x04350000); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfa5e0000); cx25840_write4(client, DIF_BPF_COEFF2021, 0x073b0000); cx25840_write4(client, DIF_BPF_COEFF2223, 0xf7110000); cx25840_write4(client, DIF_BPF_COEFF2425, 0x0aac0000); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf3a40000); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0de70000); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf0c90000); cx25840_write4(client, DIF_BPF_COEFF3233, 0x10360000); cx25840_write4(client, DIF_BPF_COEFF3435, 0xef290000); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 12600000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00010001); cx25840_write4(client, DIF_BPF_COEFF23, 0xfff8fff9); cx25840_write4(client, DIF_BPF_COEFF45, 0x001f0015); cx25840_write4(client, DIF_BPF_COEFF67, 0xffafffd3); cx25840_write4(client, DIF_BPF_COEFF89, 0x00a80050); cx25840_write4(client, DIF_BPF_COEFF1011, 0xfed3ff82); cx25840_write4(client, DIF_BPF_COEFF1213, 0x01e900b4); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfd20ff12); cx25840_write4(client, DIF_BPF_COEFF1617, 0x04130128); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfa82fea4); cx25840_write4(client, DIF_BPF_COEFF2021, 0x07150183); cx25840_write4(client, DIF_BPF_COEFF2223, 0xf734fe68); cx25840_write4(client, DIF_BPF_COEFF2425, 0x0a8d0197); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf3bdfe84); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0dd50148); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf0d5ff03); cx25840_write4(client, DIF_BPF_COEFF3233, 0x103100a0); cx25840_write4(client, DIF_BPF_COEFF3435, 0xef2bffc9); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 12700000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000002); cx25840_write4(client, DIF_BPF_COEFF23, 0xfffafff2); cx25840_write4(client, DIF_BPF_COEFF45, 0x00170027); cx25840_write4(client, DIF_BPF_COEFF67, 0xffc1ffab); cx25840_write4(client, DIF_BPF_COEFF89, 0x00880098); cx25840_write4(client, DIF_BPF_COEFF1011, 0xff04ff10); cx25840_write4(client, DIF_BPF_COEFF1213, 0x01a60159); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfd75fe34); cx25840_write4(client, DIF_BPF_COEFF1617, 0x03b00240); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfaeffd58); cx25840_write4(client, DIF_BPF_COEFF2021, 0x06a702f9); cx25840_write4(client, DIF_BPF_COEFF2223, 0xf79dfcda); cx25840_write4(client, DIF_BPF_COEFF2425, 0x0a310326); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf407fd0d); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0d9f028e); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf0f6fe06); cx25840_write4(client, DIF_BPF_COEFF3233, 0x10210140); cx25840_write4(client, DIF_BPF_COEFF3435, 0xef2fff93); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 12800000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000003); cx25840_write4(client, DIF_BPF_COEFF23, 0xfffeffef); cx25840_write4(client, DIF_BPF_COEFF45, 0x000c0034); cx25840_write4(client, DIF_BPF_COEFF67, 0xffdbff8f); cx25840_write4(client, DIF_BPF_COEFF89, 0x005800ce); cx25840_write4(client, DIF_BPF_COEFF1011, 0xff4ffeb6); cx25840_write4(client, DIF_BPF_COEFF1213, 0x013c01e1); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfdfbfd76); cx25840_write4(client, DIF_BPF_COEFF1617, 0x03110337); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfb9dfc2a); cx25840_write4(client, DIF_BPF_COEFF2021, 0x05f40453); cx25840_write4(client, DIF_BPF_COEFF2223, 0xf848fb63); cx25840_write4(client, DIF_BPF_COEFF2425, 0x099904a5); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf482fb9f); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0d4603ce); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf12dfd0c); cx25840_write4(client, DIF_BPF_COEFF3233, 0x100701df); cx25840_write4(client, DIF_BPF_COEFF3435, 0xef36ff5c); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 12900000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000003); cx25840_write4(client, DIF_BPF_COEFF23, 0x0001ffee); cx25840_write4(client, DIF_BPF_COEFF45, 0xffff0038); cx25840_write4(client, DIF_BPF_COEFF67, 0xfffbff82); cx25840_write4(client, DIF_BPF_COEFF89, 0x001d00ec); cx25840_write4(client, DIF_BPF_COEFF1011, 0xffadfe7c); cx25840_write4(client, DIF_BPF_COEFF1213, 0x00b70242); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfea9fce5); cx25840_write4(client, DIF_BPF_COEFF1617, 0x024103ff); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfc85fb2a); cx25840_write4(client, DIF_BPF_COEFF2021, 0x05040587); cx25840_write4(client, DIF_BPF_COEFF2223, 0xf930fa0a); cx25840_write4(client, DIF_BPF_COEFF2425, 0x08ca060e); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf52bfa40); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0ccb0507); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf179fc15); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0fe3027d); cx25840_write4(client, DIF_BPF_COEFF3435, 0xef3fff25); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 13000000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000002); cx25840_write4(client, DIF_BPF_COEFF23, 0x0005fff0); cx25840_write4(client, DIF_BPF_COEFF45, 0xfff20034); cx25840_write4(client, DIF_BPF_COEFF67, 0x001bff85); cx25840_write4(client, DIF_BPF_COEFF89, 0xffdf00f0); cx25840_write4(client, DIF_BPF_COEFF1011, 0x0014fe68); cx25840_write4(client, DIF_BPF_COEFF1213, 0x00200272); cx25840_write4(client, DIF_BPF_COEFF1415, 0xff71fc8b); cx25840_write4(client, DIF_BPF_COEFF1617, 0x014d048d); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfd9afa61); cx25840_write4(client, DIF_BPF_COEFF2021, 0x03e00688); cx25840_write4(client, DIF_BPF_COEFF2223, 0xfa4ef8da); cx25840_write4(client, DIF_BPF_COEFF2425, 0x07c80759); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf600f8f4); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0c2f0637); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf1dbfb22); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0fb4031b); cx25840_write4(client, DIF_BPF_COEFF3435, 0xef4bfeef); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 13100000: cx25840_write4(client, DIF_BPF_COEFF01, 0xffff0001); cx25840_write4(client, DIF_BPF_COEFF23, 0x0007fff5); cx25840_write4(client, DIF_BPF_COEFF45, 0xffe70028); cx25840_write4(client, DIF_BPF_COEFF67, 0x0037ff98); cx25840_write4(client, DIF_BPF_COEFF89, 0xffa400d8); cx25840_write4(client, DIF_BPF_COEFF1011, 0x0079fe7c); cx25840_write4(client, DIF_BPF_COEFF1213, 0xff87026f); cx25840_write4(client, DIF_BPF_COEFF1415, 0x0043fc6e); cx25840_write4(client, DIF_BPF_COEFF1617, 0x004404da); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfecef9da); cx25840_write4(client, DIF_BPF_COEFF2021, 0x0294074e); cx25840_write4(client, DIF_BPF_COEFF2223, 0xfb99f7db); cx25840_write4(client, DIF_BPF_COEFF2425, 0x06980881); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf6fef7be); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0b730759); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf251fa33); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0f7b03b8); cx25840_write4(client, DIF_BPF_COEFF3435, 0xef5afeb8); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 13200000: cx25840_write4(client, DIF_BPF_COEFF01, 0xffff0000); cx25840_write4(client, DIF_BPF_COEFF23, 0x0008fffc); cx25840_write4(client, DIF_BPF_COEFF45, 0xffe00017); cx25840_write4(client, DIF_BPF_COEFF67, 0x004cffb9); cx25840_write4(client, DIF_BPF_COEFF89, 0xff7500a8); cx25840_write4(client, DIF_BPF_COEFF1011, 0x00d1feb6); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfef90238); cx25840_write4(client, DIF_BPF_COEFF1415, 0x0111fc91); cx25840_write4(client, DIF_BPF_COEFF1617, 0xff3604df); cx25840_write4(client, DIF_BPF_COEFF1819, 0x0012f99b); cx25840_write4(client, DIF_BPF_COEFF2021, 0x012d07d2); cx25840_write4(client, DIF_BPF_COEFF2223, 0xfd07f714); cx25840_write4(client, DIF_BPF_COEFF2425, 0x0542097e); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf81ff6a4); cx25840_write4(client, DIF_BPF_COEFF2829, 0x0a9a086e); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf2dbf94b); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0f380453); cx25840_write4(client, DIF_BPF_COEFF3435, 0xef6cfe82); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 13300000: cx25840_write4(client, DIF_BPF_COEFF01, 0xffffffff); cx25840_write4(client, DIF_BPF_COEFF23, 0x00080003); cx25840_write4(client, DIF_BPF_COEFF45, 0xffde0001); cx25840_write4(client, DIF_BPF_COEFF67, 0x0056ffe3); cx25840_write4(client, DIF_BPF_COEFF89, 0xff570064); cx25840_write4(client, DIF_BPF_COEFF1011, 0x0113ff10); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe8201d2); cx25840_write4(client, DIF_BPF_COEFF1415, 0x01cafcf0); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfe35049e); cx25840_write4(client, DIF_BPF_COEFF1819, 0x0155f9a6); cx25840_write4(client, DIF_BPF_COEFF2021, 0xffba080e); cx25840_write4(client, DIF_BPF_COEFF2223, 0xfe8cf689); cx25840_write4(client, DIF_BPF_COEFF2425, 0x03ce0a4e); cx25840_write4(client, DIF_BPF_COEFF2627, 0xf961f5a8); cx25840_write4(client, DIF_BPF_COEFF2829, 0x09a50971); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf379f869); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0eeb04ec); cx25840_write4(client, DIF_BPF_COEFF3435, 0xef80fe4b); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 13400000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0000fffe); cx25840_write4(client, DIF_BPF_COEFF23, 0x0007000a); cx25840_write4(client, DIF_BPF_COEFF45, 0xffe2ffec); cx25840_write4(client, DIF_BPF_COEFF67, 0x00540012); cx25840_write4(client, DIF_BPF_COEFF89, 0xff4e0015); cx25840_write4(client, DIF_BPF_COEFF1011, 0x0137ff82); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe2e0145); cx25840_write4(client, DIF_BPF_COEFF1415, 0x0260fd86); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfd51041a); cx25840_write4(client, DIF_BPF_COEFF1819, 0x0287f9fb); cx25840_write4(client, DIF_BPF_COEFF2021, 0xfe4a0802); cx25840_write4(client, DIF_BPF_COEFF2223, 0x001df63f); cx25840_write4(client, DIF_BPF_COEFF2425, 0x02430aeb); cx25840_write4(client, DIF_BPF_COEFF2627, 0xfabdf4ce); cx25840_write4(client, DIF_BPF_COEFF2829, 0x08970a62); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf428f78f); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0e950584); cx25840_write4(client, DIF_BPF_COEFF3435, 0xef97fe15); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 13500000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0000fffd); cx25840_write4(client, DIF_BPF_COEFF23, 0x0004000f); cx25840_write4(client, DIF_BPF_COEFF45, 0xffeaffda); cx25840_write4(client, DIF_BPF_COEFF67, 0x0046003d); cx25840_write4(client, DIF_BPF_COEFF89, 0xff5affc4); cx25840_write4(client, DIF_BPF_COEFF1011, 0x013b0000); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe04009d); cx25840_write4(client, DIF_BPF_COEFF1415, 0x02c8fe48); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfc99035a); cx25840_write4(client, DIF_BPF_COEFF1819, 0x0397fa96); cx25840_write4(client, DIF_BPF_COEFF2021, 0xfcec07ad); cx25840_write4(client, DIF_BPF_COEFF2223, 0x01adf637); cx25840_write4(client, DIF_BPF_COEFF2425, 0x00ac0b53); cx25840_write4(client, DIF_BPF_COEFF2627, 0xfc2ef419); cx25840_write4(client, DIF_BPF_COEFF2829, 0x07730b3e); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf4e9f6bd); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0e35061a); cx25840_write4(client, DIF_BPF_COEFF3435, 0xefb1fddf); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 13600000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0000fffd); cx25840_write4(client, DIF_BPF_COEFF23, 0x00000012); cx25840_write4(client, DIF_BPF_COEFF45, 0xfff6ffcd); cx25840_write4(client, DIF_BPF_COEFF67, 0x002f0061); cx25840_write4(client, DIF_BPF_COEFF89, 0xff7bff79); cx25840_write4(client, DIF_BPF_COEFF1011, 0x011e007e); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe08ffe8); cx25840_write4(client, DIF_BPF_COEFF1415, 0x02f9ff28); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfc17026a); cx25840_write4(client, DIF_BPF_COEFF1819, 0x0479fb70); cx25840_write4(client, DIF_BPF_COEFF2021, 0xfbad0713); cx25840_write4(client, DIF_BPF_COEFF2223, 0x032ff672); cx25840_write4(client, DIF_BPF_COEFF2425, 0xff100b83); cx25840_write4(client, DIF_BPF_COEFF2627, 0xfdaff38b); cx25840_write4(client, DIF_BPF_COEFF2829, 0x063c0c04); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf5baf5f5); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0dcc06ae); cx25840_write4(client, DIF_BPF_COEFF3435, 0xefcdfda8); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 13700000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0000fffd); cx25840_write4(client, DIF_BPF_COEFF23, 0xfffd0012); cx25840_write4(client, DIF_BPF_COEFF45, 0x0004ffc8); cx25840_write4(client, DIF_BPF_COEFF67, 0x00100078); cx25840_write4(client, DIF_BPF_COEFF89, 0xffacff3e); cx25840_write4(client, DIF_BPF_COEFF1011, 0x00e200f0); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe39ff35); cx25840_write4(client, DIF_BPF_COEFF1415, 0x02f10017); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfbd30156); cx25840_write4(client, DIF_BPF_COEFF1819, 0x0521fc7f); cx25840_write4(client, DIF_BPF_COEFF2021, 0xfa9c0638); cx25840_write4(client, DIF_BPF_COEFF2223, 0x0499f6ee); cx25840_write4(client, DIF_BPF_COEFF2425, 0xfd7a0b7c); cx25840_write4(client, DIF_BPF_COEFF2627, 0xff39f325); cx25840_write4(client, DIF_BPF_COEFF2829, 0x04f40cb3); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf69af537); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0d5a073f); cx25840_write4(client, DIF_BPF_COEFF3435, 0xefecfd72); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 13800000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0001fffe); cx25840_write4(client, DIF_BPF_COEFF23, 0xfffa000e); cx25840_write4(client, DIF_BPF_COEFF45, 0x0011ffcb); cx25840_write4(client, DIF_BPF_COEFF67, 0xfff0007f); cx25840_write4(client, DIF_BPF_COEFF89, 0xffe7ff19); cx25840_write4(client, DIF_BPF_COEFF1011, 0x008f014a); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe94fe93); cx25840_write4(client, DIF_BPF_COEFF1415, 0x02b00105); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfbd3002f); cx25840_write4(client, DIF_BPF_COEFF1819, 0x0585fdb7); cx25840_write4(client, DIF_BPF_COEFF2021, 0xf9c10525); cx25840_write4(client, DIF_BPF_COEFF2223, 0x05def7a8); cx25840_write4(client, DIF_BPF_COEFF2425, 0xfbf20b3c); cx25840_write4(client, DIF_BPF_COEFF2627, 0x00c7f2e9); cx25840_write4(client, DIF_BPF_COEFF2829, 0x03a00d48); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf787f484); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0cdf07cd); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf00dfd3c); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 13900000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00010000); cx25840_write4(client, DIF_BPF_COEFF23, 0xfff80008); cx25840_write4(client, DIF_BPF_COEFF45, 0x001bffd7); cx25840_write4(client, DIF_BPF_COEFF67, 0xffd10076); cx25840_write4(client, DIF_BPF_COEFF89, 0x0026ff0e); cx25840_write4(client, DIF_BPF_COEFF1011, 0x002c0184); cx25840_write4(client, DIF_BPF_COEFF1213, 0xff0ffe10); cx25840_write4(client, DIF_BPF_COEFF1415, 0x023b01e0); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfc17ff06); cx25840_write4(client, DIF_BPF_COEFF1819, 0x05a2ff09); cx25840_write4(client, DIF_BPF_COEFF2021, 0xf92703e4); cx25840_write4(client, DIF_BPF_COEFF2223, 0x06f4f89b); cx25840_write4(client, DIF_BPF_COEFF2425, 0xfa820ac5); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0251f2d9); cx25840_write4(client, DIF_BPF_COEFF2829, 0x02430dc3); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf881f3dc); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0c5c0859); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf031fd06); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 14000000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00010001); cx25840_write4(client, DIF_BPF_COEFF23, 0xfff80001); cx25840_write4(client, DIF_BPF_COEFF45, 0x0021ffe8); cx25840_write4(client, DIF_BPF_COEFF67, 0xffba005d); cx25840_write4(client, DIF_BPF_COEFF89, 0x0060ff1f); cx25840_write4(client, DIF_BPF_COEFF1011, 0xffc40198); cx25840_write4(client, DIF_BPF_COEFF1213, 0xffa0fdb5); cx25840_write4(client, DIF_BPF_COEFF1415, 0x019a029a); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfc99fdea); cx25840_write4(client, DIF_BPF_COEFF1819, 0x05750067); cx25840_write4(client, DIF_BPF_COEFF2021, 0xf8d4027f); cx25840_write4(client, DIF_BPF_COEFF2223, 0x07d4f9c0); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf9320a1a); cx25840_write4(client, DIF_BPF_COEFF2627, 0x03d2f2f3); cx25840_write4(client, DIF_BPF_COEFF2829, 0x00df0e22); cx25840_write4(client, DIF_BPF_COEFF3031, 0xf986f341); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0bd108e2); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf058fcd1); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 14100000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000002); cx25840_write4(client, DIF_BPF_COEFF23, 0xfff9fffa); cx25840_write4(client, DIF_BPF_COEFF45, 0x0021fffd); cx25840_write4(client, DIF_BPF_COEFF67, 0xffac0038); cx25840_write4(client, DIF_BPF_COEFF89, 0x008eff4a); cx25840_write4(client, DIF_BPF_COEFF1011, 0xff630184); cx25840_write4(client, DIF_BPF_COEFF1213, 0x003afd8b); cx25840_write4(client, DIF_BPF_COEFF1415, 0x00da0326); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfd51fced); cx25840_write4(client, DIF_BPF_COEFF1819, 0x050101c0); cx25840_write4(client, DIF_BPF_COEFF2021, 0xf8cb0103); cx25840_write4(client, DIF_BPF_COEFF2223, 0x0876fb10); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf80a093e); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0543f338); cx25840_write4(client, DIF_BPF_COEFF2829, 0xff7a0e66); cx25840_write4(client, DIF_BPF_COEFF3031, 0xfa94f2b2); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0b3f0967); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf081fc9b); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 14200000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000003); cx25840_write4(client, DIF_BPF_COEFF23, 0xfffbfff3); cx25840_write4(client, DIF_BPF_COEFF45, 0x001d0013); cx25840_write4(client, DIF_BPF_COEFF67, 0xffaa000b); cx25840_write4(client, DIF_BPF_COEFF89, 0x00aaff89); cx25840_write4(client, DIF_BPF_COEFF1011, 0xff13014a); cx25840_write4(client, DIF_BPF_COEFF1213, 0x00cefd95); cx25840_write4(client, DIF_BPF_COEFF1415, 0x000a037b); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfe35fc1d); cx25840_write4(client, DIF_BPF_COEFF1819, 0x044c0305); cx25840_write4(client, DIF_BPF_COEFF2021, 0xf90cff7e); cx25840_write4(client, DIF_BPF_COEFF2223, 0x08d5fc81); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf7100834); cx25840_write4(client, DIF_BPF_COEFF2627, 0x069ff3a7); cx25840_write4(client, DIF_BPF_COEFF2829, 0xfe160e8d); cx25840_write4(client, DIF_BPF_COEFF3031, 0xfbaaf231); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0aa509e9); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf0adfc65); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 14300000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000003); cx25840_write4(client, DIF_BPF_COEFF23, 0xffffffef); cx25840_write4(client, DIF_BPF_COEFF45, 0x00140025); cx25840_write4(client, DIF_BPF_COEFF67, 0xffb4ffdd); cx25840_write4(client, DIF_BPF_COEFF89, 0x00b2ffd6); cx25840_write4(client, DIF_BPF_COEFF1011, 0xfedb00f0); cx25840_write4(client, DIF_BPF_COEFF1213, 0x0150fdd3); cx25840_write4(client, DIF_BPF_COEFF1415, 0xff380391); cx25840_write4(client, DIF_BPF_COEFF1617, 0xff36fb85); cx25840_write4(client, DIF_BPF_COEFF1819, 0x035e0426); cx25840_write4(client, DIF_BPF_COEFF2021, 0xf994fdfe); cx25840_write4(client, DIF_BPF_COEFF2223, 0x08eefe0b); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf6490702); cx25840_write4(client, DIF_BPF_COEFF2627, 0x07e1f43e); cx25840_write4(client, DIF_BPF_COEFF2829, 0xfcb60e97); cx25840_write4(client, DIF_BPF_COEFF3031, 0xfcc6f1be); cx25840_write4(client, DIF_BPF_COEFF3233, 0x0a040a67); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf0dbfc30); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 14400000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000003); cx25840_write4(client, DIF_BPF_COEFF23, 0x0002ffee); cx25840_write4(client, DIF_BPF_COEFF45, 0x00070033); cx25840_write4(client, DIF_BPF_COEFF67, 0xffc9ffb4); cx25840_write4(client, DIF_BPF_COEFF89, 0x00a40027); cx25840_write4(client, DIF_BPF_COEFF1011, 0xfec3007e); cx25840_write4(client, DIF_BPF_COEFF1213, 0x01b4fe3f); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfe760369); cx25840_write4(client, DIF_BPF_COEFF1617, 0x0044fb2e); cx25840_write4(client, DIF_BPF_COEFF1819, 0x02450518); cx25840_write4(client, DIF_BPF_COEFF2021, 0xfa5ffc90); cx25840_write4(client, DIF_BPF_COEFF2223, 0x08c1ffa1); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf5bc05ae); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0902f4fc); cx25840_write4(client, DIF_BPF_COEFF2829, 0xfb600e85); cx25840_write4(client, DIF_BPF_COEFF3031, 0xfde7f15a); cx25840_write4(client, DIF_BPF_COEFF3233, 0x095d0ae2); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf10cfbfb); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 14500000: cx25840_write4(client, DIF_BPF_COEFF01, 0xffff0002); cx25840_write4(client, DIF_BPF_COEFF23, 0x0005ffef); cx25840_write4(client, DIF_BPF_COEFF45, 0xfffa0038); cx25840_write4(client, DIF_BPF_COEFF67, 0xffe5ff95); cx25840_write4(client, DIF_BPF_COEFF89, 0x00820074); cx25840_write4(client, DIF_BPF_COEFF1011, 0xfecc0000); cx25840_write4(client, DIF_BPF_COEFF1213, 0x01f0fed0); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfdd20304); cx25840_write4(client, DIF_BPF_COEFF1617, 0x014dfb1d); cx25840_write4(client, DIF_BPF_COEFF1819, 0x010e05ce); cx25840_write4(client, DIF_BPF_COEFF2021, 0xfb64fb41); cx25840_write4(client, DIF_BPF_COEFF2223, 0x084e013b); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf569043e); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0a00f5dd); cx25840_write4(client, DIF_BPF_COEFF2829, 0xfa150e55); cx25840_write4(client, DIF_BPF_COEFF3031, 0xff0bf104); cx25840_write4(client, DIF_BPF_COEFF3233, 0x08b00b59); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf13ffbc6); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 14600000: cx25840_write4(client, DIF_BPF_COEFF01, 0xffff0001); cx25840_write4(client, DIF_BPF_COEFF23, 0x0008fff4); cx25840_write4(client, DIF_BPF_COEFF45, 0xffed0035); cx25840_write4(client, DIF_BPF_COEFF67, 0x0005ff83); cx25840_write4(client, DIF_BPF_COEFF89, 0x005000b4); cx25840_write4(client, DIF_BPF_COEFF1011, 0xfef6ff82); cx25840_write4(client, DIF_BPF_COEFF1213, 0x01ffff7a); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfd580269); cx25840_write4(client, DIF_BPF_COEFF1617, 0x0241fb53); cx25840_write4(client, DIF_BPF_COEFF1819, 0xffca0640); cx25840_write4(client, DIF_BPF_COEFF2021, 0xfc99fa1e); cx25840_write4(client, DIF_BPF_COEFF2223, 0x079a02cb); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf55502ba); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0ad5f6e0); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf8d90e0a); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0031f0bd); cx25840_write4(client, DIF_BPF_COEFF3233, 0x07fd0bcb); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf174fb91); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 14700000: cx25840_write4(client, DIF_BPF_COEFF01, 0xffffffff); cx25840_write4(client, DIF_BPF_COEFF23, 0x0009fffb); cx25840_write4(client, DIF_BPF_COEFF45, 0xffe4002a); cx25840_write4(client, DIF_BPF_COEFF67, 0x0025ff82); cx25840_write4(client, DIF_BPF_COEFF89, 0x001400e0); cx25840_write4(client, DIF_BPF_COEFF1011, 0xff3cff10); cx25840_write4(client, DIF_BPF_COEFF1213, 0x01e10030); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfd1201a4); cx25840_write4(client, DIF_BPF_COEFF1617, 0x0311fbcd); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfe88066a); cx25840_write4(client, DIF_BPF_COEFF2021, 0xfdf1f92f); cx25840_write4(client, DIF_BPF_COEFF2223, 0x06aa0449); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf57e0128); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0b7ef801); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf7b00da2); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0156f086); cx25840_write4(client, DIF_BPF_COEFF3233, 0x07450c39); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf1acfb5c); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 14800000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0000fffe); cx25840_write4(client, DIF_BPF_COEFF23, 0x00080002); cx25840_write4(client, DIF_BPF_COEFF45, 0xffdf0019); cx25840_write4(client, DIF_BPF_COEFF67, 0x003fff92); cx25840_write4(client, DIF_BPF_COEFF89, 0xffd600f1); cx25840_write4(client, DIF_BPF_COEFF1011, 0xff96feb6); cx25840_write4(client, DIF_BPF_COEFF1213, 0x019700e1); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfd0500c2); cx25840_write4(client, DIF_BPF_COEFF1617, 0x03b0fc84); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfd590649); cx25840_write4(client, DIF_BPF_COEFF2021, 0xff5df87f); cx25840_write4(client, DIF_BPF_COEFF2223, 0x058505aa); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf5e4ff91); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0bf9f93c); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf69d0d20); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0279f05e); cx25840_write4(client, DIF_BPF_COEFF3233, 0x06880ca3); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf1e6fb28); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 14900000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0000fffd); cx25840_write4(client, DIF_BPF_COEFF23, 0x00060009); cx25840_write4(client, DIF_BPF_COEFF45, 0xffdf0004); cx25840_write4(client, DIF_BPF_COEFF67, 0x0051ffb0); cx25840_write4(client, DIF_BPF_COEFF89, 0xff9d00e8); cx25840_write4(client, DIF_BPF_COEFF1011, 0xfffcfe7c); cx25840_write4(client, DIF_BPF_COEFF1213, 0x01280180); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfd32ffd2); cx25840_write4(client, DIF_BPF_COEFF1617, 0x0413fd6e); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfc4d05df); cx25840_write4(client, DIF_BPF_COEFF2021, 0x00d1f812); cx25840_write4(client, DIF_BPF_COEFF2223, 0x043506e4); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf685fdfb); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0c43fa8d); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf5a10c83); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0399f046); cx25840_write4(client, DIF_BPF_COEFF3233, 0x05c70d08); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf222faf3); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 15000000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0000fffd); cx25840_write4(client, DIF_BPF_COEFF23, 0x0003000f); cx25840_write4(client, DIF_BPF_COEFF45, 0xffe5ffef); cx25840_write4(client, DIF_BPF_COEFF67, 0x0057ffd9); cx25840_write4(client, DIF_BPF_COEFF89, 0xff7000c4); cx25840_write4(client, DIF_BPF_COEFF1011, 0x0062fe68); cx25840_write4(client, DIF_BPF_COEFF1213, 0x009e01ff); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfd95fee6); cx25840_write4(client, DIF_BPF_COEFF1617, 0x0435fe7d); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfb710530); cx25840_write4(client, DIF_BPF_COEFF2021, 0x023cf7ee); cx25840_write4(client, DIF_BPF_COEFF2223, 0x02c307ef); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf75efc70); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0c5cfbef); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf4c10bce); cx25840_write4(client, DIF_BPF_COEFF3031, 0x04b3f03f); cx25840_write4(client, DIF_BPF_COEFF3233, 0x05030d69); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf261fabf); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 15100000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0000fffd); cx25840_write4(client, DIF_BPF_COEFF23, 0xffff0012); cx25840_write4(client, DIF_BPF_COEFF45, 0xffefffdc); cx25840_write4(client, DIF_BPF_COEFF67, 0x00510006); cx25840_write4(client, DIF_BPF_COEFF89, 0xff540089); cx25840_write4(client, DIF_BPF_COEFF1011, 0x00befe7c); cx25840_write4(client, DIF_BPF_COEFF1213, 0x00060253); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfe27fe0d); cx25840_write4(client, DIF_BPF_COEFF1617, 0x0413ffa2); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfad10446); cx25840_write4(client, DIF_BPF_COEFF2021, 0x0390f812); cx25840_write4(client, DIF_BPF_COEFF2223, 0x013b08c3); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf868faf6); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0c43fd5f); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf3fd0b02); cx25840_write4(client, DIF_BPF_COEFF3031, 0x05c7f046); cx25840_write4(client, DIF_BPF_COEFF3233, 0x043b0dc4); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf2a1fa8b); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 15200000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0001fffe); cx25840_write4(client, DIF_BPF_COEFF23, 0xfffc0012); cx25840_write4(client, DIF_BPF_COEFF45, 0xfffbffce); cx25840_write4(client, DIF_BPF_COEFF67, 0x003f0033); cx25840_write4(client, DIF_BPF_COEFF89, 0xff4e003f); cx25840_write4(client, DIF_BPF_COEFF1011, 0x0106feb6); cx25840_write4(client, DIF_BPF_COEFF1213, 0xff6e0276); cx25840_write4(client, DIF_BPF_COEFF1415, 0xfeddfd56); cx25840_write4(client, DIF_BPF_COEFF1617, 0x03b000cc); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfa740329); cx25840_write4(client, DIF_BPF_COEFF2021, 0x04bff87f); cx25840_write4(client, DIF_BPF_COEFF2223, 0xffaa095d); cx25840_write4(client, DIF_BPF_COEFF2425, 0xf99ef995); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0bf9fed8); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf3590a1f); cx25840_write4(client, DIF_BPF_COEFF3031, 0x06d2f05e); cx25840_write4(client, DIF_BPF_COEFF3233, 0x03700e1b); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf2e4fa58); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 15300000: cx25840_write4(client, DIF_BPF_COEFF01, 0x0001ffff); cx25840_write4(client, DIF_BPF_COEFF23, 0xfff9000f); cx25840_write4(client, DIF_BPF_COEFF45, 0x0009ffc8); cx25840_write4(client, DIF_BPF_COEFF67, 0x00250059); cx25840_write4(client, DIF_BPF_COEFF89, 0xff5effee); cx25840_write4(client, DIF_BPF_COEFF1011, 0x0132ff10); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfee30265); cx25840_write4(client, DIF_BPF_COEFF1415, 0xffaafccf); cx25840_write4(client, DIF_BPF_COEFF1617, 0x031101eb); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfa6001e8); cx25840_write4(client, DIF_BPF_COEFF2021, 0x05bdf92f); cx25840_write4(client, DIF_BPF_COEFF2223, 0xfe1b09b6); cx25840_write4(client, DIF_BPF_COEFF2425, 0xfafaf852); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0b7e0055); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf2d50929); cx25840_write4(client, DIF_BPF_COEFF3031, 0x07d3f086); cx25840_write4(client, DIF_BPF_COEFF3233, 0x02a30e6c); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf329fa24); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 15400000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00010001); cx25840_write4(client, DIF_BPF_COEFF23, 0xfff80009); cx25840_write4(client, DIF_BPF_COEFF45, 0x0015ffca); cx25840_write4(client, DIF_BPF_COEFF67, 0x00050074); cx25840_write4(client, DIF_BPF_COEFF89, 0xff81ff9f); cx25840_write4(client, DIF_BPF_COEFF1011, 0x013dff82); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe710221); cx25840_write4(client, DIF_BPF_COEFF1415, 0x007cfc80); cx25840_write4(client, DIF_BPF_COEFF1617, 0x024102ed); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfa940090); cx25840_write4(client, DIF_BPF_COEFF2021, 0x0680fa1e); cx25840_write4(client, DIF_BPF_COEFF2223, 0xfc9b09cd); cx25840_write4(client, DIF_BPF_COEFF2425, 0xfc73f736); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0ad501d0); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf2740820); cx25840_write4(client, DIF_BPF_COEFF3031, 0x08c9f0bd); cx25840_write4(client, DIF_BPF_COEFF3233, 0x01d40eb9); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf371f9f1); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 15500000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000002); cx25840_write4(client, DIF_BPF_COEFF23, 0xfff80002); cx25840_write4(client, DIF_BPF_COEFF45, 0x001effd5); cx25840_write4(client, DIF_BPF_COEFF67, 0xffe5007f); cx25840_write4(client, DIF_BPF_COEFF89, 0xffb4ff5b); cx25840_write4(client, DIF_BPF_COEFF1011, 0x01280000); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe2401b0); cx25840_write4(client, DIF_BPF_COEFF1415, 0x0146fc70); cx25840_write4(client, DIF_BPF_COEFF1617, 0x014d03c6); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfb10ff32); cx25840_write4(client, DIF_BPF_COEFF2021, 0x0701fb41); cx25840_write4(client, DIF_BPF_COEFF2223, 0xfb3709a1); cx25840_write4(client, DIF_BPF_COEFF2425, 0xfe00f644); cx25840_write4(client, DIF_BPF_COEFF2627, 0x0a000345); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf2350708); cx25840_write4(client, DIF_BPF_COEFF3031, 0x09b2f104); cx25840_write4(client, DIF_BPF_COEFF3233, 0x01050eff); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf3baf9be); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 15600000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000003); cx25840_write4(client, DIF_BPF_COEFF23, 0xfff9fffb); cx25840_write4(client, DIF_BPF_COEFF45, 0x0022ffe6); cx25840_write4(client, DIF_BPF_COEFF67, 0xffc9007a); cx25840_write4(client, DIF_BPF_COEFF89, 0xfff0ff29); cx25840_write4(client, DIF_BPF_COEFF1011, 0x00f2007e); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe01011b); cx25840_write4(client, DIF_BPF_COEFF1415, 0x01f6fc9e); cx25840_write4(client, DIF_BPF_COEFF1617, 0x00440467); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfbccfdde); cx25840_write4(client, DIF_BPF_COEFF2021, 0x0738fc90); cx25840_write4(client, DIF_BPF_COEFF2223, 0xf9f70934); cx25840_write4(client, DIF_BPF_COEFF2425, 0xff99f582); cx25840_write4(client, DIF_BPF_COEFF2627, 0x090204b0); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf21a05e1); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0a8df15a); cx25840_write4(client, DIF_BPF_COEFF3233, 0x00340f41); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf405f98b); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 15700000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000003); cx25840_write4(client, DIF_BPF_COEFF23, 0xfffcfff4); cx25840_write4(client, DIF_BPF_COEFF45, 0x0020fffa); cx25840_write4(client, DIF_BPF_COEFF67, 0xffb40064); cx25840_write4(client, DIF_BPF_COEFF89, 0x002fff11); cx25840_write4(client, DIF_BPF_COEFF1011, 0x00a400f0); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe0d006e); cx25840_write4(client, DIF_BPF_COEFF1415, 0x0281fd09); cx25840_write4(client, DIF_BPF_COEFF1617, 0xff3604c9); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfcbffca2); cx25840_write4(client, DIF_BPF_COEFF2021, 0x0726fdfe); cx25840_write4(client, DIF_BPF_COEFF2223, 0xf8e80888); cx25840_write4(client, DIF_BPF_COEFF2425, 0x0134f4f3); cx25840_write4(client, DIF_BPF_COEFF2627, 0x07e1060c); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf22304af); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0b59f1be); cx25840_write4(client, DIF_BPF_COEFF3233, 0xff640f7d); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf452f959); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 15800000: cx25840_write4(client, DIF_BPF_COEFF01, 0x00000003); cx25840_write4(client, DIF_BPF_COEFF23, 0x0000fff0); cx25840_write4(client, DIF_BPF_COEFF45, 0x001a0010); cx25840_write4(client, DIF_BPF_COEFF67, 0xffaa0041); cx25840_write4(client, DIF_BPF_COEFF89, 0x0067ff13); cx25840_write4(client, DIF_BPF_COEFF1011, 0x0043014a); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfe46ffb9); cx25840_write4(client, DIF_BPF_COEFF1415, 0x02dbfda8); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfe3504e5); cx25840_write4(client, DIF_BPF_COEFF1819, 0xfddcfb8d); cx25840_write4(client, DIF_BPF_COEFF2021, 0x06c9ff7e); cx25840_write4(client, DIF_BPF_COEFF2223, 0xf81107a2); cx25840_write4(client, DIF_BPF_COEFF2425, 0x02c9f49a); cx25840_write4(client, DIF_BPF_COEFF2627, 0x069f0753); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf2500373); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0c14f231); cx25840_write4(client, DIF_BPF_COEFF3233, 0xfe930fb3); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf4a1f927); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 15900000: cx25840_write4(client, DIF_BPF_COEFF01, 0xffff0002); cx25840_write4(client, DIF_BPF_COEFF23, 0x0003ffee); cx25840_write4(client, DIF_BPF_COEFF45, 0x000f0023); cx25840_write4(client, DIF_BPF_COEFF67, 0xffac0016); cx25840_write4(client, DIF_BPF_COEFF89, 0x0093ff31); cx25840_write4(client, DIF_BPF_COEFF1011, 0xffdc0184); cx25840_write4(client, DIF_BPF_COEFF1213, 0xfea6ff09); cx25840_write4(client, DIF_BPF_COEFF1415, 0x02fdfe70); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfd5104ba); cx25840_write4(client, DIF_BPF_COEFF1819, 0xff15faac); cx25840_write4(client, DIF_BPF_COEFF2021, 0x06270103); cx25840_write4(client, DIF_BPF_COEFF2223, 0xf7780688); cx25840_write4(client, DIF_BPF_COEFF2425, 0x044df479); cx25840_write4(client, DIF_BPF_COEFF2627, 0x05430883); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf2a00231); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0cbef2b2); cx25840_write4(client, DIF_BPF_COEFF3233, 0xfdc40fe3); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf4f2f8f5); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; case 16000000: cx25840_write4(client, DIF_BPF_COEFF01, 0xffff0001); cx25840_write4(client, DIF_BPF_COEFF23, 0x0006ffef); cx25840_write4(client, DIF_BPF_COEFF45, 0x00020031); cx25840_write4(client, DIF_BPF_COEFF67, 0xffbaffe8); cx25840_write4(client, DIF_BPF_COEFF89, 0x00adff66); cx25840_write4(client, DIF_BPF_COEFF1011, 0xff790198); cx25840_write4(client, DIF_BPF_COEFF1213, 0xff26fe6e); cx25840_write4(client, DIF_BPF_COEFF1415, 0x02e5ff55); cx25840_write4(client, DIF_BPF_COEFF1617, 0xfc99044a); cx25840_write4(client, DIF_BPF_COEFF1819, 0x005bfa09); cx25840_write4(client, DIF_BPF_COEFF2021, 0x0545027f); cx25840_write4(client, DIF_BPF_COEFF2223, 0xf7230541); cx25840_write4(client, DIF_BPF_COEFF2425, 0x05b8f490); cx25840_write4(client, DIF_BPF_COEFF2627, 0x03d20997); cx25840_write4(client, DIF_BPF_COEFF2829, 0xf31300eb); cx25840_write4(client, DIF_BPF_COEFF3031, 0x0d55f341); cx25840_write4(client, DIF_BPF_COEFF3233, 0xfcf6100e); cx25840_write4(client, DIF_BPF_COEFF3435, 0xf544f8c3); cx25840_write4(client, DIF_BPF_COEFF36, 0x110d0000); break; } } static void cx23888_std_setup(struct i2c_client *client) { struct cx25840_state *state = to_state(i2c_get_clientdata(client)); v4l2_std_id std = state->std; u32 ifHz; cx25840_write4(client, 0x478, 0x6628021F); cx25840_write4(client, 0x400, 0x0); cx25840_write4(client, 0x4b4, 0x20524030); cx25840_write4(client, 0x47c, 0x010a8263); if (std & V4L2_STD_525_60) { v4l_dbg(1, cx25840_debug, client, "%s() Selecting NTSC", __func__); /* Horiz / vert timing */ cx25840_write4(client, 0x428, 0x1e1e601a); cx25840_write4(client, 0x424, 0x5b2d007a); /* DIF NTSC */ cx25840_write4(client, 0x304, 0x6503bc0c); cx25840_write4(client, 0x308, 0xbd038c85); cx25840_write4(client, 0x30c, 0x1db4640a); cx25840_write4(client, 0x310, 0x00008800); cx25840_write4(client, 0x314, 0x44400400); cx25840_write4(client, 0x32c, 0x0c800800); cx25840_write4(client, 0x330, 0x27000100); cx25840_write4(client, 0x334, 0x1f296e1f); cx25840_write4(client, 0x338, 0x009f50c1); cx25840_write4(client, 0x340, 0x1befbf06); cx25840_write4(client, 0x344, 0x000035e8); /* DIF I/F */ ifHz = 5400000; } else { v4l_dbg(1, cx25840_debug, client, "%s() Selecting PAL-BG", __func__); /* Horiz / vert timing */ cx25840_write4(client, 0x428, 0x28244024); cx25840_write4(client, 0x424, 0x5d2d0084); /* DIF */ cx25840_write4(client, 0x304, 0x6503bc0c); cx25840_write4(client, 0x308, 0xbd038c85); cx25840_write4(client, 0x30c, 0x1db4640a); cx25840_write4(client, 0x310, 0x00008800); cx25840_write4(client, 0x314, 0x44400600); cx25840_write4(client, 0x32c, 0x0c800800); cx25840_write4(client, 0x330, 0x27000100); cx25840_write4(client, 0x334, 0x213530ec); cx25840_write4(client, 0x338, 0x00a65ba8); cx25840_write4(client, 0x340, 0x1befbf06); cx25840_write4(client, 0x344, 0x000035e8); /* DIF I/F */ ifHz = 6000000; } cx23885_dif_setup(client, ifHz); /* Explicitly ensure the inputs are reconfigured after * a standard change. */ set_input(client, state->vid_input, state->aud_input); } /* ----------------------------------------------------------------------- */ static const struct v4l2_ctrl_ops cx25840_ctrl_ops = { .s_ctrl = cx25840_s_ctrl, }; static const struct v4l2_subdev_core_ops cx25840_core_ops = { .log_status = cx25840_log_status, .reset = cx25840_reset, /* calling the (optional) init op will turn on the generic mode */ .init = cx25840_init, .load_fw = cx25840_load_fw, .s_io_pin_config = common_s_io_pin_config, #ifdef CONFIG_VIDEO_ADV_DEBUG .g_register = cx25840_g_register, .s_register = cx25840_s_register, #endif .interrupt_service_routine = cx25840_irq_handler, }; static const struct v4l2_subdev_tuner_ops cx25840_tuner_ops = { .s_frequency = cx25840_s_frequency, .s_radio = cx25840_s_radio, .g_tuner = cx25840_g_tuner, .s_tuner = cx25840_s_tuner, }; static const struct v4l2_subdev_audio_ops cx25840_audio_ops = { .s_clock_freq = cx25840_s_clock_freq, .s_routing = cx25840_s_audio_routing, .s_stream = cx25840_s_audio_stream, }; static const struct v4l2_subdev_video_ops cx25840_video_ops = { .g_std = cx25840_g_std, .s_std = cx25840_s_std, .querystd = cx25840_querystd, .s_routing = cx25840_s_video_routing, .s_stream = cx25840_s_stream, .g_input_status = cx25840_g_input_status, }; static const struct v4l2_subdev_vbi_ops cx25840_vbi_ops = { .decode_vbi_line = cx25840_decode_vbi_line, .s_raw_fmt = cx25840_s_raw_fmt, .s_sliced_fmt = cx25840_s_sliced_fmt, .g_sliced_fmt = cx25840_g_sliced_fmt, }; static const struct v4l2_subdev_pad_ops cx25840_pad_ops = { .set_fmt = cx25840_set_fmt, }; static const struct v4l2_subdev_ops cx25840_ops = { .core = &cx25840_core_ops, .tuner = &cx25840_tuner_ops, .audio = &cx25840_audio_ops, .video = &cx25840_video_ops, .vbi = &cx25840_vbi_ops, .pad = &cx25840_pad_ops, .ir = &cx25840_ir_ops, }; /* ----------------------------------------------------------------------- */ static u32 get_cx2388x_ident(struct i2c_client *client) { u32 ret; /* Come out of digital power down */ cx25840_write(client, 0x000, 0); /* * Detecting whether the part is cx23885/7/8 is more * difficult than it needs to be. No ID register. Instead we * probe certain registers indicated in the datasheets to look * for specific defaults that differ between the silicon designs. */ /* It's either 885/7 if the IR Tx Clk Divider register exists */ if (cx25840_read4(client, 0x204) & 0xffff) { /* * CX23885 returns bogus repetitive byte values for the DIF, * which doesn't exist for it. (Ex. 8a8a8a8a or 31313131) */ ret = cx25840_read4(client, 0x300); if (((ret & 0xffff0000) >> 16) == (ret & 0xffff)) { /* No DIF */ ret = CX23885_AV; } else { /* * CX23887 has a broken DIF, but the registers * appear valid (but unused), good enough to detect. */ ret = CX23887_AV; } } else if (cx25840_read4(client, 0x300) & 0x0fffffff) { /* DIF PLL Freq Word reg exists; chip must be a CX23888 */ ret = CX23888_AV; } else { v4l_err(client, "Unable to detect h/w, assuming cx23887\n"); ret = CX23887_AV; } /* Back into digital power down */ cx25840_write(client, 0x000, 2); return ret; } static int cx25840_probe(struct i2c_client *client) { struct cx25840_state *state; struct v4l2_subdev *sd; int default_volume; u32 id; u16 device_id; #if defined(CONFIG_MEDIA_CONTROLLER) int ret; #endif /* Check if the adapter supports the needed features */ if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE_DATA)) return -EIO; v4l_dbg(1, cx25840_debug, client, "detecting cx25840 client on address 0x%x\n", client->addr << 1); device_id = cx25840_read(client, 0x101) << 8; device_id |= cx25840_read(client, 0x100); v4l_dbg(1, cx25840_debug, client, "device_id = 0x%04x\n", device_id); /* * The high byte of the device ID should be * 0x83 for the cx2583x and 0x84 for the cx2584x */ if ((device_id & 0xff00) == 0x8300) { id = CX25836 + ((device_id >> 4) & 0xf) - 6; } else if ((device_id & 0xff00) == 0x8400) { id = CX25840 + ((device_id >> 4) & 0xf); } else if (device_id == 0x0000) { id = get_cx2388x_ident(client); } else if ((device_id & 0xfff0) == 0x5A30) { /* The CX23100 (0x5A3C = 23100) doesn't have an A/V decoder */ id = CX2310X_AV; } else if ((device_id & 0xff) == (device_id >> 8)) { v4l_err(client, "likely a confused/unresponsive cx2388[578] A/V decoder found @ 0x%x (%s)\n", client->addr << 1, client->adapter->name); v4l_err(client, "A method to reset it from the cx25840 driver software is not known at this time\n"); return -ENODEV; } else { v4l_dbg(1, cx25840_debug, client, "cx25840 not found\n"); return -ENODEV; } state = devm_kzalloc(&client->dev, sizeof(*state), GFP_KERNEL); if (!state) return -ENOMEM; sd = &state->sd; v4l2_i2c_subdev_init(sd, client, &cx25840_ops); #if defined(CONFIG_MEDIA_CONTROLLER) /* * TODO: add media controller support for analog video inputs like * composite, svideo, etc. * A real input pad for this analog demod would be like: * ___________ * TUNER --------> | | * | | * SVIDEO .......> | cx25840 | * | | * COMPOSITE1 ...> |_________| * * However, at least for now, there's no much gain on modelling * those extra inputs. So, let's add it only when needed. */ state->pads[CX25840_PAD_INPUT].flags = MEDIA_PAD_FL_SINK; state->pads[CX25840_PAD_INPUT].sig_type = PAD_SIGNAL_ANALOG; state->pads[CX25840_PAD_VID_OUT].flags = MEDIA_PAD_FL_SOURCE; state->pads[CX25840_PAD_VID_OUT].sig_type = PAD_SIGNAL_DV; sd->entity.function = MEDIA_ENT_F_ATV_DECODER; ret = media_entity_pads_init(&sd->entity, ARRAY_SIZE(state->pads), state->pads); if (ret < 0) { v4l_info(client, "failed to initialize media entity!\n"); return ret; } #endif switch (id) { case CX23885_AV: v4l_info(client, "cx23885 A/V decoder found @ 0x%x (%s)\n", client->addr << 1, client->adapter->name); break; case CX23887_AV: v4l_info(client, "cx23887 A/V decoder found @ 0x%x (%s)\n", client->addr << 1, client->adapter->name); break; case CX23888_AV: v4l_info(client, "cx23888 A/V decoder found @ 0x%x (%s)\n", client->addr << 1, client->adapter->name); break; case CX2310X_AV: v4l_info(client, "cx%d A/V decoder found @ 0x%x (%s)\n", device_id, client->addr << 1, client->adapter->name); break; case CX25840: case CX25841: case CX25842: case CX25843: /* * Note: revision '(device_id & 0x0f) == 2' was never built. * The marking skips from 0x1 == 22 to 0x3 == 23. */ v4l_info(client, "cx25%3x-2%x found @ 0x%x (%s)\n", (device_id & 0xfff0) >> 4, (device_id & 0x0f) < 3 ? (device_id & 0x0f) + 1 : (device_id & 0x0f), client->addr << 1, client->adapter->name); break; case CX25836: case CX25837: default: v4l_info(client, "cx25%3x-%x found @ 0x%x (%s)\n", (device_id & 0xfff0) >> 4, device_id & 0x0f, client->addr << 1, client->adapter->name); break; } state->c = client; state->vid_input = CX25840_COMPOSITE7; state->aud_input = CX25840_AUDIO8; state->audclk_freq = 48000; state->audmode = V4L2_TUNER_MODE_LANG1; state->vbi_line_offset = 8; state->id = id; state->rev = device_id; state->vbi_regs_offset = id == CX23888_AV ? 0x500 - 0x424 : 0; state->std = V4L2_STD_NTSC_M; v4l2_ctrl_handler_init(&state->hdl, 9); v4l2_ctrl_new_std(&state->hdl, &cx25840_ctrl_ops, V4L2_CID_BRIGHTNESS, 0, 255, 1, 128); v4l2_ctrl_new_std(&state->hdl, &cx25840_ctrl_ops, V4L2_CID_CONTRAST, 0, 127, 1, 64); v4l2_ctrl_new_std(&state->hdl, &cx25840_ctrl_ops, V4L2_CID_SATURATION, 0, 127, 1, 64); v4l2_ctrl_new_std(&state->hdl, &cx25840_ctrl_ops, V4L2_CID_HUE, -128, 127, 1, 0); if (!is_cx2583x(state)) { default_volume = cx25840_read(client, 0x8d4); /* * Enforce the legacy PVR-350/MSP3400 to PVR-150/CX25843 volume * scale mapping limits to avoid -ERANGE errors when * initializing the volume control */ if (default_volume > 228) { /* Bottom out at -96 dB, v4l2 vol range 0x2e00-0x2fff */ default_volume = 228; cx25840_write(client, 0x8d4, 228); } else if (default_volume < 20) { /* Top out at + 8 dB, v4l2 vol range 0xfe00-0xffff */ default_volume = 20; cx25840_write(client, 0x8d4, 20); } default_volume = (((228 - default_volume) >> 1) + 23) << 9; state->volume = v4l2_ctrl_new_std(&state->hdl, &cx25840_audio_ctrl_ops, V4L2_CID_AUDIO_VOLUME, 0, 65535, 65535 / 100, default_volume); state->mute = v4l2_ctrl_new_std(&state->hdl, &cx25840_audio_ctrl_ops, V4L2_CID_AUDIO_MUTE, 0, 1, 1, 0); v4l2_ctrl_new_std(&state->hdl, &cx25840_audio_ctrl_ops, V4L2_CID_AUDIO_BALANCE, 0, 65535, 65535 / 100, 32768); v4l2_ctrl_new_std(&state->hdl, &cx25840_audio_ctrl_ops, V4L2_CID_AUDIO_BASS, 0, 65535, 65535 / 100, 32768); v4l2_ctrl_new_std(&state->hdl, &cx25840_audio_ctrl_ops, V4L2_CID_AUDIO_TREBLE, 0, 65535, 65535 / 100, 32768); } sd->ctrl_handler = &state->hdl; if (state->hdl.error) { int err = state->hdl.error; v4l2_ctrl_handler_free(&state->hdl); return err; } if (!is_cx2583x(state)) v4l2_ctrl_cluster(2, &state->volume); v4l2_ctrl_handler_setup(&state->hdl); if (client->dev.platform_data) { struct cx25840_platform_data *pdata = client->dev.platform_data; state->pvr150_workaround = pdata->pvr150_workaround; } cx25840_ir_probe(sd); return 0; } static void cx25840_remove(struct i2c_client *client) { struct v4l2_subdev *sd = i2c_get_clientdata(client); struct cx25840_state *state = to_state(sd); cx25840_ir_remove(sd); v4l2_device_unregister_subdev(sd); v4l2_ctrl_handler_free(&state->hdl); } static const struct i2c_device_id cx25840_id[] = { { "cx25840", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, cx25840_id); static struct i2c_driver cx25840_driver = { .driver = { .name = "cx25840", }, .probe = cx25840_probe, .remove = cx25840_remove, .id_table = cx25840_id, }; module_i2c_driver(cx25840_driver);
linux-master
drivers/media/i2c/cx25840/cx25840-core.c
// SPDX-License-Identifier: GPL-2.0-or-later /* cx25840 firmware functions */ #include <linux/module.h> #include <linux/i2c.h> #include <linux/firmware.h> #include <media/v4l2-common.h> #include <media/drv-intf/cx25840.h> #include "cx25840-core.h" /* * Mike Isely <[email protected]> - The FWSEND parameter controls the * size of the firmware chunks sent down the I2C bus to the chip. * Previously this had been set to 1024 but unfortunately some I2C * implementations can't transfer data in such big gulps. * Specifically, the pvrusb2 driver has a hard limit of around 60 * bytes, due to the encapsulation there of I2C traffic into USB * messages. So we have to significantly reduce this parameter. */ #define FWSEND 48 #define FWDEV(x) &((x)->dev) static char *firmware = ""; module_param(firmware, charp, 0444); MODULE_PARM_DESC(firmware, "Firmware image to load"); static void start_fw_load(struct i2c_client *client) { /* DL_ADDR_LB=0 DL_ADDR_HB=0 */ cx25840_write(client, 0x800, 0x00); cx25840_write(client, 0x801, 0x00); // DL_MAP=3 DL_AUTO_INC=0 DL_ENABLE=1 cx25840_write(client, 0x803, 0x0b); /* AUTO_INC_DIS=1 */ cx25840_write(client, 0x000, 0x20); } static void end_fw_load(struct i2c_client *client) { /* AUTO_INC_DIS=0 */ cx25840_write(client, 0x000, 0x00); /* DL_ENABLE=0 */ cx25840_write(client, 0x803, 0x03); } #define CX2388x_FIRMWARE "v4l-cx23885-avcore-01.fw" #define CX231xx_FIRMWARE "v4l-cx231xx-avcore-01.fw" #define CX25840_FIRMWARE "v4l-cx25840.fw" static const char *get_fw_name(struct i2c_client *client) { struct cx25840_state *state = to_state(i2c_get_clientdata(client)); if (firmware[0]) return firmware; if (is_cx2388x(state)) return CX2388x_FIRMWARE; if (is_cx231xx(state)) return CX231xx_FIRMWARE; return CX25840_FIRMWARE; } static int check_fw_load(struct i2c_client *client, int size) { /* DL_ADDR_HB DL_ADDR_LB */ int s = cx25840_read(client, 0x801) << 8; s |= cx25840_read(client, 0x800); if (size != s) { v4l_err(client, "firmware %s load failed\n", get_fw_name(client)); return -EINVAL; } v4l_info(client, "loaded %s firmware (%d bytes)\n", get_fw_name(client), size); return 0; } static int fw_write(struct i2c_client *client, const u8 *data, int size) { if (i2c_master_send(client, data, size) < size) { v4l_err(client, "firmware load i2c failure\n"); return -ENOSYS; } return 0; } int cx25840_loadfw(struct i2c_client *client) { struct cx25840_state *state = to_state(i2c_get_clientdata(client)); const struct firmware *fw = NULL; u8 buffer[FWSEND]; const u8 *ptr; const char *fwname = get_fw_name(client); int size, retval; int max_buf_size = FWSEND; u32 gpio_oe = 0, gpio_da = 0; if (is_cx2388x(state)) { /* Preserve the GPIO OE and output bits */ gpio_oe = cx25840_read(client, 0x160); gpio_da = cx25840_read(client, 0x164); } /* cx231xx cannot accept more than 16 bytes at a time */ if (is_cx231xx(state) && max_buf_size > 16) max_buf_size = 16; if (request_firmware(&fw, fwname, FWDEV(client)) != 0) { v4l_err(client, "unable to open firmware %s\n", fwname); return -EINVAL; } start_fw_load(client); buffer[0] = 0x08; buffer[1] = 0x02; size = fw->size; ptr = fw->data; while (size > 0) { int len = min(max_buf_size - 2, size); memcpy(buffer + 2, ptr, len); retval = fw_write(client, buffer, len + 2); if (retval < 0) { release_firmware(fw); return retval; } size -= len; ptr += len; } end_fw_load(client); size = fw->size; release_firmware(fw); if (is_cx2388x(state)) { /* Restore GPIO configuration after f/w load */ cx25840_write(client, 0x160, gpio_oe); cx25840_write(client, 0x164, gpio_da); } return check_fw_load(client, size); } MODULE_FIRMWARE(CX2388x_FIRMWARE); MODULE_FIRMWARE(CX231xx_FIRMWARE); MODULE_FIRMWARE(CX25840_FIRMWARE);
linux-master
drivers/media/i2c/cx25840/cx25840-firmware.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Driver for the Conexant CX2584x Audio/Video decoder chip and related cores * * Integrated Consumer Infrared Controller * * Copyright (C) 2010 Andy Walls <[email protected]> */ #include <linux/slab.h> #include <linux/kfifo.h> #include <linux/module.h> #include <media/drv-intf/cx25840.h> #include <media/rc-core.h> #include "cx25840-core.h" static unsigned int ir_debug; module_param(ir_debug, int, 0644); MODULE_PARM_DESC(ir_debug, "enable integrated IR debug messages"); #define CX25840_IR_REG_BASE 0x200 #define CX25840_IR_CNTRL_REG 0x200 #define CNTRL_WIN_3_3 0x00000000 #define CNTRL_WIN_4_3 0x00000001 #define CNTRL_WIN_3_4 0x00000002 #define CNTRL_WIN_4_4 0x00000003 #define CNTRL_WIN 0x00000003 #define CNTRL_EDG_NONE 0x00000000 #define CNTRL_EDG_FALL 0x00000004 #define CNTRL_EDG_RISE 0x00000008 #define CNTRL_EDG_BOTH 0x0000000C #define CNTRL_EDG 0x0000000C #define CNTRL_DMD 0x00000010 #define CNTRL_MOD 0x00000020 #define CNTRL_RFE 0x00000040 #define CNTRL_TFE 0x00000080 #define CNTRL_RXE 0x00000100 #define CNTRL_TXE 0x00000200 #define CNTRL_RIC 0x00000400 #define CNTRL_TIC 0x00000800 #define CNTRL_CPL 0x00001000 #define CNTRL_LBM 0x00002000 #define CNTRL_R 0x00004000 #define CX25840_IR_TXCLK_REG 0x204 #define TXCLK_TCD 0x0000FFFF #define CX25840_IR_RXCLK_REG 0x208 #define RXCLK_RCD 0x0000FFFF #define CX25840_IR_CDUTY_REG 0x20C #define CDUTY_CDC 0x0000000F #define CX25840_IR_STATS_REG 0x210 #define STATS_RTO 0x00000001 #define STATS_ROR 0x00000002 #define STATS_RBY 0x00000004 #define STATS_TBY 0x00000008 #define STATS_RSR 0x00000010 #define STATS_TSR 0x00000020 #define CX25840_IR_IRQEN_REG 0x214 #define IRQEN_RTE 0x00000001 #define IRQEN_ROE 0x00000002 #define IRQEN_RSE 0x00000010 #define IRQEN_TSE 0x00000020 #define IRQEN_MSK 0x00000033 #define CX25840_IR_FILTR_REG 0x218 #define FILTR_LPF 0x0000FFFF #define CX25840_IR_FIFO_REG 0x23C #define FIFO_RXTX 0x0000FFFF #define FIFO_RXTX_LVL 0x00010000 #define FIFO_RXTX_RTO 0x0001FFFF #define FIFO_RX_NDV 0x00020000 #define FIFO_RX_DEPTH 8 #define FIFO_TX_DEPTH 8 #define CX25840_VIDCLK_FREQ 108000000 /* 108 MHz, BT.656 */ #define CX25840_IR_REFCLK_FREQ (CX25840_VIDCLK_FREQ / 2) /* * We use this union internally for convenience, but callers to tx_write * and rx_read will be expecting records of type struct ir_raw_event. * Always ensure the size of this union is dictated by struct ir_raw_event. */ union cx25840_ir_fifo_rec { u32 hw_fifo_data; struct ir_raw_event ir_core_data; }; #define CX25840_IR_RX_KFIFO_SIZE (256 * sizeof(union cx25840_ir_fifo_rec)) #define CX25840_IR_TX_KFIFO_SIZE (256 * sizeof(union cx25840_ir_fifo_rec)) struct cx25840_ir_state { struct i2c_client *c; struct v4l2_subdev_ir_parameters rx_params; struct mutex rx_params_lock; /* protects Rx parameter settings cache */ atomic_t rxclk_divider; atomic_t rx_invert; struct kfifo rx_kfifo; spinlock_t rx_kfifo_lock; /* protect Rx data kfifo */ struct v4l2_subdev_ir_parameters tx_params; struct mutex tx_params_lock; /* protects Tx parameter settings cache */ atomic_t txclk_divider; }; static inline struct cx25840_ir_state *to_ir_state(struct v4l2_subdev *sd) { struct cx25840_state *state = to_state(sd); return state ? state->ir_state : NULL; } /* * Rx and Tx Clock Divider register computations * * Note the largest clock divider value of 0xffff corresponds to: * (0xffff + 1) * 1000 / 108/2 MHz = 1,213,629.629... ns * which fits in 21 bits, so we'll use unsigned int for time arguments. */ static inline u16 count_to_clock_divider(unsigned int d) { if (d > RXCLK_RCD + 1) d = RXCLK_RCD; else if (d < 2) d = 1; else d--; return (u16) d; } static inline u16 carrier_freq_to_clock_divider(unsigned int freq) { return count_to_clock_divider( DIV_ROUND_CLOSEST(CX25840_IR_REFCLK_FREQ, freq * 16)); } static inline unsigned int clock_divider_to_carrier_freq(unsigned int divider) { return DIV_ROUND_CLOSEST(CX25840_IR_REFCLK_FREQ, (divider + 1) * 16); } static inline unsigned int clock_divider_to_freq(unsigned int divider, unsigned int rollovers) { return DIV_ROUND_CLOSEST(CX25840_IR_REFCLK_FREQ, (divider + 1) * rollovers); } /* * Low Pass Filter register calculations * * Note the largest count value of 0xffff corresponds to: * 0xffff * 1000 / 108/2 MHz = 1,213,611.11... ns * which fits in 21 bits, so we'll use unsigned int for time arguments. */ static inline u16 count_to_lpf_count(unsigned int d) { if (d > FILTR_LPF) d = FILTR_LPF; else if (d < 4) d = 0; return (u16) d; } static inline u16 ns_to_lpf_count(unsigned int ns) { return count_to_lpf_count( DIV_ROUND_CLOSEST(CX25840_IR_REFCLK_FREQ / 1000000 * ns, 1000)); } static inline unsigned int lpf_count_to_ns(unsigned int count) { /* Duration of the Low Pass Filter rejection window in ns */ return DIV_ROUND_CLOSEST(count * 1000, CX25840_IR_REFCLK_FREQ / 1000000); } static inline unsigned int lpf_count_to_us(unsigned int count) { /* Duration of the Low Pass Filter rejection window in us */ return DIV_ROUND_CLOSEST(count, CX25840_IR_REFCLK_FREQ / 1000000); } /* * FIFO register pulse width count computations */ static u32 clock_divider_to_resolution(u16 divider) { /* * Resolution is the duration of 1 tick of the readable portion of * the pulse width counter as read from the FIFO. The two lsb's are * not readable, hence the << 2. This function returns ns. */ return DIV_ROUND_CLOSEST((1 << 2) * ((u32) divider + 1) * 1000, CX25840_IR_REFCLK_FREQ / 1000000); } static u64 pulse_width_count_to_ns(u16 count, u16 divider) { u64 n; u32 rem; /* * The 2 lsb's of the pulse width timer count are not readable, hence * the (count << 2) | 0x3 */ n = (((u64) count << 2) | 0x3) * (divider + 1) * 1000; /* millicycles */ rem = do_div(n, CX25840_IR_REFCLK_FREQ / 1000000); /* / MHz => ns */ if (rem >= CX25840_IR_REFCLK_FREQ / 1000000 / 2) n++; return n; } #if 0 /* Keep as we will need this for Transmit functionality */ static u16 ns_to_pulse_width_count(u32 ns, u16 divider) { u64 n; u32 d; u32 rem; /* * The 2 lsb's of the pulse width timer count are not accessible, hence * the (1 << 2) */ n = ((u64) ns) * CX25840_IR_REFCLK_FREQ / 1000000; /* millicycles */ d = (1 << 2) * ((u32) divider + 1) * 1000; /* millicycles/count */ rem = do_div(n, d); if (rem >= d / 2) n++; if (n > FIFO_RXTX) n = FIFO_RXTX; else if (n == 0) n = 1; return (u16) n; } #endif static unsigned int pulse_width_count_to_us(u16 count, u16 divider) { u64 n; u32 rem; /* * The 2 lsb's of the pulse width timer count are not readable, hence * the (count << 2) | 0x3 */ n = (((u64) count << 2) | 0x3) * (divider + 1); /* cycles */ rem = do_div(n, CX25840_IR_REFCLK_FREQ / 1000000); /* / MHz => us */ if (rem >= CX25840_IR_REFCLK_FREQ / 1000000 / 2) n++; return (unsigned int) n; } /* * Pulse Clocks computations: Combined Pulse Width Count & Rx Clock Counts * * The total pulse clock count is an 18 bit pulse width timer count as the most * significant part and (up to) 16 bit clock divider count as a modulus. * When the Rx clock divider ticks down to 0, it increments the 18 bit pulse * width timer count's least significant bit. */ static u64 ns_to_pulse_clocks(u32 ns) { u64 clocks; u32 rem; clocks = CX25840_IR_REFCLK_FREQ / 1000000 * (u64) ns; /* millicycles */ rem = do_div(clocks, 1000); /* /1000 = cycles */ if (rem >= 1000 / 2) clocks++; return clocks; } static u16 pulse_clocks_to_clock_divider(u64 count) { do_div(count, (FIFO_RXTX << 2) | 0x3); /* net result needs to be rounded down and decremented by 1 */ if (count > RXCLK_RCD + 1) count = RXCLK_RCD; else if (count < 2) count = 1; else count--; return (u16) count; } /* * IR Control Register helpers */ enum tx_fifo_watermark { TX_FIFO_HALF_EMPTY = 0, TX_FIFO_EMPTY = CNTRL_TIC, }; enum rx_fifo_watermark { RX_FIFO_HALF_FULL = 0, RX_FIFO_NOT_EMPTY = CNTRL_RIC, }; static inline void control_tx_irq_watermark(struct i2c_client *c, enum tx_fifo_watermark level) { cx25840_and_or4(c, CX25840_IR_CNTRL_REG, ~CNTRL_TIC, level); } static inline void control_rx_irq_watermark(struct i2c_client *c, enum rx_fifo_watermark level) { cx25840_and_or4(c, CX25840_IR_CNTRL_REG, ~CNTRL_RIC, level); } static inline void control_tx_enable(struct i2c_client *c, bool enable) { cx25840_and_or4(c, CX25840_IR_CNTRL_REG, ~(CNTRL_TXE | CNTRL_TFE), enable ? (CNTRL_TXE | CNTRL_TFE) : 0); } static inline void control_rx_enable(struct i2c_client *c, bool enable) { cx25840_and_or4(c, CX25840_IR_CNTRL_REG, ~(CNTRL_RXE | CNTRL_RFE), enable ? (CNTRL_RXE | CNTRL_RFE) : 0); } static inline void control_tx_modulation_enable(struct i2c_client *c, bool enable) { cx25840_and_or4(c, CX25840_IR_CNTRL_REG, ~CNTRL_MOD, enable ? CNTRL_MOD : 0); } static inline void control_rx_demodulation_enable(struct i2c_client *c, bool enable) { cx25840_and_or4(c, CX25840_IR_CNTRL_REG, ~CNTRL_DMD, enable ? CNTRL_DMD : 0); } static inline void control_rx_s_edge_detection(struct i2c_client *c, u32 edge_types) { cx25840_and_or4(c, CX25840_IR_CNTRL_REG, ~CNTRL_EDG_BOTH, edge_types & CNTRL_EDG_BOTH); } static void control_rx_s_carrier_window(struct i2c_client *c, unsigned int carrier, unsigned int *carrier_range_low, unsigned int *carrier_range_high) { u32 v; unsigned int c16 = carrier * 16; if (*carrier_range_low < DIV_ROUND_CLOSEST(c16, 16 + 3)) { v = CNTRL_WIN_3_4; *carrier_range_low = DIV_ROUND_CLOSEST(c16, 16 + 4); } else { v = CNTRL_WIN_3_3; *carrier_range_low = DIV_ROUND_CLOSEST(c16, 16 + 3); } if (*carrier_range_high > DIV_ROUND_CLOSEST(c16, 16 - 3)) { v |= CNTRL_WIN_4_3; *carrier_range_high = DIV_ROUND_CLOSEST(c16, 16 - 4); } else { v |= CNTRL_WIN_3_3; *carrier_range_high = DIV_ROUND_CLOSEST(c16, 16 - 3); } cx25840_and_or4(c, CX25840_IR_CNTRL_REG, ~CNTRL_WIN, v); } static inline void control_tx_polarity_invert(struct i2c_client *c, bool invert) { cx25840_and_or4(c, CX25840_IR_CNTRL_REG, ~CNTRL_CPL, invert ? CNTRL_CPL : 0); } /* * IR Rx & Tx Clock Register helpers */ static unsigned int txclk_tx_s_carrier(struct i2c_client *c, unsigned int freq, u16 *divider) { *divider = carrier_freq_to_clock_divider(freq); cx25840_write4(c, CX25840_IR_TXCLK_REG, *divider); return clock_divider_to_carrier_freq(*divider); } static unsigned int rxclk_rx_s_carrier(struct i2c_client *c, unsigned int freq, u16 *divider) { *divider = carrier_freq_to_clock_divider(freq); cx25840_write4(c, CX25840_IR_RXCLK_REG, *divider); return clock_divider_to_carrier_freq(*divider); } static u32 txclk_tx_s_max_pulse_width(struct i2c_client *c, u32 ns, u16 *divider) { u64 pulse_clocks; if (ns > IR_MAX_DURATION) ns = IR_MAX_DURATION; pulse_clocks = ns_to_pulse_clocks(ns); *divider = pulse_clocks_to_clock_divider(pulse_clocks); cx25840_write4(c, CX25840_IR_TXCLK_REG, *divider); return (u32) pulse_width_count_to_ns(FIFO_RXTX, *divider); } static u32 rxclk_rx_s_max_pulse_width(struct i2c_client *c, u32 ns, u16 *divider) { u64 pulse_clocks; if (ns > IR_MAX_DURATION) ns = IR_MAX_DURATION; pulse_clocks = ns_to_pulse_clocks(ns); *divider = pulse_clocks_to_clock_divider(pulse_clocks); cx25840_write4(c, CX25840_IR_RXCLK_REG, *divider); return (u32) pulse_width_count_to_ns(FIFO_RXTX, *divider); } /* * IR Tx Carrier Duty Cycle register helpers */ static unsigned int cduty_tx_s_duty_cycle(struct i2c_client *c, unsigned int duty_cycle) { u32 n; n = DIV_ROUND_CLOSEST(duty_cycle * 100, 625); /* 16ths of 100% */ if (n != 0) n--; if (n > 15) n = 15; cx25840_write4(c, CX25840_IR_CDUTY_REG, n); return DIV_ROUND_CLOSEST((n + 1) * 100, 16); } /* * IR Filter Register helpers */ static u32 filter_rx_s_min_width(struct i2c_client *c, u32 min_width_ns) { u32 count = ns_to_lpf_count(min_width_ns); cx25840_write4(c, CX25840_IR_FILTR_REG, count); return lpf_count_to_ns(count); } /* * IR IRQ Enable Register helpers */ static inline void irqenable_rx(struct v4l2_subdev *sd, u32 mask) { struct cx25840_state *state = to_state(sd); if (is_cx23885(state) || is_cx23887(state)) mask ^= IRQEN_MSK; mask &= (IRQEN_RTE | IRQEN_ROE | IRQEN_RSE); cx25840_and_or4(state->c, CX25840_IR_IRQEN_REG, ~(IRQEN_RTE | IRQEN_ROE | IRQEN_RSE), mask); } static inline void irqenable_tx(struct v4l2_subdev *sd, u32 mask) { struct cx25840_state *state = to_state(sd); if (is_cx23885(state) || is_cx23887(state)) mask ^= IRQEN_MSK; mask &= IRQEN_TSE; cx25840_and_or4(state->c, CX25840_IR_IRQEN_REG, ~IRQEN_TSE, mask); } /* * V4L2 Subdevice IR Ops */ int cx25840_ir_irq_handler(struct v4l2_subdev *sd, u32 status, bool *handled) { struct cx25840_state *state = to_state(sd); struct cx25840_ir_state *ir_state = to_ir_state(sd); struct i2c_client *c = NULL; unsigned long flags; union cx25840_ir_fifo_rec rx_data[FIFO_RX_DEPTH]; unsigned int i, j, k; u32 events, v; int tsr, rsr, rto, ror, tse, rse, rte, roe, kror; u32 cntrl, irqen, stats; *handled = false; if (ir_state == NULL) return -ENODEV; c = ir_state->c; /* Only support the IR controller for the CX2388[57] AV Core for now */ if (!(is_cx23885(state) || is_cx23887(state))) return -ENODEV; cntrl = cx25840_read4(c, CX25840_IR_CNTRL_REG); irqen = cx25840_read4(c, CX25840_IR_IRQEN_REG); if (is_cx23885(state) || is_cx23887(state)) irqen ^= IRQEN_MSK; stats = cx25840_read4(c, CX25840_IR_STATS_REG); tsr = stats & STATS_TSR; /* Tx FIFO Service Request */ rsr = stats & STATS_RSR; /* Rx FIFO Service Request */ rto = stats & STATS_RTO; /* Rx Pulse Width Timer Time Out */ ror = stats & STATS_ROR; /* Rx FIFO Over Run */ tse = irqen & IRQEN_TSE; /* Tx FIFO Service Request IRQ Enable */ rse = irqen & IRQEN_RSE; /* Rx FIFO Service Request IRQ Enable */ rte = irqen & IRQEN_RTE; /* Rx Pulse Width Timer Time Out IRQ Enable */ roe = irqen & IRQEN_ROE; /* Rx FIFO Over Run IRQ Enable */ v4l2_dbg(2, ir_debug, sd, "IR IRQ Status: %s %s %s %s %s %s\n", tsr ? "tsr" : " ", rsr ? "rsr" : " ", rto ? "rto" : " ", ror ? "ror" : " ", stats & STATS_TBY ? "tby" : " ", stats & STATS_RBY ? "rby" : " "); v4l2_dbg(2, ir_debug, sd, "IR IRQ Enables: %s %s %s %s\n", tse ? "tse" : " ", rse ? "rse" : " ", rte ? "rte" : " ", roe ? "roe" : " "); /* * Transmitter interrupt service */ if (tse && tsr) { /* * TODO: * Check the watermark threshold setting * Pull FIFO_TX_DEPTH or FIFO_TX_DEPTH/2 entries from tx_kfifo * Push the data to the hardware FIFO. * If there was nothing more to send in the tx_kfifo, disable * the TSR IRQ and notify the v4l2_device. * If there was something in the tx_kfifo, check the tx_kfifo * level and notify the v4l2_device, if it is low. */ /* For now, inhibit TSR interrupt until Tx is implemented */ irqenable_tx(sd, 0); events = V4L2_SUBDEV_IR_TX_FIFO_SERVICE_REQ; v4l2_subdev_notify(sd, V4L2_SUBDEV_IR_TX_NOTIFY, &events); *handled = true; } /* * Receiver interrupt service */ kror = 0; if ((rse && rsr) || (rte && rto)) { /* * Receive data on RSR to clear the STATS_RSR. * Receive data on RTO, since we may not have yet hit the RSR * watermark when we receive the RTO. */ for (i = 0, v = FIFO_RX_NDV; (v & FIFO_RX_NDV) && !kror; i = 0) { for (j = 0; (v & FIFO_RX_NDV) && j < FIFO_RX_DEPTH; j++) { v = cx25840_read4(c, CX25840_IR_FIFO_REG); rx_data[i].hw_fifo_data = v & ~FIFO_RX_NDV; i++; } if (i == 0) break; j = i * sizeof(union cx25840_ir_fifo_rec); k = kfifo_in_locked(&ir_state->rx_kfifo, (unsigned char *) rx_data, j, &ir_state->rx_kfifo_lock); if (k != j) kror++; /* rx_kfifo over run */ } *handled = true; } events = 0; v = 0; if (kror) { events |= V4L2_SUBDEV_IR_RX_SW_FIFO_OVERRUN; v4l2_err(sd, "IR receiver software FIFO overrun\n"); } if (roe && ror) { /* * The RX FIFO Enable (CNTRL_RFE) must be toggled to clear * the Rx FIFO Over Run status (STATS_ROR) */ v |= CNTRL_RFE; events |= V4L2_SUBDEV_IR_RX_HW_FIFO_OVERRUN; v4l2_err(sd, "IR receiver hardware FIFO overrun\n"); } if (rte && rto) { /* * The IR Receiver Enable (CNTRL_RXE) must be toggled to clear * the Rx Pulse Width Timer Time Out (STATS_RTO) */ v |= CNTRL_RXE; events |= V4L2_SUBDEV_IR_RX_END_OF_RX_DETECTED; } if (v) { /* Clear STATS_ROR & STATS_RTO as needed by resetting hardware */ cx25840_write4(c, CX25840_IR_CNTRL_REG, cntrl & ~v); cx25840_write4(c, CX25840_IR_CNTRL_REG, cntrl); *handled = true; } spin_lock_irqsave(&ir_state->rx_kfifo_lock, flags); if (kfifo_len(&ir_state->rx_kfifo) >= CX25840_IR_RX_KFIFO_SIZE / 2) events |= V4L2_SUBDEV_IR_RX_FIFO_SERVICE_REQ; spin_unlock_irqrestore(&ir_state->rx_kfifo_lock, flags); if (events) v4l2_subdev_notify(sd, V4L2_SUBDEV_IR_RX_NOTIFY, &events); return 0; } /* Receiver */ static int cx25840_ir_rx_read(struct v4l2_subdev *sd, u8 *buf, size_t count, ssize_t *num) { struct cx25840_ir_state *ir_state = to_ir_state(sd); bool invert; u16 divider; unsigned int i, n; union cx25840_ir_fifo_rec *p; unsigned u, v, w; if (ir_state == NULL) return -ENODEV; invert = (bool) atomic_read(&ir_state->rx_invert); divider = (u16) atomic_read(&ir_state->rxclk_divider); n = count / sizeof(union cx25840_ir_fifo_rec) * sizeof(union cx25840_ir_fifo_rec); if (n == 0) { *num = 0; return 0; } n = kfifo_out_locked(&ir_state->rx_kfifo, buf, n, &ir_state->rx_kfifo_lock); n /= sizeof(union cx25840_ir_fifo_rec); *num = n * sizeof(union cx25840_ir_fifo_rec); for (p = (union cx25840_ir_fifo_rec *) buf, i = 0; i < n; p++, i++) { if ((p->hw_fifo_data & FIFO_RXTX_RTO) == FIFO_RXTX_RTO) { /* Assume RTO was because of no IR light input */ u = 0; w = 1; } else { u = (p->hw_fifo_data & FIFO_RXTX_LVL) ? 1 : 0; if (invert) u = u ? 0 : 1; w = 0; } v = (unsigned) pulse_width_count_to_ns( (u16)(p->hw_fifo_data & FIFO_RXTX), divider) / 1000; if (v > IR_MAX_DURATION) v = IR_MAX_DURATION; p->ir_core_data = (struct ir_raw_event) { .pulse = u, .duration = v, .timeout = w }; v4l2_dbg(2, ir_debug, sd, "rx read: %10u ns %s %s\n", v, u ? "mark" : "space", w ? "(timed out)" : ""); if (w) v4l2_dbg(2, ir_debug, sd, "rx read: end of rx\n"); } return 0; } static int cx25840_ir_rx_g_parameters(struct v4l2_subdev *sd, struct v4l2_subdev_ir_parameters *p) { struct cx25840_ir_state *ir_state = to_ir_state(sd); if (ir_state == NULL) return -ENODEV; mutex_lock(&ir_state->rx_params_lock); memcpy(p, &ir_state->rx_params, sizeof(struct v4l2_subdev_ir_parameters)); mutex_unlock(&ir_state->rx_params_lock); return 0; } static int cx25840_ir_rx_shutdown(struct v4l2_subdev *sd) { struct cx25840_ir_state *ir_state = to_ir_state(sd); struct i2c_client *c; if (ir_state == NULL) return -ENODEV; c = ir_state->c; mutex_lock(&ir_state->rx_params_lock); /* Disable or slow down all IR Rx circuits and counters */ irqenable_rx(sd, 0); control_rx_enable(c, false); control_rx_demodulation_enable(c, false); control_rx_s_edge_detection(c, CNTRL_EDG_NONE); filter_rx_s_min_width(c, 0); cx25840_write4(c, CX25840_IR_RXCLK_REG, RXCLK_RCD); ir_state->rx_params.shutdown = true; mutex_unlock(&ir_state->rx_params_lock); return 0; } static int cx25840_ir_rx_s_parameters(struct v4l2_subdev *sd, struct v4l2_subdev_ir_parameters *p) { struct cx25840_ir_state *ir_state = to_ir_state(sd); struct i2c_client *c; struct v4l2_subdev_ir_parameters *o; u16 rxclk_divider; if (ir_state == NULL) return -ENODEV; if (p->shutdown) return cx25840_ir_rx_shutdown(sd); if (p->mode != V4L2_SUBDEV_IR_MODE_PULSE_WIDTH) return -ENOSYS; c = ir_state->c; o = &ir_state->rx_params; mutex_lock(&ir_state->rx_params_lock); o->shutdown = p->shutdown; p->mode = V4L2_SUBDEV_IR_MODE_PULSE_WIDTH; o->mode = p->mode; p->bytes_per_data_element = sizeof(union cx25840_ir_fifo_rec); o->bytes_per_data_element = p->bytes_per_data_element; /* Before we tweak the hardware, we have to disable the receiver */ irqenable_rx(sd, 0); control_rx_enable(c, false); control_rx_demodulation_enable(c, p->modulation); o->modulation = p->modulation; if (p->modulation) { p->carrier_freq = rxclk_rx_s_carrier(c, p->carrier_freq, &rxclk_divider); o->carrier_freq = p->carrier_freq; p->duty_cycle = 50; o->duty_cycle = p->duty_cycle; control_rx_s_carrier_window(c, p->carrier_freq, &p->carrier_range_lower, &p->carrier_range_upper); o->carrier_range_lower = p->carrier_range_lower; o->carrier_range_upper = p->carrier_range_upper; p->max_pulse_width = (u32) pulse_width_count_to_ns(FIFO_RXTX, rxclk_divider); } else { p->max_pulse_width = rxclk_rx_s_max_pulse_width(c, p->max_pulse_width, &rxclk_divider); } o->max_pulse_width = p->max_pulse_width; atomic_set(&ir_state->rxclk_divider, rxclk_divider); p->noise_filter_min_width = filter_rx_s_min_width(c, p->noise_filter_min_width); o->noise_filter_min_width = p->noise_filter_min_width; p->resolution = clock_divider_to_resolution(rxclk_divider); o->resolution = p->resolution; /* FIXME - make this dependent on resolution for better performance */ control_rx_irq_watermark(c, RX_FIFO_HALF_FULL); control_rx_s_edge_detection(c, CNTRL_EDG_BOTH); o->invert_level = p->invert_level; atomic_set(&ir_state->rx_invert, p->invert_level); o->interrupt_enable = p->interrupt_enable; o->enable = p->enable; if (p->enable) { unsigned long flags; spin_lock_irqsave(&ir_state->rx_kfifo_lock, flags); kfifo_reset(&ir_state->rx_kfifo); spin_unlock_irqrestore(&ir_state->rx_kfifo_lock, flags); if (p->interrupt_enable) irqenable_rx(sd, IRQEN_RSE | IRQEN_RTE | IRQEN_ROE); control_rx_enable(c, p->enable); } mutex_unlock(&ir_state->rx_params_lock); return 0; } /* Transmitter */ static int cx25840_ir_tx_write(struct v4l2_subdev *sd, u8 *buf, size_t count, ssize_t *num) { struct cx25840_ir_state *ir_state = to_ir_state(sd); if (ir_state == NULL) return -ENODEV; #if 0 /* * FIXME - the code below is an incomplete and untested sketch of what * may need to be done. The critical part is to get 4 (or 8) pulses * from the tx_kfifo, or converted from ns to the proper units from the * input, and push them off to the hardware Tx FIFO right away, if the * HW TX fifo needs service. The rest can be pushed to the tx_kfifo in * a less critical timeframe. Also watch out for overruning the * tx_kfifo - don't let it happen and let the caller know not all his * pulses were written. */ u32 *ns_pulse = (u32 *) buf; unsigned int n; u32 fifo_pulse[FIFO_TX_DEPTH]; u32 mark; /* Compute how much we can fit in the tx kfifo */ n = CX25840_IR_TX_KFIFO_SIZE - kfifo_len(ir_state->tx_kfifo); n = min(n, (unsigned int) count); n /= sizeof(u32); /* FIXME - turn on Tx Fifo service interrupt * check hardware fifo level, and other stuff */ for (i = 0; i < n; ) { for (j = 0; j < FIFO_TX_DEPTH / 2 && i < n; j++) { mark = ns_pulse[i] & LEVEL_MASK; fifo_pulse[j] = ns_to_pulse_width_count( ns_pulse[i] & ~LEVEL_MASK, ir_state->txclk_divider); if (mark) fifo_pulse[j] &= FIFO_RXTX_LVL; i++; } kfifo_put(ir_state->tx_kfifo, (u8 *) fifo_pulse, j * sizeof(u32)); } *num = n * sizeof(u32); #else /* For now enable the Tx FIFO Service interrupt & pretend we did work */ irqenable_tx(sd, IRQEN_TSE); *num = count; #endif return 0; } static int cx25840_ir_tx_g_parameters(struct v4l2_subdev *sd, struct v4l2_subdev_ir_parameters *p) { struct cx25840_ir_state *ir_state = to_ir_state(sd); if (ir_state == NULL) return -ENODEV; mutex_lock(&ir_state->tx_params_lock); memcpy(p, &ir_state->tx_params, sizeof(struct v4l2_subdev_ir_parameters)); mutex_unlock(&ir_state->tx_params_lock); return 0; } static int cx25840_ir_tx_shutdown(struct v4l2_subdev *sd) { struct cx25840_ir_state *ir_state = to_ir_state(sd); struct i2c_client *c; if (ir_state == NULL) return -ENODEV; c = ir_state->c; mutex_lock(&ir_state->tx_params_lock); /* Disable or slow down all IR Tx circuits and counters */ irqenable_tx(sd, 0); control_tx_enable(c, false); control_tx_modulation_enable(c, false); cx25840_write4(c, CX25840_IR_TXCLK_REG, TXCLK_TCD); ir_state->tx_params.shutdown = true; mutex_unlock(&ir_state->tx_params_lock); return 0; } static int cx25840_ir_tx_s_parameters(struct v4l2_subdev *sd, struct v4l2_subdev_ir_parameters *p) { struct cx25840_ir_state *ir_state = to_ir_state(sd); struct i2c_client *c; struct v4l2_subdev_ir_parameters *o; u16 txclk_divider; if (ir_state == NULL) return -ENODEV; if (p->shutdown) return cx25840_ir_tx_shutdown(sd); if (p->mode != V4L2_SUBDEV_IR_MODE_PULSE_WIDTH) return -ENOSYS; c = ir_state->c; o = &ir_state->tx_params; mutex_lock(&ir_state->tx_params_lock); o->shutdown = p->shutdown; p->mode = V4L2_SUBDEV_IR_MODE_PULSE_WIDTH; o->mode = p->mode; p->bytes_per_data_element = sizeof(union cx25840_ir_fifo_rec); o->bytes_per_data_element = p->bytes_per_data_element; /* Before we tweak the hardware, we have to disable the transmitter */ irqenable_tx(sd, 0); control_tx_enable(c, false); control_tx_modulation_enable(c, p->modulation); o->modulation = p->modulation; if (p->modulation) { p->carrier_freq = txclk_tx_s_carrier(c, p->carrier_freq, &txclk_divider); o->carrier_freq = p->carrier_freq; p->duty_cycle = cduty_tx_s_duty_cycle(c, p->duty_cycle); o->duty_cycle = p->duty_cycle; p->max_pulse_width = (u32) pulse_width_count_to_ns(FIFO_RXTX, txclk_divider); } else { p->max_pulse_width = txclk_tx_s_max_pulse_width(c, p->max_pulse_width, &txclk_divider); } o->max_pulse_width = p->max_pulse_width; atomic_set(&ir_state->txclk_divider, txclk_divider); p->resolution = clock_divider_to_resolution(txclk_divider); o->resolution = p->resolution; /* FIXME - make this dependent on resolution for better performance */ control_tx_irq_watermark(c, TX_FIFO_HALF_EMPTY); control_tx_polarity_invert(c, p->invert_carrier_sense); o->invert_carrier_sense = p->invert_carrier_sense; /* * FIXME: we don't have hardware help for IO pin level inversion * here like we have on the CX23888. * Act on this with some mix of logical inversion of data levels, * carrier polarity, and carrier duty cycle. */ o->invert_level = p->invert_level; o->interrupt_enable = p->interrupt_enable; o->enable = p->enable; if (p->enable) { /* reset tx_fifo here */ if (p->interrupt_enable) irqenable_tx(sd, IRQEN_TSE); control_tx_enable(c, p->enable); } mutex_unlock(&ir_state->tx_params_lock); return 0; } /* * V4L2 Subdevice Core Ops support */ int cx25840_ir_log_status(struct v4l2_subdev *sd) { struct cx25840_state *state = to_state(sd); struct i2c_client *c = state->c; char *s; int i, j; u32 cntrl, txclk, rxclk, cduty, stats, irqen, filtr; /* The CX23888 chip doesn't have an IR controller on the A/V core */ if (is_cx23888(state)) return 0; cntrl = cx25840_read4(c, CX25840_IR_CNTRL_REG); txclk = cx25840_read4(c, CX25840_IR_TXCLK_REG) & TXCLK_TCD; rxclk = cx25840_read4(c, CX25840_IR_RXCLK_REG) & RXCLK_RCD; cduty = cx25840_read4(c, CX25840_IR_CDUTY_REG) & CDUTY_CDC; stats = cx25840_read4(c, CX25840_IR_STATS_REG); irqen = cx25840_read4(c, CX25840_IR_IRQEN_REG); if (is_cx23885(state) || is_cx23887(state)) irqen ^= IRQEN_MSK; filtr = cx25840_read4(c, CX25840_IR_FILTR_REG) & FILTR_LPF; v4l2_info(sd, "IR Receiver:\n"); v4l2_info(sd, "\tEnabled: %s\n", cntrl & CNTRL_RXE ? "yes" : "no"); v4l2_info(sd, "\tDemodulation from a carrier: %s\n", cntrl & CNTRL_DMD ? "enabled" : "disabled"); v4l2_info(sd, "\tFIFO: %s\n", cntrl & CNTRL_RFE ? "enabled" : "disabled"); switch (cntrl & CNTRL_EDG) { case CNTRL_EDG_NONE: s = "disabled"; break; case CNTRL_EDG_FALL: s = "falling edge"; break; case CNTRL_EDG_RISE: s = "rising edge"; break; case CNTRL_EDG_BOTH: s = "rising & falling edges"; break; default: s = "??? edge"; break; } v4l2_info(sd, "\tPulse timers' start/stop trigger: %s\n", s); v4l2_info(sd, "\tFIFO data on pulse timer overflow: %s\n", cntrl & CNTRL_R ? "not loaded" : "overflow marker"); v4l2_info(sd, "\tFIFO interrupt watermark: %s\n", cntrl & CNTRL_RIC ? "not empty" : "half full or greater"); v4l2_info(sd, "\tLoopback mode: %s\n", cntrl & CNTRL_LBM ? "loopback active" : "normal receive"); if (cntrl & CNTRL_DMD) { v4l2_info(sd, "\tExpected carrier (16 clocks): %u Hz\n", clock_divider_to_carrier_freq(rxclk)); switch (cntrl & CNTRL_WIN) { case CNTRL_WIN_3_3: i = 3; j = 3; break; case CNTRL_WIN_4_3: i = 4; j = 3; break; case CNTRL_WIN_3_4: i = 3; j = 4; break; case CNTRL_WIN_4_4: i = 4; j = 4; break; default: i = 0; j = 0; break; } v4l2_info(sd, "\tNext carrier edge window: 16 clocks -%1d/+%1d, %u to %u Hz\n", i, j, clock_divider_to_freq(rxclk, 16 + j), clock_divider_to_freq(rxclk, 16 - i)); } v4l2_info(sd, "\tMax measurable pulse width: %u us, %llu ns\n", pulse_width_count_to_us(FIFO_RXTX, rxclk), pulse_width_count_to_ns(FIFO_RXTX, rxclk)); v4l2_info(sd, "\tLow pass filter: %s\n", filtr ? "enabled" : "disabled"); if (filtr) v4l2_info(sd, "\tMin acceptable pulse width (LPF): %u us, %u ns\n", lpf_count_to_us(filtr), lpf_count_to_ns(filtr)); v4l2_info(sd, "\tPulse width timer timed-out: %s\n", stats & STATS_RTO ? "yes" : "no"); v4l2_info(sd, "\tPulse width timer time-out intr: %s\n", irqen & IRQEN_RTE ? "enabled" : "disabled"); v4l2_info(sd, "\tFIFO overrun: %s\n", stats & STATS_ROR ? "yes" : "no"); v4l2_info(sd, "\tFIFO overrun interrupt: %s\n", irqen & IRQEN_ROE ? "enabled" : "disabled"); v4l2_info(sd, "\tBusy: %s\n", stats & STATS_RBY ? "yes" : "no"); v4l2_info(sd, "\tFIFO service requested: %s\n", stats & STATS_RSR ? "yes" : "no"); v4l2_info(sd, "\tFIFO service request interrupt: %s\n", irqen & IRQEN_RSE ? "enabled" : "disabled"); v4l2_info(sd, "IR Transmitter:\n"); v4l2_info(sd, "\tEnabled: %s\n", cntrl & CNTRL_TXE ? "yes" : "no"); v4l2_info(sd, "\tModulation onto a carrier: %s\n", cntrl & CNTRL_MOD ? "enabled" : "disabled"); v4l2_info(sd, "\tFIFO: %s\n", cntrl & CNTRL_TFE ? "enabled" : "disabled"); v4l2_info(sd, "\tFIFO interrupt watermark: %s\n", cntrl & CNTRL_TIC ? "not empty" : "half full or less"); v4l2_info(sd, "\tCarrier polarity: %s\n", cntrl & CNTRL_CPL ? "space:burst mark:noburst" : "space:noburst mark:burst"); if (cntrl & CNTRL_MOD) { v4l2_info(sd, "\tCarrier (16 clocks): %u Hz\n", clock_divider_to_carrier_freq(txclk)); v4l2_info(sd, "\tCarrier duty cycle: %2u/16\n", cduty + 1); } v4l2_info(sd, "\tMax pulse width: %u us, %llu ns\n", pulse_width_count_to_us(FIFO_RXTX, txclk), pulse_width_count_to_ns(FIFO_RXTX, txclk)); v4l2_info(sd, "\tBusy: %s\n", stats & STATS_TBY ? "yes" : "no"); v4l2_info(sd, "\tFIFO service requested: %s\n", stats & STATS_TSR ? "yes" : "no"); v4l2_info(sd, "\tFIFO service request interrupt: %s\n", irqen & IRQEN_TSE ? "enabled" : "disabled"); return 0; } const struct v4l2_subdev_ir_ops cx25840_ir_ops = { .rx_read = cx25840_ir_rx_read, .rx_g_parameters = cx25840_ir_rx_g_parameters, .rx_s_parameters = cx25840_ir_rx_s_parameters, .tx_write = cx25840_ir_tx_write, .tx_g_parameters = cx25840_ir_tx_g_parameters, .tx_s_parameters = cx25840_ir_tx_s_parameters, }; static const struct v4l2_subdev_ir_parameters default_rx_params = { .bytes_per_data_element = sizeof(union cx25840_ir_fifo_rec), .mode = V4L2_SUBDEV_IR_MODE_PULSE_WIDTH, .enable = false, .interrupt_enable = false, .shutdown = true, .modulation = true, .carrier_freq = 36000, /* 36 kHz - RC-5, and RC-6 carrier */ /* RC-5: 666,667 ns = 1/36 kHz * 32 cycles * 1 mark * 0.75 */ /* RC-6: 333,333 ns = 1/36 kHz * 16 cycles * 1 mark * 0.75 */ .noise_filter_min_width = 333333, /* ns */ .carrier_range_lower = 35000, .carrier_range_upper = 37000, .invert_level = false, }; static const struct v4l2_subdev_ir_parameters default_tx_params = { .bytes_per_data_element = sizeof(union cx25840_ir_fifo_rec), .mode = V4L2_SUBDEV_IR_MODE_PULSE_WIDTH, .enable = false, .interrupt_enable = false, .shutdown = true, .modulation = true, .carrier_freq = 36000, /* 36 kHz - RC-5 carrier */ .duty_cycle = 25, /* 25 % - RC-5 carrier */ .invert_level = false, .invert_carrier_sense = false, }; int cx25840_ir_probe(struct v4l2_subdev *sd) { struct cx25840_state *state = to_state(sd); struct cx25840_ir_state *ir_state; struct v4l2_subdev_ir_parameters default_params; /* Only init the IR controller for the CX2388[57] AV Core for now */ if (!(is_cx23885(state) || is_cx23887(state))) return 0; ir_state = devm_kzalloc(&state->c->dev, sizeof(*ir_state), GFP_KERNEL); if (ir_state == NULL) return -ENOMEM; spin_lock_init(&ir_state->rx_kfifo_lock); if (kfifo_alloc(&ir_state->rx_kfifo, CX25840_IR_RX_KFIFO_SIZE, GFP_KERNEL)) return -ENOMEM; ir_state->c = state->c; state->ir_state = ir_state; /* Ensure no interrupts arrive yet */ if (is_cx23885(state) || is_cx23887(state)) cx25840_write4(ir_state->c, CX25840_IR_IRQEN_REG, IRQEN_MSK); else cx25840_write4(ir_state->c, CX25840_IR_IRQEN_REG, 0); mutex_init(&ir_state->rx_params_lock); default_params = default_rx_params; v4l2_subdev_call(sd, ir, rx_s_parameters, &default_params); mutex_init(&ir_state->tx_params_lock); default_params = default_tx_params; v4l2_subdev_call(sd, ir, tx_s_parameters, &default_params); return 0; } int cx25840_ir_remove(struct v4l2_subdev *sd) { struct cx25840_state *state = to_state(sd); struct cx25840_ir_state *ir_state = to_ir_state(sd); if (ir_state == NULL) return -ENODEV; cx25840_ir_rx_shutdown(sd); cx25840_ir_tx_shutdown(sd); kfifo_free(&ir_state->rx_kfifo); state->ir_state = NULL; return 0; }
linux-master
drivers/media/i2c/cx25840/cx25840-ir.c
// SPDX-License-Identifier: GPL-2.0-or-later /* cx25840 VBI functions */ #include <linux/videodev2.h> #include <linux/i2c.h> #include <media/v4l2-common.h> #include <media/drv-intf/cx25840.h> #include "cx25840-core.h" static int odd_parity(u8 c) { c ^= (c >> 4); c ^= (c >> 2); c ^= (c >> 1); return c & 1; } static int decode_vps(u8 * dst, u8 * p) { static const u8 biphase_tbl[] = { 0xf0, 0x78, 0x70, 0xf0, 0xb4, 0x3c, 0x34, 0xb4, 0xb0, 0x38, 0x30, 0xb0, 0xf0, 0x78, 0x70, 0xf0, 0xd2, 0x5a, 0x52, 0xd2, 0x96, 0x1e, 0x16, 0x96, 0x92, 0x1a, 0x12, 0x92, 0xd2, 0x5a, 0x52, 0xd2, 0xd0, 0x58, 0x50, 0xd0, 0x94, 0x1c, 0x14, 0x94, 0x90, 0x18, 0x10, 0x90, 0xd0, 0x58, 0x50, 0xd0, 0xf0, 0x78, 0x70, 0xf0, 0xb4, 0x3c, 0x34, 0xb4, 0xb0, 0x38, 0x30, 0xb0, 0xf0, 0x78, 0x70, 0xf0, 0xe1, 0x69, 0x61, 0xe1, 0xa5, 0x2d, 0x25, 0xa5, 0xa1, 0x29, 0x21, 0xa1, 0xe1, 0x69, 0x61, 0xe1, 0xc3, 0x4b, 0x43, 0xc3, 0x87, 0x0f, 0x07, 0x87, 0x83, 0x0b, 0x03, 0x83, 0xc3, 0x4b, 0x43, 0xc3, 0xc1, 0x49, 0x41, 0xc1, 0x85, 0x0d, 0x05, 0x85, 0x81, 0x09, 0x01, 0x81, 0xc1, 0x49, 0x41, 0xc1, 0xe1, 0x69, 0x61, 0xe1, 0xa5, 0x2d, 0x25, 0xa5, 0xa1, 0x29, 0x21, 0xa1, 0xe1, 0x69, 0x61, 0xe1, 0xe0, 0x68, 0x60, 0xe0, 0xa4, 0x2c, 0x24, 0xa4, 0xa0, 0x28, 0x20, 0xa0, 0xe0, 0x68, 0x60, 0xe0, 0xc2, 0x4a, 0x42, 0xc2, 0x86, 0x0e, 0x06, 0x86, 0x82, 0x0a, 0x02, 0x82, 0xc2, 0x4a, 0x42, 0xc2, 0xc0, 0x48, 0x40, 0xc0, 0x84, 0x0c, 0x04, 0x84, 0x80, 0x08, 0x00, 0x80, 0xc0, 0x48, 0x40, 0xc0, 0xe0, 0x68, 0x60, 0xe0, 0xa4, 0x2c, 0x24, 0xa4, 0xa0, 0x28, 0x20, 0xa0, 0xe0, 0x68, 0x60, 0xe0, 0xf0, 0x78, 0x70, 0xf0, 0xb4, 0x3c, 0x34, 0xb4, 0xb0, 0x38, 0x30, 0xb0, 0xf0, 0x78, 0x70, 0xf0, 0xd2, 0x5a, 0x52, 0xd2, 0x96, 0x1e, 0x16, 0x96, 0x92, 0x1a, 0x12, 0x92, 0xd2, 0x5a, 0x52, 0xd2, 0xd0, 0x58, 0x50, 0xd0, 0x94, 0x1c, 0x14, 0x94, 0x90, 0x18, 0x10, 0x90, 0xd0, 0x58, 0x50, 0xd0, 0xf0, 0x78, 0x70, 0xf0, 0xb4, 0x3c, 0x34, 0xb4, 0xb0, 0x38, 0x30, 0xb0, 0xf0, 0x78, 0x70, 0xf0, }; u8 c, err = 0; int i; for (i = 0; i < 2 * 13; i += 2) { err |= biphase_tbl[p[i]] | biphase_tbl[p[i + 1]]; c = (biphase_tbl[p[i + 1]] & 0xf) | ((biphase_tbl[p[i]] & 0xf) << 4); dst[i / 2] = c; } return err & 0xf0; } int cx25840_g_sliced_fmt(struct v4l2_subdev *sd, struct v4l2_sliced_vbi_format *svbi) { struct i2c_client *client = v4l2_get_subdevdata(sd); struct cx25840_state *state = to_state(sd); static const u16 lcr2vbi[] = { 0, V4L2_SLICED_TELETEXT_B, 0, /* 1 */ 0, V4L2_SLICED_WSS_625, 0, /* 4 */ V4L2_SLICED_CAPTION_525, /* 6 */ 0, 0, V4L2_SLICED_VPS, 0, 0, /* 9 */ 0, 0, 0, 0 }; int is_pal = !(state->std & V4L2_STD_525_60); int i; memset(svbi->service_lines, 0, sizeof(svbi->service_lines)); svbi->service_set = 0; /* we're done if raw VBI is active */ /* TODO: this will have to be changed for generic_mode VBI */ if ((cx25840_read(client, 0x404) & 0x10) == 0) return 0; if (is_pal) { for (i = 7; i <= 23; i++) { u8 v = cx25840_read(client, state->vbi_regs_offset + 0x424 + i - 7); svbi->service_lines[0][i] = lcr2vbi[v >> 4]; svbi->service_lines[1][i] = lcr2vbi[v & 0xf]; svbi->service_set |= svbi->service_lines[0][i] | svbi->service_lines[1][i]; } } else { for (i = 10; i <= 21; i++) { u8 v = cx25840_read(client, state->vbi_regs_offset + 0x424 + i - 10); svbi->service_lines[0][i] = lcr2vbi[v >> 4]; svbi->service_lines[1][i] = lcr2vbi[v & 0xf]; svbi->service_set |= svbi->service_lines[0][i] | svbi->service_lines[1][i]; } } return 0; } int cx25840_s_raw_fmt(struct v4l2_subdev *sd, struct v4l2_vbi_format *fmt) { struct i2c_client *client = v4l2_get_subdevdata(sd); struct cx25840_state *state = to_state(sd); int is_pal = !(state->std & V4L2_STD_525_60); int vbi_offset = is_pal ? 1 : 0; /* Setup standard */ cx25840_std_setup(client); /* VBI Offset */ if (is_cx23888(state)) cx25840_write(client, 0x54f, vbi_offset); else cx25840_write(client, 0x47f, vbi_offset); /* TODO: this will have to be changed for generic_mode VBI */ cx25840_write(client, 0x404, 0x2e); return 0; } int cx25840_s_sliced_fmt(struct v4l2_subdev *sd, struct v4l2_sliced_vbi_format *svbi) { struct i2c_client *client = v4l2_get_subdevdata(sd); struct cx25840_state *state = to_state(sd); int is_pal = !(state->std & V4L2_STD_525_60); int vbi_offset = is_pal ? 1 : 0; int i, x; u8 lcr[24]; for (x = 0; x <= 23; x++) lcr[x] = 0x00; /* Setup standard */ cx25840_std_setup(client); /* Sliced VBI */ /* TODO: this will have to be changed for generic_mode VBI */ cx25840_write(client, 0x404, 0x32); /* Ancillary data */ cx25840_write(client, 0x406, 0x13); if (is_cx23888(state)) cx25840_write(client, 0x54f, vbi_offset); else cx25840_write(client, 0x47f, vbi_offset); if (is_pal) { for (i = 0; i <= 6; i++) svbi->service_lines[0][i] = svbi->service_lines[1][i] = 0; } else { for (i = 0; i <= 9; i++) svbi->service_lines[0][i] = svbi->service_lines[1][i] = 0; for (i = 22; i <= 23; i++) svbi->service_lines[0][i] = svbi->service_lines[1][i] = 0; } for (i = 7; i <= 23; i++) { for (x = 0; x <= 1; x++) { switch (svbi->service_lines[1-x][i]) { case V4L2_SLICED_TELETEXT_B: lcr[i] |= 1 << (4 * x); break; case V4L2_SLICED_WSS_625: lcr[i] |= 4 << (4 * x); break; case V4L2_SLICED_CAPTION_525: lcr[i] |= 6 << (4 * x); break; case V4L2_SLICED_VPS: lcr[i] |= 9 << (4 * x); break; } } } if (is_pal) { for (x = 1, i = state->vbi_regs_offset + 0x424; i <= state->vbi_regs_offset + 0x434; i++, x++) cx25840_write(client, i, lcr[6 + x]); } else { for (x = 1, i = state->vbi_regs_offset + 0x424; i <= state->vbi_regs_offset + 0x430; i++, x++) cx25840_write(client, i, lcr[9 + x]); for (i = state->vbi_regs_offset + 0x431; i <= state->vbi_regs_offset + 0x434; i++) cx25840_write(client, i, 0); } cx25840_write(client, state->vbi_regs_offset + 0x43c, 0x16); /* TODO: this will have to be changed for generic_mode VBI */ if (is_cx23888(state)) cx25840_write(client, 0x428, is_pal ? 0x2a : 0x22); else cx25840_write(client, 0x474, is_pal ? 0x2a : 0x22); return 0; } int cx25840_decode_vbi_line(struct v4l2_subdev *sd, struct v4l2_decode_vbi_line *vbi) { struct cx25840_state *state = to_state(sd); u8 *p = vbi->p; int id1, id2, l, err = 0; if (p[0] || p[1] != 0xff || p[2] != 0xff || (p[3] != 0x55 && p[3] != 0x91)) { vbi->line = vbi->type = 0; return 0; } p += 4; id1 = p[-1]; id2 = p[0] & 0xf; l = p[2] & 0x3f; l += state->vbi_line_offset; p += 4; switch (id2) { case 1: id2 = V4L2_SLICED_TELETEXT_B; break; case 4: id2 = V4L2_SLICED_WSS_625; break; case 6: id2 = V4L2_SLICED_CAPTION_525; err = !odd_parity(p[0]) || !odd_parity(p[1]); break; case 9: id2 = V4L2_SLICED_VPS; if (decode_vps(p, p) != 0) err = 1; break; default: id2 = 0; err = 1; break; } vbi->type = err ? 0 : id2; vbi->line = err ? 0 : l; vbi->is_second_field = err ? 0 : (id1 == 0x55); vbi->p = p; return 0; }
linux-master
drivers/media/i2c/cx25840/cx25840-vbi.c
// SPDX-License-Identifier: GPL-2.0-or-later /* cx25840 audio functions */ #include <linux/videodev2.h> #include <linux/i2c.h> #include <media/v4l2-common.h> #include <media/drv-intf/cx25840.h> #include "cx25840-core.h" /* * Note: The PLL and SRC parameters are based on a reference frequency that * would ideally be: * * NTSC Color subcarrier freq * 8 = 4.5 MHz/286 * 455/2 * 8 = 28.63636363... MHz * * However, it's not the exact reference frequency that matters, only that the * firmware and modules that comprise the driver for a particular board all * use the same value (close to the ideal value). * * Comments below will note which reference frequency is assumed for various * parameters. They will usually be one of * * ref_freq = 28.636360 MHz * or * ref_freq = 28.636363 MHz */ static int cx25840_set_audclk_freq(struct i2c_client *client, u32 freq) { struct cx25840_state *state = to_state(i2c_get_clientdata(client)); if (state->aud_input != CX25840_AUDIO_SERIAL) { switch (freq) { case 32000: /* * VID_PLL Integer = 0x0f, VID_PLL Post Divider = 0x04 * AUX_PLL Integer = 0x06, AUX PLL Post Divider = 0x10 */ cx25840_write4(client, 0x108, 0x1006040f); /* * VID_PLL Fraction (register 0x10c) = 0x2be2fe * 28636360 * 0xf.15f17f0/4 = 108 MHz * 432 MHz pre-postdivide */ /* * AUX_PLL Fraction = 0x1bb39ee * 28636363 * 0x6.dd9cf70/0x10 = 32000 * 384 * 196.6 MHz pre-postdivide * FIXME < 200 MHz is out of specified valid range * FIXME 28636363 ref_freq doesn't match VID PLL ref */ cx25840_write4(client, 0x110, 0x01bb39ee); /* * SA_MCLK_SEL = 1 * SA_MCLK_DIV = 0x10 = 384/384 * AUX_PLL post dvivider */ cx25840_write(client, 0x127, 0x50); if (is_cx2583x(state)) break; /* src3/4/6_ctl */ /* 0x1.f77f = (4 * 28636360/8 * 2/455) / 32000 */ cx25840_write4(client, 0x900, 0x0801f77f); cx25840_write4(client, 0x904, 0x0801f77f); cx25840_write4(client, 0x90c, 0x0801f77f); break; case 44100: /* * VID_PLL Integer = 0x0f, VID_PLL Post Divider = 0x04 * AUX_PLL Integer = 0x09, AUX PLL Post Divider = 0x10 */ cx25840_write4(client, 0x108, 0x1009040f); /* * VID_PLL Fraction (register 0x10c) = 0x2be2fe * 28636360 * 0xf.15f17f0/4 = 108 MHz * 432 MHz pre-postdivide */ /* * AUX_PLL Fraction = 0x0ec6bd6 * 28636363 * 0x9.7635eb0/0x10 = 44100 * 384 * 271 MHz pre-postdivide * FIXME 28636363 ref_freq doesn't match VID PLL ref */ cx25840_write4(client, 0x110, 0x00ec6bd6); /* * SA_MCLK_SEL = 1 * SA_MCLK_DIV = 0x10 = 384/384 * AUX_PLL post dvivider */ cx25840_write(client, 0x127, 0x50); if (is_cx2583x(state)) break; /* src3/4/6_ctl */ /* 0x1.6d59 = (4 * 28636360/8 * 2/455) / 44100 */ cx25840_write4(client, 0x900, 0x08016d59); cx25840_write4(client, 0x904, 0x08016d59); cx25840_write4(client, 0x90c, 0x08016d59); break; case 48000: /* * VID_PLL Integer = 0x0f, VID_PLL Post Divider = 0x04 * AUX_PLL Integer = 0x0a, AUX PLL Post Divider = 0x10 */ cx25840_write4(client, 0x108, 0x100a040f); /* * VID_PLL Fraction (register 0x10c) = 0x2be2fe * 28636360 * 0xf.15f17f0/4 = 108 MHz * 432 MHz pre-postdivide */ /* * AUX_PLL Fraction = 0x098d6e5 * 28636363 * 0xa.4c6b728/0x10 = 48000 * 384 * 295 MHz pre-postdivide * FIXME 28636363 ref_freq doesn't match VID PLL ref */ cx25840_write4(client, 0x110, 0x0098d6e5); /* * SA_MCLK_SEL = 1 * SA_MCLK_DIV = 0x10 = 384/384 * AUX_PLL post dvivider */ cx25840_write(client, 0x127, 0x50); if (is_cx2583x(state)) break; /* src3/4/6_ctl */ /* 0x1.4faa = (4 * 28636360/8 * 2/455) / 48000 */ cx25840_write4(client, 0x900, 0x08014faa); cx25840_write4(client, 0x904, 0x08014faa); cx25840_write4(client, 0x90c, 0x08014faa); break; } } else { switch (freq) { case 32000: /* * VID_PLL Integer = 0x0f, VID_PLL Post Divider = 0x04 * AUX_PLL Integer = 0x08, AUX PLL Post Divider = 0x1e */ cx25840_write4(client, 0x108, 0x1e08040f); /* * VID_PLL Fraction (register 0x10c) = 0x2be2fe * 28636360 * 0xf.15f17f0/4 = 108 MHz * 432 MHz pre-postdivide */ /* * AUX_PLL Fraction = 0x12a0869 * 28636363 * 0x8.9504348/0x1e = 32000 * 256 * 246 MHz pre-postdivide * FIXME 28636363 ref_freq doesn't match VID PLL ref */ cx25840_write4(client, 0x110, 0x012a0869); /* * SA_MCLK_SEL = 1 * SA_MCLK_DIV = 0x14 = 256/384 * AUX_PLL post dvivider */ cx25840_write(client, 0x127, 0x54); if (is_cx2583x(state)) break; /* src1_ctl */ /* 0x1.0000 = 32000/32000 */ cx25840_write4(client, 0x8f8, 0x08010000); /* src3/4/6_ctl */ /* 0x2.0000 = 2 * (32000/32000) */ cx25840_write4(client, 0x900, 0x08020000); cx25840_write4(client, 0x904, 0x08020000); cx25840_write4(client, 0x90c, 0x08020000); break; case 44100: /* * VID_PLL Integer = 0x0f, VID_PLL Post Divider = 0x04 * AUX_PLL Integer = 0x09, AUX PLL Post Divider = 0x18 */ cx25840_write4(client, 0x108, 0x1809040f); /* * VID_PLL Fraction (register 0x10c) = 0x2be2fe * 28636360 * 0xf.15f17f0/4 = 108 MHz * 432 MHz pre-postdivide */ /* * AUX_PLL Fraction = 0x0ec6bd6 * 28636363 * 0x9.7635eb0/0x18 = 44100 * 256 * 271 MHz pre-postdivide * FIXME 28636363 ref_freq doesn't match VID PLL ref */ cx25840_write4(client, 0x110, 0x00ec6bd6); /* * SA_MCLK_SEL = 1 * SA_MCLK_DIV = 0x10 = 256/384 * AUX_PLL post dvivider */ cx25840_write(client, 0x127, 0x50); if (is_cx2583x(state)) break; /* src1_ctl */ /* 0x1.60cd = 44100/32000 */ cx25840_write4(client, 0x8f8, 0x080160cd); /* src3/4/6_ctl */ /* 0x1.7385 = 2 * (32000/44100) */ cx25840_write4(client, 0x900, 0x08017385); cx25840_write4(client, 0x904, 0x08017385); cx25840_write4(client, 0x90c, 0x08017385); break; case 48000: /* * VID_PLL Integer = 0x0f, VID_PLL Post Divider = 0x04 * AUX_PLL Integer = 0x0a, AUX PLL Post Divider = 0x18 */ cx25840_write4(client, 0x108, 0x180a040f); /* * VID_PLL Fraction (register 0x10c) = 0x2be2fe * 28636360 * 0xf.15f17f0/4 = 108 MHz * 432 MHz pre-postdivide */ /* * AUX_PLL Fraction = 0x098d6e5 * 28636363 * 0xa.4c6b728/0x18 = 48000 * 256 * 295 MHz pre-postdivide * FIXME 28636363 ref_freq doesn't match VID PLL ref */ cx25840_write4(client, 0x110, 0x0098d6e5); /* * SA_MCLK_SEL = 1 * SA_MCLK_DIV = 0x10 = 256/384 * AUX_PLL post dvivider */ cx25840_write(client, 0x127, 0x50); if (is_cx2583x(state)) break; /* src1_ctl */ /* 0x1.8000 = 48000/32000 */ cx25840_write4(client, 0x8f8, 0x08018000); /* src3/4/6_ctl */ /* 0x1.5555 = 2 * (32000/48000) */ cx25840_write4(client, 0x900, 0x08015555); cx25840_write4(client, 0x904, 0x08015555); cx25840_write4(client, 0x90c, 0x08015555); break; } } state->audclk_freq = freq; return 0; } static inline int cx25836_set_audclk_freq(struct i2c_client *client, u32 freq) { return cx25840_set_audclk_freq(client, freq); } static int cx23885_set_audclk_freq(struct i2c_client *client, u32 freq) { struct cx25840_state *state = to_state(i2c_get_clientdata(client)); if (state->aud_input != CX25840_AUDIO_SERIAL) { switch (freq) { case 32000: case 44100: case 48000: /* We don't have register values * so avoid destroying registers. */ /* FIXME return -EINVAL; */ break; } } else { switch (freq) { case 32000: case 44100: /* We don't have register values * so avoid destroying registers. */ /* FIXME return -EINVAL; */ break; case 48000: /* src1_ctl */ /* 0x1.867c = 48000 / (2 * 28636360/8 * 2/455) */ cx25840_write4(client, 0x8f8, 0x0801867c); /* src3/4/6_ctl */ /* 0x1.4faa = (4 * 28636360/8 * 2/455) / 48000 */ cx25840_write4(client, 0x900, 0x08014faa); cx25840_write4(client, 0x904, 0x08014faa); cx25840_write4(client, 0x90c, 0x08014faa); break; } } state->audclk_freq = freq; return 0; } static int cx231xx_set_audclk_freq(struct i2c_client *client, u32 freq) { struct cx25840_state *state = to_state(i2c_get_clientdata(client)); if (state->aud_input != CX25840_AUDIO_SERIAL) { switch (freq) { case 32000: /* src3/4/6_ctl */ /* 0x1.f77f = (4 * 28636360/8 * 2/455) / 32000 */ cx25840_write4(client, 0x900, 0x0801f77f); cx25840_write4(client, 0x904, 0x0801f77f); cx25840_write4(client, 0x90c, 0x0801f77f); break; case 44100: /* src3/4/6_ctl */ /* 0x1.6d59 = (4 * 28636360/8 * 2/455) / 44100 */ cx25840_write4(client, 0x900, 0x08016d59); cx25840_write4(client, 0x904, 0x08016d59); cx25840_write4(client, 0x90c, 0x08016d59); break; case 48000: /* src3/4/6_ctl */ /* 0x1.4faa = (4 * 28636360/8 * 2/455) / 48000 */ cx25840_write4(client, 0x900, 0x08014faa); cx25840_write4(client, 0x904, 0x08014faa); cx25840_write4(client, 0x90c, 0x08014faa); break; } } else { switch (freq) { /* FIXME These cases make different assumptions about audclk */ case 32000: /* src1_ctl */ /* 0x1.0000 = 32000/32000 */ cx25840_write4(client, 0x8f8, 0x08010000); /* src3/4/6_ctl */ /* 0x2.0000 = 2 * (32000/32000) */ cx25840_write4(client, 0x900, 0x08020000); cx25840_write4(client, 0x904, 0x08020000); cx25840_write4(client, 0x90c, 0x08020000); break; case 44100: /* src1_ctl */ /* 0x1.60cd = 44100/32000 */ cx25840_write4(client, 0x8f8, 0x080160cd); /* src3/4/6_ctl */ /* 0x1.7385 = 2 * (32000/44100) */ cx25840_write4(client, 0x900, 0x08017385); cx25840_write4(client, 0x904, 0x08017385); cx25840_write4(client, 0x90c, 0x08017385); break; case 48000: /* src1_ctl */ /* 0x1.867c = 48000 / (2 * 28636360/8 * 2/455) */ cx25840_write4(client, 0x8f8, 0x0801867c); /* src3/4/6_ctl */ /* 0x1.4faa = (4 * 28636360/8 * 2/455) / 48000 */ cx25840_write4(client, 0x900, 0x08014faa); cx25840_write4(client, 0x904, 0x08014faa); cx25840_write4(client, 0x90c, 0x08014faa); break; } } state->audclk_freq = freq; return 0; } static int set_audclk_freq(struct i2c_client *client, u32 freq) { struct cx25840_state *state = to_state(i2c_get_clientdata(client)); if (freq != 32000 && freq != 44100 && freq != 48000) return -EINVAL; if (is_cx231xx(state)) return cx231xx_set_audclk_freq(client, freq); if (is_cx2388x(state)) return cx23885_set_audclk_freq(client, freq); if (is_cx2583x(state)) return cx25836_set_audclk_freq(client, freq); return cx25840_set_audclk_freq(client, freq); } void cx25840_audio_set_path(struct i2c_client *client) { struct cx25840_state *state = to_state(i2c_get_clientdata(client)); if (!is_cx2583x(state)) { /* assert soft reset */ cx25840_and_or(client, 0x810, ~0x1, 0x01); /* stop microcontroller */ cx25840_and_or(client, 0x803, ~0x10, 0); /* Mute everything to prevent the PFFT! */ cx25840_write(client, 0x8d3, 0x1f); if (state->aud_input == CX25840_AUDIO_SERIAL) { /* Set Path1 to Serial Audio Input */ cx25840_write4(client, 0x8d0, 0x01011012); /* The microcontroller should not be started for the * non-tuner inputs: autodetection is specific for * TV audio. */ } else { /* Set Path1 to Analog Demod Main Channel */ cx25840_write4(client, 0x8d0, 0x1f063870); } } set_audclk_freq(client, state->audclk_freq); if (!is_cx2583x(state)) { if (state->aud_input != CX25840_AUDIO_SERIAL) { /* When the microcontroller detects the * audio format, it will unmute the lines */ cx25840_and_or(client, 0x803, ~0x10, 0x10); } /* deassert soft reset */ cx25840_and_or(client, 0x810, ~0x1, 0x00); /* Ensure the controller is running when we exit */ if (is_cx2388x(state) || is_cx231xx(state)) cx25840_and_or(client, 0x803, ~0x10, 0x10); } } static void set_volume(struct i2c_client *client, int volume) { int vol; /* Convert the volume to msp3400 values (0-127) */ vol = volume >> 9; /* now scale it up to cx25840 values * -114dB to -96dB maps to 0 * this should be 19, but in my testing that was 4dB too loud */ if (vol <= 23) { vol = 0; } else { vol -= 23; } /* PATH1_VOLUME */ cx25840_write(client, 0x8d4, 228 - (vol * 2)); } static void set_balance(struct i2c_client *client, int balance) { int bal = balance >> 8; if (bal > 0x80) { /* PATH1_BAL_LEFT */ cx25840_and_or(client, 0x8d5, 0x7f, 0x80); /* PATH1_BAL_LEVEL */ cx25840_and_or(client, 0x8d5, ~0x7f, bal & 0x7f); } else { /* PATH1_BAL_LEFT */ cx25840_and_or(client, 0x8d5, 0x7f, 0x00); /* PATH1_BAL_LEVEL */ cx25840_and_or(client, 0x8d5, ~0x7f, 0x80 - bal); } } int cx25840_s_clock_freq(struct v4l2_subdev *sd, u32 freq) { struct i2c_client *client = v4l2_get_subdevdata(sd); struct cx25840_state *state = to_state(sd); int retval; if (!is_cx2583x(state)) cx25840_and_or(client, 0x810, ~0x1, 1); if (state->aud_input != CX25840_AUDIO_SERIAL) { cx25840_and_or(client, 0x803, ~0x10, 0); cx25840_write(client, 0x8d3, 0x1f); } retval = set_audclk_freq(client, freq); if (state->aud_input != CX25840_AUDIO_SERIAL) cx25840_and_or(client, 0x803, ~0x10, 0x10); if (!is_cx2583x(state)) cx25840_and_or(client, 0x810, ~0x1, 0); return retval; } static int cx25840_audio_s_ctrl(struct v4l2_ctrl *ctrl) { struct v4l2_subdev *sd = to_sd(ctrl); struct cx25840_state *state = to_state(sd); struct i2c_client *client = v4l2_get_subdevdata(sd); switch (ctrl->id) { case V4L2_CID_AUDIO_VOLUME: if (state->mute->val) set_volume(client, 0); else set_volume(client, state->volume->val); break; case V4L2_CID_AUDIO_BASS: /* PATH1_EQ_BASS_VOL */ cx25840_and_or(client, 0x8d9, ~0x3f, 48 - (ctrl->val * 48 / 0xffff)); break; case V4L2_CID_AUDIO_TREBLE: /* PATH1_EQ_TREBLE_VOL */ cx25840_and_or(client, 0x8db, ~0x3f, 48 - (ctrl->val * 48 / 0xffff)); break; case V4L2_CID_AUDIO_BALANCE: set_balance(client, ctrl->val); break; default: return -EINVAL; } return 0; } const struct v4l2_ctrl_ops cx25840_audio_ctrl_ops = { .s_ctrl = cx25840_audio_s_ctrl, };
linux-master
drivers/media/i2c/cx25840/cx25840-audio.c
// SPDX-License-Identifier: GPL-2.0-only /* * Samsung LSI S5C73M3 8M pixel camera driver * * Copyright (C) 2012, Samsung Electronics, Co., Ltd. * Sylwester Nawrocki <[email protected]> * Andrzej Hajda <[email protected]> */ #include <linux/clk.h> #include <linux/delay.h> #include <linux/firmware.h> #include <linux/gpio/consumer.h> #include <linux/i2c.h> #include <linux/init.h> #include <linux/media.h> #include <linux/module.h> #include <linux/of_graph.h> #include <linux/regulator/consumer.h> #include <linux/sizes.h> #include <linux/slab.h> #include <linux/spi/spi.h> #include <linux/videodev2.h> #include <media/media-entity.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-device.h> #include <media/v4l2-subdev.h> #include <media/v4l2-mediabus.h> #include <media/v4l2-fwnode.h> #include "s5c73m3.h" int s5c73m3_dbg; module_param_named(debug, s5c73m3_dbg, int, 0644); static int boot_from_rom = 1; module_param(boot_from_rom, int, 0644); static int update_fw; module_param(update_fw, int, 0644); #define S5C73M3_EMBEDDED_DATA_MAXLEN SZ_4K #define S5C73M3_MIPI_DATA_LANES 4 #define S5C73M3_CLK_NAME "cis_extclk" static const char * const s5c73m3_supply_names[S5C73M3_MAX_SUPPLIES] = { "vdd-int", /* Digital Core supply (1.2V), CAM_ISP_CORE_1.2V */ "vdda", /* Analog Core supply (1.2V), CAM_SENSOR_CORE_1.2V */ "vdd-reg", /* Regulator input supply (2.8V), CAM_SENSOR_A2.8V */ "vddio-host", /* Digital Host I/O power supply (1.8V...2.8V), CAM_ISP_SENSOR_1.8V */ "vddio-cis", /* Digital CIS I/O power (1.2V...1.8V), CAM_ISP_MIPI_1.2V */ "vdd-af", /* Lens, CAM_AF_2.8V */ }; static const struct s5c73m3_frame_size s5c73m3_isp_resolutions[] = { { 320, 240, COMM_CHG_MODE_YUV_320_240 }, { 352, 288, COMM_CHG_MODE_YUV_352_288 }, { 640, 480, COMM_CHG_MODE_YUV_640_480 }, { 880, 720, COMM_CHG_MODE_YUV_880_720 }, { 960, 720, COMM_CHG_MODE_YUV_960_720 }, { 1008, 672, COMM_CHG_MODE_YUV_1008_672 }, { 1184, 666, COMM_CHG_MODE_YUV_1184_666 }, { 1280, 720, COMM_CHG_MODE_YUV_1280_720 }, { 1536, 864, COMM_CHG_MODE_YUV_1536_864 }, { 1600, 1200, COMM_CHG_MODE_YUV_1600_1200 }, { 1632, 1224, COMM_CHG_MODE_YUV_1632_1224 }, { 1920, 1080, COMM_CHG_MODE_YUV_1920_1080 }, { 1920, 1440, COMM_CHG_MODE_YUV_1920_1440 }, { 2304, 1296, COMM_CHG_MODE_YUV_2304_1296 }, { 3264, 2448, COMM_CHG_MODE_YUV_3264_2448 }, }; static const struct s5c73m3_frame_size s5c73m3_jpeg_resolutions[] = { { 640, 480, COMM_CHG_MODE_JPEG_640_480 }, { 800, 450, COMM_CHG_MODE_JPEG_800_450 }, { 800, 600, COMM_CHG_MODE_JPEG_800_600 }, { 1024, 768, COMM_CHG_MODE_JPEG_1024_768 }, { 1280, 720, COMM_CHG_MODE_JPEG_1280_720 }, { 1280, 960, COMM_CHG_MODE_JPEG_1280_960 }, { 1600, 900, COMM_CHG_MODE_JPEG_1600_900 }, { 1600, 1200, COMM_CHG_MODE_JPEG_1600_1200 }, { 2048, 1152, COMM_CHG_MODE_JPEG_2048_1152 }, { 2048, 1536, COMM_CHG_MODE_JPEG_2048_1536 }, { 2560, 1440, COMM_CHG_MODE_JPEG_2560_1440 }, { 2560, 1920, COMM_CHG_MODE_JPEG_2560_1920 }, { 3264, 1836, COMM_CHG_MODE_JPEG_3264_1836 }, { 3264, 2176, COMM_CHG_MODE_JPEG_3264_2176 }, { 3264, 2448, COMM_CHG_MODE_JPEG_3264_2448 }, }; static const struct s5c73m3_frame_size * const s5c73m3_resolutions[] = { [RES_ISP] = s5c73m3_isp_resolutions, [RES_JPEG] = s5c73m3_jpeg_resolutions }; static const int s5c73m3_resolutions_len[] = { [RES_ISP] = ARRAY_SIZE(s5c73m3_isp_resolutions), [RES_JPEG] = ARRAY_SIZE(s5c73m3_jpeg_resolutions) }; static const struct s5c73m3_interval s5c73m3_intervals[] = { { COMM_FRAME_RATE_FIXED_7FPS, {142857, 1000000}, {3264, 2448} }, { COMM_FRAME_RATE_FIXED_15FPS, {66667, 1000000}, {3264, 2448} }, { COMM_FRAME_RATE_FIXED_20FPS, {50000, 1000000}, {2304, 1296} }, { COMM_FRAME_RATE_FIXED_30FPS, {33333, 1000000}, {2304, 1296} }, }; #define S5C73M3_DEFAULT_FRAME_INTERVAL 3 /* 30 fps */ static void s5c73m3_fill_mbus_fmt(struct v4l2_mbus_framefmt *mf, const struct s5c73m3_frame_size *fs, u32 code) { mf->width = fs->width; mf->height = fs->height; mf->code = code; mf->colorspace = V4L2_COLORSPACE_JPEG; mf->field = V4L2_FIELD_NONE; } static int s5c73m3_i2c_write(struct i2c_client *client, u16 addr, u16 data) { u8 buf[4] = { addr >> 8, addr & 0xff, data >> 8, data & 0xff }; int ret = i2c_master_send(client, buf, sizeof(buf)); v4l_dbg(4, s5c73m3_dbg, client, "%s: addr 0x%04x, data 0x%04x\n", __func__, addr, data); if (ret == 4) return 0; return ret < 0 ? ret : -EREMOTEIO; } static int s5c73m3_i2c_read(struct i2c_client *client, u16 addr, u16 *data) { int ret; u8 rbuf[2], wbuf[2] = { addr >> 8, addr & 0xff }; struct i2c_msg msg[2] = { { .addr = client->addr, .flags = 0, .len = sizeof(wbuf), .buf = wbuf }, { .addr = client->addr, .flags = I2C_M_RD, .len = sizeof(rbuf), .buf = rbuf } }; /* * Issue repeated START after writing 2 address bytes and * just one STOP only after reading the data bytes. */ ret = i2c_transfer(client->adapter, msg, 2); if (ret == 2) { *data = be16_to_cpup((__be16 *)rbuf); v4l2_dbg(4, s5c73m3_dbg, client, "%s: addr: 0x%04x, data: 0x%04x\n", __func__, addr, *data); return 0; } v4l2_err(client, "I2C read failed: addr: %04x, (%d)\n", addr, ret); return ret >= 0 ? -EREMOTEIO : ret; } int s5c73m3_write(struct s5c73m3 *state, u32 addr, u16 data) { struct i2c_client *client = state->i2c_client; int ret; if ((addr ^ state->i2c_write_address) & 0xffff0000) { ret = s5c73m3_i2c_write(client, REG_CMDWR_ADDRH, addr >> 16); if (ret < 0) { state->i2c_write_address = 0; return ret; } } if ((addr ^ state->i2c_write_address) & 0xffff) { ret = s5c73m3_i2c_write(client, REG_CMDWR_ADDRL, addr & 0xffff); if (ret < 0) { state->i2c_write_address = 0; return ret; } } state->i2c_write_address = addr; ret = s5c73m3_i2c_write(client, REG_CMDBUF_ADDR, data); if (ret < 0) return ret; state->i2c_write_address += 2; return ret; } int s5c73m3_read(struct s5c73m3 *state, u32 addr, u16 *data) { struct i2c_client *client = state->i2c_client; int ret; if ((addr ^ state->i2c_read_address) & 0xffff0000) { ret = s5c73m3_i2c_write(client, REG_CMDRD_ADDRH, addr >> 16); if (ret < 0) { state->i2c_read_address = 0; return ret; } } if ((addr ^ state->i2c_read_address) & 0xffff) { ret = s5c73m3_i2c_write(client, REG_CMDRD_ADDRL, addr & 0xffff); if (ret < 0) { state->i2c_read_address = 0; return ret; } } state->i2c_read_address = addr; ret = s5c73m3_i2c_read(client, REG_CMDBUF_ADDR, data); if (ret < 0) return ret; state->i2c_read_address += 2; return ret; } static int s5c73m3_check_status(struct s5c73m3 *state, unsigned int value) { unsigned long start = jiffies; unsigned long end = start + msecs_to_jiffies(2000); int ret; u16 status; int count = 0; do { ret = s5c73m3_read(state, REG_STATUS, &status); if (ret < 0 || status == value) break; usleep_range(500, 1000); ++count; } while (time_is_after_jiffies(end)); if (count > 0) v4l2_dbg(1, s5c73m3_dbg, &state->sensor_sd, "status check took %dms\n", jiffies_to_msecs(jiffies - start)); if (ret == 0 && status != value) { u16 i2c_status = 0; u16 i2c_seq_status = 0; s5c73m3_read(state, REG_I2C_STATUS, &i2c_status); s5c73m3_read(state, REG_I2C_SEQ_STATUS, &i2c_seq_status); v4l2_err(&state->sensor_sd, "wrong status %#x, expected: %#x, i2c_status: %#x/%#x\n", status, value, i2c_status, i2c_seq_status); return -ETIMEDOUT; } return ret; } int s5c73m3_isp_command(struct s5c73m3 *state, u16 command, u16 data) { int ret; ret = s5c73m3_check_status(state, REG_STATUS_ISP_COMMAND_COMPLETED); if (ret < 0) return ret; ret = s5c73m3_write(state, 0x00095000, command); if (ret < 0) return ret; ret = s5c73m3_write(state, 0x00095002, data); if (ret < 0) return ret; return s5c73m3_write(state, REG_STATUS, 0x0001); } static int s5c73m3_isp_comm_result(struct s5c73m3 *state, u16 command, u16 *data) { return s5c73m3_read(state, COMM_RESULT_OFFSET + command, data); } static int s5c73m3_set_af_softlanding(struct s5c73m3 *state) { unsigned long start = jiffies; u16 af_softlanding; int count = 0; int ret; const char *msg; ret = s5c73m3_isp_command(state, COMM_AF_SOFTLANDING, COMM_AF_SOFTLANDING_ON); if (ret < 0) { v4l2_info(&state->sensor_sd, "AF soft-landing failed\n"); return ret; } for (;;) { ret = s5c73m3_isp_comm_result(state, COMM_AF_SOFTLANDING, &af_softlanding); if (ret < 0) { msg = "failed"; break; } if (af_softlanding == COMM_AF_SOFTLANDING_RES_COMPLETE) { msg = "succeeded"; break; } if (++count > 100) { ret = -ETIME; msg = "timed out"; break; } msleep(25); } v4l2_info(&state->sensor_sd, "AF soft-landing %s after %dms\n", msg, jiffies_to_msecs(jiffies - start)); return ret; } static int s5c73m3_load_fw(struct v4l2_subdev *sd) { struct s5c73m3 *state = sensor_sd_to_s5c73m3(sd); struct i2c_client *client = state->i2c_client; const struct firmware *fw; int ret; char fw_name[20]; snprintf(fw_name, sizeof(fw_name), "SlimISP_%.2s.bin", state->fw_file_version); ret = request_firmware(&fw, fw_name, &client->dev); if (ret < 0) { v4l2_err(sd, "Firmware request failed (%s)\n", fw_name); return -EINVAL; } v4l2_info(sd, "Loading firmware (%s, %zu B)\n", fw_name, fw->size); ret = s5c73m3_spi_write(state, fw->data, fw->size, 64); if (ret >= 0) state->isp_ready = 1; else v4l2_err(sd, "SPI write failed\n"); release_firmware(fw); return ret; } static int s5c73m3_set_frame_size(struct s5c73m3 *state) { const struct s5c73m3_frame_size *prev_size = state->sensor_pix_size[RES_ISP]; const struct s5c73m3_frame_size *cap_size = state->sensor_pix_size[RES_JPEG]; unsigned int chg_mode; v4l2_dbg(1, s5c73m3_dbg, &state->sensor_sd, "Preview size: %dx%d, reg_val: 0x%x\n", prev_size->width, prev_size->height, prev_size->reg_val); chg_mode = prev_size->reg_val | COMM_CHG_MODE_NEW; if (state->mbus_code == S5C73M3_JPEG_FMT) { v4l2_dbg(1, s5c73m3_dbg, &state->sensor_sd, "Capture size: %dx%d, reg_val: 0x%x\n", cap_size->width, cap_size->height, cap_size->reg_val); chg_mode |= cap_size->reg_val; } return s5c73m3_isp_command(state, COMM_CHG_MODE, chg_mode); } static int s5c73m3_set_frame_rate(struct s5c73m3 *state) { int ret; if (state->ctrls.stabilization->val) return 0; if (WARN_ON(state->fiv == NULL)) return -EINVAL; ret = s5c73m3_isp_command(state, COMM_FRAME_RATE, state->fiv->fps_reg); if (!ret) state->apply_fiv = 0; return ret; } static int __s5c73m3_s_stream(struct s5c73m3 *state, struct v4l2_subdev *sd, int on) { u16 mode; int ret; if (on && state->apply_fmt) { if (state->mbus_code == S5C73M3_JPEG_FMT) mode = COMM_IMG_OUTPUT_INTERLEAVED; else mode = COMM_IMG_OUTPUT_YUV; ret = s5c73m3_isp_command(state, COMM_IMG_OUTPUT, mode); if (!ret) ret = s5c73m3_set_frame_size(state); if (ret) return ret; state->apply_fmt = 0; } ret = s5c73m3_isp_command(state, COMM_SENSOR_STREAMING, !!on); if (ret) return ret; state->streaming = !!on; if (!on) return 0; if (state->apply_fiv) { ret = s5c73m3_set_frame_rate(state); if (ret < 0) v4l2_err(sd, "Error setting frame rate(%d)\n", ret); } return s5c73m3_check_status(state, REG_STATUS_ISP_COMMAND_COMPLETED); } static int s5c73m3_oif_s_stream(struct v4l2_subdev *sd, int on) { struct s5c73m3 *state = oif_sd_to_s5c73m3(sd); int ret; mutex_lock(&state->lock); ret = __s5c73m3_s_stream(state, sd, on); mutex_unlock(&state->lock); return ret; } static int s5c73m3_system_status_wait(struct s5c73m3 *state, u32 value, unsigned int delay, unsigned int steps) { u16 reg = 0; while (steps-- > 0) { int ret = s5c73m3_read(state, 0x30100010, &reg); if (ret < 0) return ret; if (reg == value) return 0; usleep_range(delay, delay + 25); } return -ETIMEDOUT; } static int s5c73m3_read_fw_version(struct s5c73m3 *state) { struct v4l2_subdev *sd = &state->sensor_sd; int i, ret; u16 data[2]; int offset; offset = state->isp_ready ? 0x60 : 0; for (i = 0; i < S5C73M3_SENSOR_FW_LEN / 2; i++) { ret = s5c73m3_read(state, offset + i * 2, data); if (ret < 0) return ret; state->sensor_fw[i * 2] = (char)(*data & 0xff); state->sensor_fw[i * 2 + 1] = (char)(*data >> 8); } state->sensor_fw[S5C73M3_SENSOR_FW_LEN] = '\0'; for (i = 0; i < S5C73M3_SENSOR_TYPE_LEN / 2; i++) { ret = s5c73m3_read(state, offset + 6 + i * 2, data); if (ret < 0) return ret; state->sensor_type[i * 2] = (char)(*data & 0xff); state->sensor_type[i * 2 + 1] = (char)(*data >> 8); } state->sensor_type[S5C73M3_SENSOR_TYPE_LEN] = '\0'; ret = s5c73m3_read(state, offset + 0x14, data); if (ret >= 0) { ret = s5c73m3_read(state, offset + 0x16, data + 1); if (ret >= 0) state->fw_size = data[0] + (data[1] << 16); } v4l2_info(sd, "Sensor type: %s, FW version: %s\n", state->sensor_type, state->sensor_fw); return ret; } static int s5c73m3_fw_update_from(struct s5c73m3 *state) { struct v4l2_subdev *sd = &state->sensor_sd; u16 status = COMM_FW_UPDATE_NOT_READY; int ret; int count = 0; v4l2_warn(sd, "Updating F-ROM firmware.\n"); do { if (status == COMM_FW_UPDATE_NOT_READY) { ret = s5c73m3_isp_command(state, COMM_FW_UPDATE, 0); if (ret < 0) return ret; } ret = s5c73m3_read(state, 0x00095906, &status); if (ret < 0) return ret; switch (status) { case COMM_FW_UPDATE_FAIL: v4l2_warn(sd, "Updating F-ROM firmware failed.\n"); return -EIO; case COMM_FW_UPDATE_SUCCESS: v4l2_warn(sd, "Updating F-ROM firmware finished.\n"); return 0; } ++count; msleep(20); } while (count < 500); v4l2_warn(sd, "Updating F-ROM firmware timed-out.\n"); return -ETIMEDOUT; } static int s5c73m3_spi_boot(struct s5c73m3 *state, bool load_fw) { struct v4l2_subdev *sd = &state->sensor_sd; int ret; /* Run ARM MCU */ ret = s5c73m3_write(state, 0x30000004, 0xffff); if (ret < 0) return ret; usleep_range(400, 500); /* Check booting status */ ret = s5c73m3_system_status_wait(state, 0x0c, 100, 3); if (ret < 0) { v4l2_err(sd, "booting failed: %d\n", ret); return ret; } /* P,M,S and Boot Mode */ ret = s5c73m3_write(state, 0x30100014, 0x2146); if (ret < 0) return ret; ret = s5c73m3_write(state, 0x30100010, 0x210c); if (ret < 0) return ret; usleep_range(200, 250); /* Check SPI status */ ret = s5c73m3_system_status_wait(state, 0x210d, 100, 300); if (ret < 0) v4l2_err(sd, "SPI not ready: %d\n", ret); /* Firmware download over SPI */ if (load_fw) s5c73m3_load_fw(sd); /* MCU reset */ ret = s5c73m3_write(state, 0x30000004, 0xfffd); if (ret < 0) return ret; /* Remap */ ret = s5c73m3_write(state, 0x301000a4, 0x0183); if (ret < 0) return ret; /* MCU restart */ ret = s5c73m3_write(state, 0x30000004, 0xffff); if (ret < 0 || !load_fw) return ret; ret = s5c73m3_read_fw_version(state); if (ret < 0) return ret; if (load_fw && update_fw) { ret = s5c73m3_fw_update_from(state); update_fw = 0; } return ret; } static int s5c73m3_set_timing_register_for_vdd(struct s5c73m3 *state) { static const u32 regs[][2] = { { 0x30100018, 0x0618 }, { 0x3010001c, 0x10c1 }, { 0x30100020, 0x249e } }; int ret; int i; for (i = 0; i < ARRAY_SIZE(regs); i++) { ret = s5c73m3_write(state, regs[i][0], regs[i][1]); if (ret < 0) return ret; } return 0; } static void s5c73m3_set_fw_file_version(struct s5c73m3 *state) { switch (state->sensor_fw[0]) { case 'G': case 'O': state->fw_file_version[0] = 'G'; break; case 'S': case 'Z': state->fw_file_version[0] = 'Z'; break; } switch (state->sensor_fw[1]) { case 'C'...'F': state->fw_file_version[1] = state->sensor_fw[1]; break; } } static int s5c73m3_get_fw_version(struct s5c73m3 *state) { struct v4l2_subdev *sd = &state->sensor_sd; int ret; /* Run ARM MCU */ ret = s5c73m3_write(state, 0x30000004, 0xffff); if (ret < 0) return ret; usleep_range(400, 500); /* Check booting status */ ret = s5c73m3_system_status_wait(state, 0x0c, 100, 3); if (ret < 0) { v4l2_err(sd, "%s: booting failed: %d\n", __func__, ret); return ret; } /* Change I/O Driver Current in order to read from F-ROM */ ret = s5c73m3_write(state, 0x30100120, 0x0820); ret = s5c73m3_write(state, 0x30100124, 0x0820); /* Offset Setting */ ret = s5c73m3_write(state, 0x00010418, 0x0008); /* P,M,S and Boot Mode */ ret = s5c73m3_write(state, 0x30100014, 0x2146); if (ret < 0) return ret; ret = s5c73m3_write(state, 0x30100010, 0x230c); if (ret < 0) return ret; usleep_range(200, 250); /* Check SPI status */ ret = s5c73m3_system_status_wait(state, 0x230e, 100, 300); if (ret < 0) v4l2_err(sd, "SPI not ready: %d\n", ret); /* ARM reset */ ret = s5c73m3_write(state, 0x30000004, 0xfffd); if (ret < 0) return ret; /* Remap */ ret = s5c73m3_write(state, 0x301000a4, 0x0183); if (ret < 0) return ret; s5c73m3_set_timing_register_for_vdd(state); ret = s5c73m3_read_fw_version(state); s5c73m3_set_fw_file_version(state); return ret; } static int s5c73m3_rom_boot(struct s5c73m3 *state, bool load_fw) { static const u32 boot_regs[][2] = { { 0x3100010c, 0x0044 }, { 0x31000108, 0x000d }, { 0x31000304, 0x0001 }, { 0x00010000, 0x5800 }, { 0x00010002, 0x0002 }, { 0x31000000, 0x0001 }, { 0x30100014, 0x1b85 }, { 0x30100010, 0x230c } }; struct v4l2_subdev *sd = &state->sensor_sd; int i, ret; /* Run ARM MCU */ ret = s5c73m3_write(state, 0x30000004, 0xffff); if (ret < 0) return ret; usleep_range(400, 450); /* Check booting status */ ret = s5c73m3_system_status_wait(state, 0x0c, 100, 4); if (ret < 0) { v4l2_err(sd, "Booting failed: %d\n", ret); return ret; } for (i = 0; i < ARRAY_SIZE(boot_regs); i++) { ret = s5c73m3_write(state, boot_regs[i][0], boot_regs[i][1]); if (ret < 0) return ret; } msleep(200); /* Check the binary read status */ ret = s5c73m3_system_status_wait(state, 0x230e, 1000, 150); if (ret < 0) { v4l2_err(sd, "Binary read failed: %d\n", ret); return ret; } /* ARM reset */ ret = s5c73m3_write(state, 0x30000004, 0xfffd); if (ret < 0) return ret; /* Remap */ ret = s5c73m3_write(state, 0x301000a4, 0x0183); if (ret < 0) return ret; /* MCU re-start */ ret = s5c73m3_write(state, 0x30000004, 0xffff); if (ret < 0) return ret; state->isp_ready = 1; return s5c73m3_read_fw_version(state); } static int s5c73m3_isp_init(struct s5c73m3 *state) { int ret; state->i2c_read_address = 0; state->i2c_write_address = 0; ret = s5c73m3_i2c_write(state->i2c_client, AHB_MSB_ADDR_PTR, 0x3310); if (ret < 0) return ret; if (boot_from_rom) return s5c73m3_rom_boot(state, true); else return s5c73m3_spi_boot(state, true); } static const struct s5c73m3_frame_size *s5c73m3_find_frame_size( struct v4l2_mbus_framefmt *fmt, enum s5c73m3_resolution_types idx) { const struct s5c73m3_frame_size *fs; const struct s5c73m3_frame_size *best_fs; int best_dist = INT_MAX; int i; fs = s5c73m3_resolutions[idx]; best_fs = NULL; for (i = 0; i < s5c73m3_resolutions_len[idx]; ++i) { int dist = abs(fs->width - fmt->width) + abs(fs->height - fmt->height); if (dist < best_dist) { best_dist = dist; best_fs = fs; } ++fs; } return best_fs; } static void s5c73m3_oif_try_format(struct s5c73m3 *state, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *fmt, const struct s5c73m3_frame_size **fs) { struct v4l2_subdev *sd = &state->sensor_sd; u32 code; switch (fmt->pad) { case OIF_ISP_PAD: *fs = s5c73m3_find_frame_size(&fmt->format, RES_ISP); code = S5C73M3_ISP_FMT; break; case OIF_JPEG_PAD: *fs = s5c73m3_find_frame_size(&fmt->format, RES_JPEG); code = S5C73M3_JPEG_FMT; break; case OIF_SOURCE_PAD: default: if (fmt->format.code == S5C73M3_JPEG_FMT) code = S5C73M3_JPEG_FMT; else code = S5C73M3_ISP_FMT; if (fmt->which == V4L2_SUBDEV_FORMAT_ACTIVE) *fs = state->oif_pix_size[RES_ISP]; else *fs = s5c73m3_find_frame_size( v4l2_subdev_get_try_format(sd, sd_state, OIF_ISP_PAD), RES_ISP); break; } s5c73m3_fill_mbus_fmt(&fmt->format, *fs, code); } static void s5c73m3_try_format(struct s5c73m3 *state, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *fmt, const struct s5c73m3_frame_size **fs) { u32 code; if (fmt->pad == S5C73M3_ISP_PAD) { *fs = s5c73m3_find_frame_size(&fmt->format, RES_ISP); code = S5C73M3_ISP_FMT; } else { *fs = s5c73m3_find_frame_size(&fmt->format, RES_JPEG); code = S5C73M3_JPEG_FMT; } s5c73m3_fill_mbus_fmt(&fmt->format, *fs, code); } static int s5c73m3_oif_g_frame_interval(struct v4l2_subdev *sd, struct v4l2_subdev_frame_interval *fi) { struct s5c73m3 *state = oif_sd_to_s5c73m3(sd); if (fi->pad != OIF_SOURCE_PAD) return -EINVAL; mutex_lock(&state->lock); fi->interval = state->fiv->interval; mutex_unlock(&state->lock); return 0; } static int __s5c73m3_set_frame_interval(struct s5c73m3 *state, struct v4l2_subdev_frame_interval *fi) { const struct s5c73m3_frame_size *prev_size = state->sensor_pix_size[RES_ISP]; const struct s5c73m3_interval *fiv = &s5c73m3_intervals[0]; unsigned int ret, min_err = UINT_MAX; unsigned int i, fr_time; if (fi->interval.denominator == 0) return -EINVAL; fr_time = fi->interval.numerator * 1000 / fi->interval.denominator; for (i = 0; i < ARRAY_SIZE(s5c73m3_intervals); i++) { const struct s5c73m3_interval *iv = &s5c73m3_intervals[i]; if (prev_size->width > iv->size.width || prev_size->height > iv->size.height) continue; ret = abs(iv->interval.numerator / 1000 - fr_time); if (ret < min_err) { fiv = iv; min_err = ret; } } state->fiv = fiv; v4l2_dbg(1, s5c73m3_dbg, &state->sensor_sd, "Changed frame interval to %u us\n", fiv->interval.numerator); return 0; } static int s5c73m3_oif_s_frame_interval(struct v4l2_subdev *sd, struct v4l2_subdev_frame_interval *fi) { struct s5c73m3 *state = oif_sd_to_s5c73m3(sd); int ret; if (fi->pad != OIF_SOURCE_PAD) return -EINVAL; v4l2_dbg(1, s5c73m3_dbg, sd, "Setting %d/%d frame interval\n", fi->interval.numerator, fi->interval.denominator); mutex_lock(&state->lock); ret = __s5c73m3_set_frame_interval(state, fi); if (!ret) { if (state->streaming) ret = s5c73m3_set_frame_rate(state); else state->apply_fiv = 1; } mutex_unlock(&state->lock); return ret; } static int s5c73m3_oif_enum_frame_interval(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_frame_interval_enum *fie) { struct s5c73m3 *state = oif_sd_to_s5c73m3(sd); const struct s5c73m3_interval *fi; int ret = 0; if (fie->pad != OIF_SOURCE_PAD) return -EINVAL; if (fie->index >= ARRAY_SIZE(s5c73m3_intervals)) return -EINVAL; mutex_lock(&state->lock); fi = &s5c73m3_intervals[fie->index]; if (fie->width > fi->size.width || fie->height > fi->size.height) ret = -EINVAL; else fie->interval = fi->interval; mutex_unlock(&state->lock); return ret; } static int s5c73m3_oif_get_pad_code(int pad, int index) { if (pad == OIF_SOURCE_PAD) { if (index > 1) return -EINVAL; return (index == 0) ? S5C73M3_ISP_FMT : S5C73M3_JPEG_FMT; } if (index > 0) return -EINVAL; return (pad == OIF_ISP_PAD) ? S5C73M3_ISP_FMT : S5C73M3_JPEG_FMT; } static int s5c73m3_get_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *fmt) { struct s5c73m3 *state = sensor_sd_to_s5c73m3(sd); const struct s5c73m3_frame_size *fs; u32 code; if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) { fmt->format = *v4l2_subdev_get_try_format(sd, sd_state, fmt->pad); return 0; } mutex_lock(&state->lock); switch (fmt->pad) { case S5C73M3_ISP_PAD: code = S5C73M3_ISP_FMT; fs = state->sensor_pix_size[RES_ISP]; break; case S5C73M3_JPEG_PAD: code = S5C73M3_JPEG_FMT; fs = state->sensor_pix_size[RES_JPEG]; break; default: mutex_unlock(&state->lock); return -EINVAL; } s5c73m3_fill_mbus_fmt(&fmt->format, fs, code); mutex_unlock(&state->lock); return 0; } static int s5c73m3_oif_get_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *fmt) { struct s5c73m3 *state = oif_sd_to_s5c73m3(sd); const struct s5c73m3_frame_size *fs; u32 code; if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) { fmt->format = *v4l2_subdev_get_try_format(sd, sd_state, fmt->pad); return 0; } mutex_lock(&state->lock); switch (fmt->pad) { case OIF_ISP_PAD: code = S5C73M3_ISP_FMT; fs = state->oif_pix_size[RES_ISP]; break; case OIF_JPEG_PAD: code = S5C73M3_JPEG_FMT; fs = state->oif_pix_size[RES_JPEG]; break; case OIF_SOURCE_PAD: code = state->mbus_code; fs = state->oif_pix_size[RES_ISP]; break; default: mutex_unlock(&state->lock); return -EINVAL; } s5c73m3_fill_mbus_fmt(&fmt->format, fs, code); mutex_unlock(&state->lock); return 0; } static int s5c73m3_set_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *fmt) { const struct s5c73m3_frame_size *frame_size = NULL; struct s5c73m3 *state = sensor_sd_to_s5c73m3(sd); struct v4l2_mbus_framefmt *mf; int ret = 0; mutex_lock(&state->lock); s5c73m3_try_format(state, sd_state, fmt, &frame_size); if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) { mf = v4l2_subdev_get_try_format(sd, sd_state, fmt->pad); *mf = fmt->format; } else { switch (fmt->pad) { case S5C73M3_ISP_PAD: state->sensor_pix_size[RES_ISP] = frame_size; break; case S5C73M3_JPEG_PAD: state->sensor_pix_size[RES_JPEG] = frame_size; break; default: ret = -EBUSY; } if (state->streaming) ret = -EBUSY; else state->apply_fmt = 1; } mutex_unlock(&state->lock); return ret; } static int s5c73m3_oif_set_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *fmt) { const struct s5c73m3_frame_size *frame_size = NULL; struct s5c73m3 *state = oif_sd_to_s5c73m3(sd); struct v4l2_mbus_framefmt *mf; int ret = 0; mutex_lock(&state->lock); s5c73m3_oif_try_format(state, sd_state, fmt, &frame_size); if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) { mf = v4l2_subdev_get_try_format(sd, sd_state, fmt->pad); *mf = fmt->format; if (fmt->pad == OIF_ISP_PAD) { mf = v4l2_subdev_get_try_format(sd, sd_state, OIF_SOURCE_PAD); mf->width = fmt->format.width; mf->height = fmt->format.height; } } else { switch (fmt->pad) { case OIF_ISP_PAD: state->oif_pix_size[RES_ISP] = frame_size; break; case OIF_JPEG_PAD: state->oif_pix_size[RES_JPEG] = frame_size; break; case OIF_SOURCE_PAD: state->mbus_code = fmt->format.code; break; default: ret = -EBUSY; } if (state->streaming) ret = -EBUSY; else state->apply_fmt = 1; } mutex_unlock(&state->lock); return ret; } static int s5c73m3_oif_get_frame_desc(struct v4l2_subdev *sd, unsigned int pad, struct v4l2_mbus_frame_desc *fd) { struct s5c73m3 *state = oif_sd_to_s5c73m3(sd); int i; if (pad != OIF_SOURCE_PAD || fd == NULL) return -EINVAL; mutex_lock(&state->lock); fd->num_entries = 2; for (i = 0; i < fd->num_entries; i++) fd->entry[i] = state->frame_desc.entry[i]; mutex_unlock(&state->lock); return 0; } static int s5c73m3_oif_set_frame_desc(struct v4l2_subdev *sd, unsigned int pad, struct v4l2_mbus_frame_desc *fd) { struct s5c73m3 *state = oif_sd_to_s5c73m3(sd); struct v4l2_mbus_frame_desc *frame_desc = &state->frame_desc; int i; if (pad != OIF_SOURCE_PAD || fd == NULL) return -EINVAL; fd->entry[0].length = 10 * SZ_1M; fd->entry[1].length = max_t(u32, fd->entry[1].length, S5C73M3_EMBEDDED_DATA_MAXLEN); fd->num_entries = 2; mutex_lock(&state->lock); for (i = 0; i < fd->num_entries; i++) frame_desc->entry[i] = fd->entry[i]; mutex_unlock(&state->lock); return 0; } static int s5c73m3_enum_mbus_code(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_mbus_code_enum *code) { static const int codes[] = { [S5C73M3_ISP_PAD] = S5C73M3_ISP_FMT, [S5C73M3_JPEG_PAD] = S5C73M3_JPEG_FMT}; if (code->index > 0 || code->pad >= S5C73M3_NUM_PADS) return -EINVAL; code->code = codes[code->pad]; return 0; } static int s5c73m3_oif_enum_mbus_code(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_mbus_code_enum *code) { int ret; ret = s5c73m3_oif_get_pad_code(code->pad, code->index); if (ret < 0) return ret; code->code = ret; return 0; } static int s5c73m3_enum_frame_size(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_frame_size_enum *fse) { int idx; if (fse->pad == S5C73M3_ISP_PAD) { if (fse->code != S5C73M3_ISP_FMT) return -EINVAL; idx = RES_ISP; } else{ if (fse->code != S5C73M3_JPEG_FMT) return -EINVAL; idx = RES_JPEG; } if (fse->index >= s5c73m3_resolutions_len[idx]) return -EINVAL; fse->min_width = s5c73m3_resolutions[idx][fse->index].width; fse->max_width = fse->min_width; fse->max_height = s5c73m3_resolutions[idx][fse->index].height; fse->min_height = fse->max_height; return 0; } static int s5c73m3_oif_enum_frame_size(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_frame_size_enum *fse) { struct s5c73m3 *state = oif_sd_to_s5c73m3(sd); int idx; if (fse->pad == OIF_SOURCE_PAD) { if (fse->index > 0) return -EINVAL; switch (fse->code) { case S5C73M3_JPEG_FMT: case S5C73M3_ISP_FMT: { unsigned w, h; if (fse->which == V4L2_SUBDEV_FORMAT_TRY) { struct v4l2_mbus_framefmt *mf; mf = v4l2_subdev_get_try_format(sd, sd_state, OIF_ISP_PAD); w = mf->width; h = mf->height; } else { const struct s5c73m3_frame_size *fs; fs = state->oif_pix_size[RES_ISP]; w = fs->width; h = fs->height; } fse->max_width = fse->min_width = w; fse->max_height = fse->min_height = h; return 0; } default: return -EINVAL; } } if (fse->code != s5c73m3_oif_get_pad_code(fse->pad, 0)) return -EINVAL; if (fse->pad == OIF_JPEG_PAD) idx = RES_JPEG; else idx = RES_ISP; if (fse->index >= s5c73m3_resolutions_len[idx]) return -EINVAL; fse->min_width = s5c73m3_resolutions[idx][fse->index].width; fse->max_width = fse->min_width; fse->max_height = s5c73m3_resolutions[idx][fse->index].height; fse->min_height = fse->max_height; return 0; } static int s5c73m3_oif_log_status(struct v4l2_subdev *sd) { struct s5c73m3 *state = oif_sd_to_s5c73m3(sd); v4l2_ctrl_handler_log_status(sd->ctrl_handler, sd->name); v4l2_info(sd, "power: %d, apply_fmt: %d\n", state->power, state->apply_fmt); return 0; } static int s5c73m3_open(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh) { struct v4l2_mbus_framefmt *mf; mf = v4l2_subdev_get_try_format(sd, fh->state, S5C73M3_ISP_PAD); s5c73m3_fill_mbus_fmt(mf, &s5c73m3_isp_resolutions[1], S5C73M3_ISP_FMT); mf = v4l2_subdev_get_try_format(sd, fh->state, S5C73M3_JPEG_PAD); s5c73m3_fill_mbus_fmt(mf, &s5c73m3_jpeg_resolutions[1], S5C73M3_JPEG_FMT); return 0; } static int s5c73m3_oif_open(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh) { struct v4l2_mbus_framefmt *mf; mf = v4l2_subdev_get_try_format(sd, fh->state, OIF_ISP_PAD); s5c73m3_fill_mbus_fmt(mf, &s5c73m3_isp_resolutions[1], S5C73M3_ISP_FMT); mf = v4l2_subdev_get_try_format(sd, fh->state, OIF_JPEG_PAD); s5c73m3_fill_mbus_fmt(mf, &s5c73m3_jpeg_resolutions[1], S5C73M3_JPEG_FMT); mf = v4l2_subdev_get_try_format(sd, fh->state, OIF_SOURCE_PAD); s5c73m3_fill_mbus_fmt(mf, &s5c73m3_isp_resolutions[1], S5C73M3_ISP_FMT); return 0; } static int __s5c73m3_power_on(struct s5c73m3 *state) { int i, ret; for (i = 0; i < S5C73M3_MAX_SUPPLIES; i++) { ret = regulator_enable(state->supplies[i].consumer); if (ret) goto err_reg_dis; } ret = clk_set_rate(state->clock, state->mclk_frequency); if (ret < 0) goto err_reg_dis; ret = clk_prepare_enable(state->clock); if (ret < 0) goto err_reg_dis; v4l2_dbg(1, s5c73m3_dbg, &state->oif_sd, "clock frequency: %ld\n", clk_get_rate(state->clock)); gpiod_set_value(state->stby, 0); usleep_range(100, 200); gpiod_set_value(state->reset, 0); usleep_range(50, 100); return 0; err_reg_dis: for (--i; i >= 0; i--) regulator_disable(state->supplies[i].consumer); return ret; } static int __s5c73m3_power_off(struct s5c73m3 *state) { int i, ret; gpiod_set_value(state->reset, 1); usleep_range(10, 50); gpiod_set_value(state->stby, 1); usleep_range(100, 200); clk_disable_unprepare(state->clock); state->streaming = 0; state->isp_ready = 0; for (i = S5C73M3_MAX_SUPPLIES - 1; i >= 0; i--) { ret = regulator_disable(state->supplies[i].consumer); if (ret) goto err; } return 0; err: for (++i; i < S5C73M3_MAX_SUPPLIES; i++) { int r = regulator_enable(state->supplies[i].consumer); if (r < 0) v4l2_err(&state->oif_sd, "Failed to re-enable %s: %d\n", state->supplies[i].supply, r); } clk_prepare_enable(state->clock); return ret; } static int s5c73m3_oif_set_power(struct v4l2_subdev *sd, int on) { struct s5c73m3 *state = oif_sd_to_s5c73m3(sd); int ret = 0; mutex_lock(&state->lock); if (on && !state->power) { ret = __s5c73m3_power_on(state); if (!ret) ret = s5c73m3_isp_init(state); if (!ret) { state->apply_fiv = 1; state->apply_fmt = 1; } } else if (state->power == !on) { ret = s5c73m3_set_af_softlanding(state); if (!ret) ret = __s5c73m3_power_off(state); else v4l2_err(sd, "Soft landing lens failed\n"); } if (!ret) state->power += on ? 1 : -1; v4l2_dbg(1, s5c73m3_dbg, sd, "%s: power: %d\n", __func__, state->power); mutex_unlock(&state->lock); return ret; } static int s5c73m3_oif_registered(struct v4l2_subdev *sd) { struct s5c73m3 *state = oif_sd_to_s5c73m3(sd); int ret; ret = v4l2_device_register_subdev(sd->v4l2_dev, &state->sensor_sd); if (ret) { v4l2_err(sd->v4l2_dev, "Failed to register %s\n", state->oif_sd.name); return ret; } ret = media_create_pad_link(&state->sensor_sd.entity, S5C73M3_ISP_PAD, &state->oif_sd.entity, OIF_ISP_PAD, MEDIA_LNK_FL_IMMUTABLE | MEDIA_LNK_FL_ENABLED); ret = media_create_pad_link(&state->sensor_sd.entity, S5C73M3_JPEG_PAD, &state->oif_sd.entity, OIF_JPEG_PAD, MEDIA_LNK_FL_IMMUTABLE | MEDIA_LNK_FL_ENABLED); return ret; } static void s5c73m3_oif_unregistered(struct v4l2_subdev *sd) { struct s5c73m3 *state = oif_sd_to_s5c73m3(sd); v4l2_device_unregister_subdev(&state->sensor_sd); } static const struct v4l2_subdev_internal_ops s5c73m3_internal_ops = { .open = s5c73m3_open, }; static const struct v4l2_subdev_pad_ops s5c73m3_pad_ops = { .enum_mbus_code = s5c73m3_enum_mbus_code, .enum_frame_size = s5c73m3_enum_frame_size, .get_fmt = s5c73m3_get_fmt, .set_fmt = s5c73m3_set_fmt, }; static const struct v4l2_subdev_ops s5c73m3_subdev_ops = { .pad = &s5c73m3_pad_ops, }; static const struct v4l2_subdev_internal_ops oif_internal_ops = { .registered = s5c73m3_oif_registered, .unregistered = s5c73m3_oif_unregistered, .open = s5c73m3_oif_open, }; static const struct v4l2_subdev_pad_ops s5c73m3_oif_pad_ops = { .enum_mbus_code = s5c73m3_oif_enum_mbus_code, .enum_frame_size = s5c73m3_oif_enum_frame_size, .enum_frame_interval = s5c73m3_oif_enum_frame_interval, .get_fmt = s5c73m3_oif_get_fmt, .set_fmt = s5c73m3_oif_set_fmt, .get_frame_desc = s5c73m3_oif_get_frame_desc, .set_frame_desc = s5c73m3_oif_set_frame_desc, }; static const struct v4l2_subdev_core_ops s5c73m3_oif_core_ops = { .s_power = s5c73m3_oif_set_power, .log_status = s5c73m3_oif_log_status, }; static const struct v4l2_subdev_video_ops s5c73m3_oif_video_ops = { .s_stream = s5c73m3_oif_s_stream, .g_frame_interval = s5c73m3_oif_g_frame_interval, .s_frame_interval = s5c73m3_oif_s_frame_interval, }; static const struct v4l2_subdev_ops oif_subdev_ops = { .core = &s5c73m3_oif_core_ops, .pad = &s5c73m3_oif_pad_ops, .video = &s5c73m3_oif_video_ops, }; static int s5c73m3_get_dt_data(struct s5c73m3 *state) { struct device *dev = &state->i2c_client->dev; struct device_node *node = dev->of_node; struct device_node *node_ep; struct v4l2_fwnode_endpoint ep = { .bus_type = 0 }; int ret; if (!node) return -EINVAL; state->clock = devm_clk_get(dev, S5C73M3_CLK_NAME); if (IS_ERR(state->clock)) return PTR_ERR(state->clock); if (of_property_read_u32(node, "clock-frequency", &state->mclk_frequency)) { state->mclk_frequency = S5C73M3_DEFAULT_MCLK_FREQ; dev_info(dev, "using default %u Hz clock frequency\n", state->mclk_frequency); } /* Request GPIO lines asserted */ state->stby = devm_gpiod_get(dev, "standby", GPIOD_OUT_HIGH); if (IS_ERR(state->stby)) return dev_err_probe(dev, PTR_ERR(state->stby), "failed to request gpio S5C73M3_STBY\n"); gpiod_set_consumer_name(state->stby, "S5C73M3_STBY"); state->reset = devm_gpiod_get(dev, "xshutdown", GPIOD_OUT_HIGH); if (IS_ERR(state->reset)) return dev_err_probe(dev, PTR_ERR(state->reset), "failed to request gpio S5C73M3_RST\n"); gpiod_set_consumer_name(state->reset, "S5C73M3_RST"); node_ep = of_graph_get_next_endpoint(node, NULL); if (!node_ep) { dev_warn(dev, "no endpoint defined for node: %pOF\n", node); return 0; } ret = v4l2_fwnode_endpoint_parse(of_fwnode_handle(node_ep), &ep); of_node_put(node_ep); if (ret) return ret; if (ep.bus_type != V4L2_MBUS_CSI2_DPHY) { dev_err(dev, "unsupported bus type\n"); return -EINVAL; } /* * Number of MIPI CSI-2 data lanes is currently not configurable, * always a default value of 4 lanes is used. */ if (ep.bus.mipi_csi2.num_data_lanes != S5C73M3_MIPI_DATA_LANES) dev_info(dev, "falling back to 4 MIPI CSI-2 data lanes\n"); return 0; } static int s5c73m3_probe(struct i2c_client *client) { struct device *dev = &client->dev; struct v4l2_subdev *sd; struct v4l2_subdev *oif_sd; struct s5c73m3 *state; int ret, i; state = devm_kzalloc(dev, sizeof(*state), GFP_KERNEL); if (!state) return -ENOMEM; state->i2c_client = client; ret = s5c73m3_get_dt_data(state); if (ret < 0) return ret; mutex_init(&state->lock); sd = &state->sensor_sd; oif_sd = &state->oif_sd; v4l2_subdev_init(sd, &s5c73m3_subdev_ops); sd->owner = client->dev.driver->owner; v4l2_set_subdevdata(sd, state); strscpy(sd->name, "S5C73M3", sizeof(sd->name)); sd->internal_ops = &s5c73m3_internal_ops; sd->flags |= V4L2_SUBDEV_FL_HAS_DEVNODE; state->sensor_pads[S5C73M3_JPEG_PAD].flags = MEDIA_PAD_FL_SOURCE; state->sensor_pads[S5C73M3_ISP_PAD].flags = MEDIA_PAD_FL_SOURCE; sd->entity.function = MEDIA_ENT_F_CAM_SENSOR; ret = media_entity_pads_init(&sd->entity, S5C73M3_NUM_PADS, state->sensor_pads); if (ret < 0) return ret; v4l2_i2c_subdev_init(oif_sd, client, &oif_subdev_ops); /* Static name; NEVER use in new drivers! */ strscpy(oif_sd->name, "S5C73M3-OIF", sizeof(oif_sd->name)); oif_sd->internal_ops = &oif_internal_ops; oif_sd->flags |= V4L2_SUBDEV_FL_HAS_DEVNODE; state->oif_pads[OIF_ISP_PAD].flags = MEDIA_PAD_FL_SINK; state->oif_pads[OIF_JPEG_PAD].flags = MEDIA_PAD_FL_SINK; state->oif_pads[OIF_SOURCE_PAD].flags = MEDIA_PAD_FL_SOURCE; oif_sd->entity.function = MEDIA_ENT_F_PROC_VIDEO_SCALER; ret = media_entity_pads_init(&oif_sd->entity, OIF_NUM_PADS, state->oif_pads); if (ret < 0) return ret; for (i = 0; i < S5C73M3_MAX_SUPPLIES; i++) state->supplies[i].supply = s5c73m3_supply_names[i]; ret = devm_regulator_bulk_get(dev, S5C73M3_MAX_SUPPLIES, state->supplies); if (ret) { dev_err(dev, "failed to get regulators\n"); goto out_err; } ret = s5c73m3_init_controls(state); if (ret) goto out_err; state->sensor_pix_size[RES_ISP] = &s5c73m3_isp_resolutions[1]; state->sensor_pix_size[RES_JPEG] = &s5c73m3_jpeg_resolutions[1]; state->oif_pix_size[RES_ISP] = state->sensor_pix_size[RES_ISP]; state->oif_pix_size[RES_JPEG] = state->sensor_pix_size[RES_JPEG]; state->mbus_code = S5C73M3_ISP_FMT; state->fiv = &s5c73m3_intervals[S5C73M3_DEFAULT_FRAME_INTERVAL]; state->fw_file_version[0] = 'G'; state->fw_file_version[1] = 'C'; ret = s5c73m3_register_spi_driver(state); if (ret < 0) goto out_err; oif_sd->dev = dev; ret = __s5c73m3_power_on(state); if (ret < 0) goto out_err1; ret = s5c73m3_get_fw_version(state); __s5c73m3_power_off(state); if (ret < 0) { dev_err(dev, "Device detection failed: %d\n", ret); goto out_err1; } ret = v4l2_async_register_subdev(oif_sd); if (ret < 0) goto out_err1; v4l2_info(sd, "%s: completed successfully\n", __func__); return 0; out_err1: s5c73m3_unregister_spi_driver(state); out_err: media_entity_cleanup(&sd->entity); return ret; } static void s5c73m3_remove(struct i2c_client *client) { struct v4l2_subdev *oif_sd = i2c_get_clientdata(client); struct s5c73m3 *state = oif_sd_to_s5c73m3(oif_sd); struct v4l2_subdev *sensor_sd = &state->sensor_sd; v4l2_async_unregister_subdev(oif_sd); v4l2_ctrl_handler_free(oif_sd->ctrl_handler); media_entity_cleanup(&oif_sd->entity); v4l2_device_unregister_subdev(sensor_sd); media_entity_cleanup(&sensor_sd->entity); s5c73m3_unregister_spi_driver(state); } static const struct i2c_device_id s5c73m3_id[] = { { DRIVER_NAME, 0 }, { } }; MODULE_DEVICE_TABLE(i2c, s5c73m3_id); #ifdef CONFIG_OF static const struct of_device_id s5c73m3_of_match[] = { { .compatible = "samsung,s5c73m3" }, { } }; MODULE_DEVICE_TABLE(of, s5c73m3_of_match); #endif static struct i2c_driver s5c73m3_i2c_driver = { .driver = { .of_match_table = of_match_ptr(s5c73m3_of_match), .name = DRIVER_NAME, }, .probe = s5c73m3_probe, .remove = s5c73m3_remove, .id_table = s5c73m3_id, }; module_i2c_driver(s5c73m3_i2c_driver); MODULE_DESCRIPTION("Samsung S5C73M3 camera driver"); MODULE_AUTHOR("Sylwester Nawrocki <[email protected]>"); MODULE_LICENSE("GPL");
linux-master
drivers/media/i2c/s5c73m3/s5c73m3-core.c
// SPDX-License-Identifier: GPL-2.0-only /* * Samsung LSI S5C73M3 8M pixel camera driver * * Copyright (C) 2012, Samsung Electronics, Co., Ltd. * Sylwester Nawrocki <[email protected]> * Andrzej Hajda <[email protected]> */ #include <linux/sizes.h> #include <linux/delay.h> #include <linux/init.h> #include <linux/media.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/spi/spi.h> #include "s5c73m3.h" #define S5C73M3_SPI_DRV_NAME "S5C73M3-SPI" static const struct of_device_id s5c73m3_spi_ids[] = { { .compatible = "samsung,s5c73m3" }, { } }; MODULE_DEVICE_TABLE(of, s5c73m3_spi_ids); enum spi_direction { SPI_DIR_RX, SPI_DIR_TX }; static int spi_xmit(struct spi_device *spi_dev, void *addr, const int len, enum spi_direction dir) { struct spi_message msg; int r; struct spi_transfer xfer = { .len = len, }; if (dir == SPI_DIR_TX) xfer.tx_buf = addr; else xfer.rx_buf = addr; if (spi_dev == NULL) { pr_err("SPI device is uninitialized\n"); return -ENODEV; } spi_message_init(&msg); spi_message_add_tail(&xfer, &msg); r = spi_sync(spi_dev, &msg); if (r < 0) dev_err(&spi_dev->dev, "%s spi_sync failed %d\n", __func__, r); return r; } int s5c73m3_spi_write(struct s5c73m3 *state, const void *addr, const unsigned int len, const unsigned int tx_size) { struct spi_device *spi_dev = state->spi_dev; u32 count = len / tx_size; u32 extra = len % tx_size; unsigned int i, j = 0; u8 padding[32]; int r = 0; memset(padding, 0, sizeof(padding)); for (i = 0; i < count; i++) { r = spi_xmit(spi_dev, (void *)addr + j, tx_size, SPI_DIR_TX); if (r < 0) return r; j += tx_size; } if (extra > 0) { r = spi_xmit(spi_dev, (void *)addr + j, extra, SPI_DIR_TX); if (r < 0) return r; } return spi_xmit(spi_dev, padding, sizeof(padding), SPI_DIR_TX); } int s5c73m3_spi_read(struct s5c73m3 *state, void *addr, const unsigned int len, const unsigned int tx_size) { struct spi_device *spi_dev = state->spi_dev; u32 count = len / tx_size; u32 extra = len % tx_size; unsigned int i, j = 0; int r = 0; for (i = 0; i < count; i++) { r = spi_xmit(spi_dev, addr + j, tx_size, SPI_DIR_RX); if (r < 0) return r; j += tx_size; } if (extra > 0) return spi_xmit(spi_dev, addr + j, extra, SPI_DIR_RX); return 0; } static int s5c73m3_spi_probe(struct spi_device *spi) { int r; struct s5c73m3 *state = container_of(spi->dev.driver, struct s5c73m3, spidrv.driver); spi->bits_per_word = 32; r = spi_setup(spi); if (r < 0) { dev_err(&spi->dev, "spi_setup() failed\n"); return r; } mutex_lock(&state->lock); state->spi_dev = spi; mutex_unlock(&state->lock); v4l2_info(&state->sensor_sd, "S5C73M3 SPI probed successfully\n"); return 0; } int s5c73m3_register_spi_driver(struct s5c73m3 *state) { struct spi_driver *spidrv = &state->spidrv; spidrv->probe = s5c73m3_spi_probe; spidrv->driver.name = S5C73M3_SPI_DRV_NAME; spidrv->driver.of_match_table = s5c73m3_spi_ids; return spi_register_driver(spidrv); } void s5c73m3_unregister_spi_driver(struct s5c73m3 *state) { spi_unregister_driver(&state->spidrv); }
linux-master
drivers/media/i2c/s5c73m3/s5c73m3-spi.c
// SPDX-License-Identifier: GPL-2.0-only /* * Samsung LSI S5C73M3 8M pixel camera driver * * Copyright (C) 2012, Samsung Electronics, Co., Ltd. * Sylwester Nawrocki <[email protected]> * Andrzej Hajda <[email protected]> */ #include <linux/sizes.h> #include <linux/delay.h> #include <linux/firmware.h> #include <linux/i2c.h> #include <linux/init.h> #include <linux/media.h> #include <linux/module.h> #include <linux/regulator/consumer.h> #include <linux/slab.h> #include <linux/spi/spi.h> #include <linux/videodev2.h> #include <media/media-entity.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-device.h> #include <media/v4l2-subdev.h> #include <media/v4l2-mediabus.h> #include "s5c73m3.h" static int s5c73m3_get_af_status(struct s5c73m3 *state, struct v4l2_ctrl *ctrl) { u16 reg = REG_AF_STATUS_UNFOCUSED; int ret = s5c73m3_read(state, REG_AF_STATUS, &reg); switch (reg) { case REG_CAF_STATUS_FIND_SEARCH_DIR: case REG_AF_STATUS_FOCUSING: case REG_CAF_STATUS_FOCUSING: ctrl->val = V4L2_AUTO_FOCUS_STATUS_BUSY; break; case REG_CAF_STATUS_FOCUSED: case REG_AF_STATUS_FOCUSED: ctrl->val = V4L2_AUTO_FOCUS_STATUS_REACHED; break; default: v4l2_info(&state->sensor_sd, "Unknown AF status %#x\n", reg); fallthrough; case REG_CAF_STATUS_UNFOCUSED: case REG_AF_STATUS_UNFOCUSED: case REG_AF_STATUS_INVALID: ctrl->val = V4L2_AUTO_FOCUS_STATUS_FAILED; break; } return ret; } static int s5c73m3_g_volatile_ctrl(struct v4l2_ctrl *ctrl) { struct v4l2_subdev *sd = ctrl_to_sensor_sd(ctrl); struct s5c73m3 *state = sensor_sd_to_s5c73m3(sd); int ret; if (state->power == 0) return -EBUSY; switch (ctrl->id) { case V4L2_CID_FOCUS_AUTO: ret = s5c73m3_get_af_status(state, state->ctrls.af_status); if (ret) return ret; break; } return 0; } static int s5c73m3_set_colorfx(struct s5c73m3 *state, int val) { static const unsigned short colorfx[][2] = { { V4L2_COLORFX_NONE, COMM_IMAGE_EFFECT_NONE }, { V4L2_COLORFX_BW, COMM_IMAGE_EFFECT_MONO }, { V4L2_COLORFX_SEPIA, COMM_IMAGE_EFFECT_SEPIA }, { V4L2_COLORFX_NEGATIVE, COMM_IMAGE_EFFECT_NEGATIVE }, { V4L2_COLORFX_AQUA, COMM_IMAGE_EFFECT_AQUA }, }; int i; for (i = 0; i < ARRAY_SIZE(colorfx); i++) { if (colorfx[i][0] != val) continue; v4l2_dbg(1, s5c73m3_dbg, &state->sensor_sd, "Setting %s color effect\n", v4l2_ctrl_get_menu(state->ctrls.colorfx->id)[i]); return s5c73m3_isp_command(state, COMM_IMAGE_EFFECT, colorfx[i][1]); } return -EINVAL; } /* Set exposure metering/exposure bias */ static int s5c73m3_set_exposure(struct s5c73m3 *state, int auto_exp) { struct v4l2_subdev *sd = &state->sensor_sd; struct s5c73m3_ctrls *ctrls = &state->ctrls; int ret = 0; if (ctrls->exposure_metering->is_new) { u16 metering; switch (ctrls->exposure_metering->val) { case V4L2_EXPOSURE_METERING_CENTER_WEIGHTED: metering = COMM_METERING_CENTER; break; case V4L2_EXPOSURE_METERING_SPOT: metering = COMM_METERING_SPOT; break; default: metering = COMM_METERING_AVERAGE; break; } ret = s5c73m3_isp_command(state, COMM_METERING, metering); } if (!ret && ctrls->exposure_bias->is_new) { u16 exp_bias = ctrls->exposure_bias->val; ret = s5c73m3_isp_command(state, COMM_EV, exp_bias); } v4l2_dbg(1, s5c73m3_dbg, sd, "%s: exposure bias: %#x, metering: %#x (%d)\n", __func__, ctrls->exposure_bias->val, ctrls->exposure_metering->val, ret); return ret; } static int s5c73m3_set_white_balance(struct s5c73m3 *state, int val) { static const unsigned short wb[][2] = { { V4L2_WHITE_BALANCE_INCANDESCENT, COMM_AWB_MODE_INCANDESCENT}, { V4L2_WHITE_BALANCE_FLUORESCENT, COMM_AWB_MODE_FLUORESCENT1}, { V4L2_WHITE_BALANCE_FLUORESCENT_H, COMM_AWB_MODE_FLUORESCENT2}, { V4L2_WHITE_BALANCE_CLOUDY, COMM_AWB_MODE_CLOUDY}, { V4L2_WHITE_BALANCE_DAYLIGHT, COMM_AWB_MODE_DAYLIGHT}, { V4L2_WHITE_BALANCE_AUTO, COMM_AWB_MODE_AUTO}, }; int i; for (i = 0; i < ARRAY_SIZE(wb); i++) { if (wb[i][0] != val) continue; v4l2_dbg(1, s5c73m3_dbg, &state->sensor_sd, "Setting white balance to: %s\n", v4l2_ctrl_get_menu(state->ctrls.auto_wb->id)[i]); return s5c73m3_isp_command(state, COMM_AWB_MODE, wb[i][1]); } return -EINVAL; } static int s5c73m3_af_run(struct s5c73m3 *state, bool on) { struct s5c73m3_ctrls *c = &state->ctrls; if (!on) return s5c73m3_isp_command(state, COMM_AF_CON, COMM_AF_CON_STOP); if (c->focus_auto->val) return s5c73m3_isp_command(state, COMM_AF_MODE, COMM_AF_MODE_PREVIEW_CAF_START); return s5c73m3_isp_command(state, COMM_AF_CON, COMM_AF_CON_START); } static int s5c73m3_3a_lock(struct s5c73m3 *state, struct v4l2_ctrl *ctrl) { bool awb_lock = ctrl->val & V4L2_LOCK_WHITE_BALANCE; bool ae_lock = ctrl->val & V4L2_LOCK_EXPOSURE; bool af_lock = ctrl->val & V4L2_LOCK_FOCUS; int ret = 0; if ((ctrl->val ^ ctrl->cur.val) & V4L2_LOCK_EXPOSURE) { ret = s5c73m3_isp_command(state, COMM_AE_CON, ae_lock ? COMM_AE_STOP : COMM_AE_START); if (ret) return ret; } if (((ctrl->val ^ ctrl->cur.val) & V4L2_LOCK_WHITE_BALANCE) && state->ctrls.auto_wb->val) { ret = s5c73m3_isp_command(state, COMM_AWB_CON, awb_lock ? COMM_AWB_STOP : COMM_AWB_START); if (ret) return ret; } if ((ctrl->val ^ ctrl->cur.val) & V4L2_LOCK_FOCUS) ret = s5c73m3_af_run(state, !af_lock); return ret; } static int s5c73m3_set_auto_focus(struct s5c73m3 *state, int caf) { struct s5c73m3_ctrls *c = &state->ctrls; int ret = 1; if (c->af_distance->is_new) { u16 mode = (c->af_distance->val == V4L2_AUTO_FOCUS_RANGE_MACRO) ? COMM_AF_MODE_MACRO : COMM_AF_MODE_NORMAL; ret = s5c73m3_isp_command(state, COMM_AF_MODE, mode); if (ret != 0) return ret; } if (!ret || (c->focus_auto->is_new && c->focus_auto->val) || c->af_start->is_new) ret = s5c73m3_af_run(state, 1); else if ((c->focus_auto->is_new && !c->focus_auto->val) || c->af_stop->is_new) ret = s5c73m3_af_run(state, 0); else ret = 0; return ret; } static int s5c73m3_set_contrast(struct s5c73m3 *state, int val) { u16 reg = (val < 0) ? -val + 2 : val; return s5c73m3_isp_command(state, COMM_CONTRAST, reg); } static int s5c73m3_set_saturation(struct s5c73m3 *state, int val) { u16 reg = (val < 0) ? -val + 2 : val; return s5c73m3_isp_command(state, COMM_SATURATION, reg); } static int s5c73m3_set_sharpness(struct s5c73m3 *state, int val) { u16 reg = (val < 0) ? -val + 2 : val; return s5c73m3_isp_command(state, COMM_SHARPNESS, reg); } static int s5c73m3_set_iso(struct s5c73m3 *state, int val) { u32 iso; if (val == V4L2_ISO_SENSITIVITY_MANUAL) iso = state->ctrls.iso->val + 1; else iso = 0; return s5c73m3_isp_command(state, COMM_ISO, iso); } static int s5c73m3_set_stabilization(struct s5c73m3 *state, int val) { struct v4l2_subdev *sd = &state->sensor_sd; v4l2_dbg(1, s5c73m3_dbg, sd, "Image stabilization: %d\n", val); return s5c73m3_isp_command(state, COMM_FRAME_RATE, val ? COMM_FRAME_RATE_ANTI_SHAKE : COMM_FRAME_RATE_AUTO_SET); } static int s5c73m3_set_jpeg_quality(struct s5c73m3 *state, int quality) { int reg; if (quality <= 65) reg = COMM_IMAGE_QUALITY_NORMAL; else if (quality <= 75) reg = COMM_IMAGE_QUALITY_FINE; else reg = COMM_IMAGE_QUALITY_SUPERFINE; return s5c73m3_isp_command(state, COMM_IMAGE_QUALITY, reg); } static int s5c73m3_set_scene_program(struct s5c73m3 *state, int val) { static const unsigned short scene_lookup[] = { COMM_SCENE_MODE_NONE, /* V4L2_SCENE_MODE_NONE */ COMM_SCENE_MODE_AGAINST_LIGHT,/* V4L2_SCENE_MODE_BACKLIGHT */ COMM_SCENE_MODE_BEACH, /* V4L2_SCENE_MODE_BEACH_SNOW */ COMM_SCENE_MODE_CANDLE, /* V4L2_SCENE_MODE_CANDLE_LIGHT */ COMM_SCENE_MODE_DAWN, /* V4L2_SCENE_MODE_DAWN_DUSK */ COMM_SCENE_MODE_FALL, /* V4L2_SCENE_MODE_FALL_COLORS */ COMM_SCENE_MODE_FIRE, /* V4L2_SCENE_MODE_FIREWORKS */ COMM_SCENE_MODE_LANDSCAPE, /* V4L2_SCENE_MODE_LANDSCAPE */ COMM_SCENE_MODE_NIGHT, /* V4L2_SCENE_MODE_NIGHT */ COMM_SCENE_MODE_INDOOR, /* V4L2_SCENE_MODE_PARTY_INDOOR */ COMM_SCENE_MODE_PORTRAIT, /* V4L2_SCENE_MODE_PORTRAIT */ COMM_SCENE_MODE_SPORTS, /* V4L2_SCENE_MODE_SPORTS */ COMM_SCENE_MODE_SUNSET, /* V4L2_SCENE_MODE_SUNSET */ COMM_SCENE_MODE_TEXT, /* V4L2_SCENE_MODE_TEXT */ }; v4l2_dbg(1, s5c73m3_dbg, &state->sensor_sd, "Setting %s scene mode\n", v4l2_ctrl_get_menu(state->ctrls.scene_mode->id)[val]); return s5c73m3_isp_command(state, COMM_SCENE_MODE, scene_lookup[val]); } static int s5c73m3_set_power_line_freq(struct s5c73m3 *state, int val) { unsigned int pwr_line_freq = COMM_FLICKER_NONE; switch (val) { case V4L2_CID_POWER_LINE_FREQUENCY_DISABLED: pwr_line_freq = COMM_FLICKER_NONE; break; case V4L2_CID_POWER_LINE_FREQUENCY_50HZ: pwr_line_freq = COMM_FLICKER_AUTO_50HZ; break; case V4L2_CID_POWER_LINE_FREQUENCY_60HZ: pwr_line_freq = COMM_FLICKER_AUTO_60HZ; break; default: case V4L2_CID_POWER_LINE_FREQUENCY_AUTO: pwr_line_freq = COMM_FLICKER_NONE; } return s5c73m3_isp_command(state, COMM_FLICKER_MODE, pwr_line_freq); } static int s5c73m3_s_ctrl(struct v4l2_ctrl *ctrl) { struct v4l2_subdev *sd = ctrl_to_sensor_sd(ctrl); struct s5c73m3 *state = sensor_sd_to_s5c73m3(sd); int ret = 0; v4l2_dbg(1, s5c73m3_dbg, sd, "set_ctrl: %s, value: %d\n", ctrl->name, ctrl->val); mutex_lock(&state->lock); /* * If the device is not powered up by the host driver do * not apply any controls to H/W at this time. Instead * the controls will be restored right after power-up. */ if (state->power == 0) goto unlock; if (ctrl->flags & V4L2_CTRL_FLAG_INACTIVE) { ret = -EINVAL; goto unlock; } switch (ctrl->id) { case V4L2_CID_3A_LOCK: ret = s5c73m3_3a_lock(state, ctrl); break; case V4L2_CID_AUTO_N_PRESET_WHITE_BALANCE: ret = s5c73m3_set_white_balance(state, ctrl->val); break; case V4L2_CID_CONTRAST: ret = s5c73m3_set_contrast(state, ctrl->val); break; case V4L2_CID_COLORFX: ret = s5c73m3_set_colorfx(state, ctrl->val); break; case V4L2_CID_EXPOSURE_AUTO: ret = s5c73m3_set_exposure(state, ctrl->val); break; case V4L2_CID_FOCUS_AUTO: ret = s5c73m3_set_auto_focus(state, ctrl->val); break; case V4L2_CID_IMAGE_STABILIZATION: ret = s5c73m3_set_stabilization(state, ctrl->val); break; case V4L2_CID_ISO_SENSITIVITY: ret = s5c73m3_set_iso(state, ctrl->val); break; case V4L2_CID_JPEG_COMPRESSION_QUALITY: ret = s5c73m3_set_jpeg_quality(state, ctrl->val); break; case V4L2_CID_POWER_LINE_FREQUENCY: ret = s5c73m3_set_power_line_freq(state, ctrl->val); break; case V4L2_CID_SATURATION: ret = s5c73m3_set_saturation(state, ctrl->val); break; case V4L2_CID_SCENE_MODE: ret = s5c73m3_set_scene_program(state, ctrl->val); break; case V4L2_CID_SHARPNESS: ret = s5c73m3_set_sharpness(state, ctrl->val); break; case V4L2_CID_WIDE_DYNAMIC_RANGE: ret = s5c73m3_isp_command(state, COMM_WDR, !!ctrl->val); break; case V4L2_CID_ZOOM_ABSOLUTE: ret = s5c73m3_isp_command(state, COMM_ZOOM_STEP, ctrl->val); break; } unlock: mutex_unlock(&state->lock); return ret; } static const struct v4l2_ctrl_ops s5c73m3_ctrl_ops = { .g_volatile_ctrl = s5c73m3_g_volatile_ctrl, .s_ctrl = s5c73m3_s_ctrl, }; /* Supported manual ISO values */ static const s64 iso_qmenu[] = { /* COMM_ISO: 0x0001...0x0004 */ 100, 200, 400, 800, }; /* Supported exposure bias values (-2.0EV...+2.0EV) */ static const s64 ev_bias_qmenu[] = { /* COMM_EV: 0x0000...0x0008 */ -2000, -1500, -1000, -500, 0, 500, 1000, 1500, 2000 }; int s5c73m3_init_controls(struct s5c73m3 *state) { const struct v4l2_ctrl_ops *ops = &s5c73m3_ctrl_ops; struct s5c73m3_ctrls *ctrls = &state->ctrls; struct v4l2_ctrl_handler *hdl = &ctrls->handler; int ret = v4l2_ctrl_handler_init(hdl, 22); if (ret) return ret; /* White balance */ ctrls->auto_wb = v4l2_ctrl_new_std_menu(hdl, ops, V4L2_CID_AUTO_N_PRESET_WHITE_BALANCE, 9, ~0x15e, V4L2_WHITE_BALANCE_AUTO); /* Exposure (only automatic exposure) */ ctrls->auto_exposure = v4l2_ctrl_new_std_menu(hdl, ops, V4L2_CID_EXPOSURE_AUTO, 0, ~0x01, V4L2_EXPOSURE_AUTO); ctrls->exposure_bias = v4l2_ctrl_new_int_menu(hdl, ops, V4L2_CID_AUTO_EXPOSURE_BIAS, ARRAY_SIZE(ev_bias_qmenu) - 1, ARRAY_SIZE(ev_bias_qmenu)/2 - 1, ev_bias_qmenu); ctrls->exposure_metering = v4l2_ctrl_new_std_menu(hdl, ops, V4L2_CID_EXPOSURE_METERING, 2, ~0x7, V4L2_EXPOSURE_METERING_AVERAGE); /* Auto focus */ ctrls->focus_auto = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_FOCUS_AUTO, 0, 1, 1, 0); ctrls->af_start = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_AUTO_FOCUS_START, 0, 1, 1, 0); ctrls->af_stop = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_AUTO_FOCUS_STOP, 0, 1, 1, 0); ctrls->af_status = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_AUTO_FOCUS_STATUS, 0, (V4L2_AUTO_FOCUS_STATUS_BUSY | V4L2_AUTO_FOCUS_STATUS_REACHED | V4L2_AUTO_FOCUS_STATUS_FAILED), 0, V4L2_AUTO_FOCUS_STATUS_IDLE); ctrls->af_distance = v4l2_ctrl_new_std_menu(hdl, ops, V4L2_CID_AUTO_FOCUS_RANGE, V4L2_AUTO_FOCUS_RANGE_MACRO, ~(1 << V4L2_AUTO_FOCUS_RANGE_NORMAL | 1 << V4L2_AUTO_FOCUS_RANGE_MACRO), V4L2_AUTO_FOCUS_RANGE_NORMAL); /* ISO sensitivity */ ctrls->auto_iso = v4l2_ctrl_new_std_menu(hdl, ops, V4L2_CID_ISO_SENSITIVITY_AUTO, 1, 0, V4L2_ISO_SENSITIVITY_AUTO); ctrls->iso = v4l2_ctrl_new_int_menu(hdl, ops, V4L2_CID_ISO_SENSITIVITY, ARRAY_SIZE(iso_qmenu) - 1, ARRAY_SIZE(iso_qmenu)/2 - 1, iso_qmenu); ctrls->contrast = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_CONTRAST, -2, 2, 1, 0); ctrls->saturation = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_SATURATION, -2, 2, 1, 0); ctrls->sharpness = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_SHARPNESS, -2, 2, 1, 0); ctrls->zoom = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_ZOOM_ABSOLUTE, 0, 30, 1, 0); ctrls->colorfx = v4l2_ctrl_new_std_menu(hdl, ops, V4L2_CID_COLORFX, V4L2_COLORFX_AQUA, ~0x40f, V4L2_COLORFX_NONE); ctrls->wdr = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_WIDE_DYNAMIC_RANGE, 0, 1, 1, 0); ctrls->stabilization = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_IMAGE_STABILIZATION, 0, 1, 1, 0); v4l2_ctrl_new_std_menu(hdl, ops, V4L2_CID_POWER_LINE_FREQUENCY, V4L2_CID_POWER_LINE_FREQUENCY_AUTO, 0, V4L2_CID_POWER_LINE_FREQUENCY_AUTO); ctrls->jpeg_quality = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_JPEG_COMPRESSION_QUALITY, 1, 100, 1, 80); ctrls->scene_mode = v4l2_ctrl_new_std_menu(hdl, ops, V4L2_CID_SCENE_MODE, V4L2_SCENE_MODE_TEXT, ~0x3fff, V4L2_SCENE_MODE_NONE); ctrls->aaa_lock = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_3A_LOCK, 0, 0x7, 0, 0); if (hdl->error) { ret = hdl->error; v4l2_ctrl_handler_free(hdl); return ret; } v4l2_ctrl_auto_cluster(3, &ctrls->auto_exposure, 0, false); ctrls->auto_iso->flags |= V4L2_CTRL_FLAG_VOLATILE | V4L2_CTRL_FLAG_UPDATE; v4l2_ctrl_auto_cluster(2, &ctrls->auto_iso, 0, false); ctrls->af_status->flags |= V4L2_CTRL_FLAG_VOLATILE; v4l2_ctrl_cluster(5, &ctrls->focus_auto); state->sensor_sd.ctrl_handler = hdl; return 0; }
linux-master
drivers/media/i2c/s5c73m3/s5c73m3-ctrls.c
// SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause /* * CCS static data binary parser library * * Copyright 2019--2020 Intel Corporation */ #include <linux/device.h> #include <linux/errno.h> #include <linux/limits.h> #include <linux/mm.h> #include <linux/slab.h> #include "ccs-data-defs.h" struct bin_container { void *base; void *now; void *end; size_t size; }; static void *bin_alloc(struct bin_container *bin, size_t len) { void *ptr; len = ALIGN(len, 8); if (bin->end - bin->now < len) return NULL; ptr = bin->now; bin->now += len; return ptr; } static void bin_reserve(struct bin_container *bin, size_t len) { bin->size += ALIGN(len, 8); } static int bin_backing_alloc(struct bin_container *bin) { bin->base = bin->now = kvzalloc(bin->size, GFP_KERNEL); if (!bin->base) return -ENOMEM; bin->end = bin->base + bin->size; return 0; } #define is_contained(var, endp) \ (sizeof(*var) <= (endp) - (void *)(var)) #define has_headroom(ptr, headroom, endp) \ ((headroom) <= (endp) - (void *)(ptr)) #define is_contained_with_headroom(var, headroom, endp) \ (sizeof(*var) + (headroom) <= (endp) - (void *)(var)) static int ccs_data_parse_length_specifier(const struct __ccs_data_length_specifier *__len, size_t *__hlen, size_t *__plen, const void *endp) { size_t hlen, plen; if (!is_contained(__len, endp)) return -ENODATA; switch (__len->length >> CCS_DATA_LENGTH_SPECIFIER_SIZE_SHIFT) { case CCS_DATA_LENGTH_SPECIFIER_1: hlen = sizeof(*__len); plen = __len->length & ((1 << CCS_DATA_LENGTH_SPECIFIER_SIZE_SHIFT) - 1); break; case CCS_DATA_LENGTH_SPECIFIER_2: { struct __ccs_data_length_specifier2 *__len2 = (void *)__len; if (!is_contained(__len2, endp)) return -ENODATA; hlen = sizeof(*__len2); plen = ((size_t) (__len2->length[0] & ((1 << CCS_DATA_LENGTH_SPECIFIER_SIZE_SHIFT) - 1)) << 8) + __len2->length[1]; break; } case CCS_DATA_LENGTH_SPECIFIER_3: { struct __ccs_data_length_specifier3 *__len3 = (void *)__len; if (!is_contained(__len3, endp)) return -ENODATA; hlen = sizeof(*__len3); plen = ((size_t) (__len3->length[0] & ((1 << CCS_DATA_LENGTH_SPECIFIER_SIZE_SHIFT) - 1)) << 16) + (__len3->length[0] << 8) + __len3->length[1]; break; } default: return -EINVAL; } if (!has_headroom(__len, hlen + plen, endp)) return -ENODATA; *__hlen = hlen; *__plen = plen; return 0; } static u8 ccs_data_parse_format_version(const struct __ccs_data_block *block) { return block->id >> CCS_DATA_BLOCK_HEADER_ID_VERSION_SHIFT; } static u8 ccs_data_parse_block_id(const struct __ccs_data_block *block, bool is_first) { if (!is_first) return block->id; return block->id & ((1 << CCS_DATA_BLOCK_HEADER_ID_VERSION_SHIFT) - 1); } static int ccs_data_parse_version(struct bin_container *bin, struct ccs_data_container *ccsdata, const void *payload, const void *endp) { const struct __ccs_data_block_version *v = payload; struct ccs_data_block_version *vv; if (v + 1 != endp) return -ENODATA; if (!bin->base) { bin_reserve(bin, sizeof(*ccsdata->version)); return 0; } ccsdata->version = bin_alloc(bin, sizeof(*ccsdata->version)); if (!ccsdata->version) return -ENOMEM; vv = ccsdata->version; vv->version_major = ((u16)v->static_data_version_major[0] << 8) + v->static_data_version_major[1]; vv->version_minor = ((u16)v->static_data_version_minor[0] << 8) + v->static_data_version_minor[1]; vv->date_year = ((u16)v->year[0] << 8) + v->year[1]; vv->date_month = v->month; vv->date_day = v->day; return 0; } static void print_ccs_data_version(struct device *dev, struct ccs_data_block_version *v) { dev_dbg(dev, "static data version %4.4x.%4.4x, date %4.4u-%2.2u-%2.2u\n", v->version_major, v->version_minor, v->date_year, v->date_month, v->date_day); } static int ccs_data_block_parse_header(const struct __ccs_data_block *block, bool is_first, unsigned int *__block_id, const void **payload, const struct __ccs_data_block **next_block, const void *endp, struct device *dev, bool verbose) { size_t plen, hlen; u8 block_id; int rval; if (!is_contained(block, endp)) return -ENODATA; rval = ccs_data_parse_length_specifier(&block->length, &hlen, &plen, endp); if (rval < 0) return rval; block_id = ccs_data_parse_block_id(block, is_first); if (verbose) dev_dbg(dev, "Block ID 0x%2.2x, header length %zu, payload length %zu\n", block_id, hlen, plen); if (!has_headroom(&block->length, hlen + plen, endp)) return -ENODATA; if (__block_id) *__block_id = block_id; if (payload) *payload = (void *)&block->length + hlen; if (next_block) *next_block = (void *)&block->length + hlen + plen; return 0; } static int ccs_data_parse_regs(struct bin_container *bin, struct ccs_reg **__regs, size_t *__num_regs, const void *payload, const void *endp, struct device *dev) { struct ccs_reg *regs_base = NULL, *regs = NULL; size_t num_regs = 0; u16 addr = 0; if (bin->base && __regs) { regs = regs_base = bin_alloc(bin, sizeof(*regs) * *__num_regs); if (!regs) return -ENOMEM; } while (payload < endp && num_regs < INT_MAX) { const struct __ccs_data_block_regs *r = payload; size_t len; const void *data; if (!is_contained(r, endp)) return -ENODATA; switch (r->reg_len >> CCS_DATA_BLOCK_REGS_SEL_SHIFT) { case CCS_DATA_BLOCK_REGS_SEL_REGS: addr += r->reg_len & CCS_DATA_BLOCK_REGS_ADDR_MASK; len = ((r->reg_len & CCS_DATA_BLOCK_REGS_LEN_MASK) >> CCS_DATA_BLOCK_REGS_LEN_SHIFT) + 1; if (!is_contained_with_headroom(r, len, endp)) return -ENODATA; data = r + 1; break; case CCS_DATA_BLOCK_REGS_SEL_REGS2: { const struct __ccs_data_block_regs2 *r2 = payload; if (!is_contained(r2, endp)) return -ENODATA; addr += ((u16)(r2->reg_len & CCS_DATA_BLOCK_REGS_2_ADDR_MASK) << 8) + r2->addr; len = ((r2->reg_len & CCS_DATA_BLOCK_REGS_2_LEN_MASK) >> CCS_DATA_BLOCK_REGS_2_LEN_SHIFT) + 1; if (!is_contained_with_headroom(r2, len, endp)) return -ENODATA; data = r2 + 1; break; } case CCS_DATA_BLOCK_REGS_SEL_REGS3: { const struct __ccs_data_block_regs3 *r3 = payload; if (!is_contained(r3, endp)) return -ENODATA; addr = ((u16)r3->addr[0] << 8) + r3->addr[1]; len = (r3->reg_len & CCS_DATA_BLOCK_REGS_3_LEN_MASK) + 1; if (!is_contained_with_headroom(r3, len, endp)) return -ENODATA; data = r3 + 1; break; } default: return -EINVAL; } num_regs++; if (!bin->base) { bin_reserve(bin, len); } else if (__regs) { if (!regs) return -EIO; regs->addr = addr; regs->len = len; regs->value = bin_alloc(bin, len); if (!regs->value) return -ENOMEM; memcpy(regs->value, data, len); regs++; } addr += len; payload = data + len; } if (!bin->base) bin_reserve(bin, sizeof(*regs) * num_regs); if (__num_regs) *__num_regs = num_regs; if (bin->base && __regs) { if (!regs_base) return -EIO; *__regs = regs_base; } return 0; } static int ccs_data_parse_reg_rules(struct bin_container *bin, struct ccs_reg **__regs, size_t *__num_regs, const void *payload, const void *endp, struct device *dev) { int rval; if (!bin->base) return ccs_data_parse_regs(bin, NULL, NULL, payload, endp, dev); rval = ccs_data_parse_regs(bin, NULL, __num_regs, payload, endp, dev); if (rval) return rval; return ccs_data_parse_regs(bin, __regs, __num_regs, payload, endp, dev); } static void assign_ffd_entry(struct ccs_frame_format_desc *desc, const struct __ccs_data_block_ffd_entry *ent) { desc->pixelcode = ent->pixelcode; desc->value = ((u16)ent->value[0] << 8) + ent->value[1]; } static int ccs_data_parse_ffd(struct bin_container *bin, struct ccs_frame_format_descs **ffd, const void *payload, const void *endp, struct device *dev) { const struct __ccs_data_block_ffd *__ffd = payload; const struct __ccs_data_block_ffd_entry *__entry; unsigned int i; if (!is_contained(__ffd, endp)) return -ENODATA; if ((void *)__ffd + sizeof(*__ffd) + ((u32)__ffd->num_column_descs + (u32)__ffd->num_row_descs) * sizeof(struct __ccs_data_block_ffd_entry) != endp) return -ENODATA; if (!bin->base) { bin_reserve(bin, sizeof(**ffd)); bin_reserve(bin, __ffd->num_column_descs * sizeof(struct ccs_frame_format_desc)); bin_reserve(bin, __ffd->num_row_descs * sizeof(struct ccs_frame_format_desc)); return 0; } *ffd = bin_alloc(bin, sizeof(**ffd)); if (!*ffd) return -ENOMEM; (*ffd)->num_column_descs = __ffd->num_column_descs; (*ffd)->num_row_descs = __ffd->num_row_descs; __entry = (void *)(__ffd + 1); (*ffd)->column_descs = bin_alloc(bin, __ffd->num_column_descs * sizeof(*(*ffd)->column_descs)); if (!(*ffd)->column_descs) return -ENOMEM; for (i = 0; i < __ffd->num_column_descs; i++, __entry++) assign_ffd_entry(&(*ffd)->column_descs[i], __entry); (*ffd)->row_descs = bin_alloc(bin, __ffd->num_row_descs * sizeof(*(*ffd)->row_descs)); if (!(*ffd)->row_descs) return -ENOMEM; for (i = 0; i < __ffd->num_row_descs; i++, __entry++) assign_ffd_entry(&(*ffd)->row_descs[i], __entry); if (__entry != endp) return -EPROTO; return 0; } static int ccs_data_parse_pdaf_readout(struct bin_container *bin, struct ccs_pdaf_readout **pdaf_readout, const void *payload, const void *endp, struct device *dev) { const struct __ccs_data_block_pdaf_readout *__pdaf = payload; if (!is_contained(__pdaf, endp)) return -ENODATA; if (!bin->base) { bin_reserve(bin, sizeof(**pdaf_readout)); } else { *pdaf_readout = bin_alloc(bin, sizeof(**pdaf_readout)); if (!*pdaf_readout) return -ENOMEM; (*pdaf_readout)->pdaf_readout_info_order = __pdaf->pdaf_readout_info_order; } return ccs_data_parse_ffd(bin, !bin->base ? NULL : &(*pdaf_readout)->ffd, __pdaf + 1, endp, dev); } static int ccs_data_parse_rules(struct bin_container *bin, struct ccs_rule **__rules, size_t *__num_rules, const void *payload, const void *endp, struct device *dev) { struct ccs_rule *rules_base = NULL, *rules = NULL, *next_rule = NULL; size_t num_rules = 0; const void *__next_rule = payload; int rval; if (bin->base) { rules_base = next_rule = bin_alloc(bin, sizeof(*rules) * *__num_rules); if (!rules_base) return -ENOMEM; } while (__next_rule < endp) { size_t rule_hlen, rule_plen, rule_plen2; const u8 *__rule_type; const void *rule_payload; /* Size of a single rule */ rval = ccs_data_parse_length_specifier(__next_rule, &rule_hlen, &rule_plen, endp); if (rval < 0) return rval; __rule_type = __next_rule + rule_hlen; if (!is_contained(__rule_type, endp)) return -ENODATA; rule_payload = __rule_type + 1; rule_plen2 = rule_plen - sizeof(*__rule_type); if (*__rule_type == CCS_DATA_BLOCK_RULE_ID_IF) { const struct __ccs_data_block_rule_if *__if_rules = rule_payload; const size_t __num_if_rules = rule_plen2 / sizeof(*__if_rules); struct ccs_if_rule *if_rule; if (!has_headroom(__if_rules, sizeof(*__if_rules) * __num_if_rules, rule_payload + rule_plen2)) return -ENODATA; /* Also check there is no extra data */ if (__if_rules + __num_if_rules != rule_payload + rule_plen2) return -EINVAL; if (!bin->base) { bin_reserve(bin, sizeof(*if_rule) * __num_if_rules); num_rules++; } else { unsigned int i; if (!next_rule) return -EIO; rules = next_rule; next_rule++; if_rule = bin_alloc(bin, sizeof(*if_rule) * __num_if_rules); if (!if_rule) return -ENOMEM; for (i = 0; i < __num_if_rules; i++) { if_rule[i].addr = ((u16)__if_rules[i].addr[0] << 8) + __if_rules[i].addr[1]; if_rule[i].value = __if_rules[i].value; if_rule[i].mask = __if_rules[i].mask; } rules->if_rules = if_rule; rules->num_if_rules = __num_if_rules; } } else { /* Check there was an if rule before any other rules */ if (bin->base && !rules) return -EINVAL; switch (*__rule_type) { case CCS_DATA_BLOCK_RULE_ID_READ_ONLY_REGS: rval = ccs_data_parse_reg_rules(bin, rules ? &rules->read_only_regs : NULL, rules ? &rules->num_read_only_regs : NULL, rule_payload, rule_payload + rule_plen2, dev); if (rval) return rval; break; case CCS_DATA_BLOCK_RULE_ID_FFD: rval = ccs_data_parse_ffd(bin, rules ? &rules->frame_format : NULL, rule_payload, rule_payload + rule_plen2, dev); if (rval) return rval; break; case CCS_DATA_BLOCK_RULE_ID_MSR: rval = ccs_data_parse_reg_rules(bin, rules ? &rules->manufacturer_regs : NULL, rules ? &rules->num_manufacturer_regs : NULL, rule_payload, rule_payload + rule_plen2, dev); if (rval) return rval; break; case CCS_DATA_BLOCK_RULE_ID_PDAF_READOUT: rval = ccs_data_parse_pdaf_readout(bin, rules ? &rules->pdaf_readout : NULL, rule_payload, rule_payload + rule_plen2, dev); if (rval) return rval; break; default: dev_dbg(dev, "Don't know how to handle rule type %u!\n", *__rule_type); return -EINVAL; } } __next_rule = __next_rule + rule_hlen + rule_plen; } if (!bin->base) { bin_reserve(bin, sizeof(*rules) * num_rules); *__num_rules = num_rules; } else { if (!rules_base) return -EIO; *__rules = rules_base; } return 0; } static int ccs_data_parse_pdaf(struct bin_container *bin, struct ccs_pdaf_pix_loc **pdaf, const void *payload, const void *endp, struct device *dev) { const struct __ccs_data_block_pdaf_pix_loc *__pdaf = payload; const struct __ccs_data_block_pdaf_pix_loc_block_desc_group *__bdesc_group; const struct __ccs_data_block_pdaf_pix_loc_pixel_desc *__pixel_desc; unsigned int i; u16 num_block_desc_groups; u8 max_block_type_id = 0; const u8 *__num_pixel_descs; if (!is_contained(__pdaf, endp)) return -ENODATA; if (bin->base) { *pdaf = bin_alloc(bin, sizeof(**pdaf)); if (!*pdaf) return -ENOMEM; } else { bin_reserve(bin, sizeof(**pdaf)); } num_block_desc_groups = ((u16)__pdaf->num_block_desc_groups[0] << 8) + __pdaf->num_block_desc_groups[1]; if (bin->base) { (*pdaf)->main_offset_x = ((u16)__pdaf->main_offset_x[0] << 8) + __pdaf->main_offset_x[1]; (*pdaf)->main_offset_y = ((u16)__pdaf->main_offset_y[0] << 8) + __pdaf->main_offset_y[1]; (*pdaf)->global_pdaf_type = __pdaf->global_pdaf_type; (*pdaf)->block_width = __pdaf->block_width; (*pdaf)->block_height = __pdaf->block_height; (*pdaf)->num_block_desc_groups = num_block_desc_groups; } __bdesc_group = (const void *)(__pdaf + 1); if (bin->base) { (*pdaf)->block_desc_groups = bin_alloc(bin, sizeof(struct ccs_pdaf_pix_loc_block_desc_group) * num_block_desc_groups); if (!(*pdaf)->block_desc_groups) return -ENOMEM; } else { bin_reserve(bin, sizeof(struct ccs_pdaf_pix_loc_block_desc_group) * num_block_desc_groups); } for (i = 0; i < num_block_desc_groups; i++) { const struct __ccs_data_block_pdaf_pix_loc_block_desc *__bdesc; u16 num_block_descs; unsigned int j; if (!is_contained(__bdesc_group, endp)) return -ENODATA; num_block_descs = ((u16)__bdesc_group->num_block_descs[0] << 8) + __bdesc_group->num_block_descs[1]; if (bin->base) { (*pdaf)->block_desc_groups[i].repeat_y = __bdesc_group->repeat_y; (*pdaf)->block_desc_groups[i].num_block_descs = num_block_descs; } __bdesc = (const void *)(__bdesc_group + 1); if (bin->base) { (*pdaf)->block_desc_groups[i].block_descs = bin_alloc(bin, sizeof(struct ccs_pdaf_pix_loc_block_desc) * num_block_descs); if (!(*pdaf)->block_desc_groups[i].block_descs) return -ENOMEM; } else { bin_reserve(bin, sizeof(struct ccs_pdaf_pix_loc_block_desc) * num_block_descs); } for (j = 0; j < num_block_descs; j++, __bdesc++) { struct ccs_pdaf_pix_loc_block_desc *bdesc; if (!is_contained(__bdesc, endp)) return -ENODATA; if (max_block_type_id <= __bdesc->block_type_id) max_block_type_id = __bdesc->block_type_id + 1; if (!bin->base) continue; bdesc = &(*pdaf)->block_desc_groups[i].block_descs[j]; bdesc->repeat_x = ((u16)__bdesc->repeat_x[0] << 8) + __bdesc->repeat_x[1]; if (__bdesc->block_type_id >= num_block_descs) return -EINVAL; bdesc->block_type_id = __bdesc->block_type_id; } __bdesc_group = (const void *)__bdesc; } __num_pixel_descs = (const void *)__bdesc_group; if (bin->base) { (*pdaf)->pixel_desc_groups = bin_alloc(bin, sizeof(struct ccs_pdaf_pix_loc_pixel_desc_group) * max_block_type_id); if (!(*pdaf)->pixel_desc_groups) return -ENOMEM; (*pdaf)->num_pixel_desc_grups = max_block_type_id; } else { bin_reserve(bin, sizeof(struct ccs_pdaf_pix_loc_pixel_desc_group) * max_block_type_id); } for (i = 0; i < max_block_type_id; i++) { struct ccs_pdaf_pix_loc_pixel_desc_group *pdgroup = NULL; unsigned int j; if (!is_contained(__num_pixel_descs, endp)) return -ENODATA; if (bin->base) { pdgroup = &(*pdaf)->pixel_desc_groups[i]; pdgroup->descs = bin_alloc(bin, sizeof(struct ccs_pdaf_pix_loc_pixel_desc) * *__num_pixel_descs); if (!pdgroup->descs) return -ENOMEM; pdgroup->num_descs = *__num_pixel_descs; } else { bin_reserve(bin, sizeof(struct ccs_pdaf_pix_loc_pixel_desc) * *__num_pixel_descs); } __pixel_desc = (const void *)(__num_pixel_descs + 1); for (j = 0; j < *__num_pixel_descs; j++, __pixel_desc++) { struct ccs_pdaf_pix_loc_pixel_desc *pdesc; if (!is_contained(__pixel_desc, endp)) return -ENODATA; if (!bin->base) continue; if (!pdgroup) return -EIO; pdesc = &pdgroup->descs[j]; pdesc->pixel_type = __pixel_desc->pixel_type; pdesc->small_offset_x = __pixel_desc->small_offset_x; pdesc->small_offset_y = __pixel_desc->small_offset_y; } __num_pixel_descs = (const void *)(__pixel_desc + 1); } return 0; } static int ccs_data_parse_license(struct bin_container *bin, char **__license, size_t *__license_length, const void *payload, const void *endp) { size_t size = endp - payload; char *license; if (!bin->base) { bin_reserve(bin, size); return 0; } license = bin_alloc(bin, size); if (!license) return -ENOMEM; memcpy(license, payload, size); *__license = license; *__license_length = size; return 0; } static int ccs_data_parse_end(bool *end, const void *payload, const void *endp, struct device *dev) { const struct __ccs_data_block_end *__end = payload; if (__end + 1 != endp) { dev_dbg(dev, "Invalid end block length %u\n", (unsigned int)(endp - payload)); return -ENODATA; } *end = true; return 0; } static int __ccs_data_parse(struct bin_container *bin, struct ccs_data_container *ccsdata, const void *data, size_t len, struct device *dev, bool verbose) { const struct __ccs_data_block *block = data; const struct __ccs_data_block *endp = data + len; unsigned int version; bool is_first = true; int rval; version = ccs_data_parse_format_version(block); if (version != CCS_STATIC_DATA_VERSION) { dev_dbg(dev, "Don't know how to handle version %u\n", version); return -EINVAL; } if (verbose) dev_dbg(dev, "Parsing CCS static data version %u\n", version); if (!bin->base) *ccsdata = (struct ccs_data_container){ 0 }; while (block < endp) { const struct __ccs_data_block *next_block; unsigned int block_id; const void *payload; rval = ccs_data_block_parse_header(block, is_first, &block_id, &payload, &next_block, endp, dev, bin->base ? false : verbose); if (rval < 0) return rval; switch (block_id) { case CCS_DATA_BLOCK_ID_DUMMY: break; case CCS_DATA_BLOCK_ID_DATA_VERSION: rval = ccs_data_parse_version(bin, ccsdata, payload, next_block); if (rval < 0) return rval; break; case CCS_DATA_BLOCK_ID_SENSOR_READ_ONLY_REGS: rval = ccs_data_parse_regs( bin, &ccsdata->sensor_read_only_regs, &ccsdata->num_sensor_read_only_regs, payload, next_block, dev); if (rval < 0) return rval; break; case CCS_DATA_BLOCK_ID_SENSOR_MANUFACTURER_REGS: rval = ccs_data_parse_regs( bin, &ccsdata->sensor_manufacturer_regs, &ccsdata->num_sensor_manufacturer_regs, payload, next_block, dev); if (rval < 0) return rval; break; case CCS_DATA_BLOCK_ID_MODULE_READ_ONLY_REGS: rval = ccs_data_parse_regs( bin, &ccsdata->module_read_only_regs, &ccsdata->num_module_read_only_regs, payload, next_block, dev); if (rval < 0) return rval; break; case CCS_DATA_BLOCK_ID_MODULE_MANUFACTURER_REGS: rval = ccs_data_parse_regs( bin, &ccsdata->module_manufacturer_regs, &ccsdata->num_module_manufacturer_regs, payload, next_block, dev); if (rval < 0) return rval; break; case CCS_DATA_BLOCK_ID_SENSOR_PDAF_PIXEL_LOCATION: rval = ccs_data_parse_pdaf(bin, &ccsdata->sensor_pdaf, payload, next_block, dev); if (rval < 0) return rval; break; case CCS_DATA_BLOCK_ID_MODULE_PDAF_PIXEL_LOCATION: rval = ccs_data_parse_pdaf(bin, &ccsdata->module_pdaf, payload, next_block, dev); if (rval < 0) return rval; break; case CCS_DATA_BLOCK_ID_SENSOR_RULE_BASED_BLOCK: rval = ccs_data_parse_rules( bin, &ccsdata->sensor_rules, &ccsdata->num_sensor_rules, payload, next_block, dev); if (rval < 0) return rval; break; case CCS_DATA_BLOCK_ID_MODULE_RULE_BASED_BLOCK: rval = ccs_data_parse_rules( bin, &ccsdata->module_rules, &ccsdata->num_module_rules, payload, next_block, dev); if (rval < 0) return rval; break; case CCS_DATA_BLOCK_ID_LICENSE: rval = ccs_data_parse_license(bin, &ccsdata->license, &ccsdata->license_length, payload, next_block); if (rval < 0) return rval; break; case CCS_DATA_BLOCK_ID_END: rval = ccs_data_parse_end(&ccsdata->end, payload, next_block, dev); if (rval < 0) return rval; break; default: dev_dbg(dev, "WARNING: not handling block ID 0x%2.2x\n", block_id); } block = next_block; is_first = false; } return 0; } /** * ccs_data_parse - Parse a CCS static data file into a usable in-memory * data structure * @ccsdata: CCS static data in-memory data structure * @data: CCS static data binary * @len: Length of @data * @dev: Device the data is related to (used for printing debug messages) * @verbose: Whether to be verbose or not */ int ccs_data_parse(struct ccs_data_container *ccsdata, const void *data, size_t len, struct device *dev, bool verbose) { struct bin_container bin = { 0 }; int rval; rval = __ccs_data_parse(&bin, ccsdata, data, len, dev, verbose); if (rval) return rval; rval = bin_backing_alloc(&bin); if (rval) return rval; rval = __ccs_data_parse(&bin, ccsdata, data, len, dev, false); if (rval) goto out_free; if (verbose && ccsdata->version) print_ccs_data_version(dev, ccsdata->version); if (bin.now != bin.end) { rval = -EPROTO; dev_dbg(dev, "parsing mismatch; base %p; now %p; end %p\n", bin.base, bin.now, bin.end); goto out_free; } ccsdata->backing = bin.base; return 0; out_free: kvfree(bin.base); return rval; }
linux-master
drivers/media/i2c/ccs/ccs-data.c
// SPDX-License-Identifier: GPL-2.0-only /* * drivers/media/i2c/ccs/ccs-reg-access.c * * Generic driver for MIPI CCS/SMIA/SMIA++ compliant camera sensors * * Copyright (C) 2020 Intel Corporation * Copyright (C) 2011--2012 Nokia Corporation * Contact: Sakari Ailus <[email protected]> */ #include <asm/unaligned.h> #include <linux/delay.h> #include <linux/i2c.h> #include "ccs.h" #include "ccs-limits.h" static u32 float_to_u32_mul_1000000(struct i2c_client *client, u32 phloat) { s32 exp; u64 man; if (phloat >= 0x80000000) { dev_err(&client->dev, "this is a negative number\n"); return 0; } if (phloat == 0x7f800000) return ~0; /* Inf. */ if ((phloat & 0x7f800000) == 0x7f800000) { dev_err(&client->dev, "NaN or other special number\n"); return 0; } /* Valid cases begin here */ if (phloat == 0) return 0; /* Valid zero */ if (phloat > 0x4f800000) return ~0; /* larger than 4294967295 */ /* * Unbias exponent (note how phloat is now guaranteed to * have 0 in the high bit) */ exp = ((int32_t)phloat >> 23) - 127; /* Extract mantissa, add missing '1' bit and it's in MHz */ man = ((phloat & 0x7fffff) | 0x800000) * 1000000ULL; if (exp < 0) man >>= -exp; else man <<= exp; man >>= 23; /* Remove mantissa bias */ return man & 0xffffffff; } /* * Read a 8/16/32-bit i2c register. The value is returned in 'val'. * Returns zero if successful, or non-zero otherwise. */ static int ____ccs_read_addr(struct ccs_sensor *sensor, u16 reg, u16 len, u32 *val) { struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd); struct i2c_msg msg; unsigned char data_buf[sizeof(u32)] = { 0 }; unsigned char offset_buf[sizeof(u16)]; int r; if (len > sizeof(data_buf)) return -EINVAL; msg.addr = client->addr; msg.flags = 0; msg.len = sizeof(offset_buf); msg.buf = offset_buf; put_unaligned_be16(reg, offset_buf); r = i2c_transfer(client->adapter, &msg, 1); if (r != 1) { if (r >= 0) r = -EBUSY; goto err; } msg.len = len; msg.flags = I2C_M_RD; msg.buf = &data_buf[sizeof(data_buf) - len]; r = i2c_transfer(client->adapter, &msg, 1); if (r != 1) { if (r >= 0) r = -EBUSY; goto err; } *val = get_unaligned_be32(data_buf); return 0; err: dev_err(&client->dev, "read from offset 0x%x error %d\n", reg, r); return r; } /* Read a register using 8-bit access only. */ static int ____ccs_read_addr_8only(struct ccs_sensor *sensor, u16 reg, u16 len, u32 *val) { unsigned int i; int rval; *val = 0; for (i = 0; i < len; i++) { u32 val8; rval = ____ccs_read_addr(sensor, reg + i, 1, &val8); if (rval < 0) return rval; *val |= val8 << ((len - i - 1) << 3); } return 0; } unsigned int ccs_reg_width(u32 reg) { if (reg & CCS_FL_16BIT) return sizeof(u16); if (reg & CCS_FL_32BIT) return sizeof(u32); return sizeof(u8); } static u32 ireal32_to_u32_mul_1000000(struct i2c_client *client, u32 val) { if (val >> 10 > U32_MAX / 15625) { dev_warn(&client->dev, "value %u overflows!\n", val); return U32_MAX; } return ((val >> 10) * 15625) + (val & GENMASK(9, 0)) * 15625 / 1024; } u32 ccs_reg_conv(struct ccs_sensor *sensor, u32 reg, u32 val) { struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd); if (reg & CCS_FL_FLOAT_IREAL) { if (CCS_LIM(sensor, CLOCK_CAPA_TYPE_CAPABILITY) & CCS_CLOCK_CAPA_TYPE_CAPABILITY_IREAL) val = ireal32_to_u32_mul_1000000(client, val); else val = float_to_u32_mul_1000000(client, val); } else if (reg & CCS_FL_IREAL) { val = ireal32_to_u32_mul_1000000(client, val); } return val; } /* * Read a 8/16/32-bit i2c register. The value is returned in 'val'. * Returns zero if successful, or non-zero otherwise. */ static int __ccs_read_addr(struct ccs_sensor *sensor, u32 reg, u32 *val, bool only8, bool conv) { unsigned int len = ccs_reg_width(reg); int rval; if (!only8) rval = ____ccs_read_addr(sensor, CCS_REG_ADDR(reg), len, val); else rval = ____ccs_read_addr_8only(sensor, CCS_REG_ADDR(reg), len, val); if (rval < 0) return rval; if (!conv) return 0; *val = ccs_reg_conv(sensor, reg, *val); return 0; } static int __ccs_read_data(struct ccs_reg *regs, size_t num_regs, u32 reg, u32 *val) { unsigned int width = ccs_reg_width(reg); size_t i; for (i = 0; i < num_regs; i++, regs++) { u8 *data; if (regs->addr + regs->len < CCS_REG_ADDR(reg) + width) continue; if (regs->addr > CCS_REG_ADDR(reg)) break; data = &regs->value[CCS_REG_ADDR(reg) - regs->addr]; switch (width) { case sizeof(u8): *val = *data; break; case sizeof(u16): *val = get_unaligned_be16(data); break; case sizeof(u32): *val = get_unaligned_be32(data); break; default: WARN_ON(1); return -EINVAL; } return 0; } return -ENOENT; } static int ccs_read_data(struct ccs_sensor *sensor, u32 reg, u32 *val) { if (!__ccs_read_data(sensor->sdata.sensor_read_only_regs, sensor->sdata.num_sensor_read_only_regs, reg, val)) return 0; return __ccs_read_data(sensor->mdata.module_read_only_regs, sensor->mdata.num_module_read_only_regs, reg, val); } static int ccs_read_addr_raw(struct ccs_sensor *sensor, u32 reg, u32 *val, bool force8, bool quirk, bool conv, bool data) { int rval; if (data) { rval = ccs_read_data(sensor, reg, val); if (!rval) return 0; } if (quirk) { *val = 0; rval = ccs_call_quirk(sensor, reg_access, false, &reg, val); if (rval == -ENOIOCTLCMD) return 0; if (rval < 0) return rval; if (force8) return __ccs_read_addr(sensor, reg, val, true, conv); } return __ccs_read_addr(sensor, reg, val, ccs_needs_quirk(sensor, CCS_QUIRK_FLAG_8BIT_READ_ONLY), conv); } int ccs_read_addr(struct ccs_sensor *sensor, u32 reg, u32 *val) { return ccs_read_addr_raw(sensor, reg, val, false, true, true, true); } int ccs_read_addr_8only(struct ccs_sensor *sensor, u32 reg, u32 *val) { return ccs_read_addr_raw(sensor, reg, val, true, true, true, true); } int ccs_read_addr_noconv(struct ccs_sensor *sensor, u32 reg, u32 *val) { return ccs_read_addr_raw(sensor, reg, val, false, true, false, true); } static int ccs_write_retry(struct i2c_client *client, struct i2c_msg *msg) { unsigned int retries; int r; for (retries = 0; retries < 10; retries++) { /* * Due to unknown reason sensor stops responding. This * loop is a temporaty solution until the root cause * is found. */ r = i2c_transfer(client->adapter, msg, 1); if (r != 1) { usleep_range(1000, 2000); continue; } if (retries) dev_err(&client->dev, "sensor i2c stall encountered. retries: %d\n", retries); return 0; } return r; } int ccs_write_addr_no_quirk(struct ccs_sensor *sensor, u32 reg, u32 val) { struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd); struct i2c_msg msg; unsigned char data[6]; unsigned int len = ccs_reg_width(reg); int r; if (len > sizeof(data) - 2) return -EINVAL; msg.addr = client->addr; msg.flags = 0; /* Write */ msg.len = 2 + len; msg.buf = data; put_unaligned_be16(CCS_REG_ADDR(reg), data); put_unaligned_be32(val << (8 * (sizeof(val) - len)), data + 2); dev_dbg(&client->dev, "writing reg 0x%4.4x value 0x%*.*x (%u)\n", CCS_REG_ADDR(reg), ccs_reg_width(reg) << 1, ccs_reg_width(reg) << 1, val, val); r = ccs_write_retry(client, &msg); if (r) dev_err(&client->dev, "wrote 0x%x to offset 0x%x error %d\n", val, CCS_REG_ADDR(reg), r); return r; } /* * Write to a 8/16-bit register. * Returns zero if successful, or non-zero otherwise. */ int ccs_write_addr(struct ccs_sensor *sensor, u32 reg, u32 val) { int rval; rval = ccs_call_quirk(sensor, reg_access, true, &reg, &val); if (rval == -ENOIOCTLCMD) return 0; if (rval < 0) return rval; return ccs_write_addr_no_quirk(sensor, reg, val); } #define MAX_WRITE_LEN 32U int ccs_write_data_regs(struct ccs_sensor *sensor, struct ccs_reg *regs, size_t num_regs) { struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd); unsigned char buf[2 + MAX_WRITE_LEN]; struct i2c_msg msg = { .addr = client->addr, .buf = buf, }; size_t i; for (i = 0; i < num_regs; i++, regs++) { unsigned char *regdata = regs->value; unsigned int j; for (j = 0; j < regs->len; j += msg.len - 2, regdata += msg.len - 2) { char printbuf[(MAX_WRITE_LEN << 1) + 1 /* \0 */] = { 0 }; int rval; msg.len = min(regs->len - j, MAX_WRITE_LEN); bin2hex(printbuf, regdata, msg.len); dev_dbg(&client->dev, "writing msr reg 0x%4.4x value 0x%s\n", regs->addr + j, printbuf); put_unaligned_be16(regs->addr + j, buf); memcpy(buf + 2, regdata, msg.len); msg.len += 2; rval = ccs_write_retry(client, &msg); if (rval) { dev_err(&client->dev, "error writing %u octets to address 0x%4.4x\n", msg.len, regs->addr + j); return rval; } } } return 0; }
linux-master
drivers/media/i2c/ccs/ccs-reg-access.c
// SPDX-License-Identifier: GPL-2.0-only /* * drivers/media/i2c/ccs/ccs-quirk.c * * Generic driver for MIPI CCS/SMIA/SMIA++ compliant camera sensors * * Copyright (C) 2020 Intel Corporation * Copyright (C) 2011--2012 Nokia Corporation * Contact: Sakari Ailus <[email protected]> */ #include <linux/delay.h> #include "ccs.h" #include "ccs-limits.h" static int ccs_write_addr_8s(struct ccs_sensor *sensor, const struct ccs_reg_8 *regs, int len) { struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd); int rval; for (; len > 0; len--, regs++) { rval = ccs_write_addr(sensor, regs->reg, regs->val); if (rval < 0) { dev_err(&client->dev, "error %d writing reg 0x%4.4x, val 0x%2.2x", rval, regs->reg, regs->val); return rval; } } return 0; } static int jt8ew9_limits(struct ccs_sensor *sensor) { if (sensor->minfo.revision_number < 0x0300) sensor->frame_skip = 1; /* Below 24 gain doesn't have effect at all, */ /* but ~59 is needed for full dynamic range */ ccs_replace_limit(sensor, CCS_L_ANALOG_GAIN_CODE_MIN, 0, 59); ccs_replace_limit(sensor, CCS_L_ANALOG_GAIN_CODE_MAX, 0, 6000); return 0; } static int jt8ew9_post_poweron(struct ccs_sensor *sensor) { static const struct ccs_reg_8 regs[] = { { 0x30a3, 0xd8 }, /* Output port control : LVDS ports only */ { 0x30ae, 0x00 }, /* 0x0307 pll_multiplier maximum value on PLL input 9.6MHz ( 19.2MHz is divided on pre_pll_div) */ { 0x30af, 0xd0 }, /* 0x0307 pll_multiplier maximum value on PLL input 9.6MHz ( 19.2MHz is divided on pre_pll_div) */ { 0x322d, 0x04 }, /* Adjusting Processing Image Size to Scaler Toshiba Recommendation Setting */ { 0x3255, 0x0f }, /* Horizontal Noise Reduction Control Toshiba Recommendation Setting */ { 0x3256, 0x15 }, /* Horizontal Noise Reduction Control Toshiba Recommendation Setting */ { 0x3258, 0x70 }, /* Analog Gain Control Toshiba Recommendation Setting */ { 0x3259, 0x70 }, /* Analog Gain Control Toshiba Recommendation Setting */ { 0x325f, 0x7c }, /* Analog Gain Control Toshiba Recommendation Setting */ { 0x3302, 0x06 }, /* Pixel Reference Voltage Control Toshiba Recommendation Setting */ { 0x3304, 0x00 }, /* Pixel Reference Voltage Control Toshiba Recommendation Setting */ { 0x3307, 0x22 }, /* Pixel Reference Voltage Control Toshiba Recommendation Setting */ { 0x3308, 0x8d }, /* Pixel Reference Voltage Control Toshiba Recommendation Setting */ { 0x331e, 0x0f }, /* Black Hole Sun Correction Control Toshiba Recommendation Setting */ { 0x3320, 0x30 }, /* Black Hole Sun Correction Control Toshiba Recommendation Setting */ { 0x3321, 0x11 }, /* Black Hole Sun Correction Control Toshiba Recommendation Setting */ { 0x3322, 0x98 }, /* Black Hole Sun Correction Control Toshiba Recommendation Setting */ { 0x3323, 0x64 }, /* Black Hole Sun Correction Control Toshiba Recommendation Setting */ { 0x3325, 0x83 }, /* Read Out Timing Control Toshiba Recommendation Setting */ { 0x3330, 0x18 }, /* Read Out Timing Control Toshiba Recommendation Setting */ { 0x333c, 0x01 }, /* Read Out Timing Control Toshiba Recommendation Setting */ { 0x3345, 0x2f }, /* Black Hole Sun Correction Control Toshiba Recommendation Setting */ { 0x33de, 0x38 }, /* Horizontal Noise Reduction Control Toshiba Recommendation Setting */ /* Taken from v03. No idea what the rest are. */ { 0x32e0, 0x05 }, { 0x32e1, 0x05 }, { 0x32e2, 0x04 }, { 0x32e5, 0x04 }, { 0x32e6, 0x04 }, }; return ccs_write_addr_8s(sensor, regs, ARRAY_SIZE(regs)); } const struct ccs_quirk smiapp_jt8ew9_quirk = { .limits = jt8ew9_limits, .post_poweron = jt8ew9_post_poweron, }; static int imx125es_post_poweron(struct ccs_sensor *sensor) { /* Taken from v02. No idea what the other two are. */ static const struct ccs_reg_8 regs[] = { /* * 0x3302: clk during frame blanking: * 0x00 - HS mode, 0x01 - LP11 */ { 0x3302, 0x01 }, { 0x302d, 0x00 }, { 0x3b08, 0x8c }, }; return ccs_write_addr_8s(sensor, regs, ARRAY_SIZE(regs)); } const struct ccs_quirk smiapp_imx125es_quirk = { .post_poweron = imx125es_post_poweron, }; static int jt8ev1_limits(struct ccs_sensor *sensor) { ccs_replace_limit(sensor, CCS_L_X_ADDR_MAX, 0, 4271); ccs_replace_limit(sensor, CCS_L_MIN_LINE_BLANKING_PCK_BIN, 0, 184); return 0; } static int jt8ev1_post_poweron(struct ccs_sensor *sensor) { struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd); int rval; static const struct ccs_reg_8 regs[] = { { 0x3031, 0xcd }, /* For digital binning (EQ_MONI) */ { 0x30a3, 0xd0 }, /* FLASH STROBE enable */ { 0x3237, 0x00 }, /* For control of pulse timing for ADC */ { 0x3238, 0x43 }, { 0x3301, 0x06 }, /* For analog bias for sensor */ { 0x3302, 0x06 }, { 0x3304, 0x00 }, { 0x3305, 0x88 }, { 0x332a, 0x14 }, { 0x332c, 0x6b }, { 0x3336, 0x01 }, { 0x333f, 0x1f }, { 0x3355, 0x00 }, { 0x3356, 0x20 }, { 0x33bf, 0x20 }, /* Adjust the FBC speed */ { 0x33c9, 0x20 }, { 0x33ce, 0x30 }, /* Adjust the parameter for logic function */ { 0x33cf, 0xec }, /* For Black sun */ { 0x3328, 0x80 }, /* Ugh. No idea what's this. */ }; static const struct ccs_reg_8 regs_96[] = { { 0x30ae, 0x00 }, /* For control of ADC clock */ { 0x30af, 0xd0 }, { 0x30b0, 0x01 }, }; rval = ccs_write_addr_8s(sensor, regs, ARRAY_SIZE(regs)); if (rval < 0) return rval; switch (sensor->hwcfg.ext_clk) { case 9600000: return ccs_write_addr_8s(sensor, regs_96, ARRAY_SIZE(regs_96)); default: dev_warn(&client->dev, "no MSRs for %d Hz ext_clk\n", sensor->hwcfg.ext_clk); return 0; } } static int jt8ev1_pre_streamon(struct ccs_sensor *sensor) { return ccs_write_addr(sensor, 0x3328, 0x00); } static int jt8ev1_post_streamoff(struct ccs_sensor *sensor) { int rval; /* Workaround: allows fast standby to work properly */ rval = ccs_write_addr(sensor, 0x3205, 0x04); if (rval < 0) return rval; /* Wait for 1 ms + one line => 2 ms is likely enough */ usleep_range(2000, 2050); /* Restore it */ rval = ccs_write_addr(sensor, 0x3205, 0x00); if (rval < 0) return rval; return ccs_write_addr(sensor, 0x3328, 0x80); } static int jt8ev1_init(struct ccs_sensor *sensor) { sensor->pll.flags |= CCS_PLL_FLAG_LANE_SPEED_MODEL | CCS_PLL_FLAG_LINK_DECOUPLED; sensor->pll.vt_lanes = 1; sensor->pll.op_lanes = sensor->pll.csi2.lanes; return 0; } const struct ccs_quirk smiapp_jt8ev1_quirk = { .limits = jt8ev1_limits, .post_poweron = jt8ev1_post_poweron, .pre_streamon = jt8ev1_pre_streamon, .post_streamoff = jt8ev1_post_streamoff, .init = jt8ev1_init, }; static int tcm8500md_limits(struct ccs_sensor *sensor) { ccs_replace_limit(sensor, CCS_L_MIN_PLL_IP_CLK_FREQ_MHZ, 0, 2700000); return 0; } const struct ccs_quirk smiapp_tcm8500md_quirk = { .limits = tcm8500md_limits, };
linux-master
drivers/media/i2c/ccs/ccs-quirk.c
// SPDX-License-Identifier: GPL-2.0-only OR BSD-3-Clause /* Copyright (C) 2019--2020 Intel Corporation */ /* * Generated by Documentation/driver-api/media/drivers/ccs/mk-ccs-regs; * do not modify. */ #include "ccs-limits.h" #include "ccs-regs.h" const struct ccs_limit ccs_limits[] = { { CCS_R_FRAME_FORMAT_MODEL_TYPE, 1, 0, "frame_format_model_type" }, { CCS_R_FRAME_FORMAT_MODEL_SUBTYPE, 1, 0, "frame_format_model_subtype" }, { CCS_R_FRAME_FORMAT_DESCRIPTOR(0), 30, 0, "frame_format_descriptor" }, { CCS_R_FRAME_FORMAT_DESCRIPTOR_4(0), 32, 0, "frame_format_descriptor_4" }, { CCS_R_ANALOG_GAIN_CAPABILITY, 2, 0, "analog_gain_capability" }, { CCS_R_ANALOG_GAIN_CODE_MIN, 2, 0, "analog_gain_code_min" }, { CCS_R_ANALOG_GAIN_CODE_MAX, 2, 0, "analog_gain_code_max" }, { CCS_R_ANALOG_GAIN_CODE_STEP, 2, 0, "analog_gain_code_step" }, { CCS_R_ANALOG_GAIN_TYPE, 2, 0, "analog_gain_type" }, { CCS_R_ANALOG_GAIN_M0, 2, 0, "analog_gain_m0" }, { CCS_R_ANALOG_GAIN_C0, 2, 0, "analog_gain_c0" }, { CCS_R_ANALOG_GAIN_M1, 2, 0, "analog_gain_m1" }, { CCS_R_ANALOG_GAIN_C1, 2, 0, "analog_gain_c1" }, { CCS_R_ANALOG_LINEAR_GAIN_MIN, 2, 0, "analog_linear_gain_min" }, { CCS_R_ANALOG_LINEAR_GAIN_MAX, 2, 0, "analog_linear_gain_max" }, { CCS_R_ANALOG_LINEAR_GAIN_STEP_SIZE, 2, 0, "analog_linear_gain_step_size" }, { CCS_R_ANALOG_EXPONENTIAL_GAIN_MIN, 2, 0, "analog_exponential_gain_min" }, { CCS_R_ANALOG_EXPONENTIAL_GAIN_MAX, 2, 0, "analog_exponential_gain_max" }, { CCS_R_ANALOG_EXPONENTIAL_GAIN_STEP_SIZE, 2, 0, "analog_exponential_gain_step_size" }, { CCS_R_DATA_FORMAT_MODEL_TYPE, 1, 0, "data_format_model_type" }, { CCS_R_DATA_FORMAT_MODEL_SUBTYPE, 1, 0, "data_format_model_subtype" }, { CCS_R_DATA_FORMAT_DESCRIPTOR(0), 32, 0, "data_format_descriptor" }, { CCS_R_INTEGRATION_TIME_CAPABILITY, 2, 0, "integration_time_capability" }, { CCS_R_COARSE_INTEGRATION_TIME_MIN, 2, 0, "coarse_integration_time_min" }, { CCS_R_COARSE_INTEGRATION_TIME_MAX_MARGIN, 2, 0, "coarse_integration_time_max_margin" }, { CCS_R_FINE_INTEGRATION_TIME_MIN, 2, 0, "fine_integration_time_min" }, { CCS_R_FINE_INTEGRATION_TIME_MAX_MARGIN, 2, 0, "fine_integration_time_max_margin" }, { CCS_R_DIGITAL_GAIN_CAPABILITY, 1, 0, "digital_gain_capability" }, { CCS_R_DIGITAL_GAIN_MIN, 2, 0, "digital_gain_min" }, { CCS_R_DIGITAL_GAIN_MAX, 2, 0, "digital_gain_max" }, { CCS_R_DIGITAL_GAIN_STEP_SIZE, 2, 0, "digital_gain_step_size" }, { CCS_R_PEDESTAL_CAPABILITY, 1, 0, "Pedestal_capability" }, { CCS_R_ADC_CAPABILITY, 1, 0, "ADC_capability" }, { CCS_R_ADC_BIT_DEPTH_CAPABILITY, 4, 0, "ADC_bit_depth_capability" }, { CCS_R_MIN_EXT_CLK_FREQ_MHZ, 4, 0, "min_ext_clk_freq_mhz" }, { CCS_R_MAX_EXT_CLK_FREQ_MHZ, 4, 0, "max_ext_clk_freq_mhz" }, { CCS_R_MIN_PRE_PLL_CLK_DIV, 2, 0, "min_pre_pll_clk_div" }, { CCS_R_MAX_PRE_PLL_CLK_DIV, 2, 0, "max_pre_pll_clk_div" }, { CCS_R_MIN_PLL_IP_CLK_FREQ_MHZ, 4, 0, "min_pll_ip_clk_freq_mhz" }, { CCS_R_MAX_PLL_IP_CLK_FREQ_MHZ, 4, 0, "max_pll_ip_clk_freq_mhz" }, { CCS_R_MIN_PLL_MULTIPLIER, 2, 0, "min_pll_multiplier" }, { CCS_R_MAX_PLL_MULTIPLIER, 2, 0, "max_pll_multiplier" }, { CCS_R_MIN_PLL_OP_CLK_FREQ_MHZ, 4, 0, "min_pll_op_clk_freq_mhz" }, { CCS_R_MAX_PLL_OP_CLK_FREQ_MHZ, 4, 0, "max_pll_op_clk_freq_mhz" }, { CCS_R_MIN_VT_SYS_CLK_DIV, 2, 0, "min_vt_sys_clk_div" }, { CCS_R_MAX_VT_SYS_CLK_DIV, 2, 0, "max_vt_sys_clk_div" }, { CCS_R_MIN_VT_SYS_CLK_FREQ_MHZ, 4, 0, "min_vt_sys_clk_freq_mhz" }, { CCS_R_MAX_VT_SYS_CLK_FREQ_MHZ, 4, 0, "max_vt_sys_clk_freq_mhz" }, { CCS_R_MIN_VT_PIX_CLK_FREQ_MHZ, 4, 0, "min_vt_pix_clk_freq_mhz" }, { CCS_R_MAX_VT_PIX_CLK_FREQ_MHZ, 4, 0, "max_vt_pix_clk_freq_mhz" }, { CCS_R_MIN_VT_PIX_CLK_DIV, 2, 0, "min_vt_pix_clk_div" }, { CCS_R_MAX_VT_PIX_CLK_DIV, 2, 0, "max_vt_pix_clk_div" }, { CCS_R_CLOCK_CALCULATION, 1, 0, "clock_calculation" }, { CCS_R_NUM_OF_VT_LANES, 1, 0, "num_of_vt_lanes" }, { CCS_R_NUM_OF_OP_LANES, 1, 0, "num_of_op_lanes" }, { CCS_R_OP_BITS_PER_LANE, 1, 0, "op_bits_per_lane" }, { CCS_R_MIN_FRAME_LENGTH_LINES, 2, 0, "min_frame_length_lines" }, { CCS_R_MAX_FRAME_LENGTH_LINES, 2, 0, "max_frame_length_lines" }, { CCS_R_MIN_LINE_LENGTH_PCK, 2, 0, "min_line_length_pck" }, { CCS_R_MAX_LINE_LENGTH_PCK, 2, 0, "max_line_length_pck" }, { CCS_R_MIN_LINE_BLANKING_PCK, 2, 0, "min_line_blanking_pck" }, { CCS_R_MIN_FRAME_BLANKING_LINES, 2, 0, "min_frame_blanking_lines" }, { CCS_R_MIN_LINE_LENGTH_PCK_STEP_SIZE, 1, 0, "min_line_length_pck_step_size" }, { CCS_R_TIMING_MODE_CAPABILITY, 1, 0, "timing_mode_capability" }, { CCS_R_FRAME_MARGIN_MAX_VALUE, 2, 0, "frame_margin_max_value" }, { CCS_R_FRAME_MARGIN_MIN_VALUE, 1, 0, "frame_margin_min_value" }, { CCS_R_GAIN_DELAY_TYPE, 1, 0, "gain_delay_type" }, { CCS_R_MIN_OP_SYS_CLK_DIV, 2, 0, "min_op_sys_clk_div" }, { CCS_R_MAX_OP_SYS_CLK_DIV, 2, 0, "max_op_sys_clk_div" }, { CCS_R_MIN_OP_SYS_CLK_FREQ_MHZ, 4, 0, "min_op_sys_clk_freq_mhz" }, { CCS_R_MAX_OP_SYS_CLK_FREQ_MHZ, 4, 0, "max_op_sys_clk_freq_mhz" }, { CCS_R_MIN_OP_PIX_CLK_DIV, 2, 0, "min_op_pix_clk_div" }, { CCS_R_MAX_OP_PIX_CLK_DIV, 2, 0, "max_op_pix_clk_div" }, { CCS_R_MIN_OP_PIX_CLK_FREQ_MHZ, 4, 0, "min_op_pix_clk_freq_mhz" }, { CCS_R_MAX_OP_PIX_CLK_FREQ_MHZ, 4, 0, "max_op_pix_clk_freq_mhz" }, { CCS_R_X_ADDR_MIN, 2, 0, "x_addr_min" }, { CCS_R_Y_ADDR_MIN, 2, 0, "y_addr_min" }, { CCS_R_X_ADDR_MAX, 2, 0, "x_addr_max" }, { CCS_R_Y_ADDR_MAX, 2, 0, "y_addr_max" }, { CCS_R_MIN_X_OUTPUT_SIZE, 2, 0, "min_x_output_size" }, { CCS_R_MIN_Y_OUTPUT_SIZE, 2, 0, "min_y_output_size" }, { CCS_R_MAX_X_OUTPUT_SIZE, 2, 0, "max_x_output_size" }, { CCS_R_MAX_Y_OUTPUT_SIZE, 2, 0, "max_y_output_size" }, { CCS_R_X_ADDR_START_DIV_CONSTANT, 1, 0, "x_addr_start_div_constant" }, { CCS_R_Y_ADDR_START_DIV_CONSTANT, 1, 0, "y_addr_start_div_constant" }, { CCS_R_X_ADDR_END_DIV_CONSTANT, 1, 0, "x_addr_end_div_constant" }, { CCS_R_Y_ADDR_END_DIV_CONSTANT, 1, 0, "y_addr_end_div_constant" }, { CCS_R_X_SIZE_DIV, 1, 0, "x_size_div" }, { CCS_R_Y_SIZE_DIV, 1, 0, "y_size_div" }, { CCS_R_X_OUTPUT_DIV, 1, 0, "x_output_div" }, { CCS_R_Y_OUTPUT_DIV, 1, 0, "y_output_div" }, { CCS_R_NON_FLEXIBLE_RESOLUTION_SUPPORT, 1, 0, "non_flexible_resolution_support" }, { CCS_R_MIN_OP_PRE_PLL_CLK_DIV, 2, 0, "min_op_pre_pll_clk_div" }, { CCS_R_MAX_OP_PRE_PLL_CLK_DIV, 2, 0, "max_op_pre_pll_clk_div" }, { CCS_R_MIN_OP_PLL_IP_CLK_FREQ_MHZ, 4, 0, "min_op_pll_ip_clk_freq_mhz" }, { CCS_R_MAX_OP_PLL_IP_CLK_FREQ_MHZ, 4, 0, "max_op_pll_ip_clk_freq_mhz" }, { CCS_R_MIN_OP_PLL_MULTIPLIER, 2, 0, "min_op_pll_multiplier" }, { CCS_R_MAX_OP_PLL_MULTIPLIER, 2, 0, "max_op_pll_multiplier" }, { CCS_R_MIN_OP_PLL_OP_CLK_FREQ_MHZ, 4, 0, "min_op_pll_op_clk_freq_mhz" }, { CCS_R_MAX_OP_PLL_OP_CLK_FREQ_MHZ, 4, 0, "max_op_pll_op_clk_freq_mhz" }, { CCS_R_CLOCK_TREE_PLL_CAPABILITY, 1, 0, "clock_tree_pll_capability" }, { CCS_R_CLOCK_CAPA_TYPE_CAPABILITY, 1, 0, "clock_capa_type_capability" }, { CCS_R_MIN_EVEN_INC, 2, 0, "min_even_inc" }, { CCS_R_MIN_ODD_INC, 2, 0, "min_odd_inc" }, { CCS_R_MAX_EVEN_INC, 2, 0, "max_even_inc" }, { CCS_R_MAX_ODD_INC, 2, 0, "max_odd_inc" }, { CCS_R_AUX_SUBSAMP_CAPABILITY, 1, 0, "aux_subsamp_capability" }, { CCS_R_AUX_SUBSAMP_MONO_CAPABILITY, 1, 0, "aux_subsamp_mono_capability" }, { CCS_R_MONOCHROME_CAPABILITY, 1, 0, "monochrome_capability" }, { CCS_R_PIXEL_READOUT_CAPABILITY, 1, 0, "pixel_readout_capability" }, { CCS_R_MIN_EVEN_INC_MONO, 2, 0, "min_even_inc_mono" }, { CCS_R_MAX_EVEN_INC_MONO, 2, 0, "max_even_inc_mono" }, { CCS_R_MIN_ODD_INC_MONO, 2, 0, "min_odd_inc_mono" }, { CCS_R_MAX_ODD_INC_MONO, 2, 0, "max_odd_inc_mono" }, { CCS_R_MIN_EVEN_INC_BC2, 2, 0, "min_even_inc_bc2" }, { CCS_R_MAX_EVEN_INC_BC2, 2, 0, "max_even_inc_bc2" }, { CCS_R_MIN_ODD_INC_BC2, 2, 0, "min_odd_inc_bc2" }, { CCS_R_MAX_ODD_INC_BC2, 2, 0, "max_odd_inc_bc2" }, { CCS_R_MIN_EVEN_INC_MONO_BC2, 2, 0, "min_even_inc_mono_bc2" }, { CCS_R_MAX_EVEN_INC_MONO_BC2, 2, 0, "max_even_inc_mono_bc2" }, { CCS_R_MIN_ODD_INC_MONO_BC2, 2, 0, "min_odd_inc_mono_bc2" }, { CCS_R_MAX_ODD_INC_MONO_BC2, 2, 0, "max_odd_inc_mono_bc2" }, { CCS_R_SCALING_CAPABILITY, 2, 0, "scaling_capability" }, { CCS_R_SCALER_M_MIN, 2, 0, "scaler_m_min" }, { CCS_R_SCALER_M_MAX, 2, 0, "scaler_m_max" }, { CCS_R_SCALER_N_MIN, 2, 0, "scaler_n_min" }, { CCS_R_SCALER_N_MAX, 2, 0, "scaler_n_max" }, { CCS_R_DIGITAL_CROP_CAPABILITY, 1, 0, "digital_crop_capability" }, { CCS_R_HDR_CAPABILITY_1, 1, 0, "hdr_capability_1" }, { CCS_R_MIN_HDR_BIT_DEPTH, 1, 0, "min_hdr_bit_depth" }, { CCS_R_HDR_RESOLUTION_SUB_TYPES, 1, 0, "hdr_resolution_sub_types" }, { CCS_R_HDR_RESOLUTION_SUB_TYPE(0), 2, 0, "hdr_resolution_sub_type" }, { CCS_R_HDR_CAPABILITY_2, 1, 0, "hdr_capability_2" }, { CCS_R_MAX_HDR_BIT_DEPTH, 1, 0, "max_hdr_bit_depth" }, { CCS_R_USL_SUPPORT_CAPABILITY, 1, 0, "usl_support_capability" }, { CCS_R_USL_CLOCK_MODE_D_CAPABILITY, 1, 0, "usl_clock_mode_d_capability" }, { CCS_R_MIN_OP_SYS_CLK_DIV_REV, 1, 0, "min_op_sys_clk_div_rev" }, { CCS_R_MAX_OP_SYS_CLK_DIV_REV, 1, 0, "max_op_sys_clk_div_rev" }, { CCS_R_MIN_OP_PIX_CLK_DIV_REV, 1, 0, "min_op_pix_clk_div_rev" }, { CCS_R_MAX_OP_PIX_CLK_DIV_REV, 1, 0, "max_op_pix_clk_div_rev" }, { CCS_R_MIN_OP_SYS_CLK_FREQ_REV_MHZ, 4, 0, "min_op_sys_clk_freq_rev_mhz" }, { CCS_R_MAX_OP_SYS_CLK_FREQ_REV_MHZ, 4, 0, "max_op_sys_clk_freq_rev_mhz" }, { CCS_R_MIN_OP_PIX_CLK_FREQ_REV_MHZ, 4, 0, "min_op_pix_clk_freq_rev_mhz" }, { CCS_R_MAX_OP_PIX_CLK_FREQ_REV_MHZ, 4, 0, "max_op_pix_clk_freq_rev_mhz" }, { CCS_R_MAX_BITRATE_REV_D_MODE_MBPS, 4, 0, "max_bitrate_rev_d_mode_mbps" }, { CCS_R_MAX_SYMRATE_REV_C_MODE_MSPS, 4, 0, "max_symrate_rev_c_mode_msps" }, { CCS_R_COMPRESSION_CAPABILITY, 1, 0, "compression_capability" }, { CCS_R_TEST_MODE_CAPABILITY, 2, 0, "test_mode_capability" }, { CCS_R_PN9_DATA_FORMAT1, 1, 0, "pn9_data_format1" }, { CCS_R_PN9_DATA_FORMAT2, 1, 0, "pn9_data_format2" }, { CCS_R_PN9_DATA_FORMAT3, 1, 0, "pn9_data_format3" }, { CCS_R_PN9_DATA_FORMAT4, 1, 0, "pn9_data_format4" }, { CCS_R_PN9_MISC_CAPABILITY, 1, 0, "pn9_misc_capability" }, { CCS_R_TEST_PATTERN_CAPABILITY, 1, 0, "test_pattern_capability" }, { CCS_R_PATTERN_SIZE_DIV_M1, 1, 0, "pattern_size_div_m1" }, { CCS_R_FIFO_SUPPORT_CAPABILITY, 1, 0, "fifo_support_capability" }, { CCS_R_PHY_CTRL_CAPABILITY, 1, 0, "phy_ctrl_capability" }, { CCS_R_CSI_DPHY_LANE_MODE_CAPABILITY, 1, 0, "csi_dphy_lane_mode_capability" }, { CCS_R_CSI_SIGNALING_MODE_CAPABILITY, 1, 0, "csi_signaling_mode_capability" }, { CCS_R_FAST_STANDBY_CAPABILITY, 1, 0, "fast_standby_capability" }, { CCS_R_CSI_ADDRESS_CONTROL_CAPABILITY, 1, 0, "csi_address_control_capability" }, { CCS_R_DATA_TYPE_CAPABILITY, 1, 0, "data_type_capability" }, { CCS_R_CSI_CPHY_LANE_MODE_CAPABILITY, 1, 0, "csi_cphy_lane_mode_capability" }, { CCS_R_EMB_DATA_CAPABILITY, 1, 0, "emb_data_capability" }, { CCS_R_MAX_PER_LANE_BITRATE_LANE_D_MODE_MBPS(0), 16, 0, "max_per_lane_bitrate_lane_d_mode_mbps 0" }, { CCS_R_MAX_PER_LANE_BITRATE_LANE_D_MODE_MBPS(4), 16, CCS_L_FL_SAME_REG, "max_per_lane_bitrate_lane_d_mode_mbps 4" }, { CCS_R_TEMP_SENSOR_CAPABILITY, 1, 0, "temp_sensor_capability" }, { CCS_R_MAX_PER_LANE_BITRATE_LANE_C_MODE_MBPS(0), 16, 0, "max_per_lane_bitrate_lane_c_mode_mbps 0" }, { CCS_R_MAX_PER_LANE_BITRATE_LANE_C_MODE_MBPS(4), 16, CCS_L_FL_SAME_REG, "max_per_lane_bitrate_lane_c_mode_mbps 4" }, { CCS_R_DPHY_EQUALIZATION_CAPABILITY, 1, 0, "dphy_equalization_capability" }, { CCS_R_CPHY_EQUALIZATION_CAPABILITY, 1, 0, "cphy_equalization_capability" }, { CCS_R_DPHY_PREAMBLE_CAPABILITY, 1, 0, "dphy_preamble_capability" }, { CCS_R_DPHY_SSC_CAPABILITY, 1, 0, "dphy_ssc_capability" }, { CCS_R_CPHY_CALIBRATION_CAPABILITY, 1, 0, "cphy_calibration_capability" }, { CCS_R_DPHY_CALIBRATION_CAPABILITY, 1, 0, "dphy_calibration_capability" }, { CCS_R_PHY_CTRL_CAPABILITY_2, 1, 0, "phy_ctrl_capability_2" }, { CCS_R_LRTE_CPHY_CAPABILITY, 1, 0, "lrte_cphy_capability" }, { CCS_R_LRTE_DPHY_CAPABILITY, 1, 0, "lrte_dphy_capability" }, { CCS_R_ALPS_CAPABILITY_DPHY, 1, 0, "alps_capability_dphy" }, { CCS_R_ALPS_CAPABILITY_CPHY, 1, 0, "alps_capability_cphy" }, { CCS_R_SCRAMBLING_CAPABILITY, 1, 0, "scrambling_capability" }, { CCS_R_DPHY_MANUAL_CONSTANT, 1, 0, "dphy_manual_constant" }, { CCS_R_CPHY_MANUAL_CONSTANT, 1, 0, "cphy_manual_constant" }, { CCS_R_CSI2_INTERFACE_CAPABILITY_MISC, 1, 0, "CSI2_interface_capability_misc" }, { CCS_R_PHY_CTRL_CAPABILITY_3, 1, 0, "PHY_ctrl_capability_3" }, { CCS_R_DPHY_SF, 1, 0, "dphy_sf" }, { CCS_R_CPHY_SF, 1, 0, "cphy_sf" }, { CCS_R_DPHY_LIMITS_1, 1, 0, "dphy_limits_1" }, { CCS_R_DPHY_LIMITS_2, 1, 0, "dphy_limits_2" }, { CCS_R_DPHY_LIMITS_3, 1, 0, "dphy_limits_3" }, { CCS_R_DPHY_LIMITS_4, 1, 0, "dphy_limits_4" }, { CCS_R_DPHY_LIMITS_5, 1, 0, "dphy_limits_5" }, { CCS_R_DPHY_LIMITS_6, 1, 0, "dphy_limits_6" }, { CCS_R_CPHY_LIMITS_1, 1, 0, "cphy_limits_1" }, { CCS_R_CPHY_LIMITS_2, 1, 0, "cphy_limits_2" }, { CCS_R_CPHY_LIMITS_3, 1, 0, "cphy_limits_3" }, { CCS_R_MIN_FRAME_LENGTH_LINES_BIN, 2, 0, "min_frame_length_lines_bin" }, { CCS_R_MAX_FRAME_LENGTH_LINES_BIN, 2, 0, "max_frame_length_lines_bin" }, { CCS_R_MIN_LINE_LENGTH_PCK_BIN, 2, 0, "min_line_length_pck_bin" }, { CCS_R_MAX_LINE_LENGTH_PCK_BIN, 2, 0, "max_line_length_pck_bin" }, { CCS_R_MIN_LINE_BLANKING_PCK_BIN, 2, 0, "min_line_blanking_pck_bin" }, { CCS_R_FINE_INTEGRATION_TIME_MIN_BIN, 2, 0, "fine_integration_time_min_bin" }, { CCS_R_FINE_INTEGRATION_TIME_MAX_MARGIN_BIN, 2, 0, "fine_integration_time_max_margin_bin" }, { CCS_R_BINNING_CAPABILITY, 1, 0, "binning_capability" }, { CCS_R_BINNING_WEIGHTING_CAPABILITY, 1, 0, "binning_weighting_capability" }, { CCS_R_BINNING_SUB_TYPES, 1, 0, "binning_sub_types" }, { CCS_R_BINNING_SUB_TYPE(0), 64, 0, "binning_sub_type" }, { CCS_R_BINNING_WEIGHTING_MONO_CAPABILITY, 1, 0, "binning_weighting_mono_capability" }, { CCS_R_BINNING_SUB_TYPES_MONO, 1, 0, "binning_sub_types_mono" }, { CCS_R_BINNING_SUB_TYPE_MONO(0), 64, 0, "binning_sub_type_mono" }, { CCS_R_DATA_TRANSFER_IF_CAPABILITY, 1, 0, "data_transfer_if_capability" }, { CCS_R_SHADING_CORRECTION_CAPABILITY, 1, 0, "shading_correction_capability" }, { CCS_R_GREEN_IMBALANCE_CAPABILITY, 1, 0, "green_imbalance_capability" }, { CCS_R_MODULE_SPECIFIC_CORRECTION_CAPABILITY, 1, 0, "module_specific_correction_capability" }, { CCS_R_DEFECT_CORRECTION_CAPABILITY, 2, 0, "defect_correction_capability" }, { CCS_R_DEFECT_CORRECTION_CAPABILITY_2, 2, 0, "defect_correction_capability_2" }, { CCS_R_NF_CAPABILITY, 1, 0, "nf_capability" }, { CCS_R_OB_READOUT_CAPABILITY, 1, 0, "ob_readout_capability" }, { CCS_R_COLOR_FEEDBACK_CAPABILITY, 1, 0, "color_feedback_capability" }, { CCS_R_CFA_PATTERN_CAPABILITY, 1, 0, "CFA_pattern_capability" }, { CCS_R_CFA_PATTERN_CONVERSION_CAPABILITY, 1, 0, "CFA_pattern_conversion_capability" }, { CCS_R_FLASH_MODE_CAPABILITY, 1, 0, "flash_mode_capability" }, { CCS_R_SA_STROBE_MODE_CAPABILITY, 1, 0, "sa_strobe_mode_capability" }, { CCS_R_RESET_MAX_DELAY, 1, 0, "reset_max_delay" }, { CCS_R_RESET_MIN_TIME, 1, 0, "reset_min_time" }, { CCS_R_PDAF_CAPABILITY_1, 1, 0, "pdaf_capability_1" }, { CCS_R_PDAF_CAPABILITY_2, 1, 0, "pdaf_capability_2" }, { CCS_R_BRACKETING_LUT_CAPABILITY_1, 1, 0, "bracketing_lut_capability_1" }, { CCS_R_BRACKETING_LUT_CAPABILITY_2, 1, 0, "bracketing_lut_capability_2" }, { CCS_R_BRACKETING_LUT_SIZE, 1, 0, "bracketing_lut_size" }, { 0 } /* Guardian */ };
linux-master
drivers/media/i2c/ccs/ccs-limits.c
// SPDX-License-Identifier: GPL-2.0-only /* * drivers/media/i2c/ccs/ccs-core.c * * Generic driver for MIPI CCS/SMIA/SMIA++ compliant camera sensors * * Copyright (C) 2020 Intel Corporation * Copyright (C) 2010--2012 Nokia Corporation * Contact: Sakari Ailus <[email protected]> * * Based on smiapp driver by Vimarsh Zutshi * Based on jt8ev1.c by Vimarsh Zutshi * Based on smia-sensor.c by Tuukka Toivonen <[email protected]> */ #include <linux/clk.h> #include <linux/delay.h> #include <linux/device.h> #include <linux/firmware.h> #include <linux/gpio/consumer.h> #include <linux/module.h> #include <linux/pm_runtime.h> #include <linux/property.h> #include <linux/regulator/consumer.h> #include <linux/slab.h> #include <linux/smiapp.h> #include <linux/v4l2-mediabus.h> #include <media/v4l2-fwnode.h> #include <media/v4l2-device.h> #include <uapi/linux/ccs.h> #include "ccs.h" #define CCS_ALIGN_DIM(dim, flags) \ ((flags) & V4L2_SEL_FLAG_GE \ ? ALIGN((dim), 2) \ : (dim) & ~1) static struct ccs_limit_offset { u16 lim; u16 info; } ccs_limit_offsets[CCS_L_LAST + 1]; /* * ccs_module_idents - supported camera modules */ static const struct ccs_module_ident ccs_module_idents[] = { CCS_IDENT_L(0x01, 0x022b, -1, "vs6555"), CCS_IDENT_L(0x01, 0x022e, -1, "vw6558"), CCS_IDENT_L(0x07, 0x7698, -1, "ovm7698"), CCS_IDENT_L(0x0b, 0x4242, -1, "smiapp-003"), CCS_IDENT_L(0x0c, 0x208a, -1, "tcm8330md"), CCS_IDENT_LQ(0x0c, 0x2134, -1, "tcm8500md", &smiapp_tcm8500md_quirk), CCS_IDENT_L(0x0c, 0x213e, -1, "et8en2"), CCS_IDENT_L(0x0c, 0x2184, -1, "tcm8580md"), CCS_IDENT_LQ(0x0c, 0x560f, -1, "jt8ew9", &smiapp_jt8ew9_quirk), CCS_IDENT_LQ(0x10, 0x4141, -1, "jt8ev1", &smiapp_jt8ev1_quirk), CCS_IDENT_LQ(0x10, 0x4241, -1, "imx125es", &smiapp_imx125es_quirk), }; #define CCS_DEVICE_FLAG_IS_SMIA BIT(0) struct ccs_device { unsigned char flags; }; static const char * const ccs_regulators[] = { "vcore", "vio", "vana" }; /* * * Dynamic Capability Identification * */ static void ccs_assign_limit(void *ptr, unsigned int width, u32 val) { switch (width) { case sizeof(u8): *(u8 *)ptr = val; break; case sizeof(u16): *(u16 *)ptr = val; break; case sizeof(u32): *(u32 *)ptr = val; break; } } static int ccs_limit_ptr(struct ccs_sensor *sensor, unsigned int limit, unsigned int offset, void **__ptr) { const struct ccs_limit *linfo; if (WARN_ON(limit >= CCS_L_LAST)) return -EINVAL; linfo = &ccs_limits[ccs_limit_offsets[limit].info]; if (WARN_ON(!sensor->ccs_limits) || WARN_ON(offset + ccs_reg_width(linfo->reg) > ccs_limit_offsets[limit + 1].lim)) return -EINVAL; *__ptr = sensor->ccs_limits + ccs_limit_offsets[limit].lim + offset; return 0; } void ccs_replace_limit(struct ccs_sensor *sensor, unsigned int limit, unsigned int offset, u32 val) { struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd); const struct ccs_limit *linfo; void *ptr; int ret; ret = ccs_limit_ptr(sensor, limit, offset, &ptr); if (ret) return; linfo = &ccs_limits[ccs_limit_offsets[limit].info]; dev_dbg(&client->dev, "quirk: 0x%8.8x \"%s\" %u = %u, 0x%x\n", linfo->reg, linfo->name, offset, val, val); ccs_assign_limit(ptr, ccs_reg_width(linfo->reg), val); } u32 ccs_get_limit(struct ccs_sensor *sensor, unsigned int limit, unsigned int offset) { void *ptr; u32 val; int ret; ret = ccs_limit_ptr(sensor, limit, offset, &ptr); if (ret) return 0; switch (ccs_reg_width(ccs_limits[ccs_limit_offsets[limit].info].reg)) { case sizeof(u8): val = *(u8 *)ptr; break; case sizeof(u16): val = *(u16 *)ptr; break; case sizeof(u32): val = *(u32 *)ptr; break; default: WARN_ON(1); return 0; } return ccs_reg_conv(sensor, ccs_limits[limit].reg, val); } static int ccs_read_all_limits(struct ccs_sensor *sensor) { struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd); void *ptr, *alloc, *end; unsigned int i, l; int ret; kfree(sensor->ccs_limits); sensor->ccs_limits = NULL; alloc = kzalloc(ccs_limit_offsets[CCS_L_LAST].lim, GFP_KERNEL); if (!alloc) return -ENOMEM; end = alloc + ccs_limit_offsets[CCS_L_LAST].lim; for (i = 0, l = 0, ptr = alloc; ccs_limits[i].size; i++) { u32 reg = ccs_limits[i].reg; unsigned int width = ccs_reg_width(reg); unsigned int j; if (l == CCS_L_LAST) { dev_err(&client->dev, "internal error --- end of limit array\n"); ret = -EINVAL; goto out_err; } for (j = 0; j < ccs_limits[i].size / width; j++, reg += width, ptr += width) { u32 val; ret = ccs_read_addr_noconv(sensor, reg, &val); if (ret) goto out_err; if (ptr + width > end) { dev_err(&client->dev, "internal error --- no room for regs\n"); ret = -EINVAL; goto out_err; } if (!val && j) break; ccs_assign_limit(ptr, width, val); dev_dbg(&client->dev, "0x%8.8x \"%s\" = %u, 0x%x\n", reg, ccs_limits[i].name, val, val); } if (ccs_limits[i].flags & CCS_L_FL_SAME_REG) continue; l++; ptr = alloc + ccs_limit_offsets[l].lim; } if (l != CCS_L_LAST) { dev_err(&client->dev, "internal error --- insufficient limits\n"); ret = -EINVAL; goto out_err; } sensor->ccs_limits = alloc; if (CCS_LIM(sensor, SCALER_N_MIN) < 16) ccs_replace_limit(sensor, CCS_L_SCALER_N_MIN, 0, 16); return 0; out_err: kfree(alloc); return ret; } static int ccs_read_frame_fmt(struct ccs_sensor *sensor) { struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd); u8 fmt_model_type, fmt_model_subtype, ncol_desc, nrow_desc; unsigned int i; int pixel_count = 0; int line_count = 0; fmt_model_type = CCS_LIM(sensor, FRAME_FORMAT_MODEL_TYPE); fmt_model_subtype = CCS_LIM(sensor, FRAME_FORMAT_MODEL_SUBTYPE); ncol_desc = (fmt_model_subtype & CCS_FRAME_FORMAT_MODEL_SUBTYPE_COLUMNS_MASK) >> CCS_FRAME_FORMAT_MODEL_SUBTYPE_COLUMNS_SHIFT; nrow_desc = fmt_model_subtype & CCS_FRAME_FORMAT_MODEL_SUBTYPE_ROWS_MASK; dev_dbg(&client->dev, "format_model_type %s\n", fmt_model_type == CCS_FRAME_FORMAT_MODEL_TYPE_2_BYTE ? "2 byte" : fmt_model_type == CCS_FRAME_FORMAT_MODEL_TYPE_4_BYTE ? "4 byte" : "is simply bad"); dev_dbg(&client->dev, "%u column and %u row descriptors\n", ncol_desc, nrow_desc); for (i = 0; i < ncol_desc + nrow_desc; i++) { u32 desc; u32 pixelcode; u32 pixels; char *which; char *what; if (fmt_model_type == CCS_FRAME_FORMAT_MODEL_TYPE_2_BYTE) { desc = CCS_LIM_AT(sensor, FRAME_FORMAT_DESCRIPTOR, i); pixelcode = (desc & CCS_FRAME_FORMAT_DESCRIPTOR_PCODE_MASK) >> CCS_FRAME_FORMAT_DESCRIPTOR_PCODE_SHIFT; pixels = desc & CCS_FRAME_FORMAT_DESCRIPTOR_PIXELS_MASK; } else if (fmt_model_type == CCS_FRAME_FORMAT_MODEL_TYPE_4_BYTE) { desc = CCS_LIM_AT(sensor, FRAME_FORMAT_DESCRIPTOR_4, i); pixelcode = (desc & CCS_FRAME_FORMAT_DESCRIPTOR_4_PCODE_MASK) >> CCS_FRAME_FORMAT_DESCRIPTOR_4_PCODE_SHIFT; pixels = desc & CCS_FRAME_FORMAT_DESCRIPTOR_4_PIXELS_MASK; } else { dev_dbg(&client->dev, "invalid frame format model type %u\n", fmt_model_type); return -EINVAL; } if (i < ncol_desc) which = "columns"; else which = "rows"; switch (pixelcode) { case CCS_FRAME_FORMAT_DESCRIPTOR_PCODE_EMBEDDED: what = "embedded"; break; case CCS_FRAME_FORMAT_DESCRIPTOR_PCODE_DUMMY_PIXEL: what = "dummy"; break; case CCS_FRAME_FORMAT_DESCRIPTOR_PCODE_BLACK_PIXEL: what = "black"; break; case CCS_FRAME_FORMAT_DESCRIPTOR_PCODE_DARK_PIXEL: what = "dark"; break; case CCS_FRAME_FORMAT_DESCRIPTOR_PCODE_VISIBLE_PIXEL: what = "visible"; break; default: what = "invalid"; break; } dev_dbg(&client->dev, "%s pixels: %u %s (pixelcode %u)\n", what, pixels, which, pixelcode); if (i < ncol_desc) { if (pixelcode == CCS_FRAME_FORMAT_DESCRIPTOR_PCODE_VISIBLE_PIXEL) sensor->visible_pixel_start = pixel_count; pixel_count += pixels; continue; } /* Handle row descriptors */ switch (pixelcode) { case CCS_FRAME_FORMAT_DESCRIPTOR_PCODE_EMBEDDED: if (sensor->embedded_end) break; sensor->embedded_start = line_count; sensor->embedded_end = line_count + pixels; break; case CCS_FRAME_FORMAT_DESCRIPTOR_PCODE_VISIBLE_PIXEL: sensor->image_start = line_count; break; } line_count += pixels; } if (sensor->embedded_end > sensor->image_start) { dev_dbg(&client->dev, "adjusting image start line to %u (was %u)\n", sensor->embedded_end, sensor->image_start); sensor->image_start = sensor->embedded_end; } dev_dbg(&client->dev, "embedded data from lines %u to %u\n", sensor->embedded_start, sensor->embedded_end); dev_dbg(&client->dev, "image data starts at line %u\n", sensor->image_start); return 0; } static int ccs_pll_configure(struct ccs_sensor *sensor) { struct ccs_pll *pll = &sensor->pll; int rval; rval = ccs_write(sensor, VT_PIX_CLK_DIV, pll->vt_bk.pix_clk_div); if (rval < 0) return rval; rval = ccs_write(sensor, VT_SYS_CLK_DIV, pll->vt_bk.sys_clk_div); if (rval < 0) return rval; rval = ccs_write(sensor, PRE_PLL_CLK_DIV, pll->vt_fr.pre_pll_clk_div); if (rval < 0) return rval; rval = ccs_write(sensor, PLL_MULTIPLIER, pll->vt_fr.pll_multiplier); if (rval < 0) return rval; if (!(CCS_LIM(sensor, PHY_CTRL_CAPABILITY) & CCS_PHY_CTRL_CAPABILITY_AUTO_PHY_CTL)) { /* Lane op clock ratio does not apply here. */ rval = ccs_write(sensor, REQUESTED_LINK_RATE, DIV_ROUND_UP(pll->op_bk.sys_clk_freq_hz, 1000000 / 256 / 256) * (pll->flags & CCS_PLL_FLAG_LANE_SPEED_MODEL ? sensor->pll.csi2.lanes : 1) << (pll->flags & CCS_PLL_FLAG_OP_SYS_DDR ? 1 : 0)); if (rval < 0) return rval; } if (sensor->pll.flags & CCS_PLL_FLAG_NO_OP_CLOCKS) return 0; rval = ccs_write(sensor, OP_PIX_CLK_DIV, pll->op_bk.pix_clk_div); if (rval < 0) return rval; rval = ccs_write(sensor, OP_SYS_CLK_DIV, pll->op_bk.sys_clk_div); if (rval < 0) return rval; if (!(pll->flags & CCS_PLL_FLAG_DUAL_PLL)) return 0; rval = ccs_write(sensor, PLL_MODE, CCS_PLL_MODE_DUAL); if (rval < 0) return rval; rval = ccs_write(sensor, OP_PRE_PLL_CLK_DIV, pll->op_fr.pre_pll_clk_div); if (rval < 0) return rval; return ccs_write(sensor, OP_PLL_MULTIPLIER, pll->op_fr.pll_multiplier); } static int ccs_pll_try(struct ccs_sensor *sensor, struct ccs_pll *pll) { struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd); struct ccs_pll_limits lim = { .vt_fr = { .min_pre_pll_clk_div = CCS_LIM(sensor, MIN_PRE_PLL_CLK_DIV), .max_pre_pll_clk_div = CCS_LIM(sensor, MAX_PRE_PLL_CLK_DIV), .min_pll_ip_clk_freq_hz = CCS_LIM(sensor, MIN_PLL_IP_CLK_FREQ_MHZ), .max_pll_ip_clk_freq_hz = CCS_LIM(sensor, MAX_PLL_IP_CLK_FREQ_MHZ), .min_pll_multiplier = CCS_LIM(sensor, MIN_PLL_MULTIPLIER), .max_pll_multiplier = CCS_LIM(sensor, MAX_PLL_MULTIPLIER), .min_pll_op_clk_freq_hz = CCS_LIM(sensor, MIN_PLL_OP_CLK_FREQ_MHZ), .max_pll_op_clk_freq_hz = CCS_LIM(sensor, MAX_PLL_OP_CLK_FREQ_MHZ), }, .op_fr = { .min_pre_pll_clk_div = CCS_LIM(sensor, MIN_OP_PRE_PLL_CLK_DIV), .max_pre_pll_clk_div = CCS_LIM(sensor, MAX_OP_PRE_PLL_CLK_DIV), .min_pll_ip_clk_freq_hz = CCS_LIM(sensor, MIN_OP_PLL_IP_CLK_FREQ_MHZ), .max_pll_ip_clk_freq_hz = CCS_LIM(sensor, MAX_OP_PLL_IP_CLK_FREQ_MHZ), .min_pll_multiplier = CCS_LIM(sensor, MIN_OP_PLL_MULTIPLIER), .max_pll_multiplier = CCS_LIM(sensor, MAX_OP_PLL_MULTIPLIER), .min_pll_op_clk_freq_hz = CCS_LIM(sensor, MIN_OP_PLL_OP_CLK_FREQ_MHZ), .max_pll_op_clk_freq_hz = CCS_LIM(sensor, MAX_OP_PLL_OP_CLK_FREQ_MHZ), }, .op_bk = { .min_sys_clk_div = CCS_LIM(sensor, MIN_OP_SYS_CLK_DIV), .max_sys_clk_div = CCS_LIM(sensor, MAX_OP_SYS_CLK_DIV), .min_pix_clk_div = CCS_LIM(sensor, MIN_OP_PIX_CLK_DIV), .max_pix_clk_div = CCS_LIM(sensor, MAX_OP_PIX_CLK_DIV), .min_sys_clk_freq_hz = CCS_LIM(sensor, MIN_OP_SYS_CLK_FREQ_MHZ), .max_sys_clk_freq_hz = CCS_LIM(sensor, MAX_OP_SYS_CLK_FREQ_MHZ), .min_pix_clk_freq_hz = CCS_LIM(sensor, MIN_OP_PIX_CLK_FREQ_MHZ), .max_pix_clk_freq_hz = CCS_LIM(sensor, MAX_OP_PIX_CLK_FREQ_MHZ), }, .vt_bk = { .min_sys_clk_div = CCS_LIM(sensor, MIN_VT_SYS_CLK_DIV), .max_sys_clk_div = CCS_LIM(sensor, MAX_VT_SYS_CLK_DIV), .min_pix_clk_div = CCS_LIM(sensor, MIN_VT_PIX_CLK_DIV), .max_pix_clk_div = CCS_LIM(sensor, MAX_VT_PIX_CLK_DIV), .min_sys_clk_freq_hz = CCS_LIM(sensor, MIN_VT_SYS_CLK_FREQ_MHZ), .max_sys_clk_freq_hz = CCS_LIM(sensor, MAX_VT_SYS_CLK_FREQ_MHZ), .min_pix_clk_freq_hz = CCS_LIM(sensor, MIN_VT_PIX_CLK_FREQ_MHZ), .max_pix_clk_freq_hz = CCS_LIM(sensor, MAX_VT_PIX_CLK_FREQ_MHZ), }, .min_line_length_pck_bin = CCS_LIM(sensor, MIN_LINE_LENGTH_PCK_BIN), .min_line_length_pck = CCS_LIM(sensor, MIN_LINE_LENGTH_PCK), }; return ccs_pll_calculate(&client->dev, &lim, pll); } static int ccs_pll_update(struct ccs_sensor *sensor) { struct ccs_pll *pll = &sensor->pll; int rval; pll->binning_horizontal = sensor->binning_horizontal; pll->binning_vertical = sensor->binning_vertical; pll->link_freq = sensor->link_freq->qmenu_int[sensor->link_freq->val]; pll->scale_m = sensor->scale_m; pll->bits_per_pixel = sensor->csi_format->compressed; rval = ccs_pll_try(sensor, pll); if (rval < 0) return rval; __v4l2_ctrl_s_ctrl_int64(sensor->pixel_rate_parray, pll->pixel_rate_pixel_array); __v4l2_ctrl_s_ctrl_int64(sensor->pixel_rate_csi, pll->pixel_rate_csi); return 0; } /* * * V4L2 Controls handling * */ static void __ccs_update_exposure_limits(struct ccs_sensor *sensor) { struct v4l2_ctrl *ctrl = sensor->exposure; int max; max = sensor->pixel_array->crop[CCS_PA_PAD_SRC].height + sensor->vblank->val - CCS_LIM(sensor, COARSE_INTEGRATION_TIME_MAX_MARGIN); __v4l2_ctrl_modify_range(ctrl, ctrl->minimum, max, ctrl->step, max); } /* * Order matters. * * 1. Bits-per-pixel, descending. * 2. Bits-per-pixel compressed, descending. * 3. Pixel order, same as in pixel_order_str. Formats for all four pixel * orders must be defined. */ static const struct ccs_csi_data_format ccs_csi_data_formats[] = { { MEDIA_BUS_FMT_SGRBG16_1X16, 16, 16, CCS_PIXEL_ORDER_GRBG, }, { MEDIA_BUS_FMT_SRGGB16_1X16, 16, 16, CCS_PIXEL_ORDER_RGGB, }, { MEDIA_BUS_FMT_SBGGR16_1X16, 16, 16, CCS_PIXEL_ORDER_BGGR, }, { MEDIA_BUS_FMT_SGBRG16_1X16, 16, 16, CCS_PIXEL_ORDER_GBRG, }, { MEDIA_BUS_FMT_SGRBG14_1X14, 14, 14, CCS_PIXEL_ORDER_GRBG, }, { MEDIA_BUS_FMT_SRGGB14_1X14, 14, 14, CCS_PIXEL_ORDER_RGGB, }, { MEDIA_BUS_FMT_SBGGR14_1X14, 14, 14, CCS_PIXEL_ORDER_BGGR, }, { MEDIA_BUS_FMT_SGBRG14_1X14, 14, 14, CCS_PIXEL_ORDER_GBRG, }, { MEDIA_BUS_FMT_SGRBG12_1X12, 12, 12, CCS_PIXEL_ORDER_GRBG, }, { MEDIA_BUS_FMT_SRGGB12_1X12, 12, 12, CCS_PIXEL_ORDER_RGGB, }, { MEDIA_BUS_FMT_SBGGR12_1X12, 12, 12, CCS_PIXEL_ORDER_BGGR, }, { MEDIA_BUS_FMT_SGBRG12_1X12, 12, 12, CCS_PIXEL_ORDER_GBRG, }, { MEDIA_BUS_FMT_SGRBG10_1X10, 10, 10, CCS_PIXEL_ORDER_GRBG, }, { MEDIA_BUS_FMT_SRGGB10_1X10, 10, 10, CCS_PIXEL_ORDER_RGGB, }, { MEDIA_BUS_FMT_SBGGR10_1X10, 10, 10, CCS_PIXEL_ORDER_BGGR, }, { MEDIA_BUS_FMT_SGBRG10_1X10, 10, 10, CCS_PIXEL_ORDER_GBRG, }, { MEDIA_BUS_FMT_SGRBG10_DPCM8_1X8, 10, 8, CCS_PIXEL_ORDER_GRBG, }, { MEDIA_BUS_FMT_SRGGB10_DPCM8_1X8, 10, 8, CCS_PIXEL_ORDER_RGGB, }, { MEDIA_BUS_FMT_SBGGR10_DPCM8_1X8, 10, 8, CCS_PIXEL_ORDER_BGGR, }, { MEDIA_BUS_FMT_SGBRG10_DPCM8_1X8, 10, 8, CCS_PIXEL_ORDER_GBRG, }, { MEDIA_BUS_FMT_SGRBG8_1X8, 8, 8, CCS_PIXEL_ORDER_GRBG, }, { MEDIA_BUS_FMT_SRGGB8_1X8, 8, 8, CCS_PIXEL_ORDER_RGGB, }, { MEDIA_BUS_FMT_SBGGR8_1X8, 8, 8, CCS_PIXEL_ORDER_BGGR, }, { MEDIA_BUS_FMT_SGBRG8_1X8, 8, 8, CCS_PIXEL_ORDER_GBRG, }, }; static const char *pixel_order_str[] = { "GRBG", "RGGB", "BGGR", "GBRG" }; #define to_csi_format_idx(fmt) (((unsigned long)(fmt) \ - (unsigned long)ccs_csi_data_formats) \ / sizeof(*ccs_csi_data_formats)) static u32 ccs_pixel_order(struct ccs_sensor *sensor) { struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd); int flip = 0; if (sensor->hflip) { if (sensor->hflip->val) flip |= CCS_IMAGE_ORIENTATION_HORIZONTAL_MIRROR; if (sensor->vflip->val) flip |= CCS_IMAGE_ORIENTATION_VERTICAL_FLIP; } dev_dbg(&client->dev, "flip %u\n", flip); return sensor->default_pixel_order ^ flip; } static void ccs_update_mbus_formats(struct ccs_sensor *sensor) { struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd); unsigned int csi_format_idx = to_csi_format_idx(sensor->csi_format) & ~3; unsigned int internal_csi_format_idx = to_csi_format_idx(sensor->internal_csi_format) & ~3; unsigned int pixel_order = ccs_pixel_order(sensor); if (WARN_ON_ONCE(max(internal_csi_format_idx, csi_format_idx) + pixel_order >= ARRAY_SIZE(ccs_csi_data_formats))) return; sensor->mbus_frame_fmts = sensor->default_mbus_frame_fmts << pixel_order; sensor->csi_format = &ccs_csi_data_formats[csi_format_idx + pixel_order]; sensor->internal_csi_format = &ccs_csi_data_formats[internal_csi_format_idx + pixel_order]; dev_dbg(&client->dev, "new pixel order %s\n", pixel_order_str[pixel_order]); } static const char * const ccs_test_patterns[] = { "Disabled", "Solid Colour", "Eight Vertical Colour Bars", "Colour Bars With Fade to Grey", "Pseudorandom Sequence (PN9)", }; static int ccs_set_ctrl(struct v4l2_ctrl *ctrl) { struct ccs_sensor *sensor = container_of(ctrl->handler, struct ccs_subdev, ctrl_handler) ->sensor; struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd); int pm_status; u32 orient = 0; unsigned int i; int exposure; int rval; switch (ctrl->id) { case V4L2_CID_HFLIP: case V4L2_CID_VFLIP: if (sensor->streaming) return -EBUSY; if (sensor->hflip->val) orient |= CCS_IMAGE_ORIENTATION_HORIZONTAL_MIRROR; if (sensor->vflip->val) orient |= CCS_IMAGE_ORIENTATION_VERTICAL_FLIP; ccs_update_mbus_formats(sensor); break; case V4L2_CID_VBLANK: exposure = sensor->exposure->val; __ccs_update_exposure_limits(sensor); if (exposure > sensor->exposure->maximum) { sensor->exposure->val = sensor->exposure->maximum; rval = ccs_set_ctrl(sensor->exposure); if (rval < 0) return rval; } break; case V4L2_CID_LINK_FREQ: if (sensor->streaming) return -EBUSY; rval = ccs_pll_update(sensor); if (rval) return rval; return 0; case V4L2_CID_TEST_PATTERN: for (i = 0; i < ARRAY_SIZE(sensor->test_data); i++) v4l2_ctrl_activate( sensor->test_data[i], ctrl->val == V4L2_SMIAPP_TEST_PATTERN_MODE_SOLID_COLOUR); break; } pm_status = pm_runtime_get_if_active(&client->dev, true); if (!pm_status) return 0; switch (ctrl->id) { case V4L2_CID_ANALOGUE_GAIN: rval = ccs_write(sensor, ANALOG_GAIN_CODE_GLOBAL, ctrl->val); break; case V4L2_CID_CCS_ANALOGUE_LINEAR_GAIN: rval = ccs_write(sensor, ANALOG_LINEAR_GAIN_GLOBAL, ctrl->val); break; case V4L2_CID_CCS_ANALOGUE_EXPONENTIAL_GAIN: rval = ccs_write(sensor, ANALOG_EXPONENTIAL_GAIN_GLOBAL, ctrl->val); break; case V4L2_CID_DIGITAL_GAIN: if (CCS_LIM(sensor, DIGITAL_GAIN_CAPABILITY) == CCS_DIGITAL_GAIN_CAPABILITY_GLOBAL) { rval = ccs_write(sensor, DIGITAL_GAIN_GLOBAL, ctrl->val); break; } rval = ccs_write_addr(sensor, SMIAPP_REG_U16_DIGITAL_GAIN_GREENR, ctrl->val); if (rval) break; rval = ccs_write_addr(sensor, SMIAPP_REG_U16_DIGITAL_GAIN_RED, ctrl->val); if (rval) break; rval = ccs_write_addr(sensor, SMIAPP_REG_U16_DIGITAL_GAIN_BLUE, ctrl->val); if (rval) break; rval = ccs_write_addr(sensor, SMIAPP_REG_U16_DIGITAL_GAIN_GREENB, ctrl->val); break; case V4L2_CID_EXPOSURE: rval = ccs_write(sensor, COARSE_INTEGRATION_TIME, ctrl->val); break; case V4L2_CID_HFLIP: case V4L2_CID_VFLIP: rval = ccs_write(sensor, IMAGE_ORIENTATION, orient); break; case V4L2_CID_VBLANK: rval = ccs_write(sensor, FRAME_LENGTH_LINES, sensor->pixel_array->crop[ CCS_PA_PAD_SRC].height + ctrl->val); break; case V4L2_CID_HBLANK: rval = ccs_write(sensor, LINE_LENGTH_PCK, sensor->pixel_array->crop[CCS_PA_PAD_SRC].width + ctrl->val); break; case V4L2_CID_TEST_PATTERN: rval = ccs_write(sensor, TEST_PATTERN_MODE, ctrl->val); break; case V4L2_CID_TEST_PATTERN_RED: rval = ccs_write(sensor, TEST_DATA_RED, ctrl->val); break; case V4L2_CID_TEST_PATTERN_GREENR: rval = ccs_write(sensor, TEST_DATA_GREENR, ctrl->val); break; case V4L2_CID_TEST_PATTERN_BLUE: rval = ccs_write(sensor, TEST_DATA_BLUE, ctrl->val); break; case V4L2_CID_TEST_PATTERN_GREENB: rval = ccs_write(sensor, TEST_DATA_GREENB, ctrl->val); break; case V4L2_CID_CCS_SHADING_CORRECTION: rval = ccs_write(sensor, SHADING_CORRECTION_EN, ctrl->val ? CCS_SHADING_CORRECTION_EN_ENABLE : 0); if (!rval && sensor->luminance_level) v4l2_ctrl_activate(sensor->luminance_level, ctrl->val); break; case V4L2_CID_CCS_LUMINANCE_CORRECTION_LEVEL: rval = ccs_write(sensor, LUMINANCE_CORRECTION_LEVEL, ctrl->val); break; case V4L2_CID_PIXEL_RATE: /* For v4l2_ctrl_s_ctrl_int64() used internally. */ rval = 0; break; default: rval = -EINVAL; } if (pm_status > 0) { pm_runtime_mark_last_busy(&client->dev); pm_runtime_put_autosuspend(&client->dev); } return rval; } static const struct v4l2_ctrl_ops ccs_ctrl_ops = { .s_ctrl = ccs_set_ctrl, }; static int ccs_init_controls(struct ccs_sensor *sensor) { struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd); struct v4l2_fwnode_device_properties props; int rval; rval = v4l2_ctrl_handler_init(&sensor->pixel_array->ctrl_handler, 19); if (rval) return rval; sensor->pixel_array->ctrl_handler.lock = &sensor->mutex; rval = v4l2_fwnode_device_parse(&client->dev, &props); if (rval) return rval; rval = v4l2_ctrl_new_fwnode_properties(&sensor->pixel_array->ctrl_handler, &ccs_ctrl_ops, &props); if (rval) return rval; switch (CCS_LIM(sensor, ANALOG_GAIN_CAPABILITY)) { case CCS_ANALOG_GAIN_CAPABILITY_GLOBAL: { struct { const char *name; u32 id; s32 value; } const gain_ctrls[] = { { "Analogue Gain m0", V4L2_CID_CCS_ANALOGUE_GAIN_M0, CCS_LIM(sensor, ANALOG_GAIN_M0), }, { "Analogue Gain c0", V4L2_CID_CCS_ANALOGUE_GAIN_C0, CCS_LIM(sensor, ANALOG_GAIN_C0), }, { "Analogue Gain m1", V4L2_CID_CCS_ANALOGUE_GAIN_M1, CCS_LIM(sensor, ANALOG_GAIN_M1), }, { "Analogue Gain c1", V4L2_CID_CCS_ANALOGUE_GAIN_C1, CCS_LIM(sensor, ANALOG_GAIN_C1), }, }; struct v4l2_ctrl_config ctrl_cfg = { .type = V4L2_CTRL_TYPE_INTEGER, .ops = &ccs_ctrl_ops, .flags = V4L2_CTRL_FLAG_READ_ONLY, .step = 1, }; unsigned int i; for (i = 0; i < ARRAY_SIZE(gain_ctrls); i++) { ctrl_cfg.name = gain_ctrls[i].name; ctrl_cfg.id = gain_ctrls[i].id; ctrl_cfg.min = ctrl_cfg.max = ctrl_cfg.def = gain_ctrls[i].value; v4l2_ctrl_new_custom(&sensor->pixel_array->ctrl_handler, &ctrl_cfg, NULL); } v4l2_ctrl_new_std(&sensor->pixel_array->ctrl_handler, &ccs_ctrl_ops, V4L2_CID_ANALOGUE_GAIN, CCS_LIM(sensor, ANALOG_GAIN_CODE_MIN), CCS_LIM(sensor, ANALOG_GAIN_CODE_MAX), max(CCS_LIM(sensor, ANALOG_GAIN_CODE_STEP), 1U), CCS_LIM(sensor, ANALOG_GAIN_CODE_MIN)); } break; case CCS_ANALOG_GAIN_CAPABILITY_ALTERNATE_GLOBAL: { struct { const char *name; u32 id; u16 min, max, step; } const gain_ctrls[] = { { "Analogue Linear Gain", V4L2_CID_CCS_ANALOGUE_LINEAR_GAIN, CCS_LIM(sensor, ANALOG_LINEAR_GAIN_MIN), CCS_LIM(sensor, ANALOG_LINEAR_GAIN_MAX), max(CCS_LIM(sensor, ANALOG_LINEAR_GAIN_STEP_SIZE), 1U), }, { "Analogue Exponential Gain", V4L2_CID_CCS_ANALOGUE_EXPONENTIAL_GAIN, CCS_LIM(sensor, ANALOG_EXPONENTIAL_GAIN_MIN), CCS_LIM(sensor, ANALOG_EXPONENTIAL_GAIN_MAX), max(CCS_LIM(sensor, ANALOG_EXPONENTIAL_GAIN_STEP_SIZE), 1U), }, }; struct v4l2_ctrl_config ctrl_cfg = { .type = V4L2_CTRL_TYPE_INTEGER, .ops = &ccs_ctrl_ops, }; unsigned int i; for (i = 0; i < ARRAY_SIZE(gain_ctrls); i++) { ctrl_cfg.name = gain_ctrls[i].name; ctrl_cfg.min = ctrl_cfg.def = gain_ctrls[i].min; ctrl_cfg.max = gain_ctrls[i].max; ctrl_cfg.step = gain_ctrls[i].step; ctrl_cfg.id = gain_ctrls[i].id; v4l2_ctrl_new_custom(&sensor->pixel_array->ctrl_handler, &ctrl_cfg, NULL); } } } if (CCS_LIM(sensor, SHADING_CORRECTION_CAPABILITY) & (CCS_SHADING_CORRECTION_CAPABILITY_COLOR_SHADING | CCS_SHADING_CORRECTION_CAPABILITY_LUMINANCE_CORRECTION)) { const struct v4l2_ctrl_config ctrl_cfg = { .name = "Shading Correction", .type = V4L2_CTRL_TYPE_BOOLEAN, .id = V4L2_CID_CCS_SHADING_CORRECTION, .ops = &ccs_ctrl_ops, .max = 1, .step = 1, }; v4l2_ctrl_new_custom(&sensor->pixel_array->ctrl_handler, &ctrl_cfg, NULL); } if (CCS_LIM(sensor, SHADING_CORRECTION_CAPABILITY) & CCS_SHADING_CORRECTION_CAPABILITY_LUMINANCE_CORRECTION) { const struct v4l2_ctrl_config ctrl_cfg = { .name = "Luminance Correction Level", .type = V4L2_CTRL_TYPE_BOOLEAN, .id = V4L2_CID_CCS_LUMINANCE_CORRECTION_LEVEL, .ops = &ccs_ctrl_ops, .max = 255, .step = 1, .def = 128, }; sensor->luminance_level = v4l2_ctrl_new_custom(&sensor->pixel_array->ctrl_handler, &ctrl_cfg, NULL); } if (CCS_LIM(sensor, DIGITAL_GAIN_CAPABILITY) == CCS_DIGITAL_GAIN_CAPABILITY_GLOBAL || CCS_LIM(sensor, DIGITAL_GAIN_CAPABILITY) == SMIAPP_DIGITAL_GAIN_CAPABILITY_PER_CHANNEL) v4l2_ctrl_new_std(&sensor->pixel_array->ctrl_handler, &ccs_ctrl_ops, V4L2_CID_DIGITAL_GAIN, CCS_LIM(sensor, DIGITAL_GAIN_MIN), CCS_LIM(sensor, DIGITAL_GAIN_MAX), max(CCS_LIM(sensor, DIGITAL_GAIN_STEP_SIZE), 1U), 0x100); /* Exposure limits will be updated soon, use just something here. */ sensor->exposure = v4l2_ctrl_new_std( &sensor->pixel_array->ctrl_handler, &ccs_ctrl_ops, V4L2_CID_EXPOSURE, 0, 0, 1, 0); sensor->hflip = v4l2_ctrl_new_std( &sensor->pixel_array->ctrl_handler, &ccs_ctrl_ops, V4L2_CID_HFLIP, 0, 1, 1, 0); sensor->vflip = v4l2_ctrl_new_std( &sensor->pixel_array->ctrl_handler, &ccs_ctrl_ops, V4L2_CID_VFLIP, 0, 1, 1, 0); sensor->vblank = v4l2_ctrl_new_std( &sensor->pixel_array->ctrl_handler, &ccs_ctrl_ops, V4L2_CID_VBLANK, 0, 1, 1, 0); if (sensor->vblank) sensor->vblank->flags |= V4L2_CTRL_FLAG_UPDATE; sensor->hblank = v4l2_ctrl_new_std( &sensor->pixel_array->ctrl_handler, &ccs_ctrl_ops, V4L2_CID_HBLANK, 0, 1, 1, 0); if (sensor->hblank) sensor->hblank->flags |= V4L2_CTRL_FLAG_UPDATE; sensor->pixel_rate_parray = v4l2_ctrl_new_std( &sensor->pixel_array->ctrl_handler, &ccs_ctrl_ops, V4L2_CID_PIXEL_RATE, 1, INT_MAX, 1, 1); v4l2_ctrl_new_std_menu_items(&sensor->pixel_array->ctrl_handler, &ccs_ctrl_ops, V4L2_CID_TEST_PATTERN, ARRAY_SIZE(ccs_test_patterns) - 1, 0, 0, ccs_test_patterns); if (sensor->pixel_array->ctrl_handler.error) { dev_err(&client->dev, "pixel array controls initialization failed (%d)\n", sensor->pixel_array->ctrl_handler.error); return sensor->pixel_array->ctrl_handler.error; } sensor->pixel_array->sd.ctrl_handler = &sensor->pixel_array->ctrl_handler; v4l2_ctrl_cluster(2, &sensor->hflip); rval = v4l2_ctrl_handler_init(&sensor->src->ctrl_handler, 0); if (rval) return rval; sensor->src->ctrl_handler.lock = &sensor->mutex; sensor->pixel_rate_csi = v4l2_ctrl_new_std( &sensor->src->ctrl_handler, &ccs_ctrl_ops, V4L2_CID_PIXEL_RATE, 1, INT_MAX, 1, 1); if (sensor->src->ctrl_handler.error) { dev_err(&client->dev, "src controls initialization failed (%d)\n", sensor->src->ctrl_handler.error); return sensor->src->ctrl_handler.error; } sensor->src->sd.ctrl_handler = &sensor->src->ctrl_handler; return 0; } /* * For controls that require information on available media bus codes * and linke frequencies. */ static int ccs_init_late_controls(struct ccs_sensor *sensor) { unsigned long *valid_link_freqs = &sensor->valid_link_freqs[ sensor->csi_format->compressed - sensor->compressed_min_bpp]; unsigned int i; for (i = 0; i < ARRAY_SIZE(sensor->test_data); i++) { int max_value = (1 << sensor->csi_format->width) - 1; sensor->test_data[i] = v4l2_ctrl_new_std( &sensor->pixel_array->ctrl_handler, &ccs_ctrl_ops, V4L2_CID_TEST_PATTERN_RED + i, 0, max_value, 1, max_value); } sensor->link_freq = v4l2_ctrl_new_int_menu( &sensor->src->ctrl_handler, &ccs_ctrl_ops, V4L2_CID_LINK_FREQ, __fls(*valid_link_freqs), __ffs(*valid_link_freqs), sensor->hwcfg.op_sys_clock); return sensor->src->ctrl_handler.error; } static void ccs_free_controls(struct ccs_sensor *sensor) { unsigned int i; for (i = 0; i < sensor->ssds_used; i++) v4l2_ctrl_handler_free(&sensor->ssds[i].ctrl_handler); } static int ccs_get_mbus_formats(struct ccs_sensor *sensor) { struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd); struct ccs_pll *pll = &sensor->pll; u8 compressed_max_bpp = 0; unsigned int type, n; unsigned int i, pixel_order; int rval; type = CCS_LIM(sensor, DATA_FORMAT_MODEL_TYPE); dev_dbg(&client->dev, "data_format_model_type %u\n", type); rval = ccs_read(sensor, PIXEL_ORDER, &pixel_order); if (rval) return rval; if (pixel_order >= ARRAY_SIZE(pixel_order_str)) { dev_dbg(&client->dev, "bad pixel order %u\n", pixel_order); return -EINVAL; } dev_dbg(&client->dev, "pixel order %u (%s)\n", pixel_order, pixel_order_str[pixel_order]); switch (type) { case CCS_DATA_FORMAT_MODEL_TYPE_NORMAL: n = SMIAPP_DATA_FORMAT_MODEL_TYPE_NORMAL_N; break; case CCS_DATA_FORMAT_MODEL_TYPE_EXTENDED: n = CCS_LIM_DATA_FORMAT_DESCRIPTOR_MAX_N + 1; break; default: return -EINVAL; } sensor->default_pixel_order = pixel_order; sensor->mbus_frame_fmts = 0; for (i = 0; i < n; i++) { unsigned int fmt, j; fmt = CCS_LIM_AT(sensor, DATA_FORMAT_DESCRIPTOR, i); dev_dbg(&client->dev, "%u: bpp %u, compressed %u\n", i, fmt >> 8, (u8)fmt); for (j = 0; j < ARRAY_SIZE(ccs_csi_data_formats); j++) { const struct ccs_csi_data_format *f = &ccs_csi_data_formats[j]; if (f->pixel_order != CCS_PIXEL_ORDER_GRBG) continue; if (f->width != fmt >> CCS_DATA_FORMAT_DESCRIPTOR_UNCOMPRESSED_SHIFT || f->compressed != (fmt & CCS_DATA_FORMAT_DESCRIPTOR_COMPRESSED_MASK)) continue; dev_dbg(&client->dev, "jolly good! %u\n", j); sensor->default_mbus_frame_fmts |= 1 << j; } } /* Figure out which BPP values can be used with which formats. */ pll->binning_horizontal = 1; pll->binning_vertical = 1; pll->scale_m = sensor->scale_m; for (i = 0; i < ARRAY_SIZE(ccs_csi_data_formats); i++) { sensor->compressed_min_bpp = min(ccs_csi_data_formats[i].compressed, sensor->compressed_min_bpp); compressed_max_bpp = max(ccs_csi_data_formats[i].compressed, compressed_max_bpp); } sensor->valid_link_freqs = devm_kcalloc( &client->dev, compressed_max_bpp - sensor->compressed_min_bpp + 1, sizeof(*sensor->valid_link_freqs), GFP_KERNEL); if (!sensor->valid_link_freqs) return -ENOMEM; for (i = 0; i < ARRAY_SIZE(ccs_csi_data_formats); i++) { const struct ccs_csi_data_format *f = &ccs_csi_data_formats[i]; unsigned long *valid_link_freqs = &sensor->valid_link_freqs[ f->compressed - sensor->compressed_min_bpp]; unsigned int j; if (!(sensor->default_mbus_frame_fmts & 1 << i)) continue; pll->bits_per_pixel = f->compressed; for (j = 0; sensor->hwcfg.op_sys_clock[j]; j++) { pll->link_freq = sensor->hwcfg.op_sys_clock[j]; rval = ccs_pll_try(sensor, pll); dev_dbg(&client->dev, "link freq %u Hz, bpp %u %s\n", pll->link_freq, pll->bits_per_pixel, rval ? "not ok" : "ok"); if (rval) continue; set_bit(j, valid_link_freqs); } if (!*valid_link_freqs) { dev_info(&client->dev, "no valid link frequencies for %u bpp\n", f->compressed); sensor->default_mbus_frame_fmts &= ~BIT(i); continue; } if (!sensor->csi_format || f->width > sensor->csi_format->width || (f->width == sensor->csi_format->width && f->compressed > sensor->csi_format->compressed)) { sensor->csi_format = f; sensor->internal_csi_format = f; } } if (!sensor->csi_format) { dev_err(&client->dev, "no supported mbus code found\n"); return -EINVAL; } ccs_update_mbus_formats(sensor); return 0; } static void ccs_update_blanking(struct ccs_sensor *sensor) { struct v4l2_ctrl *vblank = sensor->vblank; struct v4l2_ctrl *hblank = sensor->hblank; u16 min_fll, max_fll, min_llp, max_llp, min_lbp; int min, max; if (sensor->binning_vertical > 1 || sensor->binning_horizontal > 1) { min_fll = CCS_LIM(sensor, MIN_FRAME_LENGTH_LINES_BIN); max_fll = CCS_LIM(sensor, MAX_FRAME_LENGTH_LINES_BIN); min_llp = CCS_LIM(sensor, MIN_LINE_LENGTH_PCK_BIN); max_llp = CCS_LIM(sensor, MAX_LINE_LENGTH_PCK_BIN); min_lbp = CCS_LIM(sensor, MIN_LINE_BLANKING_PCK_BIN); } else { min_fll = CCS_LIM(sensor, MIN_FRAME_LENGTH_LINES); max_fll = CCS_LIM(sensor, MAX_FRAME_LENGTH_LINES); min_llp = CCS_LIM(sensor, MIN_LINE_LENGTH_PCK); max_llp = CCS_LIM(sensor, MAX_LINE_LENGTH_PCK); min_lbp = CCS_LIM(sensor, MIN_LINE_BLANKING_PCK); } min = max_t(int, CCS_LIM(sensor, MIN_FRAME_BLANKING_LINES), min_fll - sensor->pixel_array->crop[CCS_PA_PAD_SRC].height); max = max_fll - sensor->pixel_array->crop[CCS_PA_PAD_SRC].height; __v4l2_ctrl_modify_range(vblank, min, max, vblank->step, min); min = max_t(int, min_llp - sensor->pixel_array->crop[CCS_PA_PAD_SRC].width, min_lbp); max = max_llp - sensor->pixel_array->crop[CCS_PA_PAD_SRC].width; __v4l2_ctrl_modify_range(hblank, min, max, hblank->step, min); __ccs_update_exposure_limits(sensor); } static int ccs_pll_blanking_update(struct ccs_sensor *sensor) { struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd); int rval; rval = ccs_pll_update(sensor); if (rval < 0) return rval; /* Output from pixel array, including blanking */ ccs_update_blanking(sensor); dev_dbg(&client->dev, "vblank\t\t%d\n", sensor->vblank->val); dev_dbg(&client->dev, "hblank\t\t%d\n", sensor->hblank->val); dev_dbg(&client->dev, "real timeperframe\t100/%d\n", sensor->pll.pixel_rate_pixel_array / ((sensor->pixel_array->crop[CCS_PA_PAD_SRC].width + sensor->hblank->val) * (sensor->pixel_array->crop[CCS_PA_PAD_SRC].height + sensor->vblank->val) / 100)); return 0; } /* * * SMIA++ NVM handling * */ static int ccs_read_nvm_page(struct ccs_sensor *sensor, u32 p, u8 *nvm, u8 *status) { unsigned int i; int rval; u32 s; *status = 0; rval = ccs_write(sensor, DATA_TRANSFER_IF_1_PAGE_SELECT, p); if (rval) return rval; rval = ccs_write(sensor, DATA_TRANSFER_IF_1_CTRL, CCS_DATA_TRANSFER_IF_1_CTRL_ENABLE); if (rval) return rval; rval = ccs_read(sensor, DATA_TRANSFER_IF_1_STATUS, &s); if (rval) return rval; if (s & CCS_DATA_TRANSFER_IF_1_STATUS_IMPROPER_IF_USAGE) { *status = s; return -ENODATA; } if (CCS_LIM(sensor, DATA_TRANSFER_IF_CAPABILITY) & CCS_DATA_TRANSFER_IF_CAPABILITY_POLLING) { for (i = 1000; i > 0; i--) { if (s & CCS_DATA_TRANSFER_IF_1_STATUS_READ_IF_READY) break; rval = ccs_read(sensor, DATA_TRANSFER_IF_1_STATUS, &s); if (rval) return rval; } if (!i) return -ETIMEDOUT; } for (i = 0; i <= CCS_LIM_DATA_TRANSFER_IF_1_DATA_MAX_P; i++) { u32 v; rval = ccs_read(sensor, DATA_TRANSFER_IF_1_DATA(i), &v); if (rval) return rval; *nvm++ = v; } return 0; } static int ccs_read_nvm(struct ccs_sensor *sensor, unsigned char *nvm, size_t nvm_size) { u8 status = 0; u32 p; int rval = 0, rval2; for (p = 0; p < nvm_size / (CCS_LIM_DATA_TRANSFER_IF_1_DATA_MAX_P + 1) && !rval; p++) { rval = ccs_read_nvm_page(sensor, p, nvm, &status); nvm += CCS_LIM_DATA_TRANSFER_IF_1_DATA_MAX_P + 1; } if (rval == -ENODATA && status & CCS_DATA_TRANSFER_IF_1_STATUS_IMPROPER_IF_USAGE) rval = 0; rval2 = ccs_write(sensor, DATA_TRANSFER_IF_1_CTRL, 0); if (rval < 0) return rval; else return rval2 ?: p * (CCS_LIM_DATA_TRANSFER_IF_1_DATA_MAX_P + 1); } /* * * SMIA++ CCI address control * */ static int ccs_change_cci_addr(struct ccs_sensor *sensor) { struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd); int rval; u32 val; client->addr = sensor->hwcfg.i2c_addr_dfl; rval = ccs_write(sensor, CCI_ADDRESS_CTRL, sensor->hwcfg.i2c_addr_alt << 1); if (rval) return rval; client->addr = sensor->hwcfg.i2c_addr_alt; /* verify addr change went ok */ rval = ccs_read(sensor, CCI_ADDRESS_CTRL, &val); if (rval) return rval; if (val != sensor->hwcfg.i2c_addr_alt << 1) return -ENODEV; return 0; } /* * * SMIA++ Mode Control * */ static int ccs_setup_flash_strobe(struct ccs_sensor *sensor) { struct ccs_flash_strobe_parms *strobe_setup; unsigned int ext_freq = sensor->hwcfg.ext_clk; u32 tmp; u32 strobe_adjustment; u32 strobe_width_high_rs; int rval; strobe_setup = sensor->hwcfg.strobe_setup; /* * How to calculate registers related to strobe length. Please * do not change, or if you do at least know what you're * doing. :-) * * Sakari Ailus <[email protected]> 2010-10-25 * * flash_strobe_length [us] / 10^6 = (tFlash_strobe_width_ctrl * / EXTCLK freq [Hz]) * flash_strobe_adjustment * * tFlash_strobe_width_ctrl E N, [1 - 0xffff] * flash_strobe_adjustment E N, [1 - 0xff] * * The formula above is written as below to keep it on one * line: * * l / 10^6 = w / e * a * * Let's mark w * a by x: * * x = w * a * * Thus, we get: * * x = l * e / 10^6 * * The strobe width must be at least as long as requested, * thus rounding upwards is needed. * * x = (l * e + 10^6 - 1) / 10^6 * ----------------------------- * * Maximum possible accuracy is wanted at all times. Thus keep * a as small as possible. * * Calculate a, assuming maximum w, with rounding upwards: * * a = (x + (2^16 - 1) - 1) / (2^16 - 1) * ------------------------------------- * * Thus, we also get w, with that a, with rounding upwards: * * w = (x + a - 1) / a * ------------------- * * To get limits: * * x E [1, (2^16 - 1) * (2^8 - 1)] * * Substituting maximum x to the original formula (with rounding), * the maximum l is thus * * (2^16 - 1) * (2^8 - 1) * 10^6 = l * e + 10^6 - 1 * * l = (10^6 * (2^16 - 1) * (2^8 - 1) - 10^6 + 1) / e * -------------------------------------------------- * * flash_strobe_length must be clamped between 1 and * (10^6 * (2^16 - 1) * (2^8 - 1) - 10^6 + 1) / EXTCLK freq. * * Then, * * flash_strobe_adjustment = ((flash_strobe_length * * EXTCLK freq + 10^6 - 1) / 10^6 + (2^16 - 1) - 1) / (2^16 - 1) * * tFlash_strobe_width_ctrl = ((flash_strobe_length * * EXTCLK freq + 10^6 - 1) / 10^6 + * flash_strobe_adjustment - 1) / flash_strobe_adjustment */ tmp = div_u64(1000000ULL * ((1 << 16) - 1) * ((1 << 8) - 1) - 1000000 + 1, ext_freq); strobe_setup->strobe_width_high_us = clamp_t(u32, strobe_setup->strobe_width_high_us, 1, tmp); tmp = div_u64(((u64)strobe_setup->strobe_width_high_us * (u64)ext_freq + 1000000 - 1), 1000000ULL); strobe_adjustment = (tmp + (1 << 16) - 1 - 1) / ((1 << 16) - 1); strobe_width_high_rs = (tmp + strobe_adjustment - 1) / strobe_adjustment; rval = ccs_write(sensor, FLASH_MODE_RS, strobe_setup->mode); if (rval < 0) goto out; rval = ccs_write(sensor, FLASH_STROBE_ADJUSTMENT, strobe_adjustment); if (rval < 0) goto out; rval = ccs_write(sensor, TFLASH_STROBE_WIDTH_HIGH_RS_CTRL, strobe_width_high_rs); if (rval < 0) goto out; rval = ccs_write(sensor, TFLASH_STROBE_DELAY_RS_CTRL, strobe_setup->strobe_delay); if (rval < 0) goto out; rval = ccs_write(sensor, FLASH_STROBE_START_POINT, strobe_setup->stobe_start_point); if (rval < 0) goto out; rval = ccs_write(sensor, FLASH_TRIGGER_RS, strobe_setup->trigger); out: sensor->hwcfg.strobe_setup->trigger = 0; return rval; } /* ----------------------------------------------------------------------------- * Power management */ static int ccs_write_msr_regs(struct ccs_sensor *sensor) { int rval; rval = ccs_write_data_regs(sensor, sensor->sdata.sensor_manufacturer_regs, sensor->sdata.num_sensor_manufacturer_regs); if (rval) return rval; return ccs_write_data_regs(sensor, sensor->mdata.module_manufacturer_regs, sensor->mdata.num_module_manufacturer_regs); } static int ccs_update_phy_ctrl(struct ccs_sensor *sensor) { struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd); u8 val; if (!sensor->ccs_limits) return 0; if (CCS_LIM(sensor, PHY_CTRL_CAPABILITY) & CCS_PHY_CTRL_CAPABILITY_AUTO_PHY_CTL) { val = CCS_PHY_CTRL_AUTO; } else if (CCS_LIM(sensor, PHY_CTRL_CAPABILITY) & CCS_PHY_CTRL_CAPABILITY_UI_PHY_CTL) { val = CCS_PHY_CTRL_UI; } else { dev_err(&client->dev, "manual PHY control not supported\n"); return -EINVAL; } return ccs_write(sensor, PHY_CTRL, val); } static int ccs_power_on(struct device *dev) { struct v4l2_subdev *subdev = dev_get_drvdata(dev); struct ccs_subdev *ssd = to_ccs_subdev(subdev); /* * The sub-device related to the I2C device is always the * source one, i.e. ssds[0]. */ struct ccs_sensor *sensor = container_of(ssd, struct ccs_sensor, ssds[0]); const struct ccs_device *ccsdev = device_get_match_data(dev); int rval; rval = regulator_bulk_enable(ARRAY_SIZE(ccs_regulators), sensor->regulators); if (rval) { dev_err(dev, "failed to enable vana regulator\n"); return rval; } if (sensor->reset || sensor->xshutdown || sensor->ext_clk) { unsigned int sleep; rval = clk_prepare_enable(sensor->ext_clk); if (rval < 0) { dev_dbg(dev, "failed to enable xclk\n"); goto out_xclk_fail; } gpiod_set_value(sensor->reset, 0); gpiod_set_value(sensor->xshutdown, 1); if (ccsdev->flags & CCS_DEVICE_FLAG_IS_SMIA) sleep = SMIAPP_RESET_DELAY(sensor->hwcfg.ext_clk); else sleep = 5000; usleep_range(sleep, sleep); } /* * Failures to respond to the address change command have been noticed. * Those failures seem to be caused by the sensor requiring a longer * boot time than advertised. An additional 10ms delay seems to work * around the issue, but the SMIA++ I2C write retry hack makes the delay * unnecessary. The failures need to be investigated to find a proper * fix, and a delay will likely need to be added here if the I2C write * retry hack is reverted before the root cause of the boot time issue * is found. */ if (!sensor->reset && !sensor->xshutdown) { u8 retry = 100; u32 reset; rval = ccs_write(sensor, SOFTWARE_RESET, CCS_SOFTWARE_RESET_ON); if (rval < 0) { dev_err(dev, "software reset failed\n"); goto out_cci_addr_fail; } do { rval = ccs_read(sensor, SOFTWARE_RESET, &reset); reset = !rval && reset == CCS_SOFTWARE_RESET_OFF; if (reset) break; usleep_range(1000, 2000); } while (--retry); if (!reset) { dev_err(dev, "software reset failed\n"); rval = -EIO; goto out_cci_addr_fail; } } if (sensor->hwcfg.i2c_addr_alt) { rval = ccs_change_cci_addr(sensor); if (rval) { dev_err(dev, "cci address change error\n"); goto out_cci_addr_fail; } } rval = ccs_write(sensor, COMPRESSION_MODE, CCS_COMPRESSION_MODE_DPCM_PCM_SIMPLE); if (rval) { dev_err(dev, "compression mode set failed\n"); goto out_cci_addr_fail; } rval = ccs_write(sensor, EXTCLK_FREQUENCY_MHZ, sensor->hwcfg.ext_clk / (1000000 / (1 << 8))); if (rval) { dev_err(dev, "extclk frequency set failed\n"); goto out_cci_addr_fail; } rval = ccs_write(sensor, CSI_LANE_MODE, sensor->hwcfg.lanes - 1); if (rval) { dev_err(dev, "csi lane mode set failed\n"); goto out_cci_addr_fail; } rval = ccs_write(sensor, FAST_STANDBY_CTRL, CCS_FAST_STANDBY_CTRL_FRAME_TRUNCATION); if (rval) { dev_err(dev, "fast standby set failed\n"); goto out_cci_addr_fail; } rval = ccs_write(sensor, CSI_SIGNALING_MODE, sensor->hwcfg.csi_signalling_mode); if (rval) { dev_err(dev, "csi signalling mode set failed\n"); goto out_cci_addr_fail; } rval = ccs_update_phy_ctrl(sensor); if (rval < 0) goto out_cci_addr_fail; rval = ccs_write_msr_regs(sensor); if (rval) goto out_cci_addr_fail; rval = ccs_call_quirk(sensor, post_poweron); if (rval) { dev_err(dev, "post_poweron quirks failed\n"); goto out_cci_addr_fail; } return 0; out_cci_addr_fail: gpiod_set_value(sensor->reset, 1); gpiod_set_value(sensor->xshutdown, 0); clk_disable_unprepare(sensor->ext_clk); out_xclk_fail: regulator_bulk_disable(ARRAY_SIZE(ccs_regulators), sensor->regulators); return rval; } static int ccs_power_off(struct device *dev) { struct v4l2_subdev *subdev = dev_get_drvdata(dev); struct ccs_subdev *ssd = to_ccs_subdev(subdev); struct ccs_sensor *sensor = container_of(ssd, struct ccs_sensor, ssds[0]); /* * Currently power/clock to lens are enable/disabled separately * but they are essentially the same signals. So if the sensor is * powered off while the lens is powered on the sensor does not * really see a power off and next time the cci address change * will fail. So do a soft reset explicitly here. */ if (sensor->hwcfg.i2c_addr_alt) ccs_write(sensor, SOFTWARE_RESET, CCS_SOFTWARE_RESET_ON); gpiod_set_value(sensor->reset, 1); gpiod_set_value(sensor->xshutdown, 0); clk_disable_unprepare(sensor->ext_clk); usleep_range(5000, 5000); regulator_bulk_disable(ARRAY_SIZE(ccs_regulators), sensor->regulators); sensor->streaming = false; return 0; } /* ----------------------------------------------------------------------------- * Video stream management */ static int ccs_start_streaming(struct ccs_sensor *sensor) { struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd); unsigned int binning_mode; int rval; mutex_lock(&sensor->mutex); rval = ccs_write(sensor, CSI_DATA_FORMAT, (sensor->csi_format->width << 8) | sensor->csi_format->compressed); if (rval) goto out; /* Binning configuration */ if (sensor->binning_horizontal == 1 && sensor->binning_vertical == 1) { binning_mode = 0; } else { u8 binning_type = (sensor->binning_horizontal << 4) | sensor->binning_vertical; rval = ccs_write(sensor, BINNING_TYPE, binning_type); if (rval < 0) goto out; binning_mode = 1; } rval = ccs_write(sensor, BINNING_MODE, binning_mode); if (rval < 0) goto out; /* Set up PLL */ rval = ccs_pll_configure(sensor); if (rval) goto out; /* Analog crop start coordinates */ rval = ccs_write(sensor, X_ADDR_START, sensor->pixel_array->crop[CCS_PA_PAD_SRC].left); if (rval < 0) goto out; rval = ccs_write(sensor, Y_ADDR_START, sensor->pixel_array->crop[CCS_PA_PAD_SRC].top); if (rval < 0) goto out; /* Analog crop end coordinates */ rval = ccs_write( sensor, X_ADDR_END, sensor->pixel_array->crop[CCS_PA_PAD_SRC].left + sensor->pixel_array->crop[CCS_PA_PAD_SRC].width - 1); if (rval < 0) goto out; rval = ccs_write( sensor, Y_ADDR_END, sensor->pixel_array->crop[CCS_PA_PAD_SRC].top + sensor->pixel_array->crop[CCS_PA_PAD_SRC].height - 1); if (rval < 0) goto out; /* * Output from pixel array, including blanking, is set using * controls below. No need to set here. */ /* Digital crop */ if (CCS_LIM(sensor, DIGITAL_CROP_CAPABILITY) == CCS_DIGITAL_CROP_CAPABILITY_INPUT_CROP) { rval = ccs_write( sensor, DIGITAL_CROP_X_OFFSET, sensor->scaler->crop[CCS_PAD_SINK].left); if (rval < 0) goto out; rval = ccs_write( sensor, DIGITAL_CROP_Y_OFFSET, sensor->scaler->crop[CCS_PAD_SINK].top); if (rval < 0) goto out; rval = ccs_write( sensor, DIGITAL_CROP_IMAGE_WIDTH, sensor->scaler->crop[CCS_PAD_SINK].width); if (rval < 0) goto out; rval = ccs_write( sensor, DIGITAL_CROP_IMAGE_HEIGHT, sensor->scaler->crop[CCS_PAD_SINK].height); if (rval < 0) goto out; } /* Scaling */ if (CCS_LIM(sensor, SCALING_CAPABILITY) != CCS_SCALING_CAPABILITY_NONE) { rval = ccs_write(sensor, SCALING_MODE, sensor->scaling_mode); if (rval < 0) goto out; rval = ccs_write(sensor, SCALE_M, sensor->scale_m); if (rval < 0) goto out; } /* Output size from sensor */ rval = ccs_write(sensor, X_OUTPUT_SIZE, sensor->src->crop[CCS_PAD_SRC].width); if (rval < 0) goto out; rval = ccs_write(sensor, Y_OUTPUT_SIZE, sensor->src->crop[CCS_PAD_SRC].height); if (rval < 0) goto out; if (CCS_LIM(sensor, FLASH_MODE_CAPABILITY) & (CCS_FLASH_MODE_CAPABILITY_SINGLE_STROBE | SMIAPP_FLASH_MODE_CAPABILITY_MULTIPLE_STROBE) && sensor->hwcfg.strobe_setup != NULL && sensor->hwcfg.strobe_setup->trigger != 0) { rval = ccs_setup_flash_strobe(sensor); if (rval) goto out; } rval = ccs_call_quirk(sensor, pre_streamon); if (rval) { dev_err(&client->dev, "pre_streamon quirks failed\n"); goto out; } rval = ccs_write(sensor, MODE_SELECT, CCS_MODE_SELECT_STREAMING); out: mutex_unlock(&sensor->mutex); return rval; } static int ccs_stop_streaming(struct ccs_sensor *sensor) { struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd); int rval; mutex_lock(&sensor->mutex); rval = ccs_write(sensor, MODE_SELECT, CCS_MODE_SELECT_SOFTWARE_STANDBY); if (rval) goto out; rval = ccs_call_quirk(sensor, post_streamoff); if (rval) dev_err(&client->dev, "post_streamoff quirks failed\n"); out: mutex_unlock(&sensor->mutex); return rval; } /* ----------------------------------------------------------------------------- * V4L2 subdev video operations */ static int ccs_pm_get_init(struct ccs_sensor *sensor) { struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd); int rval; /* * It can't use pm_runtime_resume_and_get() here, as the driver * relies at the returned value to detect if the device was already * active or not. */ rval = pm_runtime_get_sync(&client->dev); if (rval < 0) goto error; /* Device was already active, so don't set controls */ if (rval == 1) return 0; /* Restore V4L2 controls to the previously suspended device */ rval = v4l2_ctrl_handler_setup(&sensor->pixel_array->ctrl_handler); if (rval) goto error; rval = v4l2_ctrl_handler_setup(&sensor->src->ctrl_handler); if (rval) goto error; /* Keep PM runtime usage_count incremented on success */ return 0; error: pm_runtime_put(&client->dev); return rval; } static int ccs_set_stream(struct v4l2_subdev *subdev, int enable) { struct ccs_sensor *sensor = to_ccs_sensor(subdev); struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd); int rval; if (sensor->streaming == enable) return 0; if (!enable) { ccs_stop_streaming(sensor); sensor->streaming = false; pm_runtime_mark_last_busy(&client->dev); pm_runtime_put_autosuspend(&client->dev); return 0; } rval = ccs_pm_get_init(sensor); if (rval) return rval; sensor->streaming = true; rval = ccs_start_streaming(sensor); if (rval < 0) { sensor->streaming = false; pm_runtime_mark_last_busy(&client->dev); pm_runtime_put_autosuspend(&client->dev); } return rval; } static int ccs_pre_streamon(struct v4l2_subdev *subdev, u32 flags) { struct ccs_sensor *sensor = to_ccs_sensor(subdev); struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd); int rval; if (flags & V4L2_SUBDEV_PRE_STREAMON_FL_MANUAL_LP) { switch (sensor->hwcfg.csi_signalling_mode) { case CCS_CSI_SIGNALING_MODE_CSI_2_DPHY: if (!(CCS_LIM(sensor, PHY_CTRL_CAPABILITY_2) & CCS_PHY_CTRL_CAPABILITY_2_MANUAL_LP_DPHY)) return -EACCES; break; case CCS_CSI_SIGNALING_MODE_CSI_2_CPHY: if (!(CCS_LIM(sensor, PHY_CTRL_CAPABILITY_2) & CCS_PHY_CTRL_CAPABILITY_2_MANUAL_LP_CPHY)) return -EACCES; break; default: return -EACCES; } } rval = ccs_pm_get_init(sensor); if (rval) return rval; if (flags & V4L2_SUBDEV_PRE_STREAMON_FL_MANUAL_LP) { rval = ccs_write(sensor, MANUAL_LP_CTRL, CCS_MANUAL_LP_CTRL_ENABLE); if (rval) pm_runtime_put(&client->dev); } return rval; } static int ccs_post_streamoff(struct v4l2_subdev *subdev) { struct ccs_sensor *sensor = to_ccs_sensor(subdev); struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd); return pm_runtime_put(&client->dev); } static int ccs_enum_mbus_code(struct v4l2_subdev *subdev, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_mbus_code_enum *code) { struct i2c_client *client = v4l2_get_subdevdata(subdev); struct ccs_sensor *sensor = to_ccs_sensor(subdev); unsigned int i; int idx = -1; int rval = -EINVAL; mutex_lock(&sensor->mutex); dev_err(&client->dev, "subdev %s, pad %u, index %u\n", subdev->name, code->pad, code->index); if (subdev != &sensor->src->sd || code->pad != CCS_PAD_SRC) { if (code->index) goto out; code->code = sensor->internal_csi_format->code; rval = 0; goto out; } for (i = 0; i < ARRAY_SIZE(ccs_csi_data_formats); i++) { if (sensor->mbus_frame_fmts & (1 << i)) idx++; if (idx == code->index) { code->code = ccs_csi_data_formats[i].code; dev_err(&client->dev, "found index %u, i %u, code %x\n", code->index, i, code->code); rval = 0; break; } } out: mutex_unlock(&sensor->mutex); return rval; } static u32 __ccs_get_mbus_code(struct v4l2_subdev *subdev, unsigned int pad) { struct ccs_sensor *sensor = to_ccs_sensor(subdev); if (subdev == &sensor->src->sd && pad == CCS_PAD_SRC) return sensor->csi_format->code; else return sensor->internal_csi_format->code; } static int __ccs_get_format(struct v4l2_subdev *subdev, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *fmt) { struct ccs_subdev *ssd = to_ccs_subdev(subdev); if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) { fmt->format = *v4l2_subdev_get_try_format(subdev, sd_state, fmt->pad); } else { struct v4l2_rect *r; if (fmt->pad == ssd->source_pad) r = &ssd->crop[ssd->source_pad]; else r = &ssd->sink_fmt; fmt->format.code = __ccs_get_mbus_code(subdev, fmt->pad); fmt->format.width = r->width; fmt->format.height = r->height; fmt->format.field = V4L2_FIELD_NONE; } return 0; } static int ccs_get_format(struct v4l2_subdev *subdev, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *fmt) { struct ccs_sensor *sensor = to_ccs_sensor(subdev); int rval; mutex_lock(&sensor->mutex); rval = __ccs_get_format(subdev, sd_state, fmt); mutex_unlock(&sensor->mutex); return rval; } static void ccs_get_crop_compose(struct v4l2_subdev *subdev, struct v4l2_subdev_state *sd_state, struct v4l2_rect **crops, struct v4l2_rect **comps, int which) { struct ccs_subdev *ssd = to_ccs_subdev(subdev); unsigned int i; if (which == V4L2_SUBDEV_FORMAT_ACTIVE) { if (crops) for (i = 0; i < subdev->entity.num_pads; i++) crops[i] = &ssd->crop[i]; if (comps) *comps = &ssd->compose; } else { if (crops) { for (i = 0; i < subdev->entity.num_pads; i++) crops[i] = v4l2_subdev_get_try_crop(subdev, sd_state, i); } if (comps) *comps = v4l2_subdev_get_try_compose(subdev, sd_state, CCS_PAD_SINK); } } /* Changes require propagation only on sink pad. */ static void ccs_propagate(struct v4l2_subdev *subdev, struct v4l2_subdev_state *sd_state, int which, int target) { struct ccs_sensor *sensor = to_ccs_sensor(subdev); struct ccs_subdev *ssd = to_ccs_subdev(subdev); struct v4l2_rect *comp, *crops[CCS_PADS]; ccs_get_crop_compose(subdev, sd_state, crops, &comp, which); switch (target) { case V4L2_SEL_TGT_CROP: comp->width = crops[CCS_PAD_SINK]->width; comp->height = crops[CCS_PAD_SINK]->height; if (which == V4L2_SUBDEV_FORMAT_ACTIVE) { if (ssd == sensor->scaler) { sensor->scale_m = CCS_LIM(sensor, SCALER_N_MIN); sensor->scaling_mode = CCS_SCALING_MODE_NO_SCALING; } else if (ssd == sensor->binner) { sensor->binning_horizontal = 1; sensor->binning_vertical = 1; } } fallthrough; case V4L2_SEL_TGT_COMPOSE: *crops[CCS_PAD_SRC] = *comp; break; default: WARN_ON_ONCE(1); } } static const struct ccs_csi_data_format *ccs_validate_csi_data_format(struct ccs_sensor *sensor, u32 code) { unsigned int i; for (i = 0; i < ARRAY_SIZE(ccs_csi_data_formats); i++) { if (sensor->mbus_frame_fmts & (1 << i) && ccs_csi_data_formats[i].code == code) return &ccs_csi_data_formats[i]; } return sensor->csi_format; } static int ccs_set_format_source(struct v4l2_subdev *subdev, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *fmt) { struct ccs_sensor *sensor = to_ccs_sensor(subdev); const struct ccs_csi_data_format *csi_format, *old_csi_format = sensor->csi_format; unsigned long *valid_link_freqs; u32 code = fmt->format.code; unsigned int i; int rval; rval = __ccs_get_format(subdev, sd_state, fmt); if (rval) return rval; /* * Media bus code is changeable on src subdev's source pad. On * other source pads we just get format here. */ if (subdev != &sensor->src->sd) return 0; csi_format = ccs_validate_csi_data_format(sensor, code); fmt->format.code = csi_format->code; if (fmt->which != V4L2_SUBDEV_FORMAT_ACTIVE) return 0; sensor->csi_format = csi_format; if (csi_format->width != old_csi_format->width) for (i = 0; i < ARRAY_SIZE(sensor->test_data); i++) __v4l2_ctrl_modify_range( sensor->test_data[i], 0, (1 << csi_format->width) - 1, 1, 0); if (csi_format->compressed == old_csi_format->compressed) return 0; valid_link_freqs = &sensor->valid_link_freqs[sensor->csi_format->compressed - sensor->compressed_min_bpp]; __v4l2_ctrl_modify_range( sensor->link_freq, 0, __fls(*valid_link_freqs), ~*valid_link_freqs, __ffs(*valid_link_freqs)); return ccs_pll_update(sensor); } static int ccs_set_format(struct v4l2_subdev *subdev, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *fmt) { struct ccs_sensor *sensor = to_ccs_sensor(subdev); struct ccs_subdev *ssd = to_ccs_subdev(subdev); struct v4l2_rect *crops[CCS_PADS]; mutex_lock(&sensor->mutex); if (fmt->pad == ssd->source_pad) { int rval; rval = ccs_set_format_source(subdev, sd_state, fmt); mutex_unlock(&sensor->mutex); return rval; } /* Sink pad. Width and height are changeable here. */ fmt->format.code = __ccs_get_mbus_code(subdev, fmt->pad); fmt->format.width &= ~1; fmt->format.height &= ~1; fmt->format.field = V4L2_FIELD_NONE; fmt->format.width = clamp(fmt->format.width, CCS_LIM(sensor, MIN_X_OUTPUT_SIZE), CCS_LIM(sensor, MAX_X_OUTPUT_SIZE)); fmt->format.height = clamp(fmt->format.height, CCS_LIM(sensor, MIN_Y_OUTPUT_SIZE), CCS_LIM(sensor, MAX_Y_OUTPUT_SIZE)); ccs_get_crop_compose(subdev, sd_state, crops, NULL, fmt->which); crops[ssd->sink_pad]->left = 0; crops[ssd->sink_pad]->top = 0; crops[ssd->sink_pad]->width = fmt->format.width; crops[ssd->sink_pad]->height = fmt->format.height; if (fmt->which == V4L2_SUBDEV_FORMAT_ACTIVE) ssd->sink_fmt = *crops[ssd->sink_pad]; ccs_propagate(subdev, sd_state, fmt->which, V4L2_SEL_TGT_CROP); mutex_unlock(&sensor->mutex); return 0; } /* * Calculate goodness of scaled image size compared to expected image * size and flags provided. */ #define SCALING_GOODNESS 100000 #define SCALING_GOODNESS_EXTREME 100000000 static int scaling_goodness(struct v4l2_subdev *subdev, int w, int ask_w, int h, int ask_h, u32 flags) { struct ccs_sensor *sensor = to_ccs_sensor(subdev); struct i2c_client *client = v4l2_get_subdevdata(subdev); int val = 0; w &= ~1; ask_w &= ~1; h &= ~1; ask_h &= ~1; if (flags & V4L2_SEL_FLAG_GE) { if (w < ask_w) val -= SCALING_GOODNESS; if (h < ask_h) val -= SCALING_GOODNESS; } if (flags & V4L2_SEL_FLAG_LE) { if (w > ask_w) val -= SCALING_GOODNESS; if (h > ask_h) val -= SCALING_GOODNESS; } val -= abs(w - ask_w); val -= abs(h - ask_h); if (w < CCS_LIM(sensor, MIN_X_OUTPUT_SIZE)) val -= SCALING_GOODNESS_EXTREME; dev_dbg(&client->dev, "w %d ask_w %d h %d ask_h %d goodness %d\n", w, ask_w, h, ask_h, val); return val; } static void ccs_set_compose_binner(struct v4l2_subdev *subdev, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_selection *sel, struct v4l2_rect **crops, struct v4l2_rect *comp) { struct ccs_sensor *sensor = to_ccs_sensor(subdev); unsigned int i; unsigned int binh = 1, binv = 1; int best = scaling_goodness( subdev, crops[CCS_PAD_SINK]->width, sel->r.width, crops[CCS_PAD_SINK]->height, sel->r.height, sel->flags); for (i = 0; i < sensor->nbinning_subtypes; i++) { int this = scaling_goodness( subdev, crops[CCS_PAD_SINK]->width / sensor->binning_subtypes[i].horizontal, sel->r.width, crops[CCS_PAD_SINK]->height / sensor->binning_subtypes[i].vertical, sel->r.height, sel->flags); if (this > best) { binh = sensor->binning_subtypes[i].horizontal; binv = sensor->binning_subtypes[i].vertical; best = this; } } if (sel->which == V4L2_SUBDEV_FORMAT_ACTIVE) { sensor->binning_vertical = binv; sensor->binning_horizontal = binh; } sel->r.width = (crops[CCS_PAD_SINK]->width / binh) & ~1; sel->r.height = (crops[CCS_PAD_SINK]->height / binv) & ~1; } /* * Calculate best scaling ratio and mode for given output resolution. * * Try all of these: horizontal ratio, vertical ratio and smallest * size possible (horizontally). * * Also try whether horizontal scaler or full scaler gives a better * result. */ static void ccs_set_compose_scaler(struct v4l2_subdev *subdev, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_selection *sel, struct v4l2_rect **crops, struct v4l2_rect *comp) { struct i2c_client *client = v4l2_get_subdevdata(subdev); struct ccs_sensor *sensor = to_ccs_sensor(subdev); u32 min, max, a, b, max_m; u32 scale_m = CCS_LIM(sensor, SCALER_N_MIN); int mode = CCS_SCALING_MODE_HORIZONTAL; u32 try[4]; u32 ntry = 0; unsigned int i; int best = INT_MIN; sel->r.width = min_t(unsigned int, sel->r.width, crops[CCS_PAD_SINK]->width); sel->r.height = min_t(unsigned int, sel->r.height, crops[CCS_PAD_SINK]->height); a = crops[CCS_PAD_SINK]->width * CCS_LIM(sensor, SCALER_N_MIN) / sel->r.width; b = crops[CCS_PAD_SINK]->height * CCS_LIM(sensor, SCALER_N_MIN) / sel->r.height; max_m = crops[CCS_PAD_SINK]->width * CCS_LIM(sensor, SCALER_N_MIN) / CCS_LIM(sensor, MIN_X_OUTPUT_SIZE); a = clamp(a, CCS_LIM(sensor, SCALER_M_MIN), CCS_LIM(sensor, SCALER_M_MAX)); b = clamp(b, CCS_LIM(sensor, SCALER_M_MIN), CCS_LIM(sensor, SCALER_M_MAX)); max_m = clamp(max_m, CCS_LIM(sensor, SCALER_M_MIN), CCS_LIM(sensor, SCALER_M_MAX)); dev_dbg(&client->dev, "scaling: a %u b %u max_m %u\n", a, b, max_m); min = min(max_m, min(a, b)); max = min(max_m, max(a, b)); try[ntry] = min; ntry++; if (min != max) { try[ntry] = max; ntry++; } if (max != max_m) { try[ntry] = min + 1; ntry++; if (min != max) { try[ntry] = max + 1; ntry++; } } for (i = 0; i < ntry; i++) { int this = scaling_goodness( subdev, crops[CCS_PAD_SINK]->width / try[i] * CCS_LIM(sensor, SCALER_N_MIN), sel->r.width, crops[CCS_PAD_SINK]->height, sel->r.height, sel->flags); dev_dbg(&client->dev, "trying factor %u (%u)\n", try[i], i); if (this > best) { scale_m = try[i]; mode = CCS_SCALING_MODE_HORIZONTAL; best = this; } if (CCS_LIM(sensor, SCALING_CAPABILITY) == CCS_SCALING_CAPABILITY_HORIZONTAL) continue; this = scaling_goodness( subdev, crops[CCS_PAD_SINK]->width / try[i] * CCS_LIM(sensor, SCALER_N_MIN), sel->r.width, crops[CCS_PAD_SINK]->height / try[i] * CCS_LIM(sensor, SCALER_N_MIN), sel->r.height, sel->flags); if (this > best) { scale_m = try[i]; mode = SMIAPP_SCALING_MODE_BOTH; best = this; } } sel->r.width = (crops[CCS_PAD_SINK]->width / scale_m * CCS_LIM(sensor, SCALER_N_MIN)) & ~1; if (mode == SMIAPP_SCALING_MODE_BOTH) sel->r.height = (crops[CCS_PAD_SINK]->height / scale_m * CCS_LIM(sensor, SCALER_N_MIN)) & ~1; else sel->r.height = crops[CCS_PAD_SINK]->height; if (sel->which == V4L2_SUBDEV_FORMAT_ACTIVE) { sensor->scale_m = scale_m; sensor->scaling_mode = mode; } } /* We're only called on source pads. This function sets scaling. */ static int ccs_set_compose(struct v4l2_subdev *subdev, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_selection *sel) { struct ccs_sensor *sensor = to_ccs_sensor(subdev); struct ccs_subdev *ssd = to_ccs_subdev(subdev); struct v4l2_rect *comp, *crops[CCS_PADS]; ccs_get_crop_compose(subdev, sd_state, crops, &comp, sel->which); sel->r.top = 0; sel->r.left = 0; if (ssd == sensor->binner) ccs_set_compose_binner(subdev, sd_state, sel, crops, comp); else ccs_set_compose_scaler(subdev, sd_state, sel, crops, comp); *comp = sel->r; ccs_propagate(subdev, sd_state, sel->which, V4L2_SEL_TGT_COMPOSE); if (sel->which == V4L2_SUBDEV_FORMAT_ACTIVE) return ccs_pll_blanking_update(sensor); return 0; } static int __ccs_sel_supported(struct v4l2_subdev *subdev, struct v4l2_subdev_selection *sel) { struct ccs_sensor *sensor = to_ccs_sensor(subdev); struct ccs_subdev *ssd = to_ccs_subdev(subdev); /* We only implement crop in three places. */ switch (sel->target) { case V4L2_SEL_TGT_CROP: case V4L2_SEL_TGT_CROP_BOUNDS: if (ssd == sensor->pixel_array && sel->pad == CCS_PA_PAD_SRC) return 0; if (ssd == sensor->src && sel->pad == CCS_PAD_SRC) return 0; if (ssd == sensor->scaler && sel->pad == CCS_PAD_SINK && CCS_LIM(sensor, DIGITAL_CROP_CAPABILITY) == CCS_DIGITAL_CROP_CAPABILITY_INPUT_CROP) return 0; return -EINVAL; case V4L2_SEL_TGT_NATIVE_SIZE: if (ssd == sensor->pixel_array && sel->pad == CCS_PA_PAD_SRC) return 0; return -EINVAL; case V4L2_SEL_TGT_COMPOSE: case V4L2_SEL_TGT_COMPOSE_BOUNDS: if (sel->pad == ssd->source_pad) return -EINVAL; if (ssd == sensor->binner) return 0; if (ssd == sensor->scaler && CCS_LIM(sensor, SCALING_CAPABILITY) != CCS_SCALING_CAPABILITY_NONE) return 0; fallthrough; default: return -EINVAL; } } static int ccs_set_crop(struct v4l2_subdev *subdev, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_selection *sel) { struct ccs_sensor *sensor = to_ccs_sensor(subdev); struct ccs_subdev *ssd = to_ccs_subdev(subdev); struct v4l2_rect *src_size, *crops[CCS_PADS]; struct v4l2_rect _r; ccs_get_crop_compose(subdev, sd_state, crops, NULL, sel->which); if (sel->which == V4L2_SUBDEV_FORMAT_ACTIVE) { if (sel->pad == ssd->sink_pad) src_size = &ssd->sink_fmt; else src_size = &ssd->compose; } else { if (sel->pad == ssd->sink_pad) { _r.left = 0; _r.top = 0; _r.width = v4l2_subdev_get_try_format(subdev, sd_state, sel->pad) ->width; _r.height = v4l2_subdev_get_try_format(subdev, sd_state, sel->pad) ->height; src_size = &_r; } else { src_size = v4l2_subdev_get_try_compose( subdev, sd_state, ssd->sink_pad); } } if (ssd == sensor->src && sel->pad == CCS_PAD_SRC) { sel->r.left = 0; sel->r.top = 0; } sel->r.width = min(sel->r.width, src_size->width); sel->r.height = min(sel->r.height, src_size->height); sel->r.left = min_t(int, sel->r.left, src_size->width - sel->r.width); sel->r.top = min_t(int, sel->r.top, src_size->height - sel->r.height); *crops[sel->pad] = sel->r; if (ssd != sensor->pixel_array && sel->pad == CCS_PAD_SINK) ccs_propagate(subdev, sd_state, sel->which, V4L2_SEL_TGT_CROP); return 0; } static void ccs_get_native_size(struct ccs_subdev *ssd, struct v4l2_rect *r) { r->top = 0; r->left = 0; r->width = CCS_LIM(ssd->sensor, X_ADDR_MAX) + 1; r->height = CCS_LIM(ssd->sensor, Y_ADDR_MAX) + 1; } static int __ccs_get_selection(struct v4l2_subdev *subdev, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_selection *sel) { struct ccs_sensor *sensor = to_ccs_sensor(subdev); struct ccs_subdev *ssd = to_ccs_subdev(subdev); struct v4l2_rect *comp, *crops[CCS_PADS]; struct v4l2_rect sink_fmt; int ret; ret = __ccs_sel_supported(subdev, sel); if (ret) return ret; ccs_get_crop_compose(subdev, sd_state, crops, &comp, sel->which); if (sel->which == V4L2_SUBDEV_FORMAT_ACTIVE) { sink_fmt = ssd->sink_fmt; } else { struct v4l2_mbus_framefmt *fmt = v4l2_subdev_get_try_format(subdev, sd_state, ssd->sink_pad); sink_fmt.left = 0; sink_fmt.top = 0; sink_fmt.width = fmt->width; sink_fmt.height = fmt->height; } switch (sel->target) { case V4L2_SEL_TGT_CROP_BOUNDS: case V4L2_SEL_TGT_NATIVE_SIZE: if (ssd == sensor->pixel_array) ccs_get_native_size(ssd, &sel->r); else if (sel->pad == ssd->sink_pad) sel->r = sink_fmt; else sel->r = *comp; break; case V4L2_SEL_TGT_CROP: case V4L2_SEL_TGT_COMPOSE_BOUNDS: sel->r = *crops[sel->pad]; break; case V4L2_SEL_TGT_COMPOSE: sel->r = *comp; break; } return 0; } static int ccs_get_selection(struct v4l2_subdev *subdev, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_selection *sel) { struct ccs_sensor *sensor = to_ccs_sensor(subdev); int rval; mutex_lock(&sensor->mutex); rval = __ccs_get_selection(subdev, sd_state, sel); mutex_unlock(&sensor->mutex); return rval; } static int ccs_set_selection(struct v4l2_subdev *subdev, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_selection *sel) { struct ccs_sensor *sensor = to_ccs_sensor(subdev); int ret; ret = __ccs_sel_supported(subdev, sel); if (ret) return ret; mutex_lock(&sensor->mutex); sel->r.left = max(0, sel->r.left & ~1); sel->r.top = max(0, sel->r.top & ~1); sel->r.width = CCS_ALIGN_DIM(sel->r.width, sel->flags); sel->r.height = CCS_ALIGN_DIM(sel->r.height, sel->flags); sel->r.width = max_t(unsigned int, CCS_LIM(sensor, MIN_X_OUTPUT_SIZE), sel->r.width); sel->r.height = max_t(unsigned int, CCS_LIM(sensor, MIN_Y_OUTPUT_SIZE), sel->r.height); switch (sel->target) { case V4L2_SEL_TGT_CROP: ret = ccs_set_crop(subdev, sd_state, sel); break; case V4L2_SEL_TGT_COMPOSE: ret = ccs_set_compose(subdev, sd_state, sel); break; default: ret = -EINVAL; } mutex_unlock(&sensor->mutex); return ret; } static int ccs_get_skip_frames(struct v4l2_subdev *subdev, u32 *frames) { struct ccs_sensor *sensor = to_ccs_sensor(subdev); *frames = sensor->frame_skip; return 0; } static int ccs_get_skip_top_lines(struct v4l2_subdev *subdev, u32 *lines) { struct ccs_sensor *sensor = to_ccs_sensor(subdev); *lines = sensor->image_start; return 0; } /* ----------------------------------------------------------------------------- * sysfs attributes */ static ssize_t nvm_show(struct device *dev, struct device_attribute *attr, char *buf) { struct v4l2_subdev *subdev = i2c_get_clientdata(to_i2c_client(dev)); struct i2c_client *client = v4l2_get_subdevdata(subdev); struct ccs_sensor *sensor = to_ccs_sensor(subdev); int rval; if (!sensor->dev_init_done) return -EBUSY; rval = ccs_pm_get_init(sensor); if (rval < 0) return -ENODEV; rval = ccs_read_nvm(sensor, buf, PAGE_SIZE); if (rval < 0) { pm_runtime_put(&client->dev); dev_err(&client->dev, "nvm read failed\n"); return -ENODEV; } pm_runtime_mark_last_busy(&client->dev); pm_runtime_put_autosuspend(&client->dev); /* * NVM is still way below a PAGE_SIZE, so we can safely * assume this for now. */ return rval; } static DEVICE_ATTR_RO(nvm); static ssize_t ident_show(struct device *dev, struct device_attribute *attr, char *buf) { struct v4l2_subdev *subdev = i2c_get_clientdata(to_i2c_client(dev)); struct ccs_sensor *sensor = to_ccs_sensor(subdev); struct ccs_module_info *minfo = &sensor->minfo; if (minfo->mipi_manufacturer_id) return sysfs_emit(buf, "%4.4x%4.4x%2.2x\n", minfo->mipi_manufacturer_id, minfo->model_id, minfo->revision_number) + 1; else return sysfs_emit(buf, "%2.2x%4.4x%2.2x\n", minfo->smia_manufacturer_id, minfo->model_id, minfo->revision_number) + 1; } static DEVICE_ATTR_RO(ident); /* ----------------------------------------------------------------------------- * V4L2 subdev core operations */ static int ccs_identify_module(struct ccs_sensor *sensor) { struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd); struct ccs_module_info *minfo = &sensor->minfo; unsigned int i; u32 rev; int rval = 0; /* Module info */ rval = ccs_read(sensor, MODULE_MANUFACTURER_ID, &minfo->mipi_manufacturer_id); if (!rval && !minfo->mipi_manufacturer_id) rval = ccs_read_addr_8only(sensor, SMIAPP_REG_U8_MANUFACTURER_ID, &minfo->smia_manufacturer_id); if (!rval) rval = ccs_read_addr_8only(sensor, CCS_R_MODULE_MODEL_ID, &minfo->model_id); if (!rval) rval = ccs_read_addr_8only(sensor, CCS_R_MODULE_REVISION_NUMBER_MAJOR, &rev); if (!rval) { rval = ccs_read_addr_8only(sensor, CCS_R_MODULE_REVISION_NUMBER_MINOR, &minfo->revision_number); minfo->revision_number |= rev << 8; } if (!rval) rval = ccs_read_addr_8only(sensor, CCS_R_MODULE_DATE_YEAR, &minfo->module_year); if (!rval) rval = ccs_read_addr_8only(sensor, CCS_R_MODULE_DATE_MONTH, &minfo->module_month); if (!rval) rval = ccs_read_addr_8only(sensor, CCS_R_MODULE_DATE_DAY, &minfo->module_day); /* Sensor info */ if (!rval) rval = ccs_read(sensor, SENSOR_MANUFACTURER_ID, &minfo->sensor_mipi_manufacturer_id); if (!rval && !minfo->sensor_mipi_manufacturer_id) rval = ccs_read_addr_8only(sensor, CCS_R_SENSOR_MANUFACTURER_ID, &minfo->sensor_smia_manufacturer_id); if (!rval) rval = ccs_read_addr_8only(sensor, CCS_R_SENSOR_MODEL_ID, &minfo->sensor_model_id); if (!rval) rval = ccs_read_addr_8only(sensor, CCS_R_SENSOR_REVISION_NUMBER, &minfo->sensor_revision_number); if (!rval && !minfo->sensor_revision_number) rval = ccs_read_addr_8only(sensor, CCS_R_SENSOR_REVISION_NUMBER_16, &minfo->sensor_revision_number); if (!rval) rval = ccs_read_addr_8only(sensor, CCS_R_SENSOR_FIRMWARE_VERSION, &minfo->sensor_firmware_version); /* SMIA */ if (!rval) rval = ccs_read(sensor, MIPI_CCS_VERSION, &minfo->ccs_version); if (!rval && !minfo->ccs_version) rval = ccs_read_addr_8only(sensor, SMIAPP_REG_U8_SMIA_VERSION, &minfo->smia_version); if (!rval && !minfo->ccs_version) rval = ccs_read_addr_8only(sensor, SMIAPP_REG_U8_SMIAPP_VERSION, &minfo->smiapp_version); if (rval) { dev_err(&client->dev, "sensor detection failed\n"); return -ENODEV; } if (minfo->mipi_manufacturer_id) dev_dbg(&client->dev, "MIPI CCS module 0x%4.4x-0x%4.4x\n", minfo->mipi_manufacturer_id, minfo->model_id); else dev_dbg(&client->dev, "SMIA module 0x%2.2x-0x%4.4x\n", minfo->smia_manufacturer_id, minfo->model_id); dev_dbg(&client->dev, "module revision 0x%4.4x date %2.2d-%2.2d-%2.2d\n", minfo->revision_number, minfo->module_year, minfo->module_month, minfo->module_day); if (minfo->sensor_mipi_manufacturer_id) dev_dbg(&client->dev, "MIPI CCS sensor 0x%4.4x-0x%4.4x\n", minfo->sensor_mipi_manufacturer_id, minfo->sensor_model_id); else dev_dbg(&client->dev, "SMIA sensor 0x%2.2x-0x%4.4x\n", minfo->sensor_smia_manufacturer_id, minfo->sensor_model_id); dev_dbg(&client->dev, "sensor revision 0x%4.4x firmware version 0x%2.2x\n", minfo->sensor_revision_number, minfo->sensor_firmware_version); if (minfo->ccs_version) { dev_dbg(&client->dev, "MIPI CCS version %u.%u", (minfo->ccs_version & CCS_MIPI_CCS_VERSION_MAJOR_MASK) >> CCS_MIPI_CCS_VERSION_MAJOR_SHIFT, (minfo->ccs_version & CCS_MIPI_CCS_VERSION_MINOR_MASK)); minfo->name = CCS_NAME; } else { dev_dbg(&client->dev, "smia version %2.2d smiapp version %2.2d\n", minfo->smia_version, minfo->smiapp_version); minfo->name = SMIAPP_NAME; /* * Some modules have bad data in the lvalues below. Hope the * rvalues have better stuff. The lvalues are module * parameters whereas the rvalues are sensor parameters. */ if (minfo->sensor_smia_manufacturer_id && !minfo->smia_manufacturer_id && !minfo->model_id) { minfo->smia_manufacturer_id = minfo->sensor_smia_manufacturer_id; minfo->model_id = minfo->sensor_model_id; minfo->revision_number = minfo->sensor_revision_number; } } for (i = 0; i < ARRAY_SIZE(ccs_module_idents); i++) { if (ccs_module_idents[i].mipi_manufacturer_id && ccs_module_idents[i].mipi_manufacturer_id != minfo->mipi_manufacturer_id) continue; if (ccs_module_idents[i].smia_manufacturer_id && ccs_module_idents[i].smia_manufacturer_id != minfo->smia_manufacturer_id) continue; if (ccs_module_idents[i].model_id != minfo->model_id) continue; if (ccs_module_idents[i].flags & CCS_MODULE_IDENT_FLAG_REV_LE) { if (ccs_module_idents[i].revision_number_major < (minfo->revision_number >> 8)) continue; } else { if (ccs_module_idents[i].revision_number_major != (minfo->revision_number >> 8)) continue; } minfo->name = ccs_module_idents[i].name; minfo->quirk = ccs_module_idents[i].quirk; break; } if (i >= ARRAY_SIZE(ccs_module_idents)) dev_warn(&client->dev, "no quirks for this module; let's hope it's fully compliant\n"); dev_dbg(&client->dev, "the sensor is called %s\n", minfo->name); return 0; } static const struct v4l2_subdev_ops ccs_ops; static const struct v4l2_subdev_internal_ops ccs_internal_ops; static const struct media_entity_operations ccs_entity_ops; static int ccs_register_subdev(struct ccs_sensor *sensor, struct ccs_subdev *ssd, struct ccs_subdev *sink_ssd, u16 source_pad, u16 sink_pad, u32 link_flags) { struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd); int rval; if (!sink_ssd) return 0; rval = media_entity_pads_init(&ssd->sd.entity, ssd->npads, ssd->pads); if (rval) { dev_err(&client->dev, "media_entity_pads_init failed\n"); return rval; } rval = v4l2_device_register_subdev(sensor->src->sd.v4l2_dev, &ssd->sd); if (rval) { dev_err(&client->dev, "v4l2_device_register_subdev failed\n"); return rval; } rval = media_create_pad_link(&ssd->sd.entity, source_pad, &sink_ssd->sd.entity, sink_pad, link_flags); if (rval) { dev_err(&client->dev, "media_create_pad_link failed\n"); v4l2_device_unregister_subdev(&ssd->sd); return rval; } return 0; } static void ccs_unregistered(struct v4l2_subdev *subdev) { struct ccs_sensor *sensor = to_ccs_sensor(subdev); unsigned int i; for (i = 1; i < sensor->ssds_used; i++) v4l2_device_unregister_subdev(&sensor->ssds[i].sd); } static int ccs_registered(struct v4l2_subdev *subdev) { struct ccs_sensor *sensor = to_ccs_sensor(subdev); int rval; if (sensor->scaler) { rval = ccs_register_subdev(sensor, sensor->binner, sensor->scaler, CCS_PAD_SRC, CCS_PAD_SINK, MEDIA_LNK_FL_ENABLED | MEDIA_LNK_FL_IMMUTABLE); if (rval < 0) return rval; } rval = ccs_register_subdev(sensor, sensor->pixel_array, sensor->binner, CCS_PA_PAD_SRC, CCS_PAD_SINK, MEDIA_LNK_FL_ENABLED | MEDIA_LNK_FL_IMMUTABLE); if (rval) goto out_err; return 0; out_err: ccs_unregistered(subdev); return rval; } static void ccs_cleanup(struct ccs_sensor *sensor) { struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd); device_remove_file(&client->dev, &dev_attr_nvm); device_remove_file(&client->dev, &dev_attr_ident); ccs_free_controls(sensor); } static void ccs_create_subdev(struct ccs_sensor *sensor, struct ccs_subdev *ssd, const char *name, unsigned short num_pads, u32 function) { struct i2c_client *client = v4l2_get_subdevdata(&sensor->src->sd); if (!ssd) return; if (ssd != sensor->src) v4l2_subdev_init(&ssd->sd, &ccs_ops); ssd->sd.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE; ssd->sd.entity.function = function; ssd->sensor = sensor; ssd->npads = num_pads; ssd->source_pad = num_pads - 1; v4l2_i2c_subdev_set_name(&ssd->sd, client, sensor->minfo.name, name); ccs_get_native_size(ssd, &ssd->sink_fmt); ssd->compose.width = ssd->sink_fmt.width; ssd->compose.height = ssd->sink_fmt.height; ssd->crop[ssd->source_pad] = ssd->compose; ssd->pads[ssd->source_pad].flags = MEDIA_PAD_FL_SOURCE; if (ssd != sensor->pixel_array) { ssd->crop[ssd->sink_pad] = ssd->compose; ssd->pads[ssd->sink_pad].flags = MEDIA_PAD_FL_SINK; } ssd->sd.entity.ops = &ccs_entity_ops; if (ssd == sensor->src) return; ssd->sd.internal_ops = &ccs_internal_ops; ssd->sd.owner = THIS_MODULE; ssd->sd.dev = &client->dev; v4l2_set_subdevdata(&ssd->sd, client); } static int ccs_open(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh) { struct ccs_subdev *ssd = to_ccs_subdev(sd); struct ccs_sensor *sensor = ssd->sensor; unsigned int i; mutex_lock(&sensor->mutex); for (i = 0; i < ssd->npads; i++) { struct v4l2_mbus_framefmt *try_fmt = v4l2_subdev_get_try_format(sd, fh->state, i); struct v4l2_rect *try_crop = v4l2_subdev_get_try_crop(sd, fh->state, i); struct v4l2_rect *try_comp; ccs_get_native_size(ssd, try_crop); try_fmt->width = try_crop->width; try_fmt->height = try_crop->height; try_fmt->code = sensor->internal_csi_format->code; try_fmt->field = V4L2_FIELD_NONE; if (ssd != sensor->pixel_array) continue; try_comp = v4l2_subdev_get_try_compose(sd, fh->state, i); *try_comp = *try_crop; } mutex_unlock(&sensor->mutex); return 0; } static const struct v4l2_subdev_video_ops ccs_video_ops = { .s_stream = ccs_set_stream, .pre_streamon = ccs_pre_streamon, .post_streamoff = ccs_post_streamoff, }; static const struct v4l2_subdev_pad_ops ccs_pad_ops = { .enum_mbus_code = ccs_enum_mbus_code, .get_fmt = ccs_get_format, .set_fmt = ccs_set_format, .get_selection = ccs_get_selection, .set_selection = ccs_set_selection, }; static const struct v4l2_subdev_sensor_ops ccs_sensor_ops = { .g_skip_frames = ccs_get_skip_frames, .g_skip_top_lines = ccs_get_skip_top_lines, }; static const struct v4l2_subdev_ops ccs_ops = { .video = &ccs_video_ops, .pad = &ccs_pad_ops, .sensor = &ccs_sensor_ops, }; static const struct media_entity_operations ccs_entity_ops = { .link_validate = v4l2_subdev_link_validate, }; static const struct v4l2_subdev_internal_ops ccs_internal_src_ops = { .registered = ccs_registered, .unregistered = ccs_unregistered, .open = ccs_open, }; static const struct v4l2_subdev_internal_ops ccs_internal_ops = { .open = ccs_open, }; /* ----------------------------------------------------------------------------- * I2C Driver */ static int __maybe_unused ccs_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct v4l2_subdev *subdev = i2c_get_clientdata(client); struct ccs_sensor *sensor = to_ccs_sensor(subdev); bool streaming = sensor->streaming; int rval; rval = pm_runtime_resume_and_get(dev); if (rval < 0) return rval; if (sensor->streaming) ccs_stop_streaming(sensor); /* save state for resume */ sensor->streaming = streaming; return 0; } static int __maybe_unused ccs_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct v4l2_subdev *subdev = i2c_get_clientdata(client); struct ccs_sensor *sensor = to_ccs_sensor(subdev); int rval = 0; pm_runtime_put(dev); if (sensor->streaming) rval = ccs_start_streaming(sensor); return rval; } static int ccs_get_hwconfig(struct ccs_sensor *sensor, struct device *dev) { struct ccs_hwconfig *hwcfg = &sensor->hwcfg; struct v4l2_fwnode_endpoint bus_cfg = { .bus_type = V4L2_MBUS_UNKNOWN }; struct fwnode_handle *ep; struct fwnode_handle *fwnode = dev_fwnode(dev); unsigned int i; int rval; ep = fwnode_graph_get_endpoint_by_id(fwnode, 0, 0, FWNODE_GRAPH_ENDPOINT_NEXT); if (!ep) return -ENODEV; /* * Note that we do need to rely on detecting the bus type between CSI-2 * D-PHY and CCP2 as the old bindings did not require it. */ rval = v4l2_fwnode_endpoint_alloc_parse(ep, &bus_cfg); if (rval) goto out_err; switch (bus_cfg.bus_type) { case V4L2_MBUS_CSI2_DPHY: hwcfg->csi_signalling_mode = CCS_CSI_SIGNALING_MODE_CSI_2_DPHY; hwcfg->lanes = bus_cfg.bus.mipi_csi2.num_data_lanes; break; case V4L2_MBUS_CSI2_CPHY: hwcfg->csi_signalling_mode = CCS_CSI_SIGNALING_MODE_CSI_2_CPHY; hwcfg->lanes = bus_cfg.bus.mipi_csi2.num_data_lanes; break; case V4L2_MBUS_CSI1: case V4L2_MBUS_CCP2: hwcfg->csi_signalling_mode = (bus_cfg.bus.mipi_csi1.strobe) ? SMIAPP_CSI_SIGNALLING_MODE_CCP2_DATA_STROBE : SMIAPP_CSI_SIGNALLING_MODE_CCP2_DATA_CLOCK; hwcfg->lanes = 1; break; default: dev_err(dev, "unsupported bus %u\n", bus_cfg.bus_type); rval = -EINVAL; goto out_err; } rval = fwnode_property_read_u32(dev_fwnode(dev), "clock-frequency", &hwcfg->ext_clk); if (rval) dev_info(dev, "can't get clock-frequency\n"); dev_dbg(dev, "clk %u, mode %u\n", hwcfg->ext_clk, hwcfg->csi_signalling_mode); if (!bus_cfg.nr_of_link_frequencies) { dev_warn(dev, "no link frequencies defined\n"); rval = -EINVAL; goto out_err; } hwcfg->op_sys_clock = devm_kcalloc( dev, bus_cfg.nr_of_link_frequencies + 1 /* guardian */, sizeof(*hwcfg->op_sys_clock), GFP_KERNEL); if (!hwcfg->op_sys_clock) { rval = -ENOMEM; goto out_err; } for (i = 0; i < bus_cfg.nr_of_link_frequencies; i++) { hwcfg->op_sys_clock[i] = bus_cfg.link_frequencies[i]; dev_dbg(dev, "freq %u: %lld\n", i, hwcfg->op_sys_clock[i]); } v4l2_fwnode_endpoint_free(&bus_cfg); fwnode_handle_put(ep); return 0; out_err: v4l2_fwnode_endpoint_free(&bus_cfg); fwnode_handle_put(ep); return rval; } static int ccs_firmware_name(struct i2c_client *client, struct ccs_sensor *sensor, char *filename, size_t filename_size, bool is_module) { const struct ccs_device *ccsdev = device_get_match_data(&client->dev); bool is_ccs = !(ccsdev->flags & CCS_DEVICE_FLAG_IS_SMIA); bool is_smiapp = sensor->minfo.smiapp_version; u16 manufacturer_id; u16 model_id; u16 revision_number; /* * Old SMIA is module-agnostic. Its sensor identification is based on * what now are those of the module. */ if (is_module || (!is_ccs && !is_smiapp)) { manufacturer_id = is_ccs ? sensor->minfo.mipi_manufacturer_id : sensor->minfo.smia_manufacturer_id; model_id = sensor->minfo.model_id; revision_number = sensor->minfo.revision_number; } else { manufacturer_id = is_ccs ? sensor->minfo.sensor_mipi_manufacturer_id : sensor->minfo.sensor_smia_manufacturer_id; model_id = sensor->minfo.sensor_model_id; revision_number = sensor->minfo.sensor_revision_number; } return snprintf(filename, filename_size, "ccs/%s-%s-%0*x-%4.4x-%0*x.fw", is_ccs ? "ccs" : is_smiapp ? "smiapp" : "smia", is_module || (!is_ccs && !is_smiapp) ? "module" : "sensor", is_ccs ? 4 : 2, manufacturer_id, model_id, !is_ccs && !is_module ? 2 : 4, revision_number); } static int ccs_probe(struct i2c_client *client) { const struct ccs_device *ccsdev = device_get_match_data(&client->dev); struct ccs_sensor *sensor; const struct firmware *fw; char filename[40]; unsigned int i; int rval; sensor = devm_kzalloc(&client->dev, sizeof(*sensor), GFP_KERNEL); if (sensor == NULL) return -ENOMEM; rval = ccs_get_hwconfig(sensor, &client->dev); if (rval) return rval; sensor->src = &sensor->ssds[sensor->ssds_used]; v4l2_i2c_subdev_init(&sensor->src->sd, client, &ccs_ops); sensor->src->sd.internal_ops = &ccs_internal_src_ops; sensor->regulators = devm_kcalloc(&client->dev, ARRAY_SIZE(ccs_regulators), sizeof(*sensor->regulators), GFP_KERNEL); if (!sensor->regulators) return -ENOMEM; for (i = 0; i < ARRAY_SIZE(ccs_regulators); i++) sensor->regulators[i].supply = ccs_regulators[i]; rval = devm_regulator_bulk_get(&client->dev, ARRAY_SIZE(ccs_regulators), sensor->regulators); if (rval) { dev_err(&client->dev, "could not get regulators\n"); return rval; } sensor->ext_clk = devm_clk_get(&client->dev, NULL); if (PTR_ERR(sensor->ext_clk) == -ENOENT) { dev_info(&client->dev, "no clock defined, continuing...\n"); sensor->ext_clk = NULL; } else if (IS_ERR(sensor->ext_clk)) { dev_err(&client->dev, "could not get clock (%ld)\n", PTR_ERR(sensor->ext_clk)); return -EPROBE_DEFER; } if (sensor->ext_clk) { if (sensor->hwcfg.ext_clk) { unsigned long rate; rval = clk_set_rate(sensor->ext_clk, sensor->hwcfg.ext_clk); if (rval < 0) { dev_err(&client->dev, "unable to set clock freq to %u\n", sensor->hwcfg.ext_clk); return rval; } rate = clk_get_rate(sensor->ext_clk); if (rate != sensor->hwcfg.ext_clk) { dev_err(&client->dev, "can't set clock freq, asked for %u but got %lu\n", sensor->hwcfg.ext_clk, rate); return -EINVAL; } } else { sensor->hwcfg.ext_clk = clk_get_rate(sensor->ext_clk); dev_dbg(&client->dev, "obtained clock freq %u\n", sensor->hwcfg.ext_clk); } } else if (sensor->hwcfg.ext_clk) { dev_dbg(&client->dev, "assuming clock freq %u\n", sensor->hwcfg.ext_clk); } else { dev_err(&client->dev, "unable to obtain clock freq\n"); return -EINVAL; } if (!sensor->hwcfg.ext_clk) { dev_err(&client->dev, "cannot work with xclk frequency 0\n"); return -EINVAL; } sensor->reset = devm_gpiod_get_optional(&client->dev, "reset", GPIOD_OUT_HIGH); if (IS_ERR(sensor->reset)) return PTR_ERR(sensor->reset); /* Support old users that may have used "xshutdown" property. */ if (!sensor->reset) sensor->xshutdown = devm_gpiod_get_optional(&client->dev, "xshutdown", GPIOD_OUT_LOW); if (IS_ERR(sensor->xshutdown)) return PTR_ERR(sensor->xshutdown); rval = ccs_power_on(&client->dev); if (rval < 0) return rval; mutex_init(&sensor->mutex); rval = ccs_identify_module(sensor); if (rval) { rval = -ENODEV; goto out_power_off; } rval = ccs_firmware_name(client, sensor, filename, sizeof(filename), false); if (rval >= sizeof(filename)) { rval = -ENOMEM; goto out_power_off; } rval = request_firmware(&fw, filename, &client->dev); if (!rval) { ccs_data_parse(&sensor->sdata, fw->data, fw->size, &client->dev, true); release_firmware(fw); } if (!(ccsdev->flags & CCS_DEVICE_FLAG_IS_SMIA) || sensor->minfo.smiapp_version) { rval = ccs_firmware_name(client, sensor, filename, sizeof(filename), true); if (rval >= sizeof(filename)) { rval = -ENOMEM; goto out_release_sdata; } rval = request_firmware(&fw, filename, &client->dev); if (!rval) { ccs_data_parse(&sensor->mdata, fw->data, fw->size, &client->dev, true); release_firmware(fw); } } rval = ccs_read_all_limits(sensor); if (rval) goto out_release_mdata; rval = ccs_read_frame_fmt(sensor); if (rval) { rval = -ENODEV; goto out_free_ccs_limits; } rval = ccs_update_phy_ctrl(sensor); if (rval < 0) goto out_free_ccs_limits; rval = ccs_call_quirk(sensor, limits); if (rval) { dev_err(&client->dev, "limits quirks failed\n"); goto out_free_ccs_limits; } if (CCS_LIM(sensor, BINNING_CAPABILITY)) { sensor->nbinning_subtypes = min_t(u8, CCS_LIM(sensor, BINNING_SUB_TYPES), CCS_LIM_BINNING_SUB_TYPE_MAX_N); for (i = 0; i < sensor->nbinning_subtypes; i++) { sensor->binning_subtypes[i].horizontal = CCS_LIM_AT(sensor, BINNING_SUB_TYPE, i) >> CCS_BINNING_SUB_TYPE_COLUMN_SHIFT; sensor->binning_subtypes[i].vertical = CCS_LIM_AT(sensor, BINNING_SUB_TYPE, i) & CCS_BINNING_SUB_TYPE_ROW_MASK; dev_dbg(&client->dev, "binning %xx%x\n", sensor->binning_subtypes[i].horizontal, sensor->binning_subtypes[i].vertical); } } sensor->binning_horizontal = 1; sensor->binning_vertical = 1; if (device_create_file(&client->dev, &dev_attr_ident) != 0) { dev_err(&client->dev, "sysfs ident entry creation failed\n"); rval = -ENOENT; goto out_free_ccs_limits; } if (sensor->minfo.smiapp_version && CCS_LIM(sensor, DATA_TRANSFER_IF_CAPABILITY) & CCS_DATA_TRANSFER_IF_CAPABILITY_SUPPORTED) { if (device_create_file(&client->dev, &dev_attr_nvm) != 0) { dev_err(&client->dev, "sysfs nvm entry failed\n"); rval = -EBUSY; goto out_cleanup; } } if (!CCS_LIM(sensor, MIN_OP_SYS_CLK_DIV) || !CCS_LIM(sensor, MAX_OP_SYS_CLK_DIV) || !CCS_LIM(sensor, MIN_OP_PIX_CLK_DIV) || !CCS_LIM(sensor, MAX_OP_PIX_CLK_DIV)) { /* No OP clock branch */ sensor->pll.flags |= CCS_PLL_FLAG_NO_OP_CLOCKS; } else if (CCS_LIM(sensor, SCALING_CAPABILITY) != CCS_SCALING_CAPABILITY_NONE || CCS_LIM(sensor, DIGITAL_CROP_CAPABILITY) == CCS_DIGITAL_CROP_CAPABILITY_INPUT_CROP) { /* We have a scaler or digital crop. */ sensor->scaler = &sensor->ssds[sensor->ssds_used]; sensor->ssds_used++; } sensor->binner = &sensor->ssds[sensor->ssds_used]; sensor->ssds_used++; sensor->pixel_array = &sensor->ssds[sensor->ssds_used]; sensor->ssds_used++; sensor->scale_m = CCS_LIM(sensor, SCALER_N_MIN); /* prepare PLL configuration input values */ sensor->pll.bus_type = CCS_PLL_BUS_TYPE_CSI2_DPHY; sensor->pll.csi2.lanes = sensor->hwcfg.lanes; if (CCS_LIM(sensor, CLOCK_CALCULATION) & CCS_CLOCK_CALCULATION_LANE_SPEED) { sensor->pll.flags |= CCS_PLL_FLAG_LANE_SPEED_MODEL; if (CCS_LIM(sensor, CLOCK_CALCULATION) & CCS_CLOCK_CALCULATION_LINK_DECOUPLED) { sensor->pll.vt_lanes = CCS_LIM(sensor, NUM_OF_VT_LANES) + 1; sensor->pll.op_lanes = CCS_LIM(sensor, NUM_OF_OP_LANES) + 1; sensor->pll.flags |= CCS_PLL_FLAG_LINK_DECOUPLED; } else { sensor->pll.vt_lanes = sensor->pll.csi2.lanes; sensor->pll.op_lanes = sensor->pll.csi2.lanes; } } if (CCS_LIM(sensor, CLOCK_TREE_PLL_CAPABILITY) & CCS_CLOCK_TREE_PLL_CAPABILITY_EXT_DIVIDER) sensor->pll.flags |= CCS_PLL_FLAG_EXT_IP_PLL_DIVIDER; if (CCS_LIM(sensor, CLOCK_TREE_PLL_CAPABILITY) & CCS_CLOCK_TREE_PLL_CAPABILITY_FLEXIBLE_OP_PIX_CLK_DIV) sensor->pll.flags |= CCS_PLL_FLAG_FLEXIBLE_OP_PIX_CLK_DIV; if (CCS_LIM(sensor, FIFO_SUPPORT_CAPABILITY) & CCS_FIFO_SUPPORT_CAPABILITY_DERATING) sensor->pll.flags |= CCS_PLL_FLAG_FIFO_DERATING; if (CCS_LIM(sensor, FIFO_SUPPORT_CAPABILITY) & CCS_FIFO_SUPPORT_CAPABILITY_DERATING_OVERRATING) sensor->pll.flags |= CCS_PLL_FLAG_FIFO_DERATING | CCS_PLL_FLAG_FIFO_OVERRATING; if (CCS_LIM(sensor, CLOCK_TREE_PLL_CAPABILITY) & CCS_CLOCK_TREE_PLL_CAPABILITY_DUAL_PLL) { if (CCS_LIM(sensor, CLOCK_TREE_PLL_CAPABILITY) & CCS_CLOCK_TREE_PLL_CAPABILITY_SINGLE_PLL) { u32 v; /* Use sensor default in PLL mode selection */ rval = ccs_read(sensor, PLL_MODE, &v); if (rval) goto out_cleanup; if (v == CCS_PLL_MODE_DUAL) sensor->pll.flags |= CCS_PLL_FLAG_DUAL_PLL; } else { sensor->pll.flags |= CCS_PLL_FLAG_DUAL_PLL; } if (CCS_LIM(sensor, CLOCK_CALCULATION) & CCS_CLOCK_CALCULATION_DUAL_PLL_OP_SYS_DDR) sensor->pll.flags |= CCS_PLL_FLAG_OP_SYS_DDR; if (CCS_LIM(sensor, CLOCK_CALCULATION) & CCS_CLOCK_CALCULATION_DUAL_PLL_OP_PIX_DDR) sensor->pll.flags |= CCS_PLL_FLAG_OP_PIX_DDR; } sensor->pll.op_bits_per_lane = CCS_LIM(sensor, OP_BITS_PER_LANE); sensor->pll.ext_clk_freq_hz = sensor->hwcfg.ext_clk; sensor->pll.scale_n = CCS_LIM(sensor, SCALER_N_MIN); ccs_create_subdev(sensor, sensor->scaler, " scaler", 2, MEDIA_ENT_F_PROC_VIDEO_SCALER); ccs_create_subdev(sensor, sensor->binner, " binner", 2, MEDIA_ENT_F_PROC_VIDEO_SCALER); ccs_create_subdev(sensor, sensor->pixel_array, " pixel_array", 1, MEDIA_ENT_F_CAM_SENSOR); rval = ccs_init_controls(sensor); if (rval < 0) goto out_cleanup; rval = ccs_call_quirk(sensor, init); if (rval) goto out_cleanup; rval = ccs_get_mbus_formats(sensor); if (rval) { rval = -ENODEV; goto out_cleanup; } rval = ccs_init_late_controls(sensor); if (rval) { rval = -ENODEV; goto out_cleanup; } mutex_lock(&sensor->mutex); rval = ccs_pll_blanking_update(sensor); mutex_unlock(&sensor->mutex); if (rval) { dev_err(&client->dev, "update mode failed\n"); goto out_cleanup; } sensor->streaming = false; sensor->dev_init_done = true; rval = media_entity_pads_init(&sensor->src->sd.entity, 2, sensor->src->pads); if (rval < 0) goto out_media_entity_cleanup; rval = ccs_write_msr_regs(sensor); if (rval) goto out_media_entity_cleanup; pm_runtime_set_active(&client->dev); pm_runtime_get_noresume(&client->dev); pm_runtime_enable(&client->dev); rval = v4l2_async_register_subdev_sensor(&sensor->src->sd); if (rval < 0) goto out_disable_runtime_pm; pm_runtime_set_autosuspend_delay(&client->dev, 1000); pm_runtime_use_autosuspend(&client->dev); pm_runtime_put_autosuspend(&client->dev); return 0; out_disable_runtime_pm: pm_runtime_put_noidle(&client->dev); pm_runtime_disable(&client->dev); out_media_entity_cleanup: media_entity_cleanup(&sensor->src->sd.entity); out_cleanup: ccs_cleanup(sensor); out_release_mdata: kvfree(sensor->mdata.backing); out_release_sdata: kvfree(sensor->sdata.backing); out_free_ccs_limits: kfree(sensor->ccs_limits); out_power_off: ccs_power_off(&client->dev); mutex_destroy(&sensor->mutex); return rval; } static void ccs_remove(struct i2c_client *client) { struct v4l2_subdev *subdev = i2c_get_clientdata(client); struct ccs_sensor *sensor = to_ccs_sensor(subdev); unsigned int i; v4l2_async_unregister_subdev(subdev); pm_runtime_disable(&client->dev); if (!pm_runtime_status_suspended(&client->dev)) ccs_power_off(&client->dev); pm_runtime_set_suspended(&client->dev); for (i = 0; i < sensor->ssds_used; i++) { v4l2_device_unregister_subdev(&sensor->ssds[i].sd); media_entity_cleanup(&sensor->ssds[i].sd.entity); } ccs_cleanup(sensor); mutex_destroy(&sensor->mutex); kfree(sensor->ccs_limits); kvfree(sensor->sdata.backing); kvfree(sensor->mdata.backing); } static const struct ccs_device smia_device = { .flags = CCS_DEVICE_FLAG_IS_SMIA, }; static const struct ccs_device ccs_device = {}; static const struct acpi_device_id ccs_acpi_table[] = { { .id = "MIPI0200", .driver_data = (unsigned long)&ccs_device }, { }, }; MODULE_DEVICE_TABLE(acpi, ccs_acpi_table); static const struct of_device_id ccs_of_table[] = { { .compatible = "mipi-ccs-1.1", .data = &ccs_device }, { .compatible = "mipi-ccs-1.0", .data = &ccs_device }, { .compatible = "mipi-ccs", .data = &ccs_device }, { .compatible = "nokia,smia", .data = &smia_device }, { }, }; MODULE_DEVICE_TABLE(of, ccs_of_table); static const struct dev_pm_ops ccs_pm_ops = { SET_SYSTEM_SLEEP_PM_OPS(ccs_suspend, ccs_resume) SET_RUNTIME_PM_OPS(ccs_power_off, ccs_power_on, NULL) }; static struct i2c_driver ccs_i2c_driver = { .driver = { .acpi_match_table = ccs_acpi_table, .of_match_table = ccs_of_table, .name = CCS_NAME, .pm = &ccs_pm_ops, }, .probe = ccs_probe, .remove = ccs_remove, }; static int ccs_module_init(void) { unsigned int i, l; for (i = 0, l = 0; ccs_limits[i].size && l < CCS_L_LAST; i++) { if (!(ccs_limits[i].flags & CCS_L_FL_SAME_REG)) { ccs_limit_offsets[l + 1].lim = ALIGN(ccs_limit_offsets[l].lim + ccs_limits[i].size, ccs_reg_width(ccs_limits[i + 1].reg)); ccs_limit_offsets[l].info = i; l++; } else { ccs_limit_offsets[l].lim += ccs_limits[i].size; } } if (WARN_ON(ccs_limits[i].size)) return -EINVAL; if (WARN_ON(l != CCS_L_LAST)) return -EINVAL; return i2c_register_driver(THIS_MODULE, &ccs_i2c_driver); } static void ccs_module_cleanup(void) { i2c_del_driver(&ccs_i2c_driver); } module_init(ccs_module_init); module_exit(ccs_module_cleanup); MODULE_AUTHOR("Sakari Ailus <[email protected]>"); MODULE_DESCRIPTION("Generic MIPI CCS/SMIA/SMIA++ camera sensor driver"); MODULE_LICENSE("GPL v2"); MODULE_ALIAS("smiapp");
linux-master
drivers/media/i2c/ccs/ccs-core.c
// SPDX-License-Identifier: GPL-2.0+ /* * A virtual v4l2-mem2mem example device. * * This is a virtual device driver for testing mem-to-mem vb2 framework. * It simulates a device that uses memory buffers for both source and * destination, processes the data and issues an "irq" (simulated by a delayed * workqueue). * The device is capable of multi-instance, multi-buffer-per-transaction * operation (via the mem2mem framework). * * Copyright (c) 2009-2010 Samsung Electronics Co., Ltd. * Pawel Osciak, <[email protected]> * Marek Szyprowski, <[email protected]> */ #include <linux/module.h> #include <linux/delay.h> #include <linux/fs.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/platform_device.h> #include <media/v4l2-mem2mem.h> #include <media/v4l2-device.h> #include <media/v4l2-ioctl.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-event.h> #include <media/videobuf2-vmalloc.h> MODULE_DESCRIPTION("Virtual device for mem2mem framework testing"); MODULE_AUTHOR("Pawel Osciak, <[email protected]>"); MODULE_LICENSE("GPL"); MODULE_VERSION("0.2"); MODULE_ALIAS("mem2mem_testdev"); static unsigned int debug; module_param(debug, uint, 0644); MODULE_PARM_DESC(debug, "debug level"); /* Default transaction time in msec */ static unsigned int default_transtime = 40; /* Max 25 fps */ module_param(default_transtime, uint, 0644); MODULE_PARM_DESC(default_transtime, "default transaction time in ms"); #define MIN_W 32 #define MIN_H 32 #define MAX_W 640 #define MAX_H 480 /* Pixel alignment for non-bayer formats */ #define WIDTH_ALIGN 2 #define HEIGHT_ALIGN 1 /* Pixel alignment for bayer formats */ #define BAYER_WIDTH_ALIGN 2 #define BAYER_HEIGHT_ALIGN 2 /* Flags that indicate a format can be used for capture/output */ #define MEM2MEM_CAPTURE BIT(0) #define MEM2MEM_OUTPUT BIT(1) #define MEM2MEM_NAME "vim2m" /* Per queue */ #define MEM2MEM_DEF_NUM_BUFS VIDEO_MAX_FRAME /* In bytes, per queue */ #define MEM2MEM_VID_MEM_LIMIT (16 * 1024 * 1024) /* Flags that indicate processing mode */ #define MEM2MEM_HFLIP BIT(0) #define MEM2MEM_VFLIP BIT(1) #define dprintk(dev, lvl, fmt, arg...) \ v4l2_dbg(lvl, debug, &(dev)->v4l2_dev, "%s: " fmt, __func__, ## arg) static void vim2m_dev_release(struct device *dev) {} static struct platform_device vim2m_pdev = { .name = MEM2MEM_NAME, .dev.release = vim2m_dev_release, }; struct vim2m_fmt { u32 fourcc; int depth; /* Types the format can be used for */ u32 types; }; static struct vim2m_fmt formats[] = { { .fourcc = V4L2_PIX_FMT_RGB565, /* rrrrrggg gggbbbbb */ .depth = 16, .types = MEM2MEM_CAPTURE | MEM2MEM_OUTPUT, }, { .fourcc = V4L2_PIX_FMT_RGB565X, /* gggbbbbb rrrrrggg */ .depth = 16, .types = MEM2MEM_CAPTURE | MEM2MEM_OUTPUT, }, { .fourcc = V4L2_PIX_FMT_RGB24, .depth = 24, .types = MEM2MEM_CAPTURE | MEM2MEM_OUTPUT, }, { .fourcc = V4L2_PIX_FMT_BGR24, .depth = 24, .types = MEM2MEM_CAPTURE | MEM2MEM_OUTPUT, }, { .fourcc = V4L2_PIX_FMT_YUYV, .depth = 16, .types = MEM2MEM_CAPTURE, }, { .fourcc = V4L2_PIX_FMT_SBGGR8, .depth = 8, .types = MEM2MEM_CAPTURE, }, { .fourcc = V4L2_PIX_FMT_SGBRG8, .depth = 8, .types = MEM2MEM_CAPTURE, }, { .fourcc = V4L2_PIX_FMT_SGRBG8, .depth = 8, .types = MEM2MEM_CAPTURE, }, { .fourcc = V4L2_PIX_FMT_SRGGB8, .depth = 8, .types = MEM2MEM_CAPTURE, }, }; #define NUM_FORMATS ARRAY_SIZE(formats) /* Per-queue, driver-specific private data */ struct vim2m_q_data { unsigned int width; unsigned int height; unsigned int sizeimage; unsigned int sequence; struct vim2m_fmt *fmt; }; enum { V4L2_M2M_SRC = 0, V4L2_M2M_DST = 1, }; #define V4L2_CID_TRANS_TIME_MSEC (V4L2_CID_USER_BASE + 0x1000) #define V4L2_CID_TRANS_NUM_BUFS (V4L2_CID_USER_BASE + 0x1001) static struct vim2m_fmt *find_format(u32 fourcc) { struct vim2m_fmt *fmt; unsigned int k; for (k = 0; k < NUM_FORMATS; k++) { fmt = &formats[k]; if (fmt->fourcc == fourcc) break; } if (k == NUM_FORMATS) return NULL; return &formats[k]; } static void get_alignment(u32 fourcc, unsigned int *walign, unsigned int *halign) { switch (fourcc) { case V4L2_PIX_FMT_SBGGR8: case V4L2_PIX_FMT_SGBRG8: case V4L2_PIX_FMT_SGRBG8: case V4L2_PIX_FMT_SRGGB8: *walign = BAYER_WIDTH_ALIGN; *halign = BAYER_HEIGHT_ALIGN; return; default: *walign = WIDTH_ALIGN; *halign = HEIGHT_ALIGN; return; } } struct vim2m_dev { struct v4l2_device v4l2_dev; struct video_device vfd; #ifdef CONFIG_MEDIA_CONTROLLER struct media_device mdev; #endif atomic_t num_inst; struct mutex dev_mutex; struct v4l2_m2m_dev *m2m_dev; }; struct vim2m_ctx { struct v4l2_fh fh; struct vim2m_dev *dev; struct v4l2_ctrl_handler hdl; /* Processed buffers in this transaction */ u8 num_processed; /* Transaction length (i.e. how many buffers per transaction) */ u32 translen; /* Transaction time (i.e. simulated processing time) in milliseconds */ u32 transtime; struct mutex vb_mutex; struct delayed_work work_run; /* Abort requested by m2m */ int aborting; /* Processing mode */ int mode; enum v4l2_colorspace colorspace; enum v4l2_ycbcr_encoding ycbcr_enc; enum v4l2_xfer_func xfer_func; enum v4l2_quantization quant; /* Source and destination queue data */ struct vim2m_q_data q_data[2]; }; static inline struct vim2m_ctx *file2ctx(struct file *file) { return container_of(file->private_data, struct vim2m_ctx, fh); } static struct vim2m_q_data *get_q_data(struct vim2m_ctx *ctx, enum v4l2_buf_type type) { switch (type) { case V4L2_BUF_TYPE_VIDEO_OUTPUT: return &ctx->q_data[V4L2_M2M_SRC]; case V4L2_BUF_TYPE_VIDEO_CAPTURE: return &ctx->q_data[V4L2_M2M_DST]; default: return NULL; } } static const char *type_name(enum v4l2_buf_type type) { switch (type) { case V4L2_BUF_TYPE_VIDEO_OUTPUT: return "Output"; case V4L2_BUF_TYPE_VIDEO_CAPTURE: return "Capture"; default: return "Invalid"; } } #define CLIP(__color) \ (u8)(((__color) > 0xff) ? 0xff : (((__color) < 0) ? 0 : (__color))) static void copy_line(struct vim2m_q_data *q_data_out, u8 *src, u8 *dst, bool reverse) { int x, depth = q_data_out->fmt->depth >> 3; if (!reverse) { memcpy(dst, src, q_data_out->width * depth); } else { for (x = 0; x < q_data_out->width >> 1; x++) { memcpy(dst, src, depth); memcpy(dst + depth, src - depth, depth); src -= depth << 1; dst += depth << 1; } return; } } static void copy_two_pixels(struct vim2m_q_data *q_data_in, struct vim2m_q_data *q_data_out, u8 *src[2], u8 **dst, int ypos, bool reverse) { struct vim2m_fmt *out = q_data_out->fmt; struct vim2m_fmt *in = q_data_in->fmt; u8 _r[2], _g[2], _b[2], *r, *g, *b; int i; /* Step 1: read two consecutive pixels from src pointer */ r = _r; g = _g; b = _b; switch (in->fourcc) { case V4L2_PIX_FMT_RGB565: /* rrrrrggg gggbbbbb */ for (i = 0; i < 2; i++) { u16 pix = le16_to_cpu(*(__le16 *)(src[i])); *r++ = (u8)(((pix & 0xf800) >> 11) << 3) | 0x07; *g++ = (u8)((((pix & 0x07e0) >> 5)) << 2) | 0x03; *b++ = (u8)((pix & 0x1f) << 3) | 0x07; } break; case V4L2_PIX_FMT_RGB565X: /* gggbbbbb rrrrrggg */ for (i = 0; i < 2; i++) { u16 pix = be16_to_cpu(*(__be16 *)(src[i])); *r++ = (u8)(((pix & 0xf800) >> 11) << 3) | 0x07; *g++ = (u8)((((pix & 0x07e0) >> 5)) << 2) | 0x03; *b++ = (u8)((pix & 0x1f) << 3) | 0x07; } break; default: case V4L2_PIX_FMT_RGB24: for (i = 0; i < 2; i++) { *r++ = src[i][0]; *g++ = src[i][1]; *b++ = src[i][2]; } break; case V4L2_PIX_FMT_BGR24: for (i = 0; i < 2; i++) { *b++ = src[i][0]; *g++ = src[i][1]; *r++ = src[i][2]; } break; } /* Step 2: store two consecutive points, reversing them if needed */ r = _r; g = _g; b = _b; switch (out->fourcc) { case V4L2_PIX_FMT_RGB565: /* rrrrrggg gggbbbbb */ for (i = 0; i < 2; i++) { u16 pix; __le16 *dst_pix = (__le16 *)*dst; pix = ((*r << 8) & 0xf800) | ((*g << 3) & 0x07e0) | (*b >> 3); *dst_pix = cpu_to_le16(pix); *dst += 2; } return; case V4L2_PIX_FMT_RGB565X: /* gggbbbbb rrrrrggg */ for (i = 0; i < 2; i++) { u16 pix; __be16 *dst_pix = (__be16 *)*dst; pix = ((*r << 8) & 0xf800) | ((*g << 3) & 0x07e0) | (*b >> 3); *dst_pix = cpu_to_be16(pix); *dst += 2; } return; case V4L2_PIX_FMT_RGB24: for (i = 0; i < 2; i++) { *(*dst)++ = *r++; *(*dst)++ = *g++; *(*dst)++ = *b++; } return; case V4L2_PIX_FMT_BGR24: for (i = 0; i < 2; i++) { *(*dst)++ = *b++; *(*dst)++ = *g++; *(*dst)++ = *r++; } return; case V4L2_PIX_FMT_YUYV: default: { u8 y, y1, u, v; y = ((8453 * (*r) + 16594 * (*g) + 3223 * (*b) + 524288) >> 15); u = ((-4878 * (*r) - 9578 * (*g) + 14456 * (*b) + 4210688) >> 15); v = ((14456 * (*r++) - 12105 * (*g++) - 2351 * (*b++) + 4210688) >> 15); y1 = ((8453 * (*r) + 16594 * (*g) + 3223 * (*b) + 524288) >> 15); *(*dst)++ = y; *(*dst)++ = u; *(*dst)++ = y1; *(*dst)++ = v; return; } case V4L2_PIX_FMT_SBGGR8: if (!(ypos & 1)) { *(*dst)++ = *b; *(*dst)++ = *++g; } else { *(*dst)++ = *g; *(*dst)++ = *++r; } return; case V4L2_PIX_FMT_SGBRG8: if (!(ypos & 1)) { *(*dst)++ = *g; *(*dst)++ = *++b; } else { *(*dst)++ = *r; *(*dst)++ = *++g; } return; case V4L2_PIX_FMT_SGRBG8: if (!(ypos & 1)) { *(*dst)++ = *g; *(*dst)++ = *++r; } else { *(*dst)++ = *b; *(*dst)++ = *++g; } return; case V4L2_PIX_FMT_SRGGB8: if (!(ypos & 1)) { *(*dst)++ = *r; *(*dst)++ = *++g; } else { *(*dst)++ = *g; *(*dst)++ = *++b; } return; } } static int device_process(struct vim2m_ctx *ctx, struct vb2_v4l2_buffer *in_vb, struct vb2_v4l2_buffer *out_vb) { struct vim2m_dev *dev = ctx->dev; struct vim2m_q_data *q_data_in, *q_data_out; u8 *p_in, *p_line, *p_in_x[2], *p, *p_out; unsigned int width, height, bytesperline, bytes_per_pixel; unsigned int x, y, y_in, y_out, x_int, x_fract, x_err, x_offset; int start, end, step; q_data_in = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_OUTPUT); if (!q_data_in) return 0; bytesperline = (q_data_in->width * q_data_in->fmt->depth) >> 3; bytes_per_pixel = q_data_in->fmt->depth >> 3; q_data_out = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_CAPTURE); if (!q_data_out) return 0; /* As we're doing scaling, use the output dimensions here */ height = q_data_out->height; width = q_data_out->width; p_in = vb2_plane_vaddr(&in_vb->vb2_buf, 0); p_out = vb2_plane_vaddr(&out_vb->vb2_buf, 0); if (!p_in || !p_out) { v4l2_err(&dev->v4l2_dev, "Acquiring kernel pointers to buffers failed\n"); return -EFAULT; } out_vb->sequence = q_data_out->sequence++; in_vb->sequence = q_data_in->sequence++; v4l2_m2m_buf_copy_metadata(in_vb, out_vb, true); if (ctx->mode & MEM2MEM_VFLIP) { start = height - 1; end = -1; step = -1; } else { start = 0; end = height; step = 1; } y_out = 0; /* * When format and resolution are identical, * we can use a faster copy logic */ if (q_data_in->fmt->fourcc == q_data_out->fmt->fourcc && q_data_in->width == q_data_out->width && q_data_in->height == q_data_out->height) { for (y = start; y != end; y += step, y_out++) { p = p_in + (y * bytesperline); if (ctx->mode & MEM2MEM_HFLIP) p += bytesperline - (q_data_in->fmt->depth >> 3); copy_line(q_data_out, p, p_out, ctx->mode & MEM2MEM_HFLIP); p_out += bytesperline; } return 0; } /* Slower algorithm with format conversion, hflip, vflip and scaler */ /* To speed scaler up, use Bresenham for X dimension */ x_int = q_data_in->width / q_data_out->width; x_fract = q_data_in->width % q_data_out->width; for (y = start; y != end; y += step, y_out++) { y_in = (y * q_data_in->height) / q_data_out->height; x_offset = 0; x_err = 0; p_line = p_in + (y_in * bytesperline); if (ctx->mode & MEM2MEM_HFLIP) p_line += bytesperline - (q_data_in->fmt->depth >> 3); p_in_x[0] = p_line; for (x = 0; x < width >> 1; x++) { x_offset += x_int; x_err += x_fract; if (x_err > width) { x_offset++; x_err -= width; } if (ctx->mode & MEM2MEM_HFLIP) p_in_x[1] = p_line - x_offset * bytes_per_pixel; else p_in_x[1] = p_line + x_offset * bytes_per_pixel; copy_two_pixels(q_data_in, q_data_out, p_in_x, &p_out, y_out, ctx->mode & MEM2MEM_HFLIP); /* Calculate the next p_in_x0 */ x_offset += x_int; x_err += x_fract; if (x_err > width) { x_offset++; x_err -= width; } if (ctx->mode & MEM2MEM_HFLIP) p_in_x[0] = p_line - x_offset * bytes_per_pixel; else p_in_x[0] = p_line + x_offset * bytes_per_pixel; } } return 0; } /* * mem2mem callbacks */ /* * job_ready() - check whether an instance is ready to be scheduled to run */ static int job_ready(void *priv) { struct vim2m_ctx *ctx = priv; if (v4l2_m2m_num_src_bufs_ready(ctx->fh.m2m_ctx) < ctx->translen || v4l2_m2m_num_dst_bufs_ready(ctx->fh.m2m_ctx) < ctx->translen) { dprintk(ctx->dev, 1, "Not enough buffers available\n"); return 0; } return 1; } static void job_abort(void *priv) { struct vim2m_ctx *ctx = priv; /* Will cancel the transaction in the next interrupt handler */ ctx->aborting = 1; } /* device_run() - prepares and starts the device * * This simulates all the immediate preparations required before starting * a device. This will be called by the framework when it decides to schedule * a particular instance. */ static void device_run(void *priv) { struct vim2m_ctx *ctx = priv; struct vb2_v4l2_buffer *src_buf, *dst_buf; src_buf = v4l2_m2m_next_src_buf(ctx->fh.m2m_ctx); dst_buf = v4l2_m2m_next_dst_buf(ctx->fh.m2m_ctx); /* Apply request controls if any */ v4l2_ctrl_request_setup(src_buf->vb2_buf.req_obj.req, &ctx->hdl); device_process(ctx, src_buf, dst_buf); /* Complete request controls if any */ v4l2_ctrl_request_complete(src_buf->vb2_buf.req_obj.req, &ctx->hdl); /* Run delayed work, which simulates a hardware irq */ schedule_delayed_work(&ctx->work_run, msecs_to_jiffies(ctx->transtime)); } static void device_work(struct work_struct *w) { struct vim2m_ctx *curr_ctx; struct vim2m_dev *vim2m_dev; struct vb2_v4l2_buffer *src_vb, *dst_vb; curr_ctx = container_of(w, struct vim2m_ctx, work_run.work); vim2m_dev = curr_ctx->dev; src_vb = v4l2_m2m_src_buf_remove(curr_ctx->fh.m2m_ctx); dst_vb = v4l2_m2m_dst_buf_remove(curr_ctx->fh.m2m_ctx); curr_ctx->num_processed++; v4l2_m2m_buf_done(src_vb, VB2_BUF_STATE_DONE); v4l2_m2m_buf_done(dst_vb, VB2_BUF_STATE_DONE); if (curr_ctx->num_processed == curr_ctx->translen || curr_ctx->aborting) { dprintk(curr_ctx->dev, 2, "Finishing capture buffer fill\n"); curr_ctx->num_processed = 0; v4l2_m2m_job_finish(vim2m_dev->m2m_dev, curr_ctx->fh.m2m_ctx); } else { device_run(curr_ctx); } } /* * video ioctls */ static int vidioc_querycap(struct file *file, void *priv, struct v4l2_capability *cap) { strscpy(cap->driver, MEM2MEM_NAME, sizeof(cap->driver)); strscpy(cap->card, MEM2MEM_NAME, sizeof(cap->card)); snprintf(cap->bus_info, sizeof(cap->bus_info), "platform:%s", MEM2MEM_NAME); return 0; } static int enum_fmt(struct v4l2_fmtdesc *f, u32 type) { int i, num; struct vim2m_fmt *fmt; num = 0; for (i = 0; i < NUM_FORMATS; ++i) { if (formats[i].types & type) { /* index-th format of type type found ? */ if (num == f->index) break; /* * Correct type but haven't reached our index yet, * just increment per-type index */ ++num; } } if (i < NUM_FORMATS) { /* Format found */ fmt = &formats[i]; f->pixelformat = fmt->fourcc; return 0; } /* Format not found */ return -EINVAL; } static int vidioc_enum_fmt_vid_cap(struct file *file, void *priv, struct v4l2_fmtdesc *f) { return enum_fmt(f, MEM2MEM_CAPTURE); } static int vidioc_enum_fmt_vid_out(struct file *file, void *priv, struct v4l2_fmtdesc *f) { return enum_fmt(f, MEM2MEM_OUTPUT); } static int vidioc_enum_framesizes(struct file *file, void *priv, struct v4l2_frmsizeenum *fsize) { if (fsize->index != 0) return -EINVAL; if (!find_format(fsize->pixel_format)) return -EINVAL; fsize->type = V4L2_FRMSIZE_TYPE_STEPWISE; fsize->stepwise.min_width = MIN_W; fsize->stepwise.min_height = MIN_H; fsize->stepwise.max_width = MAX_W; fsize->stepwise.max_height = MAX_H; get_alignment(fsize->pixel_format, &fsize->stepwise.step_width, &fsize->stepwise.step_height); return 0; } static int vidioc_g_fmt(struct vim2m_ctx *ctx, struct v4l2_format *f) { struct vb2_queue *vq; struct vim2m_q_data *q_data; vq = v4l2_m2m_get_vq(ctx->fh.m2m_ctx, f->type); if (!vq) return -EINVAL; q_data = get_q_data(ctx, f->type); if (!q_data) return -EINVAL; f->fmt.pix.width = q_data->width; f->fmt.pix.height = q_data->height; f->fmt.pix.field = V4L2_FIELD_NONE; f->fmt.pix.pixelformat = q_data->fmt->fourcc; f->fmt.pix.bytesperline = (q_data->width * q_data->fmt->depth) >> 3; f->fmt.pix.sizeimage = q_data->sizeimage; f->fmt.pix.colorspace = ctx->colorspace; f->fmt.pix.xfer_func = ctx->xfer_func; f->fmt.pix.ycbcr_enc = ctx->ycbcr_enc; f->fmt.pix.quantization = ctx->quant; return 0; } static int vidioc_g_fmt_vid_out(struct file *file, void *priv, struct v4l2_format *f) { return vidioc_g_fmt(file2ctx(file), f); } static int vidioc_g_fmt_vid_cap(struct file *file, void *priv, struct v4l2_format *f) { return vidioc_g_fmt(file2ctx(file), f); } static int vidioc_try_fmt(struct v4l2_format *f, struct vim2m_fmt *fmt) { int walign, halign; /* * V4L2 specification specifies the driver corrects the * format struct if any of the dimensions is unsupported */ if (f->fmt.pix.height < MIN_H) f->fmt.pix.height = MIN_H; else if (f->fmt.pix.height > MAX_H) f->fmt.pix.height = MAX_H; if (f->fmt.pix.width < MIN_W) f->fmt.pix.width = MIN_W; else if (f->fmt.pix.width > MAX_W) f->fmt.pix.width = MAX_W; get_alignment(f->fmt.pix.pixelformat, &walign, &halign); f->fmt.pix.width &= ~(walign - 1); f->fmt.pix.height &= ~(halign - 1); f->fmt.pix.bytesperline = (f->fmt.pix.width * fmt->depth) >> 3; f->fmt.pix.sizeimage = f->fmt.pix.height * f->fmt.pix.bytesperline; f->fmt.pix.field = V4L2_FIELD_NONE; return 0; } static int vidioc_try_fmt_vid_cap(struct file *file, void *priv, struct v4l2_format *f) { struct vim2m_fmt *fmt; struct vim2m_ctx *ctx = file2ctx(file); fmt = find_format(f->fmt.pix.pixelformat); if (!fmt) { f->fmt.pix.pixelformat = formats[0].fourcc; fmt = find_format(f->fmt.pix.pixelformat); } if (!(fmt->types & MEM2MEM_CAPTURE)) { v4l2_err(&ctx->dev->v4l2_dev, "Fourcc format (0x%08x) invalid.\n", f->fmt.pix.pixelformat); return -EINVAL; } f->fmt.pix.colorspace = ctx->colorspace; f->fmt.pix.xfer_func = ctx->xfer_func; f->fmt.pix.ycbcr_enc = ctx->ycbcr_enc; f->fmt.pix.quantization = ctx->quant; return vidioc_try_fmt(f, fmt); } static int vidioc_try_fmt_vid_out(struct file *file, void *priv, struct v4l2_format *f) { struct vim2m_fmt *fmt; struct vim2m_ctx *ctx = file2ctx(file); fmt = find_format(f->fmt.pix.pixelformat); if (!fmt) { f->fmt.pix.pixelformat = formats[0].fourcc; fmt = find_format(f->fmt.pix.pixelformat); } if (!(fmt->types & MEM2MEM_OUTPUT)) { v4l2_err(&ctx->dev->v4l2_dev, "Fourcc format (0x%08x) invalid.\n", f->fmt.pix.pixelformat); return -EINVAL; } if (!f->fmt.pix.colorspace) f->fmt.pix.colorspace = V4L2_COLORSPACE_REC709; return vidioc_try_fmt(f, fmt); } static int vidioc_s_fmt(struct vim2m_ctx *ctx, struct v4l2_format *f) { struct vim2m_q_data *q_data; struct vb2_queue *vq; vq = v4l2_m2m_get_vq(ctx->fh.m2m_ctx, f->type); if (!vq) return -EINVAL; q_data = get_q_data(ctx, f->type); if (!q_data) return -EINVAL; if (vb2_is_busy(vq)) { v4l2_err(&ctx->dev->v4l2_dev, "%s queue busy\n", __func__); return -EBUSY; } q_data->fmt = find_format(f->fmt.pix.pixelformat); q_data->width = f->fmt.pix.width; q_data->height = f->fmt.pix.height; q_data->sizeimage = q_data->width * q_data->height * q_data->fmt->depth >> 3; dprintk(ctx->dev, 1, "Format for type %s: %dx%d (%d bpp), fmt: %c%c%c%c\n", type_name(f->type), q_data->width, q_data->height, q_data->fmt->depth, (q_data->fmt->fourcc & 0xff), (q_data->fmt->fourcc >> 8) & 0xff, (q_data->fmt->fourcc >> 16) & 0xff, (q_data->fmt->fourcc >> 24) & 0xff); return 0; } static int vidioc_s_fmt_vid_cap(struct file *file, void *priv, struct v4l2_format *f) { int ret; ret = vidioc_try_fmt_vid_cap(file, priv, f); if (ret) return ret; return vidioc_s_fmt(file2ctx(file), f); } static int vidioc_s_fmt_vid_out(struct file *file, void *priv, struct v4l2_format *f) { struct vim2m_ctx *ctx = file2ctx(file); int ret; ret = vidioc_try_fmt_vid_out(file, priv, f); if (ret) return ret; ret = vidioc_s_fmt(file2ctx(file), f); if (!ret) { ctx->colorspace = f->fmt.pix.colorspace; ctx->xfer_func = f->fmt.pix.xfer_func; ctx->ycbcr_enc = f->fmt.pix.ycbcr_enc; ctx->quant = f->fmt.pix.quantization; } return ret; } static int vim2m_s_ctrl(struct v4l2_ctrl *ctrl) { struct vim2m_ctx *ctx = container_of(ctrl->handler, struct vim2m_ctx, hdl); switch (ctrl->id) { case V4L2_CID_HFLIP: if (ctrl->val) ctx->mode |= MEM2MEM_HFLIP; else ctx->mode &= ~MEM2MEM_HFLIP; break; case V4L2_CID_VFLIP: if (ctrl->val) ctx->mode |= MEM2MEM_VFLIP; else ctx->mode &= ~MEM2MEM_VFLIP; break; case V4L2_CID_TRANS_TIME_MSEC: ctx->transtime = ctrl->val; if (ctx->transtime < 1) ctx->transtime = 1; break; case V4L2_CID_TRANS_NUM_BUFS: ctx->translen = ctrl->val; break; default: v4l2_err(&ctx->dev->v4l2_dev, "Invalid control\n"); return -EINVAL; } return 0; } static const struct v4l2_ctrl_ops vim2m_ctrl_ops = { .s_ctrl = vim2m_s_ctrl, }; static const struct v4l2_ioctl_ops vim2m_ioctl_ops = { .vidioc_querycap = vidioc_querycap, .vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap, .vidioc_enum_framesizes = vidioc_enum_framesizes, .vidioc_g_fmt_vid_cap = vidioc_g_fmt_vid_cap, .vidioc_try_fmt_vid_cap = vidioc_try_fmt_vid_cap, .vidioc_s_fmt_vid_cap = vidioc_s_fmt_vid_cap, .vidioc_enum_fmt_vid_out = vidioc_enum_fmt_vid_out, .vidioc_g_fmt_vid_out = vidioc_g_fmt_vid_out, .vidioc_try_fmt_vid_out = vidioc_try_fmt_vid_out, .vidioc_s_fmt_vid_out = vidioc_s_fmt_vid_out, .vidioc_reqbufs = v4l2_m2m_ioctl_reqbufs, .vidioc_querybuf = v4l2_m2m_ioctl_querybuf, .vidioc_qbuf = v4l2_m2m_ioctl_qbuf, .vidioc_dqbuf = v4l2_m2m_ioctl_dqbuf, .vidioc_prepare_buf = v4l2_m2m_ioctl_prepare_buf, .vidioc_create_bufs = v4l2_m2m_ioctl_create_bufs, .vidioc_expbuf = v4l2_m2m_ioctl_expbuf, .vidioc_streamon = v4l2_m2m_ioctl_streamon, .vidioc_streamoff = v4l2_m2m_ioctl_streamoff, .vidioc_subscribe_event = v4l2_ctrl_subscribe_event, .vidioc_unsubscribe_event = v4l2_event_unsubscribe, }; /* * Queue operations */ static int vim2m_queue_setup(struct vb2_queue *vq, unsigned int *nbuffers, unsigned int *nplanes, unsigned int sizes[], struct device *alloc_devs[]) { struct vim2m_ctx *ctx = vb2_get_drv_priv(vq); struct vim2m_q_data *q_data; unsigned int size, count = *nbuffers; q_data = get_q_data(ctx, vq->type); if (!q_data) return -EINVAL; size = q_data->width * q_data->height * q_data->fmt->depth >> 3; while (size * count > MEM2MEM_VID_MEM_LIMIT) (count)--; *nbuffers = count; if (*nplanes) return sizes[0] < size ? -EINVAL : 0; *nplanes = 1; sizes[0] = size; dprintk(ctx->dev, 1, "%s: get %d buffer(s) of size %d each.\n", type_name(vq->type), count, size); return 0; } static int vim2m_buf_out_validate(struct vb2_buffer *vb) { struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb); struct vim2m_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue); if (vbuf->field == V4L2_FIELD_ANY) vbuf->field = V4L2_FIELD_NONE; if (vbuf->field != V4L2_FIELD_NONE) { dprintk(ctx->dev, 1, "%s field isn't supported\n", __func__); return -EINVAL; } return 0; } static int vim2m_buf_prepare(struct vb2_buffer *vb) { struct vim2m_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue); struct vim2m_q_data *q_data; dprintk(ctx->dev, 2, "type: %s\n", type_name(vb->vb2_queue->type)); q_data = get_q_data(ctx, vb->vb2_queue->type); if (!q_data) return -EINVAL; if (vb2_plane_size(vb, 0) < q_data->sizeimage) { dprintk(ctx->dev, 1, "%s data will not fit into plane (%lu < %lu)\n", __func__, vb2_plane_size(vb, 0), (long)q_data->sizeimage); return -EINVAL; } vb2_set_plane_payload(vb, 0, q_data->sizeimage); return 0; } static void vim2m_buf_queue(struct vb2_buffer *vb) { struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb); struct vim2m_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue); v4l2_m2m_buf_queue(ctx->fh.m2m_ctx, vbuf); } static int vim2m_start_streaming(struct vb2_queue *q, unsigned int count) { struct vim2m_ctx *ctx = vb2_get_drv_priv(q); struct vim2m_q_data *q_data = get_q_data(ctx, q->type); if (!q_data) return -EINVAL; if (V4L2_TYPE_IS_OUTPUT(q->type)) ctx->aborting = 0; q_data->sequence = 0; return 0; } static void vim2m_stop_streaming(struct vb2_queue *q) { struct vim2m_ctx *ctx = vb2_get_drv_priv(q); struct vb2_v4l2_buffer *vbuf; cancel_delayed_work_sync(&ctx->work_run); for (;;) { if (V4L2_TYPE_IS_OUTPUT(q->type)) vbuf = v4l2_m2m_src_buf_remove(ctx->fh.m2m_ctx); else vbuf = v4l2_m2m_dst_buf_remove(ctx->fh.m2m_ctx); if (!vbuf) return; v4l2_ctrl_request_complete(vbuf->vb2_buf.req_obj.req, &ctx->hdl); v4l2_m2m_buf_done(vbuf, VB2_BUF_STATE_ERROR); } } static void vim2m_buf_request_complete(struct vb2_buffer *vb) { struct vim2m_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue); v4l2_ctrl_request_complete(vb->req_obj.req, &ctx->hdl); } static const struct vb2_ops vim2m_qops = { .queue_setup = vim2m_queue_setup, .buf_out_validate = vim2m_buf_out_validate, .buf_prepare = vim2m_buf_prepare, .buf_queue = vim2m_buf_queue, .start_streaming = vim2m_start_streaming, .stop_streaming = vim2m_stop_streaming, .wait_prepare = vb2_ops_wait_prepare, .wait_finish = vb2_ops_wait_finish, .buf_request_complete = vim2m_buf_request_complete, }; static int queue_init(void *priv, struct vb2_queue *src_vq, struct vb2_queue *dst_vq) { struct vim2m_ctx *ctx = priv; int ret; src_vq->type = V4L2_BUF_TYPE_VIDEO_OUTPUT; src_vq->io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF; src_vq->drv_priv = ctx; src_vq->buf_struct_size = sizeof(struct v4l2_m2m_buffer); src_vq->ops = &vim2m_qops; src_vq->mem_ops = &vb2_vmalloc_memops; src_vq->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_COPY; src_vq->lock = &ctx->vb_mutex; src_vq->supports_requests = true; ret = vb2_queue_init(src_vq); if (ret) return ret; dst_vq->type = V4L2_BUF_TYPE_VIDEO_CAPTURE; dst_vq->io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF; dst_vq->drv_priv = ctx; dst_vq->buf_struct_size = sizeof(struct v4l2_m2m_buffer); dst_vq->ops = &vim2m_qops; dst_vq->mem_ops = &vb2_vmalloc_memops; dst_vq->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_COPY; dst_vq->lock = &ctx->vb_mutex; return vb2_queue_init(dst_vq); } static struct v4l2_ctrl_config vim2m_ctrl_trans_time_msec = { .ops = &vim2m_ctrl_ops, .id = V4L2_CID_TRANS_TIME_MSEC, .name = "Transaction Time (msec)", .type = V4L2_CTRL_TYPE_INTEGER, .min = 1, .max = 10001, .step = 1, }; static const struct v4l2_ctrl_config vim2m_ctrl_trans_num_bufs = { .ops = &vim2m_ctrl_ops, .id = V4L2_CID_TRANS_NUM_BUFS, .name = "Buffers Per Transaction", .type = V4L2_CTRL_TYPE_INTEGER, .def = 1, .min = 1, .max = MEM2MEM_DEF_NUM_BUFS, .step = 1, }; /* * File operations */ static int vim2m_open(struct file *file) { struct vim2m_dev *dev = video_drvdata(file); struct vim2m_ctx *ctx = NULL; struct v4l2_ctrl_handler *hdl; int rc = 0; if (mutex_lock_interruptible(&dev->dev_mutex)) return -ERESTARTSYS; ctx = kzalloc(sizeof(*ctx), GFP_KERNEL); if (!ctx) { rc = -ENOMEM; goto open_unlock; } v4l2_fh_init(&ctx->fh, video_devdata(file)); file->private_data = &ctx->fh; ctx->dev = dev; hdl = &ctx->hdl; v4l2_ctrl_handler_init(hdl, 4); v4l2_ctrl_new_std(hdl, &vim2m_ctrl_ops, V4L2_CID_HFLIP, 0, 1, 1, 0); v4l2_ctrl_new_std(hdl, &vim2m_ctrl_ops, V4L2_CID_VFLIP, 0, 1, 1, 0); vim2m_ctrl_trans_time_msec.def = default_transtime; v4l2_ctrl_new_custom(hdl, &vim2m_ctrl_trans_time_msec, NULL); v4l2_ctrl_new_custom(hdl, &vim2m_ctrl_trans_num_bufs, NULL); if (hdl->error) { rc = hdl->error; v4l2_ctrl_handler_free(hdl); kfree(ctx); goto open_unlock; } ctx->fh.ctrl_handler = hdl; v4l2_ctrl_handler_setup(hdl); ctx->q_data[V4L2_M2M_SRC].fmt = &formats[0]; ctx->q_data[V4L2_M2M_SRC].width = 640; ctx->q_data[V4L2_M2M_SRC].height = 480; ctx->q_data[V4L2_M2M_SRC].sizeimage = ctx->q_data[V4L2_M2M_SRC].width * ctx->q_data[V4L2_M2M_SRC].height * (ctx->q_data[V4L2_M2M_SRC].fmt->depth >> 3); ctx->q_data[V4L2_M2M_DST] = ctx->q_data[V4L2_M2M_SRC]; ctx->colorspace = V4L2_COLORSPACE_REC709; ctx->fh.m2m_ctx = v4l2_m2m_ctx_init(dev->m2m_dev, ctx, &queue_init); mutex_init(&ctx->vb_mutex); INIT_DELAYED_WORK(&ctx->work_run, device_work); if (IS_ERR(ctx->fh.m2m_ctx)) { rc = PTR_ERR(ctx->fh.m2m_ctx); v4l2_ctrl_handler_free(hdl); v4l2_fh_exit(&ctx->fh); kfree(ctx); goto open_unlock; } v4l2_fh_add(&ctx->fh); atomic_inc(&dev->num_inst); dprintk(dev, 1, "Created instance: %p, m2m_ctx: %p\n", ctx, ctx->fh.m2m_ctx); open_unlock: mutex_unlock(&dev->dev_mutex); return rc; } static int vim2m_release(struct file *file) { struct vim2m_dev *dev = video_drvdata(file); struct vim2m_ctx *ctx = file2ctx(file); dprintk(dev, 1, "Releasing instance %p\n", ctx); v4l2_fh_del(&ctx->fh); v4l2_fh_exit(&ctx->fh); v4l2_ctrl_handler_free(&ctx->hdl); mutex_lock(&dev->dev_mutex); v4l2_m2m_ctx_release(ctx->fh.m2m_ctx); mutex_unlock(&dev->dev_mutex); kfree(ctx); atomic_dec(&dev->num_inst); return 0; } static void vim2m_device_release(struct video_device *vdev) { struct vim2m_dev *dev = container_of(vdev, struct vim2m_dev, vfd); v4l2_device_unregister(&dev->v4l2_dev); v4l2_m2m_release(dev->m2m_dev); #ifdef CONFIG_MEDIA_CONTROLLER media_device_cleanup(&dev->mdev); #endif kfree(dev); } static const struct v4l2_file_operations vim2m_fops = { .owner = THIS_MODULE, .open = vim2m_open, .release = vim2m_release, .poll = v4l2_m2m_fop_poll, .unlocked_ioctl = video_ioctl2, .mmap = v4l2_m2m_fop_mmap, }; static const struct video_device vim2m_videodev = { .name = MEM2MEM_NAME, .vfl_dir = VFL_DIR_M2M, .fops = &vim2m_fops, .ioctl_ops = &vim2m_ioctl_ops, .minor = -1, .release = vim2m_device_release, .device_caps = V4L2_CAP_VIDEO_M2M | V4L2_CAP_STREAMING, }; static const struct v4l2_m2m_ops m2m_ops = { .device_run = device_run, .job_ready = job_ready, .job_abort = job_abort, }; static const struct media_device_ops m2m_media_ops = { .req_validate = vb2_request_validate, .req_queue = v4l2_m2m_request_queue, }; static int vim2m_probe(struct platform_device *pdev) { struct vim2m_dev *dev; struct video_device *vfd; int ret; dev = kzalloc(sizeof(*dev), GFP_KERNEL); if (!dev) return -ENOMEM; ret = v4l2_device_register(&pdev->dev, &dev->v4l2_dev); if (ret) goto error_free; atomic_set(&dev->num_inst, 0); mutex_init(&dev->dev_mutex); dev->vfd = vim2m_videodev; vfd = &dev->vfd; vfd->lock = &dev->dev_mutex; vfd->v4l2_dev = &dev->v4l2_dev; video_set_drvdata(vfd, dev); v4l2_info(&dev->v4l2_dev, "Device registered as /dev/video%d\n", vfd->num); platform_set_drvdata(pdev, dev); dev->m2m_dev = v4l2_m2m_init(&m2m_ops); if (IS_ERR(dev->m2m_dev)) { v4l2_err(&dev->v4l2_dev, "Failed to init mem2mem device\n"); ret = PTR_ERR(dev->m2m_dev); dev->m2m_dev = NULL; goto error_dev; } #ifdef CONFIG_MEDIA_CONTROLLER dev->mdev.dev = &pdev->dev; strscpy(dev->mdev.model, "vim2m", sizeof(dev->mdev.model)); strscpy(dev->mdev.bus_info, "platform:vim2m", sizeof(dev->mdev.bus_info)); media_device_init(&dev->mdev); dev->mdev.ops = &m2m_media_ops; dev->v4l2_dev.mdev = &dev->mdev; #endif ret = video_register_device(vfd, VFL_TYPE_VIDEO, 0); if (ret) { v4l2_err(&dev->v4l2_dev, "Failed to register video device\n"); goto error_m2m; } #ifdef CONFIG_MEDIA_CONTROLLER ret = v4l2_m2m_register_media_controller(dev->m2m_dev, vfd, MEDIA_ENT_F_PROC_VIDEO_SCALER); if (ret) { v4l2_err(&dev->v4l2_dev, "Failed to init mem2mem media controller\n"); goto error_v4l2; } ret = media_device_register(&dev->mdev); if (ret) { v4l2_err(&dev->v4l2_dev, "Failed to register mem2mem media device\n"); goto error_m2m_mc; } #endif return 0; #ifdef CONFIG_MEDIA_CONTROLLER error_m2m_mc: v4l2_m2m_unregister_media_controller(dev->m2m_dev); #endif error_v4l2: video_unregister_device(&dev->vfd); /* vim2m_device_release called by video_unregister_device to release various objects */ return ret; error_m2m: v4l2_m2m_release(dev->m2m_dev); error_dev: v4l2_device_unregister(&dev->v4l2_dev); error_free: kfree(dev); return ret; } static void vim2m_remove(struct platform_device *pdev) { struct vim2m_dev *dev = platform_get_drvdata(pdev); v4l2_info(&dev->v4l2_dev, "Removing " MEM2MEM_NAME); #ifdef CONFIG_MEDIA_CONTROLLER media_device_unregister(&dev->mdev); v4l2_m2m_unregister_media_controller(dev->m2m_dev); #endif video_unregister_device(&dev->vfd); } static struct platform_driver vim2m_pdrv = { .probe = vim2m_probe, .remove_new = vim2m_remove, .driver = { .name = MEM2MEM_NAME, }, }; static void __exit vim2m_exit(void) { platform_driver_unregister(&vim2m_pdrv); platform_device_unregister(&vim2m_pdev); } static int __init vim2m_init(void) { int ret; ret = platform_device_register(&vim2m_pdev); if (ret) return ret; ret = platform_driver_register(&vim2m_pdrv); if (ret) platform_device_unregister(&vim2m_pdev); return ret; } module_init(vim2m_init); module_exit(vim2m_exit);
linux-master
drivers/media/test-drivers/vim2m.c
// SPDX-License-Identifier: GPL-2.0-only /* * vivid-touch-cap.c - touch support functions. */ #include "vivid-core.h" #include "vivid-kthread-touch.h" #include "vivid-vid-common.h" #include "vivid-touch-cap.h" static int touch_cap_queue_setup(struct vb2_queue *vq, unsigned int *nbuffers, unsigned int *nplanes, unsigned int sizes[], struct device *alloc_devs[]) { struct vivid_dev *dev = vb2_get_drv_priv(vq); struct v4l2_pix_format *f = &dev->tch_format; unsigned int size = f->sizeimage; if (*nplanes) { if (sizes[0] < size) return -EINVAL; } else { sizes[0] = size; } if (vq->num_buffers + *nbuffers < 2) *nbuffers = 2 - vq->num_buffers; *nplanes = 1; return 0; } static int touch_cap_buf_prepare(struct vb2_buffer *vb) { struct vivid_dev *dev = vb2_get_drv_priv(vb->vb2_queue); struct v4l2_pix_format *f = &dev->tch_format; unsigned int size = f->sizeimage; if (dev->buf_prepare_error) { /* * Error injection: test what happens if buf_prepare() returns * an error. */ dev->buf_prepare_error = false; return -EINVAL; } if (vb2_plane_size(vb, 0) < size) { dprintk(dev, 1, "%s data will not fit into plane (%lu < %u)\n", __func__, vb2_plane_size(vb, 0), size); return -EINVAL; } vb2_set_plane_payload(vb, 0, size); return 0; } static void touch_cap_buf_queue(struct vb2_buffer *vb) { struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb); struct vivid_dev *dev = vb2_get_drv_priv(vb->vb2_queue); struct vivid_buffer *buf = container_of(vbuf, struct vivid_buffer, vb); vbuf->field = V4L2_FIELD_NONE; spin_lock(&dev->slock); list_add_tail(&buf->list, &dev->touch_cap_active); spin_unlock(&dev->slock); } static int touch_cap_start_streaming(struct vb2_queue *vq, unsigned int count) { struct vivid_dev *dev = vb2_get_drv_priv(vq); int err; dev->touch_cap_seq_count = 0; if (dev->start_streaming_error) { dev->start_streaming_error = false; err = -EINVAL; } else { err = vivid_start_generating_touch_cap(dev); } if (err) { struct vivid_buffer *buf, *tmp; list_for_each_entry_safe(buf, tmp, &dev->touch_cap_active, list) { list_del(&buf->list); vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_QUEUED); } } return err; } /* abort streaming and wait for last buffer */ static void touch_cap_stop_streaming(struct vb2_queue *vq) { struct vivid_dev *dev = vb2_get_drv_priv(vq); vivid_stop_generating_touch_cap(dev); } static void touch_cap_buf_request_complete(struct vb2_buffer *vb) { struct vivid_dev *dev = vb2_get_drv_priv(vb->vb2_queue); v4l2_ctrl_request_complete(vb->req_obj.req, &dev->ctrl_hdl_touch_cap); } const struct vb2_ops vivid_touch_cap_qops = { .queue_setup = touch_cap_queue_setup, .buf_prepare = touch_cap_buf_prepare, .buf_queue = touch_cap_buf_queue, .start_streaming = touch_cap_start_streaming, .stop_streaming = touch_cap_stop_streaming, .buf_request_complete = touch_cap_buf_request_complete, .wait_prepare = vb2_ops_wait_prepare, .wait_finish = vb2_ops_wait_finish, }; int vivid_enum_fmt_tch(struct file *file, void *priv, struct v4l2_fmtdesc *f) { if (f->index) return -EINVAL; f->pixelformat = V4L2_TCH_FMT_DELTA_TD16; return 0; } int vivid_g_fmt_tch(struct file *file, void *priv, struct v4l2_format *f) { struct vivid_dev *dev = video_drvdata(file); if (dev->multiplanar) return -ENOTTY; f->fmt.pix = dev->tch_format; return 0; } int vivid_g_fmt_tch_mplane(struct file *file, void *priv, struct v4l2_format *f) { struct vivid_dev *dev = video_drvdata(file); struct v4l2_format sp_fmt; if (!dev->multiplanar) return -ENOTTY; sp_fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; sp_fmt.fmt.pix = dev->tch_format; fmt_sp2mp(&sp_fmt, f); return 0; } int vivid_g_parm_tch(struct file *file, void *priv, struct v4l2_streamparm *parm) { struct vivid_dev *dev = video_drvdata(file); if (parm->type != (dev->multiplanar ? V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE : V4L2_BUF_TYPE_VIDEO_CAPTURE)) return -EINVAL; parm->parm.capture.capability = V4L2_CAP_TIMEPERFRAME; parm->parm.capture.timeperframe = dev->timeperframe_tch_cap; parm->parm.capture.readbuffers = 1; return 0; } int vivid_enum_input_tch(struct file *file, void *priv, struct v4l2_input *inp) { if (inp->index) return -EINVAL; inp->type = V4L2_INPUT_TYPE_TOUCH; strscpy(inp->name, "Vivid Touch", sizeof(inp->name)); inp->capabilities = 0; return 0; } int vivid_g_input_tch(struct file *file, void *priv, unsigned int *i) { *i = 0; return 0; } int vivid_set_touch(struct vivid_dev *dev, unsigned int i) { struct v4l2_pix_format *f = &dev->tch_format; if (i) return -EINVAL; f->pixelformat = V4L2_TCH_FMT_DELTA_TD16; f->width = VIVID_TCH_WIDTH; f->height = VIVID_TCH_HEIGHT; f->field = V4L2_FIELD_NONE; f->colorspace = V4L2_COLORSPACE_RAW; f->bytesperline = f->width * sizeof(s16); f->sizeimage = f->width * f->height * sizeof(s16); return 0; } int vivid_s_input_tch(struct file *file, void *priv, unsigned int i) { return vivid_set_touch(video_drvdata(file), i); } static void vivid_fill_buff_noise(__s16 *tch_buf, int size) { int i; /* Fill 10% of the values within range -3 and 3, zero the others */ for (i = 0; i < size; i++) { unsigned int rand = get_random_u32(); if (rand % 10) tch_buf[i] = 0; else tch_buf[i] = (rand / 10) % 7 - 3; } } static inline int get_random_pressure(void) { return get_random_u32_below(VIVID_PRESSURE_LIMIT); } static void vivid_tch_buf_set(struct v4l2_pix_format *f, __s16 *tch_buf, int index) { unsigned int x = index % f->width; unsigned int y = index / f->width; unsigned int offset = VIVID_MIN_PRESSURE; tch_buf[index] = offset + get_random_pressure(); offset /= 2; if (x) tch_buf[index - 1] = offset + get_random_pressure(); if (x < f->width - 1) tch_buf[index + 1] = offset + get_random_pressure(); if (y) tch_buf[index - f->width] = offset + get_random_pressure(); if (y < f->height - 1) tch_buf[index + f->width] = offset + get_random_pressure(); offset /= 2; if (x && y) tch_buf[index - 1 - f->width] = offset + get_random_pressure(); if (x < f->width - 1 && y) tch_buf[index + 1 - f->width] = offset + get_random_pressure(); if (x && y < f->height - 1) tch_buf[index - 1 + f->width] = offset + get_random_pressure(); if (x < f->width - 1 && y < f->height - 1) tch_buf[index + 1 + f->width] = offset + get_random_pressure(); } void vivid_fillbuff_tch(struct vivid_dev *dev, struct vivid_buffer *buf) { struct v4l2_pix_format *f = &dev->tch_format; int size = f->width * f->height; int x, y, xstart, ystart, offset_x, offset_y; unsigned int test_pattern, test_pat_idx, rand; __s16 *tch_buf = vb2_plane_vaddr(&buf->vb.vb2_buf, 0); buf->vb.sequence = dev->touch_cap_with_seq_wrap_count; test_pattern = (buf->vb.sequence / TCH_SEQ_COUNT) % TEST_CASE_MAX; test_pat_idx = buf->vb.sequence % TCH_SEQ_COUNT; vivid_fill_buff_noise(tch_buf, size); if (test_pat_idx >= TCH_PATTERN_COUNT) return; if (test_pat_idx == 0) dev->tch_pat_random = get_random_u32(); rand = dev->tch_pat_random; switch (test_pattern) { case SINGLE_TAP: if (test_pat_idx == 2) vivid_tch_buf_set(f, tch_buf, rand % size); break; case DOUBLE_TAP: if (test_pat_idx == 2 || test_pat_idx == 4) vivid_tch_buf_set(f, tch_buf, rand % size); break; case TRIPLE_TAP: if (test_pat_idx == 2 || test_pat_idx == 4 || test_pat_idx == 6) vivid_tch_buf_set(f, tch_buf, rand % size); break; case MOVE_LEFT_TO_RIGHT: vivid_tch_buf_set(f, tch_buf, (rand % f->height) * f->width + test_pat_idx * (f->width / TCH_PATTERN_COUNT)); break; case ZOOM_IN: x = f->width / 2; y = f->height / 2; offset_x = ((TCH_PATTERN_COUNT - 1 - test_pat_idx) * x) / TCH_PATTERN_COUNT; offset_y = ((TCH_PATTERN_COUNT - 1 - test_pat_idx) * y) / TCH_PATTERN_COUNT; vivid_tch_buf_set(f, tch_buf, (x - offset_x) + f->width * (y - offset_y)); vivid_tch_buf_set(f, tch_buf, (x + offset_x) + f->width * (y + offset_y)); break; case ZOOM_OUT: x = f->width / 2; y = f->height / 2; offset_x = (test_pat_idx * x) / TCH_PATTERN_COUNT; offset_y = (test_pat_idx * y) / TCH_PATTERN_COUNT; vivid_tch_buf_set(f, tch_buf, (x - offset_x) + f->width * (y - offset_y)); vivid_tch_buf_set(f, tch_buf, (x + offset_x) + f->width * (y + offset_y)); break; case PALM_PRESS: for (x = 0; x < f->width; x++) for (y = f->height / 2; y < f->height; y++) tch_buf[x + f->width * y] = VIVID_MIN_PRESSURE + get_random_pressure(); break; case MULTIPLE_PRESS: /* 16 pressure points */ for (y = 0; y < 4; y++) { for (x = 0; x < 4; x++) { ystart = (y * f->height) / 4 + f->height / 8; xstart = (x * f->width) / 4 + f->width / 8; vivid_tch_buf_set(f, tch_buf, ystart * f->width + xstart); } } break; } #ifdef __BIG_ENDIAN__ for (x = 0; x < size; x++) tch_buf[x] = (__force s16)__cpu_to_le16((u16)tch_buf[x]); #endif }
linux-master
drivers/media/test-drivers/vivid/vivid-touch-cap.c
// SPDX-License-Identifier: GPL-2.0-only /* * vivid-radio-tx.c - radio transmitter support functions. * * Copyright 2014 Cisco Systems, Inc. and/or its affiliates. All rights reserved. */ #include <linux/errno.h> #include <linux/kernel.h> #include <linux/sched/signal.h> #include <linux/delay.h> #include <linux/videodev2.h> #include <linux/v4l2-dv-timings.h> #include <media/v4l2-common.h> #include <media/v4l2-event.h> #include <media/v4l2-dv-timings.h> #include "vivid-core.h" #include "vivid-ctrls.h" #include "vivid-radio-common.h" #include "vivid-radio-tx.h" ssize_t vivid_radio_tx_write(struct file *file, const char __user *buf, size_t size, loff_t *offset) { struct vivid_dev *dev = video_drvdata(file); struct v4l2_rds_data *data = dev->rds_gen.data; ktime_t timestamp; unsigned blk; int i; if (dev->radio_tx_rds_controls) return -EINVAL; if (size < sizeof(*data)) return -EINVAL; size = sizeof(*data) * (size / sizeof(*data)); if (mutex_lock_interruptible(&dev->mutex)) return -ERESTARTSYS; if (dev->radio_tx_rds_owner && file->private_data != dev->radio_tx_rds_owner) { mutex_unlock(&dev->mutex); return -EBUSY; } dev->radio_tx_rds_owner = file->private_data; retry: timestamp = ktime_sub(ktime_get(), dev->radio_rds_init_time); blk = ktime_divns(timestamp, VIVID_RDS_NSEC_PER_BLK); if (blk - VIVID_RDS_GEN_BLOCKS >= dev->radio_tx_rds_last_block) dev->radio_tx_rds_last_block = blk - VIVID_RDS_GEN_BLOCKS + 1; /* * No data is available if there hasn't been time to get new data, * or if the RDS receiver has been disabled, or if we use the data * from the RDS transmitter and that RDS transmitter has been disabled, * or if the signal quality is too weak. */ if (blk == dev->radio_tx_rds_last_block || !(dev->radio_tx_subchans & V4L2_TUNER_SUB_RDS)) { mutex_unlock(&dev->mutex); if (file->f_flags & O_NONBLOCK) return -EWOULDBLOCK; if (msleep_interruptible(20) && signal_pending(current)) return -EINTR; if (mutex_lock_interruptible(&dev->mutex)) return -ERESTARTSYS; goto retry; } for (i = 0; i < size && blk > dev->radio_tx_rds_last_block; dev->radio_tx_rds_last_block++) { unsigned data_blk = dev->radio_tx_rds_last_block % VIVID_RDS_GEN_BLOCKS; struct v4l2_rds_data rds; if (copy_from_user(&rds, buf + i, sizeof(rds))) { i = -EFAULT; break; } i += sizeof(rds); if (!dev->radio_rds_loop) continue; if ((rds.block & V4L2_RDS_BLOCK_MSK) == V4L2_RDS_BLOCK_INVALID || (rds.block & V4L2_RDS_BLOCK_ERROR)) continue; rds.block &= V4L2_RDS_BLOCK_MSK; data[data_blk] = rds; } mutex_unlock(&dev->mutex); return i; } __poll_t vivid_radio_tx_poll(struct file *file, struct poll_table_struct *wait) { return EPOLLOUT | EPOLLWRNORM | v4l2_ctrl_poll(file, wait); } int vidioc_g_modulator(struct file *file, void *fh, struct v4l2_modulator *a) { struct vivid_dev *dev = video_drvdata(file); if (a->index > 0) return -EINVAL; strscpy(a->name, "AM/FM/SW Transmitter", sizeof(a->name)); a->capability = V4L2_TUNER_CAP_LOW | V4L2_TUNER_CAP_STEREO | V4L2_TUNER_CAP_FREQ_BANDS | V4L2_TUNER_CAP_RDS | (dev->radio_tx_rds_controls ? V4L2_TUNER_CAP_RDS_CONTROLS : V4L2_TUNER_CAP_RDS_BLOCK_IO); a->rangelow = AM_FREQ_RANGE_LOW; a->rangehigh = FM_FREQ_RANGE_HIGH; a->txsubchans = dev->radio_tx_subchans; return 0; } int vidioc_s_modulator(struct file *file, void *fh, const struct v4l2_modulator *a) { struct vivid_dev *dev = video_drvdata(file); if (a->index) return -EINVAL; if (a->txsubchans & ~0x13) return -EINVAL; dev->radio_tx_subchans = a->txsubchans; return 0; }
linux-master
drivers/media/test-drivers/vivid/vivid-radio-tx.c
// SPDX-License-Identifier: GPL-2.0-only /* * vivid-rds-gen.c - rds (radio data system) generator support functions. * * Copyright 2014 Cisco Systems, Inc. and/or its affiliates. All rights reserved. */ #include <linux/kernel.h> #include <linux/ktime.h> #include <linux/string.h> #include <linux/videodev2.h> #include "vivid-rds-gen.h" static u8 vivid_get_di(const struct vivid_rds_gen *rds, unsigned grp) { switch (grp) { case 0: return (rds->dyn_pty << 2) | (grp & 3); case 1: return (rds->compressed << 2) | (grp & 3); case 2: return (rds->art_head << 2) | (grp & 3); case 3: return (rds->mono_stereo << 2) | (grp & 3); } return 0; } /* * This RDS generator creates 57 RDS groups (one group == four RDS blocks). * Groups 0-3, 22-25 and 44-47 (spaced 22 groups apart) are filled with a * standard 0B group containing the PI code and PS name. * * Groups 4-19 and 26-41 use group 2A for the radio text. * * Group 56 contains the time (group 4A). * * All remaining groups use a filler group 15B block that just repeats * the PI and PTY codes. */ void vivid_rds_generate(struct vivid_rds_gen *rds) { struct v4l2_rds_data *data = rds->data; unsigned grp; unsigned idx; struct tm tm; unsigned date; unsigned time; int l; for (grp = 0; grp < VIVID_RDS_GEN_GROUPS; grp++, data += VIVID_RDS_GEN_BLKS_PER_GRP) { data[0].lsb = rds->picode & 0xff; data[0].msb = rds->picode >> 8; data[0].block = V4L2_RDS_BLOCK_A | (V4L2_RDS_BLOCK_A << 3); data[1].lsb = rds->pty << 5; data[1].msb = (rds->pty >> 3) | (rds->tp << 2); data[1].block = V4L2_RDS_BLOCK_B | (V4L2_RDS_BLOCK_B << 3); data[3].block = V4L2_RDS_BLOCK_D | (V4L2_RDS_BLOCK_D << 3); switch (grp) { case 0 ... 3: case 22 ... 25: case 44 ... 47: /* Group 0B */ idx = (grp % 22) % 4; data[1].lsb |= (rds->ta << 4) | (rds->ms << 3); data[1].lsb |= vivid_get_di(rds, idx); data[1].msb |= 1 << 3; data[2].lsb = rds->picode & 0xff; data[2].msb = rds->picode >> 8; data[2].block = V4L2_RDS_BLOCK_C_ALT | (V4L2_RDS_BLOCK_C_ALT << 3); data[3].lsb = rds->psname[2 * idx + 1]; data[3].msb = rds->psname[2 * idx]; break; case 4 ... 19: case 26 ... 41: /* Group 2A */ idx = ((grp - 4) % 22) % 16; data[1].lsb |= idx; data[1].msb |= 4 << 3; data[2].msb = rds->radiotext[4 * idx]; data[2].lsb = rds->radiotext[4 * idx + 1]; data[2].block = V4L2_RDS_BLOCK_C | (V4L2_RDS_BLOCK_C << 3); data[3].msb = rds->radiotext[4 * idx + 2]; data[3].lsb = rds->radiotext[4 * idx + 3]; break; case 56: /* * Group 4A * * Uses the algorithm from Annex G of the RDS standard * EN 50067:1998 to convert a UTC date to an RDS Modified * Julian Day. */ time64_to_tm(ktime_get_real_seconds(), 0, &tm); l = tm.tm_mon <= 1; date = 14956 + tm.tm_mday + ((tm.tm_year - l) * 1461) / 4 + ((tm.tm_mon + 2 + l * 12) * 306001) / 10000; time = (tm.tm_hour << 12) | (tm.tm_min << 6) | (sys_tz.tz_minuteswest >= 0 ? 0x20 : 0) | (abs(sys_tz.tz_minuteswest) / 30); data[1].lsb &= ~3; data[1].lsb |= date >> 15; data[1].msb |= 8 << 3; data[2].lsb = (date << 1) & 0xfe; data[2].lsb |= (time >> 16) & 1; data[2].msb = (date >> 7) & 0xff; data[2].block = V4L2_RDS_BLOCK_C | (V4L2_RDS_BLOCK_C << 3); data[3].lsb = time & 0xff; data[3].msb = (time >> 8) & 0xff; break; default: /* Group 15B */ data[1].lsb |= (rds->ta << 4) | (rds->ms << 3); data[1].lsb |= vivid_get_di(rds, grp % 22); data[1].msb |= 0x1f << 3; data[2].lsb = rds->picode & 0xff; data[2].msb = rds->picode >> 8; data[2].block = V4L2_RDS_BLOCK_C_ALT | (V4L2_RDS_BLOCK_C_ALT << 3); data[3].lsb = rds->pty << 5; data[3].lsb |= (rds->ta << 4) | (rds->ms << 3); data[3].lsb |= vivid_get_di(rds, grp % 22); data[3].msb |= rds->pty >> 3; data[3].msb |= 0x1f << 3; break; } } } void vivid_rds_gen_fill(struct vivid_rds_gen *rds, unsigned freq, bool alt) { /* Alternate PTY between Info and Weather */ if (rds->use_rbds) { rds->picode = 0x2e75; /* 'KLNX' call sign */ rds->pty = alt ? 29 : 2; } else { rds->picode = 0x8088; rds->pty = alt ? 16 : 3; } rds->mono_stereo = true; rds->art_head = false; rds->compressed = false; rds->dyn_pty = false; rds->tp = true; rds->ta = alt; rds->ms = true; snprintf(rds->psname, sizeof(rds->psname), "%6d.%1d", freq / 16, ((freq & 0xf) * 10) / 16); if (alt) strscpy(rds->radiotext, " The Radio Data System can switch between different Radio Texts ", sizeof(rds->radiotext)); else strscpy(rds->radiotext, "An example of Radio Text as transmitted by the Radio Data System", sizeof(rds->radiotext)); }
linux-master
drivers/media/test-drivers/vivid/vivid-rds-gen.c
// SPDX-License-Identifier: GPL-2.0-only /* * vivid-kthread-out.h - video/vbi output thread support functions. * * Copyright 2014 Cisco Systems, Inc. and/or its affiliates. All rights reserved. */ #include <linux/module.h> #include <linux/errno.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/font.h> #include <linux/mutex.h> #include <linux/videodev2.h> #include <linux/kthread.h> #include <linux/freezer.h> #include <linux/random.h> #include <linux/v4l2-dv-timings.h> #include <linux/jiffies.h> #include <asm/div64.h> #include <media/videobuf2-vmalloc.h> #include <media/v4l2-dv-timings.h> #include <media/v4l2-ioctl.h> #include <media/v4l2-fh.h> #include <media/v4l2-event.h> #include "vivid-core.h" #include "vivid-vid-common.h" #include "vivid-vid-cap.h" #include "vivid-vid-out.h" #include "vivid-radio-common.h" #include "vivid-radio-rx.h" #include "vivid-radio-tx.h" #include "vivid-sdr-cap.h" #include "vivid-vbi-cap.h" #include "vivid-vbi-out.h" #include "vivid-osd.h" #include "vivid-ctrls.h" #include "vivid-kthread-out.h" #include "vivid-meta-out.h" static void vivid_thread_vid_out_tick(struct vivid_dev *dev) { struct vivid_buffer *vid_out_buf = NULL; struct vivid_buffer *vbi_out_buf = NULL; struct vivid_buffer *meta_out_buf = NULL; dprintk(dev, 1, "Video Output Thread Tick\n"); /* Drop a certain percentage of buffers. */ if (dev->perc_dropped_buffers && get_random_u32_below(100) < dev->perc_dropped_buffers) return; spin_lock(&dev->slock); /* * Only dequeue buffer if there is at least one more pending. * This makes video loopback possible. */ if (!list_empty(&dev->vid_out_active) && !list_is_singular(&dev->vid_out_active)) { vid_out_buf = list_entry(dev->vid_out_active.next, struct vivid_buffer, list); list_del(&vid_out_buf->list); } if (!list_empty(&dev->vbi_out_active) && (dev->field_out != V4L2_FIELD_ALTERNATE || (dev->vbi_out_seq_count & 1))) { vbi_out_buf = list_entry(dev->vbi_out_active.next, struct vivid_buffer, list); list_del(&vbi_out_buf->list); } if (!list_empty(&dev->meta_out_active)) { meta_out_buf = list_entry(dev->meta_out_active.next, struct vivid_buffer, list); list_del(&meta_out_buf->list); } spin_unlock(&dev->slock); if (!vid_out_buf && !vbi_out_buf && !meta_out_buf) return; if (vid_out_buf) { v4l2_ctrl_request_setup(vid_out_buf->vb.vb2_buf.req_obj.req, &dev->ctrl_hdl_vid_out); v4l2_ctrl_request_complete(vid_out_buf->vb.vb2_buf.req_obj.req, &dev->ctrl_hdl_vid_out); vid_out_buf->vb.sequence = dev->vid_out_seq_count; if (dev->field_out == V4L2_FIELD_ALTERNATE) { /* * The sequence counter counts frames, not fields. * So divide by two. */ vid_out_buf->vb.sequence /= 2; } vid_out_buf->vb.vb2_buf.timestamp = ktime_get_ns() + dev->time_wrap_offset; vb2_buffer_done(&vid_out_buf->vb.vb2_buf, dev->dqbuf_error ? VB2_BUF_STATE_ERROR : VB2_BUF_STATE_DONE); dprintk(dev, 2, "vid_out buffer %d done\n", vid_out_buf->vb.vb2_buf.index); } if (vbi_out_buf) { v4l2_ctrl_request_setup(vbi_out_buf->vb.vb2_buf.req_obj.req, &dev->ctrl_hdl_vbi_out); v4l2_ctrl_request_complete(vbi_out_buf->vb.vb2_buf.req_obj.req, &dev->ctrl_hdl_vbi_out); if (dev->stream_sliced_vbi_out) vivid_sliced_vbi_out_process(dev, vbi_out_buf); vbi_out_buf->vb.sequence = dev->vbi_out_seq_count; vbi_out_buf->vb.vb2_buf.timestamp = ktime_get_ns() + dev->time_wrap_offset; vb2_buffer_done(&vbi_out_buf->vb.vb2_buf, dev->dqbuf_error ? VB2_BUF_STATE_ERROR : VB2_BUF_STATE_DONE); dprintk(dev, 2, "vbi_out buffer %d done\n", vbi_out_buf->vb.vb2_buf.index); } if (meta_out_buf) { v4l2_ctrl_request_setup(meta_out_buf->vb.vb2_buf.req_obj.req, &dev->ctrl_hdl_meta_out); v4l2_ctrl_request_complete(meta_out_buf->vb.vb2_buf.req_obj.req, &dev->ctrl_hdl_meta_out); vivid_meta_out_process(dev, meta_out_buf); meta_out_buf->vb.sequence = dev->meta_out_seq_count; meta_out_buf->vb.vb2_buf.timestamp = ktime_get_ns() + dev->time_wrap_offset; vb2_buffer_done(&meta_out_buf->vb.vb2_buf, dev->dqbuf_error ? VB2_BUF_STATE_ERROR : VB2_BUF_STATE_DONE); dprintk(dev, 2, "meta_out buffer %d done\n", meta_out_buf->vb.vb2_buf.index); } dev->dqbuf_error = false; } static int vivid_thread_vid_out(void *data) { struct vivid_dev *dev = data; u64 numerators_since_start; u64 buffers_since_start; u64 next_jiffies_since_start; unsigned long jiffies_since_start; unsigned long cur_jiffies; unsigned wait_jiffies; unsigned numerator; unsigned denominator; dprintk(dev, 1, "Video Output Thread Start\n"); set_freezable(); /* Resets frame counters */ dev->out_seq_offset = 0; dev->out_seq_count = 0; dev->jiffies_vid_out = jiffies; dev->out_seq_resync = false; if (dev->time_wrap) dev->time_wrap_offset = dev->time_wrap - ktime_get_ns(); else dev->time_wrap_offset = 0; for (;;) { try_to_freeze(); if (kthread_should_stop()) break; if (!mutex_trylock(&dev->mutex)) { schedule(); continue; } cur_jiffies = jiffies; if (dev->out_seq_resync) { dev->jiffies_vid_out = cur_jiffies; dev->out_seq_offset = dev->out_seq_count + 1; dev->out_seq_count = 0; dev->out_seq_resync = false; } numerator = dev->timeperframe_vid_out.numerator; denominator = dev->timeperframe_vid_out.denominator; if (dev->field_out == V4L2_FIELD_ALTERNATE) denominator *= 2; /* Calculate the number of jiffies since we started streaming */ jiffies_since_start = cur_jiffies - dev->jiffies_vid_out; /* Get the number of buffers streamed since the start */ buffers_since_start = (u64)jiffies_since_start * denominator + (HZ * numerator) / 2; do_div(buffers_since_start, HZ * numerator); /* * After more than 0xf0000000 (rounded down to a multiple of * 'jiffies-per-day' to ease jiffies_to_msecs calculation) * jiffies have passed since we started streaming reset the * counters and keep track of the sequence offset. */ if (jiffies_since_start > JIFFIES_RESYNC) { dev->jiffies_vid_out = cur_jiffies; dev->out_seq_offset = buffers_since_start; buffers_since_start = 0; } dev->out_seq_count = buffers_since_start + dev->out_seq_offset; dev->vid_out_seq_count = dev->out_seq_count - dev->vid_out_seq_start; dev->vbi_out_seq_count = dev->out_seq_count - dev->vbi_out_seq_start; dev->meta_out_seq_count = dev->out_seq_count - dev->meta_out_seq_start; vivid_thread_vid_out_tick(dev); mutex_unlock(&dev->mutex); /* * Calculate the number of 'numerators' streamed since we started, * not including the current buffer. */ numerators_since_start = buffers_since_start * numerator; /* And the number of jiffies since we started */ jiffies_since_start = jiffies - dev->jiffies_vid_out; /* Increase by the 'numerator' of one buffer */ numerators_since_start += numerator; /* * Calculate when that next buffer is supposed to start * in jiffies since we started streaming. */ next_jiffies_since_start = numerators_since_start * HZ + denominator / 2; do_div(next_jiffies_since_start, denominator); /* If it is in the past, then just schedule asap */ if (next_jiffies_since_start < jiffies_since_start) next_jiffies_since_start = jiffies_since_start; wait_jiffies = next_jiffies_since_start - jiffies_since_start; while (time_is_after_jiffies(cur_jiffies + wait_jiffies) && !kthread_should_stop()) schedule(); } dprintk(dev, 1, "Video Output Thread End\n"); return 0; } static void vivid_grab_controls(struct vivid_dev *dev, bool grab) { v4l2_ctrl_grab(dev->ctrl_has_crop_out, grab); v4l2_ctrl_grab(dev->ctrl_has_compose_out, grab); v4l2_ctrl_grab(dev->ctrl_has_scaler_out, grab); v4l2_ctrl_grab(dev->ctrl_tx_mode, grab); v4l2_ctrl_grab(dev->ctrl_tx_rgb_range, grab); } int vivid_start_generating_vid_out(struct vivid_dev *dev, bool *pstreaming) { dprintk(dev, 1, "%s\n", __func__); if (dev->kthread_vid_out) { u32 seq_count = dev->out_seq_count + dev->seq_wrap * 128; if (pstreaming == &dev->vid_out_streaming) dev->vid_out_seq_start = seq_count; else if (pstreaming == &dev->vbi_out_streaming) dev->vbi_out_seq_start = seq_count; else dev->meta_out_seq_start = seq_count; *pstreaming = true; return 0; } /* Resets frame counters */ dev->jiffies_vid_out = jiffies; dev->vid_out_seq_start = dev->seq_wrap * 128; dev->vbi_out_seq_start = dev->seq_wrap * 128; dev->meta_out_seq_start = dev->seq_wrap * 128; dev->kthread_vid_out = kthread_run(vivid_thread_vid_out, dev, "%s-vid-out", dev->v4l2_dev.name); if (IS_ERR(dev->kthread_vid_out)) { int err = PTR_ERR(dev->kthread_vid_out); dev->kthread_vid_out = NULL; v4l2_err(&dev->v4l2_dev, "kernel_thread() failed\n"); return err; } *pstreaming = true; vivid_grab_controls(dev, true); dprintk(dev, 1, "returning from %s\n", __func__); return 0; } void vivid_stop_generating_vid_out(struct vivid_dev *dev, bool *pstreaming) { dprintk(dev, 1, "%s\n", __func__); if (dev->kthread_vid_out == NULL) return; *pstreaming = false; if (pstreaming == &dev->vid_out_streaming) { /* Release all active buffers */ while (!list_empty(&dev->vid_out_active)) { struct vivid_buffer *buf; buf = list_entry(dev->vid_out_active.next, struct vivid_buffer, list); list_del(&buf->list); v4l2_ctrl_request_complete(buf->vb.vb2_buf.req_obj.req, &dev->ctrl_hdl_vid_out); vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR); dprintk(dev, 2, "vid_out buffer %d done\n", buf->vb.vb2_buf.index); } } if (pstreaming == &dev->vbi_out_streaming) { while (!list_empty(&dev->vbi_out_active)) { struct vivid_buffer *buf; buf = list_entry(dev->vbi_out_active.next, struct vivid_buffer, list); list_del(&buf->list); v4l2_ctrl_request_complete(buf->vb.vb2_buf.req_obj.req, &dev->ctrl_hdl_vbi_out); vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR); dprintk(dev, 2, "vbi_out buffer %d done\n", buf->vb.vb2_buf.index); } } if (pstreaming == &dev->meta_out_streaming) { while (!list_empty(&dev->meta_out_active)) { struct vivid_buffer *buf; buf = list_entry(dev->meta_out_active.next, struct vivid_buffer, list); list_del(&buf->list); v4l2_ctrl_request_complete(buf->vb.vb2_buf.req_obj.req, &dev->ctrl_hdl_meta_out); vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR); dprintk(dev, 2, "meta_out buffer %d done\n", buf->vb.vb2_buf.index); } } if (dev->vid_out_streaming || dev->vbi_out_streaming || dev->meta_out_streaming) return; /* shutdown control thread */ vivid_grab_controls(dev, false); kthread_stop(dev->kthread_vid_out); dev->kthread_vid_out = NULL; }
linux-master
drivers/media/test-drivers/vivid/vivid-kthread-out.c
// SPDX-License-Identifier: GPL-2.0-only /* * vivid-cec.c - A Virtual Video Test Driver, cec emulation * * Copyright 2016 Cisco Systems, Inc. and/or its affiliates. All rights reserved. */ #include <linux/delay.h> #include <media/cec.h> #include "vivid-core.h" #include "vivid-cec.h" #define CEC_START_BIT_US 4500 #define CEC_DATA_BIT_US 2400 #define CEC_MARGIN_US 350 struct xfer_on_bus { struct cec_adapter *adap; u8 status; }; static bool find_dest_adap(struct vivid_dev *dev, struct cec_adapter *adap, u8 dest) { unsigned int i; if (dest >= 0xf) return false; if (adap != dev->cec_rx_adap && dev->cec_rx_adap && dev->cec_rx_adap->is_configured && cec_has_log_addr(dev->cec_rx_adap, dest)) return true; for (i = 0; i < MAX_OUTPUTS && dev->cec_tx_adap[i]; i++) { if (adap == dev->cec_tx_adap[i]) continue; if (!dev->cec_tx_adap[i]->is_configured) continue; if (cec_has_log_addr(dev->cec_tx_adap[i], dest)) return true; } return false; } static bool xfer_ready(struct vivid_dev *dev) { unsigned int i; bool ready = false; spin_lock(&dev->cec_xfers_slock); for (i = 0; i < ARRAY_SIZE(dev->xfers); i++) { if (dev->xfers[i].sft && dev->xfers[i].sft <= dev->cec_sft) { ready = true; break; } } spin_unlock(&dev->cec_xfers_slock); return ready; } /* * If an adapter tries to send successive messages, it must wait for the * longest signal-free time between its transmissions. But, if another * adapter sends a message in the interim, then the wait can be reduced * because the messages are no longer successive. Make these adjustments * if necessary. Should be called holding cec_xfers_slock. */ static void adjust_sfts(struct vivid_dev *dev) { unsigned int i; u8 initiator; for (i = 0; i < ARRAY_SIZE(dev->xfers); i++) { if (dev->xfers[i].sft <= CEC_SIGNAL_FREE_TIME_RETRY) continue; initiator = dev->xfers[i].msg[0] >> 4; if (initiator == dev->last_initiator) dev->xfers[i].sft = CEC_SIGNAL_FREE_TIME_NEXT_XFER; else dev->xfers[i].sft = CEC_SIGNAL_FREE_TIME_NEW_INITIATOR; } } /* * The main emulation of the bus on which CEC adapters attempt to send * messages to each other. The bus keeps track of how long it has been * signal-free and accepts a pending transmission only if the state of * the bus matches the transmission's signal-free requirements. It calls * cec_transmit_attempt_done() for all transmits that enter the bus and * cec_received_msg() for successful transmits. */ int vivid_cec_bus_thread(void *_dev) { u32 last_sft; unsigned int i; unsigned int dest; ktime_t start, end; s64 delta_us, retry_us; struct vivid_dev *dev = _dev; dev->cec_sft = CEC_SIGNAL_FREE_TIME_NEXT_XFER; for (;;) { bool first = true; int wait_xfer_us = 0; bool valid_dest = false; int wait_arb_lost_us = 0; unsigned int first_idx = 0; unsigned int first_status = 0; struct cec_msg first_msg = {}; struct xfer_on_bus xfers_on_bus[MAX_OUTPUTS] = {}; wait_event_interruptible(dev->kthread_waitq_cec, xfer_ready(dev) || kthread_should_stop()); if (kthread_should_stop()) break; last_sft = dev->cec_sft; dev->cec_sft = 0; /* * Move the messages that are ready onto the bus. The adapter with * the most leading zeros will win control of the bus and any other * adapters will lose arbitration. */ spin_lock(&dev->cec_xfers_slock); for (i = 0; i < ARRAY_SIZE(dev->xfers); i++) { if (!dev->xfers[i].sft || dev->xfers[i].sft > last_sft) continue; if (first) { first = false; first_idx = i; xfers_on_bus[first_idx].adap = dev->xfers[i].adap; memcpy(first_msg.msg, dev->xfers[i].msg, dev->xfers[i].len); first_msg.len = dev->xfers[i].len; } else { xfers_on_bus[i].adap = dev->xfers[i].adap; xfers_on_bus[i].status = CEC_TX_STATUS_ARB_LOST; /* * For simplicity wait for all 4 bits of the initiator's * address even though HDMI specification uses bit-level * precision. */ wait_arb_lost_us = 4 * CEC_DATA_BIT_US + CEC_START_BIT_US; } dev->xfers[i].sft = 0; } dev->last_initiator = cec_msg_initiator(&first_msg); adjust_sfts(dev); spin_unlock(&dev->cec_xfers_slock); dest = cec_msg_destination(&first_msg); valid_dest = cec_msg_is_broadcast(&first_msg); if (!valid_dest) valid_dest = find_dest_adap(dev, xfers_on_bus[first_idx].adap, dest); if (valid_dest) { first_status = CEC_TX_STATUS_OK; /* * Message length is in bytes, but each byte is transmitted in * a block of 10 bits. */ wait_xfer_us = first_msg.len * 10 * CEC_DATA_BIT_US; } else { first_status = CEC_TX_STATUS_NACK; /* * A message that is not acknowledged stops transmitting after * the header block of 10 bits. */ wait_xfer_us = 10 * CEC_DATA_BIT_US; } wait_xfer_us += CEC_START_BIT_US; xfers_on_bus[first_idx].status = first_status; /* Sleep as if sending messages on a real hardware bus. */ start = ktime_get(); if (wait_arb_lost_us) { usleep_range(wait_arb_lost_us - CEC_MARGIN_US, wait_arb_lost_us); for (i = 0; i < ARRAY_SIZE(xfers_on_bus); i++) { if (xfers_on_bus[i].status != CEC_TX_STATUS_ARB_LOST) continue; cec_transmit_attempt_done(xfers_on_bus[i].adap, CEC_TX_STATUS_ARB_LOST); } if (kthread_should_stop()) break; } wait_xfer_us -= wait_arb_lost_us; usleep_range(wait_xfer_us - CEC_MARGIN_US, wait_xfer_us); cec_transmit_attempt_done(xfers_on_bus[first_idx].adap, first_status); if (kthread_should_stop()) break; if (first_status == CEC_TX_STATUS_OK) { if (xfers_on_bus[first_idx].adap != dev->cec_rx_adap) cec_received_msg(dev->cec_rx_adap, &first_msg); for (i = 0; i < MAX_OUTPUTS && dev->cec_tx_adap[i]; i++) if (xfers_on_bus[first_idx].adap != dev->cec_tx_adap[i]) cec_received_msg(dev->cec_tx_adap[i], &first_msg); } end = ktime_get(); /* * If the emulated transfer took more or less time than it should * have, then compensate by adjusting the wait time needed for the * bus to be signal-free for 3 bit periods (the retry time). */ delta_us = div_s64(end - start, 1000); delta_us -= wait_xfer_us + wait_arb_lost_us; retry_us = CEC_SIGNAL_FREE_TIME_RETRY * CEC_DATA_BIT_US - delta_us; if (retry_us > CEC_MARGIN_US) usleep_range(retry_us - CEC_MARGIN_US, retry_us); dev->cec_sft = CEC_SIGNAL_FREE_TIME_RETRY; /* * If there are no messages that need to be retried, check if any * adapters that did not just transmit a message are ready to * transmit. If none of these adapters are ready, then increase * the signal-free time so that the bus is available to all * adapters and go back to waiting for a transmission. */ while (dev->cec_sft >= CEC_SIGNAL_FREE_TIME_RETRY && dev->cec_sft < CEC_SIGNAL_FREE_TIME_NEXT_XFER && !xfer_ready(dev) && !kthread_should_stop()) { usleep_range(2 * CEC_DATA_BIT_US - CEC_MARGIN_US, 2 * CEC_DATA_BIT_US); dev->cec_sft += 2; } } return 0; } static int vivid_cec_adap_enable(struct cec_adapter *adap, bool enable) { adap->cec_pin_is_high = true; return 0; } static int vivid_cec_adap_log_addr(struct cec_adapter *adap, u8 log_addr) { return 0; } static int vivid_cec_adap_transmit(struct cec_adapter *adap, u8 attempts, u32 signal_free_time, struct cec_msg *msg) { struct vivid_dev *dev = cec_get_drvdata(adap); u8 idx = cec_msg_initiator(msg); spin_lock(&dev->cec_xfers_slock); dev->xfers[idx].adap = adap; memcpy(dev->xfers[idx].msg, msg->msg, CEC_MAX_MSG_SIZE); dev->xfers[idx].len = msg->len; dev->xfers[idx].sft = CEC_SIGNAL_FREE_TIME_RETRY; if (signal_free_time > CEC_SIGNAL_FREE_TIME_RETRY) { if (idx == dev->last_initiator) dev->xfers[idx].sft = CEC_SIGNAL_FREE_TIME_NEXT_XFER; else dev->xfers[idx].sft = CEC_SIGNAL_FREE_TIME_NEW_INITIATOR; } spin_unlock(&dev->cec_xfers_slock); wake_up_interruptible(&dev->kthread_waitq_cec); return 0; } static int vivid_received(struct cec_adapter *adap, struct cec_msg *msg) { struct vivid_dev *dev = cec_get_drvdata(adap); struct cec_msg reply; u8 dest = cec_msg_destination(msg); u8 disp_ctl; char osd[14]; if (cec_msg_is_broadcast(msg)) dest = adap->log_addrs.log_addr[0]; cec_msg_init(&reply, dest, cec_msg_initiator(msg)); switch (cec_msg_opcode(msg)) { case CEC_MSG_SET_OSD_STRING: if (!cec_is_sink(adap)) return -ENOMSG; cec_ops_set_osd_string(msg, &disp_ctl, osd); switch (disp_ctl) { case CEC_OP_DISP_CTL_DEFAULT: strscpy(dev->osd, osd, sizeof(dev->osd)); dev->osd_jiffies = jiffies; break; case CEC_OP_DISP_CTL_UNTIL_CLEARED: strscpy(dev->osd, osd, sizeof(dev->osd)); dev->osd_jiffies = 0; break; case CEC_OP_DISP_CTL_CLEAR: dev->osd[0] = 0; dev->osd_jiffies = 0; break; default: cec_msg_feature_abort(&reply, cec_msg_opcode(msg), CEC_OP_ABORT_INVALID_OP); cec_transmit_msg(adap, &reply, false); break; } break; default: return -ENOMSG; } return 0; } static const struct cec_adap_ops vivid_cec_adap_ops = { .adap_enable = vivid_cec_adap_enable, .adap_log_addr = vivid_cec_adap_log_addr, .adap_transmit = vivid_cec_adap_transmit, .received = vivid_received, }; struct cec_adapter *vivid_cec_alloc_adap(struct vivid_dev *dev, unsigned int idx, bool is_source) { u32 caps = CEC_CAP_DEFAULTS | CEC_CAP_MONITOR_ALL | CEC_CAP_MONITOR_PIN; char name[32]; snprintf(name, sizeof(name), "vivid-%03d-vid-%s%d", dev->inst, is_source ? "out" : "cap", idx); return cec_allocate_adapter(&vivid_cec_adap_ops, dev, name, caps, CEC_MAX_LOG_ADDRS); }
linux-master
drivers/media/test-drivers/vivid/vivid-cec.c
// SPDX-License-Identifier: GPL-2.0-only /* * vivid-vid-cap.c - video capture support functions. * * Copyright 2014 Cisco Systems, Inc. and/or its affiliates. All rights reserved. */ #include <linux/errno.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/vmalloc.h> #include <linux/videodev2.h> #include <linux/v4l2-dv-timings.h> #include <media/v4l2-common.h> #include <media/v4l2-event.h> #include <media/v4l2-dv-timings.h> #include <media/v4l2-rect.h> #include "vivid-core.h" #include "vivid-vid-common.h" #include "vivid-kthread-cap.h" #include "vivid-vid-cap.h" /* Sizes must be in increasing order */ static const struct v4l2_frmsize_discrete webcam_sizes[] = { { 320, 180 }, { 640, 360 }, { 640, 480 }, { 1280, 720 }, { 1920, 1080 }, { 3840, 2160 }, }; /* * Intervals must be in increasing order and there must be twice as many * elements in this array as there are in webcam_sizes. */ static const struct v4l2_fract webcam_intervals[] = { { 1, 1 }, { 1, 2 }, { 1, 4 }, { 1, 5 }, { 1, 10 }, { 2, 25 }, { 1, 15 }, /* 7 - maximum for 2160p */ { 1, 25 }, { 1, 30 }, /* 9 - maximum for 1080p */ { 1, 40 }, { 1, 50 }, { 1, 60 }, /* 12 - maximum for 720p */ { 1, 120 }, }; /* Limit maximum FPS rates for high resolutions */ #define IVAL_COUNT_720P 12 /* 720p and up is limited to 60 fps */ #define IVAL_COUNT_1080P 9 /* 1080p and up is limited to 30 fps */ #define IVAL_COUNT_2160P 7 /* 2160p and up is limited to 15 fps */ static inline unsigned int webcam_ival_count(const struct vivid_dev *dev, unsigned int frmsize_idx) { if (webcam_sizes[frmsize_idx].height >= 2160) return IVAL_COUNT_2160P; if (webcam_sizes[frmsize_idx].height >= 1080) return IVAL_COUNT_1080P; if (webcam_sizes[frmsize_idx].height >= 720) return IVAL_COUNT_720P; /* For low resolutions, allow all FPS rates */ return ARRAY_SIZE(webcam_intervals); } static int vid_cap_queue_setup(struct vb2_queue *vq, unsigned *nbuffers, unsigned *nplanes, unsigned sizes[], struct device *alloc_devs[]) { struct vivid_dev *dev = vb2_get_drv_priv(vq); unsigned buffers = tpg_g_buffers(&dev->tpg); unsigned h = dev->fmt_cap_rect.height; unsigned p; if (dev->field_cap == V4L2_FIELD_ALTERNATE) { /* * You cannot use read() with FIELD_ALTERNATE since the field * information (TOP/BOTTOM) cannot be passed back to the user. */ if (vb2_fileio_is_active(vq)) return -EINVAL; } if (dev->queue_setup_error) { /* * Error injection: test what happens if queue_setup() returns * an error. */ dev->queue_setup_error = false; return -EINVAL; } if (*nplanes) { /* * Check if the number of requested planes match * the number of buffers in the current format. You can't mix that. */ if (*nplanes != buffers) return -EINVAL; for (p = 0; p < buffers; p++) { if (sizes[p] < tpg_g_line_width(&dev->tpg, p) * h + dev->fmt_cap->data_offset[p]) return -EINVAL; } } else { for (p = 0; p < buffers; p++) sizes[p] = (tpg_g_line_width(&dev->tpg, p) * h) / dev->fmt_cap->vdownsampling[p] + dev->fmt_cap->data_offset[p]; } if (vq->num_buffers + *nbuffers < 2) *nbuffers = 2 - vq->num_buffers; *nplanes = buffers; dprintk(dev, 1, "%s: count=%d\n", __func__, *nbuffers); for (p = 0; p < buffers; p++) dprintk(dev, 1, "%s: size[%u]=%u\n", __func__, p, sizes[p]); return 0; } static int vid_cap_buf_prepare(struct vb2_buffer *vb) { struct vivid_dev *dev = vb2_get_drv_priv(vb->vb2_queue); unsigned long size; unsigned buffers = tpg_g_buffers(&dev->tpg); unsigned p; dprintk(dev, 1, "%s\n", __func__); if (WARN_ON(NULL == dev->fmt_cap)) return -EINVAL; if (dev->buf_prepare_error) { /* * Error injection: test what happens if buf_prepare() returns * an error. */ dev->buf_prepare_error = false; return -EINVAL; } for (p = 0; p < buffers; p++) { size = (tpg_g_line_width(&dev->tpg, p) * dev->fmt_cap_rect.height) / dev->fmt_cap->vdownsampling[p] + dev->fmt_cap->data_offset[p]; if (vb2_plane_size(vb, p) < size) { dprintk(dev, 1, "%s data will not fit into plane %u (%lu < %lu)\n", __func__, p, vb2_plane_size(vb, p), size); return -EINVAL; } vb2_set_plane_payload(vb, p, size); vb->planes[p].data_offset = dev->fmt_cap->data_offset[p]; } return 0; } static void vid_cap_buf_finish(struct vb2_buffer *vb) { struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb); struct vivid_dev *dev = vb2_get_drv_priv(vb->vb2_queue); struct v4l2_timecode *tc = &vbuf->timecode; unsigned fps = 25; unsigned seq = vbuf->sequence; if (!vivid_is_sdtv_cap(dev)) return; /* * Set the timecode. Rarely used, so it is interesting to * test this. */ vbuf->flags |= V4L2_BUF_FLAG_TIMECODE; if (dev->std_cap[dev->input] & V4L2_STD_525_60) fps = 30; tc->type = (fps == 30) ? V4L2_TC_TYPE_30FPS : V4L2_TC_TYPE_25FPS; tc->flags = 0; tc->frames = seq % fps; tc->seconds = (seq / fps) % 60; tc->minutes = (seq / (60 * fps)) % 60; tc->hours = (seq / (60 * 60 * fps)) % 24; } static void vid_cap_buf_queue(struct vb2_buffer *vb) { struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb); struct vivid_dev *dev = vb2_get_drv_priv(vb->vb2_queue); struct vivid_buffer *buf = container_of(vbuf, struct vivid_buffer, vb); dprintk(dev, 1, "%s\n", __func__); spin_lock(&dev->slock); list_add_tail(&buf->list, &dev->vid_cap_active); spin_unlock(&dev->slock); } static int vid_cap_start_streaming(struct vb2_queue *vq, unsigned count) { struct vivid_dev *dev = vb2_get_drv_priv(vq); unsigned i; int err; if (vb2_is_streaming(&dev->vb_vid_out_q)) dev->can_loop_video = vivid_vid_can_loop(dev); dev->vid_cap_seq_count = 0; dprintk(dev, 1, "%s\n", __func__); for (i = 0; i < VIDEO_MAX_FRAME; i++) dev->must_blank[i] = tpg_g_perc_fill(&dev->tpg) < 100; if (dev->start_streaming_error) { dev->start_streaming_error = false; err = -EINVAL; } else { err = vivid_start_generating_vid_cap(dev, &dev->vid_cap_streaming); } if (err) { struct vivid_buffer *buf, *tmp; list_for_each_entry_safe(buf, tmp, &dev->vid_cap_active, list) { list_del(&buf->list); vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_QUEUED); } } return err; } /* abort streaming and wait for last buffer */ static void vid_cap_stop_streaming(struct vb2_queue *vq) { struct vivid_dev *dev = vb2_get_drv_priv(vq); dprintk(dev, 1, "%s\n", __func__); vivid_stop_generating_vid_cap(dev, &dev->vid_cap_streaming); dev->can_loop_video = false; } static void vid_cap_buf_request_complete(struct vb2_buffer *vb) { struct vivid_dev *dev = vb2_get_drv_priv(vb->vb2_queue); v4l2_ctrl_request_complete(vb->req_obj.req, &dev->ctrl_hdl_vid_cap); } const struct vb2_ops vivid_vid_cap_qops = { .queue_setup = vid_cap_queue_setup, .buf_prepare = vid_cap_buf_prepare, .buf_finish = vid_cap_buf_finish, .buf_queue = vid_cap_buf_queue, .start_streaming = vid_cap_start_streaming, .stop_streaming = vid_cap_stop_streaming, .buf_request_complete = vid_cap_buf_request_complete, .wait_prepare = vb2_ops_wait_prepare, .wait_finish = vb2_ops_wait_finish, }; /* * Determine the 'picture' quality based on the current TV frequency: either * COLOR for a good 'signal', GRAY (grayscale picture) for a slightly off * signal or NOISE for no signal. */ void vivid_update_quality(struct vivid_dev *dev) { unsigned freq_modulus; if (dev->loop_video && (vivid_is_svid_cap(dev) || vivid_is_hdmi_cap(dev))) { /* * The 'noise' will only be replaced by the actual video * if the output video matches the input video settings. */ tpg_s_quality(&dev->tpg, TPG_QUAL_NOISE, 0); return; } if (vivid_is_hdmi_cap(dev) && VIVID_INVALID_SIGNAL(dev->dv_timings_signal_mode[dev->input])) { tpg_s_quality(&dev->tpg, TPG_QUAL_NOISE, 0); return; } if (vivid_is_sdtv_cap(dev) && VIVID_INVALID_SIGNAL(dev->std_signal_mode[dev->input])) { tpg_s_quality(&dev->tpg, TPG_QUAL_NOISE, 0); return; } if (!vivid_is_tv_cap(dev)) { tpg_s_quality(&dev->tpg, TPG_QUAL_COLOR, 0); return; } /* * There is a fake channel every 6 MHz at 49.25, 55.25, etc. * From +/- 0.25 MHz around the channel there is color, and from * +/- 1 MHz there is grayscale (chroma is lost). * Everywhere else it is just noise. */ freq_modulus = (dev->tv_freq - 676 /* (43.25-1) * 16 */) % (6 * 16); if (freq_modulus > 2 * 16) { tpg_s_quality(&dev->tpg, TPG_QUAL_NOISE, next_pseudo_random32(dev->tv_freq ^ 0x55) & 0x3f); return; } if (freq_modulus < 12 /*0.75 * 16*/ || freq_modulus > 20 /*1.25 * 16*/) tpg_s_quality(&dev->tpg, TPG_QUAL_GRAY, 0); else tpg_s_quality(&dev->tpg, TPG_QUAL_COLOR, 0); } /* * Get the current picture quality and the associated afc value. */ static enum tpg_quality vivid_get_quality(struct vivid_dev *dev, s32 *afc) { unsigned freq_modulus; if (afc) *afc = 0; if (tpg_g_quality(&dev->tpg) == TPG_QUAL_COLOR || tpg_g_quality(&dev->tpg) == TPG_QUAL_NOISE) return tpg_g_quality(&dev->tpg); /* * There is a fake channel every 6 MHz at 49.25, 55.25, etc. * From +/- 0.25 MHz around the channel there is color, and from * +/- 1 MHz there is grayscale (chroma is lost). * Everywhere else it is just gray. */ freq_modulus = (dev->tv_freq - 676 /* (43.25-1) * 16 */) % (6 * 16); if (afc) *afc = freq_modulus - 1 * 16; return TPG_QUAL_GRAY; } enum tpg_video_aspect vivid_get_video_aspect(const struct vivid_dev *dev) { if (vivid_is_sdtv_cap(dev)) return dev->std_aspect_ratio[dev->input]; if (vivid_is_hdmi_cap(dev)) return dev->dv_timings_aspect_ratio[dev->input]; return TPG_VIDEO_ASPECT_IMAGE; } static enum tpg_pixel_aspect vivid_get_pixel_aspect(const struct vivid_dev *dev) { if (vivid_is_sdtv_cap(dev)) return (dev->std_cap[dev->input] & V4L2_STD_525_60) ? TPG_PIXEL_ASPECT_NTSC : TPG_PIXEL_ASPECT_PAL; if (vivid_is_hdmi_cap(dev) && dev->src_rect.width == 720 && dev->src_rect.height <= 576) return dev->src_rect.height == 480 ? TPG_PIXEL_ASPECT_NTSC : TPG_PIXEL_ASPECT_PAL; return TPG_PIXEL_ASPECT_SQUARE; } /* * Called whenever the format has to be reset which can occur when * changing inputs, standard, timings, etc. */ void vivid_update_format_cap(struct vivid_dev *dev, bool keep_controls) { struct v4l2_bt_timings *bt = &dev->dv_timings_cap[dev->input].bt; u32 dims[V4L2_CTRL_MAX_DIMS] = {}; unsigned size; u64 pixelclock; switch (dev->input_type[dev->input]) { case WEBCAM: default: dev->src_rect.width = webcam_sizes[dev->webcam_size_idx].width; dev->src_rect.height = webcam_sizes[dev->webcam_size_idx].height; dev->timeperframe_vid_cap = webcam_intervals[dev->webcam_ival_idx]; dev->field_cap = V4L2_FIELD_NONE; tpg_s_rgb_range(&dev->tpg, V4L2_DV_RGB_RANGE_AUTO); break; case TV: case SVID: dev->field_cap = dev->tv_field_cap; dev->src_rect.width = 720; if (dev->std_cap[dev->input] & V4L2_STD_525_60) { dev->src_rect.height = 480; dev->timeperframe_vid_cap = (struct v4l2_fract) { 1001, 30000 }; dev->service_set_cap = V4L2_SLICED_CAPTION_525; } else { dev->src_rect.height = 576; dev->timeperframe_vid_cap = (struct v4l2_fract) { 1000, 25000 }; dev->service_set_cap = V4L2_SLICED_WSS_625 | V4L2_SLICED_TELETEXT_B; } tpg_s_rgb_range(&dev->tpg, V4L2_DV_RGB_RANGE_AUTO); break; case HDMI: dev->src_rect.width = bt->width; dev->src_rect.height = bt->height; size = V4L2_DV_BT_FRAME_WIDTH(bt) * V4L2_DV_BT_FRAME_HEIGHT(bt); if (dev->reduced_fps && can_reduce_fps(bt)) { pixelclock = div_u64(bt->pixelclock * 1000, 1001); bt->flags |= V4L2_DV_FL_REDUCED_FPS; } else { pixelclock = bt->pixelclock; bt->flags &= ~V4L2_DV_FL_REDUCED_FPS; } dev->timeperframe_vid_cap = (struct v4l2_fract) { size / 100, (u32)pixelclock / 100 }; if (bt->interlaced) dev->field_cap = V4L2_FIELD_ALTERNATE; else dev->field_cap = V4L2_FIELD_NONE; /* * We can be called from within s_ctrl, in that case we can't * set/get controls. Luckily we don't need to in that case. */ if (keep_controls || !dev->colorspace) break; if (bt->flags & V4L2_DV_FL_IS_CE_VIDEO) { if (bt->width == 720 && bt->height <= 576) v4l2_ctrl_s_ctrl(dev->colorspace, VIVID_CS_170M); else v4l2_ctrl_s_ctrl(dev->colorspace, VIVID_CS_709); v4l2_ctrl_s_ctrl(dev->real_rgb_range_cap, 1); } else { v4l2_ctrl_s_ctrl(dev->colorspace, VIVID_CS_SRGB); v4l2_ctrl_s_ctrl(dev->real_rgb_range_cap, 0); } tpg_s_rgb_range(&dev->tpg, v4l2_ctrl_g_ctrl(dev->rgb_range_cap)); break; } vivid_update_quality(dev); tpg_reset_source(&dev->tpg, dev->src_rect.width, dev->src_rect.height, dev->field_cap); dev->crop_cap = dev->src_rect; dev->crop_bounds_cap = dev->src_rect; dev->compose_cap = dev->crop_cap; if (V4L2_FIELD_HAS_T_OR_B(dev->field_cap)) dev->compose_cap.height /= 2; dev->fmt_cap_rect = dev->compose_cap; tpg_s_video_aspect(&dev->tpg, vivid_get_video_aspect(dev)); tpg_s_pixel_aspect(&dev->tpg, vivid_get_pixel_aspect(dev)); tpg_update_mv_step(&dev->tpg); /* * We can be called from within s_ctrl, in that case we can't * modify controls. Luckily we don't need to in that case. */ if (keep_controls) return; dims[0] = roundup(dev->src_rect.width, PIXEL_ARRAY_DIV); dims[1] = roundup(dev->src_rect.height, PIXEL_ARRAY_DIV); v4l2_ctrl_modify_dimensions(dev->pixel_array, dims); } /* Map the field to something that is valid for the current input */ static enum v4l2_field vivid_field_cap(struct vivid_dev *dev, enum v4l2_field field) { if (vivid_is_sdtv_cap(dev)) { switch (field) { case V4L2_FIELD_INTERLACED_TB: case V4L2_FIELD_INTERLACED_BT: case V4L2_FIELD_SEQ_TB: case V4L2_FIELD_SEQ_BT: case V4L2_FIELD_TOP: case V4L2_FIELD_BOTTOM: case V4L2_FIELD_ALTERNATE: return field; case V4L2_FIELD_INTERLACED: default: return V4L2_FIELD_INTERLACED; } } if (vivid_is_hdmi_cap(dev)) return dev->dv_timings_cap[dev->input].bt.interlaced ? V4L2_FIELD_ALTERNATE : V4L2_FIELD_NONE; return V4L2_FIELD_NONE; } static unsigned vivid_colorspace_cap(struct vivid_dev *dev) { if (!dev->loop_video || vivid_is_webcam(dev) || vivid_is_tv_cap(dev)) return tpg_g_colorspace(&dev->tpg); return dev->colorspace_out; } static unsigned vivid_xfer_func_cap(struct vivid_dev *dev) { if (!dev->loop_video || vivid_is_webcam(dev) || vivid_is_tv_cap(dev)) return tpg_g_xfer_func(&dev->tpg); return dev->xfer_func_out; } static unsigned vivid_ycbcr_enc_cap(struct vivid_dev *dev) { if (!dev->loop_video || vivid_is_webcam(dev) || vivid_is_tv_cap(dev)) return tpg_g_ycbcr_enc(&dev->tpg); return dev->ycbcr_enc_out; } static unsigned int vivid_hsv_enc_cap(struct vivid_dev *dev) { if (!dev->loop_video || vivid_is_webcam(dev) || vivid_is_tv_cap(dev)) return tpg_g_hsv_enc(&dev->tpg); return dev->hsv_enc_out; } static unsigned vivid_quantization_cap(struct vivid_dev *dev) { if (!dev->loop_video || vivid_is_webcam(dev) || vivid_is_tv_cap(dev)) return tpg_g_quantization(&dev->tpg); return dev->quantization_out; } int vivid_g_fmt_vid_cap(struct file *file, void *priv, struct v4l2_format *f) { struct vivid_dev *dev = video_drvdata(file); struct v4l2_pix_format_mplane *mp = &f->fmt.pix_mp; unsigned p; mp->width = dev->fmt_cap_rect.width; mp->height = dev->fmt_cap_rect.height; mp->field = dev->field_cap; mp->pixelformat = dev->fmt_cap->fourcc; mp->colorspace = vivid_colorspace_cap(dev); mp->xfer_func = vivid_xfer_func_cap(dev); if (dev->fmt_cap->color_enc == TGP_COLOR_ENC_HSV) mp->hsv_enc = vivid_hsv_enc_cap(dev); else mp->ycbcr_enc = vivid_ycbcr_enc_cap(dev); mp->quantization = vivid_quantization_cap(dev); mp->num_planes = dev->fmt_cap->buffers; for (p = 0; p < mp->num_planes; p++) { mp->plane_fmt[p].bytesperline = tpg_g_bytesperline(&dev->tpg, p); mp->plane_fmt[p].sizeimage = (tpg_g_line_width(&dev->tpg, p) * mp->height) / dev->fmt_cap->vdownsampling[p] + dev->fmt_cap->data_offset[p]; } return 0; } int vivid_try_fmt_vid_cap(struct file *file, void *priv, struct v4l2_format *f) { struct v4l2_pix_format_mplane *mp = &f->fmt.pix_mp; struct v4l2_plane_pix_format *pfmt = mp->plane_fmt; struct vivid_dev *dev = video_drvdata(file); const struct vivid_fmt *fmt; unsigned bytesperline, max_bpl; unsigned factor = 1; unsigned w, h; unsigned p; bool user_set_csc = !!(mp->flags & V4L2_PIX_FMT_FLAG_SET_CSC); fmt = vivid_get_format(dev, mp->pixelformat); if (!fmt) { dprintk(dev, 1, "Fourcc format (0x%08x) unknown.\n", mp->pixelformat); mp->pixelformat = V4L2_PIX_FMT_YUYV; fmt = vivid_get_format(dev, mp->pixelformat); } mp->field = vivid_field_cap(dev, mp->field); if (vivid_is_webcam(dev)) { const struct v4l2_frmsize_discrete *sz = v4l2_find_nearest_size(webcam_sizes, ARRAY_SIZE(webcam_sizes), width, height, mp->width, mp->height); w = sz->width; h = sz->height; } else if (vivid_is_sdtv_cap(dev)) { w = 720; h = (dev->std_cap[dev->input] & V4L2_STD_525_60) ? 480 : 576; } else { w = dev->src_rect.width; h = dev->src_rect.height; } if (V4L2_FIELD_HAS_T_OR_B(mp->field)) factor = 2; if (vivid_is_webcam(dev) || (!dev->has_scaler_cap && !dev->has_crop_cap && !dev->has_compose_cap)) { mp->width = w; mp->height = h / factor; } else { struct v4l2_rect r = { 0, 0, mp->width, mp->height * factor }; v4l2_rect_set_min_size(&r, &vivid_min_rect); v4l2_rect_set_max_size(&r, &vivid_max_rect); if (dev->has_scaler_cap && !dev->has_compose_cap) { struct v4l2_rect max_r = { 0, 0, MAX_ZOOM * w, MAX_ZOOM * h }; v4l2_rect_set_max_size(&r, &max_r); } else if (!dev->has_scaler_cap && dev->has_crop_cap && !dev->has_compose_cap) { v4l2_rect_set_max_size(&r, &dev->src_rect); } else if (!dev->has_scaler_cap && !dev->has_crop_cap) { v4l2_rect_set_min_size(&r, &dev->src_rect); } mp->width = r.width; mp->height = r.height / factor; } /* This driver supports custom bytesperline values */ mp->num_planes = fmt->buffers; for (p = 0; p < fmt->buffers; p++) { /* Calculate the minimum supported bytesperline value */ bytesperline = (mp->width * fmt->bit_depth[p]) >> 3; /* Calculate the maximum supported bytesperline value */ max_bpl = (MAX_ZOOM * MAX_WIDTH * fmt->bit_depth[p]) >> 3; if (pfmt[p].bytesperline > max_bpl) pfmt[p].bytesperline = max_bpl; if (pfmt[p].bytesperline < bytesperline) pfmt[p].bytesperline = bytesperline; pfmt[p].sizeimage = (pfmt[p].bytesperline * mp->height) / fmt->vdownsampling[p] + fmt->data_offset[p]; memset(pfmt[p].reserved, 0, sizeof(pfmt[p].reserved)); } for (p = fmt->buffers; p < fmt->planes; p++) pfmt[0].sizeimage += (pfmt[0].bytesperline * mp->height * (fmt->bit_depth[p] / fmt->vdownsampling[p])) / (fmt->bit_depth[0] / fmt->vdownsampling[0]); if (!user_set_csc || !v4l2_is_colorspace_valid(mp->colorspace)) mp->colorspace = vivid_colorspace_cap(dev); if (!user_set_csc || !v4l2_is_xfer_func_valid(mp->xfer_func)) mp->xfer_func = vivid_xfer_func_cap(dev); if (fmt->color_enc == TGP_COLOR_ENC_HSV) { if (!user_set_csc || !v4l2_is_hsv_enc_valid(mp->hsv_enc)) mp->hsv_enc = vivid_hsv_enc_cap(dev); } else if (fmt->color_enc == TGP_COLOR_ENC_YCBCR) { if (!user_set_csc || !v4l2_is_ycbcr_enc_valid(mp->ycbcr_enc)) mp->ycbcr_enc = vivid_ycbcr_enc_cap(dev); } else { mp->ycbcr_enc = vivid_ycbcr_enc_cap(dev); } if (fmt->color_enc == TGP_COLOR_ENC_YCBCR || fmt->color_enc == TGP_COLOR_ENC_RGB) { if (!user_set_csc || !v4l2_is_quant_valid(mp->quantization)) mp->quantization = vivid_quantization_cap(dev); } else { mp->quantization = vivid_quantization_cap(dev); } memset(mp->reserved, 0, sizeof(mp->reserved)); return 0; } int vivid_s_fmt_vid_cap(struct file *file, void *priv, struct v4l2_format *f) { struct v4l2_pix_format_mplane *mp = &f->fmt.pix_mp; struct vivid_dev *dev = video_drvdata(file); struct v4l2_rect *crop = &dev->crop_cap; struct v4l2_rect *compose = &dev->compose_cap; struct vb2_queue *q = &dev->vb_vid_cap_q; int ret = vivid_try_fmt_vid_cap(file, priv, f); unsigned factor = 1; unsigned p; unsigned i; if (ret < 0) return ret; if (vb2_is_busy(q)) { dprintk(dev, 1, "%s device busy\n", __func__); return -EBUSY; } dev->fmt_cap = vivid_get_format(dev, mp->pixelformat); if (V4L2_FIELD_HAS_T_OR_B(mp->field)) factor = 2; /* Note: the webcam input doesn't support scaling, cropping or composing */ if (!vivid_is_webcam(dev) && (dev->has_scaler_cap || dev->has_crop_cap || dev->has_compose_cap)) { struct v4l2_rect r = { 0, 0, mp->width, mp->height }; if (dev->has_scaler_cap) { if (dev->has_compose_cap) v4l2_rect_map_inside(compose, &r); else *compose = r; if (dev->has_crop_cap && !dev->has_compose_cap) { struct v4l2_rect min_r = { 0, 0, r.width / MAX_ZOOM, factor * r.height / MAX_ZOOM }; struct v4l2_rect max_r = { 0, 0, r.width * MAX_ZOOM, factor * r.height * MAX_ZOOM }; v4l2_rect_set_min_size(crop, &min_r); v4l2_rect_set_max_size(crop, &max_r); v4l2_rect_map_inside(crop, &dev->crop_bounds_cap); } else if (dev->has_crop_cap) { struct v4l2_rect min_r = { 0, 0, compose->width / MAX_ZOOM, factor * compose->height / MAX_ZOOM }; struct v4l2_rect max_r = { 0, 0, compose->width * MAX_ZOOM, factor * compose->height * MAX_ZOOM }; v4l2_rect_set_min_size(crop, &min_r); v4l2_rect_set_max_size(crop, &max_r); v4l2_rect_map_inside(crop, &dev->crop_bounds_cap); } } else if (dev->has_crop_cap && !dev->has_compose_cap) { r.height *= factor; v4l2_rect_set_size_to(crop, &r); v4l2_rect_map_inside(crop, &dev->crop_bounds_cap); r = *crop; r.height /= factor; v4l2_rect_set_size_to(compose, &r); } else if (!dev->has_crop_cap) { v4l2_rect_map_inside(compose, &r); } else { r.height *= factor; v4l2_rect_set_max_size(crop, &r); v4l2_rect_map_inside(crop, &dev->crop_bounds_cap); compose->top *= factor; compose->height *= factor; v4l2_rect_set_size_to(compose, crop); v4l2_rect_map_inside(compose, &r); compose->top /= factor; compose->height /= factor; } } else if (vivid_is_webcam(dev)) { unsigned int ival_sz = webcam_ival_count(dev, dev->webcam_size_idx); /* Guaranteed to be a match */ for (i = 0; i < ARRAY_SIZE(webcam_sizes); i++) if (webcam_sizes[i].width == mp->width && webcam_sizes[i].height == mp->height) break; dev->webcam_size_idx = i; if (dev->webcam_ival_idx >= ival_sz) dev->webcam_ival_idx = ival_sz - 1; vivid_update_format_cap(dev, false); } else { struct v4l2_rect r = { 0, 0, mp->width, mp->height }; v4l2_rect_set_size_to(compose, &r); r.height *= factor; v4l2_rect_set_size_to(crop, &r); } dev->fmt_cap_rect.width = mp->width; dev->fmt_cap_rect.height = mp->height; tpg_s_buf_height(&dev->tpg, mp->height); tpg_s_fourcc(&dev->tpg, dev->fmt_cap->fourcc); for (p = 0; p < tpg_g_buffers(&dev->tpg); p++) tpg_s_bytesperline(&dev->tpg, p, mp->plane_fmt[p].bytesperline); dev->field_cap = mp->field; if (dev->field_cap == V4L2_FIELD_ALTERNATE) tpg_s_field(&dev->tpg, V4L2_FIELD_TOP, true); else tpg_s_field(&dev->tpg, dev->field_cap, false); tpg_s_crop_compose(&dev->tpg, &dev->crop_cap, &dev->compose_cap); if (vivid_is_sdtv_cap(dev)) dev->tv_field_cap = mp->field; tpg_update_mv_step(&dev->tpg); dev->tpg.colorspace = mp->colorspace; dev->tpg.xfer_func = mp->xfer_func; if (dev->fmt_cap->color_enc == TGP_COLOR_ENC_YCBCR) dev->tpg.ycbcr_enc = mp->ycbcr_enc; else dev->tpg.hsv_enc = mp->hsv_enc; dev->tpg.quantization = mp->quantization; return 0; } int vidioc_g_fmt_vid_cap_mplane(struct file *file, void *priv, struct v4l2_format *f) { struct vivid_dev *dev = video_drvdata(file); if (!dev->multiplanar) return -ENOTTY; return vivid_g_fmt_vid_cap(file, priv, f); } int vidioc_try_fmt_vid_cap_mplane(struct file *file, void *priv, struct v4l2_format *f) { struct vivid_dev *dev = video_drvdata(file); if (!dev->multiplanar) return -ENOTTY; return vivid_try_fmt_vid_cap(file, priv, f); } int vidioc_s_fmt_vid_cap_mplane(struct file *file, void *priv, struct v4l2_format *f) { struct vivid_dev *dev = video_drvdata(file); if (!dev->multiplanar) return -ENOTTY; return vivid_s_fmt_vid_cap(file, priv, f); } int vidioc_g_fmt_vid_cap(struct file *file, void *priv, struct v4l2_format *f) { struct vivid_dev *dev = video_drvdata(file); if (dev->multiplanar) return -ENOTTY; return fmt_sp2mp_func(file, priv, f, vivid_g_fmt_vid_cap); } int vidioc_try_fmt_vid_cap(struct file *file, void *priv, struct v4l2_format *f) { struct vivid_dev *dev = video_drvdata(file); if (dev->multiplanar) return -ENOTTY; return fmt_sp2mp_func(file, priv, f, vivid_try_fmt_vid_cap); } int vidioc_s_fmt_vid_cap(struct file *file, void *priv, struct v4l2_format *f) { struct vivid_dev *dev = video_drvdata(file); if (dev->multiplanar) return -ENOTTY; return fmt_sp2mp_func(file, priv, f, vivid_s_fmt_vid_cap); } int vivid_vid_cap_g_selection(struct file *file, void *priv, struct v4l2_selection *sel) { struct vivid_dev *dev = video_drvdata(file); if (!dev->has_crop_cap && !dev->has_compose_cap) return -ENOTTY; if (sel->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) return -EINVAL; if (vivid_is_webcam(dev)) return -ENODATA; sel->r.left = sel->r.top = 0; switch (sel->target) { case V4L2_SEL_TGT_CROP: if (!dev->has_crop_cap) return -EINVAL; sel->r = dev->crop_cap; break; case V4L2_SEL_TGT_CROP_DEFAULT: case V4L2_SEL_TGT_CROP_BOUNDS: if (!dev->has_crop_cap) return -EINVAL; sel->r = dev->src_rect; break; case V4L2_SEL_TGT_COMPOSE_BOUNDS: if (!dev->has_compose_cap) return -EINVAL; sel->r = vivid_max_rect; break; case V4L2_SEL_TGT_COMPOSE: if (!dev->has_compose_cap) return -EINVAL; sel->r = dev->compose_cap; break; case V4L2_SEL_TGT_COMPOSE_DEFAULT: if (!dev->has_compose_cap) return -EINVAL; sel->r = dev->fmt_cap_rect; break; default: return -EINVAL; } return 0; } int vivid_vid_cap_s_selection(struct file *file, void *fh, struct v4l2_selection *s) { struct vivid_dev *dev = video_drvdata(file); struct v4l2_rect *crop = &dev->crop_cap; struct v4l2_rect *compose = &dev->compose_cap; unsigned factor = V4L2_FIELD_HAS_T_OR_B(dev->field_cap) ? 2 : 1; int ret; if (!dev->has_crop_cap && !dev->has_compose_cap) return -ENOTTY; if (s->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) return -EINVAL; if (vivid_is_webcam(dev)) return -ENODATA; switch (s->target) { case V4L2_SEL_TGT_CROP: if (!dev->has_crop_cap) return -EINVAL; ret = vivid_vid_adjust_sel(s->flags, &s->r); if (ret) return ret; v4l2_rect_set_min_size(&s->r, &vivid_min_rect); v4l2_rect_set_max_size(&s->r, &dev->src_rect); v4l2_rect_map_inside(&s->r, &dev->crop_bounds_cap); s->r.top /= factor; s->r.height /= factor; if (dev->has_scaler_cap) { struct v4l2_rect fmt = dev->fmt_cap_rect; struct v4l2_rect max_rect = { 0, 0, s->r.width * MAX_ZOOM, s->r.height * MAX_ZOOM }; struct v4l2_rect min_rect = { 0, 0, s->r.width / MAX_ZOOM, s->r.height / MAX_ZOOM }; v4l2_rect_set_min_size(&fmt, &min_rect); if (!dev->has_compose_cap) v4l2_rect_set_max_size(&fmt, &max_rect); if (!v4l2_rect_same_size(&dev->fmt_cap_rect, &fmt) && vb2_is_busy(&dev->vb_vid_cap_q)) return -EBUSY; if (dev->has_compose_cap) { v4l2_rect_set_min_size(compose, &min_rect); v4l2_rect_set_max_size(compose, &max_rect); v4l2_rect_map_inside(compose, &fmt); } dev->fmt_cap_rect = fmt; tpg_s_buf_height(&dev->tpg, fmt.height); } else if (dev->has_compose_cap) { struct v4l2_rect fmt = dev->fmt_cap_rect; v4l2_rect_set_min_size(&fmt, &s->r); if (!v4l2_rect_same_size(&dev->fmt_cap_rect, &fmt) && vb2_is_busy(&dev->vb_vid_cap_q)) return -EBUSY; dev->fmt_cap_rect = fmt; tpg_s_buf_height(&dev->tpg, fmt.height); v4l2_rect_set_size_to(compose, &s->r); v4l2_rect_map_inside(compose, &dev->fmt_cap_rect); } else { if (!v4l2_rect_same_size(&s->r, &dev->fmt_cap_rect) && vb2_is_busy(&dev->vb_vid_cap_q)) return -EBUSY; v4l2_rect_set_size_to(&dev->fmt_cap_rect, &s->r); v4l2_rect_set_size_to(compose, &s->r); v4l2_rect_map_inside(compose, &dev->fmt_cap_rect); tpg_s_buf_height(&dev->tpg, dev->fmt_cap_rect.height); } s->r.top *= factor; s->r.height *= factor; *crop = s->r; break; case V4L2_SEL_TGT_COMPOSE: if (!dev->has_compose_cap) return -EINVAL; ret = vivid_vid_adjust_sel(s->flags, &s->r); if (ret) return ret; v4l2_rect_set_min_size(&s->r, &vivid_min_rect); v4l2_rect_set_max_size(&s->r, &dev->fmt_cap_rect); if (dev->has_scaler_cap) { struct v4l2_rect max_rect = { 0, 0, dev->src_rect.width * MAX_ZOOM, (dev->src_rect.height / factor) * MAX_ZOOM }; v4l2_rect_set_max_size(&s->r, &max_rect); if (dev->has_crop_cap) { struct v4l2_rect min_rect = { 0, 0, s->r.width / MAX_ZOOM, (s->r.height * factor) / MAX_ZOOM }; struct v4l2_rect max_rect = { 0, 0, s->r.width * MAX_ZOOM, (s->r.height * factor) * MAX_ZOOM }; v4l2_rect_set_min_size(crop, &min_rect); v4l2_rect_set_max_size(crop, &max_rect); v4l2_rect_map_inside(crop, &dev->crop_bounds_cap); } } else if (dev->has_crop_cap) { s->r.top *= factor; s->r.height *= factor; v4l2_rect_set_max_size(&s->r, &dev->src_rect); v4l2_rect_set_size_to(crop, &s->r); v4l2_rect_map_inside(crop, &dev->crop_bounds_cap); s->r.top /= factor; s->r.height /= factor; } else { v4l2_rect_set_size_to(&s->r, &dev->src_rect); s->r.height /= factor; } v4l2_rect_map_inside(&s->r, &dev->fmt_cap_rect); *compose = s->r; break; default: return -EINVAL; } tpg_s_crop_compose(&dev->tpg, crop, compose); return 0; } int vivid_vid_cap_g_pixelaspect(struct file *file, void *priv, int type, struct v4l2_fract *f) { struct vivid_dev *dev = video_drvdata(file); if (type != V4L2_BUF_TYPE_VIDEO_CAPTURE) return -EINVAL; switch (vivid_get_pixel_aspect(dev)) { case TPG_PIXEL_ASPECT_NTSC: f->numerator = 11; f->denominator = 10; break; case TPG_PIXEL_ASPECT_PAL: f->numerator = 54; f->denominator = 59; break; default: break; } return 0; } static const struct v4l2_audio vivid_audio_inputs[] = { { 0, "TV", V4L2_AUDCAP_STEREO }, { 1, "Line-In", V4L2_AUDCAP_STEREO }, }; int vidioc_enum_input(struct file *file, void *priv, struct v4l2_input *inp) { struct vivid_dev *dev = video_drvdata(file); if (inp->index >= dev->num_inputs) return -EINVAL; inp->type = V4L2_INPUT_TYPE_CAMERA; switch (dev->input_type[inp->index]) { case WEBCAM: snprintf(inp->name, sizeof(inp->name), "Webcam %u", dev->input_name_counter[inp->index]); inp->capabilities = 0; break; case TV: snprintf(inp->name, sizeof(inp->name), "TV %u", dev->input_name_counter[inp->index]); inp->type = V4L2_INPUT_TYPE_TUNER; inp->std = V4L2_STD_ALL; if (dev->has_audio_inputs) inp->audioset = (1 << ARRAY_SIZE(vivid_audio_inputs)) - 1; inp->capabilities = V4L2_IN_CAP_STD; break; case SVID: snprintf(inp->name, sizeof(inp->name), "S-Video %u", dev->input_name_counter[inp->index]); inp->std = V4L2_STD_ALL; if (dev->has_audio_inputs) inp->audioset = (1 << ARRAY_SIZE(vivid_audio_inputs)) - 1; inp->capabilities = V4L2_IN_CAP_STD; break; case HDMI: snprintf(inp->name, sizeof(inp->name), "HDMI %u", dev->input_name_counter[inp->index]); inp->capabilities = V4L2_IN_CAP_DV_TIMINGS; if (dev->edid_blocks == 0 || dev->dv_timings_signal_mode[dev->input] == NO_SIGNAL) inp->status |= V4L2_IN_ST_NO_SIGNAL; else if (dev->dv_timings_signal_mode[dev->input] == NO_LOCK || dev->dv_timings_signal_mode[dev->input] == OUT_OF_RANGE) inp->status |= V4L2_IN_ST_NO_H_LOCK; break; } if (dev->sensor_hflip) inp->status |= V4L2_IN_ST_HFLIP; if (dev->sensor_vflip) inp->status |= V4L2_IN_ST_VFLIP; if (dev->input == inp->index && vivid_is_sdtv_cap(dev)) { if (dev->std_signal_mode[dev->input] == NO_SIGNAL) { inp->status |= V4L2_IN_ST_NO_SIGNAL; } else if (dev->std_signal_mode[dev->input] == NO_LOCK) { inp->status |= V4L2_IN_ST_NO_H_LOCK; } else if (vivid_is_tv_cap(dev)) { switch (tpg_g_quality(&dev->tpg)) { case TPG_QUAL_GRAY: inp->status |= V4L2_IN_ST_COLOR_KILL; break; case TPG_QUAL_NOISE: inp->status |= V4L2_IN_ST_NO_H_LOCK; break; default: break; } } } return 0; } int vidioc_g_input(struct file *file, void *priv, unsigned *i) { struct vivid_dev *dev = video_drvdata(file); *i = dev->input; return 0; } int vidioc_s_input(struct file *file, void *priv, unsigned i) { struct vivid_dev *dev = video_drvdata(file); struct v4l2_bt_timings *bt = &dev->dv_timings_cap[dev->input].bt; unsigned brightness; if (i >= dev->num_inputs) return -EINVAL; if (i == dev->input) return 0; if (vb2_is_busy(&dev->vb_vid_cap_q) || vb2_is_busy(&dev->vb_vbi_cap_q) || vb2_is_busy(&dev->vb_meta_cap_q)) return -EBUSY; dev->input = i; dev->vid_cap_dev.tvnorms = 0; if (dev->input_type[i] == TV || dev->input_type[i] == SVID) { dev->tv_audio_input = (dev->input_type[i] == TV) ? 0 : 1; dev->vid_cap_dev.tvnorms = V4L2_STD_ALL; } dev->vbi_cap_dev.tvnorms = dev->vid_cap_dev.tvnorms; dev->meta_cap_dev.tvnorms = dev->vid_cap_dev.tvnorms; vivid_update_format_cap(dev, false); if (dev->colorspace) { switch (dev->input_type[i]) { case WEBCAM: v4l2_ctrl_s_ctrl(dev->colorspace, VIVID_CS_SRGB); break; case TV: case SVID: v4l2_ctrl_s_ctrl(dev->colorspace, VIVID_CS_170M); break; case HDMI: if (bt->flags & V4L2_DV_FL_IS_CE_VIDEO) { if (dev->src_rect.width == 720 && dev->src_rect.height <= 576) v4l2_ctrl_s_ctrl(dev->colorspace, VIVID_CS_170M); else v4l2_ctrl_s_ctrl(dev->colorspace, VIVID_CS_709); } else { v4l2_ctrl_s_ctrl(dev->colorspace, VIVID_CS_SRGB); } break; } } /* * Modify the brightness range depending on the input. * This makes it easy to use vivid to test if applications can * handle control range modifications and is also how this is * typically used in practice as different inputs may be hooked * up to different receivers with different control ranges. */ brightness = 128 * i + dev->input_brightness[i]; v4l2_ctrl_modify_range(dev->brightness, 128 * i, 255 + 128 * i, 1, 128 + 128 * i); v4l2_ctrl_s_ctrl(dev->brightness, brightness); /* Restore per-input states. */ v4l2_ctrl_activate(dev->ctrl_dv_timings_signal_mode, vivid_is_hdmi_cap(dev)); v4l2_ctrl_activate(dev->ctrl_dv_timings, vivid_is_hdmi_cap(dev) && dev->dv_timings_signal_mode[dev->input] == SELECTED_DV_TIMINGS); v4l2_ctrl_activate(dev->ctrl_std_signal_mode, vivid_is_sdtv_cap(dev)); v4l2_ctrl_activate(dev->ctrl_standard, vivid_is_sdtv_cap(dev) && dev->std_signal_mode[dev->input]); if (vivid_is_hdmi_cap(dev)) { v4l2_ctrl_s_ctrl(dev->ctrl_dv_timings_signal_mode, dev->dv_timings_signal_mode[dev->input]); v4l2_ctrl_s_ctrl(dev->ctrl_dv_timings, dev->query_dv_timings[dev->input]); } else if (vivid_is_sdtv_cap(dev)) { v4l2_ctrl_s_ctrl(dev->ctrl_std_signal_mode, dev->std_signal_mode[dev->input]); v4l2_ctrl_s_ctrl(dev->ctrl_standard, dev->std_signal_mode[dev->input]); } return 0; } int vidioc_enumaudio(struct file *file, void *fh, struct v4l2_audio *vin) { if (vin->index >= ARRAY_SIZE(vivid_audio_inputs)) return -EINVAL; *vin = vivid_audio_inputs[vin->index]; return 0; } int vidioc_g_audio(struct file *file, void *fh, struct v4l2_audio *vin) { struct vivid_dev *dev = video_drvdata(file); if (!vivid_is_sdtv_cap(dev)) return -EINVAL; *vin = vivid_audio_inputs[dev->tv_audio_input]; return 0; } int vidioc_s_audio(struct file *file, void *fh, const struct v4l2_audio *vin) { struct vivid_dev *dev = video_drvdata(file); if (!vivid_is_sdtv_cap(dev)) return -EINVAL; if (vin->index >= ARRAY_SIZE(vivid_audio_inputs)) return -EINVAL; dev->tv_audio_input = vin->index; return 0; } int vivid_video_g_frequency(struct file *file, void *fh, struct v4l2_frequency *vf) { struct vivid_dev *dev = video_drvdata(file); if (vf->tuner != 0) return -EINVAL; vf->frequency = dev->tv_freq; return 0; } int vivid_video_s_frequency(struct file *file, void *fh, const struct v4l2_frequency *vf) { struct vivid_dev *dev = video_drvdata(file); if (vf->tuner != 0) return -EINVAL; dev->tv_freq = clamp_t(unsigned, vf->frequency, MIN_TV_FREQ, MAX_TV_FREQ); if (vivid_is_tv_cap(dev)) vivid_update_quality(dev); return 0; } int vivid_video_s_tuner(struct file *file, void *fh, const struct v4l2_tuner *vt) { struct vivid_dev *dev = video_drvdata(file); if (vt->index != 0) return -EINVAL; if (vt->audmode > V4L2_TUNER_MODE_LANG1_LANG2) return -EINVAL; dev->tv_audmode = vt->audmode; return 0; } int vivid_video_g_tuner(struct file *file, void *fh, struct v4l2_tuner *vt) { struct vivid_dev *dev = video_drvdata(file); enum tpg_quality qual; if (vt->index != 0) return -EINVAL; vt->capability = V4L2_TUNER_CAP_NORM | V4L2_TUNER_CAP_STEREO | V4L2_TUNER_CAP_LANG1 | V4L2_TUNER_CAP_LANG2; vt->audmode = dev->tv_audmode; vt->rangelow = MIN_TV_FREQ; vt->rangehigh = MAX_TV_FREQ; qual = vivid_get_quality(dev, &vt->afc); if (qual == TPG_QUAL_COLOR) vt->signal = 0xffff; else if (qual == TPG_QUAL_GRAY) vt->signal = 0x8000; else vt->signal = 0; if (qual == TPG_QUAL_NOISE) { vt->rxsubchans = 0; } else if (qual == TPG_QUAL_GRAY) { vt->rxsubchans = V4L2_TUNER_SUB_MONO; } else { unsigned int channel_nr = dev->tv_freq / (6 * 16); unsigned int options = (dev->std_cap[dev->input] & V4L2_STD_NTSC_M) ? 4 : 3; switch (channel_nr % options) { case 0: vt->rxsubchans = V4L2_TUNER_SUB_MONO; break; case 1: vt->rxsubchans = V4L2_TUNER_SUB_STEREO; break; case 2: if (dev->std_cap[dev->input] & V4L2_STD_NTSC_M) vt->rxsubchans = V4L2_TUNER_SUB_MONO | V4L2_TUNER_SUB_SAP; else vt->rxsubchans = V4L2_TUNER_SUB_LANG1 | V4L2_TUNER_SUB_LANG2; break; case 3: vt->rxsubchans = V4L2_TUNER_SUB_STEREO | V4L2_TUNER_SUB_SAP; break; } } strscpy(vt->name, "TV Tuner", sizeof(vt->name)); return 0; } /* Must remain in sync with the vivid_ctrl_standard_strings array */ const v4l2_std_id vivid_standard[] = { V4L2_STD_NTSC_M, V4L2_STD_NTSC_M_JP, V4L2_STD_NTSC_M_KR, V4L2_STD_NTSC_443, V4L2_STD_PAL_BG | V4L2_STD_PAL_H, V4L2_STD_PAL_I, V4L2_STD_PAL_DK, V4L2_STD_PAL_M, V4L2_STD_PAL_N, V4L2_STD_PAL_Nc, V4L2_STD_PAL_60, V4L2_STD_SECAM_B | V4L2_STD_SECAM_G | V4L2_STD_SECAM_H, V4L2_STD_SECAM_DK, V4L2_STD_SECAM_L, V4L2_STD_SECAM_LC, V4L2_STD_UNKNOWN }; /* Must remain in sync with the vivid_standard array */ const char * const vivid_ctrl_standard_strings[] = { "NTSC-M", "NTSC-M-JP", "NTSC-M-KR", "NTSC-443", "PAL-BGH", "PAL-I", "PAL-DK", "PAL-M", "PAL-N", "PAL-Nc", "PAL-60", "SECAM-BGH", "SECAM-DK", "SECAM-L", "SECAM-Lc", NULL, }; int vidioc_querystd(struct file *file, void *priv, v4l2_std_id *id) { struct vivid_dev *dev = video_drvdata(file); unsigned int last = dev->query_std_last[dev->input]; if (!vivid_is_sdtv_cap(dev)) return -ENODATA; if (dev->std_signal_mode[dev->input] == NO_SIGNAL || dev->std_signal_mode[dev->input] == NO_LOCK) { *id = V4L2_STD_UNKNOWN; return 0; } if (vivid_is_tv_cap(dev) && tpg_g_quality(&dev->tpg) == TPG_QUAL_NOISE) { *id = V4L2_STD_UNKNOWN; } else if (dev->std_signal_mode[dev->input] == CURRENT_STD) { *id = dev->std_cap[dev->input]; } else if (dev->std_signal_mode[dev->input] == SELECTED_STD) { *id = dev->query_std[dev->input]; } else { *id = vivid_standard[last]; dev->query_std_last[dev->input] = (last + 1) % ARRAY_SIZE(vivid_standard); } return 0; } int vivid_vid_cap_s_std(struct file *file, void *priv, v4l2_std_id id) { struct vivid_dev *dev = video_drvdata(file); if (!vivid_is_sdtv_cap(dev)) return -ENODATA; if (dev->std_cap[dev->input] == id) return 0; if (vb2_is_busy(&dev->vb_vid_cap_q) || vb2_is_busy(&dev->vb_vbi_cap_q)) return -EBUSY; dev->std_cap[dev->input] = id; vivid_update_format_cap(dev, false); return 0; } static void find_aspect_ratio(u32 width, u32 height, u32 *num, u32 *denom) { if (!(height % 3) && ((height * 4 / 3) == width)) { *num = 4; *denom = 3; } else if (!(height % 9) && ((height * 16 / 9) == width)) { *num = 16; *denom = 9; } else if (!(height % 10) && ((height * 16 / 10) == width)) { *num = 16; *denom = 10; } else if (!(height % 4) && ((height * 5 / 4) == width)) { *num = 5; *denom = 4; } else if (!(height % 9) && ((height * 15 / 9) == width)) { *num = 15; *denom = 9; } else { /* default to 16:9 */ *num = 16; *denom = 9; } } static bool valid_cvt_gtf_timings(struct v4l2_dv_timings *timings) { struct v4l2_bt_timings *bt = &timings->bt; u32 total_h_pixel; u32 total_v_lines; u32 h_freq; if (!v4l2_valid_dv_timings(timings, &vivid_dv_timings_cap, NULL, NULL)) return false; total_h_pixel = V4L2_DV_BT_FRAME_WIDTH(bt); total_v_lines = V4L2_DV_BT_FRAME_HEIGHT(bt); h_freq = (u32)bt->pixelclock / total_h_pixel; if (bt->standards == 0 || (bt->standards & V4L2_DV_BT_STD_CVT)) { if (v4l2_detect_cvt(total_v_lines, h_freq, bt->vsync, bt->width, bt->polarities, bt->interlaced, timings)) return true; } if (bt->standards == 0 || (bt->standards & V4L2_DV_BT_STD_GTF)) { struct v4l2_fract aspect_ratio; find_aspect_ratio(bt->width, bt->height, &aspect_ratio.numerator, &aspect_ratio.denominator); if (v4l2_detect_gtf(total_v_lines, h_freq, bt->vsync, bt->polarities, bt->interlaced, aspect_ratio, timings)) return true; } return false; } int vivid_vid_cap_s_dv_timings(struct file *file, void *_fh, struct v4l2_dv_timings *timings) { struct vivid_dev *dev = video_drvdata(file); if (!vivid_is_hdmi_cap(dev)) return -ENODATA; if (!v4l2_find_dv_timings_cap(timings, &vivid_dv_timings_cap, 0, NULL, NULL) && !valid_cvt_gtf_timings(timings)) return -EINVAL; if (v4l2_match_dv_timings(timings, &dev->dv_timings_cap[dev->input], 0, false)) return 0; if (vb2_is_busy(&dev->vb_vid_cap_q)) return -EBUSY; dev->dv_timings_cap[dev->input] = *timings; vivid_update_format_cap(dev, false); return 0; } int vidioc_query_dv_timings(struct file *file, void *_fh, struct v4l2_dv_timings *timings) { struct vivid_dev *dev = video_drvdata(file); unsigned int input = dev->input; unsigned int last = dev->query_dv_timings_last[input]; if (!vivid_is_hdmi_cap(dev)) return -ENODATA; if (dev->dv_timings_signal_mode[input] == NO_SIGNAL || dev->edid_blocks == 0) return -ENOLINK; if (dev->dv_timings_signal_mode[input] == NO_LOCK) return -ENOLCK; if (dev->dv_timings_signal_mode[input] == OUT_OF_RANGE) { timings->bt.pixelclock = vivid_dv_timings_cap.bt.max_pixelclock * 2; return -ERANGE; } if (dev->dv_timings_signal_mode[input] == CURRENT_DV_TIMINGS) { *timings = dev->dv_timings_cap[input]; } else if (dev->dv_timings_signal_mode[input] == SELECTED_DV_TIMINGS) { *timings = v4l2_dv_timings_presets[dev->query_dv_timings[input]]; } else { *timings = v4l2_dv_timings_presets[last]; dev->query_dv_timings_last[input] = (last + 1) % dev->query_dv_timings_size; } return 0; } int vidioc_s_edid(struct file *file, void *_fh, struct v4l2_edid *edid) { struct vivid_dev *dev = video_drvdata(file); u16 phys_addr; u32 display_present = 0; unsigned int i, j; int ret; memset(edid->reserved, 0, sizeof(edid->reserved)); if (edid->pad >= dev->num_inputs) return -EINVAL; if (dev->input_type[edid->pad] != HDMI || edid->start_block) return -EINVAL; if (edid->blocks == 0) { dev->edid_blocks = 0; v4l2_ctrl_s_ctrl(dev->ctrl_tx_edid_present, 0); v4l2_ctrl_s_ctrl(dev->ctrl_tx_hotplug, 0); phys_addr = CEC_PHYS_ADDR_INVALID; goto set_phys_addr; } if (edid->blocks > dev->edid_max_blocks) { edid->blocks = dev->edid_max_blocks; return -E2BIG; } phys_addr = cec_get_edid_phys_addr(edid->edid, edid->blocks * 128, NULL); ret = v4l2_phys_addr_validate(phys_addr, &phys_addr, NULL); if (ret) return ret; if (vb2_is_busy(&dev->vb_vid_cap_q)) return -EBUSY; dev->edid_blocks = edid->blocks; memcpy(dev->edid, edid->edid, edid->blocks * 128); for (i = 0, j = 0; i < dev->num_outputs; i++) if (dev->output_type[i] == HDMI) display_present |= dev->display_present[i] << j++; v4l2_ctrl_s_ctrl(dev->ctrl_tx_edid_present, display_present); v4l2_ctrl_s_ctrl(dev->ctrl_tx_hotplug, display_present); set_phys_addr: /* TODO: a proper hotplug detect cycle should be emulated here */ cec_s_phys_addr(dev->cec_rx_adap, phys_addr, false); for (i = 0; i < MAX_OUTPUTS && dev->cec_tx_adap[i]; i++) cec_s_phys_addr(dev->cec_tx_adap[i], dev->display_present[i] ? v4l2_phys_addr_for_input(phys_addr, i + 1) : CEC_PHYS_ADDR_INVALID, false); return 0; } int vidioc_enum_framesizes(struct file *file, void *fh, struct v4l2_frmsizeenum *fsize) { struct vivid_dev *dev = video_drvdata(file); if (!vivid_is_webcam(dev) && !dev->has_scaler_cap) return -EINVAL; if (vivid_get_format(dev, fsize->pixel_format) == NULL) return -EINVAL; if (vivid_is_webcam(dev)) { if (fsize->index >= ARRAY_SIZE(webcam_sizes)) return -EINVAL; fsize->type = V4L2_FRMSIZE_TYPE_DISCRETE; fsize->discrete = webcam_sizes[fsize->index]; return 0; } if (fsize->index) return -EINVAL; fsize->type = V4L2_FRMSIZE_TYPE_STEPWISE; fsize->stepwise.min_width = MIN_WIDTH; fsize->stepwise.max_width = MAX_WIDTH * MAX_ZOOM; fsize->stepwise.step_width = 2; fsize->stepwise.min_height = MIN_HEIGHT; fsize->stepwise.max_height = MAX_HEIGHT * MAX_ZOOM; fsize->stepwise.step_height = 2; return 0; } /* timeperframe is arbitrary and continuous */ int vidioc_enum_frameintervals(struct file *file, void *priv, struct v4l2_frmivalenum *fival) { struct vivid_dev *dev = video_drvdata(file); const struct vivid_fmt *fmt; int i; fmt = vivid_get_format(dev, fival->pixel_format); if (!fmt) return -EINVAL; if (!vivid_is_webcam(dev)) { if (fival->index) return -EINVAL; if (fival->width < MIN_WIDTH || fival->width > MAX_WIDTH * MAX_ZOOM) return -EINVAL; if (fival->height < MIN_HEIGHT || fival->height > MAX_HEIGHT * MAX_ZOOM) return -EINVAL; fival->type = V4L2_FRMIVAL_TYPE_DISCRETE; fival->discrete = dev->timeperframe_vid_cap; return 0; } for (i = 0; i < ARRAY_SIZE(webcam_sizes); i++) if (fival->width == webcam_sizes[i].width && fival->height == webcam_sizes[i].height) break; if (i == ARRAY_SIZE(webcam_sizes)) return -EINVAL; if (fival->index >= webcam_ival_count(dev, i)) return -EINVAL; fival->type = V4L2_FRMIVAL_TYPE_DISCRETE; fival->discrete = webcam_intervals[fival->index]; return 0; } int vivid_vid_cap_g_parm(struct file *file, void *priv, struct v4l2_streamparm *parm) { struct vivid_dev *dev = video_drvdata(file); if (parm->type != (dev->multiplanar ? V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE : V4L2_BUF_TYPE_VIDEO_CAPTURE)) return -EINVAL; parm->parm.capture.capability = V4L2_CAP_TIMEPERFRAME; parm->parm.capture.timeperframe = dev->timeperframe_vid_cap; parm->parm.capture.readbuffers = 1; return 0; } int vivid_vid_cap_s_parm(struct file *file, void *priv, struct v4l2_streamparm *parm) { struct vivid_dev *dev = video_drvdata(file); unsigned int ival_sz = webcam_ival_count(dev, dev->webcam_size_idx); struct v4l2_fract tpf; unsigned i; if (parm->type != (dev->multiplanar ? V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE : V4L2_BUF_TYPE_VIDEO_CAPTURE)) return -EINVAL; if (!vivid_is_webcam(dev)) return vivid_vid_cap_g_parm(file, priv, parm); tpf = parm->parm.capture.timeperframe; if (tpf.denominator == 0) tpf = webcam_intervals[ival_sz - 1]; for (i = 0; i < ival_sz; i++) if (V4L2_FRACT_COMPARE(tpf, >=, webcam_intervals[i])) break; if (i == ival_sz) i = ival_sz - 1; dev->webcam_ival_idx = i; tpf = webcam_intervals[dev->webcam_ival_idx]; /* resync the thread's timings */ dev->cap_seq_resync = true; dev->timeperframe_vid_cap = tpf; parm->parm.capture.capability = V4L2_CAP_TIMEPERFRAME; parm->parm.capture.timeperframe = tpf; parm->parm.capture.readbuffers = 1; return 0; }
linux-master
drivers/media/test-drivers/vivid/vivid-vid-cap.c
// SPDX-License-Identifier: GPL-2.0-only /* * vivid-vbi-out.c - vbi output support functions. * * Copyright 2014 Cisco Systems, Inc. and/or its affiliates. All rights reserved. */ #include <linux/errno.h> #include <linux/kernel.h> #include <linux/videodev2.h> #include <media/v4l2-common.h> #include "vivid-core.h" #include "vivid-kthread-out.h" #include "vivid-vbi-out.h" #include "vivid-vbi-cap.h" static int vbi_out_queue_setup(struct vb2_queue *vq, unsigned *nbuffers, unsigned *nplanes, unsigned sizes[], struct device *alloc_devs[]) { struct vivid_dev *dev = vb2_get_drv_priv(vq); bool is_60hz = dev->std_out & V4L2_STD_525_60; unsigned size = vq->type == V4L2_BUF_TYPE_SLICED_VBI_OUTPUT ? 36 * sizeof(struct v4l2_sliced_vbi_data) : 1440 * 2 * (is_60hz ? 12 : 18); if (!vivid_is_svid_out(dev)) return -EINVAL; sizes[0] = size; if (vq->num_buffers + *nbuffers < 2) *nbuffers = 2 - vq->num_buffers; *nplanes = 1; return 0; } static int vbi_out_buf_prepare(struct vb2_buffer *vb) { struct vivid_dev *dev = vb2_get_drv_priv(vb->vb2_queue); bool is_60hz = dev->std_out & V4L2_STD_525_60; unsigned size = vb->vb2_queue->type == V4L2_BUF_TYPE_SLICED_VBI_OUTPUT ? 36 * sizeof(struct v4l2_sliced_vbi_data) : 1440 * 2 * (is_60hz ? 12 : 18); dprintk(dev, 1, "%s\n", __func__); if (dev->buf_prepare_error) { /* * Error injection: test what happens if buf_prepare() returns * an error. */ dev->buf_prepare_error = false; return -EINVAL; } if (vb2_plane_size(vb, 0) < size) { dprintk(dev, 1, "%s data will not fit into plane (%lu < %u)\n", __func__, vb2_plane_size(vb, 0), size); return -EINVAL; } vb2_set_plane_payload(vb, 0, size); return 0; } static void vbi_out_buf_queue(struct vb2_buffer *vb) { struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb); struct vivid_dev *dev = vb2_get_drv_priv(vb->vb2_queue); struct vivid_buffer *buf = container_of(vbuf, struct vivid_buffer, vb); dprintk(dev, 1, "%s\n", __func__); spin_lock(&dev->slock); list_add_tail(&buf->list, &dev->vbi_out_active); spin_unlock(&dev->slock); } static int vbi_out_start_streaming(struct vb2_queue *vq, unsigned count) { struct vivid_dev *dev = vb2_get_drv_priv(vq); int err; dprintk(dev, 1, "%s\n", __func__); dev->vbi_out_seq_count = 0; if (dev->start_streaming_error) { dev->start_streaming_error = false; err = -EINVAL; } else { err = vivid_start_generating_vid_out(dev, &dev->vbi_out_streaming); } if (err) { struct vivid_buffer *buf, *tmp; list_for_each_entry_safe(buf, tmp, &dev->vbi_out_active, list) { list_del(&buf->list); vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_QUEUED); } } return err; } /* abort streaming and wait for last buffer */ static void vbi_out_stop_streaming(struct vb2_queue *vq) { struct vivid_dev *dev = vb2_get_drv_priv(vq); dprintk(dev, 1, "%s\n", __func__); vivid_stop_generating_vid_out(dev, &dev->vbi_out_streaming); dev->vbi_out_have_wss = false; dev->vbi_out_have_cc[0] = false; dev->vbi_out_have_cc[1] = false; } static void vbi_out_buf_request_complete(struct vb2_buffer *vb) { struct vivid_dev *dev = vb2_get_drv_priv(vb->vb2_queue); v4l2_ctrl_request_complete(vb->req_obj.req, &dev->ctrl_hdl_vbi_out); } const struct vb2_ops vivid_vbi_out_qops = { .queue_setup = vbi_out_queue_setup, .buf_prepare = vbi_out_buf_prepare, .buf_queue = vbi_out_buf_queue, .start_streaming = vbi_out_start_streaming, .stop_streaming = vbi_out_stop_streaming, .buf_request_complete = vbi_out_buf_request_complete, .wait_prepare = vb2_ops_wait_prepare, .wait_finish = vb2_ops_wait_finish, }; int vidioc_g_fmt_vbi_out(struct file *file, void *priv, struct v4l2_format *f) { struct vivid_dev *dev = video_drvdata(file); struct v4l2_vbi_format *vbi = &f->fmt.vbi; bool is_60hz = dev->std_out & V4L2_STD_525_60; if (!vivid_is_svid_out(dev) || !dev->has_raw_vbi_out) return -EINVAL; vbi->sampling_rate = 25000000; vbi->offset = 24; vbi->samples_per_line = 1440; vbi->sample_format = V4L2_PIX_FMT_GREY; vbi->start[0] = is_60hz ? V4L2_VBI_ITU_525_F1_START + 9 : V4L2_VBI_ITU_625_F1_START + 5; vbi->start[1] = is_60hz ? V4L2_VBI_ITU_525_F2_START + 9 : V4L2_VBI_ITU_625_F2_START + 5; vbi->count[0] = vbi->count[1] = is_60hz ? 12 : 18; vbi->flags = dev->vbi_cap_interlaced ? V4L2_VBI_INTERLACED : 0; vbi->reserved[0] = 0; vbi->reserved[1] = 0; return 0; } int vidioc_s_fmt_vbi_out(struct file *file, void *priv, struct v4l2_format *f) { struct vivid_dev *dev = video_drvdata(file); int ret = vidioc_g_fmt_vbi_out(file, priv, f); if (ret) return ret; if (vb2_is_busy(&dev->vb_vbi_out_q)) return -EBUSY; dev->stream_sliced_vbi_out = false; dev->vbi_out_dev.queue->type = V4L2_BUF_TYPE_VBI_OUTPUT; return 0; } int vidioc_g_fmt_sliced_vbi_out(struct file *file, void *fh, struct v4l2_format *fmt) { struct vivid_dev *dev = video_drvdata(file); struct v4l2_sliced_vbi_format *vbi = &fmt->fmt.sliced; if (!vivid_is_svid_out(dev) || !dev->has_sliced_vbi_out) return -EINVAL; vivid_fill_service_lines(vbi, dev->service_set_out); return 0; } int vidioc_try_fmt_sliced_vbi_out(struct file *file, void *fh, struct v4l2_format *fmt) { struct vivid_dev *dev = video_drvdata(file); struct v4l2_sliced_vbi_format *vbi = &fmt->fmt.sliced; bool is_60hz = dev->std_out & V4L2_STD_525_60; u32 service_set = vbi->service_set; if (!vivid_is_svid_out(dev) || !dev->has_sliced_vbi_out) return -EINVAL; service_set &= is_60hz ? V4L2_SLICED_CAPTION_525 : V4L2_SLICED_WSS_625 | V4L2_SLICED_TELETEXT_B; vivid_fill_service_lines(vbi, service_set); return 0; } int vidioc_s_fmt_sliced_vbi_out(struct file *file, void *fh, struct v4l2_format *fmt) { struct vivid_dev *dev = video_drvdata(file); struct v4l2_sliced_vbi_format *vbi = &fmt->fmt.sliced; int ret = vidioc_try_fmt_sliced_vbi_out(file, fh, fmt); if (ret) return ret; if (vb2_is_busy(&dev->vb_vbi_out_q)) return -EBUSY; dev->service_set_out = vbi->service_set; dev->stream_sliced_vbi_out = true; dev->vbi_out_dev.queue->type = V4L2_BUF_TYPE_SLICED_VBI_OUTPUT; return 0; } void vivid_sliced_vbi_out_process(struct vivid_dev *dev, struct vivid_buffer *buf) { struct v4l2_sliced_vbi_data *vbi = vb2_plane_vaddr(&buf->vb.vb2_buf, 0); unsigned elems = vb2_get_plane_payload(&buf->vb.vb2_buf, 0) / sizeof(*vbi); dev->vbi_out_have_cc[0] = false; dev->vbi_out_have_cc[1] = false; dev->vbi_out_have_wss = false; while (elems--) { switch (vbi->id) { case V4L2_SLICED_CAPTION_525: if ((dev->std_out & V4L2_STD_525_60) && vbi->line == 21) { dev->vbi_out_have_cc[!!vbi->field] = true; dev->vbi_out_cc[!!vbi->field][0] = vbi->data[0]; dev->vbi_out_cc[!!vbi->field][1] = vbi->data[1]; } break; case V4L2_SLICED_WSS_625: if ((dev->std_out & V4L2_STD_625_50) && vbi->field == 0 && vbi->line == 23) { dev->vbi_out_have_wss = true; dev->vbi_out_wss[0] = vbi->data[0]; dev->vbi_out_wss[1] = vbi->data[1]; } break; } vbi++; } }
linux-master
drivers/media/test-drivers/vivid/vivid-vbi-out.c
// SPDX-License-Identifier: GPL-2.0-only /* * vivid-vid-out.c - video output support functions. * * Copyright 2014 Cisco Systems, Inc. and/or its affiliates. All rights reserved. */ #include <linux/errno.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/videodev2.h> #include <linux/v4l2-dv-timings.h> #include <media/v4l2-common.h> #include <media/v4l2-event.h> #include <media/v4l2-dv-timings.h> #include <media/v4l2-rect.h> #include "vivid-core.h" #include "vivid-vid-common.h" #include "vivid-kthread-out.h" #include "vivid-vid-out.h" static int vid_out_queue_setup(struct vb2_queue *vq, unsigned *nbuffers, unsigned *nplanes, unsigned sizes[], struct device *alloc_devs[]) { struct vivid_dev *dev = vb2_get_drv_priv(vq); const struct vivid_fmt *vfmt = dev->fmt_out; unsigned planes = vfmt->buffers; unsigned h = dev->fmt_out_rect.height; unsigned int size = dev->bytesperline_out[0] * h + vfmt->data_offset[0]; unsigned p; for (p = vfmt->buffers; p < vfmt->planes; p++) size += dev->bytesperline_out[p] * h / vfmt->vdownsampling[p] + vfmt->data_offset[p]; if (dev->field_out == V4L2_FIELD_ALTERNATE) { /* * You cannot use write() with FIELD_ALTERNATE since the field * information (TOP/BOTTOM) cannot be passed to the kernel. */ if (vb2_fileio_is_active(vq)) return -EINVAL; } if (dev->queue_setup_error) { /* * Error injection: test what happens if queue_setup() returns * an error. */ dev->queue_setup_error = false; return -EINVAL; } if (*nplanes) { /* * Check if the number of requested planes match * the number of planes in the current format. You can't mix that. */ if (*nplanes != planes) return -EINVAL; if (sizes[0] < size) return -EINVAL; for (p = 1; p < planes; p++) { if (sizes[p] < dev->bytesperline_out[p] * h + vfmt->data_offset[p]) return -EINVAL; } } else { for (p = 0; p < planes; p++) sizes[p] = p ? dev->bytesperline_out[p] * h + vfmt->data_offset[p] : size; } if (vq->num_buffers + *nbuffers < 2) *nbuffers = 2 - vq->num_buffers; *nplanes = planes; dprintk(dev, 1, "%s: count=%d\n", __func__, *nbuffers); for (p = 0; p < planes; p++) dprintk(dev, 1, "%s: size[%u]=%u\n", __func__, p, sizes[p]); return 0; } static int vid_out_buf_out_validate(struct vb2_buffer *vb) { struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb); struct vivid_dev *dev = vb2_get_drv_priv(vb->vb2_queue); dprintk(dev, 1, "%s\n", __func__); if (dev->field_out != V4L2_FIELD_ALTERNATE) vbuf->field = dev->field_out; else if (vbuf->field != V4L2_FIELD_TOP && vbuf->field != V4L2_FIELD_BOTTOM) return -EINVAL; return 0; } static int vid_out_buf_prepare(struct vb2_buffer *vb) { struct vivid_dev *dev = vb2_get_drv_priv(vb->vb2_queue); const struct vivid_fmt *vfmt = dev->fmt_out; unsigned int planes = vfmt->buffers; unsigned int h = dev->fmt_out_rect.height; unsigned int size = dev->bytesperline_out[0] * h; unsigned p; for (p = vfmt->buffers; p < vfmt->planes; p++) size += dev->bytesperline_out[p] * h / vfmt->vdownsampling[p]; dprintk(dev, 1, "%s\n", __func__); if (WARN_ON(NULL == dev->fmt_out)) return -EINVAL; if (dev->buf_prepare_error) { /* * Error injection: test what happens if buf_prepare() returns * an error. */ dev->buf_prepare_error = false; return -EINVAL; } for (p = 0; p < planes; p++) { if (p) size = dev->bytesperline_out[p] * h; size += vb->planes[p].data_offset; if (vb2_get_plane_payload(vb, p) < size) { dprintk(dev, 1, "%s the payload is too small for plane %u (%lu < %u)\n", __func__, p, vb2_get_plane_payload(vb, p), size); return -EINVAL; } } return 0; } static void vid_out_buf_queue(struct vb2_buffer *vb) { struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb); struct vivid_dev *dev = vb2_get_drv_priv(vb->vb2_queue); struct vivid_buffer *buf = container_of(vbuf, struct vivid_buffer, vb); dprintk(dev, 1, "%s\n", __func__); spin_lock(&dev->slock); list_add_tail(&buf->list, &dev->vid_out_active); spin_unlock(&dev->slock); } static int vid_out_start_streaming(struct vb2_queue *vq, unsigned count) { struct vivid_dev *dev = vb2_get_drv_priv(vq); int err; if (vb2_is_streaming(&dev->vb_vid_cap_q)) dev->can_loop_video = vivid_vid_can_loop(dev); dev->vid_out_seq_count = 0; dprintk(dev, 1, "%s\n", __func__); if (dev->start_streaming_error) { dev->start_streaming_error = false; err = -EINVAL; } else { err = vivid_start_generating_vid_out(dev, &dev->vid_out_streaming); } if (err) { struct vivid_buffer *buf, *tmp; list_for_each_entry_safe(buf, tmp, &dev->vid_out_active, list) { list_del(&buf->list); vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_QUEUED); } } return err; } /* abort streaming and wait for last buffer */ static void vid_out_stop_streaming(struct vb2_queue *vq) { struct vivid_dev *dev = vb2_get_drv_priv(vq); dprintk(dev, 1, "%s\n", __func__); vivid_stop_generating_vid_out(dev, &dev->vid_out_streaming); dev->can_loop_video = false; } static void vid_out_buf_request_complete(struct vb2_buffer *vb) { struct vivid_dev *dev = vb2_get_drv_priv(vb->vb2_queue); v4l2_ctrl_request_complete(vb->req_obj.req, &dev->ctrl_hdl_vid_out); } const struct vb2_ops vivid_vid_out_qops = { .queue_setup = vid_out_queue_setup, .buf_out_validate = vid_out_buf_out_validate, .buf_prepare = vid_out_buf_prepare, .buf_queue = vid_out_buf_queue, .start_streaming = vid_out_start_streaming, .stop_streaming = vid_out_stop_streaming, .buf_request_complete = vid_out_buf_request_complete, .wait_prepare = vb2_ops_wait_prepare, .wait_finish = vb2_ops_wait_finish, }; /* * Called whenever the format has to be reset which can occur when * changing outputs, standard, timings, etc. */ void vivid_update_format_out(struct vivid_dev *dev) { struct v4l2_bt_timings *bt = &dev->dv_timings_out.bt; unsigned size, p; u64 pixelclock; switch (dev->output_type[dev->output]) { case SVID: default: dev->field_out = dev->tv_field_out; dev->sink_rect.width = 720; if (dev->std_out & V4L2_STD_525_60) { dev->sink_rect.height = 480; dev->timeperframe_vid_out = (struct v4l2_fract) { 1001, 30000 }; dev->service_set_out = V4L2_SLICED_CAPTION_525; } else { dev->sink_rect.height = 576; dev->timeperframe_vid_out = (struct v4l2_fract) { 1000, 25000 }; dev->service_set_out = V4L2_SLICED_WSS_625 | V4L2_SLICED_TELETEXT_B; } dev->colorspace_out = V4L2_COLORSPACE_SMPTE170M; break; case HDMI: dev->sink_rect.width = bt->width; dev->sink_rect.height = bt->height; size = V4L2_DV_BT_FRAME_WIDTH(bt) * V4L2_DV_BT_FRAME_HEIGHT(bt); if (can_reduce_fps(bt) && (bt->flags & V4L2_DV_FL_REDUCED_FPS)) pixelclock = div_u64(bt->pixelclock * 1000, 1001); else pixelclock = bt->pixelclock; dev->timeperframe_vid_out = (struct v4l2_fract) { size / 100, (u32)pixelclock / 100 }; if (bt->interlaced) dev->field_out = V4L2_FIELD_ALTERNATE; else dev->field_out = V4L2_FIELD_NONE; if (!dev->dvi_d_out && (bt->flags & V4L2_DV_FL_IS_CE_VIDEO)) { if (bt->width == 720 && bt->height <= 576) dev->colorspace_out = V4L2_COLORSPACE_SMPTE170M; else dev->colorspace_out = V4L2_COLORSPACE_REC709; } else { dev->colorspace_out = V4L2_COLORSPACE_SRGB; } break; } dev->xfer_func_out = V4L2_XFER_FUNC_DEFAULT; dev->ycbcr_enc_out = V4L2_YCBCR_ENC_DEFAULT; dev->hsv_enc_out = V4L2_HSV_ENC_180; dev->quantization_out = V4L2_QUANTIZATION_DEFAULT; dev->compose_out = dev->sink_rect; dev->compose_bounds_out = dev->sink_rect; dev->crop_out = dev->compose_out; if (V4L2_FIELD_HAS_T_OR_B(dev->field_out)) dev->crop_out.height /= 2; dev->fmt_out_rect = dev->crop_out; for (p = 0; p < dev->fmt_out->planes; p++) dev->bytesperline_out[p] = (dev->sink_rect.width * dev->fmt_out->bit_depth[p]) / 8; } /* Map the field to something that is valid for the current output */ static enum v4l2_field vivid_field_out(struct vivid_dev *dev, enum v4l2_field field) { if (vivid_is_svid_out(dev)) { switch (field) { case V4L2_FIELD_INTERLACED_TB: case V4L2_FIELD_INTERLACED_BT: case V4L2_FIELD_SEQ_TB: case V4L2_FIELD_SEQ_BT: case V4L2_FIELD_ALTERNATE: return field; case V4L2_FIELD_INTERLACED: default: return V4L2_FIELD_INTERLACED; } } if (vivid_is_hdmi_out(dev)) return dev->dv_timings_out.bt.interlaced ? V4L2_FIELD_ALTERNATE : V4L2_FIELD_NONE; return V4L2_FIELD_NONE; } static enum tpg_pixel_aspect vivid_get_pixel_aspect(const struct vivid_dev *dev) { if (vivid_is_svid_out(dev)) return (dev->std_out & V4L2_STD_525_60) ? TPG_PIXEL_ASPECT_NTSC : TPG_PIXEL_ASPECT_PAL; if (vivid_is_hdmi_out(dev) && dev->sink_rect.width == 720 && dev->sink_rect.height <= 576) return dev->sink_rect.height == 480 ? TPG_PIXEL_ASPECT_NTSC : TPG_PIXEL_ASPECT_PAL; return TPG_PIXEL_ASPECT_SQUARE; } int vivid_g_fmt_vid_out(struct file *file, void *priv, struct v4l2_format *f) { struct vivid_dev *dev = video_drvdata(file); struct v4l2_pix_format_mplane *mp = &f->fmt.pix_mp; const struct vivid_fmt *fmt = dev->fmt_out; unsigned p; mp->width = dev->fmt_out_rect.width; mp->height = dev->fmt_out_rect.height; mp->field = dev->field_out; mp->pixelformat = fmt->fourcc; mp->colorspace = dev->colorspace_out; mp->xfer_func = dev->xfer_func_out; mp->ycbcr_enc = dev->ycbcr_enc_out; mp->quantization = dev->quantization_out; mp->num_planes = fmt->buffers; for (p = 0; p < mp->num_planes; p++) { mp->plane_fmt[p].bytesperline = dev->bytesperline_out[p]; mp->plane_fmt[p].sizeimage = mp->plane_fmt[p].bytesperline * mp->height + fmt->data_offset[p]; } for (p = fmt->buffers; p < fmt->planes; p++) { unsigned stride = dev->bytesperline_out[p]; mp->plane_fmt[0].sizeimage += (stride * mp->height) / fmt->vdownsampling[p]; } return 0; } int vivid_try_fmt_vid_out(struct file *file, void *priv, struct v4l2_format *f) { struct vivid_dev *dev = video_drvdata(file); struct v4l2_bt_timings *bt = &dev->dv_timings_out.bt; struct v4l2_pix_format_mplane *mp = &f->fmt.pix_mp; struct v4l2_plane_pix_format *pfmt = mp->plane_fmt; const struct vivid_fmt *fmt; unsigned bytesperline, max_bpl; unsigned factor = 1; unsigned w, h; unsigned p; fmt = vivid_get_format(dev, mp->pixelformat); if (!fmt) { dprintk(dev, 1, "Fourcc format (0x%08x) unknown.\n", mp->pixelformat); mp->pixelformat = V4L2_PIX_FMT_YUYV; fmt = vivid_get_format(dev, mp->pixelformat); } mp->field = vivid_field_out(dev, mp->field); if (vivid_is_svid_out(dev)) { w = 720; h = (dev->std_out & V4L2_STD_525_60) ? 480 : 576; } else { w = dev->sink_rect.width; h = dev->sink_rect.height; } if (V4L2_FIELD_HAS_T_OR_B(mp->field)) factor = 2; if (!dev->has_scaler_out && !dev->has_crop_out && !dev->has_compose_out) { mp->width = w; mp->height = h / factor; } else { struct v4l2_rect r = { 0, 0, mp->width, mp->height * factor }; v4l2_rect_set_min_size(&r, &vivid_min_rect); v4l2_rect_set_max_size(&r, &vivid_max_rect); if (dev->has_scaler_out && !dev->has_crop_out) { struct v4l2_rect max_r = { 0, 0, MAX_ZOOM * w, MAX_ZOOM * h }; v4l2_rect_set_max_size(&r, &max_r); } else if (!dev->has_scaler_out && dev->has_compose_out && !dev->has_crop_out) { v4l2_rect_set_max_size(&r, &dev->sink_rect); } else if (!dev->has_scaler_out && !dev->has_compose_out) { v4l2_rect_set_min_size(&r, &dev->sink_rect); } mp->width = r.width; mp->height = r.height / factor; } /* This driver supports custom bytesperline values */ mp->num_planes = fmt->buffers; for (p = 0; p < fmt->buffers; p++) { /* Calculate the minimum supported bytesperline value */ bytesperline = (mp->width * fmt->bit_depth[p]) >> 3; /* Calculate the maximum supported bytesperline value */ max_bpl = (MAX_ZOOM * MAX_WIDTH * fmt->bit_depth[p]) >> 3; if (pfmt[p].bytesperline > max_bpl) pfmt[p].bytesperline = max_bpl; if (pfmt[p].bytesperline < bytesperline) pfmt[p].bytesperline = bytesperline; pfmt[p].sizeimage = (pfmt[p].bytesperline * mp->height) / fmt->vdownsampling[p] + fmt->data_offset[p]; memset(pfmt[p].reserved, 0, sizeof(pfmt[p].reserved)); } for (p = fmt->buffers; p < fmt->planes; p++) pfmt[0].sizeimage += (pfmt[0].bytesperline * mp->height * (fmt->bit_depth[p] / fmt->vdownsampling[p])) / (fmt->bit_depth[0] / fmt->vdownsampling[0]); mp->xfer_func = V4L2_XFER_FUNC_DEFAULT; mp->ycbcr_enc = V4L2_YCBCR_ENC_DEFAULT; mp->quantization = V4L2_QUANTIZATION_DEFAULT; if (vivid_is_svid_out(dev)) { mp->colorspace = V4L2_COLORSPACE_SMPTE170M; } else if (dev->dvi_d_out || !(bt->flags & V4L2_DV_FL_IS_CE_VIDEO)) { mp->colorspace = V4L2_COLORSPACE_SRGB; if (dev->dvi_d_out) mp->quantization = V4L2_QUANTIZATION_LIM_RANGE; } else if (bt->width == 720 && bt->height <= 576) { mp->colorspace = V4L2_COLORSPACE_SMPTE170M; } else if (mp->colorspace != V4L2_COLORSPACE_SMPTE170M && mp->colorspace != V4L2_COLORSPACE_REC709 && mp->colorspace != V4L2_COLORSPACE_OPRGB && mp->colorspace != V4L2_COLORSPACE_BT2020 && mp->colorspace != V4L2_COLORSPACE_SRGB) { mp->colorspace = V4L2_COLORSPACE_REC709; } memset(mp->reserved, 0, sizeof(mp->reserved)); return 0; } int vivid_s_fmt_vid_out(struct file *file, void *priv, struct v4l2_format *f) { struct v4l2_pix_format_mplane *mp = &f->fmt.pix_mp; struct vivid_dev *dev = video_drvdata(file); struct v4l2_rect *crop = &dev->crop_out; struct v4l2_rect *compose = &dev->compose_out; struct vb2_queue *q = &dev->vb_vid_out_q; int ret = vivid_try_fmt_vid_out(file, priv, f); unsigned factor = 1; unsigned p; if (ret < 0) return ret; if (vb2_is_busy(q) && (vivid_is_svid_out(dev) || mp->width != dev->fmt_out_rect.width || mp->height != dev->fmt_out_rect.height || mp->pixelformat != dev->fmt_out->fourcc || mp->field != dev->field_out)) { dprintk(dev, 1, "%s device busy\n", __func__); return -EBUSY; } /* * Allow for changing the colorspace on the fly. Useful for testing * purposes, and it is something that HDMI transmitters are able * to do. */ if (vb2_is_busy(q)) goto set_colorspace; dev->fmt_out = vivid_get_format(dev, mp->pixelformat); if (V4L2_FIELD_HAS_T_OR_B(mp->field)) factor = 2; if (dev->has_scaler_out || dev->has_crop_out || dev->has_compose_out) { struct v4l2_rect r = { 0, 0, mp->width, mp->height }; if (dev->has_scaler_out) { if (dev->has_crop_out) v4l2_rect_map_inside(crop, &r); else *crop = r; if (dev->has_compose_out && !dev->has_crop_out) { struct v4l2_rect min_r = { 0, 0, r.width / MAX_ZOOM, factor * r.height / MAX_ZOOM }; struct v4l2_rect max_r = { 0, 0, r.width * MAX_ZOOM, factor * r.height * MAX_ZOOM }; v4l2_rect_set_min_size(compose, &min_r); v4l2_rect_set_max_size(compose, &max_r); v4l2_rect_map_inside(compose, &dev->compose_bounds_out); } else if (dev->has_compose_out) { struct v4l2_rect min_r = { 0, 0, crop->width / MAX_ZOOM, factor * crop->height / MAX_ZOOM }; struct v4l2_rect max_r = { 0, 0, crop->width * MAX_ZOOM, factor * crop->height * MAX_ZOOM }; v4l2_rect_set_min_size(compose, &min_r); v4l2_rect_set_max_size(compose, &max_r); v4l2_rect_map_inside(compose, &dev->compose_bounds_out); } } else if (dev->has_compose_out && !dev->has_crop_out) { v4l2_rect_set_size_to(crop, &r); r.height *= factor; v4l2_rect_set_size_to(compose, &r); v4l2_rect_map_inside(compose, &dev->compose_bounds_out); } else if (!dev->has_compose_out) { v4l2_rect_map_inside(crop, &r); r.height /= factor; v4l2_rect_set_size_to(compose, &r); } else { r.height *= factor; v4l2_rect_set_max_size(compose, &r); v4l2_rect_map_inside(compose, &dev->compose_bounds_out); crop->top *= factor; crop->height *= factor; v4l2_rect_set_size_to(crop, compose); v4l2_rect_map_inside(crop, &r); crop->top /= factor; crop->height /= factor; } } else { struct v4l2_rect r = { 0, 0, mp->width, mp->height }; v4l2_rect_set_size_to(crop, &r); r.height /= factor; v4l2_rect_set_size_to(compose, &r); } dev->fmt_out_rect.width = mp->width; dev->fmt_out_rect.height = mp->height; for (p = 0; p < mp->num_planes; p++) dev->bytesperline_out[p] = mp->plane_fmt[p].bytesperline; for (p = dev->fmt_out->buffers; p < dev->fmt_out->planes; p++) dev->bytesperline_out[p] = (dev->bytesperline_out[0] * dev->fmt_out->bit_depth[p]) / dev->fmt_out->bit_depth[0]; dev->field_out = mp->field; if (vivid_is_svid_out(dev)) dev->tv_field_out = mp->field; set_colorspace: dev->colorspace_out = mp->colorspace; dev->xfer_func_out = mp->xfer_func; dev->ycbcr_enc_out = mp->ycbcr_enc; dev->quantization_out = mp->quantization; if (dev->loop_video) { vivid_send_source_change(dev, SVID); vivid_send_source_change(dev, HDMI); } return 0; } int vidioc_g_fmt_vid_out_mplane(struct file *file, void *priv, struct v4l2_format *f) { struct vivid_dev *dev = video_drvdata(file); if (!dev->multiplanar) return -ENOTTY; return vivid_g_fmt_vid_out(file, priv, f); } int vidioc_try_fmt_vid_out_mplane(struct file *file, void *priv, struct v4l2_format *f) { struct vivid_dev *dev = video_drvdata(file); if (!dev->multiplanar) return -ENOTTY; return vivid_try_fmt_vid_out(file, priv, f); } int vidioc_s_fmt_vid_out_mplane(struct file *file, void *priv, struct v4l2_format *f) { struct vivid_dev *dev = video_drvdata(file); if (!dev->multiplanar) return -ENOTTY; return vivid_s_fmt_vid_out(file, priv, f); } int vidioc_g_fmt_vid_out(struct file *file, void *priv, struct v4l2_format *f) { struct vivid_dev *dev = video_drvdata(file); if (dev->multiplanar) return -ENOTTY; return fmt_sp2mp_func(file, priv, f, vivid_g_fmt_vid_out); } int vidioc_try_fmt_vid_out(struct file *file, void *priv, struct v4l2_format *f) { struct vivid_dev *dev = video_drvdata(file); if (dev->multiplanar) return -ENOTTY; return fmt_sp2mp_func(file, priv, f, vivid_try_fmt_vid_out); } int vidioc_s_fmt_vid_out(struct file *file, void *priv, struct v4l2_format *f) { struct vivid_dev *dev = video_drvdata(file); if (dev->multiplanar) return -ENOTTY; return fmt_sp2mp_func(file, priv, f, vivid_s_fmt_vid_out); } int vivid_vid_out_g_selection(struct file *file, void *priv, struct v4l2_selection *sel) { struct vivid_dev *dev = video_drvdata(file); if (!dev->has_crop_out && !dev->has_compose_out) return -ENOTTY; if (sel->type != V4L2_BUF_TYPE_VIDEO_OUTPUT) return -EINVAL; sel->r.left = sel->r.top = 0; switch (sel->target) { case V4L2_SEL_TGT_CROP: if (!dev->has_crop_out) return -EINVAL; sel->r = dev->crop_out; break; case V4L2_SEL_TGT_CROP_DEFAULT: if (!dev->has_crop_out) return -EINVAL; sel->r = dev->fmt_out_rect; break; case V4L2_SEL_TGT_CROP_BOUNDS: if (!dev->has_crop_out) return -EINVAL; sel->r = vivid_max_rect; break; case V4L2_SEL_TGT_COMPOSE: if (!dev->has_compose_out) return -EINVAL; sel->r = dev->compose_out; break; case V4L2_SEL_TGT_COMPOSE_DEFAULT: case V4L2_SEL_TGT_COMPOSE_BOUNDS: if (!dev->has_compose_out) return -EINVAL; sel->r = dev->sink_rect; break; default: return -EINVAL; } return 0; } int vivid_vid_out_s_selection(struct file *file, void *fh, struct v4l2_selection *s) { struct vivid_dev *dev = video_drvdata(file); struct v4l2_rect *crop = &dev->crop_out; struct v4l2_rect *compose = &dev->compose_out; unsigned factor = V4L2_FIELD_HAS_T_OR_B(dev->field_out) ? 2 : 1; int ret; if (!dev->has_crop_out && !dev->has_compose_out) return -ENOTTY; if (s->type != V4L2_BUF_TYPE_VIDEO_OUTPUT) return -EINVAL; switch (s->target) { case V4L2_SEL_TGT_CROP: if (!dev->has_crop_out) return -EINVAL; ret = vivid_vid_adjust_sel(s->flags, &s->r); if (ret) return ret; v4l2_rect_set_min_size(&s->r, &vivid_min_rect); v4l2_rect_set_max_size(&s->r, &dev->fmt_out_rect); if (dev->has_scaler_out) { struct v4l2_rect max_rect = { 0, 0, dev->sink_rect.width * MAX_ZOOM, (dev->sink_rect.height / factor) * MAX_ZOOM }; v4l2_rect_set_max_size(&s->r, &max_rect); if (dev->has_compose_out) { struct v4l2_rect min_rect = { 0, 0, s->r.width / MAX_ZOOM, (s->r.height * factor) / MAX_ZOOM }; struct v4l2_rect max_rect = { 0, 0, s->r.width * MAX_ZOOM, (s->r.height * factor) * MAX_ZOOM }; v4l2_rect_set_min_size(compose, &min_rect); v4l2_rect_set_max_size(compose, &max_rect); v4l2_rect_map_inside(compose, &dev->compose_bounds_out); } } else if (dev->has_compose_out) { s->r.top *= factor; s->r.height *= factor; v4l2_rect_set_max_size(&s->r, &dev->sink_rect); v4l2_rect_set_size_to(compose, &s->r); v4l2_rect_map_inside(compose, &dev->compose_bounds_out); s->r.top /= factor; s->r.height /= factor; } else { v4l2_rect_set_size_to(&s->r, &dev->sink_rect); s->r.height /= factor; } v4l2_rect_map_inside(&s->r, &dev->fmt_out_rect); *crop = s->r; break; case V4L2_SEL_TGT_COMPOSE: if (!dev->has_compose_out) return -EINVAL; ret = vivid_vid_adjust_sel(s->flags, &s->r); if (ret) return ret; v4l2_rect_set_min_size(&s->r, &vivid_min_rect); v4l2_rect_set_max_size(&s->r, &dev->sink_rect); v4l2_rect_map_inside(&s->r, &dev->compose_bounds_out); s->r.top /= factor; s->r.height /= factor; if (dev->has_scaler_out) { struct v4l2_rect fmt = dev->fmt_out_rect; struct v4l2_rect max_rect = { 0, 0, s->r.width * MAX_ZOOM, s->r.height * MAX_ZOOM }; struct v4l2_rect min_rect = { 0, 0, s->r.width / MAX_ZOOM, s->r.height / MAX_ZOOM }; v4l2_rect_set_min_size(&fmt, &min_rect); if (!dev->has_crop_out) v4l2_rect_set_max_size(&fmt, &max_rect); if (!v4l2_rect_same_size(&dev->fmt_out_rect, &fmt) && vb2_is_busy(&dev->vb_vid_out_q)) return -EBUSY; if (dev->has_crop_out) { v4l2_rect_set_min_size(crop, &min_rect); v4l2_rect_set_max_size(crop, &max_rect); } dev->fmt_out_rect = fmt; } else if (dev->has_crop_out) { struct v4l2_rect fmt = dev->fmt_out_rect; v4l2_rect_set_min_size(&fmt, &s->r); if (!v4l2_rect_same_size(&dev->fmt_out_rect, &fmt) && vb2_is_busy(&dev->vb_vid_out_q)) return -EBUSY; dev->fmt_out_rect = fmt; v4l2_rect_set_size_to(crop, &s->r); v4l2_rect_map_inside(crop, &dev->fmt_out_rect); } else { if (!v4l2_rect_same_size(&s->r, &dev->fmt_out_rect) && vb2_is_busy(&dev->vb_vid_out_q)) return -EBUSY; v4l2_rect_set_size_to(&dev->fmt_out_rect, &s->r); v4l2_rect_set_size_to(crop, &s->r); crop->height /= factor; v4l2_rect_map_inside(crop, &dev->fmt_out_rect); } s->r.top *= factor; s->r.height *= factor; *compose = s->r; break; default: return -EINVAL; } return 0; } int vivid_vid_out_g_pixelaspect(struct file *file, void *priv, int type, struct v4l2_fract *f) { struct vivid_dev *dev = video_drvdata(file); if (type != V4L2_BUF_TYPE_VIDEO_OUTPUT) return -EINVAL; switch (vivid_get_pixel_aspect(dev)) { case TPG_PIXEL_ASPECT_NTSC: f->numerator = 11; f->denominator = 10; break; case TPG_PIXEL_ASPECT_PAL: f->numerator = 54; f->denominator = 59; break; default: break; } return 0; } int vidioc_g_fmt_vid_out_overlay(struct file *file, void *priv, struct v4l2_format *f) { struct vivid_dev *dev = video_drvdata(file); const struct v4l2_rect *compose = &dev->compose_out; struct v4l2_window *win = &f->fmt.win; if (!dev->has_fb) return -EINVAL; win->w.top = dev->overlay_out_top; win->w.left = dev->overlay_out_left; win->w.width = compose->width; win->w.height = compose->height; win->field = V4L2_FIELD_ANY; win->chromakey = dev->chromakey_out; win->global_alpha = dev->global_alpha_out; return 0; } int vidioc_try_fmt_vid_out_overlay(struct file *file, void *priv, struct v4l2_format *f) { struct vivid_dev *dev = video_drvdata(file); const struct v4l2_rect *compose = &dev->compose_out; struct v4l2_window *win = &f->fmt.win; if (!dev->has_fb) return -EINVAL; win->w.left = clamp_t(int, win->w.left, -dev->display_width, dev->display_width); win->w.top = clamp_t(int, win->w.top, -dev->display_height, dev->display_height); win->w.width = compose->width; win->w.height = compose->height; /* * It makes no sense for an OSD to overlay only top or bottom fields, * so always set this to ANY. */ win->field = V4L2_FIELD_ANY; return 0; } int vidioc_s_fmt_vid_out_overlay(struct file *file, void *priv, struct v4l2_format *f) { struct vivid_dev *dev = video_drvdata(file); struct v4l2_window *win = &f->fmt.win; int ret = vidioc_try_fmt_vid_out_overlay(file, priv, f); if (ret) return ret; dev->overlay_out_top = win->w.top; dev->overlay_out_left = win->w.left; dev->chromakey_out = win->chromakey; dev->global_alpha_out = win->global_alpha; return ret; } int vivid_vid_out_overlay(struct file *file, void *fh, unsigned i) { struct vivid_dev *dev = video_drvdata(file); if (i && !dev->fmt_out->can_do_overlay) { dprintk(dev, 1, "unsupported output format for output overlay\n"); return -EINVAL; } dev->overlay_out_enabled = i; return 0; } int vivid_vid_out_g_fbuf(struct file *file, void *fh, struct v4l2_framebuffer *a) { struct vivid_dev *dev = video_drvdata(file); a->capability = V4L2_FBUF_CAP_EXTERNOVERLAY | V4L2_FBUF_CAP_CHROMAKEY | V4L2_FBUF_CAP_SRC_CHROMAKEY | V4L2_FBUF_CAP_GLOBAL_ALPHA | V4L2_FBUF_CAP_LOCAL_ALPHA | V4L2_FBUF_CAP_LOCAL_INV_ALPHA; a->flags = V4L2_FBUF_FLAG_OVERLAY | dev->fbuf_out_flags; a->base = (void *)dev->video_pbase; a->fmt.width = dev->display_width; a->fmt.height = dev->display_height; if (dev->fb_defined.green.length == 5) a->fmt.pixelformat = V4L2_PIX_FMT_ARGB555; else a->fmt.pixelformat = V4L2_PIX_FMT_RGB565; a->fmt.bytesperline = dev->display_byte_stride; a->fmt.sizeimage = a->fmt.height * a->fmt.bytesperline; a->fmt.field = V4L2_FIELD_NONE; a->fmt.colorspace = V4L2_COLORSPACE_SRGB; a->fmt.priv = 0; return 0; } int vivid_vid_out_s_fbuf(struct file *file, void *fh, const struct v4l2_framebuffer *a) { struct vivid_dev *dev = video_drvdata(file); const unsigned chroma_flags = V4L2_FBUF_FLAG_CHROMAKEY | V4L2_FBUF_FLAG_SRC_CHROMAKEY; const unsigned alpha_flags = V4L2_FBUF_FLAG_GLOBAL_ALPHA | V4L2_FBUF_FLAG_LOCAL_ALPHA | V4L2_FBUF_FLAG_LOCAL_INV_ALPHA; if ((a->flags & chroma_flags) == chroma_flags) return -EINVAL; switch (a->flags & alpha_flags) { case 0: case V4L2_FBUF_FLAG_GLOBAL_ALPHA: case V4L2_FBUF_FLAG_LOCAL_ALPHA: case V4L2_FBUF_FLAG_LOCAL_INV_ALPHA: break; default: return -EINVAL; } dev->fbuf_out_flags &= ~(chroma_flags | alpha_flags); dev->fbuf_out_flags |= a->flags & (chroma_flags | alpha_flags); return 0; } static const struct v4l2_audioout vivid_audio_outputs[] = { { 0, "Line-Out 1" }, { 1, "Line-Out 2" }, }; int vidioc_enum_output(struct file *file, void *priv, struct v4l2_output *out) { struct vivid_dev *dev = video_drvdata(file); if (out->index >= dev->num_outputs) return -EINVAL; out->type = V4L2_OUTPUT_TYPE_ANALOG; switch (dev->output_type[out->index]) { case SVID: snprintf(out->name, sizeof(out->name), "S-Video %u", dev->output_name_counter[out->index]); out->std = V4L2_STD_ALL; if (dev->has_audio_outputs) out->audioset = (1 << ARRAY_SIZE(vivid_audio_outputs)) - 1; out->capabilities = V4L2_OUT_CAP_STD; break; case HDMI: snprintf(out->name, sizeof(out->name), "HDMI %u", dev->output_name_counter[out->index]); out->capabilities = V4L2_OUT_CAP_DV_TIMINGS; break; } return 0; } int vidioc_g_output(struct file *file, void *priv, unsigned *o) { struct vivid_dev *dev = video_drvdata(file); *o = dev->output; return 0; } int vidioc_s_output(struct file *file, void *priv, unsigned o) { struct vivid_dev *dev = video_drvdata(file); if (o >= dev->num_outputs) return -EINVAL; if (o == dev->output) return 0; if (vb2_is_busy(&dev->vb_vid_out_q) || vb2_is_busy(&dev->vb_vbi_out_q) || vb2_is_busy(&dev->vb_meta_out_q)) return -EBUSY; dev->output = o; dev->tv_audio_output = 0; if (dev->output_type[o] == SVID) dev->vid_out_dev.tvnorms = V4L2_STD_ALL; else dev->vid_out_dev.tvnorms = 0; dev->vbi_out_dev.tvnorms = dev->vid_out_dev.tvnorms; dev->meta_out_dev.tvnorms = dev->vid_out_dev.tvnorms; vivid_update_format_out(dev); v4l2_ctrl_activate(dev->ctrl_display_present, vivid_is_hdmi_out(dev)); if (vivid_is_hdmi_out(dev)) v4l2_ctrl_s_ctrl(dev->ctrl_display_present, dev->display_present[dev->output]); return 0; } int vidioc_enumaudout(struct file *file, void *fh, struct v4l2_audioout *vout) { if (vout->index >= ARRAY_SIZE(vivid_audio_outputs)) return -EINVAL; *vout = vivid_audio_outputs[vout->index]; return 0; } int vidioc_g_audout(struct file *file, void *fh, struct v4l2_audioout *vout) { struct vivid_dev *dev = video_drvdata(file); if (!vivid_is_svid_out(dev)) return -EINVAL; *vout = vivid_audio_outputs[dev->tv_audio_output]; return 0; } int vidioc_s_audout(struct file *file, void *fh, const struct v4l2_audioout *vout) { struct vivid_dev *dev = video_drvdata(file); if (!vivid_is_svid_out(dev)) return -EINVAL; if (vout->index >= ARRAY_SIZE(vivid_audio_outputs)) return -EINVAL; dev->tv_audio_output = vout->index; return 0; } int vivid_vid_out_s_std(struct file *file, void *priv, v4l2_std_id id) { struct vivid_dev *dev = video_drvdata(file); if (!vivid_is_svid_out(dev)) return -ENODATA; if (dev->std_out == id) return 0; if (vb2_is_busy(&dev->vb_vid_out_q) || vb2_is_busy(&dev->vb_vbi_out_q)) return -EBUSY; dev->std_out = id; vivid_update_format_out(dev); return 0; } static bool valid_cvt_gtf_timings(struct v4l2_dv_timings *timings) { struct v4l2_bt_timings *bt = &timings->bt; if ((bt->standards & (V4L2_DV_BT_STD_CVT | V4L2_DV_BT_STD_GTF)) && v4l2_valid_dv_timings(timings, &vivid_dv_timings_cap, NULL, NULL)) return true; return false; } int vivid_vid_out_s_dv_timings(struct file *file, void *_fh, struct v4l2_dv_timings *timings) { struct vivid_dev *dev = video_drvdata(file); if (!vivid_is_hdmi_out(dev)) return -ENODATA; if (!v4l2_find_dv_timings_cap(timings, &vivid_dv_timings_cap, 0, NULL, NULL) && !valid_cvt_gtf_timings(timings)) return -EINVAL; if (v4l2_match_dv_timings(timings, &dev->dv_timings_out, 0, true)) return 0; if (vb2_is_busy(&dev->vb_vid_out_q)) return -EBUSY; dev->dv_timings_out = *timings; vivid_update_format_out(dev); return 0; } int vivid_vid_out_g_parm(struct file *file, void *priv, struct v4l2_streamparm *parm) { struct vivid_dev *dev = video_drvdata(file); if (parm->type != (dev->multiplanar ? V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE : V4L2_BUF_TYPE_VIDEO_OUTPUT)) return -EINVAL; parm->parm.output.capability = V4L2_CAP_TIMEPERFRAME; parm->parm.output.timeperframe = dev->timeperframe_vid_out; parm->parm.output.writebuffers = 1; return 0; } int vidioc_subscribe_event(struct v4l2_fh *fh, const struct v4l2_event_subscription *sub) { switch (sub->type) { case V4L2_EVENT_SOURCE_CHANGE: if (fh->vdev->vfl_dir == VFL_DIR_RX) return v4l2_src_change_event_subscribe(fh, sub); break; default: return v4l2_ctrl_subscribe_event(fh, sub); } return -EINVAL; }
linux-master
drivers/media/test-drivers/vivid/vivid-vid-out.c
// SPDX-License-Identifier: GPL-2.0-only /* * vivid-kthread-cap.h - video/vbi capture thread support functions. * * Copyright 2014 Cisco Systems, Inc. and/or its affiliates. All rights reserved. */ #include <linux/module.h> #include <linux/errno.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/font.h> #include <linux/mutex.h> #include <linux/videodev2.h> #include <linux/kthread.h> #include <linux/freezer.h> #include <linux/random.h> #include <linux/v4l2-dv-timings.h> #include <linux/jiffies.h> #include <asm/div64.h> #include <media/videobuf2-vmalloc.h> #include <media/v4l2-dv-timings.h> #include <media/v4l2-ioctl.h> #include <media/v4l2-fh.h> #include <media/v4l2-event.h> #include <media/v4l2-rect.h> #include "vivid-core.h" #include "vivid-vid-common.h" #include "vivid-vid-cap.h" #include "vivid-vid-out.h" #include "vivid-radio-common.h" #include "vivid-radio-rx.h" #include "vivid-radio-tx.h" #include "vivid-sdr-cap.h" #include "vivid-vbi-cap.h" #include "vivid-vbi-out.h" #include "vivid-osd.h" #include "vivid-ctrls.h" #include "vivid-kthread-cap.h" #include "vivid-meta-cap.h" static inline v4l2_std_id vivid_get_std_cap(const struct vivid_dev *dev) { if (vivid_is_sdtv_cap(dev)) return dev->std_cap[dev->input]; return 0; } static void copy_pix(struct vivid_dev *dev, int win_y, int win_x, u16 *cap, const u16 *osd) { u16 out; out = *cap; *cap = *osd; if ((dev->fbuf_out_flags & V4L2_FBUF_FLAG_CHROMAKEY) && *osd != dev->chromakey_out) return; if ((dev->fbuf_out_flags & V4L2_FBUF_FLAG_SRC_CHROMAKEY) && out == dev->chromakey_out) return; if (dev->fmt_cap->alpha_mask) { if ((dev->fbuf_out_flags & V4L2_FBUF_FLAG_GLOBAL_ALPHA) && dev->global_alpha_out) return; if ((dev->fbuf_out_flags & V4L2_FBUF_FLAG_LOCAL_ALPHA) && *cap & dev->fmt_cap->alpha_mask) return; if ((dev->fbuf_out_flags & V4L2_FBUF_FLAG_LOCAL_INV_ALPHA) && !(*cap & dev->fmt_cap->alpha_mask)) return; } *cap = out; } static void blend_line(struct vivid_dev *dev, unsigned y_offset, unsigned x_offset, u8 *vcapbuf, const u8 *vosdbuf, unsigned width, unsigned pixsize) { unsigned x; for (x = 0; x < width; x++, vcapbuf += pixsize, vosdbuf += pixsize) { copy_pix(dev, y_offset, x_offset + x, (u16 *)vcapbuf, (const u16 *)vosdbuf); } } static void scale_line(const u8 *src, u8 *dst, unsigned srcw, unsigned dstw, unsigned twopixsize) { /* Coarse scaling with Bresenham */ unsigned int_part; unsigned fract_part; unsigned src_x = 0; unsigned error = 0; unsigned x; /* * We always combine two pixels to prevent color bleed in the packed * yuv case. */ srcw /= 2; dstw /= 2; int_part = srcw / dstw; fract_part = srcw % dstw; for (x = 0; x < dstw; x++, dst += twopixsize) { memcpy(dst, src + src_x * twopixsize, twopixsize); src_x += int_part; error += fract_part; if (error >= dstw) { error -= dstw; src_x++; } } } /* * Precalculate the rectangles needed to perform video looping: * * The nominal pipeline is that the video output buffer is cropped by * crop_out, scaled to compose_out, overlaid with the output overlay, * cropped on the capture side by crop_cap and scaled again to the video * capture buffer using compose_cap. * * To keep things efficient we calculate the intersection of compose_out * and crop_cap (since that's the only part of the video that will * actually end up in the capture buffer), determine which part of the * video output buffer that is and which part of the video capture buffer * so we can scale the video straight from the output buffer to the capture * buffer without any intermediate steps. * * If we need to deal with an output overlay, then there is no choice and * that intermediate step still has to be taken. For the output overlay * support we calculate the intersection of the framebuffer and the overlay * window (which may be partially or wholly outside of the framebuffer * itself) and the intersection of that with loop_vid_copy (i.e. the part of * the actual looped video that will be overlaid). The result is calculated * both in framebuffer coordinates (loop_fb_copy) and compose_out coordinates * (loop_vid_overlay). Finally calculate the part of the capture buffer that * will receive that overlaid video. */ static void vivid_precalc_copy_rects(struct vivid_dev *dev) { /* Framebuffer rectangle */ struct v4l2_rect r_fb = { 0, 0, dev->display_width, dev->display_height }; /* Overlay window rectangle in framebuffer coordinates */ struct v4l2_rect r_overlay = { dev->overlay_out_left, dev->overlay_out_top, dev->compose_out.width, dev->compose_out.height }; v4l2_rect_intersect(&dev->loop_vid_copy, &dev->crop_cap, &dev->compose_out); dev->loop_vid_out = dev->loop_vid_copy; v4l2_rect_scale(&dev->loop_vid_out, &dev->compose_out, &dev->crop_out); dev->loop_vid_out.left += dev->crop_out.left; dev->loop_vid_out.top += dev->crop_out.top; dev->loop_vid_cap = dev->loop_vid_copy; v4l2_rect_scale(&dev->loop_vid_cap, &dev->crop_cap, &dev->compose_cap); dprintk(dev, 1, "loop_vid_copy: %dx%d@%dx%d loop_vid_out: %dx%d@%dx%d loop_vid_cap: %dx%d@%dx%d\n", dev->loop_vid_copy.width, dev->loop_vid_copy.height, dev->loop_vid_copy.left, dev->loop_vid_copy.top, dev->loop_vid_out.width, dev->loop_vid_out.height, dev->loop_vid_out.left, dev->loop_vid_out.top, dev->loop_vid_cap.width, dev->loop_vid_cap.height, dev->loop_vid_cap.left, dev->loop_vid_cap.top); v4l2_rect_intersect(&r_overlay, &r_fb, &r_overlay); /* shift r_overlay to the same origin as compose_out */ r_overlay.left += dev->compose_out.left - dev->overlay_out_left; r_overlay.top += dev->compose_out.top - dev->overlay_out_top; v4l2_rect_intersect(&dev->loop_vid_overlay, &r_overlay, &dev->loop_vid_copy); dev->loop_fb_copy = dev->loop_vid_overlay; /* shift dev->loop_fb_copy back again to the fb origin */ dev->loop_fb_copy.left -= dev->compose_out.left - dev->overlay_out_left; dev->loop_fb_copy.top -= dev->compose_out.top - dev->overlay_out_top; dev->loop_vid_overlay_cap = dev->loop_vid_overlay; v4l2_rect_scale(&dev->loop_vid_overlay_cap, &dev->crop_cap, &dev->compose_cap); dprintk(dev, 1, "loop_fb_copy: %dx%d@%dx%d loop_vid_overlay: %dx%d@%dx%d loop_vid_overlay_cap: %dx%d@%dx%d\n", dev->loop_fb_copy.width, dev->loop_fb_copy.height, dev->loop_fb_copy.left, dev->loop_fb_copy.top, dev->loop_vid_overlay.width, dev->loop_vid_overlay.height, dev->loop_vid_overlay.left, dev->loop_vid_overlay.top, dev->loop_vid_overlay_cap.width, dev->loop_vid_overlay_cap.height, dev->loop_vid_overlay_cap.left, dev->loop_vid_overlay_cap.top); } static void *plane_vaddr(struct tpg_data *tpg, struct vivid_buffer *buf, unsigned p, unsigned bpl[TPG_MAX_PLANES], unsigned h) { unsigned i; void *vbuf; if (p == 0 || tpg_g_buffers(tpg) > 1) return vb2_plane_vaddr(&buf->vb.vb2_buf, p); vbuf = vb2_plane_vaddr(&buf->vb.vb2_buf, 0); for (i = 0; i < p; i++) vbuf += bpl[i] * h / tpg->vdownsampling[i]; return vbuf; } static noinline_for_stack int vivid_copy_buffer(struct vivid_dev *dev, unsigned p, u8 *vcapbuf, struct vivid_buffer *vid_cap_buf) { bool blank = dev->must_blank[vid_cap_buf->vb.vb2_buf.index]; struct tpg_data *tpg = &dev->tpg; struct vivid_buffer *vid_out_buf = NULL; unsigned vdiv = dev->fmt_out->vdownsampling[p]; unsigned twopixsize = tpg_g_twopixelsize(tpg, p); unsigned img_width = tpg_hdiv(tpg, p, dev->compose_cap.width); unsigned img_height = dev->compose_cap.height; unsigned stride_cap = tpg->bytesperline[p]; unsigned stride_out = dev->bytesperline_out[p]; unsigned stride_osd = dev->display_byte_stride; unsigned hmax = (img_height * tpg->perc_fill) / 100; u8 *voutbuf; u8 *vosdbuf = NULL; unsigned y; bool blend = dev->fbuf_out_flags; /* Coarse scaling with Bresenham */ unsigned vid_out_int_part; unsigned vid_out_fract_part; unsigned vid_out_y = 0; unsigned vid_out_error = 0; unsigned vid_overlay_int_part = 0; unsigned vid_overlay_fract_part = 0; unsigned vid_overlay_y = 0; unsigned vid_overlay_error = 0; unsigned vid_cap_left = tpg_hdiv(tpg, p, dev->loop_vid_cap.left); unsigned vid_cap_right; bool quick; vid_out_int_part = dev->loop_vid_out.height / dev->loop_vid_cap.height; vid_out_fract_part = dev->loop_vid_out.height % dev->loop_vid_cap.height; if (!list_empty(&dev->vid_out_active)) vid_out_buf = list_entry(dev->vid_out_active.next, struct vivid_buffer, list); if (vid_out_buf == NULL) return -ENODATA; vid_cap_buf->vb.field = vid_out_buf->vb.field; voutbuf = plane_vaddr(tpg, vid_out_buf, p, dev->bytesperline_out, dev->fmt_out_rect.height); if (p < dev->fmt_out->buffers) voutbuf += vid_out_buf->vb.vb2_buf.planes[p].data_offset; voutbuf += tpg_hdiv(tpg, p, dev->loop_vid_out.left) + (dev->loop_vid_out.top / vdiv) * stride_out; vcapbuf += tpg_hdiv(tpg, p, dev->compose_cap.left) + (dev->compose_cap.top / vdiv) * stride_cap; if (dev->loop_vid_copy.width == 0 || dev->loop_vid_copy.height == 0) { /* * If there is nothing to copy, then just fill the capture window * with black. */ for (y = 0; y < hmax / vdiv; y++, vcapbuf += stride_cap) memcpy(vcapbuf, tpg->black_line[p], img_width); return 0; } if (dev->overlay_out_enabled && dev->loop_vid_overlay.width && dev->loop_vid_overlay.height) { vosdbuf = dev->video_vbase; vosdbuf += (dev->loop_fb_copy.left * twopixsize) / 2 + dev->loop_fb_copy.top * stride_osd; vid_overlay_int_part = dev->loop_vid_overlay.height / dev->loop_vid_overlay_cap.height; vid_overlay_fract_part = dev->loop_vid_overlay.height % dev->loop_vid_overlay_cap.height; } vid_cap_right = tpg_hdiv(tpg, p, dev->loop_vid_cap.left + dev->loop_vid_cap.width); /* quick is true if no video scaling is needed */ quick = dev->loop_vid_out.width == dev->loop_vid_cap.width; dev->cur_scaled_line = dev->loop_vid_out.height; for (y = 0; y < hmax; y += vdiv, vcapbuf += stride_cap) { /* osdline is true if this line requires overlay blending */ bool osdline = vosdbuf && y >= dev->loop_vid_overlay_cap.top && y < dev->loop_vid_overlay_cap.top + dev->loop_vid_overlay_cap.height; /* * If this line of the capture buffer doesn't get any video, then * just fill with black. */ if (y < dev->loop_vid_cap.top || y >= dev->loop_vid_cap.top + dev->loop_vid_cap.height) { memcpy(vcapbuf, tpg->black_line[p], img_width); continue; } /* fill the left border with black */ if (dev->loop_vid_cap.left) memcpy(vcapbuf, tpg->black_line[p], vid_cap_left); /* fill the right border with black */ if (vid_cap_right < img_width) memcpy(vcapbuf + vid_cap_right, tpg->black_line[p], img_width - vid_cap_right); if (quick && !osdline) { memcpy(vcapbuf + vid_cap_left, voutbuf + vid_out_y * stride_out, tpg_hdiv(tpg, p, dev->loop_vid_cap.width)); goto update_vid_out_y; } if (dev->cur_scaled_line == vid_out_y) { memcpy(vcapbuf + vid_cap_left, dev->scaled_line, tpg_hdiv(tpg, p, dev->loop_vid_cap.width)); goto update_vid_out_y; } if (!osdline) { scale_line(voutbuf + vid_out_y * stride_out, dev->scaled_line, tpg_hdiv(tpg, p, dev->loop_vid_out.width), tpg_hdiv(tpg, p, dev->loop_vid_cap.width), tpg_g_twopixelsize(tpg, p)); } else { /* * Offset in bytes within loop_vid_copy to the start of the * loop_vid_overlay rectangle. */ unsigned offset = ((dev->loop_vid_overlay.left - dev->loop_vid_copy.left) * twopixsize) / 2; u8 *osd = vosdbuf + vid_overlay_y * stride_osd; scale_line(voutbuf + vid_out_y * stride_out, dev->blended_line, dev->loop_vid_out.width, dev->loop_vid_copy.width, tpg_g_twopixelsize(tpg, p)); if (blend) blend_line(dev, vid_overlay_y + dev->loop_vid_overlay.top, dev->loop_vid_overlay.left, dev->blended_line + offset, osd, dev->loop_vid_overlay.width, twopixsize / 2); else memcpy(dev->blended_line + offset, osd, (dev->loop_vid_overlay.width * twopixsize) / 2); scale_line(dev->blended_line, dev->scaled_line, dev->loop_vid_copy.width, dev->loop_vid_cap.width, tpg_g_twopixelsize(tpg, p)); } dev->cur_scaled_line = vid_out_y; memcpy(vcapbuf + vid_cap_left, dev->scaled_line, tpg_hdiv(tpg, p, dev->loop_vid_cap.width)); update_vid_out_y: if (osdline) { vid_overlay_y += vid_overlay_int_part; vid_overlay_error += vid_overlay_fract_part; if (vid_overlay_error >= dev->loop_vid_overlay_cap.height) { vid_overlay_error -= dev->loop_vid_overlay_cap.height; vid_overlay_y++; } } vid_out_y += vid_out_int_part; vid_out_error += vid_out_fract_part; if (vid_out_error >= dev->loop_vid_cap.height / vdiv) { vid_out_error -= dev->loop_vid_cap.height / vdiv; vid_out_y++; } } if (!blank) return 0; for (; y < img_height; y += vdiv, vcapbuf += stride_cap) memcpy(vcapbuf, tpg->contrast_line[p], img_width); return 0; } static void vivid_fillbuff(struct vivid_dev *dev, struct vivid_buffer *buf) { struct tpg_data *tpg = &dev->tpg; unsigned factor = V4L2_FIELD_HAS_T_OR_B(dev->field_cap) ? 2 : 1; unsigned line_height = 16 / factor; bool is_tv = vivid_is_sdtv_cap(dev); bool is_60hz = is_tv && (dev->std_cap[dev->input] & V4L2_STD_525_60); unsigned p; int line = 1; u8 *basep[TPG_MAX_PLANES][2]; unsigned ms; char str[100]; s32 gain; bool is_loop = false; if (dev->loop_video && dev->can_loop_video && ((vivid_is_svid_cap(dev) && !VIVID_INVALID_SIGNAL(dev->std_signal_mode[dev->input])) || (vivid_is_hdmi_cap(dev) && !VIVID_INVALID_SIGNAL(dev->dv_timings_signal_mode[dev->input])))) is_loop = true; buf->vb.sequence = dev->vid_cap_seq_count; v4l2_ctrl_s_ctrl(dev->ro_int32, buf->vb.sequence & 0xff); if (dev->field_cap == V4L2_FIELD_ALTERNATE) { /* * 60 Hz standards start with the bottom field, 50 Hz standards * with the top field. So if the 0-based seq_count is even, * then the field is TOP for 50 Hz and BOTTOM for 60 Hz * standards. */ buf->vb.field = ((dev->vid_cap_seq_count & 1) ^ is_60hz) ? V4L2_FIELD_BOTTOM : V4L2_FIELD_TOP; /* * The sequence counter counts frames, not fields. So divide * by two. */ buf->vb.sequence /= 2; } else { buf->vb.field = dev->field_cap; } tpg_s_field(tpg, buf->vb.field, dev->field_cap == V4L2_FIELD_ALTERNATE); tpg_s_perc_fill_blank(tpg, dev->must_blank[buf->vb.vb2_buf.index]); vivid_precalc_copy_rects(dev); for (p = 0; p < tpg_g_planes(tpg); p++) { void *vbuf = plane_vaddr(tpg, buf, p, tpg->bytesperline, tpg->buf_height); /* * The first plane of a multiplanar format has a non-zero * data_offset. This helps testing whether the application * correctly supports non-zero data offsets. */ if (p < tpg_g_buffers(tpg) && dev->fmt_cap->data_offset[p]) { memset(vbuf, dev->fmt_cap->data_offset[p] & 0xff, dev->fmt_cap->data_offset[p]); vbuf += dev->fmt_cap->data_offset[p]; } tpg_calc_text_basep(tpg, basep, p, vbuf); if (!is_loop || vivid_copy_buffer(dev, p, vbuf, buf)) tpg_fill_plane_buffer(tpg, vivid_get_std_cap(dev), p, vbuf); } dev->must_blank[buf->vb.vb2_buf.index] = false; /* Updates stream time, only update at the start of a new frame. */ if (dev->field_cap != V4L2_FIELD_ALTERNATE || (dev->vid_cap_seq_count & 1) == 0) dev->ms_vid_cap = jiffies_to_msecs(jiffies - dev->jiffies_vid_cap); ms = dev->ms_vid_cap; if (dev->osd_mode <= 1) { snprintf(str, sizeof(str), " %02d:%02d:%02d:%03d %u%s", (ms / (60 * 60 * 1000)) % 24, (ms / (60 * 1000)) % 60, (ms / 1000) % 60, ms % 1000, buf->vb.sequence, (dev->field_cap == V4L2_FIELD_ALTERNATE) ? (buf->vb.field == V4L2_FIELD_TOP ? " top" : " bottom") : ""); tpg_gen_text(tpg, basep, line++ * line_height, 16, str); } if (dev->osd_mode == 0) { snprintf(str, sizeof(str), " %dx%d, input %d ", dev->src_rect.width, dev->src_rect.height, dev->input); tpg_gen_text(tpg, basep, line++ * line_height, 16, str); gain = v4l2_ctrl_g_ctrl(dev->gain); mutex_lock(dev->ctrl_hdl_user_vid.lock); snprintf(str, sizeof(str), " brightness %3d, contrast %3d, saturation %3d, hue %d ", dev->brightness->cur.val, dev->contrast->cur.val, dev->saturation->cur.val, dev->hue->cur.val); tpg_gen_text(tpg, basep, line++ * line_height, 16, str); snprintf(str, sizeof(str), " autogain %d, gain %3d, alpha 0x%02x ", dev->autogain->cur.val, gain, dev->alpha->cur.val); mutex_unlock(dev->ctrl_hdl_user_vid.lock); tpg_gen_text(tpg, basep, line++ * line_height, 16, str); mutex_lock(dev->ctrl_hdl_user_aud.lock); snprintf(str, sizeof(str), " volume %3d, mute %d ", dev->volume->cur.val, dev->mute->cur.val); mutex_unlock(dev->ctrl_hdl_user_aud.lock); tpg_gen_text(tpg, basep, line++ * line_height, 16, str); mutex_lock(dev->ctrl_hdl_user_gen.lock); snprintf(str, sizeof(str), " int32 %d, ro_int32 %d, int64 %lld, bitmask %08x ", dev->int32->cur.val, dev->ro_int32->cur.val, *dev->int64->p_cur.p_s64, dev->bitmask->cur.val); tpg_gen_text(tpg, basep, line++ * line_height, 16, str); snprintf(str, sizeof(str), " boolean %d, menu %s, string \"%s\" ", dev->boolean->cur.val, dev->menu->qmenu[dev->menu->cur.val], dev->string->p_cur.p_char); tpg_gen_text(tpg, basep, line++ * line_height, 16, str); snprintf(str, sizeof(str), " integer_menu %lld, value %d ", dev->int_menu->qmenu_int[dev->int_menu->cur.val], dev->int_menu->cur.val); mutex_unlock(dev->ctrl_hdl_user_gen.lock); tpg_gen_text(tpg, basep, line++ * line_height, 16, str); if (dev->button_pressed) { dev->button_pressed--; snprintf(str, sizeof(str), " button pressed!"); tpg_gen_text(tpg, basep, line++ * line_height, 16, str); } if (dev->osd[0]) { if (vivid_is_hdmi_cap(dev)) { snprintf(str, sizeof(str), " OSD \"%s\"", dev->osd); tpg_gen_text(tpg, basep, line++ * line_height, 16, str); } if (dev->osd_jiffies && time_is_before_jiffies(dev->osd_jiffies + 5 * HZ)) { dev->osd[0] = 0; dev->osd_jiffies = 0; } } } } static void vivid_cap_update_frame_period(struct vivid_dev *dev) { u64 f_period; f_period = (u64)dev->timeperframe_vid_cap.numerator * 1000000000; if (WARN_ON(dev->timeperframe_vid_cap.denominator == 0)) dev->timeperframe_vid_cap.denominator = 1; do_div(f_period, dev->timeperframe_vid_cap.denominator); if (dev->field_cap == V4L2_FIELD_ALTERNATE) f_period >>= 1; /* * If "End of Frame", then offset the exposure time by 0.9 * of the frame period. */ dev->cap_frame_eof_offset = f_period * 9; do_div(dev->cap_frame_eof_offset, 10); dev->cap_frame_period = f_period; } static noinline_for_stack void vivid_thread_vid_cap_tick(struct vivid_dev *dev, int dropped_bufs) { struct vivid_buffer *vid_cap_buf = NULL; struct vivid_buffer *vbi_cap_buf = NULL; struct vivid_buffer *meta_cap_buf = NULL; u64 f_time = 0; dprintk(dev, 1, "Video Capture Thread Tick\n"); while (dropped_bufs-- > 1) tpg_update_mv_count(&dev->tpg, dev->field_cap == V4L2_FIELD_NONE || dev->field_cap == V4L2_FIELD_ALTERNATE); /* Drop a certain percentage of buffers. */ if (dev->perc_dropped_buffers && get_random_u32_below(100) < dev->perc_dropped_buffers) goto update_mv; spin_lock(&dev->slock); if (!list_empty(&dev->vid_cap_active)) { vid_cap_buf = list_entry(dev->vid_cap_active.next, struct vivid_buffer, list); list_del(&vid_cap_buf->list); } if (!list_empty(&dev->vbi_cap_active)) { if (dev->field_cap != V4L2_FIELD_ALTERNATE || (dev->vbi_cap_seq_count & 1)) { vbi_cap_buf = list_entry(dev->vbi_cap_active.next, struct vivid_buffer, list); list_del(&vbi_cap_buf->list); } } if (!list_empty(&dev->meta_cap_active)) { meta_cap_buf = list_entry(dev->meta_cap_active.next, struct vivid_buffer, list); list_del(&meta_cap_buf->list); } spin_unlock(&dev->slock); if (!vid_cap_buf && !vbi_cap_buf && !meta_cap_buf) goto update_mv; f_time = ktime_get_ns() + dev->time_wrap_offset; if (vid_cap_buf) { v4l2_ctrl_request_setup(vid_cap_buf->vb.vb2_buf.req_obj.req, &dev->ctrl_hdl_vid_cap); /* Fill buffer */ vivid_fillbuff(dev, vid_cap_buf); dprintk(dev, 1, "filled buffer %d\n", vid_cap_buf->vb.vb2_buf.index); v4l2_ctrl_request_complete(vid_cap_buf->vb.vb2_buf.req_obj.req, &dev->ctrl_hdl_vid_cap); vb2_buffer_done(&vid_cap_buf->vb.vb2_buf, dev->dqbuf_error ? VB2_BUF_STATE_ERROR : VB2_BUF_STATE_DONE); dprintk(dev, 2, "vid_cap buffer %d done\n", vid_cap_buf->vb.vb2_buf.index); vid_cap_buf->vb.vb2_buf.timestamp = f_time; if (!dev->tstamp_src_is_soe) vid_cap_buf->vb.vb2_buf.timestamp += dev->cap_frame_eof_offset; } if (vbi_cap_buf) { u64 vbi_period; v4l2_ctrl_request_setup(vbi_cap_buf->vb.vb2_buf.req_obj.req, &dev->ctrl_hdl_vbi_cap); if (vbi_cap_buf->vb.vb2_buf.type == V4L2_BUF_TYPE_SLICED_VBI_CAPTURE) vivid_sliced_vbi_cap_process(dev, vbi_cap_buf); else vivid_raw_vbi_cap_process(dev, vbi_cap_buf); v4l2_ctrl_request_complete(vbi_cap_buf->vb.vb2_buf.req_obj.req, &dev->ctrl_hdl_vbi_cap); vb2_buffer_done(&vbi_cap_buf->vb.vb2_buf, dev->dqbuf_error ? VB2_BUF_STATE_ERROR : VB2_BUF_STATE_DONE); dprintk(dev, 2, "vbi_cap %d done\n", vbi_cap_buf->vb.vb2_buf.index); /* If capturing a VBI, offset by 0.05 */ vbi_period = dev->cap_frame_period * 5; do_div(vbi_period, 100); vbi_cap_buf->vb.vb2_buf.timestamp = f_time + dev->cap_frame_eof_offset + vbi_period; } if (meta_cap_buf) { v4l2_ctrl_request_setup(meta_cap_buf->vb.vb2_buf.req_obj.req, &dev->ctrl_hdl_meta_cap); vivid_meta_cap_fillbuff(dev, meta_cap_buf, f_time); v4l2_ctrl_request_complete(meta_cap_buf->vb.vb2_buf.req_obj.req, &dev->ctrl_hdl_meta_cap); vb2_buffer_done(&meta_cap_buf->vb.vb2_buf, dev->dqbuf_error ? VB2_BUF_STATE_ERROR : VB2_BUF_STATE_DONE); dprintk(dev, 2, "meta_cap %d done\n", meta_cap_buf->vb.vb2_buf.index); meta_cap_buf->vb.vb2_buf.timestamp = f_time + dev->cap_frame_eof_offset; } dev->dqbuf_error = false; update_mv: /* Update the test pattern movement counters */ tpg_update_mv_count(&dev->tpg, dev->field_cap == V4L2_FIELD_NONE || dev->field_cap == V4L2_FIELD_ALTERNATE); } static int vivid_thread_vid_cap(void *data) { struct vivid_dev *dev = data; u64 numerators_since_start; u64 buffers_since_start; u64 next_jiffies_since_start; unsigned long jiffies_since_start; unsigned long cur_jiffies; unsigned wait_jiffies; unsigned numerator; unsigned denominator; int dropped_bufs; dprintk(dev, 1, "Video Capture Thread Start\n"); set_freezable(); /* Resets frame counters */ dev->cap_seq_offset = 0; dev->cap_seq_count = 0; dev->cap_seq_resync = false; dev->jiffies_vid_cap = jiffies; dev->cap_stream_start = ktime_get_ns(); if (dev->time_wrap) dev->time_wrap_offset = dev->time_wrap - dev->cap_stream_start; else dev->time_wrap_offset = 0; vivid_cap_update_frame_period(dev); for (;;) { try_to_freeze(); if (kthread_should_stop()) break; if (!mutex_trylock(&dev->mutex)) { schedule(); continue; } cur_jiffies = jiffies; if (dev->cap_seq_resync) { dev->jiffies_vid_cap = cur_jiffies; dev->cap_seq_offset = dev->cap_seq_count + 1; dev->cap_seq_count = 0; dev->cap_stream_start += dev->cap_frame_period * dev->cap_seq_offset; vivid_cap_update_frame_period(dev); dev->cap_seq_resync = false; } numerator = dev->timeperframe_vid_cap.numerator; denominator = dev->timeperframe_vid_cap.denominator; if (dev->field_cap == V4L2_FIELD_ALTERNATE) denominator *= 2; /* Calculate the number of jiffies since we started streaming */ jiffies_since_start = cur_jiffies - dev->jiffies_vid_cap; /* Get the number of buffers streamed since the start */ buffers_since_start = (u64)jiffies_since_start * denominator + (HZ * numerator) / 2; do_div(buffers_since_start, HZ * numerator); /* * After more than 0xf0000000 (rounded down to a multiple of * 'jiffies-per-day' to ease jiffies_to_msecs calculation) * jiffies have passed since we started streaming reset the * counters and keep track of the sequence offset. */ if (jiffies_since_start > JIFFIES_RESYNC) { dev->jiffies_vid_cap = cur_jiffies; dev->cap_seq_offset = buffers_since_start; buffers_since_start = 0; } dropped_bufs = buffers_since_start + dev->cap_seq_offset - dev->cap_seq_count; dev->cap_seq_count = buffers_since_start + dev->cap_seq_offset; dev->vid_cap_seq_count = dev->cap_seq_count - dev->vid_cap_seq_start; dev->vbi_cap_seq_count = dev->cap_seq_count - dev->vbi_cap_seq_start; dev->meta_cap_seq_count = dev->cap_seq_count - dev->meta_cap_seq_start; vivid_thread_vid_cap_tick(dev, dropped_bufs); /* * Calculate the number of 'numerators' streamed since we started, * including the current buffer. */ numerators_since_start = ++buffers_since_start * numerator; /* And the number of jiffies since we started */ jiffies_since_start = jiffies - dev->jiffies_vid_cap; mutex_unlock(&dev->mutex); /* * Calculate when that next buffer is supposed to start * in jiffies since we started streaming. */ next_jiffies_since_start = numerators_since_start * HZ + denominator / 2; do_div(next_jiffies_since_start, denominator); /* If it is in the past, then just schedule asap */ if (next_jiffies_since_start < jiffies_since_start) next_jiffies_since_start = jiffies_since_start; wait_jiffies = next_jiffies_since_start - jiffies_since_start; while (time_is_after_jiffies(cur_jiffies + wait_jiffies) && !kthread_should_stop()) schedule(); } dprintk(dev, 1, "Video Capture Thread End\n"); return 0; } static void vivid_grab_controls(struct vivid_dev *dev, bool grab) { v4l2_ctrl_grab(dev->ctrl_has_crop_cap, grab); v4l2_ctrl_grab(dev->ctrl_has_compose_cap, grab); v4l2_ctrl_grab(dev->ctrl_has_scaler_cap, grab); } int vivid_start_generating_vid_cap(struct vivid_dev *dev, bool *pstreaming) { dprintk(dev, 1, "%s\n", __func__); if (dev->kthread_vid_cap) { u32 seq_count = dev->cap_seq_count + dev->seq_wrap * 128; if (pstreaming == &dev->vid_cap_streaming) dev->vid_cap_seq_start = seq_count; else if (pstreaming == &dev->vbi_cap_streaming) dev->vbi_cap_seq_start = seq_count; else dev->meta_cap_seq_start = seq_count; *pstreaming = true; return 0; } /* Resets frame counters */ tpg_init_mv_count(&dev->tpg); dev->vid_cap_seq_start = dev->seq_wrap * 128; dev->vbi_cap_seq_start = dev->seq_wrap * 128; dev->meta_cap_seq_start = dev->seq_wrap * 128; dev->kthread_vid_cap = kthread_run(vivid_thread_vid_cap, dev, "%s-vid-cap", dev->v4l2_dev.name); if (IS_ERR(dev->kthread_vid_cap)) { int err = PTR_ERR(dev->kthread_vid_cap); dev->kthread_vid_cap = NULL; v4l2_err(&dev->v4l2_dev, "kernel_thread() failed\n"); return err; } *pstreaming = true; vivid_grab_controls(dev, true); dprintk(dev, 1, "returning from %s\n", __func__); return 0; } void vivid_stop_generating_vid_cap(struct vivid_dev *dev, bool *pstreaming) { dprintk(dev, 1, "%s\n", __func__); if (dev->kthread_vid_cap == NULL) return; *pstreaming = false; if (pstreaming == &dev->vid_cap_streaming) { /* Release all active buffers */ while (!list_empty(&dev->vid_cap_active)) { struct vivid_buffer *buf; buf = list_entry(dev->vid_cap_active.next, struct vivid_buffer, list); list_del(&buf->list); v4l2_ctrl_request_complete(buf->vb.vb2_buf.req_obj.req, &dev->ctrl_hdl_vid_cap); vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR); dprintk(dev, 2, "vid_cap buffer %d done\n", buf->vb.vb2_buf.index); } } if (pstreaming == &dev->vbi_cap_streaming) { while (!list_empty(&dev->vbi_cap_active)) { struct vivid_buffer *buf; buf = list_entry(dev->vbi_cap_active.next, struct vivid_buffer, list); list_del(&buf->list); v4l2_ctrl_request_complete(buf->vb.vb2_buf.req_obj.req, &dev->ctrl_hdl_vbi_cap); vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR); dprintk(dev, 2, "vbi_cap buffer %d done\n", buf->vb.vb2_buf.index); } } if (pstreaming == &dev->meta_cap_streaming) { while (!list_empty(&dev->meta_cap_active)) { struct vivid_buffer *buf; buf = list_entry(dev->meta_cap_active.next, struct vivid_buffer, list); list_del(&buf->list); v4l2_ctrl_request_complete(buf->vb.vb2_buf.req_obj.req, &dev->ctrl_hdl_meta_cap); vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR); dprintk(dev, 2, "meta_cap buffer %d done\n", buf->vb.vb2_buf.index); } } if (dev->vid_cap_streaming || dev->vbi_cap_streaming || dev->meta_cap_streaming) return; /* shutdown control thread */ vivid_grab_controls(dev, false); kthread_stop(dev->kthread_vid_cap); dev->kthread_vid_cap = NULL; }
linux-master
drivers/media/test-drivers/vivid/vivid-kthread-cap.c
// SPDX-License-Identifier: GPL-2.0-only /* * vivid-vbi-cap.c - vbi capture support functions. * * Copyright 2014 Cisco Systems, Inc. and/or its affiliates. All rights reserved. */ #include <linux/errno.h> #include <linux/kernel.h> #include <linux/videodev2.h> #include <media/v4l2-common.h> #include "vivid-core.h" #include "vivid-kthread-cap.h" #include "vivid-vbi-cap.h" #include "vivid-vbi-gen.h" static void vivid_sliced_vbi_cap_fill(struct vivid_dev *dev, unsigned seqnr) { struct vivid_vbi_gen_data *vbi_gen = &dev->vbi_gen; bool is_60hz = dev->std_cap[dev->input] & V4L2_STD_525_60; vivid_vbi_gen_sliced(vbi_gen, is_60hz, seqnr); if (!is_60hz) { if (dev->loop_video) { if (dev->vbi_out_have_wss) { vbi_gen->data[12].data[0] = dev->vbi_out_wss[0]; vbi_gen->data[12].data[1] = dev->vbi_out_wss[1]; } else { vbi_gen->data[12].id = 0; } } else { switch (tpg_g_video_aspect(&dev->tpg)) { case TPG_VIDEO_ASPECT_14X9_CENTRE: vbi_gen->data[12].data[0] = 0x01; break; case TPG_VIDEO_ASPECT_16X9_CENTRE: vbi_gen->data[12].data[0] = 0x0b; break; case TPG_VIDEO_ASPECT_16X9_ANAMORPHIC: vbi_gen->data[12].data[0] = 0x07; break; case TPG_VIDEO_ASPECT_4X3: default: vbi_gen->data[12].data[0] = 0x08; break; } } } else if (dev->loop_video && is_60hz) { if (dev->vbi_out_have_cc[0]) { vbi_gen->data[0].data[0] = dev->vbi_out_cc[0][0]; vbi_gen->data[0].data[1] = dev->vbi_out_cc[0][1]; } else { vbi_gen->data[0].id = 0; } if (dev->vbi_out_have_cc[1]) { vbi_gen->data[1].data[0] = dev->vbi_out_cc[1][0]; vbi_gen->data[1].data[1] = dev->vbi_out_cc[1][1]; } else { vbi_gen->data[1].id = 0; } } } static void vivid_g_fmt_vbi_cap(struct vivid_dev *dev, struct v4l2_vbi_format *vbi) { bool is_60hz = dev->std_cap[dev->input] & V4L2_STD_525_60; vbi->sampling_rate = 27000000; vbi->offset = 24; vbi->samples_per_line = 1440; vbi->sample_format = V4L2_PIX_FMT_GREY; vbi->start[0] = is_60hz ? V4L2_VBI_ITU_525_F1_START + 9 : V4L2_VBI_ITU_625_F1_START + 5; vbi->start[1] = is_60hz ? V4L2_VBI_ITU_525_F2_START + 9 : V4L2_VBI_ITU_625_F2_START + 5; vbi->count[0] = vbi->count[1] = is_60hz ? 12 : 18; vbi->flags = dev->vbi_cap_interlaced ? V4L2_VBI_INTERLACED : 0; vbi->reserved[0] = 0; vbi->reserved[1] = 0; } void vivid_raw_vbi_cap_process(struct vivid_dev *dev, struct vivid_buffer *buf) { struct v4l2_vbi_format vbi; u8 *vbuf = vb2_plane_vaddr(&buf->vb.vb2_buf, 0); vivid_g_fmt_vbi_cap(dev, &vbi); buf->vb.sequence = dev->vbi_cap_seq_count; if (dev->field_cap == V4L2_FIELD_ALTERNATE) buf->vb.sequence /= 2; vivid_sliced_vbi_cap_fill(dev, buf->vb.sequence); memset(vbuf, 0x10, vb2_plane_size(&buf->vb.vb2_buf, 0)); if (!VIVID_INVALID_SIGNAL(dev->std_signal_mode[dev->input])) vivid_vbi_gen_raw(&dev->vbi_gen, &vbi, vbuf); } void vivid_sliced_vbi_cap_process(struct vivid_dev *dev, struct vivid_buffer *buf) { struct v4l2_sliced_vbi_data *vbuf = vb2_plane_vaddr(&buf->vb.vb2_buf, 0); buf->vb.sequence = dev->vbi_cap_seq_count; if (dev->field_cap == V4L2_FIELD_ALTERNATE) buf->vb.sequence /= 2; vivid_sliced_vbi_cap_fill(dev, buf->vb.sequence); memset(vbuf, 0, vb2_plane_size(&buf->vb.vb2_buf, 0)); if (!VIVID_INVALID_SIGNAL(dev->std_signal_mode[dev->input])) { unsigned i; for (i = 0; i < 25; i++) vbuf[i] = dev->vbi_gen.data[i]; } } static int vbi_cap_queue_setup(struct vb2_queue *vq, unsigned *nbuffers, unsigned *nplanes, unsigned sizes[], struct device *alloc_devs[]) { struct vivid_dev *dev = vb2_get_drv_priv(vq); bool is_60hz = dev->std_cap[dev->input] & V4L2_STD_525_60; unsigned size = vq->type == V4L2_BUF_TYPE_SLICED_VBI_CAPTURE ? 36 * sizeof(struct v4l2_sliced_vbi_data) : 1440 * 2 * (is_60hz ? 12 : 18); if (!vivid_is_sdtv_cap(dev)) return -EINVAL; sizes[0] = size; if (vq->num_buffers + *nbuffers < 2) *nbuffers = 2 - vq->num_buffers; *nplanes = 1; return 0; } static int vbi_cap_buf_prepare(struct vb2_buffer *vb) { struct vivid_dev *dev = vb2_get_drv_priv(vb->vb2_queue); bool is_60hz = dev->std_cap[dev->input] & V4L2_STD_525_60; unsigned size = vb->vb2_queue->type == V4L2_BUF_TYPE_SLICED_VBI_CAPTURE ? 36 * sizeof(struct v4l2_sliced_vbi_data) : 1440 * 2 * (is_60hz ? 12 : 18); dprintk(dev, 1, "%s\n", __func__); if (dev->buf_prepare_error) { /* * Error injection: test what happens if buf_prepare() returns * an error. */ dev->buf_prepare_error = false; return -EINVAL; } if (vb2_plane_size(vb, 0) < size) { dprintk(dev, 1, "%s data will not fit into plane (%lu < %u)\n", __func__, vb2_plane_size(vb, 0), size); return -EINVAL; } vb2_set_plane_payload(vb, 0, size); return 0; } static void vbi_cap_buf_queue(struct vb2_buffer *vb) { struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb); struct vivid_dev *dev = vb2_get_drv_priv(vb->vb2_queue); struct vivid_buffer *buf = container_of(vbuf, struct vivid_buffer, vb); dprintk(dev, 1, "%s\n", __func__); spin_lock(&dev->slock); list_add_tail(&buf->list, &dev->vbi_cap_active); spin_unlock(&dev->slock); } static int vbi_cap_start_streaming(struct vb2_queue *vq, unsigned count) { struct vivid_dev *dev = vb2_get_drv_priv(vq); int err; dprintk(dev, 1, "%s\n", __func__); dev->vbi_cap_seq_count = 0; if (dev->start_streaming_error) { dev->start_streaming_error = false; err = -EINVAL; } else { err = vivid_start_generating_vid_cap(dev, &dev->vbi_cap_streaming); } if (err) { struct vivid_buffer *buf, *tmp; list_for_each_entry_safe(buf, tmp, &dev->vbi_cap_active, list) { list_del(&buf->list); vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_QUEUED); } } return err; } /* abort streaming and wait for last buffer */ static void vbi_cap_stop_streaming(struct vb2_queue *vq) { struct vivid_dev *dev = vb2_get_drv_priv(vq); dprintk(dev, 1, "%s\n", __func__); vivid_stop_generating_vid_cap(dev, &dev->vbi_cap_streaming); } static void vbi_cap_buf_request_complete(struct vb2_buffer *vb) { struct vivid_dev *dev = vb2_get_drv_priv(vb->vb2_queue); v4l2_ctrl_request_complete(vb->req_obj.req, &dev->ctrl_hdl_vbi_cap); } const struct vb2_ops vivid_vbi_cap_qops = { .queue_setup = vbi_cap_queue_setup, .buf_prepare = vbi_cap_buf_prepare, .buf_queue = vbi_cap_buf_queue, .start_streaming = vbi_cap_start_streaming, .stop_streaming = vbi_cap_stop_streaming, .buf_request_complete = vbi_cap_buf_request_complete, .wait_prepare = vb2_ops_wait_prepare, .wait_finish = vb2_ops_wait_finish, }; int vidioc_g_fmt_vbi_cap(struct file *file, void *priv, struct v4l2_format *f) { struct vivid_dev *dev = video_drvdata(file); struct v4l2_vbi_format *vbi = &f->fmt.vbi; if (!vivid_is_sdtv_cap(dev) || !dev->has_raw_vbi_cap) return -EINVAL; vivid_g_fmt_vbi_cap(dev, vbi); return 0; } int vidioc_s_fmt_vbi_cap(struct file *file, void *priv, struct v4l2_format *f) { struct vivid_dev *dev = video_drvdata(file); int ret = vidioc_g_fmt_vbi_cap(file, priv, f); if (ret) return ret; if (f->type != V4L2_BUF_TYPE_VBI_CAPTURE && vb2_is_busy(&dev->vb_vbi_cap_q)) return -EBUSY; return 0; } void vivid_fill_service_lines(struct v4l2_sliced_vbi_format *vbi, u32 service_set) { vbi->io_size = sizeof(struct v4l2_sliced_vbi_data) * 36; vbi->service_set = service_set; memset(vbi->service_lines, 0, sizeof(vbi->service_lines)); memset(vbi->reserved, 0, sizeof(vbi->reserved)); if (vbi->service_set == 0) return; if (vbi->service_set & V4L2_SLICED_CAPTION_525) { vbi->service_lines[0][21] = V4L2_SLICED_CAPTION_525; vbi->service_lines[1][21] = V4L2_SLICED_CAPTION_525; } if (vbi->service_set & V4L2_SLICED_WSS_625) { unsigned i; for (i = 7; i <= 18; i++) vbi->service_lines[0][i] = vbi->service_lines[1][i] = V4L2_SLICED_TELETEXT_B; vbi->service_lines[0][23] = V4L2_SLICED_WSS_625; } } int vidioc_g_fmt_sliced_vbi_cap(struct file *file, void *fh, struct v4l2_format *fmt) { struct vivid_dev *dev = video_drvdata(file); struct v4l2_sliced_vbi_format *vbi = &fmt->fmt.sliced; if (!vivid_is_sdtv_cap(dev) || !dev->has_sliced_vbi_cap) return -EINVAL; vivid_fill_service_lines(vbi, dev->service_set_cap); return 0; } int vidioc_try_fmt_sliced_vbi_cap(struct file *file, void *fh, struct v4l2_format *fmt) { struct vivid_dev *dev = video_drvdata(file); struct v4l2_sliced_vbi_format *vbi = &fmt->fmt.sliced; bool is_60hz = dev->std_cap[dev->input] & V4L2_STD_525_60; u32 service_set = vbi->service_set; if (!vivid_is_sdtv_cap(dev) || !dev->has_sliced_vbi_cap) return -EINVAL; service_set &= is_60hz ? V4L2_SLICED_CAPTION_525 : V4L2_SLICED_WSS_625 | V4L2_SLICED_TELETEXT_B; vivid_fill_service_lines(vbi, service_set); return 0; } int vidioc_s_fmt_sliced_vbi_cap(struct file *file, void *fh, struct v4l2_format *fmt) { struct vivid_dev *dev = video_drvdata(file); struct v4l2_sliced_vbi_format *vbi = &fmt->fmt.sliced; int ret = vidioc_try_fmt_sliced_vbi_cap(file, fh, fmt); if (ret) return ret; if (fmt->type != V4L2_BUF_TYPE_SLICED_VBI_CAPTURE && vb2_is_busy(&dev->vb_vbi_cap_q)) return -EBUSY; dev->service_set_cap = vbi->service_set; return 0; } int vidioc_g_sliced_vbi_cap(struct file *file, void *fh, struct v4l2_sliced_vbi_cap *cap) { struct vivid_dev *dev = video_drvdata(file); struct video_device *vdev = video_devdata(file); bool is_60hz; if (vdev->vfl_dir == VFL_DIR_RX) { is_60hz = dev->std_cap[dev->input] & V4L2_STD_525_60; if (!vivid_is_sdtv_cap(dev) || !dev->has_sliced_vbi_cap || cap->type != V4L2_BUF_TYPE_SLICED_VBI_CAPTURE) return -EINVAL; } else { is_60hz = dev->std_out & V4L2_STD_525_60; if (!vivid_is_svid_out(dev) || !dev->has_sliced_vbi_out || cap->type != V4L2_BUF_TYPE_SLICED_VBI_OUTPUT) return -EINVAL; } cap->service_set = is_60hz ? V4L2_SLICED_CAPTION_525 : V4L2_SLICED_WSS_625 | V4L2_SLICED_TELETEXT_B; if (is_60hz) { cap->service_lines[0][21] = V4L2_SLICED_CAPTION_525; cap->service_lines[1][21] = V4L2_SLICED_CAPTION_525; } else { unsigned i; for (i = 7; i <= 18; i++) cap->service_lines[0][i] = cap->service_lines[1][i] = V4L2_SLICED_TELETEXT_B; cap->service_lines[0][23] = V4L2_SLICED_WSS_625; } return 0; }
linux-master
drivers/media/test-drivers/vivid/vivid-vbi-cap.c
// SPDX-License-Identifier: GPL-2.0-only /* * vivid-kthread-touch.c - touch capture thread support functions. * */ #include <linux/freezer.h> #include <linux/jiffies.h> #include "vivid-core.h" #include "vivid-kthread-touch.h" #include "vivid-touch-cap.h" static noinline_for_stack void vivid_thread_tch_cap_tick(struct vivid_dev *dev, int dropped_bufs) { struct vivid_buffer *tch_cap_buf = NULL; spin_lock(&dev->slock); if (!list_empty(&dev->touch_cap_active)) { tch_cap_buf = list_entry(dev->touch_cap_active.next, struct vivid_buffer, list); list_del(&tch_cap_buf->list); } spin_unlock(&dev->slock); if (tch_cap_buf) { v4l2_ctrl_request_setup(tch_cap_buf->vb.vb2_buf.req_obj.req, &dev->ctrl_hdl_touch_cap); vivid_fillbuff_tch(dev, tch_cap_buf); v4l2_ctrl_request_complete(tch_cap_buf->vb.vb2_buf.req_obj.req, &dev->ctrl_hdl_touch_cap); vb2_buffer_done(&tch_cap_buf->vb.vb2_buf, dev->dqbuf_error ? VB2_BUF_STATE_ERROR : VB2_BUF_STATE_DONE); dprintk(dev, 2, "touch_cap buffer %d done\n", tch_cap_buf->vb.vb2_buf.index); tch_cap_buf->vb.vb2_buf.timestamp = ktime_get_ns() + dev->time_wrap_offset; } dev->dqbuf_error = false; } static int vivid_thread_touch_cap(void *data) { struct vivid_dev *dev = data; u64 numerators_since_start; u64 buffers_since_start; u64 next_jiffies_since_start; unsigned long jiffies_since_start; unsigned long cur_jiffies; unsigned int wait_jiffies; unsigned int numerator; unsigned int denominator; int dropped_bufs; dprintk(dev, 1, "Touch Capture Thread Start\n"); set_freezable(); /* Resets frame counters */ dev->touch_cap_seq_offset = 0; dev->touch_cap_seq_count = 0; dev->touch_cap_seq_resync = false; dev->jiffies_touch_cap = jiffies; if (dev->time_wrap) dev->time_wrap_offset = dev->time_wrap - ktime_get_ns(); else dev->time_wrap_offset = 0; for (;;) { try_to_freeze(); if (kthread_should_stop()) break; if (!mutex_trylock(&dev->mutex)) { schedule(); continue; } cur_jiffies = jiffies; if (dev->touch_cap_seq_resync) { dev->jiffies_touch_cap = cur_jiffies; dev->touch_cap_seq_offset = dev->touch_cap_seq_count + 1; dev->touch_cap_seq_count = 0; dev->cap_seq_resync = false; } denominator = dev->timeperframe_tch_cap.denominator; numerator = dev->timeperframe_tch_cap.numerator; /* Calculate the number of jiffies since we started streaming */ jiffies_since_start = cur_jiffies - dev->jiffies_touch_cap; /* Get the number of buffers streamed since the start */ buffers_since_start = (u64)jiffies_since_start * denominator + (HZ * numerator) / 2; do_div(buffers_since_start, HZ * numerator); /* * After more than 0xf0000000 (rounded down to a multiple of * 'jiffies-per-day' to ease jiffies_to_msecs calculation) * jiffies have passed since we started streaming reset the * counters and keep track of the sequence offset. */ if (jiffies_since_start > JIFFIES_RESYNC) { dev->jiffies_touch_cap = cur_jiffies; dev->cap_seq_offset = buffers_since_start; buffers_since_start = 0; } dropped_bufs = buffers_since_start + dev->touch_cap_seq_offset - dev->touch_cap_seq_count; dev->touch_cap_seq_count = buffers_since_start + dev->touch_cap_seq_offset; dev->touch_cap_with_seq_wrap_count = dev->touch_cap_seq_count - dev->touch_cap_seq_start; vivid_thread_tch_cap_tick(dev, dropped_bufs); /* * Calculate the number of 'numerators' streamed * since we started, including the current buffer. */ numerators_since_start = ++buffers_since_start * numerator; /* And the number of jiffies since we started */ jiffies_since_start = jiffies - dev->jiffies_touch_cap; mutex_unlock(&dev->mutex); /* * Calculate when that next buffer is supposed to start * in jiffies since we started streaming. */ next_jiffies_since_start = numerators_since_start * HZ + denominator / 2; do_div(next_jiffies_since_start, denominator); /* If it is in the past, then just schedule asap */ if (next_jiffies_since_start < jiffies_since_start) next_jiffies_since_start = jiffies_since_start; wait_jiffies = next_jiffies_since_start - jiffies_since_start; while (time_is_after_jiffies(cur_jiffies + wait_jiffies) && !kthread_should_stop()) schedule(); } dprintk(dev, 1, "Touch Capture Thread End\n"); return 0; } int vivid_start_generating_touch_cap(struct vivid_dev *dev) { if (dev->kthread_touch_cap) { dev->touch_cap_streaming = true; return 0; } dev->touch_cap_seq_start = dev->seq_wrap * 128; dev->kthread_touch_cap = kthread_run(vivid_thread_touch_cap, dev, "%s-tch-cap", dev->v4l2_dev.name); if (IS_ERR(dev->kthread_touch_cap)) { int err = PTR_ERR(dev->kthread_touch_cap); dev->kthread_touch_cap = NULL; v4l2_err(&dev->v4l2_dev, "kernel_thread() failed\n"); return err; } dev->touch_cap_streaming = true; dprintk(dev, 1, "returning from %s\n", __func__); return 0; } void vivid_stop_generating_touch_cap(struct vivid_dev *dev) { if (!dev->kthread_touch_cap) return; dev->touch_cap_streaming = false; while (!list_empty(&dev->touch_cap_active)) { struct vivid_buffer *buf; buf = list_entry(dev->touch_cap_active.next, struct vivid_buffer, list); list_del(&buf->list); v4l2_ctrl_request_complete(buf->vb.vb2_buf.req_obj.req, &dev->ctrl_hdl_touch_cap); vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR); dprintk(dev, 2, "touch_cap buffer %d done\n", buf->vb.vb2_buf.index); } kthread_stop(dev->kthread_touch_cap); dev->kthread_touch_cap = NULL; }
linux-master
drivers/media/test-drivers/vivid/vivid-kthread-touch.c
// SPDX-License-Identifier: GPL-2.0-only /* * vivid-vid-common.c - common video support functions. * * Copyright 2014 Cisco Systems, Inc. and/or its affiliates. All rights reserved. */ #include <linux/errno.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/videodev2.h> #include <linux/v4l2-dv-timings.h> #include <media/v4l2-common.h> #include <media/v4l2-event.h> #include <media/v4l2-dv-timings.h> #include "vivid-core.h" #include "vivid-vid-common.h" const struct v4l2_dv_timings_cap vivid_dv_timings_cap = { .type = V4L2_DV_BT_656_1120, /* keep this initialization for compatibility with GCC < 4.4.6 */ .reserved = { 0 }, V4L2_INIT_BT_TIMINGS(16, MAX_WIDTH, 16, MAX_HEIGHT, 14000000, 775000000, V4L2_DV_BT_STD_CEA861 | V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT | V4L2_DV_BT_STD_GTF, V4L2_DV_BT_CAP_PROGRESSIVE | V4L2_DV_BT_CAP_INTERLACED) }; /* ------------------------------------------------------------------ Basic structures ------------------------------------------------------------------*/ struct vivid_fmt vivid_formats[] = { { .fourcc = V4L2_PIX_FMT_YUYV, .vdownsampling = { 1 }, .bit_depth = { 16 }, .color_enc = TGP_COLOR_ENC_YCBCR, .planes = 1, .buffers = 1, .data_offset = { PLANE0_DATA_OFFSET }, }, { .fourcc = V4L2_PIX_FMT_UYVY, .vdownsampling = { 1 }, .bit_depth = { 16 }, .color_enc = TGP_COLOR_ENC_YCBCR, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_YVYU, .vdownsampling = { 1 }, .bit_depth = { 16 }, .color_enc = TGP_COLOR_ENC_YCBCR, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_VYUY, .vdownsampling = { 1 }, .bit_depth = { 16 }, .color_enc = TGP_COLOR_ENC_YCBCR, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_YUV422P, .vdownsampling = { 1, 1, 1 }, .bit_depth = { 8, 4, 4 }, .color_enc = TGP_COLOR_ENC_YCBCR, .planes = 3, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_YUV420, .vdownsampling = { 1, 2, 2 }, .bit_depth = { 8, 4, 4 }, .color_enc = TGP_COLOR_ENC_YCBCR, .planes = 3, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_YVU420, .vdownsampling = { 1, 2, 2 }, .bit_depth = { 8, 4, 4 }, .color_enc = TGP_COLOR_ENC_YCBCR, .planes = 3, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_NV12, .vdownsampling = { 1, 2 }, .bit_depth = { 8, 8 }, .color_enc = TGP_COLOR_ENC_YCBCR, .planes = 2, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_NV21, .vdownsampling = { 1, 2 }, .bit_depth = { 8, 8 }, .color_enc = TGP_COLOR_ENC_YCBCR, .planes = 2, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_NV16, .vdownsampling = { 1, 1 }, .bit_depth = { 8, 8 }, .color_enc = TGP_COLOR_ENC_YCBCR, .planes = 2, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_NV61, .vdownsampling = { 1, 1 }, .bit_depth = { 8, 8 }, .color_enc = TGP_COLOR_ENC_YCBCR, .planes = 2, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_NV24, .vdownsampling = { 1, 1 }, .bit_depth = { 8, 16 }, .color_enc = TGP_COLOR_ENC_YCBCR, .planes = 2, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_NV42, .vdownsampling = { 1, 1 }, .bit_depth = { 8, 16 }, .color_enc = TGP_COLOR_ENC_YCBCR, .planes = 2, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_YUV555, /* uuuvvvvv ayyyyyuu */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, .alpha_mask = 0x8000, }, { .fourcc = V4L2_PIX_FMT_YUV565, /* uuuvvvvv yyyyyuuu */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_YUV444, /* uuuuvvvv aaaayyyy */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, .alpha_mask = 0xf000, }, { .fourcc = V4L2_PIX_FMT_YUV32, /* ayuv */ .vdownsampling = { 1 }, .bit_depth = { 32 }, .planes = 1, .buffers = 1, .alpha_mask = 0x000000ff, }, { .fourcc = V4L2_PIX_FMT_AYUV32, .vdownsampling = { 1 }, .bit_depth = { 32 }, .planes = 1, .buffers = 1, .alpha_mask = 0x000000ff, }, { .fourcc = V4L2_PIX_FMT_XYUV32, .vdownsampling = { 1 }, .bit_depth = { 32 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_VUYA32, .vdownsampling = { 1 }, .bit_depth = { 32 }, .planes = 1, .buffers = 1, .alpha_mask = 0xff000000, }, { .fourcc = V4L2_PIX_FMT_VUYX32, .vdownsampling = { 1 }, .bit_depth = { 32 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_YUVA32, .vdownsampling = { 1 }, .bit_depth = { 32 }, .planes = 1, .buffers = 1, .alpha_mask = 0xff000000, }, { .fourcc = V4L2_PIX_FMT_YUVX32, .vdownsampling = { 1 }, .bit_depth = { 32 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_GREY, .vdownsampling = { 1 }, .bit_depth = { 8 }, .color_enc = TGP_COLOR_ENC_LUMA, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_Y10, .vdownsampling = { 1 }, .bit_depth = { 16 }, .color_enc = TGP_COLOR_ENC_LUMA, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_Y12, .vdownsampling = { 1 }, .bit_depth = { 16 }, .color_enc = TGP_COLOR_ENC_LUMA, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_Y16, .vdownsampling = { 1 }, .bit_depth = { 16 }, .color_enc = TGP_COLOR_ENC_LUMA, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_Y16_BE, .vdownsampling = { 1 }, .bit_depth = { 16 }, .color_enc = TGP_COLOR_ENC_LUMA, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_RGB332, /* rrrgggbb */ .vdownsampling = { 1 }, .bit_depth = { 8 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_RGB565, /* gggbbbbb rrrrrggg */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, .can_do_overlay = true, }, { .fourcc = V4L2_PIX_FMT_RGB565X, /* rrrrrggg gggbbbbb */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, .can_do_overlay = true, }, { .fourcc = V4L2_PIX_FMT_RGB444, /* ggggbbbb xxxxrrrr */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_XRGB444, /* ggggbbbb xxxxrrrr */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_ARGB444, /* ggggbbbb aaaarrrr */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, .alpha_mask = 0x00f0, }, { .fourcc = V4L2_PIX_FMT_RGBX444, /* bbbbxxxx rrrrgggg */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_RGBA444, /* bbbbaaaa rrrrgggg */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, .alpha_mask = 0x00f0, }, { .fourcc = V4L2_PIX_FMT_XBGR444, /* ggggrrrr xxxxbbbb */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_ABGR444, /* ggggrrrr aaaabbbb */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, .alpha_mask = 0x00f0, }, { .fourcc = V4L2_PIX_FMT_BGRX444, /* rrrrxxxx bbbbgggg */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_BGRA444, /* rrrraaaa bbbbgggg */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, .alpha_mask = 0x00f0, }, { .fourcc = V4L2_PIX_FMT_RGB555, /* gggbbbbb xrrrrrgg */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, .can_do_overlay = true, }, { .fourcc = V4L2_PIX_FMT_XRGB555, /* gggbbbbb xrrrrrgg */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, .can_do_overlay = true, }, { .fourcc = V4L2_PIX_FMT_ARGB555, /* gggbbbbb arrrrrgg */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, .can_do_overlay = true, .alpha_mask = 0x8000, }, { .fourcc = V4L2_PIX_FMT_RGBX555, /* ggbbbbbx rrrrrggg */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, .can_do_overlay = true, }, { .fourcc = V4L2_PIX_FMT_RGBA555, /* ggbbbbba rrrrrggg */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, .can_do_overlay = true, .alpha_mask = 0x8000, }, { .fourcc = V4L2_PIX_FMT_XBGR555, /* gggrrrrr xbbbbbgg */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, .can_do_overlay = true, }, { .fourcc = V4L2_PIX_FMT_ABGR555, /* gggrrrrr abbbbbgg */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, .can_do_overlay = true, .alpha_mask = 0x8000, }, { .fourcc = V4L2_PIX_FMT_BGRX555, /* ggrrrrrx bbbbbggg */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, .can_do_overlay = true, }, { .fourcc = V4L2_PIX_FMT_BGRA555, /* ggrrrrra bbbbbggg */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, .can_do_overlay = true, .alpha_mask = 0x8000, }, { .fourcc = V4L2_PIX_FMT_RGB555X, /* xrrrrrgg gggbbbbb */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_XRGB555X, /* xrrrrrgg gggbbbbb */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_ARGB555X, /* arrrrrgg gggbbbbb */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, .alpha_mask = 0x0080, }, { .fourcc = V4L2_PIX_FMT_RGB24, /* rgb */ .vdownsampling = { 1 }, .bit_depth = { 24 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_BGR24, /* bgr */ .vdownsampling = { 1 }, .bit_depth = { 24 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_BGR666, /* bbbbbbgg ggggrrrr rrxxxxxx */ .vdownsampling = { 1 }, .bit_depth = { 32 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_RGB32, /* xrgb */ .vdownsampling = { 1 }, .bit_depth = { 32 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_BGR32, /* bgrx */ .vdownsampling = { 1 }, .bit_depth = { 32 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_XRGB32, /* xrgb */ .vdownsampling = { 1 }, .bit_depth = { 32 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_XBGR32, /* bgrx */ .vdownsampling = { 1 }, .bit_depth = { 32 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_ARGB32, /* argb */ .vdownsampling = { 1 }, .bit_depth = { 32 }, .planes = 1, .buffers = 1, .alpha_mask = 0x000000ff, }, { .fourcc = V4L2_PIX_FMT_ABGR32, /* bgra */ .vdownsampling = { 1 }, .bit_depth = { 32 }, .planes = 1, .buffers = 1, .alpha_mask = 0xff000000, }, { .fourcc = V4L2_PIX_FMT_RGBX32, /* rgbx */ .vdownsampling = { 1 }, .bit_depth = { 32 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_BGRX32, /* xbgr */ .vdownsampling = { 1 }, .bit_depth = { 32 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_RGBA32, /* rgba */ .vdownsampling = { 1 }, .bit_depth = { 32 }, .planes = 1, .buffers = 1, .alpha_mask = 0x000000ff, }, { .fourcc = V4L2_PIX_FMT_BGRA32, /* abgr */ .vdownsampling = { 1 }, .bit_depth = { 32 }, .planes = 1, .buffers = 1, .alpha_mask = 0xff000000, }, { .fourcc = V4L2_PIX_FMT_SBGGR8, /* Bayer BG/GR */ .vdownsampling = { 1 }, .bit_depth = { 8 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_SGBRG8, /* Bayer GB/RG */ .vdownsampling = { 1 }, .bit_depth = { 8 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_SGRBG8, /* Bayer GR/BG */ .vdownsampling = { 1 }, .bit_depth = { 8 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_SRGGB8, /* Bayer RG/GB */ .vdownsampling = { 1 }, .bit_depth = { 8 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_SBGGR10, /* Bayer BG/GR */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_SGBRG10, /* Bayer GB/RG */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_SGRBG10, /* Bayer GR/BG */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_SRGGB10, /* Bayer RG/GB */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_SBGGR12, /* Bayer BG/GR */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_SGBRG12, /* Bayer GB/RG */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_SGRBG12, /* Bayer GR/BG */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_SRGGB12, /* Bayer RG/GB */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_SBGGR16, /* Bayer BG/GR */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_SGBRG16, /* Bayer GB/RG */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_SGRBG16, /* Bayer GR/BG */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_SRGGB16, /* Bayer RG/GB */ .vdownsampling = { 1 }, .bit_depth = { 16 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_HSV24, /* HSV 24bits */ .color_enc = TGP_COLOR_ENC_HSV, .vdownsampling = { 1 }, .bit_depth = { 24 }, .planes = 1, .buffers = 1, }, { .fourcc = V4L2_PIX_FMT_HSV32, /* HSV 32bits */ .color_enc = TGP_COLOR_ENC_HSV, .vdownsampling = { 1 }, .bit_depth = { 32 }, .planes = 1, .buffers = 1, }, /* Multiplanar formats */ { .fourcc = V4L2_PIX_FMT_NV16M, .vdownsampling = { 1, 1 }, .bit_depth = { 8, 8 }, .color_enc = TGP_COLOR_ENC_YCBCR, .planes = 2, .buffers = 2, .data_offset = { PLANE0_DATA_OFFSET, 0 }, }, { .fourcc = V4L2_PIX_FMT_NV61M, .vdownsampling = { 1, 1 }, .bit_depth = { 8, 8 }, .color_enc = TGP_COLOR_ENC_YCBCR, .planes = 2, .buffers = 2, .data_offset = { 0, PLANE0_DATA_OFFSET }, }, { .fourcc = V4L2_PIX_FMT_YUV420M, .vdownsampling = { 1, 2, 2 }, .bit_depth = { 8, 4, 4 }, .color_enc = TGP_COLOR_ENC_YCBCR, .planes = 3, .buffers = 3, }, { .fourcc = V4L2_PIX_FMT_YVU420M, .vdownsampling = { 1, 2, 2 }, .bit_depth = { 8, 4, 4 }, .color_enc = TGP_COLOR_ENC_YCBCR, .planes = 3, .buffers = 3, }, { .fourcc = V4L2_PIX_FMT_NV12M, .vdownsampling = { 1, 2 }, .bit_depth = { 8, 8 }, .color_enc = TGP_COLOR_ENC_YCBCR, .planes = 2, .buffers = 2, }, { .fourcc = V4L2_PIX_FMT_NV21M, .vdownsampling = { 1, 2 }, .bit_depth = { 8, 8 }, .color_enc = TGP_COLOR_ENC_YCBCR, .planes = 2, .buffers = 2, }, { .fourcc = V4L2_PIX_FMT_YUV422M, .vdownsampling = { 1, 1, 1 }, .bit_depth = { 8, 4, 4 }, .color_enc = TGP_COLOR_ENC_YCBCR, .planes = 3, .buffers = 3, }, { .fourcc = V4L2_PIX_FMT_YVU422M, .vdownsampling = { 1, 1, 1 }, .bit_depth = { 8, 4, 4 }, .color_enc = TGP_COLOR_ENC_YCBCR, .planes = 3, .buffers = 3, }, { .fourcc = V4L2_PIX_FMT_YUV444M, .vdownsampling = { 1, 1, 1 }, .bit_depth = { 8, 8, 8 }, .color_enc = TGP_COLOR_ENC_YCBCR, .planes = 3, .buffers = 3, }, { .fourcc = V4L2_PIX_FMT_YVU444M, .vdownsampling = { 1, 1, 1 }, .bit_depth = { 8, 8, 8 }, .color_enc = TGP_COLOR_ENC_YCBCR, .planes = 3, .buffers = 3, }, }; /* There are this many multiplanar formats in the list */ #define VIVID_MPLANAR_FORMATS 10 const struct vivid_fmt *vivid_get_format(struct vivid_dev *dev, u32 pixelformat) { const struct vivid_fmt *fmt; unsigned k; for (k = 0; k < ARRAY_SIZE(vivid_formats); k++) { fmt = &vivid_formats[k]; if (fmt->fourcc == pixelformat) if (fmt->buffers == 1 || dev->multiplanar) return fmt; } return NULL; } bool vivid_vid_can_loop(struct vivid_dev *dev) { if (dev->src_rect.width != dev->sink_rect.width || dev->src_rect.height != dev->sink_rect.height) return false; if (dev->fmt_cap->fourcc != dev->fmt_out->fourcc) return false; if (dev->field_cap != dev->field_out) return false; /* * While this can be supported, it is just too much work * to actually implement. */ if (dev->field_cap == V4L2_FIELD_SEQ_TB || dev->field_cap == V4L2_FIELD_SEQ_BT) return false; if (vivid_is_svid_cap(dev) && vivid_is_svid_out(dev)) { if (!(dev->std_cap[dev->input] & V4L2_STD_525_60) != !(dev->std_out & V4L2_STD_525_60)) return false; return true; } if (vivid_is_hdmi_cap(dev) && vivid_is_hdmi_out(dev)) return true; return false; } void vivid_send_source_change(struct vivid_dev *dev, unsigned type) { struct v4l2_event ev = { .type = V4L2_EVENT_SOURCE_CHANGE, .u.src_change.changes = V4L2_EVENT_SRC_CH_RESOLUTION, }; unsigned i; for (i = 0; i < dev->num_inputs; i++) { ev.id = i; if (dev->input_type[i] == type) { if (video_is_registered(&dev->vid_cap_dev) && dev->has_vid_cap) v4l2_event_queue(&dev->vid_cap_dev, &ev); if (video_is_registered(&dev->vbi_cap_dev) && dev->has_vbi_cap) v4l2_event_queue(&dev->vbi_cap_dev, &ev); } } } /* * Conversion function that converts a single-planar format to a * single-plane multiplanar format. */ void fmt_sp2mp(const struct v4l2_format *sp_fmt, struct v4l2_format *mp_fmt) { struct v4l2_pix_format_mplane *mp = &mp_fmt->fmt.pix_mp; struct v4l2_plane_pix_format *ppix = &mp->plane_fmt[0]; const struct v4l2_pix_format *pix = &sp_fmt->fmt.pix; bool is_out = sp_fmt->type == V4L2_BUF_TYPE_VIDEO_OUTPUT; memset(mp->reserved, 0, sizeof(mp->reserved)); mp_fmt->type = is_out ? V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE : V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; mp->width = pix->width; mp->height = pix->height; mp->pixelformat = pix->pixelformat; mp->field = pix->field; mp->colorspace = pix->colorspace; mp->xfer_func = pix->xfer_func; /* Also copies hsv_enc */ mp->ycbcr_enc = pix->ycbcr_enc; mp->quantization = pix->quantization; mp->num_planes = 1; mp->flags = pix->flags; ppix->sizeimage = pix->sizeimage; ppix->bytesperline = pix->bytesperline; memset(ppix->reserved, 0, sizeof(ppix->reserved)); } int fmt_sp2mp_func(struct file *file, void *priv, struct v4l2_format *f, fmtfunc func) { struct v4l2_format fmt; struct v4l2_pix_format_mplane *mp = &fmt.fmt.pix_mp; struct v4l2_plane_pix_format *ppix = &mp->plane_fmt[0]; struct v4l2_pix_format *pix = &f->fmt.pix; int ret; /* Converts to a mplane format */ fmt_sp2mp(f, &fmt); /* Passes it to the generic mplane format function */ ret = func(file, priv, &fmt); /* Copies back the mplane data to the single plane format */ pix->width = mp->width; pix->height = mp->height; pix->pixelformat = mp->pixelformat; pix->field = mp->field; pix->colorspace = mp->colorspace; pix->xfer_func = mp->xfer_func; /* Also copies hsv_enc */ pix->ycbcr_enc = mp->ycbcr_enc; pix->quantization = mp->quantization; pix->sizeimage = ppix->sizeimage; pix->bytesperline = ppix->bytesperline; pix->flags = mp->flags; return ret; } int vivid_vid_adjust_sel(unsigned flags, struct v4l2_rect *r) { unsigned w = r->width; unsigned h = r->height; /* sanitize w and h in case someone passes ~0 as the value */ w &= 0xffff; h &= 0xffff; if (!(flags & V4L2_SEL_FLAG_LE)) { w++; h++; if (w < 2) w = 2; if (h < 2) h = 2; } if (!(flags & V4L2_SEL_FLAG_GE)) { if (w > MAX_WIDTH) w = MAX_WIDTH; if (h > MAX_HEIGHT) h = MAX_HEIGHT; } w = w & ~1; h = h & ~1; if (w < 2 || h < 2) return -ERANGE; if (w > MAX_WIDTH || h > MAX_HEIGHT) return -ERANGE; if (r->top < 0) r->top = 0; if (r->left < 0) r->left = 0; /* sanitize left and top in case someone passes ~0 as the value */ r->left &= 0xfffe; r->top &= 0xfffe; if (r->left + w > MAX_WIDTH) r->left = MAX_WIDTH - w; if (r->top + h > MAX_HEIGHT) r->top = MAX_HEIGHT - h; if ((flags & (V4L2_SEL_FLAG_GE | V4L2_SEL_FLAG_LE)) == (V4L2_SEL_FLAG_GE | V4L2_SEL_FLAG_LE) && (r->width != w || r->height != h)) return -ERANGE; r->width = w; r->height = h; return 0; } int vivid_enum_fmt_vid(struct file *file, void *priv, struct v4l2_fmtdesc *f) { struct vivid_dev *dev = video_drvdata(file); const struct vivid_fmt *fmt; if (f->index >= ARRAY_SIZE(vivid_formats) - (dev->multiplanar ? 0 : VIVID_MPLANAR_FORMATS)) return -EINVAL; fmt = &vivid_formats[f->index]; f->pixelformat = fmt->fourcc; if (f->type != V4L2_BUF_TYPE_VIDEO_CAPTURE && f->type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) return 0; /* * For capture devices, we support the CSC API. * We allow userspace to: * 1. set the colorspace * 2. set the xfer_func * 3. set the ycbcr_enc on YUV formats * 4. set the hsv_enc on HSV formats * 5. set the quantization on YUV and RGB formats */ f->flags |= V4L2_FMT_FLAG_CSC_COLORSPACE; f->flags |= V4L2_FMT_FLAG_CSC_XFER_FUNC; if (fmt->color_enc == TGP_COLOR_ENC_YCBCR) { f->flags |= V4L2_FMT_FLAG_CSC_YCBCR_ENC; f->flags |= V4L2_FMT_FLAG_CSC_QUANTIZATION; } else if (fmt->color_enc == TGP_COLOR_ENC_HSV) { f->flags |= V4L2_FMT_FLAG_CSC_HSV_ENC; } else if (fmt->color_enc == TGP_COLOR_ENC_RGB) { f->flags |= V4L2_FMT_FLAG_CSC_QUANTIZATION; } return 0; } int vidioc_g_std(struct file *file, void *priv, v4l2_std_id *id) { struct vivid_dev *dev = video_drvdata(file); struct video_device *vdev = video_devdata(file); if (vdev->vfl_dir == VFL_DIR_RX) { if (!vivid_is_sdtv_cap(dev)) return -ENODATA; *id = dev->std_cap[dev->input]; } else { if (!vivid_is_svid_out(dev)) return -ENODATA; *id = dev->std_out; } return 0; } int vidioc_g_dv_timings(struct file *file, void *_fh, struct v4l2_dv_timings *timings) { struct vivid_dev *dev = video_drvdata(file); struct video_device *vdev = video_devdata(file); if (vdev->vfl_dir == VFL_DIR_RX) { if (!vivid_is_hdmi_cap(dev)) return -ENODATA; *timings = dev->dv_timings_cap[dev->input]; } else { if (!vivid_is_hdmi_out(dev)) return -ENODATA; *timings = dev->dv_timings_out; } return 0; } int vidioc_enum_dv_timings(struct file *file, void *_fh, struct v4l2_enum_dv_timings *timings) { struct vivid_dev *dev = video_drvdata(file); struct video_device *vdev = video_devdata(file); if (vdev->vfl_dir == VFL_DIR_RX) { if (!vivid_is_hdmi_cap(dev)) return -ENODATA; } else { if (!vivid_is_hdmi_out(dev)) return -ENODATA; } return v4l2_enum_dv_timings_cap(timings, &vivid_dv_timings_cap, NULL, NULL); } int vidioc_dv_timings_cap(struct file *file, void *_fh, struct v4l2_dv_timings_cap *cap) { struct vivid_dev *dev = video_drvdata(file); struct video_device *vdev = video_devdata(file); if (vdev->vfl_dir == VFL_DIR_RX) { if (!vivid_is_hdmi_cap(dev)) return -ENODATA; } else { if (!vivid_is_hdmi_out(dev)) return -ENODATA; } *cap = vivid_dv_timings_cap; return 0; } int vidioc_g_edid(struct file *file, void *_fh, struct v4l2_edid *edid) { struct vivid_dev *dev = video_drvdata(file); struct video_device *vdev = video_devdata(file); struct cec_adapter *adap; memset(edid->reserved, 0, sizeof(edid->reserved)); if (vdev->vfl_dir == VFL_DIR_RX) { if (edid->pad >= dev->num_inputs) return -EINVAL; if (dev->input_type[edid->pad] != HDMI) return -EINVAL; adap = dev->cec_rx_adap; } else { unsigned int bus_idx; if (edid->pad >= dev->num_outputs) return -EINVAL; if (dev->output_type[edid->pad] != HDMI) return -EINVAL; if (!dev->display_present[edid->pad]) return -ENODATA; bus_idx = dev->cec_output2bus_map[edid->pad]; adap = dev->cec_tx_adap[bus_idx]; } if (edid->start_block == 0 && edid->blocks == 0) { edid->blocks = dev->edid_blocks; return 0; } if (dev->edid_blocks == 0) return -ENODATA; if (edid->start_block >= dev->edid_blocks) return -EINVAL; if (edid->blocks > dev->edid_blocks - edid->start_block) edid->blocks = dev->edid_blocks - edid->start_block; if (adap) v4l2_set_edid_phys_addr(dev->edid, dev->edid_blocks * 128, adap->phys_addr); memcpy(edid->edid, dev->edid + edid->start_block * 128, edid->blocks * 128); return 0; }
linux-master
drivers/media/test-drivers/vivid/vivid-vid-common.c
// SPDX-License-Identifier: GPL-2.0-only /* * vivid-meta-cap.c - meta capture support functions. */ #include <linux/errno.h> #include <linux/kernel.h> #include <linux/videodev2.h> #include <media/v4l2-common.h> #include <linux/usb/video.h> #include "vivid-core.h" #include "vivid-kthread-cap.h" #include "vivid-meta-cap.h" static int meta_cap_queue_setup(struct vb2_queue *vq, unsigned int *nbuffers, unsigned int *nplanes, unsigned int sizes[], struct device *alloc_devs[]) { struct vivid_dev *dev = vb2_get_drv_priv(vq); unsigned int size = sizeof(struct vivid_uvc_meta_buf); if (!vivid_is_webcam(dev)) return -EINVAL; if (*nplanes) { if (sizes[0] < size) return -EINVAL; } else { sizes[0] = size; } if (vq->num_buffers + *nbuffers < 2) *nbuffers = 2 - vq->num_buffers; *nplanes = 1; return 0; } static int meta_cap_buf_prepare(struct vb2_buffer *vb) { struct vivid_dev *dev = vb2_get_drv_priv(vb->vb2_queue); unsigned int size = sizeof(struct vivid_uvc_meta_buf); dprintk(dev, 1, "%s\n", __func__); if (dev->buf_prepare_error) { /* * Error injection: test what happens if buf_prepare() returns * an error. */ dev->buf_prepare_error = false; return -EINVAL; } if (vb2_plane_size(vb, 0) < size) { dprintk(dev, 1, "%s data will not fit into plane (%lu < %u)\n", __func__, vb2_plane_size(vb, 0), size); return -EINVAL; } vb2_set_plane_payload(vb, 0, size); return 0; } static void meta_cap_buf_queue(struct vb2_buffer *vb) { struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb); struct vivid_dev *dev = vb2_get_drv_priv(vb->vb2_queue); struct vivid_buffer *buf = container_of(vbuf, struct vivid_buffer, vb); dprintk(dev, 1, "%s\n", __func__); spin_lock(&dev->slock); list_add_tail(&buf->list, &dev->meta_cap_active); spin_unlock(&dev->slock); } static int meta_cap_start_streaming(struct vb2_queue *vq, unsigned int count) { struct vivid_dev *dev = vb2_get_drv_priv(vq); int err; dprintk(dev, 1, "%s\n", __func__); dev->meta_cap_seq_count = 0; if (dev->start_streaming_error) { dev->start_streaming_error = false; err = -EINVAL; } else { err = vivid_start_generating_vid_cap(dev, &dev->meta_cap_streaming); } if (err) { struct vivid_buffer *buf, *tmp; list_for_each_entry_safe(buf, tmp, &dev->meta_cap_active, list) { list_del(&buf->list); vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_QUEUED); } } return err; } /* abort streaming and wait for last buffer */ static void meta_cap_stop_streaming(struct vb2_queue *vq) { struct vivid_dev *dev = vb2_get_drv_priv(vq); dprintk(dev, 1, "%s\n", __func__); vivid_stop_generating_vid_cap(dev, &dev->meta_cap_streaming); } static void meta_cap_buf_request_complete(struct vb2_buffer *vb) { struct vivid_dev *dev = vb2_get_drv_priv(vb->vb2_queue); v4l2_ctrl_request_complete(vb->req_obj.req, &dev->ctrl_hdl_meta_cap); } const struct vb2_ops vivid_meta_cap_qops = { .queue_setup = meta_cap_queue_setup, .buf_prepare = meta_cap_buf_prepare, .buf_queue = meta_cap_buf_queue, .start_streaming = meta_cap_start_streaming, .stop_streaming = meta_cap_stop_streaming, .buf_request_complete = meta_cap_buf_request_complete, .wait_prepare = vb2_ops_wait_prepare, .wait_finish = vb2_ops_wait_finish, }; int vidioc_enum_fmt_meta_cap(struct file *file, void *priv, struct v4l2_fmtdesc *f) { struct vivid_dev *dev = video_drvdata(file); if (!vivid_is_webcam(dev)) return -EINVAL; if (f->index > 0) return -EINVAL; f->type = V4L2_BUF_TYPE_META_CAPTURE; f->pixelformat = V4L2_META_FMT_UVC; return 0; } int vidioc_g_fmt_meta_cap(struct file *file, void *priv, struct v4l2_format *f) { struct vivid_dev *dev = video_drvdata(file); struct v4l2_meta_format *meta = &f->fmt.meta; if (!vivid_is_webcam(dev) || !dev->has_meta_cap) return -EINVAL; meta->dataformat = V4L2_META_FMT_UVC; meta->buffersize = sizeof(struct vivid_uvc_meta_buf); return 0; } void vivid_meta_cap_fillbuff(struct vivid_dev *dev, struct vivid_buffer *buf, u64 soe) { struct vivid_uvc_meta_buf *meta = vb2_plane_vaddr(&buf->vb.vb2_buf, 0); int buf_off = 0; buf->vb.sequence = dev->meta_cap_seq_count; if (dev->field_cap == V4L2_FIELD_ALTERNATE) buf->vb.sequence /= 2; memset(meta, 1, vb2_plane_size(&buf->vb.vb2_buf, 0)); meta->ns = ktime_get_ns(); meta->sof = buf->vb.sequence * 30; meta->length = sizeof(*meta) - offsetof(struct vivid_uvc_meta_buf, length); meta->flags = UVC_STREAM_EOH | UVC_STREAM_EOF; if ((buf->vb.sequence % 2) == 0) meta->flags |= UVC_STREAM_FID; dprintk(dev, 2, "%s ns:%llu sof:%4d len:%u flags: 0x%02x", __func__, meta->ns, meta->sof, meta->length, meta->flags); if (dev->meta_pts) { meta->flags |= UVC_STREAM_PTS; meta->buf[0] = div_u64(soe, VIVID_META_CLOCK_UNIT); buf_off = 4; dprintk(dev, 2, " pts: %u\n", *(__u32 *)(meta->buf)); } if (dev->meta_scr) { meta->flags |= UVC_STREAM_SCR; meta->buf[buf_off] = div_u64((soe + dev->cap_frame_eof_offset), VIVID_META_CLOCK_UNIT); meta->buf[buf_off + 4] = (buf->vb.sequence * 30) % 1000; dprintk(dev, 2, " stc: %u, sof counter: %u\n", *(__u32 *)(meta->buf + buf_off), *(__u16 *)(meta->buf + buf_off + 4)); } dprintk(dev, 2, "\n"); }
linux-master
drivers/media/test-drivers/vivid/vivid-meta-cap.c
// SPDX-License-Identifier: GPL-2.0-only /* * vivid-radio-common.c - common radio rx/tx support functions. * * Copyright 2014 Cisco Systems, Inc. and/or its affiliates. All rights reserved. */ #include <linux/errno.h> #include <linux/kernel.h> #include <linux/delay.h> #include <linux/videodev2.h> #include "vivid-core.h" #include "vivid-ctrls.h" #include "vivid-radio-common.h" #include "vivid-rds-gen.h" /* * These functions are shared between the vivid receiver and transmitter * since both use the same frequency bands. */ const struct v4l2_frequency_band vivid_radio_bands[TOT_BANDS] = { /* Band FM */ { .type = V4L2_TUNER_RADIO, .index = 0, .capability = V4L2_TUNER_CAP_LOW | V4L2_TUNER_CAP_STEREO | V4L2_TUNER_CAP_FREQ_BANDS, .rangelow = FM_FREQ_RANGE_LOW, .rangehigh = FM_FREQ_RANGE_HIGH, .modulation = V4L2_BAND_MODULATION_FM, }, /* Band AM */ { .type = V4L2_TUNER_RADIO, .index = 1, .capability = V4L2_TUNER_CAP_LOW | V4L2_TUNER_CAP_FREQ_BANDS, .rangelow = AM_FREQ_RANGE_LOW, .rangehigh = AM_FREQ_RANGE_HIGH, .modulation = V4L2_BAND_MODULATION_AM, }, /* Band SW */ { .type = V4L2_TUNER_RADIO, .index = 2, .capability = V4L2_TUNER_CAP_LOW | V4L2_TUNER_CAP_FREQ_BANDS, .rangelow = SW_FREQ_RANGE_LOW, .rangehigh = SW_FREQ_RANGE_HIGH, .modulation = V4L2_BAND_MODULATION_AM, }, }; /* * Initialize the RDS generator. If we can loop, then the RDS generator * is set up with the values from the RDS TX controls, otherwise it * will fill in standard values using one of two alternates. */ void vivid_radio_rds_init(struct vivid_dev *dev) { struct vivid_rds_gen *rds = &dev->rds_gen; bool alt = dev->radio_rx_rds_use_alternates; /* Do nothing, blocks will be filled by the transmitter */ if (dev->radio_rds_loop && !dev->radio_tx_rds_controls) return; if (dev->radio_rds_loop) { v4l2_ctrl_lock(dev->radio_tx_rds_pi); rds->picode = dev->radio_tx_rds_pi->cur.val; rds->pty = dev->radio_tx_rds_pty->cur.val; rds->mono_stereo = dev->radio_tx_rds_mono_stereo->cur.val; rds->art_head = dev->radio_tx_rds_art_head->cur.val; rds->compressed = dev->radio_tx_rds_compressed->cur.val; rds->dyn_pty = dev->radio_tx_rds_dyn_pty->cur.val; rds->ta = dev->radio_tx_rds_ta->cur.val; rds->tp = dev->radio_tx_rds_tp->cur.val; rds->ms = dev->radio_tx_rds_ms->cur.val; strscpy(rds->psname, dev->radio_tx_rds_psname->p_cur.p_char, sizeof(rds->psname)); strscpy(rds->radiotext, dev->radio_tx_rds_radiotext->p_cur.p_char + alt * 64, sizeof(rds->radiotext)); v4l2_ctrl_unlock(dev->radio_tx_rds_pi); } else { vivid_rds_gen_fill(rds, dev->radio_rx_freq, alt); } if (dev->radio_rx_rds_controls) { v4l2_ctrl_s_ctrl(dev->radio_rx_rds_pty, rds->pty); v4l2_ctrl_s_ctrl(dev->radio_rx_rds_ta, rds->ta); v4l2_ctrl_s_ctrl(dev->radio_rx_rds_tp, rds->tp); v4l2_ctrl_s_ctrl(dev->radio_rx_rds_ms, rds->ms); v4l2_ctrl_s_ctrl_string(dev->radio_rx_rds_psname, rds->psname); v4l2_ctrl_s_ctrl_string(dev->radio_rx_rds_radiotext, rds->radiotext); if (!dev->radio_rds_loop) dev->radio_rx_rds_use_alternates = !dev->radio_rx_rds_use_alternates; } vivid_rds_generate(rds); } /* * Calculate the emulated signal quality taking into account the frequency * the transmitter is using. */ static void vivid_radio_calc_sig_qual(struct vivid_dev *dev) { int mod = 16000; int delta = 800; int sig_qual, sig_qual_tx = mod; /* * For SW and FM there is a channel every 1000 kHz, for AM there is one * every 100 kHz. */ if (dev->radio_rx_freq <= AM_FREQ_RANGE_HIGH) { mod /= 10; delta /= 10; } sig_qual = (dev->radio_rx_freq + delta) % mod - delta; if (dev->has_radio_tx) sig_qual_tx = dev->radio_rx_freq - dev->radio_tx_freq; if (abs(sig_qual_tx) <= abs(sig_qual)) { sig_qual = sig_qual_tx; /* * Zero the internal rds buffer if we are going to loop * rds blocks. */ if (!dev->radio_rds_loop && !dev->radio_tx_rds_controls) memset(dev->rds_gen.data, 0, sizeof(dev->rds_gen.data)); dev->radio_rds_loop = dev->radio_rx_freq >= FM_FREQ_RANGE_LOW; } else { dev->radio_rds_loop = false; } if (dev->radio_rx_freq <= AM_FREQ_RANGE_HIGH) sig_qual *= 10; dev->radio_rx_sig_qual = sig_qual; } int vivid_radio_g_frequency(struct file *file, const unsigned *pfreq, struct v4l2_frequency *vf) { if (vf->tuner != 0) return -EINVAL; vf->frequency = *pfreq; return 0; } int vivid_radio_s_frequency(struct file *file, unsigned *pfreq, const struct v4l2_frequency *vf) { struct vivid_dev *dev = video_drvdata(file); unsigned freq; unsigned band; if (vf->tuner != 0) return -EINVAL; if (vf->frequency >= (FM_FREQ_RANGE_LOW + SW_FREQ_RANGE_HIGH) / 2) band = BAND_FM; else if (vf->frequency <= (AM_FREQ_RANGE_HIGH + SW_FREQ_RANGE_LOW) / 2) band = BAND_AM; else band = BAND_SW; freq = clamp_t(u32, vf->frequency, vivid_radio_bands[band].rangelow, vivid_radio_bands[band].rangehigh); *pfreq = freq; /* * For both receiver and transmitter recalculate the signal quality * (since that depends on both frequencies) and re-init the rds * generator. */ vivid_radio_calc_sig_qual(dev); vivid_radio_rds_init(dev); return 0; }
linux-master
drivers/media/test-drivers/vivid/vivid-radio-common.c
// SPDX-License-Identifier: GPL-2.0-only /* * vivid-ctrls.c - control support functions. * * Copyright 2014 Cisco Systems, Inc. and/or its affiliates. All rights reserved. */ #include <linux/errno.h> #include <linux/kernel.h> #include <linux/videodev2.h> #include <media/v4l2-event.h> #include <media/v4l2-common.h> #include "vivid-core.h" #include "vivid-vid-cap.h" #include "vivid-vid-out.h" #include "vivid-vid-common.h" #include "vivid-radio-common.h" #include "vivid-osd.h" #include "vivid-ctrls.h" #include "vivid-cec.h" #define VIVID_CID_CUSTOM_BASE (V4L2_CID_USER_BASE | 0xf000) #define VIVID_CID_BUTTON (VIVID_CID_CUSTOM_BASE + 0) #define VIVID_CID_BOOLEAN (VIVID_CID_CUSTOM_BASE + 1) #define VIVID_CID_INTEGER (VIVID_CID_CUSTOM_BASE + 2) #define VIVID_CID_INTEGER64 (VIVID_CID_CUSTOM_BASE + 3) #define VIVID_CID_MENU (VIVID_CID_CUSTOM_BASE + 4) #define VIVID_CID_STRING (VIVID_CID_CUSTOM_BASE + 5) #define VIVID_CID_BITMASK (VIVID_CID_CUSTOM_BASE + 6) #define VIVID_CID_INTMENU (VIVID_CID_CUSTOM_BASE + 7) #define VIVID_CID_U32_ARRAY (VIVID_CID_CUSTOM_BASE + 8) #define VIVID_CID_U16_MATRIX (VIVID_CID_CUSTOM_BASE + 9) #define VIVID_CID_U8_4D_ARRAY (VIVID_CID_CUSTOM_BASE + 10) #define VIVID_CID_AREA (VIVID_CID_CUSTOM_BASE + 11) #define VIVID_CID_RO_INTEGER (VIVID_CID_CUSTOM_BASE + 12) #define VIVID_CID_U32_DYN_ARRAY (VIVID_CID_CUSTOM_BASE + 13) #define VIVID_CID_U8_PIXEL_ARRAY (VIVID_CID_CUSTOM_BASE + 14) #define VIVID_CID_S32_ARRAY (VIVID_CID_CUSTOM_BASE + 15) #define VIVID_CID_S64_ARRAY (VIVID_CID_CUSTOM_BASE + 16) #define VIVID_CID_VIVID_BASE (0x00f00000 | 0xf000) #define VIVID_CID_VIVID_CLASS (0x00f00000 | 1) #define VIVID_CID_TEST_PATTERN (VIVID_CID_VIVID_BASE + 0) #define VIVID_CID_OSD_TEXT_MODE (VIVID_CID_VIVID_BASE + 1) #define VIVID_CID_HOR_MOVEMENT (VIVID_CID_VIVID_BASE + 2) #define VIVID_CID_VERT_MOVEMENT (VIVID_CID_VIVID_BASE + 3) #define VIVID_CID_SHOW_BORDER (VIVID_CID_VIVID_BASE + 4) #define VIVID_CID_SHOW_SQUARE (VIVID_CID_VIVID_BASE + 5) #define VIVID_CID_INSERT_SAV (VIVID_CID_VIVID_BASE + 6) #define VIVID_CID_INSERT_EAV (VIVID_CID_VIVID_BASE + 7) #define VIVID_CID_VBI_CAP_INTERLACED (VIVID_CID_VIVID_BASE + 8) #define VIVID_CID_INSERT_HDMI_VIDEO_GUARD_BAND (VIVID_CID_VIVID_BASE + 9) #define VIVID_CID_HFLIP (VIVID_CID_VIVID_BASE + 20) #define VIVID_CID_VFLIP (VIVID_CID_VIVID_BASE + 21) #define VIVID_CID_STD_ASPECT_RATIO (VIVID_CID_VIVID_BASE + 22) #define VIVID_CID_DV_TIMINGS_ASPECT_RATIO (VIVID_CID_VIVID_BASE + 23) #define VIVID_CID_TSTAMP_SRC (VIVID_CID_VIVID_BASE + 24) #define VIVID_CID_COLORSPACE (VIVID_CID_VIVID_BASE + 25) #define VIVID_CID_XFER_FUNC (VIVID_CID_VIVID_BASE + 26) #define VIVID_CID_YCBCR_ENC (VIVID_CID_VIVID_BASE + 27) #define VIVID_CID_QUANTIZATION (VIVID_CID_VIVID_BASE + 28) #define VIVID_CID_LIMITED_RGB_RANGE (VIVID_CID_VIVID_BASE + 29) #define VIVID_CID_ALPHA_MODE (VIVID_CID_VIVID_BASE + 30) #define VIVID_CID_HAS_CROP_CAP (VIVID_CID_VIVID_BASE + 31) #define VIVID_CID_HAS_COMPOSE_CAP (VIVID_CID_VIVID_BASE + 32) #define VIVID_CID_HAS_SCALER_CAP (VIVID_CID_VIVID_BASE + 33) #define VIVID_CID_HAS_CROP_OUT (VIVID_CID_VIVID_BASE + 34) #define VIVID_CID_HAS_COMPOSE_OUT (VIVID_CID_VIVID_BASE + 35) #define VIVID_CID_HAS_SCALER_OUT (VIVID_CID_VIVID_BASE + 36) #define VIVID_CID_LOOP_VIDEO (VIVID_CID_VIVID_BASE + 37) #define VIVID_CID_SEQ_WRAP (VIVID_CID_VIVID_BASE + 38) #define VIVID_CID_TIME_WRAP (VIVID_CID_VIVID_BASE + 39) #define VIVID_CID_MAX_EDID_BLOCKS (VIVID_CID_VIVID_BASE + 40) #define VIVID_CID_PERCENTAGE_FILL (VIVID_CID_VIVID_BASE + 41) #define VIVID_CID_REDUCED_FPS (VIVID_CID_VIVID_BASE + 42) #define VIVID_CID_HSV_ENC (VIVID_CID_VIVID_BASE + 43) #define VIVID_CID_DISPLAY_PRESENT (VIVID_CID_VIVID_BASE + 44) #define VIVID_CID_STD_SIGNAL_MODE (VIVID_CID_VIVID_BASE + 60) #define VIVID_CID_STANDARD (VIVID_CID_VIVID_BASE + 61) #define VIVID_CID_DV_TIMINGS_SIGNAL_MODE (VIVID_CID_VIVID_BASE + 62) #define VIVID_CID_DV_TIMINGS (VIVID_CID_VIVID_BASE + 63) #define VIVID_CID_PERC_DROPPED (VIVID_CID_VIVID_BASE + 64) #define VIVID_CID_DISCONNECT (VIVID_CID_VIVID_BASE + 65) #define VIVID_CID_DQBUF_ERROR (VIVID_CID_VIVID_BASE + 66) #define VIVID_CID_QUEUE_SETUP_ERROR (VIVID_CID_VIVID_BASE + 67) #define VIVID_CID_BUF_PREPARE_ERROR (VIVID_CID_VIVID_BASE + 68) #define VIVID_CID_START_STR_ERROR (VIVID_CID_VIVID_BASE + 69) #define VIVID_CID_QUEUE_ERROR (VIVID_CID_VIVID_BASE + 70) #define VIVID_CID_CLEAR_FB (VIVID_CID_VIVID_BASE + 71) #define VIVID_CID_REQ_VALIDATE_ERROR (VIVID_CID_VIVID_BASE + 72) #define VIVID_CID_RADIO_SEEK_MODE (VIVID_CID_VIVID_BASE + 90) #define VIVID_CID_RADIO_SEEK_PROG_LIM (VIVID_CID_VIVID_BASE + 91) #define VIVID_CID_RADIO_RX_RDS_RBDS (VIVID_CID_VIVID_BASE + 92) #define VIVID_CID_RADIO_RX_RDS_BLOCKIO (VIVID_CID_VIVID_BASE + 93) #define VIVID_CID_RADIO_TX_RDS_BLOCKIO (VIVID_CID_VIVID_BASE + 94) #define VIVID_CID_SDR_CAP_FM_DEVIATION (VIVID_CID_VIVID_BASE + 110) #define VIVID_CID_META_CAP_GENERATE_PTS (VIVID_CID_VIVID_BASE + 111) #define VIVID_CID_META_CAP_GENERATE_SCR (VIVID_CID_VIVID_BASE + 112) /* General User Controls */ static void vivid_unregister_dev(bool valid, struct video_device *vdev) { if (!valid) return; clear_bit(V4L2_FL_REGISTERED, &vdev->flags); v4l2_event_wake_all(vdev); } static int vivid_user_gen_s_ctrl(struct v4l2_ctrl *ctrl) { struct vivid_dev *dev = container_of(ctrl->handler, struct vivid_dev, ctrl_hdl_user_gen); switch (ctrl->id) { case VIVID_CID_DISCONNECT: v4l2_info(&dev->v4l2_dev, "disconnect\n"); dev->disconnect_error = true; vivid_unregister_dev(dev->has_vid_cap, &dev->vid_cap_dev); vivid_unregister_dev(dev->has_vid_out, &dev->vid_out_dev); vivid_unregister_dev(dev->has_vbi_cap, &dev->vbi_cap_dev); vivid_unregister_dev(dev->has_vbi_out, &dev->vbi_out_dev); vivid_unregister_dev(dev->has_radio_rx, &dev->radio_rx_dev); vivid_unregister_dev(dev->has_radio_tx, &dev->radio_tx_dev); vivid_unregister_dev(dev->has_sdr_cap, &dev->sdr_cap_dev); vivid_unregister_dev(dev->has_meta_cap, &dev->meta_cap_dev); vivid_unregister_dev(dev->has_meta_out, &dev->meta_out_dev); vivid_unregister_dev(dev->has_touch_cap, &dev->touch_cap_dev); break; case VIVID_CID_BUTTON: dev->button_pressed = 30; break; } return 0; } static const struct v4l2_ctrl_ops vivid_user_gen_ctrl_ops = { .s_ctrl = vivid_user_gen_s_ctrl, }; static const struct v4l2_ctrl_config vivid_ctrl_button = { .ops = &vivid_user_gen_ctrl_ops, .id = VIVID_CID_BUTTON, .name = "Button", .type = V4L2_CTRL_TYPE_BUTTON, }; static const struct v4l2_ctrl_config vivid_ctrl_boolean = { .ops = &vivid_user_gen_ctrl_ops, .id = VIVID_CID_BOOLEAN, .name = "Boolean", .type = V4L2_CTRL_TYPE_BOOLEAN, .min = 0, .max = 1, .step = 1, .def = 1, }; static const struct v4l2_ctrl_config vivid_ctrl_int32 = { .ops = &vivid_user_gen_ctrl_ops, .id = VIVID_CID_INTEGER, .name = "Integer 32 Bits", .type = V4L2_CTRL_TYPE_INTEGER, .min = 0xffffffff80000000ULL, .max = 0x7fffffff, .step = 1, }; static const struct v4l2_ctrl_config vivid_ctrl_int64 = { .ops = &vivid_user_gen_ctrl_ops, .id = VIVID_CID_INTEGER64, .name = "Integer 64 Bits", .type = V4L2_CTRL_TYPE_INTEGER64, .min = 0x8000000000000000ULL, .max = 0x7fffffffffffffffLL, .step = 1, }; static const struct v4l2_ctrl_config vivid_ctrl_u32_array = { .ops = &vivid_user_gen_ctrl_ops, .id = VIVID_CID_U32_ARRAY, .name = "U32 1 Element Array", .type = V4L2_CTRL_TYPE_U32, .def = 0x18, .min = 0x10, .max = 0x20000, .step = 1, .dims = { 1 }, }; static const struct v4l2_ctrl_config vivid_ctrl_u32_dyn_array = { .ops = &vivid_user_gen_ctrl_ops, .id = VIVID_CID_U32_DYN_ARRAY, .name = "U32 Dynamic Array", .type = V4L2_CTRL_TYPE_U32, .flags = V4L2_CTRL_FLAG_DYNAMIC_ARRAY, .def = 50, .min = 10, .max = 90, .step = 1, .dims = { 100 }, }; static const struct v4l2_ctrl_config vivid_ctrl_u16_matrix = { .ops = &vivid_user_gen_ctrl_ops, .id = VIVID_CID_U16_MATRIX, .name = "U16 8x16 Matrix", .type = V4L2_CTRL_TYPE_U16, .def = 0x18, .min = 0x10, .max = 0x2000, .step = 1, .dims = { 8, 16 }, }; static const struct v4l2_ctrl_config vivid_ctrl_u8_4d_array = { .ops = &vivid_user_gen_ctrl_ops, .id = VIVID_CID_U8_4D_ARRAY, .name = "U8 2x3x4x5 Array", .type = V4L2_CTRL_TYPE_U8, .def = 0x18, .min = 0x10, .max = 0x20, .step = 1, .dims = { 2, 3, 4, 5 }, }; static const struct v4l2_ctrl_config vivid_ctrl_u8_pixel_array = { .ops = &vivid_user_gen_ctrl_ops, .id = VIVID_CID_U8_PIXEL_ARRAY, .name = "U8 Pixel Array", .type = V4L2_CTRL_TYPE_U8, .def = 0x80, .min = 0x00, .max = 0xff, .step = 1, .dims = { 640 / PIXEL_ARRAY_DIV, 360 / PIXEL_ARRAY_DIV }, }; static const struct v4l2_ctrl_config vivid_ctrl_s32_array = { .ops = &vivid_user_gen_ctrl_ops, .id = VIVID_CID_S32_ARRAY, .name = "S32 2 Element Array", .type = V4L2_CTRL_TYPE_INTEGER, .def = 2, .min = -10, .max = 10, .step = 1, .dims = { 2 }, }; static const struct v4l2_ctrl_config vivid_ctrl_s64_array = { .ops = &vivid_user_gen_ctrl_ops, .id = VIVID_CID_S64_ARRAY, .name = "S64 5 Element Array", .type = V4L2_CTRL_TYPE_INTEGER64, .def = 4, .min = -10, .max = 10, .step = 1, .dims = { 5 }, }; static const char * const vivid_ctrl_menu_strings[] = { "Menu Item 0 (Skipped)", "Menu Item 1", "Menu Item 2 (Skipped)", "Menu Item 3", "Menu Item 4", "Menu Item 5 (Skipped)", NULL, }; static const struct v4l2_ctrl_config vivid_ctrl_menu = { .ops = &vivid_user_gen_ctrl_ops, .id = VIVID_CID_MENU, .name = "Menu", .type = V4L2_CTRL_TYPE_MENU, .min = 1, .max = 4, .def = 3, .menu_skip_mask = 0x04, .qmenu = vivid_ctrl_menu_strings, }; static const struct v4l2_ctrl_config vivid_ctrl_string = { .ops = &vivid_user_gen_ctrl_ops, .id = VIVID_CID_STRING, .name = "String", .type = V4L2_CTRL_TYPE_STRING, .min = 2, .max = 4, .step = 1, }; static const struct v4l2_ctrl_config vivid_ctrl_bitmask = { .ops = &vivid_user_gen_ctrl_ops, .id = VIVID_CID_BITMASK, .name = "Bitmask", .type = V4L2_CTRL_TYPE_BITMASK, .def = 0x80002000, .min = 0, .max = 0x80402010, .step = 0, }; static const s64 vivid_ctrl_int_menu_values[] = { 1, 1, 2, 3, 5, 8, 13, 21, 42, }; static const struct v4l2_ctrl_config vivid_ctrl_int_menu = { .ops = &vivid_user_gen_ctrl_ops, .id = VIVID_CID_INTMENU, .name = "Integer Menu", .type = V4L2_CTRL_TYPE_INTEGER_MENU, .min = 1, .max = 8, .def = 4, .menu_skip_mask = 0x02, .qmenu_int = vivid_ctrl_int_menu_values, }; static const struct v4l2_ctrl_config vivid_ctrl_disconnect = { .ops = &vivid_user_gen_ctrl_ops, .id = VIVID_CID_DISCONNECT, .name = "Disconnect", .type = V4L2_CTRL_TYPE_BUTTON, }; static const struct v4l2_area area = { .width = 1000, .height = 2000, }; static const struct v4l2_ctrl_config vivid_ctrl_area = { .ops = &vivid_user_gen_ctrl_ops, .id = VIVID_CID_AREA, .name = "Area", .type = V4L2_CTRL_TYPE_AREA, .p_def.p_const = &area, }; static const struct v4l2_ctrl_config vivid_ctrl_ro_int32 = { .ops = &vivid_user_gen_ctrl_ops, .id = VIVID_CID_RO_INTEGER, .name = "Read-Only Integer 32 Bits", .type = V4L2_CTRL_TYPE_INTEGER, .flags = V4L2_CTRL_FLAG_READ_ONLY, .min = 0, .max = 255, .step = 1, }; /* Framebuffer Controls */ static int vivid_fb_s_ctrl(struct v4l2_ctrl *ctrl) { struct vivid_dev *dev = container_of(ctrl->handler, struct vivid_dev, ctrl_hdl_fb); switch (ctrl->id) { case VIVID_CID_CLEAR_FB: vivid_clear_fb(dev); break; } return 0; } static const struct v4l2_ctrl_ops vivid_fb_ctrl_ops = { .s_ctrl = vivid_fb_s_ctrl, }; static const struct v4l2_ctrl_config vivid_ctrl_clear_fb = { .ops = &vivid_fb_ctrl_ops, .id = VIVID_CID_CLEAR_FB, .name = "Clear Framebuffer", .type = V4L2_CTRL_TYPE_BUTTON, }; /* Video User Controls */ static int vivid_user_vid_g_volatile_ctrl(struct v4l2_ctrl *ctrl) { struct vivid_dev *dev = container_of(ctrl->handler, struct vivid_dev, ctrl_hdl_user_vid); switch (ctrl->id) { case V4L2_CID_AUTOGAIN: dev->gain->val = (jiffies_to_msecs(jiffies) / 1000) & 0xff; break; } return 0; } static int vivid_user_vid_s_ctrl(struct v4l2_ctrl *ctrl) { struct vivid_dev *dev = container_of(ctrl->handler, struct vivid_dev, ctrl_hdl_user_vid); switch (ctrl->id) { case V4L2_CID_BRIGHTNESS: dev->input_brightness[dev->input] = ctrl->val - dev->input * 128; tpg_s_brightness(&dev->tpg, dev->input_brightness[dev->input]); break; case V4L2_CID_CONTRAST: tpg_s_contrast(&dev->tpg, ctrl->val); break; case V4L2_CID_SATURATION: tpg_s_saturation(&dev->tpg, ctrl->val); break; case V4L2_CID_HUE: tpg_s_hue(&dev->tpg, ctrl->val); break; case V4L2_CID_HFLIP: dev->hflip = ctrl->val; tpg_s_hflip(&dev->tpg, dev->sensor_hflip ^ dev->hflip); break; case V4L2_CID_VFLIP: dev->vflip = ctrl->val; tpg_s_vflip(&dev->tpg, dev->sensor_vflip ^ dev->vflip); break; case V4L2_CID_ALPHA_COMPONENT: tpg_s_alpha_component(&dev->tpg, ctrl->val); break; } return 0; } static const struct v4l2_ctrl_ops vivid_user_vid_ctrl_ops = { .g_volatile_ctrl = vivid_user_vid_g_volatile_ctrl, .s_ctrl = vivid_user_vid_s_ctrl, }; /* Video Capture Controls */ static int vivid_vid_cap_s_ctrl(struct v4l2_ctrl *ctrl) { static const u32 colorspaces[] = { V4L2_COLORSPACE_SMPTE170M, V4L2_COLORSPACE_REC709, V4L2_COLORSPACE_SRGB, V4L2_COLORSPACE_OPRGB, V4L2_COLORSPACE_BT2020, V4L2_COLORSPACE_DCI_P3, V4L2_COLORSPACE_SMPTE240M, V4L2_COLORSPACE_470_SYSTEM_M, V4L2_COLORSPACE_470_SYSTEM_BG, }; struct vivid_dev *dev = container_of(ctrl->handler, struct vivid_dev, ctrl_hdl_vid_cap); unsigned int i, j; switch (ctrl->id) { case VIVID_CID_TEST_PATTERN: vivid_update_quality(dev); tpg_s_pattern(&dev->tpg, ctrl->val); break; case VIVID_CID_COLORSPACE: tpg_s_colorspace(&dev->tpg, colorspaces[ctrl->val]); vivid_send_source_change(dev, TV); vivid_send_source_change(dev, SVID); vivid_send_source_change(dev, HDMI); vivid_send_source_change(dev, WEBCAM); break; case VIVID_CID_XFER_FUNC: tpg_s_xfer_func(&dev->tpg, ctrl->val); vivid_send_source_change(dev, TV); vivid_send_source_change(dev, SVID); vivid_send_source_change(dev, HDMI); vivid_send_source_change(dev, WEBCAM); break; case VIVID_CID_YCBCR_ENC: tpg_s_ycbcr_enc(&dev->tpg, ctrl->val); vivid_send_source_change(dev, TV); vivid_send_source_change(dev, SVID); vivid_send_source_change(dev, HDMI); vivid_send_source_change(dev, WEBCAM); break; case VIVID_CID_HSV_ENC: tpg_s_hsv_enc(&dev->tpg, ctrl->val ? V4L2_HSV_ENC_256 : V4L2_HSV_ENC_180); vivid_send_source_change(dev, TV); vivid_send_source_change(dev, SVID); vivid_send_source_change(dev, HDMI); vivid_send_source_change(dev, WEBCAM); break; case VIVID_CID_QUANTIZATION: tpg_s_quantization(&dev->tpg, ctrl->val); vivid_send_source_change(dev, TV); vivid_send_source_change(dev, SVID); vivid_send_source_change(dev, HDMI); vivid_send_source_change(dev, WEBCAM); break; case V4L2_CID_DV_RX_RGB_RANGE: if (!vivid_is_hdmi_cap(dev)) break; tpg_s_rgb_range(&dev->tpg, ctrl->val); break; case VIVID_CID_LIMITED_RGB_RANGE: tpg_s_real_rgb_range(&dev->tpg, ctrl->val ? V4L2_DV_RGB_RANGE_LIMITED : V4L2_DV_RGB_RANGE_FULL); break; case VIVID_CID_ALPHA_MODE: tpg_s_alpha_mode(&dev->tpg, ctrl->val); break; case VIVID_CID_HOR_MOVEMENT: tpg_s_mv_hor_mode(&dev->tpg, ctrl->val); break; case VIVID_CID_VERT_MOVEMENT: tpg_s_mv_vert_mode(&dev->tpg, ctrl->val); break; case VIVID_CID_OSD_TEXT_MODE: dev->osd_mode = ctrl->val; break; case VIVID_CID_PERCENTAGE_FILL: tpg_s_perc_fill(&dev->tpg, ctrl->val); for (i = 0; i < VIDEO_MAX_FRAME; i++) dev->must_blank[i] = ctrl->val < 100; break; case VIVID_CID_INSERT_SAV: tpg_s_insert_sav(&dev->tpg, ctrl->val); break; case VIVID_CID_INSERT_EAV: tpg_s_insert_eav(&dev->tpg, ctrl->val); break; case VIVID_CID_INSERT_HDMI_VIDEO_GUARD_BAND: tpg_s_insert_hdmi_video_guard_band(&dev->tpg, ctrl->val); break; case VIVID_CID_HFLIP: dev->sensor_hflip = ctrl->val; tpg_s_hflip(&dev->tpg, dev->sensor_hflip ^ dev->hflip); break; case VIVID_CID_VFLIP: dev->sensor_vflip = ctrl->val; tpg_s_vflip(&dev->tpg, dev->sensor_vflip ^ dev->vflip); break; case VIVID_CID_REDUCED_FPS: dev->reduced_fps = ctrl->val; vivid_update_format_cap(dev, true); break; case VIVID_CID_HAS_CROP_CAP: dev->has_crop_cap = ctrl->val; vivid_update_format_cap(dev, true); break; case VIVID_CID_HAS_COMPOSE_CAP: dev->has_compose_cap = ctrl->val; vivid_update_format_cap(dev, true); break; case VIVID_CID_HAS_SCALER_CAP: dev->has_scaler_cap = ctrl->val; vivid_update_format_cap(dev, true); break; case VIVID_CID_SHOW_BORDER: tpg_s_show_border(&dev->tpg, ctrl->val); break; case VIVID_CID_SHOW_SQUARE: tpg_s_show_square(&dev->tpg, ctrl->val); break; case VIVID_CID_STD_ASPECT_RATIO: dev->std_aspect_ratio[dev->input] = ctrl->val; tpg_s_video_aspect(&dev->tpg, vivid_get_video_aspect(dev)); break; case VIVID_CID_DV_TIMINGS_SIGNAL_MODE: dev->dv_timings_signal_mode[dev->input] = dev->ctrl_dv_timings_signal_mode->val; dev->query_dv_timings[dev->input] = dev->ctrl_dv_timings->val; dev->power_present = 0; for (i = 0, j = 0; i < ARRAY_SIZE(dev->dv_timings_signal_mode); i++) if (dev->input_type[i] == HDMI) { if (dev->dv_timings_signal_mode[i] != NO_SIGNAL) dev->power_present |= (1 << j); j++; } __v4l2_ctrl_s_ctrl(dev->ctrl_rx_power_present, dev->power_present); v4l2_ctrl_activate(dev->ctrl_dv_timings, dev->dv_timings_signal_mode[dev->input] == SELECTED_DV_TIMINGS); vivid_update_quality(dev); vivid_send_source_change(dev, HDMI); break; case VIVID_CID_DV_TIMINGS_ASPECT_RATIO: dev->dv_timings_aspect_ratio[dev->input] = ctrl->val; tpg_s_video_aspect(&dev->tpg, vivid_get_video_aspect(dev)); break; case VIVID_CID_TSTAMP_SRC: dev->tstamp_src_is_soe = ctrl->val; dev->vb_vid_cap_q.timestamp_flags &= ~V4L2_BUF_FLAG_TSTAMP_SRC_MASK; if (dev->tstamp_src_is_soe) dev->vb_vid_cap_q.timestamp_flags |= V4L2_BUF_FLAG_TSTAMP_SRC_SOE; break; case VIVID_CID_MAX_EDID_BLOCKS: dev->edid_max_blocks = ctrl->val; if (dev->edid_blocks > dev->edid_max_blocks) dev->edid_blocks = dev->edid_max_blocks; break; } return 0; } static const struct v4l2_ctrl_ops vivid_vid_cap_ctrl_ops = { .s_ctrl = vivid_vid_cap_s_ctrl, }; static const char * const vivid_ctrl_hor_movement_strings[] = { "Move Left Fast", "Move Left", "Move Left Slow", "No Movement", "Move Right Slow", "Move Right", "Move Right Fast", NULL, }; static const struct v4l2_ctrl_config vivid_ctrl_hor_movement = { .ops = &vivid_vid_cap_ctrl_ops, .id = VIVID_CID_HOR_MOVEMENT, .name = "Horizontal Movement", .type = V4L2_CTRL_TYPE_MENU, .max = TPG_MOVE_POS_FAST, .def = TPG_MOVE_NONE, .qmenu = vivid_ctrl_hor_movement_strings, }; static const char * const vivid_ctrl_vert_movement_strings[] = { "Move Up Fast", "Move Up", "Move Up Slow", "No Movement", "Move Down Slow", "Move Down", "Move Down Fast", NULL, }; static const struct v4l2_ctrl_config vivid_ctrl_vert_movement = { .ops = &vivid_vid_cap_ctrl_ops, .id = VIVID_CID_VERT_MOVEMENT, .name = "Vertical Movement", .type = V4L2_CTRL_TYPE_MENU, .max = TPG_MOVE_POS_FAST, .def = TPG_MOVE_NONE, .qmenu = vivid_ctrl_vert_movement_strings, }; static const struct v4l2_ctrl_config vivid_ctrl_show_border = { .ops = &vivid_vid_cap_ctrl_ops, .id = VIVID_CID_SHOW_BORDER, .name = "Show Border", .type = V4L2_CTRL_TYPE_BOOLEAN, .max = 1, .step = 1, }; static const struct v4l2_ctrl_config vivid_ctrl_show_square = { .ops = &vivid_vid_cap_ctrl_ops, .id = VIVID_CID_SHOW_SQUARE, .name = "Show Square", .type = V4L2_CTRL_TYPE_BOOLEAN, .max = 1, .step = 1, }; static const char * const vivid_ctrl_osd_mode_strings[] = { "All", "Counters Only", "None", NULL, }; static const struct v4l2_ctrl_config vivid_ctrl_osd_mode = { .ops = &vivid_vid_cap_ctrl_ops, .id = VIVID_CID_OSD_TEXT_MODE, .name = "OSD Text Mode", .type = V4L2_CTRL_TYPE_MENU, .max = ARRAY_SIZE(vivid_ctrl_osd_mode_strings) - 2, .qmenu = vivid_ctrl_osd_mode_strings, }; static const struct v4l2_ctrl_config vivid_ctrl_perc_fill = { .ops = &vivid_vid_cap_ctrl_ops, .id = VIVID_CID_PERCENTAGE_FILL, .name = "Fill Percentage of Frame", .type = V4L2_CTRL_TYPE_INTEGER, .min = 0, .max = 100, .def = 100, .step = 1, }; static const struct v4l2_ctrl_config vivid_ctrl_insert_sav = { .ops = &vivid_vid_cap_ctrl_ops, .id = VIVID_CID_INSERT_SAV, .name = "Insert SAV Code in Image", .type = V4L2_CTRL_TYPE_BOOLEAN, .max = 1, .step = 1, }; static const struct v4l2_ctrl_config vivid_ctrl_insert_eav = { .ops = &vivid_vid_cap_ctrl_ops, .id = VIVID_CID_INSERT_EAV, .name = "Insert EAV Code in Image", .type = V4L2_CTRL_TYPE_BOOLEAN, .max = 1, .step = 1, }; static const struct v4l2_ctrl_config vivid_ctrl_insert_hdmi_video_guard_band = { .ops = &vivid_vid_cap_ctrl_ops, .id = VIVID_CID_INSERT_HDMI_VIDEO_GUARD_BAND, .name = "Insert Video Guard Band", .type = V4L2_CTRL_TYPE_BOOLEAN, .max = 1, .step = 1, }; static const struct v4l2_ctrl_config vivid_ctrl_hflip = { .ops = &vivid_vid_cap_ctrl_ops, .id = VIVID_CID_HFLIP, .name = "Sensor Flipped Horizontally", .type = V4L2_CTRL_TYPE_BOOLEAN, .max = 1, .step = 1, }; static const struct v4l2_ctrl_config vivid_ctrl_vflip = { .ops = &vivid_vid_cap_ctrl_ops, .id = VIVID_CID_VFLIP, .name = "Sensor Flipped Vertically", .type = V4L2_CTRL_TYPE_BOOLEAN, .max = 1, .step = 1, }; static const struct v4l2_ctrl_config vivid_ctrl_reduced_fps = { .ops = &vivid_vid_cap_ctrl_ops, .id = VIVID_CID_REDUCED_FPS, .name = "Reduced Framerate", .type = V4L2_CTRL_TYPE_BOOLEAN, .max = 1, .step = 1, }; static const struct v4l2_ctrl_config vivid_ctrl_has_crop_cap = { .ops = &vivid_vid_cap_ctrl_ops, .id = VIVID_CID_HAS_CROP_CAP, .name = "Enable Capture Cropping", .type = V4L2_CTRL_TYPE_BOOLEAN, .max = 1, .def = 1, .step = 1, }; static const struct v4l2_ctrl_config vivid_ctrl_has_compose_cap = { .ops = &vivid_vid_cap_ctrl_ops, .id = VIVID_CID_HAS_COMPOSE_CAP, .name = "Enable Capture Composing", .type = V4L2_CTRL_TYPE_BOOLEAN, .max = 1, .def = 1, .step = 1, }; static const struct v4l2_ctrl_config vivid_ctrl_has_scaler_cap = { .ops = &vivid_vid_cap_ctrl_ops, .id = VIVID_CID_HAS_SCALER_CAP, .name = "Enable Capture Scaler", .type = V4L2_CTRL_TYPE_BOOLEAN, .max = 1, .def = 1, .step = 1, }; static const char * const vivid_ctrl_tstamp_src_strings[] = { "End of Frame", "Start of Exposure", NULL, }; static const struct v4l2_ctrl_config vivid_ctrl_tstamp_src = { .ops = &vivid_vid_cap_ctrl_ops, .id = VIVID_CID_TSTAMP_SRC, .name = "Timestamp Source", .type = V4L2_CTRL_TYPE_MENU, .max = ARRAY_SIZE(vivid_ctrl_tstamp_src_strings) - 2, .qmenu = vivid_ctrl_tstamp_src_strings, }; static const struct v4l2_ctrl_config vivid_ctrl_std_aspect_ratio = { .ops = &vivid_vid_cap_ctrl_ops, .id = VIVID_CID_STD_ASPECT_RATIO, .name = "Standard Aspect Ratio", .type = V4L2_CTRL_TYPE_MENU, .min = 1, .max = 4, .def = 1, .qmenu = tpg_aspect_strings, }; static const char * const vivid_ctrl_dv_timings_signal_mode_strings[] = { "Current DV Timings", "No Signal", "No Lock", "Out of Range", "Selected DV Timings", "Cycle Through All DV Timings", "Custom DV Timings", NULL, }; static const struct v4l2_ctrl_config vivid_ctrl_dv_timings_signal_mode = { .ops = &vivid_vid_cap_ctrl_ops, .id = VIVID_CID_DV_TIMINGS_SIGNAL_MODE, .name = "DV Timings Signal Mode", .type = V4L2_CTRL_TYPE_MENU, .max = 5, .qmenu = vivid_ctrl_dv_timings_signal_mode_strings, }; static const struct v4l2_ctrl_config vivid_ctrl_dv_timings_aspect_ratio = { .ops = &vivid_vid_cap_ctrl_ops, .id = VIVID_CID_DV_TIMINGS_ASPECT_RATIO, .name = "DV Timings Aspect Ratio", .type = V4L2_CTRL_TYPE_MENU, .max = 3, .qmenu = tpg_aspect_strings, }; static const struct v4l2_ctrl_config vivid_ctrl_max_edid_blocks = { .ops = &vivid_vid_cap_ctrl_ops, .id = VIVID_CID_MAX_EDID_BLOCKS, .name = "Maximum EDID Blocks", .type = V4L2_CTRL_TYPE_INTEGER, .min = 1, .max = 256, .def = 2, .step = 1, }; static const char * const vivid_ctrl_colorspace_strings[] = { "SMPTE 170M", "Rec. 709", "sRGB", "opRGB", "BT.2020", "DCI-P3", "SMPTE 240M", "470 System M", "470 System BG", NULL, }; static const struct v4l2_ctrl_config vivid_ctrl_colorspace = { .ops = &vivid_vid_cap_ctrl_ops, .id = VIVID_CID_COLORSPACE, .name = "Colorspace", .type = V4L2_CTRL_TYPE_MENU, .max = ARRAY_SIZE(vivid_ctrl_colorspace_strings) - 2, .def = 2, .qmenu = vivid_ctrl_colorspace_strings, }; static const char * const vivid_ctrl_xfer_func_strings[] = { "Default", "Rec. 709", "sRGB", "opRGB", "SMPTE 240M", "None", "DCI-P3", "SMPTE 2084", NULL, }; static const struct v4l2_ctrl_config vivid_ctrl_xfer_func = { .ops = &vivid_vid_cap_ctrl_ops, .id = VIVID_CID_XFER_FUNC, .name = "Transfer Function", .type = V4L2_CTRL_TYPE_MENU, .max = ARRAY_SIZE(vivid_ctrl_xfer_func_strings) - 2, .qmenu = vivid_ctrl_xfer_func_strings, }; static const char * const vivid_ctrl_ycbcr_enc_strings[] = { "Default", "ITU-R 601", "Rec. 709", "xvYCC 601", "xvYCC 709", "", "BT.2020", "BT.2020 Constant Luminance", "SMPTE 240M", NULL, }; static const struct v4l2_ctrl_config vivid_ctrl_ycbcr_enc = { .ops = &vivid_vid_cap_ctrl_ops, .id = VIVID_CID_YCBCR_ENC, .name = "Y'CbCr Encoding", .type = V4L2_CTRL_TYPE_MENU, .menu_skip_mask = 1 << 5, .max = ARRAY_SIZE(vivid_ctrl_ycbcr_enc_strings) - 2, .qmenu = vivid_ctrl_ycbcr_enc_strings, }; static const char * const vivid_ctrl_hsv_enc_strings[] = { "Hue 0-179", "Hue 0-256", NULL, }; static const struct v4l2_ctrl_config vivid_ctrl_hsv_enc = { .ops = &vivid_vid_cap_ctrl_ops, .id = VIVID_CID_HSV_ENC, .name = "HSV Encoding", .type = V4L2_CTRL_TYPE_MENU, .max = ARRAY_SIZE(vivid_ctrl_hsv_enc_strings) - 2, .qmenu = vivid_ctrl_hsv_enc_strings, }; static const char * const vivid_ctrl_quantization_strings[] = { "Default", "Full Range", "Limited Range", NULL, }; static const struct v4l2_ctrl_config vivid_ctrl_quantization = { .ops = &vivid_vid_cap_ctrl_ops, .id = VIVID_CID_QUANTIZATION, .name = "Quantization", .type = V4L2_CTRL_TYPE_MENU, .max = ARRAY_SIZE(vivid_ctrl_quantization_strings) - 2, .qmenu = vivid_ctrl_quantization_strings, }; static const struct v4l2_ctrl_config vivid_ctrl_alpha_mode = { .ops = &vivid_vid_cap_ctrl_ops, .id = VIVID_CID_ALPHA_MODE, .name = "Apply Alpha To Red Only", .type = V4L2_CTRL_TYPE_BOOLEAN, .max = 1, .step = 1, }; static const struct v4l2_ctrl_config vivid_ctrl_limited_rgb_range = { .ops = &vivid_vid_cap_ctrl_ops, .id = VIVID_CID_LIMITED_RGB_RANGE, .name = "Limited RGB Range (16-235)", .type = V4L2_CTRL_TYPE_BOOLEAN, .max = 1, .step = 1, }; /* Video Loop Control */ static int vivid_loop_cap_s_ctrl(struct v4l2_ctrl *ctrl) { struct vivid_dev *dev = container_of(ctrl->handler, struct vivid_dev, ctrl_hdl_loop_cap); switch (ctrl->id) { case VIVID_CID_LOOP_VIDEO: dev->loop_video = ctrl->val; vivid_update_quality(dev); vivid_send_source_change(dev, SVID); vivid_send_source_change(dev, HDMI); break; } return 0; } static const struct v4l2_ctrl_ops vivid_loop_cap_ctrl_ops = { .s_ctrl = vivid_loop_cap_s_ctrl, }; static const struct v4l2_ctrl_config vivid_ctrl_loop_video = { .ops = &vivid_loop_cap_ctrl_ops, .id = VIVID_CID_LOOP_VIDEO, .name = "Loop Video", .type = V4L2_CTRL_TYPE_BOOLEAN, .max = 1, .step = 1, }; /* VBI Capture Control */ static int vivid_vbi_cap_s_ctrl(struct v4l2_ctrl *ctrl) { struct vivid_dev *dev = container_of(ctrl->handler, struct vivid_dev, ctrl_hdl_vbi_cap); switch (ctrl->id) { case VIVID_CID_VBI_CAP_INTERLACED: dev->vbi_cap_interlaced = ctrl->val; break; } return 0; } static const struct v4l2_ctrl_ops vivid_vbi_cap_ctrl_ops = { .s_ctrl = vivid_vbi_cap_s_ctrl, }; static const struct v4l2_ctrl_config vivid_ctrl_vbi_cap_interlaced = { .ops = &vivid_vbi_cap_ctrl_ops, .id = VIVID_CID_VBI_CAP_INTERLACED, .name = "Interlaced VBI Format", .type = V4L2_CTRL_TYPE_BOOLEAN, .max = 1, .step = 1, }; /* Video Output Controls */ static int vivid_vid_out_s_ctrl(struct v4l2_ctrl *ctrl) { struct vivid_dev *dev = container_of(ctrl->handler, struct vivid_dev, ctrl_hdl_vid_out); struct v4l2_bt_timings *bt = &dev->dv_timings_out.bt; u32 display_present = 0; unsigned int i, j, bus_idx; switch (ctrl->id) { case VIVID_CID_HAS_CROP_OUT: dev->has_crop_out = ctrl->val; vivid_update_format_out(dev); break; case VIVID_CID_HAS_COMPOSE_OUT: dev->has_compose_out = ctrl->val; vivid_update_format_out(dev); break; case VIVID_CID_HAS_SCALER_OUT: dev->has_scaler_out = ctrl->val; vivid_update_format_out(dev); break; case V4L2_CID_DV_TX_MODE: dev->dvi_d_out = ctrl->val == V4L2_DV_TX_MODE_DVI_D; if (!vivid_is_hdmi_out(dev)) break; if (!dev->dvi_d_out && (bt->flags & V4L2_DV_FL_IS_CE_VIDEO)) { if (bt->width == 720 && bt->height <= 576) dev->colorspace_out = V4L2_COLORSPACE_SMPTE170M; else dev->colorspace_out = V4L2_COLORSPACE_REC709; dev->quantization_out = V4L2_QUANTIZATION_DEFAULT; } else { dev->colorspace_out = V4L2_COLORSPACE_SRGB; dev->quantization_out = dev->dvi_d_out ? V4L2_QUANTIZATION_LIM_RANGE : V4L2_QUANTIZATION_DEFAULT; } if (dev->loop_video) vivid_send_source_change(dev, HDMI); break; case VIVID_CID_DISPLAY_PRESENT: if (dev->output_type[dev->output] != HDMI) break; dev->display_present[dev->output] = ctrl->val; for (i = 0, j = 0; i < dev->num_outputs; i++) if (dev->output_type[i] == HDMI) display_present |= dev->display_present[i] << j++; __v4l2_ctrl_s_ctrl(dev->ctrl_tx_rxsense, display_present); if (dev->edid_blocks) { __v4l2_ctrl_s_ctrl(dev->ctrl_tx_edid_present, display_present); __v4l2_ctrl_s_ctrl(dev->ctrl_tx_hotplug, display_present); } bus_idx = dev->cec_output2bus_map[dev->output]; if (!dev->cec_tx_adap[bus_idx]) break; if (ctrl->val && dev->edid_blocks) cec_s_phys_addr(dev->cec_tx_adap[bus_idx], dev->cec_tx_adap[bus_idx]->phys_addr, false); else cec_phys_addr_invalidate(dev->cec_tx_adap[bus_idx]); break; } return 0; } static const struct v4l2_ctrl_ops vivid_vid_out_ctrl_ops = { .s_ctrl = vivid_vid_out_s_ctrl, }; static const struct v4l2_ctrl_config vivid_ctrl_has_crop_out = { .ops = &vivid_vid_out_ctrl_ops, .id = VIVID_CID_HAS_CROP_OUT, .name = "Enable Output Cropping", .type = V4L2_CTRL_TYPE_BOOLEAN, .max = 1, .def = 1, .step = 1, }; static const struct v4l2_ctrl_config vivid_ctrl_has_compose_out = { .ops = &vivid_vid_out_ctrl_ops, .id = VIVID_CID_HAS_COMPOSE_OUT, .name = "Enable Output Composing", .type = V4L2_CTRL_TYPE_BOOLEAN, .max = 1, .def = 1, .step = 1, }; static const struct v4l2_ctrl_config vivid_ctrl_has_scaler_out = { .ops = &vivid_vid_out_ctrl_ops, .id = VIVID_CID_HAS_SCALER_OUT, .name = "Enable Output Scaler", .type = V4L2_CTRL_TYPE_BOOLEAN, .max = 1, .def = 1, .step = 1, }; static const struct v4l2_ctrl_config vivid_ctrl_display_present = { .ops = &vivid_vid_out_ctrl_ops, .id = VIVID_CID_DISPLAY_PRESENT, .name = "Display Present", .type = V4L2_CTRL_TYPE_BOOLEAN, .max = 1, .def = 1, .step = 1, }; /* Streaming Controls */ static int vivid_streaming_s_ctrl(struct v4l2_ctrl *ctrl) { struct vivid_dev *dev = container_of(ctrl->handler, struct vivid_dev, ctrl_hdl_streaming); switch (ctrl->id) { case VIVID_CID_DQBUF_ERROR: dev->dqbuf_error = true; break; case VIVID_CID_PERC_DROPPED: dev->perc_dropped_buffers = ctrl->val; break; case VIVID_CID_QUEUE_SETUP_ERROR: dev->queue_setup_error = true; break; case VIVID_CID_BUF_PREPARE_ERROR: dev->buf_prepare_error = true; break; case VIVID_CID_START_STR_ERROR: dev->start_streaming_error = true; break; case VIVID_CID_REQ_VALIDATE_ERROR: dev->req_validate_error = true; break; case VIVID_CID_QUEUE_ERROR: if (vb2_start_streaming_called(&dev->vb_vid_cap_q)) vb2_queue_error(&dev->vb_vid_cap_q); if (vb2_start_streaming_called(&dev->vb_vbi_cap_q)) vb2_queue_error(&dev->vb_vbi_cap_q); if (vb2_start_streaming_called(&dev->vb_vid_out_q)) vb2_queue_error(&dev->vb_vid_out_q); if (vb2_start_streaming_called(&dev->vb_vbi_out_q)) vb2_queue_error(&dev->vb_vbi_out_q); if (vb2_start_streaming_called(&dev->vb_sdr_cap_q)) vb2_queue_error(&dev->vb_sdr_cap_q); break; case VIVID_CID_SEQ_WRAP: dev->seq_wrap = ctrl->val; break; case VIVID_CID_TIME_WRAP: dev->time_wrap = ctrl->val; if (dev->time_wrap == 1) dev->time_wrap = (1ULL << 63) - NSEC_PER_SEC * 16ULL; else if (dev->time_wrap == 2) dev->time_wrap = ((1ULL << 31) - 16) * NSEC_PER_SEC; break; } return 0; } static const struct v4l2_ctrl_ops vivid_streaming_ctrl_ops = { .s_ctrl = vivid_streaming_s_ctrl, }; static const struct v4l2_ctrl_config vivid_ctrl_dqbuf_error = { .ops = &vivid_streaming_ctrl_ops, .id = VIVID_CID_DQBUF_ERROR, .name = "Inject V4L2_BUF_FLAG_ERROR", .type = V4L2_CTRL_TYPE_BUTTON, }; static const struct v4l2_ctrl_config vivid_ctrl_perc_dropped = { .ops = &vivid_streaming_ctrl_ops, .id = VIVID_CID_PERC_DROPPED, .name = "Percentage of Dropped Buffers", .type = V4L2_CTRL_TYPE_INTEGER, .min = 0, .max = 100, .step = 1, }; static const struct v4l2_ctrl_config vivid_ctrl_queue_setup_error = { .ops = &vivid_streaming_ctrl_ops, .id = VIVID_CID_QUEUE_SETUP_ERROR, .name = "Inject VIDIOC_REQBUFS Error", .type = V4L2_CTRL_TYPE_BUTTON, }; static const struct v4l2_ctrl_config vivid_ctrl_buf_prepare_error = { .ops = &vivid_streaming_ctrl_ops, .id = VIVID_CID_BUF_PREPARE_ERROR, .name = "Inject VIDIOC_QBUF Error", .type = V4L2_CTRL_TYPE_BUTTON, }; static const struct v4l2_ctrl_config vivid_ctrl_start_streaming_error = { .ops = &vivid_streaming_ctrl_ops, .id = VIVID_CID_START_STR_ERROR, .name = "Inject VIDIOC_STREAMON Error", .type = V4L2_CTRL_TYPE_BUTTON, }; static const struct v4l2_ctrl_config vivid_ctrl_queue_error = { .ops = &vivid_streaming_ctrl_ops, .id = VIVID_CID_QUEUE_ERROR, .name = "Inject Fatal Streaming Error", .type = V4L2_CTRL_TYPE_BUTTON, }; #ifdef CONFIG_MEDIA_CONTROLLER static const struct v4l2_ctrl_config vivid_ctrl_req_validate_error = { .ops = &vivid_streaming_ctrl_ops, .id = VIVID_CID_REQ_VALIDATE_ERROR, .name = "Inject req_validate() Error", .type = V4L2_CTRL_TYPE_BUTTON, }; #endif static const struct v4l2_ctrl_config vivid_ctrl_seq_wrap = { .ops = &vivid_streaming_ctrl_ops, .id = VIVID_CID_SEQ_WRAP, .name = "Wrap Sequence Number", .type = V4L2_CTRL_TYPE_BOOLEAN, .max = 1, .step = 1, }; static const char * const vivid_ctrl_time_wrap_strings[] = { "None", "64 Bit", "32 Bit", NULL, }; static const struct v4l2_ctrl_config vivid_ctrl_time_wrap = { .ops = &vivid_streaming_ctrl_ops, .id = VIVID_CID_TIME_WRAP, .name = "Wrap Timestamp", .type = V4L2_CTRL_TYPE_MENU, .max = ARRAY_SIZE(vivid_ctrl_time_wrap_strings) - 2, .qmenu = vivid_ctrl_time_wrap_strings, }; /* SDTV Capture Controls */ static int vivid_sdtv_cap_s_ctrl(struct v4l2_ctrl *ctrl) { struct vivid_dev *dev = container_of(ctrl->handler, struct vivid_dev, ctrl_hdl_sdtv_cap); switch (ctrl->id) { case VIVID_CID_STD_SIGNAL_MODE: dev->std_signal_mode[dev->input] = dev->ctrl_std_signal_mode->val; if (dev->std_signal_mode[dev->input] == SELECTED_STD) dev->query_std[dev->input] = vivid_standard[dev->ctrl_standard->val]; v4l2_ctrl_activate(dev->ctrl_standard, dev->std_signal_mode[dev->input] == SELECTED_STD); vivid_update_quality(dev); vivid_send_source_change(dev, TV); vivid_send_source_change(dev, SVID); break; } return 0; } static const struct v4l2_ctrl_ops vivid_sdtv_cap_ctrl_ops = { .s_ctrl = vivid_sdtv_cap_s_ctrl, }; static const char * const vivid_ctrl_std_signal_mode_strings[] = { "Current Standard", "No Signal", "No Lock", "", "Selected Standard", "Cycle Through All Standards", NULL, }; static const struct v4l2_ctrl_config vivid_ctrl_std_signal_mode = { .ops = &vivid_sdtv_cap_ctrl_ops, .id = VIVID_CID_STD_SIGNAL_MODE, .name = "Standard Signal Mode", .type = V4L2_CTRL_TYPE_MENU, .max = ARRAY_SIZE(vivid_ctrl_std_signal_mode_strings) - 2, .menu_skip_mask = 1 << 3, .qmenu = vivid_ctrl_std_signal_mode_strings, }; static const struct v4l2_ctrl_config vivid_ctrl_standard = { .ops = &vivid_sdtv_cap_ctrl_ops, .id = VIVID_CID_STANDARD, .name = "Standard", .type = V4L2_CTRL_TYPE_MENU, .max = 14, .qmenu = vivid_ctrl_standard_strings, }; /* Radio Receiver Controls */ static int vivid_radio_rx_s_ctrl(struct v4l2_ctrl *ctrl) { struct vivid_dev *dev = container_of(ctrl->handler, struct vivid_dev, ctrl_hdl_radio_rx); switch (ctrl->id) { case VIVID_CID_RADIO_SEEK_MODE: dev->radio_rx_hw_seek_mode = ctrl->val; break; case VIVID_CID_RADIO_SEEK_PROG_LIM: dev->radio_rx_hw_seek_prog_lim = ctrl->val; break; case VIVID_CID_RADIO_RX_RDS_RBDS: dev->rds_gen.use_rbds = ctrl->val; break; case VIVID_CID_RADIO_RX_RDS_BLOCKIO: dev->radio_rx_rds_controls = ctrl->val; dev->radio_rx_caps &= ~V4L2_CAP_READWRITE; dev->radio_rx_rds_use_alternates = false; if (!dev->radio_rx_rds_controls) { dev->radio_rx_caps |= V4L2_CAP_READWRITE; __v4l2_ctrl_s_ctrl(dev->radio_rx_rds_pty, 0); __v4l2_ctrl_s_ctrl(dev->radio_rx_rds_ta, 0); __v4l2_ctrl_s_ctrl(dev->radio_rx_rds_tp, 0); __v4l2_ctrl_s_ctrl(dev->radio_rx_rds_ms, 0); __v4l2_ctrl_s_ctrl_string(dev->radio_rx_rds_psname, ""); __v4l2_ctrl_s_ctrl_string(dev->radio_rx_rds_radiotext, ""); } v4l2_ctrl_activate(dev->radio_rx_rds_pty, dev->radio_rx_rds_controls); v4l2_ctrl_activate(dev->radio_rx_rds_psname, dev->radio_rx_rds_controls); v4l2_ctrl_activate(dev->radio_rx_rds_radiotext, dev->radio_rx_rds_controls); v4l2_ctrl_activate(dev->radio_rx_rds_ta, dev->radio_rx_rds_controls); v4l2_ctrl_activate(dev->radio_rx_rds_tp, dev->radio_rx_rds_controls); v4l2_ctrl_activate(dev->radio_rx_rds_ms, dev->radio_rx_rds_controls); dev->radio_rx_dev.device_caps = dev->radio_rx_caps; break; case V4L2_CID_RDS_RECEPTION: dev->radio_rx_rds_enabled = ctrl->val; break; } return 0; } static const struct v4l2_ctrl_ops vivid_radio_rx_ctrl_ops = { .s_ctrl = vivid_radio_rx_s_ctrl, }; static const char * const vivid_ctrl_radio_rds_mode_strings[] = { "Block I/O", "Controls", NULL, }; static const struct v4l2_ctrl_config vivid_ctrl_radio_rx_rds_blockio = { .ops = &vivid_radio_rx_ctrl_ops, .id = VIVID_CID_RADIO_RX_RDS_BLOCKIO, .name = "RDS Rx I/O Mode", .type = V4L2_CTRL_TYPE_MENU, .qmenu = vivid_ctrl_radio_rds_mode_strings, .max = 1, }; static const struct v4l2_ctrl_config vivid_ctrl_radio_rx_rds_rbds = { .ops = &vivid_radio_rx_ctrl_ops, .id = VIVID_CID_RADIO_RX_RDS_RBDS, .name = "Generate RBDS Instead of RDS", .type = V4L2_CTRL_TYPE_BOOLEAN, .max = 1, .step = 1, }; static const char * const vivid_ctrl_radio_hw_seek_mode_strings[] = { "Bounded", "Wrap Around", "Both", NULL, }; static const struct v4l2_ctrl_config vivid_ctrl_radio_hw_seek_mode = { .ops = &vivid_radio_rx_ctrl_ops, .id = VIVID_CID_RADIO_SEEK_MODE, .name = "Radio HW Seek Mode", .type = V4L2_CTRL_TYPE_MENU, .max = 2, .qmenu = vivid_ctrl_radio_hw_seek_mode_strings, }; static const struct v4l2_ctrl_config vivid_ctrl_radio_hw_seek_prog_lim = { .ops = &vivid_radio_rx_ctrl_ops, .id = VIVID_CID_RADIO_SEEK_PROG_LIM, .name = "Radio Programmable HW Seek", .type = V4L2_CTRL_TYPE_BOOLEAN, .max = 1, .step = 1, }; /* Radio Transmitter Controls */ static int vivid_radio_tx_s_ctrl(struct v4l2_ctrl *ctrl) { struct vivid_dev *dev = container_of(ctrl->handler, struct vivid_dev, ctrl_hdl_radio_tx); switch (ctrl->id) { case VIVID_CID_RADIO_TX_RDS_BLOCKIO: dev->radio_tx_rds_controls = ctrl->val; dev->radio_tx_caps &= ~V4L2_CAP_READWRITE; if (!dev->radio_tx_rds_controls) dev->radio_tx_caps |= V4L2_CAP_READWRITE; dev->radio_tx_dev.device_caps = dev->radio_tx_caps; break; case V4L2_CID_RDS_TX_PTY: if (dev->radio_rx_rds_controls) v4l2_ctrl_s_ctrl(dev->radio_rx_rds_pty, ctrl->val); break; case V4L2_CID_RDS_TX_PS_NAME: if (dev->radio_rx_rds_controls) v4l2_ctrl_s_ctrl_string(dev->radio_rx_rds_psname, ctrl->p_new.p_char); break; case V4L2_CID_RDS_TX_RADIO_TEXT: if (dev->radio_rx_rds_controls) v4l2_ctrl_s_ctrl_string(dev->radio_rx_rds_radiotext, ctrl->p_new.p_char); break; case V4L2_CID_RDS_TX_TRAFFIC_ANNOUNCEMENT: if (dev->radio_rx_rds_controls) v4l2_ctrl_s_ctrl(dev->radio_rx_rds_ta, ctrl->val); break; case V4L2_CID_RDS_TX_TRAFFIC_PROGRAM: if (dev->radio_rx_rds_controls) v4l2_ctrl_s_ctrl(dev->radio_rx_rds_tp, ctrl->val); break; case V4L2_CID_RDS_TX_MUSIC_SPEECH: if (dev->radio_rx_rds_controls) v4l2_ctrl_s_ctrl(dev->radio_rx_rds_ms, ctrl->val); break; } return 0; } static const struct v4l2_ctrl_ops vivid_radio_tx_ctrl_ops = { .s_ctrl = vivid_radio_tx_s_ctrl, }; static const struct v4l2_ctrl_config vivid_ctrl_radio_tx_rds_blockio = { .ops = &vivid_radio_tx_ctrl_ops, .id = VIVID_CID_RADIO_TX_RDS_BLOCKIO, .name = "RDS Tx I/O Mode", .type = V4L2_CTRL_TYPE_MENU, .qmenu = vivid_ctrl_radio_rds_mode_strings, .max = 1, .def = 1, }; /* SDR Capture Controls */ static int vivid_sdr_cap_s_ctrl(struct v4l2_ctrl *ctrl) { struct vivid_dev *dev = container_of(ctrl->handler, struct vivid_dev, ctrl_hdl_sdr_cap); switch (ctrl->id) { case VIVID_CID_SDR_CAP_FM_DEVIATION: dev->sdr_fm_deviation = ctrl->val; break; } return 0; } static const struct v4l2_ctrl_ops vivid_sdr_cap_ctrl_ops = { .s_ctrl = vivid_sdr_cap_s_ctrl, }; static const struct v4l2_ctrl_config vivid_ctrl_sdr_cap_fm_deviation = { .ops = &vivid_sdr_cap_ctrl_ops, .id = VIVID_CID_SDR_CAP_FM_DEVIATION, .name = "FM Deviation", .type = V4L2_CTRL_TYPE_INTEGER, .min = 100, .max = 200000, .def = 75000, .step = 1, }; /* Metadata Capture Control */ static int vivid_meta_cap_s_ctrl(struct v4l2_ctrl *ctrl) { struct vivid_dev *dev = container_of(ctrl->handler, struct vivid_dev, ctrl_hdl_meta_cap); switch (ctrl->id) { case VIVID_CID_META_CAP_GENERATE_PTS: dev->meta_pts = ctrl->val; break; case VIVID_CID_META_CAP_GENERATE_SCR: dev->meta_scr = ctrl->val; break; } return 0; } static const struct v4l2_ctrl_ops vivid_meta_cap_ctrl_ops = { .s_ctrl = vivid_meta_cap_s_ctrl, }; static const struct v4l2_ctrl_config vivid_ctrl_meta_has_pts = { .ops = &vivid_meta_cap_ctrl_ops, .id = VIVID_CID_META_CAP_GENERATE_PTS, .name = "Generate PTS", .type = V4L2_CTRL_TYPE_BOOLEAN, .max = 1, .def = 1, .step = 1, }; static const struct v4l2_ctrl_config vivid_ctrl_meta_has_src_clk = { .ops = &vivid_meta_cap_ctrl_ops, .id = VIVID_CID_META_CAP_GENERATE_SCR, .name = "Generate SCR", .type = V4L2_CTRL_TYPE_BOOLEAN, .max = 1, .def = 1, .step = 1, }; static const struct v4l2_ctrl_config vivid_ctrl_class = { .ops = &vivid_user_gen_ctrl_ops, .flags = V4L2_CTRL_FLAG_READ_ONLY | V4L2_CTRL_FLAG_WRITE_ONLY, .id = VIVID_CID_VIVID_CLASS, .name = "Vivid Controls", .type = V4L2_CTRL_TYPE_CTRL_CLASS, }; int vivid_create_controls(struct vivid_dev *dev, bool show_ccs_cap, bool show_ccs_out, bool no_error_inj, bool has_sdtv, bool has_hdmi) { struct v4l2_ctrl_handler *hdl_user_gen = &dev->ctrl_hdl_user_gen; struct v4l2_ctrl_handler *hdl_user_vid = &dev->ctrl_hdl_user_vid; struct v4l2_ctrl_handler *hdl_user_aud = &dev->ctrl_hdl_user_aud; struct v4l2_ctrl_handler *hdl_streaming = &dev->ctrl_hdl_streaming; struct v4l2_ctrl_handler *hdl_sdtv_cap = &dev->ctrl_hdl_sdtv_cap; struct v4l2_ctrl_handler *hdl_loop_cap = &dev->ctrl_hdl_loop_cap; struct v4l2_ctrl_handler *hdl_fb = &dev->ctrl_hdl_fb; struct v4l2_ctrl_handler *hdl_vid_cap = &dev->ctrl_hdl_vid_cap; struct v4l2_ctrl_handler *hdl_vid_out = &dev->ctrl_hdl_vid_out; struct v4l2_ctrl_handler *hdl_vbi_cap = &dev->ctrl_hdl_vbi_cap; struct v4l2_ctrl_handler *hdl_vbi_out = &dev->ctrl_hdl_vbi_out; struct v4l2_ctrl_handler *hdl_radio_rx = &dev->ctrl_hdl_radio_rx; struct v4l2_ctrl_handler *hdl_radio_tx = &dev->ctrl_hdl_radio_tx; struct v4l2_ctrl_handler *hdl_sdr_cap = &dev->ctrl_hdl_sdr_cap; struct v4l2_ctrl_handler *hdl_meta_cap = &dev->ctrl_hdl_meta_cap; struct v4l2_ctrl_handler *hdl_meta_out = &dev->ctrl_hdl_meta_out; struct v4l2_ctrl_handler *hdl_tch_cap = &dev->ctrl_hdl_touch_cap; struct v4l2_ctrl_config vivid_ctrl_dv_timings = { .ops = &vivid_vid_cap_ctrl_ops, .id = VIVID_CID_DV_TIMINGS, .name = "DV Timings", .type = V4L2_CTRL_TYPE_MENU, }; int i; v4l2_ctrl_handler_init(hdl_user_gen, 10); v4l2_ctrl_new_custom(hdl_user_gen, &vivid_ctrl_class, NULL); v4l2_ctrl_handler_init(hdl_user_vid, 9); v4l2_ctrl_new_custom(hdl_user_vid, &vivid_ctrl_class, NULL); v4l2_ctrl_handler_init(hdl_user_aud, 2); v4l2_ctrl_new_custom(hdl_user_aud, &vivid_ctrl_class, NULL); v4l2_ctrl_handler_init(hdl_streaming, 8); v4l2_ctrl_new_custom(hdl_streaming, &vivid_ctrl_class, NULL); v4l2_ctrl_handler_init(hdl_sdtv_cap, 2); v4l2_ctrl_new_custom(hdl_sdtv_cap, &vivid_ctrl_class, NULL); v4l2_ctrl_handler_init(hdl_loop_cap, 1); v4l2_ctrl_new_custom(hdl_loop_cap, &vivid_ctrl_class, NULL); v4l2_ctrl_handler_init(hdl_fb, 1); v4l2_ctrl_new_custom(hdl_fb, &vivid_ctrl_class, NULL); v4l2_ctrl_handler_init(hdl_vid_cap, 55); v4l2_ctrl_new_custom(hdl_vid_cap, &vivid_ctrl_class, NULL); v4l2_ctrl_handler_init(hdl_vid_out, 26); if (!no_error_inj || dev->has_fb || dev->num_hdmi_outputs) v4l2_ctrl_new_custom(hdl_vid_out, &vivid_ctrl_class, NULL); v4l2_ctrl_handler_init(hdl_vbi_cap, 21); v4l2_ctrl_new_custom(hdl_vbi_cap, &vivid_ctrl_class, NULL); v4l2_ctrl_handler_init(hdl_vbi_out, 19); if (!no_error_inj) v4l2_ctrl_new_custom(hdl_vbi_out, &vivid_ctrl_class, NULL); v4l2_ctrl_handler_init(hdl_radio_rx, 17); v4l2_ctrl_new_custom(hdl_radio_rx, &vivid_ctrl_class, NULL); v4l2_ctrl_handler_init(hdl_radio_tx, 17); v4l2_ctrl_new_custom(hdl_radio_tx, &vivid_ctrl_class, NULL); v4l2_ctrl_handler_init(hdl_sdr_cap, 19); v4l2_ctrl_new_custom(hdl_sdr_cap, &vivid_ctrl_class, NULL); v4l2_ctrl_handler_init(hdl_meta_cap, 2); v4l2_ctrl_new_custom(hdl_meta_cap, &vivid_ctrl_class, NULL); v4l2_ctrl_handler_init(hdl_meta_out, 2); v4l2_ctrl_new_custom(hdl_meta_out, &vivid_ctrl_class, NULL); v4l2_ctrl_handler_init(hdl_tch_cap, 2); v4l2_ctrl_new_custom(hdl_tch_cap, &vivid_ctrl_class, NULL); /* User Controls */ dev->volume = v4l2_ctrl_new_std(hdl_user_aud, NULL, V4L2_CID_AUDIO_VOLUME, 0, 255, 1, 200); dev->mute = v4l2_ctrl_new_std(hdl_user_aud, NULL, V4L2_CID_AUDIO_MUTE, 0, 1, 1, 0); if (dev->has_vid_cap) { dev->brightness = v4l2_ctrl_new_std(hdl_user_vid, &vivid_user_vid_ctrl_ops, V4L2_CID_BRIGHTNESS, 0, 255, 1, 128); for (i = 0; i < MAX_INPUTS; i++) dev->input_brightness[i] = 128; dev->contrast = v4l2_ctrl_new_std(hdl_user_vid, &vivid_user_vid_ctrl_ops, V4L2_CID_CONTRAST, 0, 255, 1, 128); dev->saturation = v4l2_ctrl_new_std(hdl_user_vid, &vivid_user_vid_ctrl_ops, V4L2_CID_SATURATION, 0, 255, 1, 128); dev->hue = v4l2_ctrl_new_std(hdl_user_vid, &vivid_user_vid_ctrl_ops, V4L2_CID_HUE, -128, 128, 1, 0); v4l2_ctrl_new_std(hdl_user_vid, &vivid_user_vid_ctrl_ops, V4L2_CID_HFLIP, 0, 1, 1, 0); v4l2_ctrl_new_std(hdl_user_vid, &vivid_user_vid_ctrl_ops, V4L2_CID_VFLIP, 0, 1, 1, 0); dev->autogain = v4l2_ctrl_new_std(hdl_user_vid, &vivid_user_vid_ctrl_ops, V4L2_CID_AUTOGAIN, 0, 1, 1, 1); dev->gain = v4l2_ctrl_new_std(hdl_user_vid, &vivid_user_vid_ctrl_ops, V4L2_CID_GAIN, 0, 255, 1, 100); dev->alpha = v4l2_ctrl_new_std(hdl_user_vid, &vivid_user_vid_ctrl_ops, V4L2_CID_ALPHA_COMPONENT, 0, 255, 1, 0); } dev->button = v4l2_ctrl_new_custom(hdl_user_gen, &vivid_ctrl_button, NULL); dev->int32 = v4l2_ctrl_new_custom(hdl_user_gen, &vivid_ctrl_int32, NULL); dev->int64 = v4l2_ctrl_new_custom(hdl_user_gen, &vivid_ctrl_int64, NULL); dev->boolean = v4l2_ctrl_new_custom(hdl_user_gen, &vivid_ctrl_boolean, NULL); dev->menu = v4l2_ctrl_new_custom(hdl_user_gen, &vivid_ctrl_menu, NULL); dev->string = v4l2_ctrl_new_custom(hdl_user_gen, &vivid_ctrl_string, NULL); dev->bitmask = v4l2_ctrl_new_custom(hdl_user_gen, &vivid_ctrl_bitmask, NULL); dev->int_menu = v4l2_ctrl_new_custom(hdl_user_gen, &vivid_ctrl_int_menu, NULL); dev->ro_int32 = v4l2_ctrl_new_custom(hdl_user_gen, &vivid_ctrl_ro_int32, NULL); v4l2_ctrl_new_custom(hdl_user_gen, &vivid_ctrl_area, NULL); v4l2_ctrl_new_custom(hdl_user_gen, &vivid_ctrl_u32_array, NULL); v4l2_ctrl_new_custom(hdl_user_gen, &vivid_ctrl_u32_dyn_array, NULL); v4l2_ctrl_new_custom(hdl_user_gen, &vivid_ctrl_u16_matrix, NULL); v4l2_ctrl_new_custom(hdl_user_gen, &vivid_ctrl_u8_4d_array, NULL); dev->pixel_array = v4l2_ctrl_new_custom(hdl_user_gen, &vivid_ctrl_u8_pixel_array, NULL); v4l2_ctrl_new_custom(hdl_user_gen, &vivid_ctrl_s32_array, NULL); v4l2_ctrl_new_custom(hdl_user_gen, &vivid_ctrl_s64_array, NULL); if (dev->has_vid_cap) { /* Image Processing Controls */ struct v4l2_ctrl_config vivid_ctrl_test_pattern = { .ops = &vivid_vid_cap_ctrl_ops, .id = VIVID_CID_TEST_PATTERN, .name = "Test Pattern", .type = V4L2_CTRL_TYPE_MENU, .max = TPG_PAT_NOISE, .qmenu = tpg_pattern_strings, }; dev->test_pattern = v4l2_ctrl_new_custom(hdl_vid_cap, &vivid_ctrl_test_pattern, NULL); v4l2_ctrl_new_custom(hdl_vid_cap, &vivid_ctrl_perc_fill, NULL); v4l2_ctrl_new_custom(hdl_vid_cap, &vivid_ctrl_hor_movement, NULL); v4l2_ctrl_new_custom(hdl_vid_cap, &vivid_ctrl_vert_movement, NULL); v4l2_ctrl_new_custom(hdl_vid_cap, &vivid_ctrl_osd_mode, NULL); v4l2_ctrl_new_custom(hdl_vid_cap, &vivid_ctrl_show_border, NULL); v4l2_ctrl_new_custom(hdl_vid_cap, &vivid_ctrl_show_square, NULL); v4l2_ctrl_new_custom(hdl_vid_cap, &vivid_ctrl_hflip, NULL); v4l2_ctrl_new_custom(hdl_vid_cap, &vivid_ctrl_vflip, NULL); v4l2_ctrl_new_custom(hdl_vid_cap, &vivid_ctrl_insert_sav, NULL); v4l2_ctrl_new_custom(hdl_vid_cap, &vivid_ctrl_insert_eav, NULL); v4l2_ctrl_new_custom(hdl_vid_cap, &vivid_ctrl_insert_hdmi_video_guard_band, NULL); v4l2_ctrl_new_custom(hdl_vid_cap, &vivid_ctrl_reduced_fps, NULL); if (show_ccs_cap) { dev->ctrl_has_crop_cap = v4l2_ctrl_new_custom(hdl_vid_cap, &vivid_ctrl_has_crop_cap, NULL); dev->ctrl_has_compose_cap = v4l2_ctrl_new_custom(hdl_vid_cap, &vivid_ctrl_has_compose_cap, NULL); dev->ctrl_has_scaler_cap = v4l2_ctrl_new_custom(hdl_vid_cap, &vivid_ctrl_has_scaler_cap, NULL); } v4l2_ctrl_new_custom(hdl_vid_cap, &vivid_ctrl_tstamp_src, NULL); dev->colorspace = v4l2_ctrl_new_custom(hdl_vid_cap, &vivid_ctrl_colorspace, NULL); v4l2_ctrl_new_custom(hdl_vid_cap, &vivid_ctrl_xfer_func, NULL); v4l2_ctrl_new_custom(hdl_vid_cap, &vivid_ctrl_ycbcr_enc, NULL); v4l2_ctrl_new_custom(hdl_vid_cap, &vivid_ctrl_hsv_enc, NULL); v4l2_ctrl_new_custom(hdl_vid_cap, &vivid_ctrl_quantization, NULL); v4l2_ctrl_new_custom(hdl_vid_cap, &vivid_ctrl_alpha_mode, NULL); } if (dev->has_vid_out && show_ccs_out) { dev->ctrl_has_crop_out = v4l2_ctrl_new_custom(hdl_vid_out, &vivid_ctrl_has_crop_out, NULL); dev->ctrl_has_compose_out = v4l2_ctrl_new_custom(hdl_vid_out, &vivid_ctrl_has_compose_out, NULL); dev->ctrl_has_scaler_out = v4l2_ctrl_new_custom(hdl_vid_out, &vivid_ctrl_has_scaler_out, NULL); } /* * Testing this driver with v4l2-compliance will trigger the error * injection controls, and after that nothing will work as expected. * So we have a module option to drop these error injecting controls * allowing us to run v4l2_compliance again. */ if (!no_error_inj) { v4l2_ctrl_new_custom(hdl_user_gen, &vivid_ctrl_disconnect, NULL); v4l2_ctrl_new_custom(hdl_streaming, &vivid_ctrl_dqbuf_error, NULL); v4l2_ctrl_new_custom(hdl_streaming, &vivid_ctrl_perc_dropped, NULL); v4l2_ctrl_new_custom(hdl_streaming, &vivid_ctrl_queue_setup_error, NULL); v4l2_ctrl_new_custom(hdl_streaming, &vivid_ctrl_buf_prepare_error, NULL); v4l2_ctrl_new_custom(hdl_streaming, &vivid_ctrl_start_streaming_error, NULL); v4l2_ctrl_new_custom(hdl_streaming, &vivid_ctrl_queue_error, NULL); #ifdef CONFIG_MEDIA_CONTROLLER v4l2_ctrl_new_custom(hdl_streaming, &vivid_ctrl_req_validate_error, NULL); #endif v4l2_ctrl_new_custom(hdl_streaming, &vivid_ctrl_seq_wrap, NULL); v4l2_ctrl_new_custom(hdl_streaming, &vivid_ctrl_time_wrap, NULL); } if (has_sdtv && (dev->has_vid_cap || dev->has_vbi_cap)) { if (dev->has_vid_cap) v4l2_ctrl_new_custom(hdl_vid_cap, &vivid_ctrl_std_aspect_ratio, NULL); dev->ctrl_std_signal_mode = v4l2_ctrl_new_custom(hdl_sdtv_cap, &vivid_ctrl_std_signal_mode, NULL); dev->ctrl_standard = v4l2_ctrl_new_custom(hdl_sdtv_cap, &vivid_ctrl_standard, NULL); if (dev->ctrl_std_signal_mode) v4l2_ctrl_cluster(2, &dev->ctrl_std_signal_mode); if (dev->has_raw_vbi_cap) v4l2_ctrl_new_custom(hdl_vbi_cap, &vivid_ctrl_vbi_cap_interlaced, NULL); } if (dev->num_hdmi_inputs) { s64 hdmi_input_mask = GENMASK(dev->num_hdmi_inputs - 1, 0); dev->ctrl_dv_timings_signal_mode = v4l2_ctrl_new_custom(hdl_vid_cap, &vivid_ctrl_dv_timings_signal_mode, NULL); vivid_ctrl_dv_timings.max = dev->query_dv_timings_size - 1; vivid_ctrl_dv_timings.qmenu = (const char * const *)dev->query_dv_timings_qmenu; dev->ctrl_dv_timings = v4l2_ctrl_new_custom(hdl_vid_cap, &vivid_ctrl_dv_timings, NULL); if (dev->ctrl_dv_timings_signal_mode) v4l2_ctrl_cluster(2, &dev->ctrl_dv_timings_signal_mode); v4l2_ctrl_new_custom(hdl_vid_cap, &vivid_ctrl_dv_timings_aspect_ratio, NULL); v4l2_ctrl_new_custom(hdl_vid_cap, &vivid_ctrl_max_edid_blocks, NULL); dev->real_rgb_range_cap = v4l2_ctrl_new_custom(hdl_vid_cap, &vivid_ctrl_limited_rgb_range, NULL); dev->rgb_range_cap = v4l2_ctrl_new_std_menu(hdl_vid_cap, &vivid_vid_cap_ctrl_ops, V4L2_CID_DV_RX_RGB_RANGE, V4L2_DV_RGB_RANGE_FULL, 0, V4L2_DV_RGB_RANGE_AUTO); dev->ctrl_rx_power_present = v4l2_ctrl_new_std(hdl_vid_cap, NULL, V4L2_CID_DV_RX_POWER_PRESENT, 0, hdmi_input_mask, 0, hdmi_input_mask); } if (dev->num_hdmi_outputs) { s64 hdmi_output_mask = GENMASK(dev->num_hdmi_outputs - 1, 0); /* * We aren't doing anything with this at the moment, but * HDMI outputs typically have this controls. */ dev->ctrl_tx_rgb_range = v4l2_ctrl_new_std_menu(hdl_vid_out, NULL, V4L2_CID_DV_TX_RGB_RANGE, V4L2_DV_RGB_RANGE_FULL, 0, V4L2_DV_RGB_RANGE_AUTO); dev->ctrl_tx_mode = v4l2_ctrl_new_std_menu(hdl_vid_out, NULL, V4L2_CID_DV_TX_MODE, V4L2_DV_TX_MODE_HDMI, 0, V4L2_DV_TX_MODE_HDMI); dev->ctrl_display_present = v4l2_ctrl_new_custom(hdl_vid_out, &vivid_ctrl_display_present, NULL); dev->ctrl_tx_hotplug = v4l2_ctrl_new_std(hdl_vid_out, NULL, V4L2_CID_DV_TX_HOTPLUG, 0, hdmi_output_mask, 0, hdmi_output_mask); dev->ctrl_tx_rxsense = v4l2_ctrl_new_std(hdl_vid_out, NULL, V4L2_CID_DV_TX_RXSENSE, 0, hdmi_output_mask, 0, hdmi_output_mask); dev->ctrl_tx_edid_present = v4l2_ctrl_new_std(hdl_vid_out, NULL, V4L2_CID_DV_TX_EDID_PRESENT, 0, hdmi_output_mask, 0, hdmi_output_mask); } if ((dev->has_vid_cap && dev->has_vid_out) || (dev->has_vbi_cap && dev->has_vbi_out)) v4l2_ctrl_new_custom(hdl_loop_cap, &vivid_ctrl_loop_video, NULL); if (dev->has_fb) v4l2_ctrl_new_custom(hdl_fb, &vivid_ctrl_clear_fb, NULL); if (dev->has_radio_rx) { v4l2_ctrl_new_custom(hdl_radio_rx, &vivid_ctrl_radio_hw_seek_mode, NULL); v4l2_ctrl_new_custom(hdl_radio_rx, &vivid_ctrl_radio_hw_seek_prog_lim, NULL); v4l2_ctrl_new_custom(hdl_radio_rx, &vivid_ctrl_radio_rx_rds_blockio, NULL); v4l2_ctrl_new_custom(hdl_radio_rx, &vivid_ctrl_radio_rx_rds_rbds, NULL); v4l2_ctrl_new_std(hdl_radio_rx, &vivid_radio_rx_ctrl_ops, V4L2_CID_RDS_RECEPTION, 0, 1, 1, 1); dev->radio_rx_rds_pty = v4l2_ctrl_new_std(hdl_radio_rx, &vivid_radio_rx_ctrl_ops, V4L2_CID_RDS_RX_PTY, 0, 31, 1, 0); dev->radio_rx_rds_psname = v4l2_ctrl_new_std(hdl_radio_rx, &vivid_radio_rx_ctrl_ops, V4L2_CID_RDS_RX_PS_NAME, 0, 8, 8, 0); dev->radio_rx_rds_radiotext = v4l2_ctrl_new_std(hdl_radio_rx, &vivid_radio_rx_ctrl_ops, V4L2_CID_RDS_RX_RADIO_TEXT, 0, 64, 64, 0); dev->radio_rx_rds_ta = v4l2_ctrl_new_std(hdl_radio_rx, &vivid_radio_rx_ctrl_ops, V4L2_CID_RDS_RX_TRAFFIC_ANNOUNCEMENT, 0, 1, 1, 0); dev->radio_rx_rds_tp = v4l2_ctrl_new_std(hdl_radio_rx, &vivid_radio_rx_ctrl_ops, V4L2_CID_RDS_RX_TRAFFIC_PROGRAM, 0, 1, 1, 0); dev->radio_rx_rds_ms = v4l2_ctrl_new_std(hdl_radio_rx, &vivid_radio_rx_ctrl_ops, V4L2_CID_RDS_RX_MUSIC_SPEECH, 0, 1, 1, 1); } if (dev->has_radio_tx) { v4l2_ctrl_new_custom(hdl_radio_tx, &vivid_ctrl_radio_tx_rds_blockio, NULL); dev->radio_tx_rds_pi = v4l2_ctrl_new_std(hdl_radio_tx, &vivid_radio_tx_ctrl_ops, V4L2_CID_RDS_TX_PI, 0, 0xffff, 1, 0x8088); dev->radio_tx_rds_pty = v4l2_ctrl_new_std(hdl_radio_tx, &vivid_radio_tx_ctrl_ops, V4L2_CID_RDS_TX_PTY, 0, 31, 1, 3); dev->radio_tx_rds_psname = v4l2_ctrl_new_std(hdl_radio_tx, &vivid_radio_tx_ctrl_ops, V4L2_CID_RDS_TX_PS_NAME, 0, 8, 8, 0); if (dev->radio_tx_rds_psname) v4l2_ctrl_s_ctrl_string(dev->radio_tx_rds_psname, "VIVID-TX"); dev->radio_tx_rds_radiotext = v4l2_ctrl_new_std(hdl_radio_tx, &vivid_radio_tx_ctrl_ops, V4L2_CID_RDS_TX_RADIO_TEXT, 0, 64 * 2, 64, 0); if (dev->radio_tx_rds_radiotext) v4l2_ctrl_s_ctrl_string(dev->radio_tx_rds_radiotext, "This is a VIVID default Radio Text template text, change at will"); dev->radio_tx_rds_mono_stereo = v4l2_ctrl_new_std(hdl_radio_tx, &vivid_radio_tx_ctrl_ops, V4L2_CID_RDS_TX_MONO_STEREO, 0, 1, 1, 1); dev->radio_tx_rds_art_head = v4l2_ctrl_new_std(hdl_radio_tx, &vivid_radio_tx_ctrl_ops, V4L2_CID_RDS_TX_ARTIFICIAL_HEAD, 0, 1, 1, 0); dev->radio_tx_rds_compressed = v4l2_ctrl_new_std(hdl_radio_tx, &vivid_radio_tx_ctrl_ops, V4L2_CID_RDS_TX_COMPRESSED, 0, 1, 1, 0); dev->radio_tx_rds_dyn_pty = v4l2_ctrl_new_std(hdl_radio_tx, &vivid_radio_tx_ctrl_ops, V4L2_CID_RDS_TX_DYNAMIC_PTY, 0, 1, 1, 0); dev->radio_tx_rds_ta = v4l2_ctrl_new_std(hdl_radio_tx, &vivid_radio_tx_ctrl_ops, V4L2_CID_RDS_TX_TRAFFIC_ANNOUNCEMENT, 0, 1, 1, 0); dev->radio_tx_rds_tp = v4l2_ctrl_new_std(hdl_radio_tx, &vivid_radio_tx_ctrl_ops, V4L2_CID_RDS_TX_TRAFFIC_PROGRAM, 0, 1, 1, 1); dev->radio_tx_rds_ms = v4l2_ctrl_new_std(hdl_radio_tx, &vivid_radio_tx_ctrl_ops, V4L2_CID_RDS_TX_MUSIC_SPEECH, 0, 1, 1, 1); } if (dev->has_sdr_cap) { v4l2_ctrl_new_custom(hdl_sdr_cap, &vivid_ctrl_sdr_cap_fm_deviation, NULL); } if (dev->has_meta_cap) { v4l2_ctrl_new_custom(hdl_meta_cap, &vivid_ctrl_meta_has_pts, NULL); v4l2_ctrl_new_custom(hdl_meta_cap, &vivid_ctrl_meta_has_src_clk, NULL); } if (hdl_user_gen->error) return hdl_user_gen->error; if (hdl_user_vid->error) return hdl_user_vid->error; if (hdl_user_aud->error) return hdl_user_aud->error; if (hdl_streaming->error) return hdl_streaming->error; if (hdl_sdr_cap->error) return hdl_sdr_cap->error; if (hdl_loop_cap->error) return hdl_loop_cap->error; if (dev->autogain) v4l2_ctrl_auto_cluster(2, &dev->autogain, 0, true); if (dev->has_vid_cap) { v4l2_ctrl_add_handler(hdl_vid_cap, hdl_user_gen, NULL, false); v4l2_ctrl_add_handler(hdl_vid_cap, hdl_user_vid, NULL, false); v4l2_ctrl_add_handler(hdl_vid_cap, hdl_user_aud, NULL, false); v4l2_ctrl_add_handler(hdl_vid_cap, hdl_streaming, NULL, false); v4l2_ctrl_add_handler(hdl_vid_cap, hdl_sdtv_cap, NULL, false); v4l2_ctrl_add_handler(hdl_vid_cap, hdl_loop_cap, NULL, false); v4l2_ctrl_add_handler(hdl_vid_cap, hdl_fb, NULL, false); if (hdl_vid_cap->error) return hdl_vid_cap->error; dev->vid_cap_dev.ctrl_handler = hdl_vid_cap; } if (dev->has_vid_out) { v4l2_ctrl_add_handler(hdl_vid_out, hdl_user_gen, NULL, false); v4l2_ctrl_add_handler(hdl_vid_out, hdl_user_aud, NULL, false); v4l2_ctrl_add_handler(hdl_vid_out, hdl_streaming, NULL, false); v4l2_ctrl_add_handler(hdl_vid_out, hdl_fb, NULL, false); if (hdl_vid_out->error) return hdl_vid_out->error; dev->vid_out_dev.ctrl_handler = hdl_vid_out; } if (dev->has_vbi_cap) { v4l2_ctrl_add_handler(hdl_vbi_cap, hdl_user_gen, NULL, false); v4l2_ctrl_add_handler(hdl_vbi_cap, hdl_streaming, NULL, false); v4l2_ctrl_add_handler(hdl_vbi_cap, hdl_sdtv_cap, NULL, false); v4l2_ctrl_add_handler(hdl_vbi_cap, hdl_loop_cap, NULL, false); if (hdl_vbi_cap->error) return hdl_vbi_cap->error; dev->vbi_cap_dev.ctrl_handler = hdl_vbi_cap; } if (dev->has_vbi_out) { v4l2_ctrl_add_handler(hdl_vbi_out, hdl_user_gen, NULL, false); v4l2_ctrl_add_handler(hdl_vbi_out, hdl_streaming, NULL, false); if (hdl_vbi_out->error) return hdl_vbi_out->error; dev->vbi_out_dev.ctrl_handler = hdl_vbi_out; } if (dev->has_radio_rx) { v4l2_ctrl_add_handler(hdl_radio_rx, hdl_user_gen, NULL, false); v4l2_ctrl_add_handler(hdl_radio_rx, hdl_user_aud, NULL, false); if (hdl_radio_rx->error) return hdl_radio_rx->error; dev->radio_rx_dev.ctrl_handler = hdl_radio_rx; } if (dev->has_radio_tx) { v4l2_ctrl_add_handler(hdl_radio_tx, hdl_user_gen, NULL, false); v4l2_ctrl_add_handler(hdl_radio_tx, hdl_user_aud, NULL, false); if (hdl_radio_tx->error) return hdl_radio_tx->error; dev->radio_tx_dev.ctrl_handler = hdl_radio_tx; } if (dev->has_sdr_cap) { v4l2_ctrl_add_handler(hdl_sdr_cap, hdl_user_gen, NULL, false); v4l2_ctrl_add_handler(hdl_sdr_cap, hdl_streaming, NULL, false); if (hdl_sdr_cap->error) return hdl_sdr_cap->error; dev->sdr_cap_dev.ctrl_handler = hdl_sdr_cap; } if (dev->has_meta_cap) { v4l2_ctrl_add_handler(hdl_meta_cap, hdl_user_gen, NULL, false); v4l2_ctrl_add_handler(hdl_meta_cap, hdl_streaming, NULL, false); if (hdl_meta_cap->error) return hdl_meta_cap->error; dev->meta_cap_dev.ctrl_handler = hdl_meta_cap; } if (dev->has_meta_out) { v4l2_ctrl_add_handler(hdl_meta_out, hdl_user_gen, NULL, false); v4l2_ctrl_add_handler(hdl_meta_out, hdl_streaming, NULL, false); if (hdl_meta_out->error) return hdl_meta_out->error; dev->meta_out_dev.ctrl_handler = hdl_meta_out; } if (dev->has_touch_cap) { v4l2_ctrl_add_handler(hdl_tch_cap, hdl_user_gen, NULL, false); v4l2_ctrl_add_handler(hdl_tch_cap, hdl_streaming, NULL, false); if (hdl_tch_cap->error) return hdl_tch_cap->error; dev->touch_cap_dev.ctrl_handler = hdl_tch_cap; } return 0; } void vivid_free_controls(struct vivid_dev *dev) { v4l2_ctrl_handler_free(&dev->ctrl_hdl_vid_cap); v4l2_ctrl_handler_free(&dev->ctrl_hdl_vid_out); v4l2_ctrl_handler_free(&dev->ctrl_hdl_vbi_cap); v4l2_ctrl_handler_free(&dev->ctrl_hdl_vbi_out); v4l2_ctrl_handler_free(&dev->ctrl_hdl_radio_rx); v4l2_ctrl_handler_free(&dev->ctrl_hdl_radio_tx); v4l2_ctrl_handler_free(&dev->ctrl_hdl_sdr_cap); v4l2_ctrl_handler_free(&dev->ctrl_hdl_user_gen); v4l2_ctrl_handler_free(&dev->ctrl_hdl_user_vid); v4l2_ctrl_handler_free(&dev->ctrl_hdl_user_aud); v4l2_ctrl_handler_free(&dev->ctrl_hdl_streaming); v4l2_ctrl_handler_free(&dev->ctrl_hdl_sdtv_cap); v4l2_ctrl_handler_free(&dev->ctrl_hdl_loop_cap); v4l2_ctrl_handler_free(&dev->ctrl_hdl_fb); v4l2_ctrl_handler_free(&dev->ctrl_hdl_meta_cap); v4l2_ctrl_handler_free(&dev->ctrl_hdl_meta_out); v4l2_ctrl_handler_free(&dev->ctrl_hdl_touch_cap); }
linux-master
drivers/media/test-drivers/vivid/vivid-ctrls.c
// SPDX-License-Identifier: GPL-2.0-only /* * vivid-radio-rx.c - radio receiver support functions. * * Copyright 2014 Cisco Systems, Inc. and/or its affiliates. All rights reserved. */ #include <linux/errno.h> #include <linux/kernel.h> #include <linux/delay.h> #include <linux/videodev2.h> #include <linux/v4l2-dv-timings.h> #include <linux/sched/signal.h> #include <media/v4l2-common.h> #include <media/v4l2-event.h> #include <media/v4l2-dv-timings.h> #include "vivid-core.h" #include "vivid-ctrls.h" #include "vivid-radio-common.h" #include "vivid-rds-gen.h" #include "vivid-radio-rx.h" ssize_t vivid_radio_rx_read(struct file *file, char __user *buf, size_t size, loff_t *offset) { struct vivid_dev *dev = video_drvdata(file); struct v4l2_rds_data *data = dev->rds_gen.data; bool use_alternates; ktime_t timestamp; unsigned blk; int perc; int i; if (dev->radio_rx_rds_controls) return -EINVAL; if (size < sizeof(*data)) return 0; size = sizeof(*data) * (size / sizeof(*data)); if (mutex_lock_interruptible(&dev->mutex)) return -ERESTARTSYS; if (dev->radio_rx_rds_owner && file->private_data != dev->radio_rx_rds_owner) { mutex_unlock(&dev->mutex); return -EBUSY; } if (dev->radio_rx_rds_owner == NULL) { vivid_radio_rds_init(dev); dev->radio_rx_rds_owner = file->private_data; } retry: timestamp = ktime_sub(ktime_get(), dev->radio_rds_init_time); blk = ktime_divns(timestamp, VIVID_RDS_NSEC_PER_BLK); use_alternates = (blk % VIVID_RDS_GEN_BLOCKS) & 1; if (dev->radio_rx_rds_last_block == 0 || dev->radio_rx_rds_use_alternates != use_alternates) { dev->radio_rx_rds_use_alternates = use_alternates; /* Re-init the RDS generator */ vivid_radio_rds_init(dev); } if (blk >= dev->radio_rx_rds_last_block + VIVID_RDS_GEN_BLOCKS) dev->radio_rx_rds_last_block = blk - VIVID_RDS_GEN_BLOCKS + 1; /* * No data is available if there hasn't been time to get new data, * or if the RDS receiver has been disabled, or if we use the data * from the RDS transmitter and that RDS transmitter has been disabled, * or if the signal quality is too weak. */ if (blk == dev->radio_rx_rds_last_block || !dev->radio_rx_rds_enabled || (dev->radio_rds_loop && !(dev->radio_tx_subchans & V4L2_TUNER_SUB_RDS)) || abs(dev->radio_rx_sig_qual) > 200) { mutex_unlock(&dev->mutex); if (file->f_flags & O_NONBLOCK) return -EWOULDBLOCK; if (msleep_interruptible(20) && signal_pending(current)) return -EINTR; if (mutex_lock_interruptible(&dev->mutex)) return -ERESTARTSYS; goto retry; } /* abs(dev->radio_rx_sig_qual) <= 200, map that to a 0-50% range */ perc = abs(dev->radio_rx_sig_qual) / 4; for (i = 0; i < size && blk > dev->radio_rx_rds_last_block; dev->radio_rx_rds_last_block++) { unsigned data_blk = dev->radio_rx_rds_last_block % VIVID_RDS_GEN_BLOCKS; struct v4l2_rds_data rds = data[data_blk]; if (data_blk == 0 && dev->radio_rds_loop) vivid_radio_rds_init(dev); if (perc && get_random_u32_below(100) < perc) { switch (get_random_u32_below(4)) { case 0: rds.block |= V4L2_RDS_BLOCK_CORRECTED; break; case 1: rds.block |= V4L2_RDS_BLOCK_INVALID; break; case 2: rds.block |= V4L2_RDS_BLOCK_ERROR; rds.lsb = get_random_u8(); rds.msb = get_random_u8(); break; case 3: /* Skip block altogether */ if (i) continue; /* * Must make sure at least one block is * returned, otherwise the application * might think that end-of-file occurred. */ break; } } if (copy_to_user(buf + i, &rds, sizeof(rds))) { i = -EFAULT; break; } i += sizeof(rds); } mutex_unlock(&dev->mutex); return i; } __poll_t vivid_radio_rx_poll(struct file *file, struct poll_table_struct *wait) { return EPOLLIN | EPOLLRDNORM | v4l2_ctrl_poll(file, wait); } int vivid_radio_rx_enum_freq_bands(struct file *file, void *fh, struct v4l2_frequency_band *band) { if (band->tuner != 0) return -EINVAL; if (band->index >= TOT_BANDS) return -EINVAL; *band = vivid_radio_bands[band->index]; return 0; } int vivid_radio_rx_s_hw_freq_seek(struct file *file, void *fh, const struct v4l2_hw_freq_seek *a) { struct vivid_dev *dev = video_drvdata(file); unsigned low, high; unsigned freq; unsigned spacing; unsigned band; if (a->tuner) return -EINVAL; if (a->wrap_around && dev->radio_rx_hw_seek_mode == VIVID_HW_SEEK_BOUNDED) return -EINVAL; if (!a->wrap_around && dev->radio_rx_hw_seek_mode == VIVID_HW_SEEK_WRAP) return -EINVAL; if (!a->rangelow ^ !a->rangehigh) return -EINVAL; if (file->f_flags & O_NONBLOCK) return -EWOULDBLOCK; if (a->rangelow) { for (band = 0; band < TOT_BANDS; band++) if (a->rangelow >= vivid_radio_bands[band].rangelow && a->rangehigh <= vivid_radio_bands[band].rangehigh) break; if (band == TOT_BANDS) return -EINVAL; if (!dev->radio_rx_hw_seek_prog_lim && (a->rangelow != vivid_radio_bands[band].rangelow || a->rangehigh != vivid_radio_bands[band].rangehigh)) return -EINVAL; low = a->rangelow; high = a->rangehigh; } else { for (band = 0; band < TOT_BANDS; band++) if (dev->radio_rx_freq >= vivid_radio_bands[band].rangelow && dev->radio_rx_freq <= vivid_radio_bands[band].rangehigh) break; if (band == TOT_BANDS) return -EINVAL; low = vivid_radio_bands[band].rangelow; high = vivid_radio_bands[band].rangehigh; } spacing = band == BAND_AM ? 1600 : 16000; freq = clamp(dev->radio_rx_freq, low, high); if (a->seek_upward) { freq = spacing * (freq / spacing) + spacing; if (freq > high) { if (!a->wrap_around) return -ENODATA; freq = spacing * (low / spacing) + spacing; if (freq >= dev->radio_rx_freq) return -ENODATA; } } else { freq = spacing * ((freq + spacing - 1) / spacing) - spacing; if (freq < low) { if (!a->wrap_around) return -ENODATA; freq = spacing * ((high + spacing - 1) / spacing) - spacing; if (freq <= dev->radio_rx_freq) return -ENODATA; } } return 0; } int vivid_radio_rx_g_tuner(struct file *file, void *fh, struct v4l2_tuner *vt) { struct vivid_dev *dev = video_drvdata(file); int delta = 800; int sig_qual; if (vt->index > 0) return -EINVAL; strscpy(vt->name, "AM/FM/SW Receiver", sizeof(vt->name)); vt->capability = V4L2_TUNER_CAP_LOW | V4L2_TUNER_CAP_STEREO | V4L2_TUNER_CAP_FREQ_BANDS | V4L2_TUNER_CAP_RDS | (dev->radio_rx_rds_controls ? V4L2_TUNER_CAP_RDS_CONTROLS : V4L2_TUNER_CAP_RDS_BLOCK_IO) | (dev->radio_rx_hw_seek_prog_lim ? V4L2_TUNER_CAP_HWSEEK_PROG_LIM : 0); switch (dev->radio_rx_hw_seek_mode) { case VIVID_HW_SEEK_BOUNDED: vt->capability |= V4L2_TUNER_CAP_HWSEEK_BOUNDED; break; case VIVID_HW_SEEK_WRAP: vt->capability |= V4L2_TUNER_CAP_HWSEEK_WRAP; break; case VIVID_HW_SEEK_BOTH: vt->capability |= V4L2_TUNER_CAP_HWSEEK_WRAP | V4L2_TUNER_CAP_HWSEEK_BOUNDED; break; } vt->rangelow = AM_FREQ_RANGE_LOW; vt->rangehigh = FM_FREQ_RANGE_HIGH; sig_qual = dev->radio_rx_sig_qual; vt->signal = abs(sig_qual) > delta ? 0 : 0xffff - ((unsigned)abs(sig_qual) * 0xffff) / delta; vt->afc = sig_qual > delta ? 0 : sig_qual; if (abs(sig_qual) > delta) vt->rxsubchans = 0; else if (dev->radio_rx_freq < FM_FREQ_RANGE_LOW || vt->signal < 0x8000) vt->rxsubchans = V4L2_TUNER_SUB_MONO; else if (dev->radio_rds_loop && !(dev->radio_tx_subchans & V4L2_TUNER_SUB_STEREO)) vt->rxsubchans = V4L2_TUNER_SUB_MONO; else vt->rxsubchans = V4L2_TUNER_SUB_STEREO; if (dev->radio_rx_rds_enabled && (!dev->radio_rds_loop || (dev->radio_tx_subchans & V4L2_TUNER_SUB_RDS)) && dev->radio_rx_freq >= FM_FREQ_RANGE_LOW && vt->signal >= 0xc000) vt->rxsubchans |= V4L2_TUNER_SUB_RDS; if (dev->radio_rx_rds_controls) vivid_radio_rds_init(dev); vt->audmode = dev->radio_rx_audmode; return 0; } int vivid_radio_rx_s_tuner(struct file *file, void *fh, const struct v4l2_tuner *vt) { struct vivid_dev *dev = video_drvdata(file); if (vt->index) return -EINVAL; dev->radio_rx_audmode = vt->audmode >= V4L2_TUNER_MODE_STEREO; return 0; }
linux-master
drivers/media/test-drivers/vivid/vivid-radio-rx.c
// SPDX-License-Identifier: GPL-2.0-only /* * vivid-vbi-gen.c - vbi generator support functions. * * Copyright 2014 Cisco Systems, Inc. and/or its affiliates. All rights reserved. */ #include <linux/errno.h> #include <linux/kernel.h> #include <linux/ktime.h> #include <linux/string.h> #include <linux/videodev2.h> #include "vivid-vbi-gen.h" static void wss_insert(u8 *wss, u32 val, unsigned size) { while (size--) *wss++ = (val & (1 << size)) ? 0xc0 : 0x10; } static void vivid_vbi_gen_wss_raw(const struct v4l2_sliced_vbi_data *data, u8 *buf, unsigned sampling_rate) { const unsigned rate = 5000000; /* WSS has a 5 MHz transmission rate */ u8 wss[29 + 24 + 24 + 24 + 18 + 18] = { 0 }; const unsigned zero = 0x07; const unsigned one = 0x38; unsigned bit = 0; u16 wss_data; int i; wss_insert(wss + bit, 0x1f1c71c7, 29); bit += 29; wss_insert(wss + bit, 0x1e3c1f, 24); bit += 24; wss_data = (data->data[1] << 8) | data->data[0]; for (i = 0; i <= 13; i++, bit += 6) wss_insert(wss + bit, (wss_data & (1 << i)) ? one : zero, 6); for (i = 0, bit = 0; bit < sizeof(wss); bit++) { unsigned n = ((bit + 1) * sampling_rate) / rate; while (i < n) buf[i++] = wss[bit]; } } static void vivid_vbi_gen_teletext_raw(const struct v4l2_sliced_vbi_data *data, u8 *buf, unsigned sampling_rate) { const unsigned rate = 6937500 / 10; /* Teletext has a 6.9375 MHz transmission rate */ u8 teletext[45] = { 0x55, 0x55, 0x27 }; unsigned bit = 0; int i; memcpy(teletext + 3, data->data, sizeof(teletext) - 3); /* prevents 32 bit overflow */ sampling_rate /= 10; for (i = 0, bit = 0; bit < sizeof(teletext) * 8; bit++) { unsigned n = ((bit + 1) * sampling_rate) / rate; u8 val = (teletext[bit / 8] & (1 << (bit & 7))) ? 0xc0 : 0x10; while (i < n) buf[i++] = val; } } static void cc_insert(u8 *cc, u8 ch) { unsigned tot = 0; unsigned i; for (i = 0; i < 7; i++) { cc[2 * i] = cc[2 * i + 1] = (ch & (1 << i)) ? 1 : 0; tot += cc[2 * i]; } cc[14] = cc[15] = !(tot & 1); } #define CC_PREAMBLE_BITS (14 + 4 + 2) static void vivid_vbi_gen_cc_raw(const struct v4l2_sliced_vbi_data *data, u8 *buf, unsigned sampling_rate) { const unsigned rate = 1000000; /* CC has a 1 MHz transmission rate */ u8 cc[CC_PREAMBLE_BITS + 2 * 16] = { /* Clock run-in: 7 cycles */ 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, /* 2 cycles of 0 */ 0, 0, 0, 0, /* Start bit of 1 (each bit is two cycles) */ 1, 1 }; unsigned bit, i; cc_insert(cc + CC_PREAMBLE_BITS, data->data[0]); cc_insert(cc + CC_PREAMBLE_BITS + 16, data->data[1]); for (i = 0, bit = 0; bit < sizeof(cc); bit++) { unsigned n = ((bit + 1) * sampling_rate) / rate; while (i < n) buf[i++] = cc[bit] ? 0xc0 : 0x10; } } void vivid_vbi_gen_raw(const struct vivid_vbi_gen_data *vbi, const struct v4l2_vbi_format *vbi_fmt, u8 *buf) { unsigned idx; for (idx = 0; idx < 25; idx++) { const struct v4l2_sliced_vbi_data *data = vbi->data + idx; unsigned start_2nd_field; unsigned line = data->line; u8 *linebuf = buf; start_2nd_field = (data->id & V4L2_SLICED_VBI_525) ? 263 : 313; if (data->field) line += start_2nd_field; line -= vbi_fmt->start[data->field]; if (vbi_fmt->flags & V4L2_VBI_INTERLACED) linebuf += (line * 2 + data->field) * vbi_fmt->samples_per_line; else linebuf += (line + data->field * vbi_fmt->count[0]) * vbi_fmt->samples_per_line; if (data->id == V4L2_SLICED_CAPTION_525) vivid_vbi_gen_cc_raw(data, linebuf, vbi_fmt->sampling_rate); else if (data->id == V4L2_SLICED_WSS_625) vivid_vbi_gen_wss_raw(data, linebuf, vbi_fmt->sampling_rate); else if (data->id == V4L2_SLICED_TELETEXT_B) vivid_vbi_gen_teletext_raw(data, linebuf, vbi_fmt->sampling_rate); } } static const u8 vivid_cc_sequence1[30] = { 0x14, 0x20, /* Resume Caption Loading */ 'H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', 0x14, 0x2f, /* End of Caption */ }; static const u8 vivid_cc_sequence2[30] = { 0x14, 0x20, /* Resume Caption Loading */ 'C', 'l', 'o', 's', 'e', 'd', ' ', 'c', 'a', 'p', 't', 'i', 'o', 'n', 's', ' ', 't', 'e', 's', 't', 0x14, 0x2f, /* End of Caption */ }; static u8 calc_parity(u8 val) { unsigned i; unsigned tot = 0; for (i = 0; i < 7; i++) tot += (val & (1 << i)) ? 1 : 0; return val | ((tot & 1) ? 0 : 0x80); } static void vivid_vbi_gen_set_time_of_day(u8 *packet) { struct tm tm; u8 checksum, i; time64_to_tm(ktime_get_real_seconds(), 0, &tm); packet[0] = calc_parity(0x07); packet[1] = calc_parity(0x01); packet[2] = calc_parity(0x40 | tm.tm_min); packet[3] = calc_parity(0x40 | tm.tm_hour); packet[4] = calc_parity(0x40 | tm.tm_mday); if (tm.tm_mday == 1 && tm.tm_mon == 2 && sys_tz.tz_minuteswest > tm.tm_min + tm.tm_hour * 60) packet[4] = calc_parity(0x60 | tm.tm_mday); packet[5] = calc_parity(0x40 | (1 + tm.tm_mon)); packet[6] = calc_parity(0x40 | (1 + tm.tm_wday)); packet[7] = calc_parity(0x40 | ((tm.tm_year - 90) & 0x3f)); packet[8] = calc_parity(0x0f); for (checksum = i = 0; i <= 8; i++) checksum += packet[i] & 0x7f; packet[9] = calc_parity(0x100 - checksum); packet[10] = calc_parity(0x07); packet[11] = calc_parity(0x04); if (sys_tz.tz_minuteswest >= 0) packet[12] = calc_parity(0x40 | ((sys_tz.tz_minuteswest / 60) & 0x1f)); else packet[12] = calc_parity(0x40 | ((24 + sys_tz.tz_minuteswest / 60) & 0x1f)); packet[13] = calc_parity(0); packet[14] = calc_parity(0x0f); for (checksum = 0, i = 10; i <= 14; i++) checksum += packet[i] & 0x7f; packet[15] = calc_parity(0x100 - checksum); } static const u8 hamming[16] = { 0x15, 0x02, 0x49, 0x5e, 0x64, 0x73, 0x38, 0x2f, 0xd0, 0xc7, 0x8c, 0x9b, 0xa1, 0xb6, 0xfd, 0xea }; static void vivid_vbi_gen_teletext(u8 *packet, unsigned line, unsigned frame) { unsigned offset = 2; unsigned i; packet[0] = hamming[1 + ((line & 1) << 3)]; packet[1] = hamming[line >> 1]; memset(packet + 2, 0x20, 40); if (line == 0) { /* subcode */ packet[2] = hamming[frame % 10]; packet[3] = hamming[frame / 10]; packet[4] = hamming[0]; packet[5] = hamming[0]; packet[6] = hamming[0]; packet[7] = hamming[0]; packet[8] = hamming[0]; packet[9] = hamming[1]; offset = 10; } packet += offset; memcpy(packet, "Page: 100 Row: 10", 17); packet[7] = '0' + frame / 10; packet[8] = '0' + frame % 10; packet[15] = '0' + line / 10; packet[16] = '0' + line % 10; for (i = 0; i < 42 - offset; i++) packet[i] = calc_parity(packet[i]); } void vivid_vbi_gen_sliced(struct vivid_vbi_gen_data *vbi, bool is_60hz, unsigned seqnr) { struct v4l2_sliced_vbi_data *data0 = vbi->data; struct v4l2_sliced_vbi_data *data1 = vbi->data + 1; unsigned frame = seqnr % 60; memset(vbi->data, 0, sizeof(vbi->data)); if (!is_60hz) { unsigned i; for (i = 0; i <= 11; i++) { data0->id = V4L2_SLICED_TELETEXT_B; data0->line = 7 + i; vivid_vbi_gen_teletext(data0->data, i, frame); data0++; } data0->id = V4L2_SLICED_WSS_625; data0->line = 23; /* 4x3 video aspect ratio */ data0->data[0] = 0x08; data0++; for (i = 0; i <= 11; i++) { data0->id = V4L2_SLICED_TELETEXT_B; data0->field = 1; data0->line = 7 + i; vivid_vbi_gen_teletext(data0->data, 12 + i, frame); data0++; } return; } data0->id = V4L2_SLICED_CAPTION_525; data0->line = 21; data1->id = V4L2_SLICED_CAPTION_525; data1->field = 1; data1->line = 21; if (frame < 15) { data0->data[0] = calc_parity(vivid_cc_sequence1[2 * frame]); data0->data[1] = calc_parity(vivid_cc_sequence1[2 * frame + 1]); } else if (frame >= 30 && frame < 45) { frame -= 30; data0->data[0] = calc_parity(vivid_cc_sequence2[2 * frame]); data0->data[1] = calc_parity(vivid_cc_sequence2[2 * frame + 1]); } else { data0->data[0] = calc_parity(0); data0->data[1] = calc_parity(0); } frame = seqnr % (30 * 60); switch (frame) { case 0: vivid_vbi_gen_set_time_of_day(vbi->time_of_day_packet); fallthrough; case 1 ... 7: data1->data[0] = vbi->time_of_day_packet[frame * 2]; data1->data[1] = vbi->time_of_day_packet[frame * 2 + 1]; break; default: data1->data[0] = calc_parity(0); data1->data[1] = calc_parity(0); break; } }
linux-master
drivers/media/test-drivers/vivid/vivid-vbi-gen.c
// SPDX-License-Identifier: GPL-2.0-only /* * vivid-osd.c - osd support for testing overlays. * * Copyright 2014 Cisco Systems, Inc. and/or its affiliates. All rights reserved. */ #include <linux/module.h> #include <linux/errno.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/font.h> #include <linux/mutex.h> #include <linux/videodev2.h> #include <linux/kthread.h> #include <linux/freezer.h> #include <linux/fb.h> #include <media/videobuf2-vmalloc.h> #include <media/v4l2-device.h> #include <media/v4l2-ioctl.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-fh.h> #include <media/v4l2-event.h> #include <media/v4l2-common.h> #include "vivid-core.h" #include "vivid-osd.h" #define MAX_OSD_WIDTH 720 #define MAX_OSD_HEIGHT 576 /* * Order: white, yellow, cyan, green, magenta, red, blue, black, * and same again with the alpha bit set (if any) */ static const u16 rgb555[16] = { 0x7fff, 0x7fe0, 0x03ff, 0x03e0, 0x7c1f, 0x7c00, 0x001f, 0x0000, 0xffff, 0xffe0, 0x83ff, 0x83e0, 0xfc1f, 0xfc00, 0x801f, 0x8000 }; static const u16 rgb565[16] = { 0xffff, 0xffe0, 0x07ff, 0x07e0, 0xf81f, 0xf800, 0x001f, 0x0000, 0xffff, 0xffe0, 0x07ff, 0x07e0, 0xf81f, 0xf800, 0x001f, 0x0000 }; void vivid_clear_fb(struct vivid_dev *dev) { void *p = dev->video_vbase; const u16 *rgb = rgb555; unsigned x, y; if (dev->fb_defined.green.length == 6) rgb = rgb565; for (y = 0; y < dev->display_height; y++) { u16 *d = p; for (x = 0; x < dev->display_width; x++) d[x] = rgb[(y / 16 + x / 16) % 16]; p += dev->display_byte_stride; } } /* --------------------------------------------------------------------- */ static int vivid_fb_ioctl(struct fb_info *info, unsigned cmd, unsigned long arg) { struct vivid_dev *dev = (struct vivid_dev *)info->par; switch (cmd) { case FBIOGET_VBLANK: { struct fb_vblank vblank; memset(&vblank, 0, sizeof(vblank)); vblank.flags = FB_VBLANK_HAVE_COUNT | FB_VBLANK_HAVE_VCOUNT | FB_VBLANK_HAVE_VSYNC; vblank.count = 0; vblank.vcount = 0; vblank.hcount = 0; if (copy_to_user((void __user *)arg, &vblank, sizeof(vblank))) return -EFAULT; return 0; } default: dprintk(dev, 1, "Unknown ioctl %08x\n", cmd); return -EINVAL; } return 0; } /* Framebuffer device handling */ static int vivid_fb_set_var(struct vivid_dev *dev, struct fb_var_screeninfo *var) { dprintk(dev, 1, "vivid_fb_set_var\n"); if (var->bits_per_pixel != 16) { dprintk(dev, 1, "vivid_fb_set_var - Invalid bpp\n"); return -EINVAL; } dev->display_byte_stride = var->xres * dev->bytes_per_pixel; return 0; } static int vivid_fb_get_fix(struct vivid_dev *dev, struct fb_fix_screeninfo *fix) { dprintk(dev, 1, "vivid_fb_get_fix\n"); memset(fix, 0, sizeof(struct fb_fix_screeninfo)); strscpy(fix->id, "vioverlay fb", sizeof(fix->id)); fix->smem_start = dev->video_pbase; fix->smem_len = dev->video_buffer_size; fix->type = FB_TYPE_PACKED_PIXELS; fix->visual = FB_VISUAL_TRUECOLOR; fix->xpanstep = 1; fix->ypanstep = 1; fix->ywrapstep = 0; fix->line_length = dev->display_byte_stride; fix->accel = FB_ACCEL_NONE; return 0; } /* Check the requested display mode, returning -EINVAL if we can't handle it. */ static int _vivid_fb_check_var(struct fb_var_screeninfo *var, struct vivid_dev *dev) { dprintk(dev, 1, "vivid_fb_check_var\n"); var->bits_per_pixel = 16; if (var->green.length == 5) { var->red.offset = 10; var->red.length = 5; var->green.offset = 5; var->green.length = 5; var->blue.offset = 0; var->blue.length = 5; var->transp.offset = 15; var->transp.length = 1; } else { var->red.offset = 11; var->red.length = 5; var->green.offset = 5; var->green.length = 6; var->blue.offset = 0; var->blue.length = 5; var->transp.offset = 0; var->transp.length = 0; } var->xoffset = var->yoffset = 0; var->left_margin = var->upper_margin = 0; var->nonstd = 0; var->vmode &= ~FB_VMODE_MASK; var->vmode |= FB_VMODE_NONINTERLACED; /* Dummy values */ var->hsync_len = 24; var->vsync_len = 2; var->pixclock = 84316; var->right_margin = 776; var->lower_margin = 591; return 0; } static int vivid_fb_check_var(struct fb_var_screeninfo *var, struct fb_info *info) { struct vivid_dev *dev = (struct vivid_dev *) info->par; dprintk(dev, 1, "vivid_fb_check_var\n"); return _vivid_fb_check_var(var, dev); } static int vivid_fb_pan_display(struct fb_var_screeninfo *var, struct fb_info *info) { return 0; } static int vivid_fb_set_par(struct fb_info *info) { int rc = 0; struct vivid_dev *dev = (struct vivid_dev *) info->par; dprintk(dev, 1, "vivid_fb_set_par\n"); rc = vivid_fb_set_var(dev, &info->var); vivid_fb_get_fix(dev, &info->fix); return rc; } static int vivid_fb_setcolreg(unsigned regno, unsigned red, unsigned green, unsigned blue, unsigned transp, struct fb_info *info) { u32 color, *palette; if (regno >= info->cmap.len) return -EINVAL; color = ((transp & 0xFF00) << 16) | ((red & 0xFF00) << 8) | (green & 0xFF00) | ((blue & 0xFF00) >> 8); if (regno >= 16) return -EINVAL; palette = info->pseudo_palette; if (info->var.bits_per_pixel == 16) { switch (info->var.green.length) { case 6: color = (red & 0xf800) | ((green & 0xfc00) >> 5) | ((blue & 0xf800) >> 11); break; case 5: color = ((red & 0xf800) >> 1) | ((green & 0xf800) >> 6) | ((blue & 0xf800) >> 11) | (transp ? 0x8000 : 0); break; } } palette[regno] = color; return 0; } /* We don't really support blanking. All this does is enable or disable the OSD. */ static int vivid_fb_blank(int blank_mode, struct fb_info *info) { struct vivid_dev *dev = (struct vivid_dev *)info->par; dprintk(dev, 1, "Set blanking mode : %d\n", blank_mode); switch (blank_mode) { case FB_BLANK_UNBLANK: break; case FB_BLANK_NORMAL: case FB_BLANK_HSYNC_SUSPEND: case FB_BLANK_VSYNC_SUSPEND: case FB_BLANK_POWERDOWN: break; } return 0; } static const struct fb_ops vivid_fb_ops = { .owner = THIS_MODULE, FB_DEFAULT_IOMEM_OPS, .fb_check_var = vivid_fb_check_var, .fb_set_par = vivid_fb_set_par, .fb_setcolreg = vivid_fb_setcolreg, .fb_cursor = NULL, .fb_ioctl = vivid_fb_ioctl, .fb_pan_display = vivid_fb_pan_display, .fb_blank = vivid_fb_blank, }; /* Initialization */ /* Setup our initial video mode */ static int vivid_fb_init_vidmode(struct vivid_dev *dev) { struct v4l2_rect start_window; /* Color mode */ dev->bits_per_pixel = 16; dev->bytes_per_pixel = dev->bits_per_pixel / 8; start_window.width = MAX_OSD_WIDTH; start_window.left = 0; dev->display_byte_stride = start_window.width * dev->bytes_per_pixel; /* Vertical size & position */ start_window.height = MAX_OSD_HEIGHT; start_window.top = 0; dev->display_width = start_window.width; dev->display_height = start_window.height; /* Generate a valid fb_var_screeninfo */ dev->fb_defined.xres = dev->display_width; dev->fb_defined.yres = dev->display_height; dev->fb_defined.xres_virtual = dev->display_width; dev->fb_defined.yres_virtual = dev->display_height; dev->fb_defined.bits_per_pixel = dev->bits_per_pixel; dev->fb_defined.vmode = FB_VMODE_NONINTERLACED; dev->fb_defined.left_margin = start_window.left + 1; dev->fb_defined.upper_margin = start_window.top + 1; dev->fb_defined.accel_flags = FB_ACCEL_NONE; dev->fb_defined.nonstd = 0; /* set default to 1:5:5:5 */ dev->fb_defined.green.length = 5; /* We've filled in the most data, let the usual mode check routine fill in the rest. */ _vivid_fb_check_var(&dev->fb_defined, dev); /* Generate valid fb_fix_screeninfo */ vivid_fb_get_fix(dev, &dev->fb_fix); /* Generate valid fb_info */ dev->fb_info.node = -1; dev->fb_info.par = dev; dev->fb_info.var = dev->fb_defined; dev->fb_info.fix = dev->fb_fix; dev->fb_info.screen_base = (u8 __iomem *)dev->video_vbase; dev->fb_info.fbops = &vivid_fb_ops; /* Supply some monitor specs. Bogus values will do for now */ dev->fb_info.monspecs.hfmin = 8000; dev->fb_info.monspecs.hfmax = 70000; dev->fb_info.monspecs.vfmin = 10; dev->fb_info.monspecs.vfmax = 100; /* Allocate color map */ if (fb_alloc_cmap(&dev->fb_info.cmap, 256, 1)) { pr_err("abort, unable to alloc cmap\n"); return -ENOMEM; } /* Allocate the pseudo palette */ dev->fb_info.pseudo_palette = kmalloc_array(16, sizeof(u32), GFP_KERNEL); return dev->fb_info.pseudo_palette ? 0 : -ENOMEM; } /* Release any memory we've grabbed */ void vivid_fb_release_buffers(struct vivid_dev *dev) { if (dev->video_vbase == NULL) return; /* Release cmap */ if (dev->fb_info.cmap.len) fb_dealloc_cmap(&dev->fb_info.cmap); /* Release pseudo palette */ kfree(dev->fb_info.pseudo_palette); kfree(dev->video_vbase); } /* Initialize the specified card */ int vivid_fb_init(struct vivid_dev *dev) { int ret; dev->video_buffer_size = MAX_OSD_HEIGHT * MAX_OSD_WIDTH * 2; dev->video_vbase = kzalloc(dev->video_buffer_size, GFP_KERNEL); if (dev->video_vbase == NULL) return -ENOMEM; dev->video_pbase = virt_to_phys(dev->video_vbase); pr_info("Framebuffer at 0x%lx, mapped to 0x%p, size %dk\n", dev->video_pbase, dev->video_vbase, dev->video_buffer_size / 1024); /* Set the startup video mode information */ ret = vivid_fb_init_vidmode(dev); if (ret) { vivid_fb_release_buffers(dev); return ret; } vivid_clear_fb(dev); /* Register the framebuffer */ if (register_framebuffer(&dev->fb_info) < 0) { vivid_fb_release_buffers(dev); return -EINVAL; } /* Set the card to the requested mode */ vivid_fb_set_par(&dev->fb_info); return 0; }
linux-master
drivers/media/test-drivers/vivid/vivid-osd.c
// SPDX-License-Identifier: GPL-2.0-only /* * vivid-sdr-cap.c - software defined radio support functions. * * Copyright 2014 Cisco Systems, Inc. and/or its affiliates. All rights reserved. */ #include <linux/errno.h> #include <linux/kernel.h> #include <linux/delay.h> #include <linux/kthread.h> #include <linux/freezer.h> #include <linux/math64.h> #include <linux/videodev2.h> #include <linux/v4l2-dv-timings.h> #include <media/v4l2-common.h> #include <media/v4l2-event.h> #include <media/v4l2-dv-timings.h> #include <linux/fixp-arith.h> #include <linux/jiffies.h> #include "vivid-core.h" #include "vivid-ctrls.h" #include "vivid-sdr-cap.h" /* stream formats */ struct vivid_format { u32 pixelformat; u32 buffersize; }; /* format descriptions for capture and preview */ static const struct vivid_format formats[] = { { .pixelformat = V4L2_SDR_FMT_CU8, .buffersize = SDR_CAP_SAMPLES_PER_BUF * 2, }, { .pixelformat = V4L2_SDR_FMT_CS8, .buffersize = SDR_CAP_SAMPLES_PER_BUF * 2, }, }; static const struct v4l2_frequency_band bands_adc[] = { { .tuner = 0, .type = V4L2_TUNER_ADC, .index = 0, .capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS, .rangelow = 300000, .rangehigh = 300000, }, { .tuner = 0, .type = V4L2_TUNER_ADC, .index = 1, .capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS, .rangelow = 900001, .rangehigh = 2800000, }, { .tuner = 0, .type = V4L2_TUNER_ADC, .index = 2, .capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS, .rangelow = 3200000, .rangehigh = 3200000, }, }; /* ADC band midpoints */ #define BAND_ADC_0 ((bands_adc[0].rangehigh + bands_adc[1].rangelow) / 2) #define BAND_ADC_1 ((bands_adc[1].rangehigh + bands_adc[2].rangelow) / 2) static const struct v4l2_frequency_band bands_fm[] = { { .tuner = 1, .type = V4L2_TUNER_RF, .index = 0, .capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS, .rangelow = 50000000, .rangehigh = 2000000000, }, }; static void vivid_thread_sdr_cap_tick(struct vivid_dev *dev) { struct vivid_buffer *sdr_cap_buf = NULL; dprintk(dev, 1, "SDR Capture Thread Tick\n"); /* Drop a certain percentage of buffers. */ if (dev->perc_dropped_buffers && get_random_u32_below(100) < dev->perc_dropped_buffers) return; spin_lock(&dev->slock); if (!list_empty(&dev->sdr_cap_active)) { sdr_cap_buf = list_entry(dev->sdr_cap_active.next, struct vivid_buffer, list); list_del(&sdr_cap_buf->list); } spin_unlock(&dev->slock); if (sdr_cap_buf) { sdr_cap_buf->vb.sequence = dev->sdr_cap_with_seq_wrap_count; v4l2_ctrl_request_setup(sdr_cap_buf->vb.vb2_buf.req_obj.req, &dev->ctrl_hdl_sdr_cap); v4l2_ctrl_request_complete(sdr_cap_buf->vb.vb2_buf.req_obj.req, &dev->ctrl_hdl_sdr_cap); vivid_sdr_cap_process(dev, sdr_cap_buf); sdr_cap_buf->vb.vb2_buf.timestamp = ktime_get_ns() + dev->time_wrap_offset; vb2_buffer_done(&sdr_cap_buf->vb.vb2_buf, dev->dqbuf_error ? VB2_BUF_STATE_ERROR : VB2_BUF_STATE_DONE); dev->dqbuf_error = false; } } static int vivid_thread_sdr_cap(void *data) { struct vivid_dev *dev = data; u64 samples_since_start; u64 buffers_since_start; u64 next_jiffies_since_start; unsigned long jiffies_since_start; unsigned long cur_jiffies; unsigned wait_jiffies; dprintk(dev, 1, "SDR Capture Thread Start\n"); set_freezable(); /* Resets frame counters */ dev->sdr_cap_seq_offset = 0; dev->sdr_cap_seq_count = 0; dev->jiffies_sdr_cap = jiffies; dev->sdr_cap_seq_resync = false; if (dev->time_wrap) dev->time_wrap_offset = dev->time_wrap - ktime_get_ns(); else dev->time_wrap_offset = 0; for (;;) { try_to_freeze(); if (kthread_should_stop()) break; if (!mutex_trylock(&dev->mutex)) { schedule(); continue; } cur_jiffies = jiffies; if (dev->sdr_cap_seq_resync) { dev->jiffies_sdr_cap = cur_jiffies; dev->sdr_cap_seq_offset = dev->sdr_cap_seq_count + 1; dev->sdr_cap_seq_count = 0; dev->sdr_cap_seq_resync = false; } /* Calculate the number of jiffies since we started streaming */ jiffies_since_start = cur_jiffies - dev->jiffies_sdr_cap; /* Get the number of buffers streamed since the start */ buffers_since_start = (u64)jiffies_since_start * dev->sdr_adc_freq + (HZ * SDR_CAP_SAMPLES_PER_BUF) / 2; do_div(buffers_since_start, HZ * SDR_CAP_SAMPLES_PER_BUF); /* * After more than 0xf0000000 (rounded down to a multiple of * 'jiffies-per-day' to ease jiffies_to_msecs calculation) * jiffies have passed since we started streaming reset the * counters and keep track of the sequence offset. */ if (jiffies_since_start > JIFFIES_RESYNC) { dev->jiffies_sdr_cap = cur_jiffies; dev->sdr_cap_seq_offset = buffers_since_start; buffers_since_start = 0; } dev->sdr_cap_seq_count = buffers_since_start + dev->sdr_cap_seq_offset; dev->sdr_cap_with_seq_wrap_count = dev->sdr_cap_seq_count - dev->sdr_cap_seq_start; vivid_thread_sdr_cap_tick(dev); mutex_unlock(&dev->mutex); /* * Calculate the number of samples streamed since we started, * not including the current buffer. */ samples_since_start = buffers_since_start * SDR_CAP_SAMPLES_PER_BUF; /* And the number of jiffies since we started */ jiffies_since_start = jiffies - dev->jiffies_sdr_cap; /* Increase by the number of samples in one buffer */ samples_since_start += SDR_CAP_SAMPLES_PER_BUF; /* * Calculate when that next buffer is supposed to start * in jiffies since we started streaming. */ next_jiffies_since_start = samples_since_start * HZ + dev->sdr_adc_freq / 2; do_div(next_jiffies_since_start, dev->sdr_adc_freq); /* If it is in the past, then just schedule asap */ if (next_jiffies_since_start < jiffies_since_start) next_jiffies_since_start = jiffies_since_start; wait_jiffies = next_jiffies_since_start - jiffies_since_start; while (time_is_after_jiffies(cur_jiffies + wait_jiffies) && !kthread_should_stop()) schedule(); } dprintk(dev, 1, "SDR Capture Thread End\n"); return 0; } static int sdr_cap_queue_setup(struct vb2_queue *vq, unsigned *nbuffers, unsigned *nplanes, unsigned sizes[], struct device *alloc_devs[]) { /* 2 = max 16-bit sample returned */ sizes[0] = SDR_CAP_SAMPLES_PER_BUF * 2; *nplanes = 1; return 0; } static int sdr_cap_buf_prepare(struct vb2_buffer *vb) { struct vivid_dev *dev = vb2_get_drv_priv(vb->vb2_queue); unsigned size = SDR_CAP_SAMPLES_PER_BUF * 2; dprintk(dev, 1, "%s\n", __func__); if (dev->buf_prepare_error) { /* * Error injection: test what happens if buf_prepare() returns * an error. */ dev->buf_prepare_error = false; return -EINVAL; } if (vb2_plane_size(vb, 0) < size) { dprintk(dev, 1, "%s data will not fit into plane (%lu < %u)\n", __func__, vb2_plane_size(vb, 0), size); return -EINVAL; } vb2_set_plane_payload(vb, 0, size); return 0; } static void sdr_cap_buf_queue(struct vb2_buffer *vb) { struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb); struct vivid_dev *dev = vb2_get_drv_priv(vb->vb2_queue); struct vivid_buffer *buf = container_of(vbuf, struct vivid_buffer, vb); dprintk(dev, 1, "%s\n", __func__); spin_lock(&dev->slock); list_add_tail(&buf->list, &dev->sdr_cap_active); spin_unlock(&dev->slock); } static int sdr_cap_start_streaming(struct vb2_queue *vq, unsigned count) { struct vivid_dev *dev = vb2_get_drv_priv(vq); int err = 0; dprintk(dev, 1, "%s\n", __func__); dev->sdr_cap_seq_start = dev->seq_wrap * 128; if (dev->start_streaming_error) { dev->start_streaming_error = false; err = -EINVAL; } else if (dev->kthread_sdr_cap == NULL) { dev->kthread_sdr_cap = kthread_run(vivid_thread_sdr_cap, dev, "%s-sdr-cap", dev->v4l2_dev.name); if (IS_ERR(dev->kthread_sdr_cap)) { v4l2_err(&dev->v4l2_dev, "kernel_thread() failed\n"); err = PTR_ERR(dev->kthread_sdr_cap); dev->kthread_sdr_cap = NULL; } } if (err) { struct vivid_buffer *buf, *tmp; list_for_each_entry_safe(buf, tmp, &dev->sdr_cap_active, list) { list_del(&buf->list); vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_QUEUED); } } return err; } /* abort streaming and wait for last buffer */ static void sdr_cap_stop_streaming(struct vb2_queue *vq) { struct vivid_dev *dev = vb2_get_drv_priv(vq); if (dev->kthread_sdr_cap == NULL) return; while (!list_empty(&dev->sdr_cap_active)) { struct vivid_buffer *buf; buf = list_entry(dev->sdr_cap_active.next, struct vivid_buffer, list); list_del(&buf->list); v4l2_ctrl_request_complete(buf->vb.vb2_buf.req_obj.req, &dev->ctrl_hdl_sdr_cap); vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR); } /* shutdown control thread */ kthread_stop(dev->kthread_sdr_cap); dev->kthread_sdr_cap = NULL; } static void sdr_cap_buf_request_complete(struct vb2_buffer *vb) { struct vivid_dev *dev = vb2_get_drv_priv(vb->vb2_queue); v4l2_ctrl_request_complete(vb->req_obj.req, &dev->ctrl_hdl_sdr_cap); } const struct vb2_ops vivid_sdr_cap_qops = { .queue_setup = sdr_cap_queue_setup, .buf_prepare = sdr_cap_buf_prepare, .buf_queue = sdr_cap_buf_queue, .start_streaming = sdr_cap_start_streaming, .stop_streaming = sdr_cap_stop_streaming, .buf_request_complete = sdr_cap_buf_request_complete, .wait_prepare = vb2_ops_wait_prepare, .wait_finish = vb2_ops_wait_finish, }; int vivid_sdr_enum_freq_bands(struct file *file, void *fh, struct v4l2_frequency_band *band) { switch (band->tuner) { case 0: if (band->index >= ARRAY_SIZE(bands_adc)) return -EINVAL; *band = bands_adc[band->index]; return 0; case 1: if (band->index >= ARRAY_SIZE(bands_fm)) return -EINVAL; *band = bands_fm[band->index]; return 0; default: return -EINVAL; } } int vivid_sdr_g_frequency(struct file *file, void *fh, struct v4l2_frequency *vf) { struct vivid_dev *dev = video_drvdata(file); switch (vf->tuner) { case 0: vf->frequency = dev->sdr_adc_freq; vf->type = V4L2_TUNER_ADC; return 0; case 1: vf->frequency = dev->sdr_fm_freq; vf->type = V4L2_TUNER_RF; return 0; default: return -EINVAL; } } int vivid_sdr_s_frequency(struct file *file, void *fh, const struct v4l2_frequency *vf) { struct vivid_dev *dev = video_drvdata(file); unsigned freq = vf->frequency; unsigned band; switch (vf->tuner) { case 0: if (vf->type != V4L2_TUNER_ADC) return -EINVAL; if (freq < BAND_ADC_0) band = 0; else if (freq < BAND_ADC_1) band = 1; else band = 2; freq = clamp_t(unsigned, freq, bands_adc[band].rangelow, bands_adc[band].rangehigh); if (vb2_is_streaming(&dev->vb_sdr_cap_q) && freq != dev->sdr_adc_freq) { /* resync the thread's timings */ dev->sdr_cap_seq_resync = true; } dev->sdr_adc_freq = freq; return 0; case 1: if (vf->type != V4L2_TUNER_RF) return -EINVAL; dev->sdr_fm_freq = clamp_t(unsigned, freq, bands_fm[0].rangelow, bands_fm[0].rangehigh); return 0; default: return -EINVAL; } } int vivid_sdr_g_tuner(struct file *file, void *fh, struct v4l2_tuner *vt) { switch (vt->index) { case 0: strscpy(vt->name, "ADC", sizeof(vt->name)); vt->type = V4L2_TUNER_ADC; vt->capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS; vt->rangelow = bands_adc[0].rangelow; vt->rangehigh = bands_adc[2].rangehigh; return 0; case 1: strscpy(vt->name, "RF", sizeof(vt->name)); vt->type = V4L2_TUNER_RF; vt->capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS; vt->rangelow = bands_fm[0].rangelow; vt->rangehigh = bands_fm[0].rangehigh; return 0; default: return -EINVAL; } } int vivid_sdr_s_tuner(struct file *file, void *fh, const struct v4l2_tuner *vt) { if (vt->index > 1) return -EINVAL; return 0; } int vidioc_enum_fmt_sdr_cap(struct file *file, void *fh, struct v4l2_fmtdesc *f) { if (f->index >= ARRAY_SIZE(formats)) return -EINVAL; f->pixelformat = formats[f->index].pixelformat; return 0; } int vidioc_g_fmt_sdr_cap(struct file *file, void *fh, struct v4l2_format *f) { struct vivid_dev *dev = video_drvdata(file); f->fmt.sdr.pixelformat = dev->sdr_pixelformat; f->fmt.sdr.buffersize = dev->sdr_buffersize; return 0; } int vidioc_s_fmt_sdr_cap(struct file *file, void *fh, struct v4l2_format *f) { struct vivid_dev *dev = video_drvdata(file); struct vb2_queue *q = &dev->vb_sdr_cap_q; int i; if (vb2_is_busy(q)) return -EBUSY; for (i = 0; i < ARRAY_SIZE(formats); i++) { if (formats[i].pixelformat == f->fmt.sdr.pixelformat) { dev->sdr_pixelformat = formats[i].pixelformat; dev->sdr_buffersize = formats[i].buffersize; f->fmt.sdr.buffersize = formats[i].buffersize; return 0; } } dev->sdr_pixelformat = formats[0].pixelformat; dev->sdr_buffersize = formats[0].buffersize; f->fmt.sdr.pixelformat = formats[0].pixelformat; f->fmt.sdr.buffersize = formats[0].buffersize; return 0; } int vidioc_try_fmt_sdr_cap(struct file *file, void *fh, struct v4l2_format *f) { int i; for (i = 0; i < ARRAY_SIZE(formats); i++) { if (formats[i].pixelformat == f->fmt.sdr.pixelformat) { f->fmt.sdr.buffersize = formats[i].buffersize; return 0; } } f->fmt.sdr.pixelformat = formats[0].pixelformat; f->fmt.sdr.buffersize = formats[0].buffersize; return 0; } #define FIXP_N (15) #define FIXP_FRAC (1 << FIXP_N) #define FIXP_2PI ((int)(2 * 3.141592653589 * FIXP_FRAC)) #define M_100000PI (3.14159 * 100000) void vivid_sdr_cap_process(struct vivid_dev *dev, struct vivid_buffer *buf) { u8 *vbuf = vb2_plane_vaddr(&buf->vb.vb2_buf, 0); unsigned long i; unsigned long plane_size = vb2_plane_size(&buf->vb.vb2_buf, 0); s64 s64tmp; s32 src_phase_step; s32 mod_phase_step; s32 fixp_i; s32 fixp_q; /* calculate phase step */ #define BEEP_FREQ 1000 /* 1kHz beep */ src_phase_step = DIV_ROUND_CLOSEST(FIXP_2PI * BEEP_FREQ, dev->sdr_adc_freq); for (i = 0; i < plane_size; i += 2) { mod_phase_step = fixp_cos32_rad(dev->sdr_fixp_src_phase, FIXP_2PI) >> (31 - FIXP_N); dev->sdr_fixp_src_phase += src_phase_step; s64tmp = (s64) mod_phase_step * dev->sdr_fm_deviation; dev->sdr_fixp_mod_phase += div_s64(s64tmp, M_100000PI); /* * Transfer phase angle to [0, 2xPI] in order to avoid variable * overflow and make it suitable for cosine implementation * used, which does not support negative angles. */ dev->sdr_fixp_src_phase %= FIXP_2PI; dev->sdr_fixp_mod_phase %= FIXP_2PI; if (dev->sdr_fixp_mod_phase < 0) dev->sdr_fixp_mod_phase += FIXP_2PI; fixp_i = fixp_cos32_rad(dev->sdr_fixp_mod_phase, FIXP_2PI); fixp_q = fixp_sin32_rad(dev->sdr_fixp_mod_phase, FIXP_2PI); /* Normalize fraction values represented with 32 bit precision * to fixed point representation with FIXP_N bits */ fixp_i >>= (31 - FIXP_N); fixp_q >>= (31 - FIXP_N); switch (dev->sdr_pixelformat) { case V4L2_SDR_FMT_CU8: /* convert 'fixp float' to u8 [0, +255] */ /* u8 = X * 127.5 + 127.5; X is float [-1.0, +1.0] */ fixp_i = fixp_i * 1275 + FIXP_FRAC * 1275; fixp_q = fixp_q * 1275 + FIXP_FRAC * 1275; *vbuf++ = DIV_ROUND_CLOSEST(fixp_i, FIXP_FRAC * 10); *vbuf++ = DIV_ROUND_CLOSEST(fixp_q, FIXP_FRAC * 10); break; case V4L2_SDR_FMT_CS8: /* convert 'fixp float' to s8 [-128, +127] */ /* s8 = X * 127.5 - 0.5; X is float [-1.0, +1.0] */ fixp_i = fixp_i * 1275 - FIXP_FRAC * 5; fixp_q = fixp_q * 1275 - FIXP_FRAC * 5; *vbuf++ = DIV_ROUND_CLOSEST(fixp_i, FIXP_FRAC * 10); *vbuf++ = DIV_ROUND_CLOSEST(fixp_q, FIXP_FRAC * 10); break; default: break; } } }
linux-master
drivers/media/test-drivers/vivid/vivid-sdr-cap.c
// SPDX-License-Identifier: GPL-2.0-only /* * vivid-meta-out.c - meta output support functions. */ #include <linux/errno.h> #include <linux/kernel.h> #include <linux/videodev2.h> #include <media/v4l2-common.h> #include <linux/usb/video.h> #include "vivid-core.h" #include "vivid-kthread-out.h" #include "vivid-meta-out.h" static int meta_out_queue_setup(struct vb2_queue *vq, unsigned int *nbuffers, unsigned int *nplanes, unsigned int sizes[], struct device *alloc_devs[]) { struct vivid_dev *dev = vb2_get_drv_priv(vq); unsigned int size = sizeof(struct vivid_meta_out_buf); if (!vivid_is_webcam(dev)) return -EINVAL; if (*nplanes) { if (sizes[0] < size) return -EINVAL; } else { sizes[0] = size; } if (vq->num_buffers + *nbuffers < 2) *nbuffers = 2 - vq->num_buffers; *nplanes = 1; return 0; } static int meta_out_buf_prepare(struct vb2_buffer *vb) { struct vivid_dev *dev = vb2_get_drv_priv(vb->vb2_queue); unsigned int size = sizeof(struct vivid_meta_out_buf); dprintk(dev, 1, "%s\n", __func__); if (dev->buf_prepare_error) { /* * Error injection: test what happens if buf_prepare() returns * an error. */ dev->buf_prepare_error = false; return -EINVAL; } if (vb2_plane_size(vb, 0) < size) { dprintk(dev, 1, "%s data will not fit into plane (%lu < %u)\n", __func__, vb2_plane_size(vb, 0), size); return -EINVAL; } vb2_set_plane_payload(vb, 0, size); return 0; } static void meta_out_buf_queue(struct vb2_buffer *vb) { struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb); struct vivid_dev *dev = vb2_get_drv_priv(vb->vb2_queue); struct vivid_buffer *buf = container_of(vbuf, struct vivid_buffer, vb); dprintk(dev, 1, "%s\n", __func__); spin_lock(&dev->slock); list_add_tail(&buf->list, &dev->meta_out_active); spin_unlock(&dev->slock); } static int meta_out_start_streaming(struct vb2_queue *vq, unsigned int count) { struct vivid_dev *dev = vb2_get_drv_priv(vq); int err; dprintk(dev, 1, "%s\n", __func__); dev->meta_out_seq_count = 0; if (dev->start_streaming_error) { dev->start_streaming_error = false; err = -EINVAL; } else { err = vivid_start_generating_vid_out(dev, &dev->meta_out_streaming); } if (err) { struct vivid_buffer *buf, *tmp; list_for_each_entry_safe(buf, tmp, &dev->meta_out_active, list) { list_del(&buf->list); vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_QUEUED); } } return err; } /* abort streaming and wait for last buffer */ static void meta_out_stop_streaming(struct vb2_queue *vq) { struct vivid_dev *dev = vb2_get_drv_priv(vq); dprintk(dev, 1, "%s\n", __func__); vivid_stop_generating_vid_out(dev, &dev->meta_out_streaming); } static void meta_out_buf_request_complete(struct vb2_buffer *vb) { struct vivid_dev *dev = vb2_get_drv_priv(vb->vb2_queue); v4l2_ctrl_request_complete(vb->req_obj.req, &dev->ctrl_hdl_meta_out); } const struct vb2_ops vivid_meta_out_qops = { .queue_setup = meta_out_queue_setup, .buf_prepare = meta_out_buf_prepare, .buf_queue = meta_out_buf_queue, .start_streaming = meta_out_start_streaming, .stop_streaming = meta_out_stop_streaming, .buf_request_complete = meta_out_buf_request_complete, .wait_prepare = vb2_ops_wait_prepare, .wait_finish = vb2_ops_wait_finish, }; int vidioc_enum_fmt_meta_out(struct file *file, void *priv, struct v4l2_fmtdesc *f) { struct vivid_dev *dev = video_drvdata(file); if (!vivid_is_webcam(dev)) return -EINVAL; if (f->index > 0) return -EINVAL; f->type = V4L2_BUF_TYPE_META_OUTPUT; f->pixelformat = V4L2_META_FMT_VIVID; return 0; } int vidioc_g_fmt_meta_out(struct file *file, void *priv, struct v4l2_format *f) { struct vivid_dev *dev = video_drvdata(file); struct v4l2_meta_format *meta = &f->fmt.meta; if (!vivid_is_webcam(dev) || !dev->has_meta_out) return -EINVAL; meta->dataformat = V4L2_META_FMT_VIVID; meta->buffersize = sizeof(struct vivid_meta_out_buf); return 0; } void vivid_meta_out_process(struct vivid_dev *dev, struct vivid_buffer *buf) { struct vivid_meta_out_buf *meta = vb2_plane_vaddr(&buf->vb.vb2_buf, 0); v4l2_ctrl_s_ctrl(dev->brightness, meta->brightness); v4l2_ctrl_s_ctrl(dev->contrast, meta->contrast); v4l2_ctrl_s_ctrl(dev->saturation, meta->saturation); v4l2_ctrl_s_ctrl(dev->hue, meta->hue); dprintk(dev, 2, " %s brightness %u contrast %u saturation %u hue %d\n", __func__, meta->brightness, meta->contrast, meta->saturation, meta->hue); }
linux-master
drivers/media/test-drivers/vivid/vivid-meta-out.c
// SPDX-License-Identifier: GPL-2.0-only /* * vivid-core.c - A Virtual Video Test Driver, core initialization * * Copyright 2014 Cisco Systems, Inc. and/or its affiliates. All rights reserved. */ #include <linux/module.h> #include <linux/errno.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/vmalloc.h> #include <linux/font.h> #include <linux/mutex.h> #include <linux/platform_device.h> #include <linux/videodev2.h> #include <linux/v4l2-dv-timings.h> #include <media/videobuf2-vmalloc.h> #include <media/videobuf2-dma-contig.h> #include <media/v4l2-dv-timings.h> #include <media/v4l2-ioctl.h> #include <media/v4l2-fh.h> #include <media/v4l2-event.h> #include "vivid-core.h" #include "vivid-vid-common.h" #include "vivid-vid-cap.h" #include "vivid-vid-out.h" #include "vivid-radio-common.h" #include "vivid-radio-rx.h" #include "vivid-radio-tx.h" #include "vivid-sdr-cap.h" #include "vivid-vbi-cap.h" #include "vivid-vbi-out.h" #include "vivid-osd.h" #include "vivid-cec.h" #include "vivid-ctrls.h" #include "vivid-meta-cap.h" #include "vivid-meta-out.h" #include "vivid-touch-cap.h" #define VIVID_MODULE_NAME "vivid" /* The maximum number of vivid devices */ #define VIVID_MAX_DEVS CONFIG_VIDEO_VIVID_MAX_DEVS MODULE_DESCRIPTION("Virtual Video Test Driver"); MODULE_AUTHOR("Hans Verkuil"); MODULE_LICENSE("GPL"); static unsigned n_devs = 1; module_param(n_devs, uint, 0444); MODULE_PARM_DESC(n_devs, " number of driver instances to create"); static int vid_cap_nr[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = -1 }; module_param_array(vid_cap_nr, int, NULL, 0444); MODULE_PARM_DESC(vid_cap_nr, " videoX start number, -1 is autodetect"); static int vid_out_nr[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = -1 }; module_param_array(vid_out_nr, int, NULL, 0444); MODULE_PARM_DESC(vid_out_nr, " videoX start number, -1 is autodetect"); static int vbi_cap_nr[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = -1 }; module_param_array(vbi_cap_nr, int, NULL, 0444); MODULE_PARM_DESC(vbi_cap_nr, " vbiX start number, -1 is autodetect"); static int vbi_out_nr[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = -1 }; module_param_array(vbi_out_nr, int, NULL, 0444); MODULE_PARM_DESC(vbi_out_nr, " vbiX start number, -1 is autodetect"); static int sdr_cap_nr[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = -1 }; module_param_array(sdr_cap_nr, int, NULL, 0444); MODULE_PARM_DESC(sdr_cap_nr, " swradioX start number, -1 is autodetect"); static int radio_rx_nr[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = -1 }; module_param_array(radio_rx_nr, int, NULL, 0444); MODULE_PARM_DESC(radio_rx_nr, " radioX start number, -1 is autodetect"); static int radio_tx_nr[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = -1 }; module_param_array(radio_tx_nr, int, NULL, 0444); MODULE_PARM_DESC(radio_tx_nr, " radioX start number, -1 is autodetect"); static int meta_cap_nr[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = -1 }; module_param_array(meta_cap_nr, int, NULL, 0444); MODULE_PARM_DESC(meta_cap_nr, " videoX start number, -1 is autodetect"); static int meta_out_nr[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = -1 }; module_param_array(meta_out_nr, int, NULL, 0444); MODULE_PARM_DESC(meta_out_nr, " videoX start number, -1 is autodetect"); static int touch_cap_nr[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = -1 }; module_param_array(touch_cap_nr, int, NULL, 0444); MODULE_PARM_DESC(touch_cap_nr, " v4l-touchX start number, -1 is autodetect"); static int ccs_cap_mode[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = -1 }; module_param_array(ccs_cap_mode, int, NULL, 0444); MODULE_PARM_DESC(ccs_cap_mode, " capture crop/compose/scale mode:\n" "\t\t bit 0=crop, 1=compose, 2=scale,\n" "\t\t -1=user-controlled (default)"); static int ccs_out_mode[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = -1 }; module_param_array(ccs_out_mode, int, NULL, 0444); MODULE_PARM_DESC(ccs_out_mode, " output crop/compose/scale mode:\n" "\t\t bit 0=crop, 1=compose, 2=scale,\n" "\t\t -1=user-controlled (default)"); static unsigned multiplanar[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = 1 }; module_param_array(multiplanar, uint, NULL, 0444); MODULE_PARM_DESC(multiplanar, " 1 (default) creates a single planar device, 2 creates a multiplanar device."); /* * Default: video + vbi-cap (raw and sliced) + radio rx + radio tx + sdr + * vbi-out + vid-out + meta-cap */ static unsigned int node_types[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = 0xe1d3d }; module_param_array(node_types, uint, NULL, 0444); MODULE_PARM_DESC(node_types, " node types, default is 0xe1d3d. Bitmask with the following meaning:\n" "\t\t bit 0: Video Capture node\n" "\t\t bit 2-3: VBI Capture node: 0 = none, 1 = raw vbi, 2 = sliced vbi, 3 = both\n" "\t\t bit 4: Radio Receiver node\n" "\t\t bit 5: Software Defined Radio Receiver node\n" "\t\t bit 8: Video Output node\n" "\t\t bit 10-11: VBI Output node: 0 = none, 1 = raw vbi, 2 = sliced vbi, 3 = both\n" "\t\t bit 12: Radio Transmitter node\n" "\t\t bit 16: Framebuffer for testing output overlays\n" "\t\t bit 17: Metadata Capture node\n" "\t\t bit 18: Metadata Output node\n" "\t\t bit 19: Touch Capture node\n"); /* Default: 4 inputs */ static unsigned num_inputs[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = 4 }; module_param_array(num_inputs, uint, NULL, 0444); MODULE_PARM_DESC(num_inputs, " number of inputs, default is 4"); /* Default: input 0 = WEBCAM, 1 = TV, 2 = SVID, 3 = HDMI */ static unsigned input_types[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = 0xe4 }; module_param_array(input_types, uint, NULL, 0444); MODULE_PARM_DESC(input_types, " input types, default is 0xe4. Two bits per input,\n" "\t\t bits 0-1 == input 0, bits 31-30 == input 15.\n" "\t\t Type 0 == webcam, 1 == TV, 2 == S-Video, 3 == HDMI"); /* Default: 2 outputs */ static unsigned num_outputs[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = 2 }; module_param_array(num_outputs, uint, NULL, 0444); MODULE_PARM_DESC(num_outputs, " number of outputs, default is 2"); /* Default: output 0 = SVID, 1 = HDMI */ static unsigned output_types[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = 2 }; module_param_array(output_types, uint, NULL, 0444); MODULE_PARM_DESC(output_types, " output types, default is 0x02. One bit per output,\n" "\t\t bit 0 == output 0, bit 15 == output 15.\n" "\t\t Type 0 == S-Video, 1 == HDMI"); unsigned vivid_debug; module_param(vivid_debug, uint, 0644); MODULE_PARM_DESC(vivid_debug, " activates debug info"); static bool no_error_inj; module_param(no_error_inj, bool, 0444); MODULE_PARM_DESC(no_error_inj, " if set disable the error injecting controls"); static unsigned int allocators[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = 0 }; module_param_array(allocators, uint, NULL, 0444); MODULE_PARM_DESC(allocators, " memory allocator selection, default is 0.\n" "\t\t 0 == vmalloc\n" "\t\t 1 == dma-contig"); static unsigned int cache_hints[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = 0 }; module_param_array(cache_hints, uint, NULL, 0444); MODULE_PARM_DESC(cache_hints, " user-space cache hints, default is 0.\n" "\t\t 0 == forbid\n" "\t\t 1 == allow"); static unsigned int supports_requests[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = 1 }; module_param_array(supports_requests, uint, NULL, 0444); MODULE_PARM_DESC(supports_requests, " support for requests, default is 1.\n" "\t\t 0 == no support\n" "\t\t 1 == supports requests\n" "\t\t 2 == requires requests"); static struct vivid_dev *vivid_devs[VIVID_MAX_DEVS]; const struct v4l2_rect vivid_min_rect = { 0, 0, MIN_WIDTH, MIN_HEIGHT }; const struct v4l2_rect vivid_max_rect = { 0, 0, MAX_WIDTH * MAX_ZOOM, MAX_HEIGHT * MAX_ZOOM }; static const u8 vivid_hdmi_edid[256] = { 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x31, 0xd8, 0x34, 0x12, 0x00, 0x00, 0x00, 0x00, 0x22, 0x1a, 0x01, 0x03, 0x80, 0x60, 0x36, 0x78, 0x0f, 0xee, 0x91, 0xa3, 0x54, 0x4c, 0x99, 0x26, 0x0f, 0x50, 0x54, 0x2f, 0xcf, 0x00, 0x31, 0x59, 0x45, 0x59, 0x81, 0x80, 0x81, 0x40, 0x90, 0x40, 0x95, 0x00, 0xa9, 0x40, 0xb3, 0x00, 0x08, 0xe8, 0x00, 0x30, 0xf2, 0x70, 0x5a, 0x80, 0xb0, 0x58, 0x8a, 0x00, 0xc0, 0x1c, 0x32, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x18, 0x55, 0x18, 0x87, 0x3c, 0x00, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x76, 0x69, 0x76, 0x69, 0x64, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x7b, 0x02, 0x03, 0x3f, 0xf1, 0x51, 0x61, 0x60, 0x5f, 0x5e, 0x5d, 0x10, 0x1f, 0x04, 0x13, 0x22, 0x21, 0x20, 0x05, 0x14, 0x02, 0x11, 0x01, 0x23, 0x09, 0x07, 0x07, 0x83, 0x01, 0x00, 0x00, 0x6d, 0x03, 0x0c, 0x00, 0x10, 0x00, 0x00, 0x3c, 0x21, 0x00, 0x60, 0x01, 0x02, 0x03, 0x67, 0xd8, 0x5d, 0xc4, 0x01, 0x78, 0x00, 0x00, 0xe2, 0x00, 0xca, 0xe3, 0x05, 0x00, 0x00, 0xe3, 0x06, 0x01, 0x00, 0x4d, 0xd0, 0x00, 0xa0, 0xf0, 0x70, 0x3e, 0x80, 0x30, 0x20, 0x35, 0x00, 0xc0, 0x1c, 0x32, 0x00, 0x00, 0x1e, 0x1a, 0x36, 0x80, 0xa0, 0x70, 0x38, 0x1f, 0x40, 0x30, 0x20, 0x35, 0x00, 0xc0, 0x1c, 0x32, 0x00, 0x00, 0x1a, 0x1a, 0x1d, 0x00, 0x80, 0x51, 0xd0, 0x1c, 0x20, 0x40, 0x80, 0x35, 0x00, 0xc0, 0x1c, 0x32, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x82, }; static int vidioc_querycap(struct file *file, void *priv, struct v4l2_capability *cap) { struct vivid_dev *dev = video_drvdata(file); strscpy(cap->driver, "vivid", sizeof(cap->driver)); strscpy(cap->card, "vivid", sizeof(cap->card)); snprintf(cap->bus_info, sizeof(cap->bus_info), "platform:%s", dev->v4l2_dev.name); cap->capabilities = dev->vid_cap_caps | dev->vid_out_caps | dev->vbi_cap_caps | dev->vbi_out_caps | dev->radio_rx_caps | dev->radio_tx_caps | dev->sdr_cap_caps | dev->meta_cap_caps | dev->meta_out_caps | dev->touch_cap_caps | V4L2_CAP_DEVICE_CAPS; return 0; } static int vidioc_s_hw_freq_seek(struct file *file, void *fh, const struct v4l2_hw_freq_seek *a) { struct video_device *vdev = video_devdata(file); if (vdev->vfl_type == VFL_TYPE_RADIO) return vivid_radio_rx_s_hw_freq_seek(file, fh, a); return -ENOTTY; } static int vidioc_enum_freq_bands(struct file *file, void *fh, struct v4l2_frequency_band *band) { struct video_device *vdev = video_devdata(file); if (vdev->vfl_type == VFL_TYPE_RADIO) return vivid_radio_rx_enum_freq_bands(file, fh, band); if (vdev->vfl_type == VFL_TYPE_SDR) return vivid_sdr_enum_freq_bands(file, fh, band); return -ENOTTY; } static int vidioc_g_tuner(struct file *file, void *fh, struct v4l2_tuner *vt) { struct video_device *vdev = video_devdata(file); if (vdev->vfl_type == VFL_TYPE_RADIO) return vivid_radio_rx_g_tuner(file, fh, vt); if (vdev->vfl_type == VFL_TYPE_SDR) return vivid_sdr_g_tuner(file, fh, vt); return vivid_video_g_tuner(file, fh, vt); } static int vidioc_s_tuner(struct file *file, void *fh, const struct v4l2_tuner *vt) { struct video_device *vdev = video_devdata(file); if (vdev->vfl_type == VFL_TYPE_RADIO) return vivid_radio_rx_s_tuner(file, fh, vt); if (vdev->vfl_type == VFL_TYPE_SDR) return vivid_sdr_s_tuner(file, fh, vt); return vivid_video_s_tuner(file, fh, vt); } static int vidioc_g_frequency(struct file *file, void *fh, struct v4l2_frequency *vf) { struct vivid_dev *dev = video_drvdata(file); struct video_device *vdev = video_devdata(file); if (vdev->vfl_type == VFL_TYPE_RADIO) return vivid_radio_g_frequency(file, vdev->vfl_dir == VFL_DIR_RX ? &dev->radio_rx_freq : &dev->radio_tx_freq, vf); if (vdev->vfl_type == VFL_TYPE_SDR) return vivid_sdr_g_frequency(file, fh, vf); return vivid_video_g_frequency(file, fh, vf); } static int vidioc_s_frequency(struct file *file, void *fh, const struct v4l2_frequency *vf) { struct vivid_dev *dev = video_drvdata(file); struct video_device *vdev = video_devdata(file); if (vdev->vfl_type == VFL_TYPE_RADIO) return vivid_radio_s_frequency(file, vdev->vfl_dir == VFL_DIR_RX ? &dev->radio_rx_freq : &dev->radio_tx_freq, vf); if (vdev->vfl_type == VFL_TYPE_SDR) return vivid_sdr_s_frequency(file, fh, vf); return vivid_video_s_frequency(file, fh, vf); } static int vidioc_overlay(struct file *file, void *fh, unsigned i) { struct video_device *vdev = video_devdata(file); if (vdev->vfl_dir == VFL_DIR_RX) return -ENOTTY; return vivid_vid_out_overlay(file, fh, i); } static int vidioc_g_fbuf(struct file *file, void *fh, struct v4l2_framebuffer *a) { struct video_device *vdev = video_devdata(file); if (vdev->vfl_dir == VFL_DIR_RX) return -ENOTTY; return vivid_vid_out_g_fbuf(file, fh, a); } static int vidioc_s_fbuf(struct file *file, void *fh, const struct v4l2_framebuffer *a) { struct video_device *vdev = video_devdata(file); if (vdev->vfl_dir == VFL_DIR_RX) return -ENOTTY; return vivid_vid_out_s_fbuf(file, fh, a); } static int vidioc_s_std(struct file *file, void *fh, v4l2_std_id id) { struct video_device *vdev = video_devdata(file); if (vdev->vfl_dir == VFL_DIR_RX) return vivid_vid_cap_s_std(file, fh, id); return vivid_vid_out_s_std(file, fh, id); } static int vidioc_s_dv_timings(struct file *file, void *fh, struct v4l2_dv_timings *timings) { struct video_device *vdev = video_devdata(file); if (vdev->vfl_dir == VFL_DIR_RX) return vivid_vid_cap_s_dv_timings(file, fh, timings); return vivid_vid_out_s_dv_timings(file, fh, timings); } static int vidioc_g_pixelaspect(struct file *file, void *fh, int type, struct v4l2_fract *f) { struct video_device *vdev = video_devdata(file); if (vdev->vfl_dir == VFL_DIR_RX) return vivid_vid_cap_g_pixelaspect(file, fh, type, f); return vivid_vid_out_g_pixelaspect(file, fh, type, f); } static int vidioc_g_selection(struct file *file, void *fh, struct v4l2_selection *sel) { struct video_device *vdev = video_devdata(file); if (vdev->vfl_dir == VFL_DIR_RX) return vivid_vid_cap_g_selection(file, fh, sel); return vivid_vid_out_g_selection(file, fh, sel); } static int vidioc_s_selection(struct file *file, void *fh, struct v4l2_selection *sel) { struct video_device *vdev = video_devdata(file); if (vdev->vfl_dir == VFL_DIR_RX) return vivid_vid_cap_s_selection(file, fh, sel); return vivid_vid_out_s_selection(file, fh, sel); } static int vidioc_g_parm(struct file *file, void *fh, struct v4l2_streamparm *parm) { struct video_device *vdev = video_devdata(file); if (vdev->vfl_type == VFL_TYPE_TOUCH) return vivid_g_parm_tch(file, fh, parm); if (vdev->vfl_dir == VFL_DIR_RX) return vivid_vid_cap_g_parm(file, fh, parm); return vivid_vid_out_g_parm(file, fh, parm); } static int vidioc_s_parm(struct file *file, void *fh, struct v4l2_streamparm *parm) { struct video_device *vdev = video_devdata(file); if (vdev->vfl_dir == VFL_DIR_RX) return vivid_vid_cap_s_parm(file, fh, parm); return -ENOTTY; } static int vidioc_log_status(struct file *file, void *fh) { struct vivid_dev *dev = video_drvdata(file); struct video_device *vdev = video_devdata(file); v4l2_ctrl_log_status(file, fh); if (vdev->vfl_dir == VFL_DIR_RX && vdev->vfl_type == VFL_TYPE_VIDEO) tpg_log_status(&dev->tpg); return 0; } static ssize_t vivid_radio_read(struct file *file, char __user *buf, size_t size, loff_t *offset) { struct video_device *vdev = video_devdata(file); if (vdev->vfl_dir == VFL_DIR_TX) return -EINVAL; return vivid_radio_rx_read(file, buf, size, offset); } static ssize_t vivid_radio_write(struct file *file, const char __user *buf, size_t size, loff_t *offset) { struct video_device *vdev = video_devdata(file); if (vdev->vfl_dir == VFL_DIR_RX) return -EINVAL; return vivid_radio_tx_write(file, buf, size, offset); } static __poll_t vivid_radio_poll(struct file *file, struct poll_table_struct *wait) { struct video_device *vdev = video_devdata(file); if (vdev->vfl_dir == VFL_DIR_RX) return vivid_radio_rx_poll(file, wait); return vivid_radio_tx_poll(file, wait); } static int vivid_enum_input(struct file *file, void *priv, struct v4l2_input *inp) { struct video_device *vdev = video_devdata(file); if (vdev->vfl_type == VFL_TYPE_TOUCH) return vivid_enum_input_tch(file, priv, inp); return vidioc_enum_input(file, priv, inp); } static int vivid_g_input(struct file *file, void *priv, unsigned int *i) { struct video_device *vdev = video_devdata(file); if (vdev->vfl_type == VFL_TYPE_TOUCH) return vivid_g_input_tch(file, priv, i); return vidioc_g_input(file, priv, i); } static int vivid_s_input(struct file *file, void *priv, unsigned int i) { struct video_device *vdev = video_devdata(file); if (vdev->vfl_type == VFL_TYPE_TOUCH) return vivid_s_input_tch(file, priv, i); return vidioc_s_input(file, priv, i); } static int vivid_enum_fmt_cap(struct file *file, void *priv, struct v4l2_fmtdesc *f) { struct video_device *vdev = video_devdata(file); if (vdev->vfl_type == VFL_TYPE_TOUCH) return vivid_enum_fmt_tch(file, priv, f); return vivid_enum_fmt_vid(file, priv, f); } static int vivid_g_fmt_cap(struct file *file, void *priv, struct v4l2_format *f) { struct video_device *vdev = video_devdata(file); if (vdev->vfl_type == VFL_TYPE_TOUCH) return vivid_g_fmt_tch(file, priv, f); return vidioc_g_fmt_vid_cap(file, priv, f); } static int vivid_try_fmt_cap(struct file *file, void *priv, struct v4l2_format *f) { struct video_device *vdev = video_devdata(file); if (vdev->vfl_type == VFL_TYPE_TOUCH) return vivid_g_fmt_tch(file, priv, f); return vidioc_try_fmt_vid_cap(file, priv, f); } static int vivid_s_fmt_cap(struct file *file, void *priv, struct v4l2_format *f) { struct video_device *vdev = video_devdata(file); if (vdev->vfl_type == VFL_TYPE_TOUCH) return vivid_g_fmt_tch(file, priv, f); return vidioc_s_fmt_vid_cap(file, priv, f); } static int vivid_g_fmt_cap_mplane(struct file *file, void *priv, struct v4l2_format *f) { struct video_device *vdev = video_devdata(file); if (vdev->vfl_type == VFL_TYPE_TOUCH) return vivid_g_fmt_tch_mplane(file, priv, f); return vidioc_g_fmt_vid_cap_mplane(file, priv, f); } static int vivid_try_fmt_cap_mplane(struct file *file, void *priv, struct v4l2_format *f) { struct video_device *vdev = video_devdata(file); if (vdev->vfl_type == VFL_TYPE_TOUCH) return vivid_g_fmt_tch_mplane(file, priv, f); return vidioc_try_fmt_vid_cap_mplane(file, priv, f); } static int vivid_s_fmt_cap_mplane(struct file *file, void *priv, struct v4l2_format *f) { struct video_device *vdev = video_devdata(file); if (vdev->vfl_type == VFL_TYPE_TOUCH) return vivid_g_fmt_tch_mplane(file, priv, f); return vidioc_s_fmt_vid_cap_mplane(file, priv, f); } static bool vivid_is_in_use(bool valid, struct video_device *vdev) { unsigned long flags; bool res; if (!valid) return false; spin_lock_irqsave(&vdev->fh_lock, flags); res = !list_empty(&vdev->fh_list); spin_unlock_irqrestore(&vdev->fh_lock, flags); return res; } static bool vivid_is_last_user(struct vivid_dev *dev) { unsigned int uses = vivid_is_in_use(dev->has_vid_cap, &dev->vid_cap_dev) + vivid_is_in_use(dev->has_vid_out, &dev->vid_out_dev) + vivid_is_in_use(dev->has_vbi_cap, &dev->vbi_cap_dev) + vivid_is_in_use(dev->has_vbi_out, &dev->vbi_out_dev) + vivid_is_in_use(dev->has_radio_rx, &dev->radio_rx_dev) + vivid_is_in_use(dev->has_radio_tx, &dev->radio_tx_dev) + vivid_is_in_use(dev->has_sdr_cap, &dev->sdr_cap_dev) + vivid_is_in_use(dev->has_meta_cap, &dev->meta_cap_dev) + vivid_is_in_use(dev->has_meta_out, &dev->meta_out_dev) + vivid_is_in_use(dev->has_touch_cap, &dev->touch_cap_dev); return uses == 1; } static void vivid_reconnect(struct vivid_dev *dev) { if (dev->has_vid_cap) set_bit(V4L2_FL_REGISTERED, &dev->vid_cap_dev.flags); if (dev->has_vid_out) set_bit(V4L2_FL_REGISTERED, &dev->vid_out_dev.flags); if (dev->has_vbi_cap) set_bit(V4L2_FL_REGISTERED, &dev->vbi_cap_dev.flags); if (dev->has_vbi_out) set_bit(V4L2_FL_REGISTERED, &dev->vbi_out_dev.flags); if (dev->has_radio_rx) set_bit(V4L2_FL_REGISTERED, &dev->radio_rx_dev.flags); if (dev->has_radio_tx) set_bit(V4L2_FL_REGISTERED, &dev->radio_tx_dev.flags); if (dev->has_sdr_cap) set_bit(V4L2_FL_REGISTERED, &dev->sdr_cap_dev.flags); if (dev->has_meta_cap) set_bit(V4L2_FL_REGISTERED, &dev->meta_cap_dev.flags); if (dev->has_meta_out) set_bit(V4L2_FL_REGISTERED, &dev->meta_out_dev.flags); if (dev->has_touch_cap) set_bit(V4L2_FL_REGISTERED, &dev->touch_cap_dev.flags); dev->disconnect_error = false; } static int vivid_fop_release(struct file *file) { struct vivid_dev *dev = video_drvdata(file); struct video_device *vdev = video_devdata(file); mutex_lock(&dev->mutex); if (!no_error_inj && v4l2_fh_is_singular_file(file) && dev->disconnect_error && !video_is_registered(vdev) && vivid_is_last_user(dev)) { /* * I am the last user of this driver, and a disconnect * was forced (since this video_device is unregistered), * so re-register all video_device's again. */ v4l2_info(&dev->v4l2_dev, "reconnect\n"); vivid_reconnect(dev); } if (file->private_data == dev->radio_rx_rds_owner) { dev->radio_rx_rds_last_block = 0; dev->radio_rx_rds_owner = NULL; } if (file->private_data == dev->radio_tx_rds_owner) { dev->radio_tx_rds_last_block = 0; dev->radio_tx_rds_owner = NULL; } mutex_unlock(&dev->mutex); if (vdev->queue) return vb2_fop_release(file); return v4l2_fh_release(file); } static const struct v4l2_file_operations vivid_fops = { .owner = THIS_MODULE, .open = v4l2_fh_open, .release = vivid_fop_release, .read = vb2_fop_read, .write = vb2_fop_write, .poll = vb2_fop_poll, .unlocked_ioctl = video_ioctl2, .mmap = vb2_fop_mmap, }; static const struct v4l2_file_operations vivid_radio_fops = { .owner = THIS_MODULE, .open = v4l2_fh_open, .release = vivid_fop_release, .read = vivid_radio_read, .write = vivid_radio_write, .poll = vivid_radio_poll, .unlocked_ioctl = video_ioctl2, }; static int vidioc_reqbufs(struct file *file, void *priv, struct v4l2_requestbuffers *p) { struct video_device *vdev = video_devdata(file); int r; /* * Sliced and raw VBI capture share the same queue so we must * change the type. */ if (p->type == V4L2_BUF_TYPE_SLICED_VBI_CAPTURE || p->type == V4L2_BUF_TYPE_VBI_CAPTURE) { r = vb2_queue_change_type(vdev->queue, p->type); if (r) return r; } return vb2_ioctl_reqbufs(file, priv, p); } static int vidioc_create_bufs(struct file *file, void *priv, struct v4l2_create_buffers *p) { struct video_device *vdev = video_devdata(file); int r; /* * Sliced and raw VBI capture share the same queue so we must * change the type. */ if (p->format.type == V4L2_BUF_TYPE_SLICED_VBI_CAPTURE || p->format.type == V4L2_BUF_TYPE_VBI_CAPTURE) { r = vb2_queue_change_type(vdev->queue, p->format.type); if (r) return r; } return vb2_ioctl_create_bufs(file, priv, p); } static const struct v4l2_ioctl_ops vivid_ioctl_ops = { .vidioc_querycap = vidioc_querycap, .vidioc_enum_fmt_vid_cap = vivid_enum_fmt_cap, .vidioc_g_fmt_vid_cap = vivid_g_fmt_cap, .vidioc_try_fmt_vid_cap = vivid_try_fmt_cap, .vidioc_s_fmt_vid_cap = vivid_s_fmt_cap, .vidioc_g_fmt_vid_cap_mplane = vivid_g_fmt_cap_mplane, .vidioc_try_fmt_vid_cap_mplane = vivid_try_fmt_cap_mplane, .vidioc_s_fmt_vid_cap_mplane = vivid_s_fmt_cap_mplane, .vidioc_enum_fmt_vid_out = vivid_enum_fmt_vid, .vidioc_g_fmt_vid_out = vidioc_g_fmt_vid_out, .vidioc_try_fmt_vid_out = vidioc_try_fmt_vid_out, .vidioc_s_fmt_vid_out = vidioc_s_fmt_vid_out, .vidioc_g_fmt_vid_out_mplane = vidioc_g_fmt_vid_out_mplane, .vidioc_try_fmt_vid_out_mplane = vidioc_try_fmt_vid_out_mplane, .vidioc_s_fmt_vid_out_mplane = vidioc_s_fmt_vid_out_mplane, .vidioc_g_selection = vidioc_g_selection, .vidioc_s_selection = vidioc_s_selection, .vidioc_g_pixelaspect = vidioc_g_pixelaspect, .vidioc_g_fmt_vbi_cap = vidioc_g_fmt_vbi_cap, .vidioc_try_fmt_vbi_cap = vidioc_g_fmt_vbi_cap, .vidioc_s_fmt_vbi_cap = vidioc_s_fmt_vbi_cap, .vidioc_g_fmt_sliced_vbi_cap = vidioc_g_fmt_sliced_vbi_cap, .vidioc_try_fmt_sliced_vbi_cap = vidioc_try_fmt_sliced_vbi_cap, .vidioc_s_fmt_sliced_vbi_cap = vidioc_s_fmt_sliced_vbi_cap, .vidioc_g_sliced_vbi_cap = vidioc_g_sliced_vbi_cap, .vidioc_g_fmt_vbi_out = vidioc_g_fmt_vbi_out, .vidioc_try_fmt_vbi_out = vidioc_g_fmt_vbi_out, .vidioc_s_fmt_vbi_out = vidioc_s_fmt_vbi_out, .vidioc_g_fmt_sliced_vbi_out = vidioc_g_fmt_sliced_vbi_out, .vidioc_try_fmt_sliced_vbi_out = vidioc_try_fmt_sliced_vbi_out, .vidioc_s_fmt_sliced_vbi_out = vidioc_s_fmt_sliced_vbi_out, .vidioc_enum_fmt_sdr_cap = vidioc_enum_fmt_sdr_cap, .vidioc_g_fmt_sdr_cap = vidioc_g_fmt_sdr_cap, .vidioc_try_fmt_sdr_cap = vidioc_try_fmt_sdr_cap, .vidioc_s_fmt_sdr_cap = vidioc_s_fmt_sdr_cap, .vidioc_overlay = vidioc_overlay, .vidioc_enum_framesizes = vidioc_enum_framesizes, .vidioc_enum_frameintervals = vidioc_enum_frameintervals, .vidioc_g_parm = vidioc_g_parm, .vidioc_s_parm = vidioc_s_parm, .vidioc_g_fmt_vid_out_overlay = vidioc_g_fmt_vid_out_overlay, .vidioc_try_fmt_vid_out_overlay = vidioc_try_fmt_vid_out_overlay, .vidioc_s_fmt_vid_out_overlay = vidioc_s_fmt_vid_out_overlay, .vidioc_g_fbuf = vidioc_g_fbuf, .vidioc_s_fbuf = vidioc_s_fbuf, .vidioc_reqbufs = vidioc_reqbufs, .vidioc_create_bufs = vidioc_create_bufs, .vidioc_prepare_buf = vb2_ioctl_prepare_buf, .vidioc_querybuf = vb2_ioctl_querybuf, .vidioc_qbuf = vb2_ioctl_qbuf, .vidioc_dqbuf = vb2_ioctl_dqbuf, .vidioc_expbuf = vb2_ioctl_expbuf, .vidioc_streamon = vb2_ioctl_streamon, .vidioc_streamoff = vb2_ioctl_streamoff, .vidioc_enum_input = vivid_enum_input, .vidioc_g_input = vivid_g_input, .vidioc_s_input = vivid_s_input, .vidioc_s_audio = vidioc_s_audio, .vidioc_g_audio = vidioc_g_audio, .vidioc_enumaudio = vidioc_enumaudio, .vidioc_s_frequency = vidioc_s_frequency, .vidioc_g_frequency = vidioc_g_frequency, .vidioc_s_tuner = vidioc_s_tuner, .vidioc_g_tuner = vidioc_g_tuner, .vidioc_s_modulator = vidioc_s_modulator, .vidioc_g_modulator = vidioc_g_modulator, .vidioc_s_hw_freq_seek = vidioc_s_hw_freq_seek, .vidioc_enum_freq_bands = vidioc_enum_freq_bands, .vidioc_enum_output = vidioc_enum_output, .vidioc_g_output = vidioc_g_output, .vidioc_s_output = vidioc_s_output, .vidioc_s_audout = vidioc_s_audout, .vidioc_g_audout = vidioc_g_audout, .vidioc_enumaudout = vidioc_enumaudout, .vidioc_querystd = vidioc_querystd, .vidioc_g_std = vidioc_g_std, .vidioc_s_std = vidioc_s_std, .vidioc_s_dv_timings = vidioc_s_dv_timings, .vidioc_g_dv_timings = vidioc_g_dv_timings, .vidioc_query_dv_timings = vidioc_query_dv_timings, .vidioc_enum_dv_timings = vidioc_enum_dv_timings, .vidioc_dv_timings_cap = vidioc_dv_timings_cap, .vidioc_g_edid = vidioc_g_edid, .vidioc_s_edid = vidioc_s_edid, .vidioc_log_status = vidioc_log_status, .vidioc_subscribe_event = vidioc_subscribe_event, .vidioc_unsubscribe_event = v4l2_event_unsubscribe, .vidioc_enum_fmt_meta_cap = vidioc_enum_fmt_meta_cap, .vidioc_g_fmt_meta_cap = vidioc_g_fmt_meta_cap, .vidioc_s_fmt_meta_cap = vidioc_g_fmt_meta_cap, .vidioc_try_fmt_meta_cap = vidioc_g_fmt_meta_cap, .vidioc_enum_fmt_meta_out = vidioc_enum_fmt_meta_out, .vidioc_g_fmt_meta_out = vidioc_g_fmt_meta_out, .vidioc_s_fmt_meta_out = vidioc_g_fmt_meta_out, .vidioc_try_fmt_meta_out = vidioc_g_fmt_meta_out, }; /* ----------------------------------------------------------------- Initialization and module stuff ------------------------------------------------------------------*/ static void vivid_dev_release(struct v4l2_device *v4l2_dev) { struct vivid_dev *dev = container_of(v4l2_dev, struct vivid_dev, v4l2_dev); vivid_free_controls(dev); v4l2_device_unregister(&dev->v4l2_dev); #ifdef CONFIG_MEDIA_CONTROLLER media_device_cleanup(&dev->mdev); #endif vfree(dev->scaled_line); vfree(dev->blended_line); vfree(dev->edid); tpg_free(&dev->tpg); kfree(dev->query_dv_timings_qmenu); kfree(dev->query_dv_timings_qmenu_strings); kfree(dev); } #ifdef CONFIG_MEDIA_CONTROLLER static int vivid_req_validate(struct media_request *req) { struct vivid_dev *dev = container_of(req->mdev, struct vivid_dev, mdev); if (dev->req_validate_error) { dev->req_validate_error = false; return -EINVAL; } return vb2_request_validate(req); } static const struct media_device_ops vivid_media_ops = { .req_validate = vivid_req_validate, .req_queue = vb2_request_queue, }; #endif static int vivid_create_queue(struct vivid_dev *dev, struct vb2_queue *q, u32 buf_type, unsigned int min_buffers_needed, const struct vb2_ops *ops) { if (buf_type == V4L2_BUF_TYPE_VIDEO_CAPTURE && dev->multiplanar) buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; else if (buf_type == V4L2_BUF_TYPE_VIDEO_OUTPUT && dev->multiplanar) buf_type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; else if (buf_type == V4L2_BUF_TYPE_VBI_CAPTURE && !dev->has_raw_vbi_cap) buf_type = V4L2_BUF_TYPE_SLICED_VBI_CAPTURE; else if (buf_type == V4L2_BUF_TYPE_VBI_OUTPUT && !dev->has_raw_vbi_out) buf_type = V4L2_BUF_TYPE_SLICED_VBI_OUTPUT; q->type = buf_type; q->io_modes = VB2_MMAP | VB2_DMABUF; q->io_modes |= V4L2_TYPE_IS_OUTPUT(buf_type) ? VB2_WRITE : VB2_READ; if (allocators[dev->inst] != 1) q->io_modes |= VB2_USERPTR; q->drv_priv = dev; q->buf_struct_size = sizeof(struct vivid_buffer); q->ops = ops; q->mem_ops = allocators[dev->inst] == 1 ? &vb2_dma_contig_memops : &vb2_vmalloc_memops; q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC; q->min_buffers_needed = supports_requests[dev->inst] ? 0 : min_buffers_needed; q->lock = &dev->mutex; q->dev = dev->v4l2_dev.dev; q->supports_requests = supports_requests[dev->inst]; q->requires_requests = supports_requests[dev->inst] >= 2; q->allow_cache_hints = (cache_hints[dev->inst] == 1); return vb2_queue_init(q); } static int vivid_detect_feature_set(struct vivid_dev *dev, int inst, unsigned node_type, bool *has_tuner, bool *has_modulator, int *ccs_cap, int *ccs_out, unsigned in_type_counter[4], unsigned out_type_counter[4]) { int i; /* do we use single- or multi-planar? */ dev->multiplanar = multiplanar[inst] > 1; v4l2_info(&dev->v4l2_dev, "using %splanar format API\n", dev->multiplanar ? "multi" : "single "); /* how many inputs do we have and of what type? */ dev->num_inputs = num_inputs[inst]; if (node_type & 0x20007) { if (dev->num_inputs < 1) dev->num_inputs = 1; } else { dev->num_inputs = 0; } if (dev->num_inputs >= MAX_INPUTS) dev->num_inputs = MAX_INPUTS; for (i = 0; i < dev->num_inputs; i++) { dev->input_type[i] = (input_types[inst] >> (i * 2)) & 0x3; dev->input_name_counter[i] = in_type_counter[dev->input_type[i]]++; } dev->has_audio_inputs = in_type_counter[TV] && in_type_counter[SVID]; if (in_type_counter[HDMI] == 16) { /* The CEC physical address only allows for max 15 inputs */ in_type_counter[HDMI]--; dev->num_inputs--; } dev->num_hdmi_inputs = in_type_counter[HDMI]; /* how many outputs do we have and of what type? */ dev->num_outputs = num_outputs[inst]; if (node_type & 0x40300) { if (dev->num_outputs < 1) dev->num_outputs = 1; } else { dev->num_outputs = 0; } if (dev->num_outputs >= MAX_OUTPUTS) dev->num_outputs = MAX_OUTPUTS; for (i = 0; i < dev->num_outputs; i++) { dev->output_type[i] = ((output_types[inst] >> i) & 1) ? HDMI : SVID; dev->output_name_counter[i] = out_type_counter[dev->output_type[i]]++; dev->display_present[i] = true; } dev->has_audio_outputs = out_type_counter[SVID]; if (out_type_counter[HDMI] == 16) { /* * The CEC physical address only allows for max 15 inputs, * so outputs are also limited to 15 to allow for easy * CEC output to input mapping. */ out_type_counter[HDMI]--; dev->num_outputs--; } dev->num_hdmi_outputs = out_type_counter[HDMI]; /* do we create a video capture device? */ dev->has_vid_cap = node_type & 0x0001; /* do we create a vbi capture device? */ if (in_type_counter[TV] || in_type_counter[SVID]) { dev->has_raw_vbi_cap = node_type & 0x0004; dev->has_sliced_vbi_cap = node_type & 0x0008; dev->has_vbi_cap = dev->has_raw_vbi_cap | dev->has_sliced_vbi_cap; } /* do we create a meta capture device */ dev->has_meta_cap = node_type & 0x20000; /* sanity checks */ if ((in_type_counter[WEBCAM] || in_type_counter[HDMI]) && !dev->has_vid_cap && !dev->has_meta_cap) { v4l2_warn(&dev->v4l2_dev, "Webcam or HDMI input without video or metadata nodes\n"); return -EINVAL; } if ((in_type_counter[TV] || in_type_counter[SVID]) && !dev->has_vid_cap && !dev->has_vbi_cap && !dev->has_meta_cap) { v4l2_warn(&dev->v4l2_dev, "TV or S-Video input without video, VBI or metadata nodes\n"); return -EINVAL; } /* do we create a video output device? */ dev->has_vid_out = node_type & 0x0100; /* do we create a vbi output device? */ if (out_type_counter[SVID]) { dev->has_raw_vbi_out = node_type & 0x0400; dev->has_sliced_vbi_out = node_type & 0x0800; dev->has_vbi_out = dev->has_raw_vbi_out | dev->has_sliced_vbi_out; } /* do we create a metadata output device */ dev->has_meta_out = node_type & 0x40000; /* sanity checks */ if (out_type_counter[SVID] && !dev->has_vid_out && !dev->has_vbi_out && !dev->has_meta_out) { v4l2_warn(&dev->v4l2_dev, "S-Video output without video, VBI or metadata nodes\n"); return -EINVAL; } if (out_type_counter[HDMI] && !dev->has_vid_out && !dev->has_meta_out) { v4l2_warn(&dev->v4l2_dev, "HDMI output without video or metadata nodes\n"); return -EINVAL; } /* do we create a radio receiver device? */ dev->has_radio_rx = node_type & 0x0010; /* do we create a radio transmitter device? */ dev->has_radio_tx = node_type & 0x1000; /* do we create a software defined radio capture device? */ dev->has_sdr_cap = node_type & 0x0020; /* do we have a TV tuner? */ dev->has_tv_tuner = in_type_counter[TV]; /* do we have a tuner? */ *has_tuner = ((dev->has_vid_cap || dev->has_vbi_cap) && in_type_counter[TV]) || dev->has_radio_rx || dev->has_sdr_cap; /* do we have a modulator? */ *has_modulator = dev->has_radio_tx; if (dev->has_vid_cap) /* do we have a framebuffer for overlay testing? */ dev->has_fb = node_type & 0x10000; /* can we do crop/compose/scaling while capturing? */ if (no_error_inj && *ccs_cap == -1) *ccs_cap = 7; /* if ccs_cap == -1, then the user can select it using controls */ if (*ccs_cap != -1) { dev->has_crop_cap = *ccs_cap & 1; dev->has_compose_cap = *ccs_cap & 2; dev->has_scaler_cap = *ccs_cap & 4; v4l2_info(&dev->v4l2_dev, "Capture Crop: %c Compose: %c Scaler: %c\n", dev->has_crop_cap ? 'Y' : 'N', dev->has_compose_cap ? 'Y' : 'N', dev->has_scaler_cap ? 'Y' : 'N'); } /* can we do crop/compose/scaling with video output? */ if (no_error_inj && *ccs_out == -1) *ccs_out = 7; /* if ccs_out == -1, then the user can select it using controls */ if (*ccs_out != -1) { dev->has_crop_out = *ccs_out & 1; dev->has_compose_out = *ccs_out & 2; dev->has_scaler_out = *ccs_out & 4; v4l2_info(&dev->v4l2_dev, "Output Crop: %c Compose: %c Scaler: %c\n", dev->has_crop_out ? 'Y' : 'N', dev->has_compose_out ? 'Y' : 'N', dev->has_scaler_out ? 'Y' : 'N'); } /* do we create a touch capture device */ dev->has_touch_cap = node_type & 0x80000; return 0; } static void vivid_set_capabilities(struct vivid_dev *dev) { if (dev->has_vid_cap) { /* set up the capabilities of the video capture device */ dev->vid_cap_caps = dev->multiplanar ? V4L2_CAP_VIDEO_CAPTURE_MPLANE : V4L2_CAP_VIDEO_CAPTURE; dev->vid_cap_caps |= V4L2_CAP_STREAMING | V4L2_CAP_READWRITE; if (dev->has_audio_inputs) dev->vid_cap_caps |= V4L2_CAP_AUDIO; if (dev->has_tv_tuner) dev->vid_cap_caps |= V4L2_CAP_TUNER; } if (dev->has_vid_out) { /* set up the capabilities of the video output device */ dev->vid_out_caps = dev->multiplanar ? V4L2_CAP_VIDEO_OUTPUT_MPLANE : V4L2_CAP_VIDEO_OUTPUT; if (dev->has_fb) dev->vid_out_caps |= V4L2_CAP_VIDEO_OUTPUT_OVERLAY; dev->vid_out_caps |= V4L2_CAP_STREAMING | V4L2_CAP_READWRITE; if (dev->has_audio_outputs) dev->vid_out_caps |= V4L2_CAP_AUDIO; } if (dev->has_vbi_cap) { /* set up the capabilities of the vbi capture device */ dev->vbi_cap_caps = (dev->has_raw_vbi_cap ? V4L2_CAP_VBI_CAPTURE : 0) | (dev->has_sliced_vbi_cap ? V4L2_CAP_SLICED_VBI_CAPTURE : 0); dev->vbi_cap_caps |= V4L2_CAP_STREAMING | V4L2_CAP_READWRITE; if (dev->has_audio_inputs) dev->vbi_cap_caps |= V4L2_CAP_AUDIO; if (dev->has_tv_tuner) dev->vbi_cap_caps |= V4L2_CAP_TUNER; } if (dev->has_vbi_out) { /* set up the capabilities of the vbi output device */ dev->vbi_out_caps = (dev->has_raw_vbi_out ? V4L2_CAP_VBI_OUTPUT : 0) | (dev->has_sliced_vbi_out ? V4L2_CAP_SLICED_VBI_OUTPUT : 0); dev->vbi_out_caps |= V4L2_CAP_STREAMING | V4L2_CAP_READWRITE; if (dev->has_audio_outputs) dev->vbi_out_caps |= V4L2_CAP_AUDIO; } if (dev->has_sdr_cap) { /* set up the capabilities of the sdr capture device */ dev->sdr_cap_caps = V4L2_CAP_SDR_CAPTURE | V4L2_CAP_TUNER; dev->sdr_cap_caps |= V4L2_CAP_STREAMING | V4L2_CAP_READWRITE; } /* set up the capabilities of the radio receiver device */ if (dev->has_radio_rx) dev->radio_rx_caps = V4L2_CAP_RADIO | V4L2_CAP_RDS_CAPTURE | V4L2_CAP_HW_FREQ_SEEK | V4L2_CAP_TUNER | V4L2_CAP_READWRITE; /* set up the capabilities of the radio transmitter device */ if (dev->has_radio_tx) dev->radio_tx_caps = V4L2_CAP_RDS_OUTPUT | V4L2_CAP_MODULATOR | V4L2_CAP_READWRITE; /* set up the capabilities of meta capture device */ if (dev->has_meta_cap) { dev->meta_cap_caps = V4L2_CAP_META_CAPTURE | V4L2_CAP_STREAMING | V4L2_CAP_READWRITE; if (dev->has_audio_inputs) dev->meta_cap_caps |= V4L2_CAP_AUDIO; if (dev->has_tv_tuner) dev->meta_cap_caps |= V4L2_CAP_TUNER; } /* set up the capabilities of meta output device */ if (dev->has_meta_out) { dev->meta_out_caps = V4L2_CAP_META_OUTPUT | V4L2_CAP_STREAMING | V4L2_CAP_READWRITE; if (dev->has_audio_outputs) dev->meta_out_caps |= V4L2_CAP_AUDIO; } /* set up the capabilities of the touch capture device */ if (dev->has_touch_cap) { dev->touch_cap_caps = V4L2_CAP_TOUCH | V4L2_CAP_STREAMING | V4L2_CAP_READWRITE; dev->touch_cap_caps |= dev->multiplanar ? V4L2_CAP_VIDEO_CAPTURE_MPLANE : V4L2_CAP_VIDEO_CAPTURE; } } static void vivid_disable_unused_ioctls(struct vivid_dev *dev, bool has_tuner, bool has_modulator, unsigned in_type_counter[4], unsigned out_type_counter[4]) { /* disable invalid ioctls based on the feature set */ if (!dev->has_audio_inputs) { v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_S_AUDIO); v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_G_AUDIO); v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_ENUMAUDIO); v4l2_disable_ioctl(&dev->vbi_cap_dev, VIDIOC_S_AUDIO); v4l2_disable_ioctl(&dev->vbi_cap_dev, VIDIOC_G_AUDIO); v4l2_disable_ioctl(&dev->vbi_cap_dev, VIDIOC_ENUMAUDIO); v4l2_disable_ioctl(&dev->meta_cap_dev, VIDIOC_S_AUDIO); v4l2_disable_ioctl(&dev->meta_cap_dev, VIDIOC_G_AUDIO); v4l2_disable_ioctl(&dev->meta_cap_dev, VIDIOC_ENUMAUDIO); } if (!dev->has_audio_outputs) { v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_S_AUDOUT); v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_G_AUDOUT); v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_ENUMAUDOUT); v4l2_disable_ioctl(&dev->vbi_out_dev, VIDIOC_S_AUDOUT); v4l2_disable_ioctl(&dev->vbi_out_dev, VIDIOC_G_AUDOUT); v4l2_disable_ioctl(&dev->vbi_out_dev, VIDIOC_ENUMAUDOUT); v4l2_disable_ioctl(&dev->meta_out_dev, VIDIOC_S_AUDOUT); v4l2_disable_ioctl(&dev->meta_out_dev, VIDIOC_G_AUDOUT); v4l2_disable_ioctl(&dev->meta_out_dev, VIDIOC_ENUMAUDOUT); } if (!in_type_counter[TV] && !in_type_counter[SVID]) { v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_S_STD); v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_G_STD); v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_ENUMSTD); v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_QUERYSTD); } if (!out_type_counter[SVID]) { v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_S_STD); v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_G_STD); v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_ENUMSTD); } if (!has_tuner && !has_modulator) { v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_S_FREQUENCY); v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_G_FREQUENCY); v4l2_disable_ioctl(&dev->vbi_cap_dev, VIDIOC_S_FREQUENCY); v4l2_disable_ioctl(&dev->vbi_cap_dev, VIDIOC_G_FREQUENCY); v4l2_disable_ioctl(&dev->meta_cap_dev, VIDIOC_S_FREQUENCY); v4l2_disable_ioctl(&dev->meta_cap_dev, VIDIOC_G_FREQUENCY); } if (!has_tuner) { v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_S_TUNER); v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_G_TUNER); v4l2_disable_ioctl(&dev->vbi_cap_dev, VIDIOC_S_TUNER); v4l2_disable_ioctl(&dev->vbi_cap_dev, VIDIOC_G_TUNER); v4l2_disable_ioctl(&dev->meta_cap_dev, VIDIOC_S_TUNER); v4l2_disable_ioctl(&dev->meta_cap_dev, VIDIOC_G_TUNER); } if (in_type_counter[HDMI] == 0) { v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_S_EDID); v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_G_EDID); v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_DV_TIMINGS_CAP); v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_G_DV_TIMINGS); v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_S_DV_TIMINGS); v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_ENUM_DV_TIMINGS); v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_QUERY_DV_TIMINGS); } if (out_type_counter[HDMI] == 0) { v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_G_EDID); v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_DV_TIMINGS_CAP); v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_G_DV_TIMINGS); v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_S_DV_TIMINGS); v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_ENUM_DV_TIMINGS); } if (!dev->has_fb) { v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_G_FBUF); v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_S_FBUF); v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_OVERLAY); } v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_S_HW_FREQ_SEEK); v4l2_disable_ioctl(&dev->vbi_cap_dev, VIDIOC_S_HW_FREQ_SEEK); v4l2_disable_ioctl(&dev->sdr_cap_dev, VIDIOC_S_HW_FREQ_SEEK); v4l2_disable_ioctl(&dev->meta_cap_dev, VIDIOC_S_HW_FREQ_SEEK); v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_S_FREQUENCY); v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_G_FREQUENCY); v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_ENUM_FRAMESIZES); v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_ENUM_FRAMEINTERVALS); v4l2_disable_ioctl(&dev->vbi_out_dev, VIDIOC_S_FREQUENCY); v4l2_disable_ioctl(&dev->vbi_out_dev, VIDIOC_G_FREQUENCY); v4l2_disable_ioctl(&dev->meta_out_dev, VIDIOC_S_FREQUENCY); v4l2_disable_ioctl(&dev->meta_out_dev, VIDIOC_G_FREQUENCY); v4l2_disable_ioctl(&dev->touch_cap_dev, VIDIOC_S_PARM); v4l2_disable_ioctl(&dev->touch_cap_dev, VIDIOC_ENUM_FRAMESIZES); v4l2_disable_ioctl(&dev->touch_cap_dev, VIDIOC_ENUM_FRAMEINTERVALS); } static int vivid_init_dv_timings(struct vivid_dev *dev) { int i; while (v4l2_dv_timings_presets[dev->query_dv_timings_size].bt.width) dev->query_dv_timings_size++; /* * Create a char pointer array that points to the names of all the * preset timings */ dev->query_dv_timings_qmenu = kmalloc_array(dev->query_dv_timings_size, sizeof(char *), GFP_KERNEL); /* * Create a string array containing the names of all the preset * timings. Each name is max 31 chars long (+ terminating 0). */ dev->query_dv_timings_qmenu_strings = kmalloc_array(dev->query_dv_timings_size, 32, GFP_KERNEL); if (!dev->query_dv_timings_qmenu || !dev->query_dv_timings_qmenu_strings) return -ENOMEM; for (i = 0; i < dev->query_dv_timings_size; i++) { const struct v4l2_bt_timings *bt = &v4l2_dv_timings_presets[i].bt; char *p = dev->query_dv_timings_qmenu_strings + i * 32; u32 htot, vtot; dev->query_dv_timings_qmenu[i] = p; htot = V4L2_DV_BT_FRAME_WIDTH(bt); vtot = V4L2_DV_BT_FRAME_HEIGHT(bt); snprintf(p, 32, "%ux%u%s%u", bt->width, bt->height, bt->interlaced ? "i" : "p", (u32)bt->pixelclock / (htot * vtot)); } return 0; } static int vivid_create_queues(struct vivid_dev *dev) { int ret; /* start creating the vb2 queues */ if (dev->has_vid_cap) { /* initialize vid_cap queue */ ret = vivid_create_queue(dev, &dev->vb_vid_cap_q, V4L2_BUF_TYPE_VIDEO_CAPTURE, 2, &vivid_vid_cap_qops); if (ret) return ret; } if (dev->has_vid_out) { /* initialize vid_out queue */ ret = vivid_create_queue(dev, &dev->vb_vid_out_q, V4L2_BUF_TYPE_VIDEO_OUTPUT, 2, &vivid_vid_out_qops); if (ret) return ret; } if (dev->has_vbi_cap) { /* initialize vbi_cap queue */ ret = vivid_create_queue(dev, &dev->vb_vbi_cap_q, V4L2_BUF_TYPE_VBI_CAPTURE, 2, &vivid_vbi_cap_qops); if (ret) return ret; } if (dev->has_vbi_out) { /* initialize vbi_out queue */ ret = vivid_create_queue(dev, &dev->vb_vbi_out_q, V4L2_BUF_TYPE_VBI_OUTPUT, 2, &vivid_vbi_out_qops); if (ret) return ret; } if (dev->has_sdr_cap) { /* initialize sdr_cap queue */ ret = vivid_create_queue(dev, &dev->vb_sdr_cap_q, V4L2_BUF_TYPE_SDR_CAPTURE, 8, &vivid_sdr_cap_qops); if (ret) return ret; } if (dev->has_meta_cap) { /* initialize meta_cap queue */ ret = vivid_create_queue(dev, &dev->vb_meta_cap_q, V4L2_BUF_TYPE_META_CAPTURE, 2, &vivid_meta_cap_qops); if (ret) return ret; } if (dev->has_meta_out) { /* initialize meta_out queue */ ret = vivid_create_queue(dev, &dev->vb_meta_out_q, V4L2_BUF_TYPE_META_OUTPUT, 1, &vivid_meta_out_qops); if (ret) return ret; } if (dev->has_touch_cap) { /* initialize touch_cap queue */ ret = vivid_create_queue(dev, &dev->vb_touch_cap_q, V4L2_BUF_TYPE_VIDEO_CAPTURE, 1, &vivid_touch_cap_qops); if (ret) return ret; } if (dev->has_fb) { /* Create framebuffer for testing output overlay */ ret = vivid_fb_init(dev); if (ret) return ret; v4l2_info(&dev->v4l2_dev, "Framebuffer device registered as fb%d\n", dev->fb_info.node); } return 0; } static int vivid_create_devnodes(struct platform_device *pdev, struct vivid_dev *dev, int inst, unsigned int cec_tx_bus_cnt, v4l2_std_id tvnorms_cap, v4l2_std_id tvnorms_out, unsigned in_type_counter[4], unsigned out_type_counter[4]) { struct video_device *vfd; int ret; if (dev->has_vid_cap) { vfd = &dev->vid_cap_dev; snprintf(vfd->name, sizeof(vfd->name), "vivid-%03d-vid-cap", inst); vfd->fops = &vivid_fops; vfd->ioctl_ops = &vivid_ioctl_ops; vfd->device_caps = dev->vid_cap_caps; vfd->release = video_device_release_empty; vfd->v4l2_dev = &dev->v4l2_dev; vfd->queue = &dev->vb_vid_cap_q; vfd->tvnorms = tvnorms_cap; /* * Provide a mutex to v4l2 core. It will be used to protect * all fops and v4l2 ioctls. */ vfd->lock = &dev->mutex; video_set_drvdata(vfd, dev); #ifdef CONFIG_MEDIA_CONTROLLER dev->vid_cap_pad.flags = MEDIA_PAD_FL_SINK; ret = media_entity_pads_init(&vfd->entity, 1, &dev->vid_cap_pad); if (ret) return ret; #endif #ifdef CONFIG_VIDEO_VIVID_CEC if (in_type_counter[HDMI]) { ret = cec_register_adapter(dev->cec_rx_adap, &pdev->dev); if (ret < 0) { cec_delete_adapter(dev->cec_rx_adap); dev->cec_rx_adap = NULL; return ret; } cec_s_phys_addr(dev->cec_rx_adap, 0, false); v4l2_info(&dev->v4l2_dev, "CEC adapter %s registered for HDMI input 0\n", dev_name(&dev->cec_rx_adap->devnode.dev)); } #endif ret = video_register_device(vfd, VFL_TYPE_VIDEO, vid_cap_nr[inst]); if (ret < 0) return ret; v4l2_info(&dev->v4l2_dev, "V4L2 capture device registered as %s\n", video_device_node_name(vfd)); } if (dev->has_vid_out) { #ifdef CONFIG_VIDEO_VIVID_CEC int i; #endif vfd = &dev->vid_out_dev; snprintf(vfd->name, sizeof(vfd->name), "vivid-%03d-vid-out", inst); vfd->vfl_dir = VFL_DIR_TX; vfd->fops = &vivid_fops; vfd->ioctl_ops = &vivid_ioctl_ops; vfd->device_caps = dev->vid_out_caps; vfd->release = video_device_release_empty; vfd->v4l2_dev = &dev->v4l2_dev; vfd->queue = &dev->vb_vid_out_q; vfd->tvnorms = tvnorms_out; /* * Provide a mutex to v4l2 core. It will be used to protect * all fops and v4l2 ioctls. */ vfd->lock = &dev->mutex; video_set_drvdata(vfd, dev); #ifdef CONFIG_MEDIA_CONTROLLER dev->vid_out_pad.flags = MEDIA_PAD_FL_SOURCE; ret = media_entity_pads_init(&vfd->entity, 1, &dev->vid_out_pad); if (ret) return ret; #endif #ifdef CONFIG_VIDEO_VIVID_CEC for (i = 0; i < cec_tx_bus_cnt; i++) { ret = cec_register_adapter(dev->cec_tx_adap[i], &pdev->dev); if (ret < 0) { for (; i < cec_tx_bus_cnt; i++) { cec_delete_adapter(dev->cec_tx_adap[i]); dev->cec_tx_adap[i] = NULL; } return ret; } v4l2_info(&dev->v4l2_dev, "CEC adapter %s registered for HDMI output %d\n", dev_name(&dev->cec_tx_adap[i]->devnode.dev), i); if (i < out_type_counter[HDMI]) cec_s_phys_addr(dev->cec_tx_adap[i], (i + 1) << 12, false); else cec_s_phys_addr(dev->cec_tx_adap[i], 0x1000, false); } #endif ret = video_register_device(vfd, VFL_TYPE_VIDEO, vid_out_nr[inst]); if (ret < 0) return ret; v4l2_info(&dev->v4l2_dev, "V4L2 output device registered as %s\n", video_device_node_name(vfd)); } if (dev->has_vbi_cap) { vfd = &dev->vbi_cap_dev; snprintf(vfd->name, sizeof(vfd->name), "vivid-%03d-vbi-cap", inst); vfd->fops = &vivid_fops; vfd->ioctl_ops = &vivid_ioctl_ops; vfd->device_caps = dev->vbi_cap_caps; vfd->release = video_device_release_empty; vfd->v4l2_dev = &dev->v4l2_dev; vfd->queue = &dev->vb_vbi_cap_q; vfd->lock = &dev->mutex; vfd->tvnorms = tvnorms_cap; video_set_drvdata(vfd, dev); #ifdef CONFIG_MEDIA_CONTROLLER dev->vbi_cap_pad.flags = MEDIA_PAD_FL_SINK; ret = media_entity_pads_init(&vfd->entity, 1, &dev->vbi_cap_pad); if (ret) return ret; #endif ret = video_register_device(vfd, VFL_TYPE_VBI, vbi_cap_nr[inst]); if (ret < 0) return ret; v4l2_info(&dev->v4l2_dev, "V4L2 capture device registered as %s, supports %s VBI\n", video_device_node_name(vfd), (dev->has_raw_vbi_cap && dev->has_sliced_vbi_cap) ? "raw and sliced" : (dev->has_raw_vbi_cap ? "raw" : "sliced")); } if (dev->has_vbi_out) { vfd = &dev->vbi_out_dev; snprintf(vfd->name, sizeof(vfd->name), "vivid-%03d-vbi-out", inst); vfd->vfl_dir = VFL_DIR_TX; vfd->fops = &vivid_fops; vfd->ioctl_ops = &vivid_ioctl_ops; vfd->device_caps = dev->vbi_out_caps; vfd->release = video_device_release_empty; vfd->v4l2_dev = &dev->v4l2_dev; vfd->queue = &dev->vb_vbi_out_q; vfd->lock = &dev->mutex; vfd->tvnorms = tvnorms_out; video_set_drvdata(vfd, dev); #ifdef CONFIG_MEDIA_CONTROLLER dev->vbi_out_pad.flags = MEDIA_PAD_FL_SOURCE; ret = media_entity_pads_init(&vfd->entity, 1, &dev->vbi_out_pad); if (ret) return ret; #endif ret = video_register_device(vfd, VFL_TYPE_VBI, vbi_out_nr[inst]); if (ret < 0) return ret; v4l2_info(&dev->v4l2_dev, "V4L2 output device registered as %s, supports %s VBI\n", video_device_node_name(vfd), (dev->has_raw_vbi_out && dev->has_sliced_vbi_out) ? "raw and sliced" : (dev->has_raw_vbi_out ? "raw" : "sliced")); } if (dev->has_sdr_cap) { vfd = &dev->sdr_cap_dev; snprintf(vfd->name, sizeof(vfd->name), "vivid-%03d-sdr-cap", inst); vfd->fops = &vivid_fops; vfd->ioctl_ops = &vivid_ioctl_ops; vfd->device_caps = dev->sdr_cap_caps; vfd->release = video_device_release_empty; vfd->v4l2_dev = &dev->v4l2_dev; vfd->queue = &dev->vb_sdr_cap_q; vfd->lock = &dev->mutex; video_set_drvdata(vfd, dev); #ifdef CONFIG_MEDIA_CONTROLLER dev->sdr_cap_pad.flags = MEDIA_PAD_FL_SINK; ret = media_entity_pads_init(&vfd->entity, 1, &dev->sdr_cap_pad); if (ret) return ret; #endif ret = video_register_device(vfd, VFL_TYPE_SDR, sdr_cap_nr[inst]); if (ret < 0) return ret; v4l2_info(&dev->v4l2_dev, "V4L2 capture device registered as %s\n", video_device_node_name(vfd)); } if (dev->has_radio_rx) { vfd = &dev->radio_rx_dev; snprintf(vfd->name, sizeof(vfd->name), "vivid-%03d-rad-rx", inst); vfd->fops = &vivid_radio_fops; vfd->ioctl_ops = &vivid_ioctl_ops; vfd->device_caps = dev->radio_rx_caps; vfd->release = video_device_release_empty; vfd->v4l2_dev = &dev->v4l2_dev; vfd->lock = &dev->mutex; video_set_drvdata(vfd, dev); ret = video_register_device(vfd, VFL_TYPE_RADIO, radio_rx_nr[inst]); if (ret < 0) return ret; v4l2_info(&dev->v4l2_dev, "V4L2 receiver device registered as %s\n", video_device_node_name(vfd)); } if (dev->has_radio_tx) { vfd = &dev->radio_tx_dev; snprintf(vfd->name, sizeof(vfd->name), "vivid-%03d-rad-tx", inst); vfd->vfl_dir = VFL_DIR_TX; vfd->fops = &vivid_radio_fops; vfd->ioctl_ops = &vivid_ioctl_ops; vfd->device_caps = dev->radio_tx_caps; vfd->release = video_device_release_empty; vfd->v4l2_dev = &dev->v4l2_dev; vfd->lock = &dev->mutex; video_set_drvdata(vfd, dev); ret = video_register_device(vfd, VFL_TYPE_RADIO, radio_tx_nr[inst]); if (ret < 0) return ret; v4l2_info(&dev->v4l2_dev, "V4L2 transmitter device registered as %s\n", video_device_node_name(vfd)); } if (dev->has_meta_cap) { vfd = &dev->meta_cap_dev; snprintf(vfd->name, sizeof(vfd->name), "vivid-%03d-meta-cap", inst); vfd->fops = &vivid_fops; vfd->ioctl_ops = &vivid_ioctl_ops; vfd->device_caps = dev->meta_cap_caps; vfd->release = video_device_release_empty; vfd->v4l2_dev = &dev->v4l2_dev; vfd->queue = &dev->vb_meta_cap_q; vfd->lock = &dev->mutex; vfd->tvnorms = tvnorms_cap; video_set_drvdata(vfd, dev); #ifdef CONFIG_MEDIA_CONTROLLER dev->meta_cap_pad.flags = MEDIA_PAD_FL_SINK; ret = media_entity_pads_init(&vfd->entity, 1, &dev->meta_cap_pad); if (ret) return ret; #endif ret = video_register_device(vfd, VFL_TYPE_VIDEO, meta_cap_nr[inst]); if (ret < 0) return ret; v4l2_info(&dev->v4l2_dev, "V4L2 metadata capture device registered as %s\n", video_device_node_name(vfd)); } if (dev->has_meta_out) { vfd = &dev->meta_out_dev; snprintf(vfd->name, sizeof(vfd->name), "vivid-%03d-meta-out", inst); vfd->vfl_dir = VFL_DIR_TX; vfd->fops = &vivid_fops; vfd->ioctl_ops = &vivid_ioctl_ops; vfd->device_caps = dev->meta_out_caps; vfd->release = video_device_release_empty; vfd->v4l2_dev = &dev->v4l2_dev; vfd->queue = &dev->vb_meta_out_q; vfd->lock = &dev->mutex; vfd->tvnorms = tvnorms_out; video_set_drvdata(vfd, dev); #ifdef CONFIG_MEDIA_CONTROLLER dev->meta_out_pad.flags = MEDIA_PAD_FL_SOURCE; ret = media_entity_pads_init(&vfd->entity, 1, &dev->meta_out_pad); if (ret) return ret; #endif ret = video_register_device(vfd, VFL_TYPE_VIDEO, meta_out_nr[inst]); if (ret < 0) return ret; v4l2_info(&dev->v4l2_dev, "V4L2 metadata output device registered as %s\n", video_device_node_name(vfd)); } if (dev->has_touch_cap) { vfd = &dev->touch_cap_dev; snprintf(vfd->name, sizeof(vfd->name), "vivid-%03d-touch-cap", inst); vfd->fops = &vivid_fops; vfd->ioctl_ops = &vivid_ioctl_ops; vfd->device_caps = dev->touch_cap_caps; vfd->release = video_device_release_empty; vfd->v4l2_dev = &dev->v4l2_dev; vfd->queue = &dev->vb_touch_cap_q; vfd->tvnorms = tvnorms_cap; vfd->lock = &dev->mutex; video_set_drvdata(vfd, dev); #ifdef CONFIG_MEDIA_CONTROLLER dev->touch_cap_pad.flags = MEDIA_PAD_FL_SINK; ret = media_entity_pads_init(&vfd->entity, 1, &dev->touch_cap_pad); if (ret) return ret; #endif ret = video_register_device(vfd, VFL_TYPE_TOUCH, touch_cap_nr[inst]); if (ret < 0) return ret; v4l2_info(&dev->v4l2_dev, "V4L2 touch capture device registered as %s\n", video_device_node_name(vfd)); } #ifdef CONFIG_MEDIA_CONTROLLER /* Register the media device */ ret = media_device_register(&dev->mdev); if (ret) { dev_err(dev->mdev.dev, "media device register failed (err=%d)\n", ret); return ret; } #endif return 0; } static int vivid_create_instance(struct platform_device *pdev, int inst) { static const struct v4l2_dv_timings def_dv_timings = V4L2_DV_BT_CEA_1280X720P60; unsigned in_type_counter[4] = { 0, 0, 0, 0 }; unsigned out_type_counter[4] = { 0, 0, 0, 0 }; int ccs_cap = ccs_cap_mode[inst]; int ccs_out = ccs_out_mode[inst]; bool has_tuner; bool has_modulator; struct vivid_dev *dev; unsigned node_type = node_types[inst]; v4l2_std_id tvnorms_cap = 0, tvnorms_out = 0; unsigned int cec_tx_bus_cnt = 0; int ret; int i; /* allocate main vivid state structure */ dev = kzalloc(sizeof(*dev), GFP_KERNEL); if (!dev) return -ENOMEM; dev->inst = inst; #ifdef CONFIG_MEDIA_CONTROLLER dev->v4l2_dev.mdev = &dev->mdev; /* Initialize media device */ strscpy(dev->mdev.model, VIVID_MODULE_NAME, sizeof(dev->mdev.model)); snprintf(dev->mdev.bus_info, sizeof(dev->mdev.bus_info), "platform:%s-%03d", VIVID_MODULE_NAME, inst); dev->mdev.dev = &pdev->dev; media_device_init(&dev->mdev); dev->mdev.ops = &vivid_media_ops; #endif /* register v4l2_device */ snprintf(dev->v4l2_dev.name, sizeof(dev->v4l2_dev.name), "%s-%03d", VIVID_MODULE_NAME, inst); ret = v4l2_device_register(&pdev->dev, &dev->v4l2_dev); if (ret) { kfree(dev); return ret; } dev->v4l2_dev.release = vivid_dev_release; ret = vivid_detect_feature_set(dev, inst, node_type, &has_tuner, &has_modulator, &ccs_cap, &ccs_out, in_type_counter, out_type_counter); if (ret) goto free_dev; vivid_set_capabilities(dev); ret = -ENOMEM; /* initialize the test pattern generator */ tpg_init(&dev->tpg, 640, 360); if (tpg_alloc(&dev->tpg, array_size(MAX_WIDTH, MAX_ZOOM))) goto free_dev; dev->scaled_line = vzalloc(array_size(MAX_WIDTH, MAX_ZOOM)); if (!dev->scaled_line) goto free_dev; dev->blended_line = vzalloc(array_size(MAX_WIDTH, MAX_ZOOM)); if (!dev->blended_line) goto free_dev; /* load the edid */ dev->edid = vmalloc(array_size(256, 128)); if (!dev->edid) goto free_dev; ret = vivid_init_dv_timings(dev); if (ret < 0) goto free_dev; vivid_disable_unused_ioctls(dev, has_tuner, has_modulator, in_type_counter, out_type_counter); /* configure internal data */ dev->fmt_cap = &vivid_formats[0]; dev->fmt_out = &vivid_formats[0]; if (!dev->multiplanar) vivid_formats[0].data_offset[0] = 0; dev->webcam_size_idx = 1; dev->webcam_ival_idx = 3; tpg_s_fourcc(&dev->tpg, dev->fmt_cap->fourcc); dev->std_out = V4L2_STD_PAL; if (dev->input_type[0] == TV || dev->input_type[0] == SVID) tvnorms_cap = V4L2_STD_ALL; if (dev->output_type[0] == SVID) tvnorms_out = V4L2_STD_ALL; for (i = 0; i < MAX_INPUTS; i++) { dev->dv_timings_cap[i] = def_dv_timings; dev->std_cap[i] = V4L2_STD_PAL; } dev->dv_timings_out = def_dv_timings; dev->tv_freq = 2804 /* 175.25 * 16 */; dev->tv_audmode = V4L2_TUNER_MODE_STEREO; dev->tv_field_cap = V4L2_FIELD_INTERLACED; dev->tv_field_out = V4L2_FIELD_INTERLACED; dev->radio_rx_freq = 95000 * 16; dev->radio_rx_audmode = V4L2_TUNER_MODE_STEREO; if (dev->has_radio_tx) { dev->radio_tx_freq = 95500 * 16; dev->radio_rds_loop = false; } dev->radio_tx_subchans = V4L2_TUNER_SUB_STEREO | V4L2_TUNER_SUB_RDS; dev->sdr_adc_freq = 300000; dev->sdr_fm_freq = 50000000; dev->sdr_pixelformat = V4L2_SDR_FMT_CU8; dev->sdr_buffersize = SDR_CAP_SAMPLES_PER_BUF * 2; dev->edid_max_blocks = dev->edid_blocks = 2; memcpy(dev->edid, vivid_hdmi_edid, sizeof(vivid_hdmi_edid)); dev->radio_rds_init_time = ktime_get(); /* create all controls */ ret = vivid_create_controls(dev, ccs_cap == -1, ccs_out == -1, no_error_inj, in_type_counter[TV] || in_type_counter[SVID] || out_type_counter[SVID], in_type_counter[HDMI] || out_type_counter[HDMI]); if (ret) goto unreg_dev; /* enable/disable interface specific controls */ if (dev->num_outputs && dev->output_type[0] != HDMI) v4l2_ctrl_activate(dev->ctrl_display_present, false); if (dev->num_inputs && dev->input_type[0] != HDMI) { v4l2_ctrl_activate(dev->ctrl_dv_timings_signal_mode, false); v4l2_ctrl_activate(dev->ctrl_dv_timings, false); } else if (dev->num_inputs && dev->input_type[0] == HDMI) { v4l2_ctrl_activate(dev->ctrl_std_signal_mode, false); v4l2_ctrl_activate(dev->ctrl_standard, false); } /* * update the capture and output formats to do a proper initial * configuration. */ vivid_update_format_cap(dev, false); vivid_update_format_out(dev); /* update touch configuration */ dev->timeperframe_tch_cap.numerator = 1; dev->timeperframe_tch_cap.denominator = 10; vivid_set_touch(dev, 0); /* initialize locks */ spin_lock_init(&dev->slock); mutex_init(&dev->mutex); /* init dma queues */ INIT_LIST_HEAD(&dev->vid_cap_active); INIT_LIST_HEAD(&dev->vid_out_active); INIT_LIST_HEAD(&dev->vbi_cap_active); INIT_LIST_HEAD(&dev->vbi_out_active); INIT_LIST_HEAD(&dev->sdr_cap_active); INIT_LIST_HEAD(&dev->meta_cap_active); INIT_LIST_HEAD(&dev->meta_out_active); INIT_LIST_HEAD(&dev->touch_cap_active); spin_lock_init(&dev->cec_xfers_slock); if (allocators[inst] == 1) dma_coerce_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32)); ret = vivid_create_queues(dev); if (ret) goto unreg_dev; #ifdef CONFIG_VIDEO_VIVID_CEC if (dev->has_vid_cap && in_type_counter[HDMI]) { struct cec_adapter *adap; adap = vivid_cec_alloc_adap(dev, 0, false); ret = PTR_ERR_OR_ZERO(adap); if (ret < 0) goto unreg_dev; dev->cec_rx_adap = adap; } if (dev->has_vid_out) { for (i = 0; i < dev->num_outputs; i++) { struct cec_adapter *adap; if (dev->output_type[i] != HDMI) continue; dev->cec_output2bus_map[i] = cec_tx_bus_cnt; adap = vivid_cec_alloc_adap(dev, cec_tx_bus_cnt, true); ret = PTR_ERR_OR_ZERO(adap); if (ret < 0) { for (i = 0; i < dev->num_outputs; i++) cec_delete_adapter(dev->cec_tx_adap[i]); goto unreg_dev; } dev->cec_tx_adap[cec_tx_bus_cnt] = adap; cec_tx_bus_cnt++; } } if (dev->cec_rx_adap || cec_tx_bus_cnt) { init_waitqueue_head(&dev->kthread_waitq_cec); dev->kthread_cec = kthread_run(vivid_cec_bus_thread, dev, "vivid_cec-%s", dev->v4l2_dev.name); if (IS_ERR(dev->kthread_cec)) { ret = PTR_ERR(dev->kthread_cec); dev->kthread_cec = NULL; v4l2_err(&dev->v4l2_dev, "kernel_thread() failed\n"); goto unreg_dev; } } #endif v4l2_ctrl_handler_setup(&dev->ctrl_hdl_vid_cap); v4l2_ctrl_handler_setup(&dev->ctrl_hdl_vid_out); v4l2_ctrl_handler_setup(&dev->ctrl_hdl_vbi_cap); v4l2_ctrl_handler_setup(&dev->ctrl_hdl_vbi_out); v4l2_ctrl_handler_setup(&dev->ctrl_hdl_radio_rx); v4l2_ctrl_handler_setup(&dev->ctrl_hdl_radio_tx); v4l2_ctrl_handler_setup(&dev->ctrl_hdl_sdr_cap); v4l2_ctrl_handler_setup(&dev->ctrl_hdl_meta_cap); v4l2_ctrl_handler_setup(&dev->ctrl_hdl_meta_out); v4l2_ctrl_handler_setup(&dev->ctrl_hdl_touch_cap); /* finally start creating the device nodes */ ret = vivid_create_devnodes(pdev, dev, inst, cec_tx_bus_cnt, tvnorms_cap, tvnorms_out, in_type_counter, out_type_counter); if (ret) goto unreg_dev; /* Now that everything is fine, let's add it to device list */ vivid_devs[inst] = dev; return 0; unreg_dev: vb2_video_unregister_device(&dev->touch_cap_dev); vb2_video_unregister_device(&dev->meta_out_dev); vb2_video_unregister_device(&dev->meta_cap_dev); video_unregister_device(&dev->radio_tx_dev); video_unregister_device(&dev->radio_rx_dev); vb2_video_unregister_device(&dev->sdr_cap_dev); vb2_video_unregister_device(&dev->vbi_out_dev); vb2_video_unregister_device(&dev->vbi_cap_dev); vb2_video_unregister_device(&dev->vid_out_dev); vb2_video_unregister_device(&dev->vid_cap_dev); cec_unregister_adapter(dev->cec_rx_adap); for (i = 0; i < MAX_OUTPUTS; i++) cec_unregister_adapter(dev->cec_tx_adap[i]); if (dev->kthread_cec) kthread_stop(dev->kthread_cec); free_dev: v4l2_device_put(&dev->v4l2_dev); return ret; } /* This routine allocates from 1 to n_devs virtual drivers. The real maximum number of virtual drivers will depend on how many drivers will succeed. This is limited to the maximum number of devices that videodev supports, which is equal to VIDEO_NUM_DEVICES. */ static int vivid_probe(struct platform_device *pdev) { const struct font_desc *font = find_font("VGA8x16"); int ret = 0, i; if (font == NULL) { pr_err("vivid: could not find font\n"); return -ENODEV; } tpg_set_font(font->data); n_devs = clamp_t(unsigned, n_devs, 1, VIVID_MAX_DEVS); for (i = 0; i < n_devs; i++) { ret = vivid_create_instance(pdev, i); if (ret) { /* If some instantiations succeeded, keep driver */ if (i) ret = 0; break; } } if (ret < 0) { pr_err("vivid: error %d while loading driver\n", ret); return ret; } /* n_devs will reflect the actual number of allocated devices */ n_devs = i; return ret; } static void vivid_remove(struct platform_device *pdev) { struct vivid_dev *dev; unsigned int i, j; for (i = 0; i < n_devs; i++) { dev = vivid_devs[i]; if (!dev) continue; if (dev->disconnect_error) vivid_reconnect(dev); #ifdef CONFIG_MEDIA_CONTROLLER media_device_unregister(&dev->mdev); #endif if (dev->has_vid_cap) { v4l2_info(&dev->v4l2_dev, "unregistering %s\n", video_device_node_name(&dev->vid_cap_dev)); vb2_video_unregister_device(&dev->vid_cap_dev); } if (dev->has_vid_out) { v4l2_info(&dev->v4l2_dev, "unregistering %s\n", video_device_node_name(&dev->vid_out_dev)); vb2_video_unregister_device(&dev->vid_out_dev); } if (dev->has_vbi_cap) { v4l2_info(&dev->v4l2_dev, "unregistering %s\n", video_device_node_name(&dev->vbi_cap_dev)); vb2_video_unregister_device(&dev->vbi_cap_dev); } if (dev->has_vbi_out) { v4l2_info(&dev->v4l2_dev, "unregistering %s\n", video_device_node_name(&dev->vbi_out_dev)); vb2_video_unregister_device(&dev->vbi_out_dev); } if (dev->has_sdr_cap) { v4l2_info(&dev->v4l2_dev, "unregistering %s\n", video_device_node_name(&dev->sdr_cap_dev)); vb2_video_unregister_device(&dev->sdr_cap_dev); } if (dev->has_radio_rx) { v4l2_info(&dev->v4l2_dev, "unregistering %s\n", video_device_node_name(&dev->radio_rx_dev)); video_unregister_device(&dev->radio_rx_dev); } if (dev->has_radio_tx) { v4l2_info(&dev->v4l2_dev, "unregistering %s\n", video_device_node_name(&dev->radio_tx_dev)); video_unregister_device(&dev->radio_tx_dev); } if (dev->has_fb) { v4l2_info(&dev->v4l2_dev, "unregistering fb%d\n", dev->fb_info.node); unregister_framebuffer(&dev->fb_info); vivid_fb_release_buffers(dev); } if (dev->has_meta_cap) { v4l2_info(&dev->v4l2_dev, "unregistering %s\n", video_device_node_name(&dev->meta_cap_dev)); vb2_video_unregister_device(&dev->meta_cap_dev); } if (dev->has_meta_out) { v4l2_info(&dev->v4l2_dev, "unregistering %s\n", video_device_node_name(&dev->meta_out_dev)); vb2_video_unregister_device(&dev->meta_out_dev); } if (dev->has_touch_cap) { v4l2_info(&dev->v4l2_dev, "unregistering %s\n", video_device_node_name(&dev->touch_cap_dev)); vb2_video_unregister_device(&dev->touch_cap_dev); } cec_unregister_adapter(dev->cec_rx_adap); for (j = 0; j < MAX_OUTPUTS; j++) cec_unregister_adapter(dev->cec_tx_adap[j]); if (dev->kthread_cec) kthread_stop(dev->kthread_cec); v4l2_device_put(&dev->v4l2_dev); vivid_devs[i] = NULL; } } static void vivid_pdev_release(struct device *dev) { } static struct platform_device vivid_pdev = { .name = "vivid", .dev.release = vivid_pdev_release, }; static struct platform_driver vivid_pdrv = { .probe = vivid_probe, .remove_new = vivid_remove, .driver = { .name = "vivid", }, }; static int __init vivid_init(void) { int ret; ret = platform_device_register(&vivid_pdev); if (ret) return ret; ret = platform_driver_register(&vivid_pdrv); if (ret) platform_device_unregister(&vivid_pdev); return ret; } static void __exit vivid_exit(void) { platform_driver_unregister(&vivid_pdrv); platform_device_unregister(&vivid_pdev); } module_init(vivid_init); module_exit(vivid_exit);
linux-master
drivers/media/test-drivers/vivid/vivid-core.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * vimc-scaler.c Virtual Media Controller Driver * * Copyright (C) 2015-2017 Helen Koike <[email protected]> */ #include <linux/moduleparam.h> #include <linux/string.h> #include <linux/vmalloc.h> #include <linux/v4l2-mediabus.h> #include <media/v4l2-rect.h> #include <media/v4l2-subdev.h> #include "vimc-common.h" /* Pad identifier */ enum vic_sca_pad { VIMC_SCALER_SINK = 0, VIMC_SCALER_SRC = 1, }; #define VIMC_SCALER_FMT_WIDTH_DEFAULT 640 #define VIMC_SCALER_FMT_HEIGHT_DEFAULT 480 struct vimc_scaler_device { struct vimc_ent_device ved; struct v4l2_subdev sd; struct v4l2_rect crop_rect; /* Frame format for both sink and src pad */ struct v4l2_mbus_framefmt fmt[2]; /* Values calculated when the stream starts */ u8 *src_frame; unsigned int bpp; struct media_pad pads[2]; }; static const struct v4l2_mbus_framefmt fmt_default = { .width = VIMC_SCALER_FMT_WIDTH_DEFAULT, .height = VIMC_SCALER_FMT_HEIGHT_DEFAULT, .code = MEDIA_BUS_FMT_RGB888_1X24, .field = V4L2_FIELD_NONE, .colorspace = V4L2_COLORSPACE_SRGB, }; static const struct v4l2_rect crop_rect_default = { .width = VIMC_SCALER_FMT_WIDTH_DEFAULT, .height = VIMC_SCALER_FMT_HEIGHT_DEFAULT, .top = 0, .left = 0, }; static const struct v4l2_rect crop_rect_min = { .width = VIMC_FRAME_MIN_WIDTH, .height = VIMC_FRAME_MIN_HEIGHT, .top = 0, .left = 0, }; static struct v4l2_rect vimc_scaler_get_crop_bound_sink(const struct v4l2_mbus_framefmt *sink_fmt) { /* Get the crop bounds to clamp the crop rectangle correctly */ struct v4l2_rect r = { .left = 0, .top = 0, .width = sink_fmt->width, .height = sink_fmt->height, }; return r; } static int vimc_scaler_init_cfg(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state) { struct v4l2_mbus_framefmt *mf; struct v4l2_rect *r; unsigned int i; for (i = 0; i < sd->entity.num_pads; i++) { mf = v4l2_subdev_get_try_format(sd, sd_state, i); *mf = fmt_default; } r = v4l2_subdev_get_try_crop(sd, sd_state, VIMC_SCALER_SINK); *r = crop_rect_default; return 0; } static int vimc_scaler_enum_mbus_code(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_mbus_code_enum *code) { u32 mbus_code = vimc_mbus_code_by_index(code->index); const struct vimc_pix_map *vpix; if (!mbus_code) return -EINVAL; vpix = vimc_pix_map_by_code(mbus_code); /* We don't support bayer format */ if (!vpix || vpix->bayer) return -EINVAL; code->code = mbus_code; return 0; } static int vimc_scaler_enum_frame_size(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_frame_size_enum *fse) { const struct vimc_pix_map *vpix; if (fse->index) return -EINVAL; /* Only accept code in the pix map table in non bayer format */ vpix = vimc_pix_map_by_code(fse->code); if (!vpix || vpix->bayer) return -EINVAL; fse->min_width = VIMC_FRAME_MIN_WIDTH; fse->min_height = VIMC_FRAME_MIN_HEIGHT; fse->max_width = VIMC_FRAME_MAX_WIDTH; fse->max_height = VIMC_FRAME_MAX_HEIGHT; return 0; } static struct v4l2_mbus_framefmt * vimc_scaler_pad_format(struct vimc_scaler_device *vscaler, struct v4l2_subdev_state *sd_state, u32 pad, enum v4l2_subdev_format_whence which) { if (which == V4L2_SUBDEV_FORMAT_TRY) return v4l2_subdev_get_try_format(&vscaler->sd, sd_state, pad); else return &vscaler->fmt[pad]; } static struct v4l2_rect * vimc_scaler_pad_crop(struct vimc_scaler_device *vscaler, struct v4l2_subdev_state *sd_state, enum v4l2_subdev_format_whence which) { if (which == V4L2_SUBDEV_FORMAT_TRY) return v4l2_subdev_get_try_crop(&vscaler->sd, sd_state, VIMC_SCALER_SINK); else return &vscaler->crop_rect; } static int vimc_scaler_get_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *format) { struct vimc_scaler_device *vscaler = v4l2_get_subdevdata(sd); format->format = *vimc_scaler_pad_format(vscaler, sd_state, format->pad, format->which); return 0; } static int vimc_scaler_set_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *format) { struct vimc_scaler_device *vscaler = v4l2_get_subdevdata(sd); struct v4l2_mbus_framefmt *fmt; /* Do not change the active format while stream is on */ if (format->which == V4L2_SUBDEV_FORMAT_ACTIVE && vscaler->src_frame) return -EBUSY; fmt = vimc_scaler_pad_format(vscaler, sd_state, format->pad, format->which); /* * The media bus code and colorspace can only be changed on the sink * pad, the source pad only follows. */ if (format->pad == VIMC_SCALER_SINK) { const struct vimc_pix_map *vpix; /* Only accept code in the pix map table in non bayer format. */ vpix = vimc_pix_map_by_code(format->format.code); if (vpix && !vpix->bayer) fmt->code = format->format.code; else fmt->code = fmt_default.code; /* Clamp the colorspace to valid values. */ fmt->colorspace = format->format.colorspace; fmt->ycbcr_enc = format->format.ycbcr_enc; fmt->quantization = format->format.quantization; fmt->xfer_func = format->format.xfer_func; vimc_colorimetry_clamp(fmt); } /* Clamp and align the width and height */ fmt->width = clamp_t(u32, format->format.width, VIMC_FRAME_MIN_WIDTH, VIMC_FRAME_MAX_WIDTH) & ~1; fmt->height = clamp_t(u32, format->format.height, VIMC_FRAME_MIN_HEIGHT, VIMC_FRAME_MAX_HEIGHT) & ~1; /* * Propagate the sink pad format to the crop rectangle and the source * pad. */ if (format->pad == VIMC_SCALER_SINK) { struct v4l2_mbus_framefmt *src_fmt; struct v4l2_rect *crop; crop = vimc_scaler_pad_crop(vscaler, sd_state, format->which); crop->width = fmt->width; crop->height = fmt->height; crop->top = 0; crop->left = 0; src_fmt = vimc_scaler_pad_format(vscaler, sd_state, VIMC_SCALER_SRC, format->which); *src_fmt = *fmt; } format->format = *fmt; return 0; } static int vimc_scaler_get_selection(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_selection *sel) { struct vimc_scaler_device *vscaler = v4l2_get_subdevdata(sd); struct v4l2_mbus_framefmt *sink_fmt; if (VIMC_IS_SRC(sel->pad)) return -EINVAL; switch (sel->target) { case V4L2_SEL_TGT_CROP: sel->r = *vimc_scaler_pad_crop(vscaler, sd_state, sel->which); break; case V4L2_SEL_TGT_CROP_BOUNDS: sink_fmt = vimc_scaler_pad_format(vscaler, sd_state, VIMC_SCALER_SINK, sel->which); sel->r = vimc_scaler_get_crop_bound_sink(sink_fmt); break; default: return -EINVAL; } return 0; } static void vimc_scaler_adjust_sink_crop(struct v4l2_rect *r, const struct v4l2_mbus_framefmt *sink_fmt) { const struct v4l2_rect sink_rect = vimc_scaler_get_crop_bound_sink(sink_fmt); /* Disallow rectangles smaller than the minimal one. */ v4l2_rect_set_min_size(r, &crop_rect_min); v4l2_rect_map_inside(r, &sink_rect); } static int vimc_scaler_set_selection(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_selection *sel) { struct vimc_scaler_device *vscaler = v4l2_get_subdevdata(sd); struct v4l2_mbus_framefmt *sink_fmt; struct v4l2_rect *crop_rect; /* Only support setting the crop of the sink pad */ if (VIMC_IS_SRC(sel->pad) || sel->target != V4L2_SEL_TGT_CROP) return -EINVAL; if (sel->which == V4L2_SUBDEV_FORMAT_ACTIVE && vscaler->src_frame) return -EBUSY; crop_rect = vimc_scaler_pad_crop(vscaler, sd_state, sel->which); sink_fmt = vimc_scaler_pad_format(vscaler, sd_state, VIMC_SCALER_SINK, sel->which); vimc_scaler_adjust_sink_crop(&sel->r, sink_fmt); *crop_rect = sel->r; return 0; } static const struct v4l2_subdev_pad_ops vimc_scaler_pad_ops = { .init_cfg = vimc_scaler_init_cfg, .enum_mbus_code = vimc_scaler_enum_mbus_code, .enum_frame_size = vimc_scaler_enum_frame_size, .get_fmt = vimc_scaler_get_fmt, .set_fmt = vimc_scaler_set_fmt, .get_selection = vimc_scaler_get_selection, .set_selection = vimc_scaler_set_selection, }; static int vimc_scaler_s_stream(struct v4l2_subdev *sd, int enable) { struct vimc_scaler_device *vscaler = v4l2_get_subdevdata(sd); if (enable) { const struct vimc_pix_map *vpix; unsigned int frame_size; if (vscaler->src_frame) return 0; /* Save the bytes per pixel of the sink */ vpix = vimc_pix_map_by_code(vscaler->fmt[VIMC_SCALER_SINK].code); vscaler->bpp = vpix->bpp; /* Calculate the frame size of the source pad */ frame_size = vscaler->fmt[VIMC_SCALER_SRC].width * vscaler->fmt[VIMC_SCALER_SRC].height * vscaler->bpp; /* Allocate the frame buffer. Use vmalloc to be able to * allocate a large amount of memory */ vscaler->src_frame = vmalloc(frame_size); if (!vscaler->src_frame) return -ENOMEM; } else { if (!vscaler->src_frame) return 0; vfree(vscaler->src_frame); vscaler->src_frame = NULL; } return 0; } static const struct v4l2_subdev_video_ops vimc_scaler_video_ops = { .s_stream = vimc_scaler_s_stream, }; static const struct v4l2_subdev_ops vimc_scaler_ops = { .pad = &vimc_scaler_pad_ops, .video = &vimc_scaler_video_ops, }; static void vimc_scaler_fill_src_frame(const struct vimc_scaler_device *const vscaler, const u8 *const sink_frame) { const struct v4l2_mbus_framefmt *src_fmt = &vscaler->fmt[VIMC_SCALER_SRC]; const struct v4l2_rect *r = &vscaler->crop_rect; unsigned int snk_width = vscaler->fmt[VIMC_SCALER_SINK].width; unsigned int src_x, src_y; u8 *walker = vscaler->src_frame; /* Set each pixel at the src_frame to its sink_frame equivalent */ for (src_y = 0; src_y < src_fmt->height; src_y++) { unsigned int snk_y, y_offset; snk_y = (src_y * r->height) / src_fmt->height + r->top; y_offset = snk_y * snk_width * vscaler->bpp; for (src_x = 0; src_x < src_fmt->width; src_x++) { unsigned int snk_x, x_offset, index; snk_x = (src_x * r->width) / src_fmt->width + r->left; x_offset = snk_x * vscaler->bpp; index = y_offset + x_offset; memcpy(walker, &sink_frame[index], vscaler->bpp); walker += vscaler->bpp; } } } static void *vimc_scaler_process_frame(struct vimc_ent_device *ved, const void *sink_frame) { struct vimc_scaler_device *vscaler = container_of(ved, struct vimc_scaler_device, ved); /* If the stream in this node is not active, just return */ if (!vscaler->src_frame) return ERR_PTR(-EINVAL); vimc_scaler_fill_src_frame(vscaler, sink_frame); return vscaler->src_frame; }; static void vimc_scaler_release(struct vimc_ent_device *ved) { struct vimc_scaler_device *vscaler = container_of(ved, struct vimc_scaler_device, ved); media_entity_cleanup(vscaler->ved.ent); kfree(vscaler); } static struct vimc_ent_device *vimc_scaler_add(struct vimc_device *vimc, const char *vcfg_name) { struct v4l2_device *v4l2_dev = &vimc->v4l2_dev; struct vimc_scaler_device *vscaler; int ret; /* Allocate the vscaler struct */ vscaler = kzalloc(sizeof(*vscaler), GFP_KERNEL); if (!vscaler) return ERR_PTR(-ENOMEM); /* Initialize ved and sd */ vscaler->pads[VIMC_SCALER_SINK].flags = MEDIA_PAD_FL_SINK; vscaler->pads[VIMC_SCALER_SRC].flags = MEDIA_PAD_FL_SOURCE; ret = vimc_ent_sd_register(&vscaler->ved, &vscaler->sd, v4l2_dev, vcfg_name, MEDIA_ENT_F_PROC_VIDEO_SCALER, 2, vscaler->pads, &vimc_scaler_ops); if (ret) { kfree(vscaler); return ERR_PTR(ret); } vscaler->ved.process_frame = vimc_scaler_process_frame; vscaler->ved.dev = vimc->mdev.dev; /* Initialize the frame format */ vscaler->fmt[VIMC_SCALER_SINK] = fmt_default; vscaler->fmt[VIMC_SCALER_SRC] = fmt_default; /* Initialize the crop selection */ vscaler->crop_rect = crop_rect_default; return &vscaler->ved; } struct vimc_ent_type vimc_scaler_type = { .add = vimc_scaler_add, .release = vimc_scaler_release };
linux-master
drivers/media/test-drivers/vimc/vimc-scaler.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * vimc-lens.c Virtual Media Controller Driver * Copyright (C) 2022 Google, Inc * Author: [email protected] (Yunke Cao) */ #include <media/v4l2-ctrls.h> #include <media/v4l2-event.h> #include <media/v4l2-subdev.h> #include "vimc-common.h" #define VIMC_LENS_MAX_FOCUS_POS 1023 #define VIMC_LENS_MAX_FOCUS_STEP 1 struct vimc_lens_device { struct vimc_ent_device ved; struct v4l2_subdev sd; struct v4l2_ctrl_handler hdl; u32 focus_absolute; }; static const struct v4l2_subdev_core_ops vimc_lens_core_ops = { .log_status = v4l2_ctrl_subdev_log_status, .subscribe_event = v4l2_ctrl_subdev_subscribe_event, .unsubscribe_event = v4l2_event_subdev_unsubscribe, }; static const struct v4l2_subdev_ops vimc_lens_ops = { .core = &vimc_lens_core_ops }; static int vimc_lens_s_ctrl(struct v4l2_ctrl *ctrl) { struct vimc_lens_device *vlens = container_of(ctrl->handler, struct vimc_lens_device, hdl); if (ctrl->id == V4L2_CID_FOCUS_ABSOLUTE) { vlens->focus_absolute = ctrl->val; return 0; } return -EINVAL; } static const struct v4l2_ctrl_ops vimc_lens_ctrl_ops = { .s_ctrl = vimc_lens_s_ctrl, }; static struct vimc_ent_device *vimc_lens_add(struct vimc_device *vimc, const char *vcfg_name) { struct v4l2_device *v4l2_dev = &vimc->v4l2_dev; struct vimc_lens_device *vlens; int ret; /* Allocate the vlens struct */ vlens = kzalloc(sizeof(*vlens), GFP_KERNEL); if (!vlens) return ERR_PTR(-ENOMEM); v4l2_ctrl_handler_init(&vlens->hdl, 1); v4l2_ctrl_new_std(&vlens->hdl, &vimc_lens_ctrl_ops, V4L2_CID_FOCUS_ABSOLUTE, 0, VIMC_LENS_MAX_FOCUS_POS, VIMC_LENS_MAX_FOCUS_STEP, 0); vlens->sd.ctrl_handler = &vlens->hdl; if (vlens->hdl.error) { ret = vlens->hdl.error; goto err_free_vlens; } vlens->ved.dev = vimc->mdev.dev; ret = vimc_ent_sd_register(&vlens->ved, &vlens->sd, v4l2_dev, vcfg_name, MEDIA_ENT_F_LENS, 0, NULL, &vimc_lens_ops); if (ret) goto err_free_hdl; return &vlens->ved; err_free_hdl: v4l2_ctrl_handler_free(&vlens->hdl); err_free_vlens: kfree(vlens); return ERR_PTR(ret); } static void vimc_lens_release(struct vimc_ent_device *ved) { struct vimc_lens_device *vlens = container_of(ved, struct vimc_lens_device, ved); v4l2_ctrl_handler_free(&vlens->hdl); media_entity_cleanup(vlens->ved.ent); kfree(vlens); } struct vimc_ent_type vimc_lens_type = { .add = vimc_lens_add, .release = vimc_lens_release };
linux-master
drivers/media/test-drivers/vimc/vimc-lens.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * vimc-core.c Virtual Media Controller Driver * * Copyright (C) 2015-2017 Helen Koike <[email protected]> */ #include <linux/dma-mapping.h> #include <linux/font.h> #include <linux/init.h> #include <linux/module.h> #include <linux/platform_device.h> #include <media/media-device.h> #include <media/tpg/v4l2-tpg.h> #include <media/v4l2-device.h> #include "vimc-common.h" unsigned int vimc_allocator; module_param_named(allocator, vimc_allocator, uint, 0444); MODULE_PARM_DESC(allocator, " memory allocator selection, default is 0.\n" "\t\t 0 == vmalloc\n" "\t\t 1 == dma-contig"); #define VIMC_MDEV_MODEL_NAME "VIMC MDEV" #define VIMC_DATA_LINK(src, srcpad, sink, sinkpad, link_flags) { \ .src_ent = src, \ .src_pad = srcpad, \ .sink_ent = sink, \ .sink_pad = sinkpad, \ .flags = link_flags, \ } #define VIMC_ANCILLARY_LINK(primary, ancillary) { \ .primary_ent = primary, \ .ancillary_ent = ancillary \ } /* Structure which describes data links between entities */ struct vimc_data_link { unsigned int src_ent; u16 src_pad; unsigned int sink_ent; u16 sink_pad; u32 flags; }; /* Enum to improve clarity when defining vimc_data_links */ enum vimc_data_link_ents { SENSOR_A, SENSOR_B, DEBAYER_A, DEBAYER_B, RAW_CAPTURE_0, RAW_CAPTURE_1, RGB_YUV_INPUT, SCALER, RGB_YUV_CAPTURE, LENS_A, LENS_B, }; /* Structure which describes ancillary links between entities */ struct vimc_ancillary_link { unsigned int primary_ent; unsigned int ancillary_ent; }; /* Structure which describes the whole topology */ struct vimc_pipeline_config { const struct vimc_ent_config *ents; size_t num_ents; const struct vimc_data_link *data_links; size_t num_data_links; const struct vimc_ancillary_link *ancillary_links; size_t num_ancillary_links; }; /* -------------------------------------------------------------------------- * Topology Configuration */ static struct vimc_ent_config ent_config[] = { [SENSOR_A] = { .name = "Sensor A", .type = &vimc_sensor_type }, [SENSOR_B] = { .name = "Sensor B", .type = &vimc_sensor_type }, [DEBAYER_A] = { .name = "Debayer A", .type = &vimc_debayer_type }, [DEBAYER_B] = { .name = "Debayer B", .type = &vimc_debayer_type }, [RAW_CAPTURE_0] = { .name = "Raw Capture 0", .type = &vimc_capture_type }, [RAW_CAPTURE_1] = { .name = "Raw Capture 1", .type = &vimc_capture_type }, [RGB_YUV_INPUT] = { /* TODO: change this to vimc-input when it is implemented */ .name = "RGB/YUV Input", .type = &vimc_sensor_type }, [SCALER] = { .name = "Scaler", .type = &vimc_scaler_type }, [RGB_YUV_CAPTURE] = { .name = "RGB/YUV Capture", .type = &vimc_capture_type }, [LENS_A] = { .name = "Lens A", .type = &vimc_lens_type }, [LENS_B] = { .name = "Lens B", .type = &vimc_lens_type }, }; static const struct vimc_data_link data_links[] = { /* Link: Sensor A (Pad 0)->(Pad 0) Debayer A */ VIMC_DATA_LINK(SENSOR_A, 0, DEBAYER_A, 0, MEDIA_LNK_FL_ENABLED | MEDIA_LNK_FL_IMMUTABLE), /* Link: Sensor A (Pad 0)->(Pad 0) Raw Capture 0 */ VIMC_DATA_LINK(SENSOR_A, 0, RAW_CAPTURE_0, 0, MEDIA_LNK_FL_ENABLED | MEDIA_LNK_FL_IMMUTABLE), /* Link: Sensor B (Pad 0)->(Pad 0) Debayer B */ VIMC_DATA_LINK(SENSOR_B, 0, DEBAYER_B, 0, MEDIA_LNK_FL_ENABLED | MEDIA_LNK_FL_IMMUTABLE), /* Link: Sensor B (Pad 0)->(Pad 0) Raw Capture 1 */ VIMC_DATA_LINK(SENSOR_B, 0, RAW_CAPTURE_1, 0, MEDIA_LNK_FL_ENABLED | MEDIA_LNK_FL_IMMUTABLE), /* Link: Debayer A (Pad 1)->(Pad 0) Scaler */ VIMC_DATA_LINK(DEBAYER_A, 1, SCALER, 0, MEDIA_LNK_FL_ENABLED), /* Link: Debayer B (Pad 1)->(Pad 0) Scaler */ VIMC_DATA_LINK(DEBAYER_B, 1, SCALER, 0, 0), /* Link: RGB/YUV Input (Pad 0)->(Pad 0) Scaler */ VIMC_DATA_LINK(RGB_YUV_INPUT, 0, SCALER, 0, 0), /* Link: Scaler (Pad 1)->(Pad 0) RGB/YUV Capture */ VIMC_DATA_LINK(SCALER, 1, RGB_YUV_CAPTURE, 0, MEDIA_LNK_FL_ENABLED | MEDIA_LNK_FL_IMMUTABLE), }; static const struct vimc_ancillary_link ancillary_links[] = { /* Link: Sensor A -> Lens A */ VIMC_ANCILLARY_LINK(0, 9), /* Link: Sensor B -> Lens B */ VIMC_ANCILLARY_LINK(1, 10), }; static struct vimc_pipeline_config pipe_cfg = { .ents = ent_config, .num_ents = ARRAY_SIZE(ent_config), .data_links = data_links, .num_data_links = ARRAY_SIZE(data_links), .ancillary_links = ancillary_links, .num_ancillary_links = ARRAY_SIZE(ancillary_links), }; /* -------------------------------------------------------------------------- */ static void vimc_rm_links(struct vimc_device *vimc) { unsigned int i; for (i = 0; i < vimc->pipe_cfg->num_ents; i++) media_entity_remove_links(vimc->ent_devs[i]->ent); } static int vimc_create_links(struct vimc_device *vimc) { unsigned int i; int ret; /* Initialize the links between entities */ for (i = 0; i < vimc->pipe_cfg->num_data_links; i++) { const struct vimc_data_link *link = &vimc->pipe_cfg->data_links[i]; struct vimc_ent_device *ved_src = vimc->ent_devs[link->src_ent]; struct vimc_ent_device *ved_sink = vimc->ent_devs[link->sink_ent]; ret = media_create_pad_link(ved_src->ent, link->src_pad, ved_sink->ent, link->sink_pad, link->flags); if (ret) goto err_rm_links; } for (i = 0; i < vimc->pipe_cfg->num_ancillary_links; i++) { const struct vimc_ancillary_link *link = &vimc->pipe_cfg->ancillary_links[i]; struct vimc_ent_device *ved_primary = vimc->ent_devs[link->primary_ent]; struct vimc_ent_device *ved_ancillary = vimc->ent_devs[link->ancillary_ent]; struct media_link *ret_link = media_create_ancillary_link(ved_primary->ent, ved_ancillary->ent); if (IS_ERR(ret_link)) { ret = PTR_ERR(ret_link); goto err_rm_links; } } return 0; err_rm_links: vimc_rm_links(vimc); return ret; } static void vimc_release_subdevs(struct vimc_device *vimc) { unsigned int i; for (i = 0; i < vimc->pipe_cfg->num_ents; i++) if (vimc->ent_devs[i]) vimc->pipe_cfg->ents[i].type->release(vimc->ent_devs[i]); } static void vimc_unregister_subdevs(struct vimc_device *vimc) { unsigned int i; for (i = 0; i < vimc->pipe_cfg->num_ents; i++) if (vimc->ent_devs[i] && vimc->pipe_cfg->ents[i].type->unregister) vimc->pipe_cfg->ents[i].type->unregister(vimc->ent_devs[i]); } static int vimc_add_subdevs(struct vimc_device *vimc) { unsigned int i; for (i = 0; i < vimc->pipe_cfg->num_ents; i++) { dev_dbg(vimc->mdev.dev, "new entity for %s\n", vimc->pipe_cfg->ents[i].name); vimc->ent_devs[i] = vimc->pipe_cfg->ents[i].type->add(vimc, vimc->pipe_cfg->ents[i].name); if (IS_ERR(vimc->ent_devs[i])) { int err = PTR_ERR(vimc->ent_devs[i]); dev_err(vimc->mdev.dev, "adding entity %s failed (%d)\n", vimc->pipe_cfg->ents[i].name, err); vimc->ent_devs[i] = NULL; vimc_unregister_subdevs(vimc); vimc_release_subdevs(vimc); return err; } } return 0; } static void vimc_v4l2_dev_release(struct v4l2_device *v4l2_dev) { struct vimc_device *vimc = container_of(v4l2_dev, struct vimc_device, v4l2_dev); vimc_release_subdevs(vimc); media_device_cleanup(&vimc->mdev); kfree(vimc->ent_devs); kfree(vimc); } static int vimc_register_devices(struct vimc_device *vimc) { int ret; /* Register the v4l2 struct */ ret = v4l2_device_register(vimc->mdev.dev, &vimc->v4l2_dev); if (ret) { dev_err(vimc->mdev.dev, "v4l2 device register failed (err=%d)\n", ret); return ret; } /* allocate ent_devs */ vimc->ent_devs = kcalloc(vimc->pipe_cfg->num_ents, sizeof(*vimc->ent_devs), GFP_KERNEL); if (!vimc->ent_devs) { ret = -ENOMEM; goto err_v4l2_unregister; } /* Invoke entity config hooks to initialize and register subdevs */ ret = vimc_add_subdevs(vimc); if (ret) goto err_free_ent_devs; /* Initialize links */ ret = vimc_create_links(vimc); if (ret) goto err_rm_subdevs; /* Register the media device */ ret = media_device_register(&vimc->mdev); if (ret) { dev_err(vimc->mdev.dev, "media device register failed (err=%d)\n", ret); goto err_rm_subdevs; } /* Expose all subdev's nodes*/ ret = v4l2_device_register_subdev_nodes(&vimc->v4l2_dev); if (ret) { dev_err(vimc->mdev.dev, "vimc subdev nodes registration failed (err=%d)\n", ret); goto err_mdev_unregister; } return 0; err_mdev_unregister: media_device_unregister(&vimc->mdev); err_rm_subdevs: vimc_unregister_subdevs(vimc); vimc_release_subdevs(vimc); err_free_ent_devs: kfree(vimc->ent_devs); err_v4l2_unregister: v4l2_device_unregister(&vimc->v4l2_dev); return ret; } static int vimc_probe(struct platform_device *pdev) { const struct font_desc *font = find_font("VGA8x16"); struct vimc_device *vimc; int ret; dev_dbg(&pdev->dev, "probe"); if (!font) { dev_err(&pdev->dev, "could not find font\n"); return -ENODEV; } tpg_set_font(font->data); if (vimc_allocator == VIMC_ALLOCATOR_DMA_CONTIG) dma_coerce_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32)); vimc = kzalloc(sizeof(*vimc), GFP_KERNEL); if (!vimc) return -ENOMEM; vimc->pipe_cfg = &pipe_cfg; /* Link the media device within the v4l2_device */ vimc->v4l2_dev.mdev = &vimc->mdev; /* Initialize media device */ strscpy(vimc->mdev.model, VIMC_MDEV_MODEL_NAME, sizeof(vimc->mdev.model)); snprintf(vimc->mdev.bus_info, sizeof(vimc->mdev.bus_info), "platform:%s", VIMC_PDEV_NAME); vimc->mdev.dev = &pdev->dev; media_device_init(&vimc->mdev); ret = vimc_register_devices(vimc); if (ret) { media_device_cleanup(&vimc->mdev); kfree(vimc); return ret; } /* * the release cb is set only after successful registration. * if the registration fails, we release directly from probe */ vimc->v4l2_dev.release = vimc_v4l2_dev_release; platform_set_drvdata(pdev, vimc); return 0; } static void vimc_remove(struct platform_device *pdev) { struct vimc_device *vimc = platform_get_drvdata(pdev); dev_dbg(&pdev->dev, "remove"); vimc_unregister_subdevs(vimc); media_device_unregister(&vimc->mdev); v4l2_device_unregister(&vimc->v4l2_dev); v4l2_device_put(&vimc->v4l2_dev); } static void vimc_dev_release(struct device *dev) { } static struct platform_device vimc_pdev = { .name = VIMC_PDEV_NAME, .dev.release = vimc_dev_release, }; static struct platform_driver vimc_pdrv = { .probe = vimc_probe, .remove_new = vimc_remove, .driver = { .name = VIMC_PDEV_NAME, }, }; static int __init vimc_init(void) { int ret; ret = platform_device_register(&vimc_pdev); if (ret) { dev_err(&vimc_pdev.dev, "platform device registration failed (err=%d)\n", ret); return ret; } ret = platform_driver_register(&vimc_pdrv); if (ret) { dev_err(&vimc_pdev.dev, "platform driver registration failed (err=%d)\n", ret); platform_device_unregister(&vimc_pdev); return ret; } return 0; } static void __exit vimc_exit(void) { platform_driver_unregister(&vimc_pdrv); platform_device_unregister(&vimc_pdev); } module_init(vimc_init); module_exit(vimc_exit); MODULE_DESCRIPTION("Virtual Media Controller Driver (VIMC)"); MODULE_AUTHOR("Helen Fornazier <[email protected]>"); MODULE_LICENSE("GPL");
linux-master
drivers/media/test-drivers/vimc/vimc-core.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * vimc-sensor.c Virtual Media Controller Driver * * Copyright (C) 2015-2017 Helen Koike <[email protected]> */ #include <linux/v4l2-mediabus.h> #include <linux/vmalloc.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-event.h> #include <media/v4l2-subdev.h> #include <media/tpg/v4l2-tpg.h> #include "vimc-common.h" enum vimc_sensor_osd_mode { VIMC_SENSOR_OSD_SHOW_ALL = 0, VIMC_SENSOR_OSD_SHOW_COUNTERS = 1, VIMC_SENSOR_OSD_SHOW_NONE = 2 }; struct vimc_sensor_device { struct vimc_ent_device ved; struct v4l2_subdev sd; struct tpg_data tpg; u8 *frame; enum vimc_sensor_osd_mode osd_value; u64 start_stream_ts; /* The active format */ struct v4l2_mbus_framefmt mbus_format; struct v4l2_ctrl_handler hdl; struct media_pad pad; }; static const struct v4l2_mbus_framefmt fmt_default = { .width = 640, .height = 480, .code = MEDIA_BUS_FMT_RGB888_1X24, .field = V4L2_FIELD_NONE, .colorspace = V4L2_COLORSPACE_SRGB, }; static int vimc_sensor_init_cfg(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state) { unsigned int i; for (i = 0; i < sd->entity.num_pads; i++) { struct v4l2_mbus_framefmt *mf; mf = v4l2_subdev_get_try_format(sd, sd_state, i); *mf = fmt_default; } return 0; } static int vimc_sensor_enum_mbus_code(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_mbus_code_enum *code) { u32 mbus_code = vimc_mbus_code_by_index(code->index); if (!mbus_code) return -EINVAL; code->code = mbus_code; return 0; } static int vimc_sensor_enum_frame_size(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_frame_size_enum *fse) { const struct vimc_pix_map *vpix; if (fse->index) return -EINVAL; /* Only accept code in the pix map table */ vpix = vimc_pix_map_by_code(fse->code); if (!vpix) return -EINVAL; fse->min_width = VIMC_FRAME_MIN_WIDTH; fse->max_width = VIMC_FRAME_MAX_WIDTH; fse->min_height = VIMC_FRAME_MIN_HEIGHT; fse->max_height = VIMC_FRAME_MAX_HEIGHT; return 0; } static int vimc_sensor_get_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *fmt) { struct vimc_sensor_device *vsensor = container_of(sd, struct vimc_sensor_device, sd); fmt->format = fmt->which == V4L2_SUBDEV_FORMAT_TRY ? *v4l2_subdev_get_try_format(sd, sd_state, fmt->pad) : vsensor->mbus_format; return 0; } static void vimc_sensor_tpg_s_format(struct vimc_sensor_device *vsensor) { const struct vimc_pix_map *vpix = vimc_pix_map_by_code(vsensor->mbus_format.code); tpg_reset_source(&vsensor->tpg, vsensor->mbus_format.width, vsensor->mbus_format.height, vsensor->mbus_format.field); tpg_s_bytesperline(&vsensor->tpg, 0, vsensor->mbus_format.width * vpix->bpp); tpg_s_buf_height(&vsensor->tpg, vsensor->mbus_format.height); tpg_s_fourcc(&vsensor->tpg, vpix->pixelformat); /* TODO: add support for V4L2_FIELD_ALTERNATE */ tpg_s_field(&vsensor->tpg, vsensor->mbus_format.field, false); tpg_s_colorspace(&vsensor->tpg, vsensor->mbus_format.colorspace); tpg_s_ycbcr_enc(&vsensor->tpg, vsensor->mbus_format.ycbcr_enc); tpg_s_quantization(&vsensor->tpg, vsensor->mbus_format.quantization); tpg_s_xfer_func(&vsensor->tpg, vsensor->mbus_format.xfer_func); } static void vimc_sensor_adjust_fmt(struct v4l2_mbus_framefmt *fmt) { const struct vimc_pix_map *vpix; /* Only accept code in the pix map table */ vpix = vimc_pix_map_by_code(fmt->code); if (!vpix) fmt->code = fmt_default.code; fmt->width = clamp_t(u32, fmt->width, VIMC_FRAME_MIN_WIDTH, VIMC_FRAME_MAX_WIDTH) & ~1; fmt->height = clamp_t(u32, fmt->height, VIMC_FRAME_MIN_HEIGHT, VIMC_FRAME_MAX_HEIGHT) & ~1; /* TODO: add support for V4L2_FIELD_ALTERNATE */ if (fmt->field == V4L2_FIELD_ANY || fmt->field == V4L2_FIELD_ALTERNATE) fmt->field = fmt_default.field; vimc_colorimetry_clamp(fmt); } static int vimc_sensor_set_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *fmt) { struct vimc_sensor_device *vsensor = v4l2_get_subdevdata(sd); struct v4l2_mbus_framefmt *mf; if (fmt->which == V4L2_SUBDEV_FORMAT_ACTIVE) { /* Do not change the format while stream is on */ if (vsensor->frame) return -EBUSY; mf = &vsensor->mbus_format; } else { mf = v4l2_subdev_get_try_format(sd, sd_state, fmt->pad); } /* Set the new format */ vimc_sensor_adjust_fmt(&fmt->format); dev_dbg(vsensor->ved.dev, "%s: format update: " "old:%dx%d (0x%x, %d, %d, %d, %d) " "new:%dx%d (0x%x, %d, %d, %d, %d)\n", vsensor->sd.name, /* old */ mf->width, mf->height, mf->code, mf->colorspace, mf->quantization, mf->xfer_func, mf->ycbcr_enc, /* new */ fmt->format.width, fmt->format.height, fmt->format.code, fmt->format.colorspace, fmt->format.quantization, fmt->format.xfer_func, fmt->format.ycbcr_enc); *mf = fmt->format; return 0; } static const struct v4l2_subdev_pad_ops vimc_sensor_pad_ops = { .init_cfg = vimc_sensor_init_cfg, .enum_mbus_code = vimc_sensor_enum_mbus_code, .enum_frame_size = vimc_sensor_enum_frame_size, .get_fmt = vimc_sensor_get_fmt, .set_fmt = vimc_sensor_set_fmt, }; static void *vimc_sensor_process_frame(struct vimc_ent_device *ved, const void *sink_frame) { struct vimc_sensor_device *vsensor = container_of(ved, struct vimc_sensor_device, ved); const unsigned int line_height = 16; u8 *basep[TPG_MAX_PLANES][2]; unsigned int line = 1; char str[100]; tpg_fill_plane_buffer(&vsensor->tpg, 0, 0, vsensor->frame); tpg_calc_text_basep(&vsensor->tpg, basep, 0, vsensor->frame); switch (vsensor->osd_value) { case VIMC_SENSOR_OSD_SHOW_ALL: { const char *order = tpg_g_color_order(&vsensor->tpg); tpg_gen_text(&vsensor->tpg, basep, line++ * line_height, 16, order); snprintf(str, sizeof(str), "brightness %3d, contrast %3d, saturation %3d, hue %d ", vsensor->tpg.brightness, vsensor->tpg.contrast, vsensor->tpg.saturation, vsensor->tpg.hue); tpg_gen_text(&vsensor->tpg, basep, line++ * line_height, 16, str); snprintf(str, sizeof(str), "sensor size: %dx%d", vsensor->mbus_format.width, vsensor->mbus_format.height); tpg_gen_text(&vsensor->tpg, basep, line++ * line_height, 16, str); fallthrough; } case VIMC_SENSOR_OSD_SHOW_COUNTERS: { unsigned int ms; ms = div_u64(ktime_get_ns() - vsensor->start_stream_ts, 1000000); snprintf(str, sizeof(str), "%02d:%02d:%02d:%03d", (ms / (60 * 60 * 1000)) % 24, (ms / (60 * 1000)) % 60, (ms / 1000) % 60, ms % 1000); tpg_gen_text(&vsensor->tpg, basep, line++ * line_height, 16, str); break; } case VIMC_SENSOR_OSD_SHOW_NONE: default: break; } return vsensor->frame; } static int vimc_sensor_s_stream(struct v4l2_subdev *sd, int enable) { struct vimc_sensor_device *vsensor = container_of(sd, struct vimc_sensor_device, sd); if (enable) { const struct vimc_pix_map *vpix; unsigned int frame_size; vsensor->start_stream_ts = ktime_get_ns(); /* Calculate the frame size */ vpix = vimc_pix_map_by_code(vsensor->mbus_format.code); frame_size = vsensor->mbus_format.width * vpix->bpp * vsensor->mbus_format.height; /* * Allocate the frame buffer. Use vmalloc to be able to * allocate a large amount of memory */ vsensor->frame = vmalloc(frame_size); if (!vsensor->frame) return -ENOMEM; /* configure the test pattern generator */ vimc_sensor_tpg_s_format(vsensor); } else { vfree(vsensor->frame); vsensor->frame = NULL; } return 0; } static const struct v4l2_subdev_core_ops vimc_sensor_core_ops = { .log_status = v4l2_ctrl_subdev_log_status, .subscribe_event = v4l2_ctrl_subdev_subscribe_event, .unsubscribe_event = v4l2_event_subdev_unsubscribe, }; static const struct v4l2_subdev_video_ops vimc_sensor_video_ops = { .s_stream = vimc_sensor_s_stream, }; static const struct v4l2_subdev_ops vimc_sensor_ops = { .core = &vimc_sensor_core_ops, .pad = &vimc_sensor_pad_ops, .video = &vimc_sensor_video_ops, }; static int vimc_sensor_s_ctrl(struct v4l2_ctrl *ctrl) { struct vimc_sensor_device *vsensor = container_of(ctrl->handler, struct vimc_sensor_device, hdl); switch (ctrl->id) { case VIMC_CID_TEST_PATTERN: tpg_s_pattern(&vsensor->tpg, ctrl->val); break; case V4L2_CID_HFLIP: tpg_s_hflip(&vsensor->tpg, ctrl->val); break; case V4L2_CID_VFLIP: tpg_s_vflip(&vsensor->tpg, ctrl->val); break; case V4L2_CID_BRIGHTNESS: tpg_s_brightness(&vsensor->tpg, ctrl->val); break; case V4L2_CID_CONTRAST: tpg_s_contrast(&vsensor->tpg, ctrl->val); break; case V4L2_CID_HUE: tpg_s_hue(&vsensor->tpg, ctrl->val); break; case V4L2_CID_SATURATION: tpg_s_saturation(&vsensor->tpg, ctrl->val); break; case VIMC_CID_OSD_TEXT_MODE: vsensor->osd_value = ctrl->val; break; default: return -EINVAL; } return 0; } static const struct v4l2_ctrl_ops vimc_sensor_ctrl_ops = { .s_ctrl = vimc_sensor_s_ctrl, }; static void vimc_sensor_release(struct vimc_ent_device *ved) { struct vimc_sensor_device *vsensor = container_of(ved, struct vimc_sensor_device, ved); v4l2_ctrl_handler_free(&vsensor->hdl); tpg_free(&vsensor->tpg); media_entity_cleanup(vsensor->ved.ent); kfree(vsensor); } /* Image Processing Controls */ static const struct v4l2_ctrl_config vimc_sensor_ctrl_class = { .flags = V4L2_CTRL_FLAG_READ_ONLY | V4L2_CTRL_FLAG_WRITE_ONLY, .id = VIMC_CID_VIMC_CLASS, .name = "VIMC Controls", .type = V4L2_CTRL_TYPE_CTRL_CLASS, }; static const struct v4l2_ctrl_config vimc_sensor_ctrl_test_pattern = { .ops = &vimc_sensor_ctrl_ops, .id = VIMC_CID_TEST_PATTERN, .name = "Test Pattern", .type = V4L2_CTRL_TYPE_MENU, .max = TPG_PAT_NOISE, .qmenu = tpg_pattern_strings, }; static const char * const vimc_ctrl_osd_mode_strings[] = { "All", "Counters Only", "None", NULL, }; static const struct v4l2_ctrl_config vimc_sensor_ctrl_osd_mode = { .ops = &vimc_sensor_ctrl_ops, .id = VIMC_CID_OSD_TEXT_MODE, .name = "Show Information", .type = V4L2_CTRL_TYPE_MENU, .max = ARRAY_SIZE(vimc_ctrl_osd_mode_strings) - 2, .qmenu = vimc_ctrl_osd_mode_strings, }; static struct vimc_ent_device *vimc_sensor_add(struct vimc_device *vimc, const char *vcfg_name) { struct v4l2_device *v4l2_dev = &vimc->v4l2_dev; struct vimc_sensor_device *vsensor; int ret; /* Allocate the vsensor struct */ vsensor = kzalloc(sizeof(*vsensor), GFP_KERNEL); if (!vsensor) return ERR_PTR(-ENOMEM); v4l2_ctrl_handler_init(&vsensor->hdl, 4); v4l2_ctrl_new_custom(&vsensor->hdl, &vimc_sensor_ctrl_class, NULL); v4l2_ctrl_new_custom(&vsensor->hdl, &vimc_sensor_ctrl_test_pattern, NULL); v4l2_ctrl_new_custom(&vsensor->hdl, &vimc_sensor_ctrl_osd_mode, NULL); v4l2_ctrl_new_std(&vsensor->hdl, &vimc_sensor_ctrl_ops, V4L2_CID_VFLIP, 0, 1, 1, 0); v4l2_ctrl_new_std(&vsensor->hdl, &vimc_sensor_ctrl_ops, V4L2_CID_HFLIP, 0, 1, 1, 0); v4l2_ctrl_new_std(&vsensor->hdl, &vimc_sensor_ctrl_ops, V4L2_CID_BRIGHTNESS, 0, 255, 1, 128); v4l2_ctrl_new_std(&vsensor->hdl, &vimc_sensor_ctrl_ops, V4L2_CID_CONTRAST, 0, 255, 1, 128); v4l2_ctrl_new_std(&vsensor->hdl, &vimc_sensor_ctrl_ops, V4L2_CID_HUE, -128, 127, 1, 0); v4l2_ctrl_new_std(&vsensor->hdl, &vimc_sensor_ctrl_ops, V4L2_CID_SATURATION, 0, 255, 1, 128); vsensor->sd.ctrl_handler = &vsensor->hdl; if (vsensor->hdl.error) { ret = vsensor->hdl.error; goto err_free_vsensor; } /* Initialize the test pattern generator */ tpg_init(&vsensor->tpg, vsensor->mbus_format.width, vsensor->mbus_format.height); ret = tpg_alloc(&vsensor->tpg, VIMC_FRAME_MAX_WIDTH); if (ret) goto err_free_hdl; /* Initialize ved and sd */ vsensor->pad.flags = MEDIA_PAD_FL_SOURCE; ret = vimc_ent_sd_register(&vsensor->ved, &vsensor->sd, v4l2_dev, vcfg_name, MEDIA_ENT_F_CAM_SENSOR, 1, &vsensor->pad, &vimc_sensor_ops); if (ret) goto err_free_tpg; vsensor->ved.process_frame = vimc_sensor_process_frame; vsensor->ved.dev = vimc->mdev.dev; /* Initialize the frame format */ vsensor->mbus_format = fmt_default; return &vsensor->ved; err_free_tpg: tpg_free(&vsensor->tpg); err_free_hdl: v4l2_ctrl_handler_free(&vsensor->hdl); err_free_vsensor: kfree(vsensor); return ERR_PTR(ret); } struct vimc_ent_type vimc_sensor_type = { .add = vimc_sensor_add, .release = vimc_sensor_release };
linux-master
drivers/media/test-drivers/vimc/vimc-sensor.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * vimc-capture.c Virtual Media Controller Driver * * Copyright (C) 2015-2017 Helen Koike <[email protected]> */ #include <media/v4l2-ioctl.h> #include <media/videobuf2-core.h> #include <media/videobuf2-dma-contig.h> #include <media/videobuf2-vmalloc.h> #include "vimc-common.h" #include "vimc-streamer.h" struct vimc_capture_device { struct vimc_ent_device ved; struct video_device vdev; struct v4l2_pix_format format; struct vb2_queue queue; struct list_head buf_list; /* * NOTE: in a real driver, a spin lock must be used to access the * queue because the frames are generated from a hardware interruption * and the isr is not allowed to sleep. * Even if it is not necessary a spinlock in the vimc driver, we * use it here as a code reference */ spinlock_t qlock; struct mutex lock; u32 sequence; struct vimc_stream stream; struct media_pad pad; }; static const struct v4l2_pix_format fmt_default = { .width = 640, .height = 480, .pixelformat = V4L2_PIX_FMT_RGB24, .field = V4L2_FIELD_NONE, .colorspace = V4L2_COLORSPACE_SRGB, }; struct vimc_capture_buffer { /* * struct vb2_v4l2_buffer must be the first element * the videobuf2 framework will allocate this struct based on * buf_struct_size and use the first sizeof(struct vb2_buffer) bytes of * memory as a vb2_buffer */ struct vb2_v4l2_buffer vb2; struct list_head list; }; static int vimc_capture_querycap(struct file *file, void *priv, struct v4l2_capability *cap) { strscpy(cap->driver, VIMC_PDEV_NAME, sizeof(cap->driver)); strscpy(cap->card, KBUILD_MODNAME, sizeof(cap->card)); snprintf(cap->bus_info, sizeof(cap->bus_info), "platform:%s", VIMC_PDEV_NAME); return 0; } static void vimc_capture_get_format(struct vimc_ent_device *ved, struct v4l2_pix_format *fmt) { struct vimc_capture_device *vcapture = container_of(ved, struct vimc_capture_device, ved); *fmt = vcapture->format; } static int vimc_capture_g_fmt_vid_cap(struct file *file, void *priv, struct v4l2_format *f) { struct vimc_capture_device *vcapture = video_drvdata(file); f->fmt.pix = vcapture->format; return 0; } static int vimc_capture_try_fmt_vid_cap(struct file *file, void *priv, struct v4l2_format *f) { struct v4l2_pix_format *format = &f->fmt.pix; const struct vimc_pix_map *vpix; format->width = clamp_t(u32, format->width, VIMC_FRAME_MIN_WIDTH, VIMC_FRAME_MAX_WIDTH) & ~1; format->height = clamp_t(u32, format->height, VIMC_FRAME_MIN_HEIGHT, VIMC_FRAME_MAX_HEIGHT) & ~1; /* Don't accept a pixelformat that is not on the table */ vpix = vimc_pix_map_by_pixelformat(format->pixelformat); if (!vpix) { format->pixelformat = fmt_default.pixelformat; vpix = vimc_pix_map_by_pixelformat(format->pixelformat); } /* TODO: Add support for custom bytesperline values */ format->bytesperline = format->width * vpix->bpp; format->sizeimage = format->bytesperline * format->height; if (format->field == V4L2_FIELD_ANY) format->field = fmt_default.field; vimc_colorimetry_clamp(format); if (format->colorspace == V4L2_COLORSPACE_DEFAULT) format->colorspace = fmt_default.colorspace; return 0; } static int vimc_capture_s_fmt_vid_cap(struct file *file, void *priv, struct v4l2_format *f) { struct vimc_capture_device *vcapture = video_drvdata(file); int ret; /* Do not change the format while stream is on */ if (vb2_is_busy(&vcapture->queue)) return -EBUSY; ret = vimc_capture_try_fmt_vid_cap(file, priv, f); if (ret) return ret; dev_dbg(vcapture->ved.dev, "%s: format update: " "old:%dx%d (0x%x, %d, %d, %d, %d) " "new:%dx%d (0x%x, %d, %d, %d, %d)\n", vcapture->vdev.name, /* old */ vcapture->format.width, vcapture->format.height, vcapture->format.pixelformat, vcapture->format.colorspace, vcapture->format.quantization, vcapture->format.xfer_func, vcapture->format.ycbcr_enc, /* new */ f->fmt.pix.width, f->fmt.pix.height, f->fmt.pix.pixelformat, f->fmt.pix.colorspace, f->fmt.pix.quantization, f->fmt.pix.xfer_func, f->fmt.pix.ycbcr_enc); vcapture->format = f->fmt.pix; return 0; } static int vimc_capture_enum_fmt_vid_cap(struct file *file, void *priv, struct v4l2_fmtdesc *f) { const struct vimc_pix_map *vpix; if (f->mbus_code) { if (f->index > 0) return -EINVAL; vpix = vimc_pix_map_by_code(f->mbus_code); } else { vpix = vimc_pix_map_by_index(f->index); } if (!vpix) return -EINVAL; f->pixelformat = vpix->pixelformat; return 0; } static int vimc_capture_enum_framesizes(struct file *file, void *fh, struct v4l2_frmsizeenum *fsize) { const struct vimc_pix_map *vpix; if (fsize->index) return -EINVAL; /* Only accept code in the pix map table */ vpix = vimc_pix_map_by_code(fsize->pixel_format); if (!vpix) return -EINVAL; fsize->type = V4L2_FRMSIZE_TYPE_CONTINUOUS; fsize->stepwise.min_width = VIMC_FRAME_MIN_WIDTH; fsize->stepwise.max_width = VIMC_FRAME_MAX_WIDTH; fsize->stepwise.min_height = VIMC_FRAME_MIN_HEIGHT; fsize->stepwise.max_height = VIMC_FRAME_MAX_HEIGHT; fsize->stepwise.step_width = 1; fsize->stepwise.step_height = 1; return 0; } static const struct v4l2_file_operations vimc_capture_fops = { .owner = THIS_MODULE, .open = v4l2_fh_open, .release = vb2_fop_release, .read = vb2_fop_read, .poll = vb2_fop_poll, .unlocked_ioctl = video_ioctl2, .mmap = vb2_fop_mmap, }; static const struct v4l2_ioctl_ops vimc_capture_ioctl_ops = { .vidioc_querycap = vimc_capture_querycap, .vidioc_g_fmt_vid_cap = vimc_capture_g_fmt_vid_cap, .vidioc_s_fmt_vid_cap = vimc_capture_s_fmt_vid_cap, .vidioc_try_fmt_vid_cap = vimc_capture_try_fmt_vid_cap, .vidioc_enum_fmt_vid_cap = vimc_capture_enum_fmt_vid_cap, .vidioc_enum_framesizes = vimc_capture_enum_framesizes, .vidioc_reqbufs = vb2_ioctl_reqbufs, .vidioc_create_bufs = vb2_ioctl_create_bufs, .vidioc_prepare_buf = vb2_ioctl_prepare_buf, .vidioc_querybuf = vb2_ioctl_querybuf, .vidioc_qbuf = vb2_ioctl_qbuf, .vidioc_dqbuf = vb2_ioctl_dqbuf, .vidioc_expbuf = vb2_ioctl_expbuf, .vidioc_streamon = vb2_ioctl_streamon, .vidioc_streamoff = vb2_ioctl_streamoff, }; static void vimc_capture_return_all_buffers(struct vimc_capture_device *vcapture, enum vb2_buffer_state state) { struct vimc_capture_buffer *vbuf, *node; spin_lock(&vcapture->qlock); list_for_each_entry_safe(vbuf, node, &vcapture->buf_list, list) { list_del(&vbuf->list); vb2_buffer_done(&vbuf->vb2.vb2_buf, state); } spin_unlock(&vcapture->qlock); } static int vimc_capture_start_streaming(struct vb2_queue *vq, unsigned int count) { struct vimc_capture_device *vcapture = vb2_get_drv_priv(vq); int ret; vcapture->sequence = 0; /* Start the media pipeline */ ret = video_device_pipeline_start(&vcapture->vdev, &vcapture->stream.pipe); if (ret) { vimc_capture_return_all_buffers(vcapture, VB2_BUF_STATE_QUEUED); return ret; } ret = vimc_streamer_s_stream(&vcapture->stream, &vcapture->ved, 1); if (ret) { video_device_pipeline_stop(&vcapture->vdev); vimc_capture_return_all_buffers(vcapture, VB2_BUF_STATE_QUEUED); return ret; } return 0; } /* * Stop the stream engine. Any remaining buffers in the stream queue are * dequeued and passed on to the vb2 framework marked as STATE_ERROR. */ static void vimc_capture_stop_streaming(struct vb2_queue *vq) { struct vimc_capture_device *vcapture = vb2_get_drv_priv(vq); vimc_streamer_s_stream(&vcapture->stream, &vcapture->ved, 0); /* Stop the media pipeline */ video_device_pipeline_stop(&vcapture->vdev); /* Release all active buffers */ vimc_capture_return_all_buffers(vcapture, VB2_BUF_STATE_ERROR); } static void vimc_capture_buf_queue(struct vb2_buffer *vb2_buf) { struct vimc_capture_device *vcapture = vb2_get_drv_priv(vb2_buf->vb2_queue); struct vimc_capture_buffer *buf = container_of(vb2_buf, struct vimc_capture_buffer, vb2.vb2_buf); spin_lock(&vcapture->qlock); list_add_tail(&buf->list, &vcapture->buf_list); spin_unlock(&vcapture->qlock); } static int vimc_capture_queue_setup(struct vb2_queue *vq, unsigned int *nbuffers, unsigned int *nplanes, unsigned int sizes[], struct device *alloc_devs[]) { struct vimc_capture_device *vcapture = vb2_get_drv_priv(vq); if (*nplanes) return sizes[0] < vcapture->format.sizeimage ? -EINVAL : 0; /* We don't support multiplanes for now */ *nplanes = 1; sizes[0] = vcapture->format.sizeimage; return 0; } static int vimc_capture_buffer_prepare(struct vb2_buffer *vb) { struct vimc_capture_device *vcapture = vb2_get_drv_priv(vb->vb2_queue); unsigned long size = vcapture->format.sizeimage; if (vb2_plane_size(vb, 0) < size) { dev_err(vcapture->ved.dev, "%s: buffer too small (%lu < %lu)\n", vcapture->vdev.name, vb2_plane_size(vb, 0), size); return -EINVAL; } return 0; } static const struct vb2_ops vimc_capture_qops = { .start_streaming = vimc_capture_start_streaming, .stop_streaming = vimc_capture_stop_streaming, .buf_queue = vimc_capture_buf_queue, .queue_setup = vimc_capture_queue_setup, .buf_prepare = vimc_capture_buffer_prepare, /* * Since q->lock is set we can use the standard * vb2_ops_wait_prepare/finish helper functions. */ .wait_prepare = vb2_ops_wait_prepare, .wait_finish = vb2_ops_wait_finish, }; static const struct media_entity_operations vimc_capture_mops = { .link_validate = vimc_vdev_link_validate, }; static void vimc_capture_release(struct vimc_ent_device *ved) { struct vimc_capture_device *vcapture = container_of(ved, struct vimc_capture_device, ved); media_entity_cleanup(vcapture->ved.ent); kfree(vcapture); } static void vimc_capture_unregister(struct vimc_ent_device *ved) { struct vimc_capture_device *vcapture = container_of(ved, struct vimc_capture_device, ved); vb2_video_unregister_device(&vcapture->vdev); } static void *vimc_capture_process_frame(struct vimc_ent_device *ved, const void *frame) { struct vimc_capture_device *vcapture = container_of(ved, struct vimc_capture_device, ved); struct vimc_capture_buffer *vimc_buf; void *vbuf; spin_lock(&vcapture->qlock); /* Get the first entry of the list */ vimc_buf = list_first_entry_or_null(&vcapture->buf_list, typeof(*vimc_buf), list); if (!vimc_buf) { spin_unlock(&vcapture->qlock); return ERR_PTR(-EAGAIN); } /* Remove this entry from the list */ list_del(&vimc_buf->list); spin_unlock(&vcapture->qlock); /* Fill the buffer */ vimc_buf->vb2.vb2_buf.timestamp = ktime_get_ns(); vimc_buf->vb2.sequence = vcapture->sequence++; vimc_buf->vb2.field = vcapture->format.field; vbuf = vb2_plane_vaddr(&vimc_buf->vb2.vb2_buf, 0); memcpy(vbuf, frame, vcapture->format.sizeimage); /* Set it as ready */ vb2_set_plane_payload(&vimc_buf->vb2.vb2_buf, 0, vcapture->format.sizeimage); vb2_buffer_done(&vimc_buf->vb2.vb2_buf, VB2_BUF_STATE_DONE); return NULL; } static struct vimc_ent_device *vimc_capture_add(struct vimc_device *vimc, const char *vcfg_name) { struct v4l2_device *v4l2_dev = &vimc->v4l2_dev; const struct vimc_pix_map *vpix; struct vimc_capture_device *vcapture; struct video_device *vdev; struct vb2_queue *q; int ret; /* Allocate the vimc_capture_device struct */ vcapture = kzalloc(sizeof(*vcapture), GFP_KERNEL); if (!vcapture) return ERR_PTR(-ENOMEM); /* Initialize the media entity */ vcapture->vdev.entity.name = vcfg_name; vcapture->vdev.entity.function = MEDIA_ENT_F_IO_V4L; vcapture->pad.flags = MEDIA_PAD_FL_SINK; ret = media_entity_pads_init(&vcapture->vdev.entity, 1, &vcapture->pad); if (ret) goto err_free_vcapture; /* Initialize the lock */ mutex_init(&vcapture->lock); /* Initialize the vb2 queue */ q = &vcapture->queue; q->type = V4L2_BUF_TYPE_VIDEO_CAPTURE; q->io_modes = VB2_MMAP | VB2_DMABUF; if (vimc_allocator == VIMC_ALLOCATOR_VMALLOC) q->io_modes |= VB2_USERPTR; q->drv_priv = vcapture; q->buf_struct_size = sizeof(struct vimc_capture_buffer); q->ops = &vimc_capture_qops; q->mem_ops = vimc_allocator == VIMC_ALLOCATOR_DMA_CONTIG ? &vb2_dma_contig_memops : &vb2_vmalloc_memops; q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC; q->min_buffers_needed = 2; q->lock = &vcapture->lock; q->dev = v4l2_dev->dev; ret = vb2_queue_init(q); if (ret) { dev_err(vimc->mdev.dev, "%s: vb2 queue init failed (err=%d)\n", vcfg_name, ret); goto err_clean_m_ent; } /* Initialize buffer list and its lock */ INIT_LIST_HEAD(&vcapture->buf_list); spin_lock_init(&vcapture->qlock); /* Set default frame format */ vcapture->format = fmt_default; vpix = vimc_pix_map_by_pixelformat(vcapture->format.pixelformat); vcapture->format.bytesperline = vcapture->format.width * vpix->bpp; vcapture->format.sizeimage = vcapture->format.bytesperline * vcapture->format.height; /* Fill the vimc_ent_device struct */ vcapture->ved.ent = &vcapture->vdev.entity; vcapture->ved.process_frame = vimc_capture_process_frame; vcapture->ved.vdev_get_format = vimc_capture_get_format; vcapture->ved.dev = vimc->mdev.dev; /* Initialize the video_device struct */ vdev = &vcapture->vdev; vdev->device_caps = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING | V4L2_CAP_IO_MC; vdev->entity.ops = &vimc_capture_mops; vdev->release = video_device_release_empty; vdev->fops = &vimc_capture_fops; vdev->ioctl_ops = &vimc_capture_ioctl_ops; vdev->lock = &vcapture->lock; vdev->queue = q; vdev->v4l2_dev = v4l2_dev; vdev->vfl_dir = VFL_DIR_RX; strscpy(vdev->name, vcfg_name, sizeof(vdev->name)); video_set_drvdata(vdev, &vcapture->ved); /* Register the video_device with the v4l2 and the media framework */ ret = video_register_device(vdev, VFL_TYPE_VIDEO, -1); if (ret) { dev_err(vimc->mdev.dev, "%s: video register failed (err=%d)\n", vcapture->vdev.name, ret); goto err_clean_m_ent; } return &vcapture->ved; err_clean_m_ent: media_entity_cleanup(&vcapture->vdev.entity); err_free_vcapture: kfree(vcapture); return ERR_PTR(ret); } struct vimc_ent_type vimc_capture_type = { .add = vimc_capture_add, .unregister = vimc_capture_unregister, .release = vimc_capture_release };
linux-master
drivers/media/test-drivers/vimc/vimc-capture.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * vimc-debayer.c Virtual Media Controller Driver * * Copyright (C) 2015-2017 Helen Koike <[email protected]> */ #include <linux/moduleparam.h> #include <linux/platform_device.h> #include <linux/vmalloc.h> #include <linux/v4l2-mediabus.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-event.h> #include <media/v4l2-subdev.h> #include "vimc-common.h" enum vimc_debayer_rgb_colors { VIMC_DEBAYER_RED = 0, VIMC_DEBAYER_GREEN = 1, VIMC_DEBAYER_BLUE = 2, }; struct vimc_debayer_pix_map { u32 code; enum vimc_debayer_rgb_colors order[2][2]; }; struct vimc_debayer_device { struct vimc_ent_device ved; struct v4l2_subdev sd; /* The active format */ struct v4l2_mbus_framefmt sink_fmt; u32 src_code; void (*set_rgb_src)(struct vimc_debayer_device *vdebayer, unsigned int lin, unsigned int col, unsigned int rgb[3]); /* Values calculated when the stream starts */ u8 *src_frame; const struct vimc_debayer_pix_map *sink_pix_map; unsigned int sink_bpp; unsigned int mean_win_size; struct v4l2_ctrl_handler hdl; struct media_pad pads[2]; }; static const struct v4l2_mbus_framefmt sink_fmt_default = { .width = 640, .height = 480, .code = MEDIA_BUS_FMT_SRGGB8_1X8, .field = V4L2_FIELD_NONE, .colorspace = V4L2_COLORSPACE_SRGB, }; static const u32 vimc_debayer_src_mbus_codes[] = { MEDIA_BUS_FMT_GBR888_1X24, MEDIA_BUS_FMT_BGR888_1X24, MEDIA_BUS_FMT_BGR888_3X8, MEDIA_BUS_FMT_RGB888_1X24, MEDIA_BUS_FMT_RGB888_2X12_BE, MEDIA_BUS_FMT_RGB888_2X12_LE, MEDIA_BUS_FMT_RGB888_3X8, MEDIA_BUS_FMT_RGB888_1X7X4_SPWG, MEDIA_BUS_FMT_RGB888_1X7X4_JEIDA, MEDIA_BUS_FMT_RGB888_1X32_PADHI, }; static const struct vimc_debayer_pix_map vimc_debayer_pix_map_list[] = { { .code = MEDIA_BUS_FMT_SBGGR8_1X8, .order = { { VIMC_DEBAYER_BLUE, VIMC_DEBAYER_GREEN }, { VIMC_DEBAYER_GREEN, VIMC_DEBAYER_RED } } }, { .code = MEDIA_BUS_FMT_SGBRG8_1X8, .order = { { VIMC_DEBAYER_GREEN, VIMC_DEBAYER_BLUE }, { VIMC_DEBAYER_RED, VIMC_DEBAYER_GREEN } } }, { .code = MEDIA_BUS_FMT_SGRBG8_1X8, .order = { { VIMC_DEBAYER_GREEN, VIMC_DEBAYER_RED }, { VIMC_DEBAYER_BLUE, VIMC_DEBAYER_GREEN } } }, { .code = MEDIA_BUS_FMT_SRGGB8_1X8, .order = { { VIMC_DEBAYER_RED, VIMC_DEBAYER_GREEN }, { VIMC_DEBAYER_GREEN, VIMC_DEBAYER_BLUE } } }, { .code = MEDIA_BUS_FMT_SBGGR10_1X10, .order = { { VIMC_DEBAYER_BLUE, VIMC_DEBAYER_GREEN }, { VIMC_DEBAYER_GREEN, VIMC_DEBAYER_RED } } }, { .code = MEDIA_BUS_FMT_SGBRG10_1X10, .order = { { VIMC_DEBAYER_GREEN, VIMC_DEBAYER_BLUE }, { VIMC_DEBAYER_RED, VIMC_DEBAYER_GREEN } } }, { .code = MEDIA_BUS_FMT_SGRBG10_1X10, .order = { { VIMC_DEBAYER_GREEN, VIMC_DEBAYER_RED }, { VIMC_DEBAYER_BLUE, VIMC_DEBAYER_GREEN } } }, { .code = MEDIA_BUS_FMT_SRGGB10_1X10, .order = { { VIMC_DEBAYER_RED, VIMC_DEBAYER_GREEN }, { VIMC_DEBAYER_GREEN, VIMC_DEBAYER_BLUE } } }, { .code = MEDIA_BUS_FMT_SBGGR12_1X12, .order = { { VIMC_DEBAYER_BLUE, VIMC_DEBAYER_GREEN }, { VIMC_DEBAYER_GREEN, VIMC_DEBAYER_RED } } }, { .code = MEDIA_BUS_FMT_SGBRG12_1X12, .order = { { VIMC_DEBAYER_GREEN, VIMC_DEBAYER_BLUE }, { VIMC_DEBAYER_RED, VIMC_DEBAYER_GREEN } } }, { .code = MEDIA_BUS_FMT_SGRBG12_1X12, .order = { { VIMC_DEBAYER_GREEN, VIMC_DEBAYER_RED }, { VIMC_DEBAYER_BLUE, VIMC_DEBAYER_GREEN } } }, { .code = MEDIA_BUS_FMT_SRGGB12_1X12, .order = { { VIMC_DEBAYER_RED, VIMC_DEBAYER_GREEN }, { VIMC_DEBAYER_GREEN, VIMC_DEBAYER_BLUE } } }, }; static const struct vimc_debayer_pix_map *vimc_debayer_pix_map_by_code(u32 code) { unsigned int i; for (i = 0; i < ARRAY_SIZE(vimc_debayer_pix_map_list); i++) if (vimc_debayer_pix_map_list[i].code == code) return &vimc_debayer_pix_map_list[i]; return NULL; } static bool vimc_debayer_src_code_is_valid(u32 code) { unsigned int i; for (i = 0; i < ARRAY_SIZE(vimc_debayer_src_mbus_codes); i++) if (vimc_debayer_src_mbus_codes[i] == code) return true; return false; } static int vimc_debayer_init_cfg(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state) { struct vimc_debayer_device *vdebayer = v4l2_get_subdevdata(sd); struct v4l2_mbus_framefmt *mf; unsigned int i; mf = v4l2_subdev_get_try_format(sd, sd_state, 0); *mf = sink_fmt_default; for (i = 1; i < sd->entity.num_pads; i++) { mf = v4l2_subdev_get_try_format(sd, sd_state, i); *mf = sink_fmt_default; mf->code = vdebayer->src_code; } return 0; } static int vimc_debayer_enum_mbus_code(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_mbus_code_enum *code) { if (VIMC_IS_SRC(code->pad)) { if (code->index >= ARRAY_SIZE(vimc_debayer_src_mbus_codes)) return -EINVAL; code->code = vimc_debayer_src_mbus_codes[code->index]; } else { if (code->index >= ARRAY_SIZE(vimc_debayer_pix_map_list)) return -EINVAL; code->code = vimc_debayer_pix_map_list[code->index].code; } return 0; } static int vimc_debayer_enum_frame_size(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_frame_size_enum *fse) { if (fse->index) return -EINVAL; if (VIMC_IS_SINK(fse->pad)) { const struct vimc_debayer_pix_map *vpix = vimc_debayer_pix_map_by_code(fse->code); if (!vpix) return -EINVAL; } else if (!vimc_debayer_src_code_is_valid(fse->code)) { return -EINVAL; } fse->min_width = VIMC_FRAME_MIN_WIDTH; fse->max_width = VIMC_FRAME_MAX_WIDTH; fse->min_height = VIMC_FRAME_MIN_HEIGHT; fse->max_height = VIMC_FRAME_MAX_HEIGHT; return 0; } static int vimc_debayer_get_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *fmt) { struct vimc_debayer_device *vdebayer = v4l2_get_subdevdata(sd); /* Get the current sink format */ fmt->format = fmt->which == V4L2_SUBDEV_FORMAT_TRY ? *v4l2_subdev_get_try_format(sd, sd_state, 0) : vdebayer->sink_fmt; /* Set the right code for the source pad */ if (VIMC_IS_SRC(fmt->pad)) fmt->format.code = vdebayer->src_code; return 0; } static void vimc_debayer_adjust_sink_fmt(struct v4l2_mbus_framefmt *fmt) { const struct vimc_debayer_pix_map *vpix; /* Don't accept a code that is not on the debayer table */ vpix = vimc_debayer_pix_map_by_code(fmt->code); if (!vpix) fmt->code = sink_fmt_default.code; fmt->width = clamp_t(u32, fmt->width, VIMC_FRAME_MIN_WIDTH, VIMC_FRAME_MAX_WIDTH) & ~1; fmt->height = clamp_t(u32, fmt->height, VIMC_FRAME_MIN_HEIGHT, VIMC_FRAME_MAX_HEIGHT) & ~1; if (fmt->field == V4L2_FIELD_ANY) fmt->field = sink_fmt_default.field; vimc_colorimetry_clamp(fmt); } static int vimc_debayer_set_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_state *sd_state, struct v4l2_subdev_format *fmt) { struct vimc_debayer_device *vdebayer = v4l2_get_subdevdata(sd); struct v4l2_mbus_framefmt *sink_fmt; u32 *src_code; if (fmt->which == V4L2_SUBDEV_FORMAT_ACTIVE) { /* Do not change the format while stream is on */ if (vdebayer->src_frame) return -EBUSY; sink_fmt = &vdebayer->sink_fmt; src_code = &vdebayer->src_code; } else { sink_fmt = v4l2_subdev_get_try_format(sd, sd_state, 0); src_code = &v4l2_subdev_get_try_format(sd, sd_state, 1)->code; } /* * Do not change the format of the source pad, * it is propagated from the sink */ if (VIMC_IS_SRC(fmt->pad)) { u32 code = fmt->format.code; fmt->format = *sink_fmt; if (vimc_debayer_src_code_is_valid(code)) *src_code = code; fmt->format.code = *src_code; } else { /* Set the new format in the sink pad */ vimc_debayer_adjust_sink_fmt(&fmt->format); dev_dbg(vdebayer->ved.dev, "%s: sink format update: " "old:%dx%d (0x%x, %d, %d, %d, %d) " "new:%dx%d (0x%x, %d, %d, %d, %d)\n", vdebayer->sd.name, /* old */ sink_fmt->width, sink_fmt->height, sink_fmt->code, sink_fmt->colorspace, sink_fmt->quantization, sink_fmt->xfer_func, sink_fmt->ycbcr_enc, /* new */ fmt->format.width, fmt->format.height, fmt->format.code, fmt->format.colorspace, fmt->format.quantization, fmt->format.xfer_func, fmt->format.ycbcr_enc); *sink_fmt = fmt->format; } return 0; } static const struct v4l2_subdev_pad_ops vimc_debayer_pad_ops = { .init_cfg = vimc_debayer_init_cfg, .enum_mbus_code = vimc_debayer_enum_mbus_code, .enum_frame_size = vimc_debayer_enum_frame_size, .get_fmt = vimc_debayer_get_fmt, .set_fmt = vimc_debayer_set_fmt, }; static void vimc_debayer_process_rgb_frame(struct vimc_debayer_device *vdebayer, unsigned int lin, unsigned int col, unsigned int rgb[3]) { const struct vimc_pix_map *vpix; unsigned int i, index; vpix = vimc_pix_map_by_code(vdebayer->src_code); index = VIMC_FRAME_INDEX(lin, col, vdebayer->sink_fmt.width, 3); for (i = 0; i < 3; i++) { switch (vpix->pixelformat) { case V4L2_PIX_FMT_RGB24: vdebayer->src_frame[index + i] = rgb[i]; break; case V4L2_PIX_FMT_BGR24: vdebayer->src_frame[index + i] = rgb[2 - i]; break; } } } static int vimc_debayer_s_stream(struct v4l2_subdev *sd, int enable) { struct vimc_debayer_device *vdebayer = v4l2_get_subdevdata(sd); if (enable) { const struct vimc_pix_map *vpix; unsigned int frame_size; if (vdebayer->src_frame) return 0; /* Calculate the frame size of the source pad */ vpix = vimc_pix_map_by_code(vdebayer->src_code); frame_size = vdebayer->sink_fmt.width * vdebayer->sink_fmt.height * vpix->bpp; /* Save the bytes per pixel of the sink */ vpix = vimc_pix_map_by_code(vdebayer->sink_fmt.code); vdebayer->sink_bpp = vpix->bpp; /* Get the corresponding pixel map from the table */ vdebayer->sink_pix_map = vimc_debayer_pix_map_by_code(vdebayer->sink_fmt.code); /* * Allocate the frame buffer. Use vmalloc to be able to * allocate a large amount of memory */ vdebayer->src_frame = vmalloc(frame_size); if (!vdebayer->src_frame) return -ENOMEM; } else { if (!vdebayer->src_frame) return 0; vfree(vdebayer->src_frame); vdebayer->src_frame = NULL; } return 0; } static const struct v4l2_subdev_core_ops vimc_debayer_core_ops = { .log_status = v4l2_ctrl_subdev_log_status, .subscribe_event = v4l2_ctrl_subdev_subscribe_event, .unsubscribe_event = v4l2_event_subdev_unsubscribe, }; static const struct v4l2_subdev_video_ops vimc_debayer_video_ops = { .s_stream = vimc_debayer_s_stream, }; static const struct v4l2_subdev_ops vimc_debayer_ops = { .core = &vimc_debayer_core_ops, .pad = &vimc_debayer_pad_ops, .video = &vimc_debayer_video_ops, }; static unsigned int vimc_debayer_get_val(const u8 *bytes, const unsigned int n_bytes) { unsigned int i; unsigned int acc = 0; for (i = 0; i < n_bytes; i++) acc = acc + (bytes[i] << (8 * i)); return acc; } static void vimc_debayer_calc_rgb_sink(struct vimc_debayer_device *vdebayer, const u8 *frame, const unsigned int lin, const unsigned int col, unsigned int rgb[3]) { unsigned int i, seek, wlin, wcol; unsigned int n_rgb[3] = {0, 0, 0}; for (i = 0; i < 3; i++) rgb[i] = 0; /* * Calculate how many we need to subtract to get to the pixel in * the top left corner of the mean window (considering the current * pixel as the center) */ seek = vdebayer->mean_win_size / 2; /* Sum the values of the colors in the mean window */ dev_dbg(vdebayer->ved.dev, "deb: %s: --- Calc pixel %dx%d, window mean %d, seek %d ---\n", vdebayer->sd.name, lin, col, vdebayer->sink_fmt.height, seek); /* * Iterate through all the lines in the mean window, start * with zero if the pixel is outside the frame and don't pass * the height when the pixel is in the bottom border of the * frame */ for (wlin = seek > lin ? 0 : lin - seek; wlin < lin + seek + 1 && wlin < vdebayer->sink_fmt.height; wlin++) { /* * Iterate through all the columns in the mean window, start * with zero if the pixel is outside the frame and don't pass * the width when the pixel is in the right border of the * frame */ for (wcol = seek > col ? 0 : col - seek; wcol < col + seek + 1 && wcol < vdebayer->sink_fmt.width; wcol++) { enum vimc_debayer_rgb_colors color; unsigned int index; /* Check which color this pixel is */ color = vdebayer->sink_pix_map->order[wlin % 2][wcol % 2]; index = VIMC_FRAME_INDEX(wlin, wcol, vdebayer->sink_fmt.width, vdebayer->sink_bpp); dev_dbg(vdebayer->ved.dev, "deb: %s: RGB CALC: frame index %d, win pos %dx%d, color %d\n", vdebayer->sd.name, index, wlin, wcol, color); /* Get its value */ rgb[color] = rgb[color] + vimc_debayer_get_val(&frame[index], vdebayer->sink_bpp); /* Save how many values we already added */ n_rgb[color]++; dev_dbg(vdebayer->ved.dev, "deb: %s: RGB CALC: val %d, n %d\n", vdebayer->sd.name, rgb[color], n_rgb[color]); } } /* Calculate the mean */ for (i = 0; i < 3; i++) { dev_dbg(vdebayer->ved.dev, "deb: %s: PRE CALC: %dx%d Color %d, val %d, n %d\n", vdebayer->sd.name, lin, col, i, rgb[i], n_rgb[i]); if (n_rgb[i]) rgb[i] = rgb[i] / n_rgb[i]; dev_dbg(vdebayer->ved.dev, "deb: %s: FINAL CALC: %dx%d Color %d, val %d\n", vdebayer->sd.name, lin, col, i, rgb[i]); } } static void *vimc_debayer_process_frame(struct vimc_ent_device *ved, const void *sink_frame) { struct vimc_debayer_device *vdebayer = container_of(ved, struct vimc_debayer_device, ved); unsigned int rgb[3]; unsigned int i, j; /* If the stream in this node is not active, just return */ if (!vdebayer->src_frame) return ERR_PTR(-EINVAL); for (i = 0; i < vdebayer->sink_fmt.height; i++) for (j = 0; j < vdebayer->sink_fmt.width; j++) { vimc_debayer_calc_rgb_sink(vdebayer, sink_frame, i, j, rgb); vdebayer->set_rgb_src(vdebayer, i, j, rgb); } return vdebayer->src_frame; } static int vimc_debayer_s_ctrl(struct v4l2_ctrl *ctrl) { struct vimc_debayer_device *vdebayer = container_of(ctrl->handler, struct vimc_debayer_device, hdl); switch (ctrl->id) { case VIMC_CID_MEAN_WIN_SIZE: vdebayer->mean_win_size = ctrl->val; break; default: return -EINVAL; } return 0; } static const struct v4l2_ctrl_ops vimc_debayer_ctrl_ops = { .s_ctrl = vimc_debayer_s_ctrl, }; static void vimc_debayer_release(struct vimc_ent_device *ved) { struct vimc_debayer_device *vdebayer = container_of(ved, struct vimc_debayer_device, ved); v4l2_ctrl_handler_free(&vdebayer->hdl); media_entity_cleanup(vdebayer->ved.ent); kfree(vdebayer); } static const struct v4l2_ctrl_config vimc_debayer_ctrl_class = { .flags = V4L2_CTRL_FLAG_READ_ONLY | V4L2_CTRL_FLAG_WRITE_ONLY, .id = VIMC_CID_VIMC_CLASS, .name = "VIMC Controls", .type = V4L2_CTRL_TYPE_CTRL_CLASS, }; static const struct v4l2_ctrl_config vimc_debayer_ctrl_mean_win_size = { .ops = &vimc_debayer_ctrl_ops, .id = VIMC_CID_MEAN_WIN_SIZE, .name = "Debayer Mean Window Size", .type = V4L2_CTRL_TYPE_INTEGER, .min = 1, .max = 25, .step = 2, .def = 3, }; static struct vimc_ent_device *vimc_debayer_add(struct vimc_device *vimc, const char *vcfg_name) { struct v4l2_device *v4l2_dev = &vimc->v4l2_dev; struct vimc_debayer_device *vdebayer; int ret; /* Allocate the vdebayer struct */ vdebayer = kzalloc(sizeof(*vdebayer), GFP_KERNEL); if (!vdebayer) return ERR_PTR(-ENOMEM); /* Create controls: */ v4l2_ctrl_handler_init(&vdebayer->hdl, 2); v4l2_ctrl_new_custom(&vdebayer->hdl, &vimc_debayer_ctrl_class, NULL); v4l2_ctrl_new_custom(&vdebayer->hdl, &vimc_debayer_ctrl_mean_win_size, NULL); vdebayer->sd.ctrl_handler = &vdebayer->hdl; if (vdebayer->hdl.error) { ret = vdebayer->hdl.error; goto err_free_vdebayer; } /* Initialize ved and sd */ vdebayer->pads[0].flags = MEDIA_PAD_FL_SINK; vdebayer->pads[1].flags = MEDIA_PAD_FL_SOURCE; ret = vimc_ent_sd_register(&vdebayer->ved, &vdebayer->sd, v4l2_dev, vcfg_name, MEDIA_ENT_F_PROC_VIDEO_PIXEL_ENC_CONV, 2, vdebayer->pads, &vimc_debayer_ops); if (ret) goto err_free_hdl; vdebayer->ved.process_frame = vimc_debayer_process_frame; vdebayer->ved.dev = vimc->mdev.dev; vdebayer->mean_win_size = vimc_debayer_ctrl_mean_win_size.def; /* Initialize the frame format */ vdebayer->sink_fmt = sink_fmt_default; /* * TODO: Add support for more output formats, we only support * RGB888 for now * NOTE: the src format is always the same as the sink, except * for the code */ vdebayer->src_code = MEDIA_BUS_FMT_RGB888_1X24; vdebayer->set_rgb_src = vimc_debayer_process_rgb_frame; return &vdebayer->ved; err_free_hdl: v4l2_ctrl_handler_free(&vdebayer->hdl); err_free_vdebayer: kfree(vdebayer); return ERR_PTR(ret); } struct vimc_ent_type vimc_debayer_type = { .add = vimc_debayer_add, .release = vimc_debayer_release };
linux-master
drivers/media/test-drivers/vimc/vimc-debayer.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * vimc-common.c Virtual Media Controller Driver * * Copyright (C) 2015-2017 Helen Koike <[email protected]> */ #include <linux/init.h> #include <linux/module.h> #include "vimc-common.h" /* * NOTE: non-bayer formats need to come first (necessary for enum_mbus_code * in the scaler) */ static const struct vimc_pix_map vimc_pix_map_list[] = { /* TODO: add all missing formats */ /* RGB formats */ { .code = { MEDIA_BUS_FMT_BGR888_1X24, MEDIA_BUS_FMT_BGR888_3X8 }, .pixelformat = V4L2_PIX_FMT_BGR24, .bpp = 3, .bayer = false, }, { .code = { MEDIA_BUS_FMT_RGB888_1X24, MEDIA_BUS_FMT_RGB888_2X12_BE, MEDIA_BUS_FMT_RGB888_2X12_LE, MEDIA_BUS_FMT_RGB888_3X8, MEDIA_BUS_FMT_RGB888_1X7X4_SPWG, MEDIA_BUS_FMT_RGB888_1X7X4_JEIDA, MEDIA_BUS_FMT_RGB888_1X32_PADHI, MEDIA_BUS_FMT_GBR888_1X24 }, .pixelformat = V4L2_PIX_FMT_RGB24, .bpp = 3, .bayer = false, }, { .code = { MEDIA_BUS_FMT_ARGB8888_1X32 }, .pixelformat = V4L2_PIX_FMT_ARGB32, .bpp = 4, .bayer = false, }, /* Bayer formats */ { .code = { MEDIA_BUS_FMT_SBGGR8_1X8 }, .pixelformat = V4L2_PIX_FMT_SBGGR8, .bpp = 1, .bayer = true, }, { .code = { MEDIA_BUS_FMT_SGBRG8_1X8 }, .pixelformat = V4L2_PIX_FMT_SGBRG8, .bpp = 1, .bayer = true, }, { .code = { MEDIA_BUS_FMT_SGRBG8_1X8 }, .pixelformat = V4L2_PIX_FMT_SGRBG8, .bpp = 1, .bayer = true, }, { .code = { MEDIA_BUS_FMT_SRGGB8_1X8 }, .pixelformat = V4L2_PIX_FMT_SRGGB8, .bpp = 1, .bayer = true, }, { .code = { MEDIA_BUS_FMT_SBGGR10_1X10 }, .pixelformat = V4L2_PIX_FMT_SBGGR10, .bpp = 2, .bayer = true, }, { .code = { MEDIA_BUS_FMT_SGBRG10_1X10 }, .pixelformat = V4L2_PIX_FMT_SGBRG10, .bpp = 2, .bayer = true, }, { .code = { MEDIA_BUS_FMT_SGRBG10_1X10 }, .pixelformat = V4L2_PIX_FMT_SGRBG10, .bpp = 2, .bayer = true, }, { .code = { MEDIA_BUS_FMT_SRGGB10_1X10 }, .pixelformat = V4L2_PIX_FMT_SRGGB10, .bpp = 2, .bayer = true, }, /* 10bit raw bayer a-law compressed to 8 bits */ { .code = { MEDIA_BUS_FMT_SBGGR10_ALAW8_1X8 }, .pixelformat = V4L2_PIX_FMT_SBGGR10ALAW8, .bpp = 1, .bayer = true, }, { .code = { MEDIA_BUS_FMT_SGBRG10_ALAW8_1X8 }, .pixelformat = V4L2_PIX_FMT_SGBRG10ALAW8, .bpp = 1, .bayer = true, }, { .code = { MEDIA_BUS_FMT_SGRBG10_ALAW8_1X8 }, .pixelformat = V4L2_PIX_FMT_SGRBG10ALAW8, .bpp = 1, .bayer = true, }, { .code = { MEDIA_BUS_FMT_SRGGB10_ALAW8_1X8 }, .pixelformat = V4L2_PIX_FMT_SRGGB10ALAW8, .bpp = 1, .bayer = true, }, /* 10bit raw bayer DPCM compressed to 8 bits */ { .code = { MEDIA_BUS_FMT_SBGGR10_DPCM8_1X8 }, .pixelformat = V4L2_PIX_FMT_SBGGR10DPCM8, .bpp = 1, .bayer = true, }, { .code = { MEDIA_BUS_FMT_SGBRG10_DPCM8_1X8 }, .pixelformat = V4L2_PIX_FMT_SGBRG10DPCM8, .bpp = 1, .bayer = true, }, { .code = { MEDIA_BUS_FMT_SGRBG10_DPCM8_1X8 }, .pixelformat = V4L2_PIX_FMT_SGRBG10DPCM8, .bpp = 1, .bayer = true, }, { .code = { MEDIA_BUS_FMT_SRGGB10_DPCM8_1X8 }, .pixelformat = V4L2_PIX_FMT_SRGGB10DPCM8, .bpp = 1, .bayer = true, }, { .code = { MEDIA_BUS_FMT_SBGGR12_1X12 }, .pixelformat = V4L2_PIX_FMT_SBGGR12, .bpp = 2, .bayer = true, }, { .code = { MEDIA_BUS_FMT_SGBRG12_1X12 }, .pixelformat = V4L2_PIX_FMT_SGBRG12, .bpp = 2, .bayer = true, }, { .code = { MEDIA_BUS_FMT_SGRBG12_1X12 }, .pixelformat = V4L2_PIX_FMT_SGRBG12, .bpp = 2, .bayer = true, }, { .code = { MEDIA_BUS_FMT_SRGGB12_1X12 }, .pixelformat = V4L2_PIX_FMT_SRGGB12, .bpp = 2, .bayer = true, }, }; bool vimc_is_source(struct media_entity *ent) { unsigned int i; for (i = 0; i < ent->num_pads; i++) if (ent->pads[i].flags & MEDIA_PAD_FL_SINK) return false; return true; } const struct vimc_pix_map *vimc_pix_map_by_index(unsigned int i) { if (i >= ARRAY_SIZE(vimc_pix_map_list)) return NULL; return &vimc_pix_map_list[i]; } u32 vimc_mbus_code_by_index(unsigned int index) { unsigned int i, j; for (i = 0; i < ARRAY_SIZE(vimc_pix_map_list); i++) { for (j = 0; j < ARRAY_SIZE(vimc_pix_map_list[i].code); j++) { if (!vimc_pix_map_list[i].code[j]) break; if (!index) return vimc_pix_map_list[i].code[j]; index--; } } return 0; } const struct vimc_pix_map *vimc_pix_map_by_code(u32 code) { unsigned int i, j; for (i = 0; i < ARRAY_SIZE(vimc_pix_map_list); i++) { for (j = 0; j < ARRAY_SIZE(vimc_pix_map_list[i].code); j++) { if (vimc_pix_map_list[i].code[j] == code) return &vimc_pix_map_list[i]; } } return NULL; } const struct vimc_pix_map *vimc_pix_map_by_pixelformat(u32 pixelformat) { unsigned int i; for (i = 0; i < ARRAY_SIZE(vimc_pix_map_list); i++) { if (vimc_pix_map_list[i].pixelformat == pixelformat) return &vimc_pix_map_list[i]; } return NULL; } static int vimc_get_pix_format(struct media_pad *pad, struct v4l2_pix_format *fmt) { if (is_media_entity_v4l2_subdev(pad->entity)) { struct v4l2_subdev *sd = media_entity_to_v4l2_subdev(pad->entity); struct v4l2_subdev_format sd_fmt = { .which = V4L2_SUBDEV_FORMAT_ACTIVE, .pad = pad->index, }; const struct vimc_pix_map *pix_map; int ret; ret = v4l2_subdev_call(sd, pad, get_fmt, NULL, &sd_fmt); if (ret) return ret; v4l2_fill_pix_format(fmt, &sd_fmt.format); pix_map = vimc_pix_map_by_code(sd_fmt.format.code); fmt->pixelformat = pix_map->pixelformat; } else if (is_media_entity_v4l2_video_device(pad->entity)) { struct video_device *vdev = container_of(pad->entity, struct video_device, entity); struct vimc_ent_device *ved = video_get_drvdata(vdev); if (!ved->vdev_get_format) return -ENOIOCTLCMD; ved->vdev_get_format(ved, fmt); } else { return -EINVAL; } return 0; } int vimc_vdev_link_validate(struct media_link *link) { struct v4l2_pix_format source_fmt, sink_fmt; int ret; ret = vimc_get_pix_format(link->source, &source_fmt); if (ret) return ret; ret = vimc_get_pix_format(link->sink, &sink_fmt); if (ret) return ret; pr_info("vimc link validate: " "%s:src:%dx%d (0x%x, %d, %d, %d, %d) " "%s:snk:%dx%d (0x%x, %d, %d, %d, %d)\n", /* src */ link->source->entity->name, source_fmt.width, source_fmt.height, source_fmt.pixelformat, source_fmt.colorspace, source_fmt.quantization, source_fmt.xfer_func, source_fmt.ycbcr_enc, /* sink */ link->sink->entity->name, sink_fmt.width, sink_fmt.height, sink_fmt.pixelformat, sink_fmt.colorspace, sink_fmt.quantization, sink_fmt.xfer_func, sink_fmt.ycbcr_enc); /* The width, height and pixelformat must match. */ if (source_fmt.width != sink_fmt.width || source_fmt.height != sink_fmt.height || source_fmt.pixelformat != sink_fmt.pixelformat) return -EPIPE; /* * The field order must match, or the sink field order must be NONE * to support interlaced hardware connected to bridges that support * progressive formats only. */ if (source_fmt.field != sink_fmt.field && sink_fmt.field != V4L2_FIELD_NONE) return -EPIPE; /* * If colorspace is DEFAULT, then assume all the colorimetry is also * DEFAULT, return 0 to skip comparing the other colorimetry parameters */ if (source_fmt.colorspace == V4L2_COLORSPACE_DEFAULT || sink_fmt.colorspace == V4L2_COLORSPACE_DEFAULT) return 0; /* Colorspace must match. */ if (source_fmt.colorspace != sink_fmt.colorspace) return -EPIPE; /* Colorimetry must match if they are not set to DEFAULT */ if (source_fmt.ycbcr_enc != V4L2_YCBCR_ENC_DEFAULT && sink_fmt.ycbcr_enc != V4L2_YCBCR_ENC_DEFAULT && source_fmt.ycbcr_enc != sink_fmt.ycbcr_enc) return -EPIPE; if (source_fmt.quantization != V4L2_QUANTIZATION_DEFAULT && sink_fmt.quantization != V4L2_QUANTIZATION_DEFAULT && source_fmt.quantization != sink_fmt.quantization) return -EPIPE; if (source_fmt.xfer_func != V4L2_XFER_FUNC_DEFAULT && sink_fmt.xfer_func != V4L2_XFER_FUNC_DEFAULT && source_fmt.xfer_func != sink_fmt.xfer_func) return -EPIPE; return 0; } static const struct media_entity_operations vimc_ent_sd_mops = { .link_validate = v4l2_subdev_link_validate, }; int vimc_ent_sd_register(struct vimc_ent_device *ved, struct v4l2_subdev *sd, struct v4l2_device *v4l2_dev, const char *const name, u32 function, u16 num_pads, struct media_pad *pads, const struct v4l2_subdev_ops *sd_ops) { int ret; /* Fill the vimc_ent_device struct */ ved->ent = &sd->entity; /* Initialize the subdev */ v4l2_subdev_init(sd, sd_ops); sd->entity.function = function; sd->entity.ops = &vimc_ent_sd_mops; sd->owner = THIS_MODULE; strscpy(sd->name, name, sizeof(sd->name)); v4l2_set_subdevdata(sd, ved); /* Expose this subdev to user space */ sd->flags |= V4L2_SUBDEV_FL_HAS_DEVNODE; if (sd->ctrl_handler) sd->flags |= V4L2_SUBDEV_FL_HAS_EVENTS; /* Initialize the media entity */ ret = media_entity_pads_init(&sd->entity, num_pads, pads); if (ret) return ret; /* Register the subdev with the v4l2 and the media framework */ ret = v4l2_device_register_subdev(v4l2_dev, sd); if (ret) { dev_err(v4l2_dev->dev, "%s: subdev register failed (err=%d)\n", name, ret); goto err_clean_m_ent; } return 0; err_clean_m_ent: media_entity_cleanup(&sd->entity); return ret; }
linux-master
drivers/media/test-drivers/vimc/vimc-common.c
// SPDX-License-Identifier: GPL-2.0+ /* * vimc-streamer.c Virtual Media Controller Driver * * Copyright (C) 2018 Lucas A. M. Magalhães <[email protected]> * */ #include <linux/init.h> #include <linux/freezer.h> #include <linux/kthread.h> #include "vimc-streamer.h" /** * vimc_get_source_entity - get the entity connected with the first sink pad * * @ent: reference media_entity * * Helper function that returns the media entity containing the source pad * linked with the first sink pad from the given media entity pad list. * * Return: The source pad or NULL, if it wasn't found. */ static struct media_entity *vimc_get_source_entity(struct media_entity *ent) { struct media_pad *pad; int i; for (i = 0; i < ent->num_pads; i++) { if (ent->pads[i].flags & MEDIA_PAD_FL_SOURCE) continue; pad = media_pad_remote_pad_first(&ent->pads[i]); return pad ? pad->entity : NULL; } return NULL; } /** * vimc_streamer_pipeline_terminate - Disable stream in all ved in stream * * @stream: the pointer to the stream structure with the pipeline to be * disabled. * * Calls s_stream to disable the stream in each entity of the pipeline * */ static void vimc_streamer_pipeline_terminate(struct vimc_stream *stream) { struct vimc_ent_device *ved; struct v4l2_subdev *sd; while (stream->pipe_size) { stream->pipe_size--; ved = stream->ved_pipeline[stream->pipe_size]; stream->ved_pipeline[stream->pipe_size] = NULL; if (!is_media_entity_v4l2_subdev(ved->ent)) continue; sd = media_entity_to_v4l2_subdev(ved->ent); v4l2_subdev_call(sd, video, s_stream, 0); } } /** * vimc_streamer_pipeline_init - Initializes the stream structure * * @stream: the pointer to the stream structure to be initialized * @ved: the pointer to the vimc entity initializing the stream * * Initializes the stream structure. Walks through the entity graph to * construct the pipeline used later on the streamer thread. * Calls vimc_streamer_s_stream() to enable stream in all entities of * the pipeline. * * Return: 0 if success, error code otherwise. */ static int vimc_streamer_pipeline_init(struct vimc_stream *stream, struct vimc_ent_device *ved) { struct media_entity *entity; struct video_device *vdev; struct v4l2_subdev *sd; int ret = 0; stream->pipe_size = 0; while (stream->pipe_size < VIMC_STREAMER_PIPELINE_MAX_SIZE) { if (!ved) { vimc_streamer_pipeline_terminate(stream); return -EINVAL; } stream->ved_pipeline[stream->pipe_size++] = ved; if (is_media_entity_v4l2_subdev(ved->ent)) { sd = media_entity_to_v4l2_subdev(ved->ent); ret = v4l2_subdev_call(sd, video, s_stream, 1); if (ret && ret != -ENOIOCTLCMD) { dev_err(ved->dev, "subdev_call error %s\n", ved->ent->name); vimc_streamer_pipeline_terminate(stream); return ret; } } entity = vimc_get_source_entity(ved->ent); /* Check if the end of the pipeline was reached */ if (!entity) { /* the first entity of the pipe should be source only */ if (!vimc_is_source(ved->ent)) { dev_err(ved->dev, "first entity in the pipe '%s' is not a source\n", ved->ent->name); vimc_streamer_pipeline_terminate(stream); return -EPIPE; } return 0; } /* Get the next device in the pipeline */ if (is_media_entity_v4l2_subdev(entity)) { sd = media_entity_to_v4l2_subdev(entity); ved = v4l2_get_subdevdata(sd); } else { vdev = container_of(entity, struct video_device, entity); ved = video_get_drvdata(vdev); } } vimc_streamer_pipeline_terminate(stream); return -EINVAL; } /** * vimc_streamer_thread - Process frames through the pipeline * * @data: vimc_stream struct of the current stream * * From the source to the sink, gets a frame from each subdevice and send to * the next one of the pipeline at a fixed framerate. * * Return: * Always zero (created as ``int`` instead of ``void`` to comply with * kthread API). */ static int vimc_streamer_thread(void *data) { struct vimc_stream *stream = data; u8 *frame = NULL; int i; set_freezable(); for (;;) { try_to_freeze(); if (kthread_should_stop()) break; for (i = stream->pipe_size - 1; i >= 0; i--) { frame = stream->ved_pipeline[i]->process_frame( stream->ved_pipeline[i], frame); if (!frame || IS_ERR(frame)) break; } //wait for 60hz set_current_state(TASK_UNINTERRUPTIBLE); schedule_timeout(HZ / 60); } return 0; } /** * vimc_streamer_s_stream - Start/stop the streaming on the media pipeline * * @stream: the pointer to the stream structure of the current stream * @ved: pointer to the vimc entity of the entity of the stream * @enable: flag to determine if stream should start/stop * * When starting, check if there is no ``stream->kthread`` allocated. This * should indicate that a stream is already running. Then, it initializes the * pipeline, creates and runs a kthread to consume buffers through the pipeline. * When stopping, analogously check if there is a stream running, stop the * thread and terminates the pipeline. * * Return: 0 if success, error code otherwise. */ int vimc_streamer_s_stream(struct vimc_stream *stream, struct vimc_ent_device *ved, int enable) { int ret; if (!stream || !ved) return -EINVAL; if (enable) { if (stream->kthread) return 0; ret = vimc_streamer_pipeline_init(stream, ved); if (ret) return ret; stream->kthread = kthread_run(vimc_streamer_thread, stream, "vimc-streamer thread"); if (IS_ERR(stream->kthread)) { ret = PTR_ERR(stream->kthread); dev_err(ved->dev, "kthread_run failed with %d\n", ret); vimc_streamer_pipeline_terminate(stream); stream->kthread = NULL; return ret; } } else { if (!stream->kthread) return 0; ret = kthread_stop(stream->kthread); /* * kthread_stop returns -EINTR in cases when streamon was * immediately followed by streamoff, and the thread didn't had * a chance to run. Ignore errors to stop the stream in the * pipeline. */ if (ret) dev_dbg(ved->dev, "kthread_stop returned '%d'\n", ret); stream->kthread = NULL; vimc_streamer_pipeline_terminate(stream); } return 0; }
linux-master
drivers/media/test-drivers/vimc/vimc-streamer.c
// SPDX-License-Identifier: LGPL-2.1+ /* * Copyright 2016 Tom aan de Wiel * Copyright 2018 Cisco Systems, Inc. and/or its affiliates. All rights reserved. * * 8x8 Fast Walsh Hadamard Transform in sequency order based on the paper: * * A Recursive Algorithm for Sequency-Ordered Fast Walsh Transforms, * R.D. Brown, 1977 */ #include <linux/string.h> #include <linux/kernel.h> #include <linux/videodev2.h> #include "codec-fwht.h" #define OVERFLOW_BIT BIT(14) /* * Note: bit 0 of the header must always be 0. Otherwise it cannot * be guaranteed that the magic 8 byte sequence (see below) can * never occur in the rlc output. */ #define PFRAME_BIT BIT(15) #define DUPS_MASK 0x1ffe #define PBLOCK 0 #define IBLOCK 1 #define ALL_ZEROS 15 static const uint8_t zigzag[64] = { 0, 1, 8, 2, 9, 16, 3, 10, 17, 24, 4, 11, 18, 25, 32, 5, 12, 19, 26, 33, 40, 6, 13, 20, 27, 34, 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 23, 30, 37, 44, 51, 58, 31, 38, 45, 52, 59, 39, 46, 53, 60, 47, 54, 61, 55, 62, 63, }; /* * noinline_for_stack to work around * https://bugs.llvm.org/show_bug.cgi?id=38809 */ static int noinline_for_stack rlc(const s16 *in, __be16 *output, int blocktype) { s16 block[8 * 8]; s16 *wp = block; int i = 0; int x, y; int ret = 0; /* read in block from framebuffer */ int lastzero_run = 0; int to_encode; for (y = 0; y < 8; y++) { for (x = 0; x < 8; x++) { *wp = in[x + y * 8]; wp++; } } /* keep track of amount of trailing zeros */ for (i = 63; i >= 0 && !block[zigzag[i]]; i--) lastzero_run++; *output++ = (blocktype == PBLOCK ? htons(PFRAME_BIT) : 0); ret++; to_encode = 8 * 8 - (lastzero_run > 14 ? lastzero_run : 0); i = 0; while (i < to_encode) { int cnt = 0; int tmp; /* count leading zeros */ while ((tmp = block[zigzag[i]]) == 0 && cnt < 14) { cnt++; i++; if (i == to_encode) { cnt--; break; } } /* 4 bits for run, 12 for coefficient (quantization by 4) */ *output++ = htons((cnt | tmp << 4)); i++; ret++; } if (lastzero_run > 14) { *output = htons(ALL_ZEROS | 0); ret++; } return ret; } /* * This function will worst-case increase rlc_in by 65*2 bytes: * one s16 value for the header and 8 * 8 coefficients of type s16. */ static noinline_for_stack u16 derlc(const __be16 **rlc_in, s16 *dwht_out, const __be16 *end_of_input) { /* header */ const __be16 *input = *rlc_in; u16 stat; int dec_count = 0; s16 block[8 * 8 + 16]; s16 *wp = block; int i; if (input > end_of_input) return OVERFLOW_BIT; stat = ntohs(*input++); /* * Now de-compress, it expands one byte to up to 15 bytes * (or fills the remainder of the 64 bytes with zeroes if it * is the last byte to expand). * * So block has to be 8 * 8 + 16 bytes, the '+ 16' is to * allow for overflow if the incoming data was malformed. */ while (dec_count < 8 * 8) { s16 in; int length; int coeff; if (input > end_of_input) return OVERFLOW_BIT; in = ntohs(*input++); length = in & 0xf; coeff = in >> 4; /* fill remainder with zeros */ if (length == 15) { for (i = 0; i < 64 - dec_count; i++) *wp++ = 0; break; } for (i = 0; i < length; i++) *wp++ = 0; *wp++ = coeff; dec_count += length + 1; } wp = block; for (i = 0; i < 64; i++) { int pos = zigzag[i]; int y = pos / 8; int x = pos % 8; dwht_out[x + y * 8] = *wp++; } *rlc_in = input; return stat; } static const int quant_table[] = { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 2, 2, 2, 2, 2, 3, 6, 2, 2, 2, 2, 2, 3, 6, 6, 2, 2, 2, 2, 3, 6, 6, 6, 2, 2, 2, 3, 6, 6, 6, 6, 2, 2, 3, 6, 6, 6, 6, 8, }; static const int quant_table_p[] = { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 6, 3, 3, 3, 3, 3, 3, 6, 6, 3, 3, 3, 3, 3, 6, 6, 9, 3, 3, 3, 3, 6, 6, 9, 9, 3, 3, 3, 6, 6, 9, 9, 10, }; static void quantize_intra(s16 *coeff, s16 *de_coeff, u16 qp) { const int *quant = quant_table; int i, j; for (j = 0; j < 8; j++) { for (i = 0; i < 8; i++, quant++, coeff++, de_coeff++) { *coeff >>= *quant; if (*coeff >= -qp && *coeff <= qp) *coeff = *de_coeff = 0; else *de_coeff = *coeff << *quant; } } } static void dequantize_intra(s16 *coeff) { const int *quant = quant_table; int i, j; for (j = 0; j < 8; j++) for (i = 0; i < 8; i++, quant++, coeff++) *coeff <<= *quant; } static void quantize_inter(s16 *coeff, s16 *de_coeff, u16 qp) { const int *quant = quant_table_p; int i, j; for (j = 0; j < 8; j++) { for (i = 0; i < 8; i++, quant++, coeff++, de_coeff++) { *coeff >>= *quant; if (*coeff >= -qp && *coeff <= qp) *coeff = *de_coeff = 0; else *de_coeff = *coeff << *quant; } } } static void dequantize_inter(s16 *coeff) { const int *quant = quant_table_p; int i, j; for (j = 0; j < 8; j++) for (i = 0; i < 8; i++, quant++, coeff++) *coeff <<= *quant; } static void noinline_for_stack fwht(const u8 *block, s16 *output_block, unsigned int stride, unsigned int input_step, bool intra) { /* we'll need more than 8 bits for the transformed coefficients */ s32 workspace1[8], workspace2[8]; const u8 *tmp = block; s16 *out = output_block; int add = intra ? 256 : 0; unsigned int i; /* stage 1 */ for (i = 0; i < 8; i++, tmp += stride, out += 8) { switch (input_step) { case 1: workspace1[0] = tmp[0] + tmp[1] - add; workspace1[1] = tmp[0] - tmp[1]; workspace1[2] = tmp[2] + tmp[3] - add; workspace1[3] = tmp[2] - tmp[3]; workspace1[4] = tmp[4] + tmp[5] - add; workspace1[5] = tmp[4] - tmp[5]; workspace1[6] = tmp[6] + tmp[7] - add; workspace1[7] = tmp[6] - tmp[7]; break; case 2: workspace1[0] = tmp[0] + tmp[2] - add; workspace1[1] = tmp[0] - tmp[2]; workspace1[2] = tmp[4] + tmp[6] - add; workspace1[3] = tmp[4] - tmp[6]; workspace1[4] = tmp[8] + tmp[10] - add; workspace1[5] = tmp[8] - tmp[10]; workspace1[6] = tmp[12] + tmp[14] - add; workspace1[7] = tmp[12] - tmp[14]; break; case 3: workspace1[0] = tmp[0] + tmp[3] - add; workspace1[1] = tmp[0] - tmp[3]; workspace1[2] = tmp[6] + tmp[9] - add; workspace1[3] = tmp[6] - tmp[9]; workspace1[4] = tmp[12] + tmp[15] - add; workspace1[5] = tmp[12] - tmp[15]; workspace1[6] = tmp[18] + tmp[21] - add; workspace1[7] = tmp[18] - tmp[21]; break; default: workspace1[0] = tmp[0] + tmp[4] - add; workspace1[1] = tmp[0] - tmp[4]; workspace1[2] = tmp[8] + tmp[12] - add; workspace1[3] = tmp[8] - tmp[12]; workspace1[4] = tmp[16] + tmp[20] - add; workspace1[5] = tmp[16] - tmp[20]; workspace1[6] = tmp[24] + tmp[28] - add; workspace1[7] = tmp[24] - tmp[28]; break; } /* stage 2 */ workspace2[0] = workspace1[0] + workspace1[2]; workspace2[1] = workspace1[0] - workspace1[2]; workspace2[2] = workspace1[1] - workspace1[3]; workspace2[3] = workspace1[1] + workspace1[3]; workspace2[4] = workspace1[4] + workspace1[6]; workspace2[5] = workspace1[4] - workspace1[6]; workspace2[6] = workspace1[5] - workspace1[7]; workspace2[7] = workspace1[5] + workspace1[7]; /* stage 3 */ out[0] = workspace2[0] + workspace2[4]; out[1] = workspace2[0] - workspace2[4]; out[2] = workspace2[1] - workspace2[5]; out[3] = workspace2[1] + workspace2[5]; out[4] = workspace2[2] + workspace2[6]; out[5] = workspace2[2] - workspace2[6]; out[6] = workspace2[3] - workspace2[7]; out[7] = workspace2[3] + workspace2[7]; } out = output_block; for (i = 0; i < 8; i++, out++) { /* stage 1 */ workspace1[0] = out[0] + out[1 * 8]; workspace1[1] = out[0] - out[1 * 8]; workspace1[2] = out[2 * 8] + out[3 * 8]; workspace1[3] = out[2 * 8] - out[3 * 8]; workspace1[4] = out[4 * 8] + out[5 * 8]; workspace1[5] = out[4 * 8] - out[5 * 8]; workspace1[6] = out[6 * 8] + out[7 * 8]; workspace1[7] = out[6 * 8] - out[7 * 8]; /* stage 2 */ workspace2[0] = workspace1[0] + workspace1[2]; workspace2[1] = workspace1[0] - workspace1[2]; workspace2[2] = workspace1[1] - workspace1[3]; workspace2[3] = workspace1[1] + workspace1[3]; workspace2[4] = workspace1[4] + workspace1[6]; workspace2[5] = workspace1[4] - workspace1[6]; workspace2[6] = workspace1[5] - workspace1[7]; workspace2[7] = workspace1[5] + workspace1[7]; /* stage 3 */ out[0 * 8] = workspace2[0] + workspace2[4]; out[1 * 8] = workspace2[0] - workspace2[4]; out[2 * 8] = workspace2[1] - workspace2[5]; out[3 * 8] = workspace2[1] + workspace2[5]; out[4 * 8] = workspace2[2] + workspace2[6]; out[5 * 8] = workspace2[2] - workspace2[6]; out[6 * 8] = workspace2[3] - workspace2[7]; out[7 * 8] = workspace2[3] + workspace2[7]; } } /* * Not the nicest way of doing it, but P-blocks get twice the range of * that of the I-blocks. Therefore we need a type bigger than 8 bits. * Furthermore values can be negative... This is just a version that * works with 16 signed data */ static void noinline_for_stack fwht16(const s16 *block, s16 *output_block, int stride, int intra) { /* we'll need more than 8 bits for the transformed coefficients */ s32 workspace1[8], workspace2[8]; const s16 *tmp = block; s16 *out = output_block; int i; for (i = 0; i < 8; i++, tmp += stride, out += 8) { /* stage 1 */ workspace1[0] = tmp[0] + tmp[1]; workspace1[1] = tmp[0] - tmp[1]; workspace1[2] = tmp[2] + tmp[3]; workspace1[3] = tmp[2] - tmp[3]; workspace1[4] = tmp[4] + tmp[5]; workspace1[5] = tmp[4] - tmp[5]; workspace1[6] = tmp[6] + tmp[7]; workspace1[7] = tmp[6] - tmp[7]; /* stage 2 */ workspace2[0] = workspace1[0] + workspace1[2]; workspace2[1] = workspace1[0] - workspace1[2]; workspace2[2] = workspace1[1] - workspace1[3]; workspace2[3] = workspace1[1] + workspace1[3]; workspace2[4] = workspace1[4] + workspace1[6]; workspace2[5] = workspace1[4] - workspace1[6]; workspace2[6] = workspace1[5] - workspace1[7]; workspace2[7] = workspace1[5] + workspace1[7]; /* stage 3 */ out[0] = workspace2[0] + workspace2[4]; out[1] = workspace2[0] - workspace2[4]; out[2] = workspace2[1] - workspace2[5]; out[3] = workspace2[1] + workspace2[5]; out[4] = workspace2[2] + workspace2[6]; out[5] = workspace2[2] - workspace2[6]; out[6] = workspace2[3] - workspace2[7]; out[7] = workspace2[3] + workspace2[7]; } out = output_block; for (i = 0; i < 8; i++, out++) { /* stage 1 */ workspace1[0] = out[0] + out[1*8]; workspace1[1] = out[0] - out[1*8]; workspace1[2] = out[2*8] + out[3*8]; workspace1[3] = out[2*8] - out[3*8]; workspace1[4] = out[4*8] + out[5*8]; workspace1[5] = out[4*8] - out[5*8]; workspace1[6] = out[6*8] + out[7*8]; workspace1[7] = out[6*8] - out[7*8]; /* stage 2 */ workspace2[0] = workspace1[0] + workspace1[2]; workspace2[1] = workspace1[0] - workspace1[2]; workspace2[2] = workspace1[1] - workspace1[3]; workspace2[3] = workspace1[1] + workspace1[3]; workspace2[4] = workspace1[4] + workspace1[6]; workspace2[5] = workspace1[4] - workspace1[6]; workspace2[6] = workspace1[5] - workspace1[7]; workspace2[7] = workspace1[5] + workspace1[7]; /* stage 3 */ out[0*8] = workspace2[0] + workspace2[4]; out[1*8] = workspace2[0] - workspace2[4]; out[2*8] = workspace2[1] - workspace2[5]; out[3*8] = workspace2[1] + workspace2[5]; out[4*8] = workspace2[2] + workspace2[6]; out[5*8] = workspace2[2] - workspace2[6]; out[6*8] = workspace2[3] - workspace2[7]; out[7*8] = workspace2[3] + workspace2[7]; } } static noinline_for_stack void ifwht(const s16 *block, s16 *output_block, int intra) { /* * we'll need more than 8 bits for the transformed coefficients * use native unit of cpu */ int workspace1[8], workspace2[8]; int inter = intra ? 0 : 1; const s16 *tmp = block; s16 *out = output_block; int i; for (i = 0; i < 8; i++, tmp += 8, out += 8) { /* stage 1 */ workspace1[0] = tmp[0] + tmp[1]; workspace1[1] = tmp[0] - tmp[1]; workspace1[2] = tmp[2] + tmp[3]; workspace1[3] = tmp[2] - tmp[3]; workspace1[4] = tmp[4] + tmp[5]; workspace1[5] = tmp[4] - tmp[5]; workspace1[6] = tmp[6] + tmp[7]; workspace1[7] = tmp[6] - tmp[7]; /* stage 2 */ workspace2[0] = workspace1[0] + workspace1[2]; workspace2[1] = workspace1[0] - workspace1[2]; workspace2[2] = workspace1[1] - workspace1[3]; workspace2[3] = workspace1[1] + workspace1[3]; workspace2[4] = workspace1[4] + workspace1[6]; workspace2[5] = workspace1[4] - workspace1[6]; workspace2[6] = workspace1[5] - workspace1[7]; workspace2[7] = workspace1[5] + workspace1[7]; /* stage 3 */ out[0] = workspace2[0] + workspace2[4]; out[1] = workspace2[0] - workspace2[4]; out[2] = workspace2[1] - workspace2[5]; out[3] = workspace2[1] + workspace2[5]; out[4] = workspace2[2] + workspace2[6]; out[5] = workspace2[2] - workspace2[6]; out[6] = workspace2[3] - workspace2[7]; out[7] = workspace2[3] + workspace2[7]; } out = output_block; for (i = 0; i < 8; i++, out++) { /* stage 1 */ workspace1[0] = out[0] + out[1 * 8]; workspace1[1] = out[0] - out[1 * 8]; workspace1[2] = out[2 * 8] + out[3 * 8]; workspace1[3] = out[2 * 8] - out[3 * 8]; workspace1[4] = out[4 * 8] + out[5 * 8]; workspace1[5] = out[4 * 8] - out[5 * 8]; workspace1[6] = out[6 * 8] + out[7 * 8]; workspace1[7] = out[6 * 8] - out[7 * 8]; /* stage 2 */ workspace2[0] = workspace1[0] + workspace1[2]; workspace2[1] = workspace1[0] - workspace1[2]; workspace2[2] = workspace1[1] - workspace1[3]; workspace2[3] = workspace1[1] + workspace1[3]; workspace2[4] = workspace1[4] + workspace1[6]; workspace2[5] = workspace1[4] - workspace1[6]; workspace2[6] = workspace1[5] - workspace1[7]; workspace2[7] = workspace1[5] + workspace1[7]; /* stage 3 */ if (inter) { int d; out[0 * 8] = workspace2[0] + workspace2[4]; out[1 * 8] = workspace2[0] - workspace2[4]; out[2 * 8] = workspace2[1] - workspace2[5]; out[3 * 8] = workspace2[1] + workspace2[5]; out[4 * 8] = workspace2[2] + workspace2[6]; out[5 * 8] = workspace2[2] - workspace2[6]; out[6 * 8] = workspace2[3] - workspace2[7]; out[7 * 8] = workspace2[3] + workspace2[7]; for (d = 0; d < 8; d++) out[8 * d] >>= 6; } else { int d; out[0 * 8] = workspace2[0] + workspace2[4]; out[1 * 8] = workspace2[0] - workspace2[4]; out[2 * 8] = workspace2[1] - workspace2[5]; out[3 * 8] = workspace2[1] + workspace2[5]; out[4 * 8] = workspace2[2] + workspace2[6]; out[5 * 8] = workspace2[2] - workspace2[6]; out[6 * 8] = workspace2[3] - workspace2[7]; out[7 * 8] = workspace2[3] + workspace2[7]; for (d = 0; d < 8; d++) { out[8 * d] >>= 6; out[8 * d] += 128; } } } } static void fill_encoder_block(const u8 *input, s16 *dst, unsigned int stride, unsigned int input_step) { int i, j; for (i = 0; i < 8; i++) { for (j = 0; j < 8; j++, input += input_step) *dst++ = *input; input += stride - 8 * input_step; } } static int var_intra(const s16 *input) { int32_t mean = 0; int32_t ret = 0; const s16 *tmp = input; int i; for (i = 0; i < 8 * 8; i++, tmp++) mean += *tmp; mean /= 64; tmp = input; for (i = 0; i < 8 * 8; i++, tmp++) ret += (*tmp - mean) < 0 ? -(*tmp - mean) : (*tmp - mean); return ret; } static int var_inter(const s16 *old, const s16 *new) { int32_t ret = 0; int i; for (i = 0; i < 8 * 8; i++, old++, new++) ret += (*old - *new) < 0 ? -(*old - *new) : (*old - *new); return ret; } static noinline_for_stack int decide_blocktype(const u8 *cur, const u8 *reference, s16 *deltablock, unsigned int stride, unsigned int input_step) { s16 tmp[64]; s16 old[64]; s16 *work = tmp; unsigned int k, l; int vari; int vard; fill_encoder_block(cur, tmp, stride, input_step); fill_encoder_block(reference, old, 8, 1); vari = var_intra(tmp); for (k = 0; k < 8; k++) { for (l = 0; l < 8; l++) { *deltablock = *work - *reference; deltablock++; work++; reference++; } } deltablock -= 64; vard = var_inter(old, tmp); return vari <= vard ? IBLOCK : PBLOCK; } static void fill_decoder_block(u8 *dst, const s16 *input, int stride, unsigned int dst_step) { int i, j; for (i = 0; i < 8; i++) { for (j = 0; j < 8; j++, input++, dst += dst_step) { if (*input < 0) *dst = 0; else if (*input > 255) *dst = 255; else *dst = *input; } dst += stride - (8 * dst_step); } } static void add_deltas(s16 *deltas, const u8 *ref, int stride, unsigned int ref_step) { int k, l; for (k = 0; k < 8; k++) { for (l = 0; l < 8; l++) { *deltas += *ref; ref += ref_step; /* * Due to quantizing, it might possible that the * decoded coefficients are slightly out of range */ if (*deltas < 0) *deltas = 0; else if (*deltas > 255) *deltas = 255; deltas++; } ref += stride - (8 * ref_step); } } static u32 encode_plane(u8 *input, u8 *refp, __be16 **rlco, __be16 *rlco_max, struct fwht_cframe *cf, u32 height, u32 width, u32 stride, unsigned int input_step, bool is_intra, bool next_is_intra) { u8 *input_start = input; __be16 *rlco_start = *rlco; s16 deltablock[64]; __be16 pframe_bit = htons(PFRAME_BIT); u32 encoding = 0; unsigned int last_size = 0; unsigned int i, j; width = round_up(width, 8); height = round_up(height, 8); for (j = 0; j < height / 8; j++) { input = input_start + j * 8 * stride; for (i = 0; i < width / 8; i++) { /* intra code, first frame is always intra coded. */ int blocktype = IBLOCK; unsigned int size; if (!is_intra) blocktype = decide_blocktype(input, refp, deltablock, stride, input_step); if (blocktype == IBLOCK) { fwht(input, cf->coeffs, stride, input_step, 1); quantize_intra(cf->coeffs, cf->de_coeffs, cf->i_frame_qp); } else { /* inter code */ encoding |= FWHT_FRAME_PCODED; fwht16(deltablock, cf->coeffs, 8, 0); quantize_inter(cf->coeffs, cf->de_coeffs, cf->p_frame_qp); } if (!next_is_intra) { ifwht(cf->de_coeffs, cf->de_fwht, blocktype); if (blocktype == PBLOCK) add_deltas(cf->de_fwht, refp, 8, 1); fill_decoder_block(refp, cf->de_fwht, 8, 1); } input += 8 * input_step; refp += 8 * 8; size = rlc(cf->coeffs, *rlco, blocktype); if (last_size == size && !memcmp(*rlco + 1, *rlco - size + 1, 2 * size - 2)) { __be16 *last_rlco = *rlco - size; s16 hdr = ntohs(*last_rlco); if (!((*last_rlco ^ **rlco) & pframe_bit) && (hdr & DUPS_MASK) < DUPS_MASK) *last_rlco = htons(hdr + 2); else *rlco += size; } else { *rlco += size; } if (*rlco >= rlco_max) { encoding |= FWHT_FRAME_UNENCODED; goto exit_loop; } last_size = size; } } exit_loop: if (encoding & FWHT_FRAME_UNENCODED) { u8 *out = (u8 *)rlco_start; u8 *p; input = input_start; /* * The compressed stream should never contain the magic * header, so when we copy the YUV data we replace 0xff * by 0xfe. Since YUV is limited range such values * shouldn't appear anyway. */ for (j = 0; j < height; j++) { for (i = 0, p = input; i < width; i++, p += input_step) *out++ = (*p == 0xff) ? 0xfe : *p; input += stride; } *rlco = (__be16 *)out; encoding &= ~FWHT_FRAME_PCODED; } return encoding; } u32 fwht_encode_frame(struct fwht_raw_frame *frm, struct fwht_raw_frame *ref_frm, struct fwht_cframe *cf, bool is_intra, bool next_is_intra, unsigned int width, unsigned int height, unsigned int stride, unsigned int chroma_stride) { unsigned int size = height * width; __be16 *rlco = cf->rlc_data; __be16 *rlco_max; u32 encoding; rlco_max = rlco + size / 2 - 256; encoding = encode_plane(frm->luma, ref_frm->luma, &rlco, rlco_max, cf, height, width, stride, frm->luma_alpha_step, is_intra, next_is_intra); if (encoding & FWHT_FRAME_UNENCODED) encoding |= FWHT_LUMA_UNENCODED; encoding &= ~FWHT_FRAME_UNENCODED; if (frm->components_num >= 3) { u32 chroma_h = height / frm->height_div; u32 chroma_w = width / frm->width_div; unsigned int chroma_size = chroma_h * chroma_w; rlco_max = rlco + chroma_size / 2 - 256; encoding |= encode_plane(frm->cb, ref_frm->cb, &rlco, rlco_max, cf, chroma_h, chroma_w, chroma_stride, frm->chroma_step, is_intra, next_is_intra); if (encoding & FWHT_FRAME_UNENCODED) encoding |= FWHT_CB_UNENCODED; encoding &= ~FWHT_FRAME_UNENCODED; rlco_max = rlco + chroma_size / 2 - 256; encoding |= encode_plane(frm->cr, ref_frm->cr, &rlco, rlco_max, cf, chroma_h, chroma_w, chroma_stride, frm->chroma_step, is_intra, next_is_intra); if (encoding & FWHT_FRAME_UNENCODED) encoding |= FWHT_CR_UNENCODED; encoding &= ~FWHT_FRAME_UNENCODED; } if (frm->components_num == 4) { rlco_max = rlco + size / 2 - 256; encoding |= encode_plane(frm->alpha, ref_frm->alpha, &rlco, rlco_max, cf, height, width, stride, frm->luma_alpha_step, is_intra, next_is_intra); if (encoding & FWHT_FRAME_UNENCODED) encoding |= FWHT_ALPHA_UNENCODED; encoding &= ~FWHT_FRAME_UNENCODED; } cf->size = (rlco - cf->rlc_data) * sizeof(*rlco); return encoding; } static bool decode_plane(struct fwht_cframe *cf, const __be16 **rlco, u32 height, u32 width, const u8 *ref, u32 ref_stride, unsigned int ref_step, u8 *dst, unsigned int dst_stride, unsigned int dst_step, bool uncompressed, const __be16 *end_of_rlco_buf) { unsigned int copies = 0; s16 copy[8 * 8]; u16 stat; unsigned int i, j; bool is_intra = !ref; width = round_up(width, 8); height = round_up(height, 8); if (uncompressed) { int i; if (end_of_rlco_buf + 1 < *rlco + width * height / 2) return false; for (i = 0; i < height; i++) { memcpy(dst, *rlco, width); dst += dst_stride; *rlco += width / 2; } return true; } /* * When decoding each macroblock the rlco pointer will be increased * by 65 * 2 bytes worst-case. * To avoid overflow the buffer has to be 65/64th of the actual raw * image size, just in case someone feeds it malicious data. */ for (j = 0; j < height / 8; j++) { for (i = 0; i < width / 8; i++) { const u8 *refp = ref + j * 8 * ref_stride + i * 8 * ref_step; u8 *dstp = dst + j * 8 * dst_stride + i * 8 * dst_step; if (copies) { memcpy(cf->de_fwht, copy, sizeof(copy)); if ((stat & PFRAME_BIT) && !is_intra) add_deltas(cf->de_fwht, refp, ref_stride, ref_step); fill_decoder_block(dstp, cf->de_fwht, dst_stride, dst_step); copies--; continue; } stat = derlc(rlco, cf->coeffs, end_of_rlco_buf); if (stat & OVERFLOW_BIT) return false; if ((stat & PFRAME_BIT) && !is_intra) dequantize_inter(cf->coeffs); else dequantize_intra(cf->coeffs); ifwht(cf->coeffs, cf->de_fwht, ((stat & PFRAME_BIT) && !is_intra) ? 0 : 1); copies = (stat & DUPS_MASK) >> 1; if (copies) memcpy(copy, cf->de_fwht, sizeof(copy)); if ((stat & PFRAME_BIT) && !is_intra) add_deltas(cf->de_fwht, refp, ref_stride, ref_step); fill_decoder_block(dstp, cf->de_fwht, dst_stride, dst_step); } } return true; } bool fwht_decode_frame(struct fwht_cframe *cf, u32 hdr_flags, unsigned int components_num, unsigned int width, unsigned int height, const struct fwht_raw_frame *ref, unsigned int ref_stride, unsigned int ref_chroma_stride, struct fwht_raw_frame *dst, unsigned int dst_stride, unsigned int dst_chroma_stride) { const __be16 *rlco = cf->rlc_data; const __be16 *end_of_rlco_buf = cf->rlc_data + (cf->size / sizeof(*rlco)) - 1; if (!decode_plane(cf, &rlco, height, width, ref->luma, ref_stride, ref->luma_alpha_step, dst->luma, dst_stride, dst->luma_alpha_step, hdr_flags & V4L2_FWHT_FL_LUMA_IS_UNCOMPRESSED, end_of_rlco_buf)) return false; if (components_num >= 3) { u32 h = height; u32 w = width; if (!(hdr_flags & V4L2_FWHT_FL_CHROMA_FULL_HEIGHT)) h /= 2; if (!(hdr_flags & V4L2_FWHT_FL_CHROMA_FULL_WIDTH)) w /= 2; if (!decode_plane(cf, &rlco, h, w, ref->cb, ref_chroma_stride, ref->chroma_step, dst->cb, dst_chroma_stride, dst->chroma_step, hdr_flags & V4L2_FWHT_FL_CB_IS_UNCOMPRESSED, end_of_rlco_buf)) return false; if (!decode_plane(cf, &rlco, h, w, ref->cr, ref_chroma_stride, ref->chroma_step, dst->cr, dst_chroma_stride, dst->chroma_step, hdr_flags & V4L2_FWHT_FL_CR_IS_UNCOMPRESSED, end_of_rlco_buf)) return false; } if (components_num == 4) if (!decode_plane(cf, &rlco, height, width, ref->alpha, ref_stride, ref->luma_alpha_step, dst->alpha, dst_stride, dst->luma_alpha_step, hdr_flags & V4L2_FWHT_FL_ALPHA_IS_UNCOMPRESSED, end_of_rlco_buf)) return false; return true; }
linux-master
drivers/media/test-drivers/vicodec/codec-fwht.c
// SPDX-License-Identifier: LGPL-2.1 /* * A V4L2 frontend for the FWHT codec * * Copyright 2018 Cisco Systems, Inc. and/or its affiliates. All rights reserved. */ #include <linux/errno.h> #include <linux/string.h> #include <linux/videodev2.h> #include "codec-v4l2-fwht.h" static const struct v4l2_fwht_pixfmt_info v4l2_fwht_pixfmts[] = { { V4L2_PIX_FMT_YUV420, 1, 3, 2, 1, 1, 2, 2, 3, 3, V4L2_FWHT_FL_PIXENC_YUV}, { V4L2_PIX_FMT_YVU420, 1, 3, 2, 1, 1, 2, 2, 3, 3, V4L2_FWHT_FL_PIXENC_YUV}, { V4L2_PIX_FMT_YUV422P, 1, 2, 1, 1, 1, 2, 1, 3, 3, V4L2_FWHT_FL_PIXENC_YUV}, { V4L2_PIX_FMT_NV12, 1, 3, 2, 1, 2, 2, 2, 3, 2, V4L2_FWHT_FL_PIXENC_YUV}, { V4L2_PIX_FMT_NV21, 1, 3, 2, 1, 2, 2, 2, 3, 2, V4L2_FWHT_FL_PIXENC_YUV}, { V4L2_PIX_FMT_NV16, 1, 2, 1, 1, 2, 2, 1, 3, 2, V4L2_FWHT_FL_PIXENC_YUV}, { V4L2_PIX_FMT_NV61, 1, 2, 1, 1, 2, 2, 1, 3, 2, V4L2_FWHT_FL_PIXENC_YUV}, { V4L2_PIX_FMT_NV24, 1, 3, 1, 1, 2, 1, 1, 3, 2, V4L2_FWHT_FL_PIXENC_YUV}, { V4L2_PIX_FMT_NV42, 1, 3, 1, 1, 2, 1, 1, 3, 2, V4L2_FWHT_FL_PIXENC_YUV}, { V4L2_PIX_FMT_YUYV, 2, 2, 1, 2, 4, 2, 1, 3, 1, V4L2_FWHT_FL_PIXENC_YUV}, { V4L2_PIX_FMT_YVYU, 2, 2, 1, 2, 4, 2, 1, 3, 1, V4L2_FWHT_FL_PIXENC_YUV}, { V4L2_PIX_FMT_UYVY, 2, 2, 1, 2, 4, 2, 1, 3, 1, V4L2_FWHT_FL_PIXENC_YUV}, { V4L2_PIX_FMT_VYUY, 2, 2, 1, 2, 4, 2, 1, 3, 1, V4L2_FWHT_FL_PIXENC_YUV}, { V4L2_PIX_FMT_BGR24, 3, 3, 1, 3, 3, 1, 1, 3, 1, V4L2_FWHT_FL_PIXENC_RGB}, { V4L2_PIX_FMT_RGB24, 3, 3, 1, 3, 3, 1, 1, 3, 1, V4L2_FWHT_FL_PIXENC_RGB}, { V4L2_PIX_FMT_HSV24, 3, 3, 1, 3, 3, 1, 1, 3, 1, V4L2_FWHT_FL_PIXENC_HSV}, { V4L2_PIX_FMT_BGR32, 4, 4, 1, 4, 4, 1, 1, 4, 1, V4L2_FWHT_FL_PIXENC_RGB}, { V4L2_PIX_FMT_XBGR32, 4, 4, 1, 4, 4, 1, 1, 4, 1, V4L2_FWHT_FL_PIXENC_RGB}, { V4L2_PIX_FMT_ABGR32, 4, 4, 1, 4, 4, 1, 1, 4, 1, V4L2_FWHT_FL_PIXENC_RGB}, { V4L2_PIX_FMT_RGB32, 4, 4, 1, 4, 4, 1, 1, 4, 1, V4L2_FWHT_FL_PIXENC_RGB}, { V4L2_PIX_FMT_XRGB32, 4, 4, 1, 4, 4, 1, 1, 4, 1, V4L2_FWHT_FL_PIXENC_RGB}, { V4L2_PIX_FMT_ARGB32, 4, 4, 1, 4, 4, 1, 1, 4, 1, V4L2_FWHT_FL_PIXENC_RGB}, { V4L2_PIX_FMT_BGRX32, 4, 4, 1, 4, 4, 1, 1, 4, 1, V4L2_FWHT_FL_PIXENC_RGB}, { V4L2_PIX_FMT_BGRA32, 4, 4, 1, 4, 4, 1, 1, 4, 1, V4L2_FWHT_FL_PIXENC_RGB}, { V4L2_PIX_FMT_RGBX32, 4, 4, 1, 4, 4, 1, 1, 4, 1, V4L2_FWHT_FL_PIXENC_RGB}, { V4L2_PIX_FMT_RGBA32, 4, 4, 1, 4, 4, 1, 1, 4, 1, V4L2_FWHT_FL_PIXENC_RGB}, { V4L2_PIX_FMT_HSV32, 4, 4, 1, 4, 4, 1, 1, 4, 1, V4L2_FWHT_FL_PIXENC_HSV}, { V4L2_PIX_FMT_GREY, 1, 1, 1, 1, 0, 1, 1, 1, 1, V4L2_FWHT_FL_PIXENC_RGB}, }; bool v4l2_fwht_validate_fmt(const struct v4l2_fwht_pixfmt_info *info, u32 width_div, u32 height_div, u32 components_num, u32 pixenc) { if (info->width_div == width_div && info->height_div == height_div && (!pixenc || info->pixenc == pixenc) && info->components_num == components_num) return true; return false; } const struct v4l2_fwht_pixfmt_info *v4l2_fwht_find_nth_fmt(u32 width_div, u32 height_div, u32 components_num, u32 pixenc, unsigned int start_idx) { unsigned int i; for (i = 0; i < ARRAY_SIZE(v4l2_fwht_pixfmts); i++) { bool is_valid = v4l2_fwht_validate_fmt(&v4l2_fwht_pixfmts[i], width_div, height_div, components_num, pixenc); if (is_valid) { if (start_idx == 0) return v4l2_fwht_pixfmts + i; start_idx--; } } return NULL; } const struct v4l2_fwht_pixfmt_info *v4l2_fwht_find_pixfmt(u32 pixelformat) { unsigned int i; for (i = 0; i < ARRAY_SIZE(v4l2_fwht_pixfmts); i++) if (v4l2_fwht_pixfmts[i].id == pixelformat) return v4l2_fwht_pixfmts + i; return NULL; } const struct v4l2_fwht_pixfmt_info *v4l2_fwht_get_pixfmt(u32 idx) { if (idx >= ARRAY_SIZE(v4l2_fwht_pixfmts)) return NULL; return v4l2_fwht_pixfmts + idx; } static int prepare_raw_frame(struct fwht_raw_frame *rf, const struct v4l2_fwht_pixfmt_info *info, u8 *buf, unsigned int size) { rf->luma = buf; rf->width_div = info->width_div; rf->height_div = info->height_div; rf->luma_alpha_step = info->luma_alpha_step; rf->chroma_step = info->chroma_step; rf->alpha = NULL; rf->components_num = info->components_num; /* * The buffer is NULL if it is the reference * frame of an I-frame in the stateless decoder */ if (!buf) { rf->luma = NULL; rf->cb = NULL; rf->cr = NULL; rf->alpha = NULL; return 0; } switch (info->id) { case V4L2_PIX_FMT_GREY: rf->cb = NULL; rf->cr = NULL; break; case V4L2_PIX_FMT_YUV420: rf->cb = rf->luma + size; rf->cr = rf->cb + size / 4; break; case V4L2_PIX_FMT_YVU420: rf->cr = rf->luma + size; rf->cb = rf->cr + size / 4; break; case V4L2_PIX_FMT_YUV422P: rf->cb = rf->luma + size; rf->cr = rf->cb + size / 2; break; case V4L2_PIX_FMT_NV12: case V4L2_PIX_FMT_NV16: case V4L2_PIX_FMT_NV24: rf->cb = rf->luma + size; rf->cr = rf->cb + 1; break; case V4L2_PIX_FMT_NV21: case V4L2_PIX_FMT_NV61: case V4L2_PIX_FMT_NV42: rf->cr = rf->luma + size; rf->cb = rf->cr + 1; break; case V4L2_PIX_FMT_YUYV: rf->cb = rf->luma + 1; rf->cr = rf->cb + 2; break; case V4L2_PIX_FMT_YVYU: rf->cr = rf->luma + 1; rf->cb = rf->cr + 2; break; case V4L2_PIX_FMT_UYVY: rf->cb = rf->luma; rf->cr = rf->cb + 2; rf->luma++; break; case V4L2_PIX_FMT_VYUY: rf->cr = rf->luma; rf->cb = rf->cr + 2; rf->luma++; break; case V4L2_PIX_FMT_RGB24: case V4L2_PIX_FMT_HSV24: rf->cr = rf->luma; rf->cb = rf->cr + 2; rf->luma++; break; case V4L2_PIX_FMT_BGR24: rf->cb = rf->luma; rf->cr = rf->cb + 2; rf->luma++; break; case V4L2_PIX_FMT_RGB32: case V4L2_PIX_FMT_XRGB32: case V4L2_PIX_FMT_HSV32: case V4L2_PIX_FMT_ARGB32: rf->alpha = rf->luma; rf->cr = rf->luma + 1; rf->cb = rf->cr + 2; rf->luma += 2; break; case V4L2_PIX_FMT_BGR32: case V4L2_PIX_FMT_XBGR32: case V4L2_PIX_FMT_ABGR32: rf->cb = rf->luma; rf->cr = rf->cb + 2; rf->luma++; rf->alpha = rf->cr + 1; break; case V4L2_PIX_FMT_BGRX32: case V4L2_PIX_FMT_BGRA32: rf->alpha = rf->luma; rf->cb = rf->luma + 1; rf->cr = rf->cb + 2; rf->luma += 2; break; case V4L2_PIX_FMT_RGBX32: case V4L2_PIX_FMT_RGBA32: rf->alpha = rf->luma + 3; rf->cr = rf->luma; rf->cb = rf->cr + 2; rf->luma++; break; default: return -EINVAL; } return 0; } int v4l2_fwht_encode(struct v4l2_fwht_state *state, u8 *p_in, u8 *p_out) { unsigned int size = state->stride * state->coded_height; unsigned int chroma_stride = state->stride; const struct v4l2_fwht_pixfmt_info *info = state->info; struct fwht_cframe_hdr *p_hdr; struct fwht_cframe cf; struct fwht_raw_frame rf; u32 encoding; u32 flags = 0; if (!info) return -EINVAL; if (prepare_raw_frame(&rf, info, p_in, size)) return -EINVAL; if (info->planes_num == 3) chroma_stride /= 2; if (info->id == V4L2_PIX_FMT_NV24 || info->id == V4L2_PIX_FMT_NV42) chroma_stride *= 2; cf.i_frame_qp = state->i_frame_qp; cf.p_frame_qp = state->p_frame_qp; cf.rlc_data = (__be16 *)(p_out + sizeof(*p_hdr)); encoding = fwht_encode_frame(&rf, &state->ref_frame, &cf, !state->gop_cnt, state->gop_cnt == state->gop_size - 1, state->visible_width, state->visible_height, state->stride, chroma_stride); if (!(encoding & FWHT_FRAME_PCODED)) state->gop_cnt = 0; if (++state->gop_cnt >= state->gop_size) state->gop_cnt = 0; p_hdr = (struct fwht_cframe_hdr *)p_out; p_hdr->magic1 = FWHT_MAGIC1; p_hdr->magic2 = FWHT_MAGIC2; p_hdr->version = htonl(V4L2_FWHT_VERSION); p_hdr->width = htonl(state->visible_width); p_hdr->height = htonl(state->visible_height); flags |= (info->components_num - 1) << V4L2_FWHT_FL_COMPONENTS_NUM_OFFSET; flags |= info->pixenc; if (encoding & FWHT_LUMA_UNENCODED) flags |= V4L2_FWHT_FL_LUMA_IS_UNCOMPRESSED; if (encoding & FWHT_CB_UNENCODED) flags |= V4L2_FWHT_FL_CB_IS_UNCOMPRESSED; if (encoding & FWHT_CR_UNENCODED) flags |= V4L2_FWHT_FL_CR_IS_UNCOMPRESSED; if (encoding & FWHT_ALPHA_UNENCODED) flags |= V4L2_FWHT_FL_ALPHA_IS_UNCOMPRESSED; if (!(encoding & FWHT_FRAME_PCODED)) flags |= V4L2_FWHT_FL_I_FRAME; if (rf.height_div == 1) flags |= V4L2_FWHT_FL_CHROMA_FULL_HEIGHT; if (rf.width_div == 1) flags |= V4L2_FWHT_FL_CHROMA_FULL_WIDTH; p_hdr->flags = htonl(flags); p_hdr->colorspace = htonl(state->colorspace); p_hdr->xfer_func = htonl(state->xfer_func); p_hdr->ycbcr_enc = htonl(state->ycbcr_enc); p_hdr->quantization = htonl(state->quantization); p_hdr->size = htonl(cf.size); return cf.size + sizeof(*p_hdr); } int v4l2_fwht_decode(struct v4l2_fwht_state *state, u8 *p_in, u8 *p_out) { u32 flags; struct fwht_cframe cf; unsigned int components_num = 3; unsigned int version; const struct v4l2_fwht_pixfmt_info *info; unsigned int hdr_width_div, hdr_height_div; struct fwht_raw_frame dst_rf; unsigned int dst_chroma_stride = state->stride; unsigned int ref_chroma_stride = state->ref_stride; unsigned int dst_size = state->stride * state->coded_height; unsigned int ref_size; if (!state->info) return -EINVAL; info = state->info; version = ntohl(state->header.version); if (!version || version > V4L2_FWHT_VERSION) { pr_err("version %d is not supported, current version is %d\n", version, V4L2_FWHT_VERSION); return -EINVAL; } if (state->header.magic1 != FWHT_MAGIC1 || state->header.magic2 != FWHT_MAGIC2) return -EINVAL; /* TODO: support resolution changes */ if (ntohl(state->header.width) != state->visible_width || ntohl(state->header.height) != state->visible_height) return -EINVAL; flags = ntohl(state->header.flags); if (version >= 2) { if ((flags & V4L2_FWHT_FL_PIXENC_MSK) != info->pixenc) return -EINVAL; components_num = 1 + ((flags & V4L2_FWHT_FL_COMPONENTS_NUM_MSK) >> V4L2_FWHT_FL_COMPONENTS_NUM_OFFSET); } if (components_num != info->components_num) return -EINVAL; state->colorspace = ntohl(state->header.colorspace); state->xfer_func = ntohl(state->header.xfer_func); state->ycbcr_enc = ntohl(state->header.ycbcr_enc); state->quantization = ntohl(state->header.quantization); cf.rlc_data = (__be16 *)p_in; cf.size = ntohl(state->header.size); hdr_width_div = (flags & V4L2_FWHT_FL_CHROMA_FULL_WIDTH) ? 1 : 2; hdr_height_div = (flags & V4L2_FWHT_FL_CHROMA_FULL_HEIGHT) ? 1 : 2; if (hdr_width_div != info->width_div || hdr_height_div != info->height_div) return -EINVAL; if (prepare_raw_frame(&dst_rf, info, p_out, dst_size)) return -EINVAL; if (info->planes_num == 3) { dst_chroma_stride /= 2; ref_chroma_stride /= 2; } if (info->id == V4L2_PIX_FMT_NV24 || info->id == V4L2_PIX_FMT_NV42) { dst_chroma_stride *= 2; ref_chroma_stride *= 2; } ref_size = state->ref_stride * state->coded_height; if (prepare_raw_frame(&state->ref_frame, info, state->ref_frame.buf, ref_size)) return -EINVAL; if (!fwht_decode_frame(&cf, flags, components_num, state->visible_width, state->visible_height, &state->ref_frame, state->ref_stride, ref_chroma_stride, &dst_rf, state->stride, dst_chroma_stride)) return -EINVAL; return 0; }
linux-master
drivers/media/test-drivers/vicodec/codec-v4l2-fwht.c
// SPDX-License-Identifier: GPL-2.0-only /* * A virtual codec example device. * * Copyright 2018 Cisco Systems, Inc. and/or its affiliates. All rights reserved. * * This is a virtual codec device driver for testing the codec framework. * It simulates a device that uses memory buffers for both source and * destination and encodes or decodes the data. */ #include <linux/module.h> #include <linux/delay.h> #include <linux/fs.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/platform_device.h> #include <media/v4l2-mem2mem.h> #include <media/v4l2-device.h> #include <media/v4l2-ioctl.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-event.h> #include <media/videobuf2-vmalloc.h> #include "codec-v4l2-fwht.h" MODULE_DESCRIPTION("Virtual codec device"); MODULE_AUTHOR("Hans Verkuil <[email protected]>"); MODULE_LICENSE("GPL v2"); static bool multiplanar; module_param(multiplanar, bool, 0444); MODULE_PARM_DESC(multiplanar, " use multi-planar API instead of single-planar API"); static unsigned int debug; module_param(debug, uint, 0644); MODULE_PARM_DESC(debug, " activates debug info"); #define VICODEC_NAME "vicodec" #define MAX_WIDTH 4096U #define MIN_WIDTH 640U #define MAX_HEIGHT 2160U #define MIN_HEIGHT 360U #define dprintk(dev, fmt, arg...) \ v4l2_dbg(1, debug, &dev->v4l2_dev, "%s: " fmt, __func__, ## arg) struct pixfmt_info { u32 id; unsigned int bytesperline_mult; unsigned int sizeimage_mult; unsigned int sizeimage_div; unsigned int luma_step; unsigned int chroma_step; /* Chroma plane subsampling */ unsigned int width_div; unsigned int height_div; }; static const struct v4l2_fwht_pixfmt_info pixfmt_fwht = { V4L2_PIX_FMT_FWHT, 0, 3, 1, 1, 1, 1, 1, 0, 1 }; static const struct v4l2_fwht_pixfmt_info pixfmt_stateless_fwht = { V4L2_PIX_FMT_FWHT_STATELESS, 0, 3, 1, 1, 1, 1, 1, 0, 1 }; static void vicodec_dev_release(struct device *dev) { } static struct platform_device vicodec_pdev = { .name = VICODEC_NAME, .dev.release = vicodec_dev_release, }; /* Per-queue, driver-specific private data */ struct vicodec_q_data { unsigned int coded_width; unsigned int coded_height; unsigned int visible_width; unsigned int visible_height; unsigned int sizeimage; unsigned int vb2_sizeimage; unsigned int sequence; const struct v4l2_fwht_pixfmt_info *info; }; enum { V4L2_M2M_SRC = 0, V4L2_M2M_DST = 1, }; struct vicodec_dev_instance { struct video_device vfd; struct mutex mutex; spinlock_t lock; struct v4l2_m2m_dev *m2m_dev; }; struct vicodec_dev { struct v4l2_device v4l2_dev; struct vicodec_dev_instance stateful_enc; struct vicodec_dev_instance stateful_dec; struct vicodec_dev_instance stateless_dec; #ifdef CONFIG_MEDIA_CONTROLLER struct media_device mdev; #endif }; struct vicodec_ctx { struct v4l2_fh fh; struct vicodec_dev *dev; bool is_enc; bool is_stateless; spinlock_t *lock; struct v4l2_ctrl_handler hdl; /* Source and destination queue data */ struct vicodec_q_data q_data[2]; struct v4l2_fwht_state state; u32 cur_buf_offset; u32 comp_max_size; u32 comp_size; u32 header_size; u32 comp_magic_cnt; bool comp_has_frame; bool comp_has_next_frame; bool first_source_change_sent; bool source_changed; }; static const struct v4l2_event vicodec_eos_event = { .type = V4L2_EVENT_EOS }; static inline struct vicodec_ctx *file2ctx(struct file *file) { return container_of(file->private_data, struct vicodec_ctx, fh); } static struct vicodec_q_data *get_q_data(struct vicodec_ctx *ctx, enum v4l2_buf_type type) { switch (type) { case V4L2_BUF_TYPE_VIDEO_OUTPUT: case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE: return &ctx->q_data[V4L2_M2M_SRC]; case V4L2_BUF_TYPE_VIDEO_CAPTURE: case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE: return &ctx->q_data[V4L2_M2M_DST]; default: break; } return NULL; } static void copy_cap_to_ref(const u8 *cap, const struct v4l2_fwht_pixfmt_info *info, struct v4l2_fwht_state *state) { int plane_idx; u8 *p_ref = state->ref_frame.buf; unsigned int cap_stride = state->stride; unsigned int ref_stride = state->ref_stride; for (plane_idx = 0; plane_idx < info->planes_num; plane_idx++) { int i; unsigned int h_div = (plane_idx == 1 || plane_idx == 2) ? info->height_div : 1; const u8 *row_cap = cap; u8 *row_ref = p_ref; if (info->planes_num == 3 && plane_idx == 1) { cap_stride /= 2; ref_stride /= 2; } if (plane_idx == 1 && (info->id == V4L2_PIX_FMT_NV24 || info->id == V4L2_PIX_FMT_NV42)) { cap_stride *= 2; ref_stride *= 2; } for (i = 0; i < state->visible_height / h_div; i++) { memcpy(row_ref, row_cap, ref_stride); row_ref += ref_stride; row_cap += cap_stride; } cap += cap_stride * (state->coded_height / h_div); p_ref += ref_stride * (state->coded_height / h_div); } } static bool validate_by_version(unsigned int flags, unsigned int version) { if (!version || version > V4L2_FWHT_VERSION) return false; if (version >= 2) { unsigned int components_num = 1 + ((flags & V4L2_FWHT_FL_COMPONENTS_NUM_MSK) >> V4L2_FWHT_FL_COMPONENTS_NUM_OFFSET); unsigned int pixenc = flags & V4L2_FWHT_FL_PIXENC_MSK; if (components_num == 0 || components_num > 4 || !pixenc) return false; } return true; } static bool validate_stateless_params_flags(const struct v4l2_ctrl_fwht_params *params, const struct v4l2_fwht_pixfmt_info *cur_info) { unsigned int width_div = (params->flags & V4L2_FWHT_FL_CHROMA_FULL_WIDTH) ? 1 : 2; unsigned int height_div = (params->flags & V4L2_FWHT_FL_CHROMA_FULL_HEIGHT) ? 1 : 2; unsigned int components_num = 3; unsigned int pixenc = 0; if (params->version < 3) return false; components_num = 1 + ((params->flags & V4L2_FWHT_FL_COMPONENTS_NUM_MSK) >> V4L2_FWHT_FL_COMPONENTS_NUM_OFFSET); pixenc = (params->flags & V4L2_FWHT_FL_PIXENC_MSK); if (v4l2_fwht_validate_fmt(cur_info, width_div, height_div, components_num, pixenc)) return true; return false; } static void update_state_from_header(struct vicodec_ctx *ctx) { const struct fwht_cframe_hdr *p_hdr = &ctx->state.header; ctx->state.visible_width = ntohl(p_hdr->width); ctx->state.visible_height = ntohl(p_hdr->height); ctx->state.colorspace = ntohl(p_hdr->colorspace); ctx->state.xfer_func = ntohl(p_hdr->xfer_func); ctx->state.ycbcr_enc = ntohl(p_hdr->ycbcr_enc); ctx->state.quantization = ntohl(p_hdr->quantization); } static int device_process(struct vicodec_ctx *ctx, struct vb2_v4l2_buffer *src_vb, struct vb2_v4l2_buffer *dst_vb) { struct vicodec_dev *dev = ctx->dev; struct v4l2_fwht_state *state = &ctx->state; u8 *p_src, *p_dst; int ret = 0; if (ctx->is_enc || ctx->is_stateless) p_src = vb2_plane_vaddr(&src_vb->vb2_buf, 0); else p_src = state->compressed_frame; if (ctx->is_stateless) { struct media_request *src_req = src_vb->vb2_buf.req_obj.req; ret = v4l2_ctrl_request_setup(src_req, &ctx->hdl); if (ret) return ret; update_state_from_header(ctx); ctx->state.header.size = htonl(vb2_get_plane_payload(&src_vb->vb2_buf, 0)); /* * set the reference buffer from the reference timestamp * only if this is a P-frame */ if (!(ntohl(ctx->state.header.flags) & V4L2_FWHT_FL_I_FRAME)) { struct vb2_buffer *ref_vb2_buf; struct vb2_queue *vq_cap = v4l2_m2m_get_vq(ctx->fh.m2m_ctx, V4L2_BUF_TYPE_VIDEO_CAPTURE); ref_vb2_buf = vb2_find_buffer(vq_cap, ctx->state.ref_frame_ts); if (!ref_vb2_buf) return -EINVAL; if (ref_vb2_buf->state == VB2_BUF_STATE_ERROR) ret = -EINVAL; ctx->state.ref_frame.buf = vb2_plane_vaddr(ref_vb2_buf, 0); } else { ctx->state.ref_frame.buf = NULL; } } p_dst = vb2_plane_vaddr(&dst_vb->vb2_buf, 0); if (!p_src || !p_dst) { v4l2_err(&dev->v4l2_dev, "Acquiring kernel pointers to buffers failed\n"); return -EFAULT; } if (ctx->is_enc) { struct vicodec_q_data *q_src; int comp_sz_or_errcode; q_src = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_OUTPUT); state->info = q_src->info; comp_sz_or_errcode = v4l2_fwht_encode(state, p_src, p_dst); if (comp_sz_or_errcode < 0) return comp_sz_or_errcode; vb2_set_plane_payload(&dst_vb->vb2_buf, 0, comp_sz_or_errcode); } else { struct vicodec_q_data *q_dst; unsigned int comp_frame_size = ntohl(ctx->state.header.size); q_dst = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_CAPTURE); if (comp_frame_size > ctx->comp_max_size) return -EINVAL; state->info = q_dst->info; ret = v4l2_fwht_decode(state, p_src, p_dst); if (ret < 0) return ret; if (!ctx->is_stateless) copy_cap_to_ref(p_dst, ctx->state.info, &ctx->state); vb2_set_plane_payload(&dst_vb->vb2_buf, 0, q_dst->sizeimage); if (ntohl(ctx->state.header.flags) & V4L2_FWHT_FL_I_FRAME) dst_vb->flags |= V4L2_BUF_FLAG_KEYFRAME; else dst_vb->flags |= V4L2_BUF_FLAG_PFRAME; } return ret; } /* * mem2mem callbacks */ static enum vb2_buffer_state get_next_header(struct vicodec_ctx *ctx, u8 **pp, u32 sz) { static const u8 magic[] = { 0x4f, 0x4f, 0x4f, 0x4f, 0xff, 0xff, 0xff, 0xff }; u8 *p = *pp; u32 state; u8 *header = (u8 *)&ctx->state.header; state = VB2_BUF_STATE_DONE; if (!ctx->header_size) { state = VB2_BUF_STATE_ERROR; for (; p < *pp + sz; p++) { u32 copy; p = memchr(p, magic[ctx->comp_magic_cnt], *pp + sz - p); if (!p) { ctx->comp_magic_cnt = 0; p = *pp + sz; break; } copy = sizeof(magic) - ctx->comp_magic_cnt; if (*pp + sz - p < copy) copy = *pp + sz - p; memcpy(header + ctx->comp_magic_cnt, p, copy); ctx->comp_magic_cnt += copy; if (!memcmp(header, magic, ctx->comp_magic_cnt)) { p += copy; state = VB2_BUF_STATE_DONE; break; } ctx->comp_magic_cnt = 0; } if (ctx->comp_magic_cnt < sizeof(magic)) { *pp = p; return state; } ctx->header_size = sizeof(magic); } if (ctx->header_size < sizeof(struct fwht_cframe_hdr)) { u32 copy = sizeof(struct fwht_cframe_hdr) - ctx->header_size; if (*pp + sz - p < copy) copy = *pp + sz - p; memcpy(header + ctx->header_size, p, copy); p += copy; ctx->header_size += copy; } *pp = p; return state; } /* device_run() - prepares and starts the device */ static void device_run(void *priv) { struct vicodec_ctx *ctx = priv; struct vicodec_dev *dev = ctx->dev; struct vb2_v4l2_buffer *src_buf, *dst_buf; struct vicodec_q_data *q_src, *q_dst; u32 state; struct media_request *src_req; src_buf = v4l2_m2m_next_src_buf(ctx->fh.m2m_ctx); dst_buf = v4l2_m2m_dst_buf_remove(ctx->fh.m2m_ctx); src_req = src_buf->vb2_buf.req_obj.req; q_src = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_OUTPUT); q_dst = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_CAPTURE); state = VB2_BUF_STATE_DONE; if (device_process(ctx, src_buf, dst_buf)) state = VB2_BUF_STATE_ERROR; else dst_buf->sequence = q_dst->sequence++; dst_buf->flags &= ~V4L2_BUF_FLAG_LAST; v4l2_m2m_buf_copy_metadata(src_buf, dst_buf, false); spin_lock(ctx->lock); if (!ctx->comp_has_next_frame && v4l2_m2m_is_last_draining_src_buf(ctx->fh.m2m_ctx, src_buf)) { dst_buf->flags |= V4L2_BUF_FLAG_LAST; v4l2_event_queue_fh(&ctx->fh, &vicodec_eos_event); v4l2_m2m_mark_stopped(ctx->fh.m2m_ctx); } if (ctx->is_enc || ctx->is_stateless) { src_buf->sequence = q_src->sequence++; src_buf = v4l2_m2m_src_buf_remove(ctx->fh.m2m_ctx); v4l2_m2m_buf_done(src_buf, state); } else if (vb2_get_plane_payload(&src_buf->vb2_buf, 0) == ctx->cur_buf_offset) { src_buf->sequence = q_src->sequence++; src_buf = v4l2_m2m_src_buf_remove(ctx->fh.m2m_ctx); v4l2_m2m_buf_done(src_buf, state); ctx->cur_buf_offset = 0; ctx->comp_has_next_frame = false; } v4l2_m2m_buf_done(dst_buf, state); ctx->comp_size = 0; ctx->header_size = 0; ctx->comp_magic_cnt = 0; ctx->comp_has_frame = false; spin_unlock(ctx->lock); if (ctx->is_stateless && src_req) v4l2_ctrl_request_complete(src_req, &ctx->hdl); if (ctx->is_enc) v4l2_m2m_job_finish(dev->stateful_enc.m2m_dev, ctx->fh.m2m_ctx); else if (ctx->is_stateless) v4l2_m2m_job_finish(dev->stateless_dec.m2m_dev, ctx->fh.m2m_ctx); else v4l2_m2m_job_finish(dev->stateful_dec.m2m_dev, ctx->fh.m2m_ctx); } static void job_remove_src_buf(struct vicodec_ctx *ctx, u32 state) { struct vb2_v4l2_buffer *src_buf; struct vicodec_q_data *q_src; q_src = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_OUTPUT); spin_lock(ctx->lock); src_buf = v4l2_m2m_src_buf_remove(ctx->fh.m2m_ctx); src_buf->sequence = q_src->sequence++; v4l2_m2m_buf_done(src_buf, state); ctx->cur_buf_offset = 0; spin_unlock(ctx->lock); } static const struct v4l2_fwht_pixfmt_info * info_from_header(const struct fwht_cframe_hdr *p_hdr) { unsigned int flags = ntohl(p_hdr->flags); unsigned int width_div = (flags & V4L2_FWHT_FL_CHROMA_FULL_WIDTH) ? 1 : 2; unsigned int height_div = (flags & V4L2_FWHT_FL_CHROMA_FULL_HEIGHT) ? 1 : 2; unsigned int components_num = 3; unsigned int pixenc = 0; unsigned int version = ntohl(p_hdr->version); if (version >= 2) { components_num = 1 + ((flags & V4L2_FWHT_FL_COMPONENTS_NUM_MSK) >> V4L2_FWHT_FL_COMPONENTS_NUM_OFFSET); pixenc = (flags & V4L2_FWHT_FL_PIXENC_MSK); } return v4l2_fwht_find_nth_fmt(width_div, height_div, components_num, pixenc, 0); } static bool is_header_valid(const struct fwht_cframe_hdr *p_hdr) { const struct v4l2_fwht_pixfmt_info *info; unsigned int w = ntohl(p_hdr->width); unsigned int h = ntohl(p_hdr->height); unsigned int version = ntohl(p_hdr->version); unsigned int flags = ntohl(p_hdr->flags); if (w < MIN_WIDTH || w > MAX_WIDTH || h < MIN_HEIGHT || h > MAX_HEIGHT) return false; if (!validate_by_version(flags, version)) return false; info = info_from_header(p_hdr); if (!info) return false; return true; } static void update_capture_data_from_header(struct vicodec_ctx *ctx) { struct vicodec_q_data *q_dst = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_CAPTURE); const struct fwht_cframe_hdr *p_hdr = &ctx->state.header; const struct v4l2_fwht_pixfmt_info *info = info_from_header(p_hdr); unsigned int flags = ntohl(p_hdr->flags); unsigned int hdr_width_div = (flags & V4L2_FWHT_FL_CHROMA_FULL_WIDTH) ? 1 : 2; unsigned int hdr_height_div = (flags & V4L2_FWHT_FL_CHROMA_FULL_HEIGHT) ? 1 : 2; /* * This function should not be used by a stateless codec since * it changes values in q_data that are not request specific */ WARN_ON(ctx->is_stateless); q_dst->info = info; q_dst->visible_width = ntohl(p_hdr->width); q_dst->visible_height = ntohl(p_hdr->height); q_dst->coded_width = vic_round_dim(q_dst->visible_width, hdr_width_div); q_dst->coded_height = vic_round_dim(q_dst->visible_height, hdr_height_div); q_dst->sizeimage = q_dst->coded_width * q_dst->coded_height * q_dst->info->sizeimage_mult / q_dst->info->sizeimage_div; ctx->state.colorspace = ntohl(p_hdr->colorspace); ctx->state.xfer_func = ntohl(p_hdr->xfer_func); ctx->state.ycbcr_enc = ntohl(p_hdr->ycbcr_enc); ctx->state.quantization = ntohl(p_hdr->quantization); } static void set_last_buffer(struct vb2_v4l2_buffer *dst_buf, const struct vb2_v4l2_buffer *src_buf, struct vicodec_ctx *ctx) { struct vicodec_q_data *q_dst = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_CAPTURE); vb2_set_plane_payload(&dst_buf->vb2_buf, 0, 0); dst_buf->sequence = q_dst->sequence++; v4l2_m2m_buf_copy_metadata(src_buf, dst_buf, !ctx->is_enc); dst_buf->flags |= V4L2_BUF_FLAG_LAST; v4l2_m2m_buf_done(dst_buf, VB2_BUF_STATE_DONE); } static int job_ready(void *priv) { static const u8 magic[] = { 0x4f, 0x4f, 0x4f, 0x4f, 0xff, 0xff, 0xff, 0xff }; struct vicodec_ctx *ctx = priv; struct vb2_v4l2_buffer *src_buf; u8 *p_src; u8 *p; u32 sz; u32 state; struct vicodec_q_data *q_dst = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_CAPTURE); unsigned int flags; unsigned int hdr_width_div; unsigned int hdr_height_div; unsigned int max_to_copy; unsigned int comp_frame_size; if (ctx->source_changed) return 0; if (ctx->is_stateless || ctx->is_enc || ctx->comp_has_frame) return 1; restart: ctx->comp_has_next_frame = false; src_buf = v4l2_m2m_next_src_buf(ctx->fh.m2m_ctx); if (!src_buf) return 0; p_src = vb2_plane_vaddr(&src_buf->vb2_buf, 0); sz = vb2_get_plane_payload(&src_buf->vb2_buf, 0); p = p_src + ctx->cur_buf_offset; state = VB2_BUF_STATE_DONE; if (ctx->header_size < sizeof(struct fwht_cframe_hdr)) { state = get_next_header(ctx, &p, p_src + sz - p); if (ctx->header_size < sizeof(struct fwht_cframe_hdr)) { if (v4l2_m2m_is_last_draining_src_buf(ctx->fh.m2m_ctx, src_buf)) return 1; job_remove_src_buf(ctx, state); goto restart; } } comp_frame_size = ntohl(ctx->state.header.size); /* * The current scanned frame might be the first frame of a new * resolution so its size might be larger than ctx->comp_max_size. * In that case it is copied up to the current buffer capacity and * the copy will continue after allocating new large enough buffer * when restreaming */ max_to_copy = min(comp_frame_size, ctx->comp_max_size); if (ctx->comp_size < max_to_copy) { u32 copy = max_to_copy - ctx->comp_size; if (copy > p_src + sz - p) copy = p_src + sz - p; memcpy(ctx->state.compressed_frame + ctx->comp_size, p, copy); p += copy; ctx->comp_size += copy; if (ctx->comp_size < max_to_copy) { if (v4l2_m2m_is_last_draining_src_buf(ctx->fh.m2m_ctx, src_buf)) return 1; job_remove_src_buf(ctx, state); goto restart; } } ctx->cur_buf_offset = p - p_src; if (ctx->comp_size == comp_frame_size) ctx->comp_has_frame = true; ctx->comp_has_next_frame = false; if (ctx->comp_has_frame && sz - ctx->cur_buf_offset >= sizeof(struct fwht_cframe_hdr)) { struct fwht_cframe_hdr *p_hdr = (struct fwht_cframe_hdr *)p; u32 frame_size = ntohl(p_hdr->size); u32 remaining = sz - ctx->cur_buf_offset - sizeof(*p_hdr); if (!memcmp(p, magic, sizeof(magic))) ctx->comp_has_next_frame = remaining >= frame_size; } /* * if the header is invalid the device_run will just drop the frame * with an error */ if (!is_header_valid(&ctx->state.header) && ctx->comp_has_frame) return 1; flags = ntohl(ctx->state.header.flags); hdr_width_div = (flags & V4L2_FWHT_FL_CHROMA_FULL_WIDTH) ? 1 : 2; hdr_height_div = (flags & V4L2_FWHT_FL_CHROMA_FULL_HEIGHT) ? 1 : 2; if (ntohl(ctx->state.header.width) != q_dst->visible_width || ntohl(ctx->state.header.height) != q_dst->visible_height || !q_dst->info || hdr_width_div != q_dst->info->width_div || hdr_height_div != q_dst->info->height_div) { static const struct v4l2_event rs_event = { .type = V4L2_EVENT_SOURCE_CHANGE, .u.src_change.changes = V4L2_EVENT_SRC_CH_RESOLUTION, }; struct vb2_v4l2_buffer *dst_buf = v4l2_m2m_dst_buf_remove(ctx->fh.m2m_ctx); update_capture_data_from_header(ctx); v4l2_event_queue_fh(&ctx->fh, &rs_event); set_last_buffer(dst_buf, src_buf, ctx); ctx->source_changed = true; return 0; } return 1; } /* * video ioctls */ static const struct v4l2_fwht_pixfmt_info *find_fmt(u32 fmt) { const struct v4l2_fwht_pixfmt_info *info = v4l2_fwht_find_pixfmt(fmt); if (!info) info = v4l2_fwht_get_pixfmt(0); return info; } static int vidioc_querycap(struct file *file, void *priv, struct v4l2_capability *cap) { strscpy(cap->driver, VICODEC_NAME, sizeof(cap->driver)); strscpy(cap->card, VICODEC_NAME, sizeof(cap->card)); snprintf(cap->bus_info, sizeof(cap->bus_info), "platform:%s", VICODEC_NAME); return 0; } static int enum_fmt(struct v4l2_fmtdesc *f, struct vicodec_ctx *ctx, bool is_out) { bool is_uncomp = (ctx->is_enc && is_out) || (!ctx->is_enc && !is_out); if (V4L2_TYPE_IS_MULTIPLANAR(f->type) && !multiplanar) return -EINVAL; if (!V4L2_TYPE_IS_MULTIPLANAR(f->type) && multiplanar) return -EINVAL; if (is_uncomp) { const struct v4l2_fwht_pixfmt_info *info = get_q_data(ctx, f->type)->info; if (ctx->is_enc || !vb2_is_streaming(&ctx->fh.m2m_ctx->cap_q_ctx.q)) info = v4l2_fwht_get_pixfmt(f->index); else info = v4l2_fwht_find_nth_fmt(info->width_div, info->height_div, info->components_num, info->pixenc, f->index); if (!info) return -EINVAL; f->pixelformat = info->id; } else { if (f->index) return -EINVAL; f->pixelformat = ctx->is_stateless ? V4L2_PIX_FMT_FWHT_STATELESS : V4L2_PIX_FMT_FWHT; if (!ctx->is_enc && !ctx->is_stateless) f->flags = V4L2_FMT_FLAG_DYN_RESOLUTION | V4L2_FMT_FLAG_CONTINUOUS_BYTESTREAM; } return 0; } static int vidioc_enum_fmt_vid_cap(struct file *file, void *priv, struct v4l2_fmtdesc *f) { struct vicodec_ctx *ctx = file2ctx(file); return enum_fmt(f, ctx, false); } static int vidioc_enum_fmt_vid_out(struct file *file, void *priv, struct v4l2_fmtdesc *f) { struct vicodec_ctx *ctx = file2ctx(file); return enum_fmt(f, ctx, true); } static int vidioc_g_fmt(struct vicodec_ctx *ctx, struct v4l2_format *f) { struct vb2_queue *vq; struct vicodec_q_data *q_data; struct v4l2_pix_format_mplane *pix_mp; struct v4l2_pix_format *pix; const struct v4l2_fwht_pixfmt_info *info; vq = v4l2_m2m_get_vq(ctx->fh.m2m_ctx, f->type); if (!vq) return -EINVAL; q_data = get_q_data(ctx, f->type); info = q_data->info; switch (f->type) { case V4L2_BUF_TYPE_VIDEO_CAPTURE: case V4L2_BUF_TYPE_VIDEO_OUTPUT: if (multiplanar) return -EINVAL; pix = &f->fmt.pix; pix->width = q_data->coded_width; pix->height = q_data->coded_height; pix->field = V4L2_FIELD_NONE; pix->pixelformat = info->id; pix->bytesperline = q_data->coded_width * info->bytesperline_mult; pix->sizeimage = q_data->sizeimage; pix->colorspace = ctx->state.colorspace; pix->xfer_func = ctx->state.xfer_func; pix->ycbcr_enc = ctx->state.ycbcr_enc; pix->quantization = ctx->state.quantization; break; case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE: case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE: if (!multiplanar) return -EINVAL; pix_mp = &f->fmt.pix_mp; pix_mp->width = q_data->coded_width; pix_mp->height = q_data->coded_height; pix_mp->field = V4L2_FIELD_NONE; pix_mp->pixelformat = info->id; pix_mp->num_planes = 1; pix_mp->plane_fmt[0].bytesperline = q_data->coded_width * info->bytesperline_mult; pix_mp->plane_fmt[0].sizeimage = q_data->sizeimage; pix_mp->colorspace = ctx->state.colorspace; pix_mp->xfer_func = ctx->state.xfer_func; pix_mp->ycbcr_enc = ctx->state.ycbcr_enc; pix_mp->quantization = ctx->state.quantization; break; default: return -EINVAL; } return 0; } static int vidioc_g_fmt_vid_out(struct file *file, void *priv, struct v4l2_format *f) { return vidioc_g_fmt(file2ctx(file), f); } static int vidioc_g_fmt_vid_cap(struct file *file, void *priv, struct v4l2_format *f) { return vidioc_g_fmt(file2ctx(file), f); } static int vidioc_try_fmt(struct vicodec_ctx *ctx, struct v4l2_format *f) { struct v4l2_pix_format_mplane *pix_mp; struct v4l2_pix_format *pix; struct v4l2_plane_pix_format *plane; const struct v4l2_fwht_pixfmt_info *info = ctx->is_stateless ? &pixfmt_stateless_fwht : &pixfmt_fwht; switch (f->type) { case V4L2_BUF_TYPE_VIDEO_CAPTURE: case V4L2_BUF_TYPE_VIDEO_OUTPUT: pix = &f->fmt.pix; if (pix->pixelformat != V4L2_PIX_FMT_FWHT && pix->pixelformat != V4L2_PIX_FMT_FWHT_STATELESS) info = find_fmt(pix->pixelformat); pix->width = clamp(pix->width, MIN_WIDTH, MAX_WIDTH); pix->width = vic_round_dim(pix->width, info->width_div); pix->height = clamp(pix->height, MIN_HEIGHT, MAX_HEIGHT); pix->height = vic_round_dim(pix->height, info->height_div); pix->field = V4L2_FIELD_NONE; pix->bytesperline = pix->width * info->bytesperline_mult; pix->sizeimage = pix->width * pix->height * info->sizeimage_mult / info->sizeimage_div; if (pix->pixelformat == V4L2_PIX_FMT_FWHT) pix->sizeimage += sizeof(struct fwht_cframe_hdr); break; case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE: case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE: pix_mp = &f->fmt.pix_mp; plane = pix_mp->plane_fmt; if (pix_mp->pixelformat != V4L2_PIX_FMT_FWHT && pix_mp->pixelformat != V4L2_PIX_FMT_FWHT_STATELESS) info = find_fmt(pix_mp->pixelformat); pix_mp->num_planes = 1; pix_mp->width = clamp(pix_mp->width, MIN_WIDTH, MAX_WIDTH); pix_mp->width = vic_round_dim(pix_mp->width, info->width_div); pix_mp->height = clamp(pix_mp->height, MIN_HEIGHT, MAX_HEIGHT); pix_mp->height = vic_round_dim(pix_mp->height, info->height_div); pix_mp->field = V4L2_FIELD_NONE; plane->bytesperline = pix_mp->width * info->bytesperline_mult; plane->sizeimage = pix_mp->width * pix_mp->height * info->sizeimage_mult / info->sizeimage_div; if (pix_mp->pixelformat == V4L2_PIX_FMT_FWHT) plane->sizeimage += sizeof(struct fwht_cframe_hdr); break; default: return -EINVAL; } return 0; } static int vidioc_try_fmt_vid_cap(struct file *file, void *priv, struct v4l2_format *f) { struct vicodec_ctx *ctx = file2ctx(file); struct v4l2_pix_format_mplane *pix_mp; struct v4l2_pix_format *pix; switch (f->type) { case V4L2_BUF_TYPE_VIDEO_CAPTURE: if (multiplanar) return -EINVAL; pix = &f->fmt.pix; pix->pixelformat = ctx->is_enc ? V4L2_PIX_FMT_FWHT : find_fmt(f->fmt.pix.pixelformat)->id; pix->colorspace = ctx->state.colorspace; pix->xfer_func = ctx->state.xfer_func; pix->ycbcr_enc = ctx->state.ycbcr_enc; pix->quantization = ctx->state.quantization; break; case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE: if (!multiplanar) return -EINVAL; pix_mp = &f->fmt.pix_mp; pix_mp->pixelformat = ctx->is_enc ? V4L2_PIX_FMT_FWHT : find_fmt(pix_mp->pixelformat)->id; pix_mp->colorspace = ctx->state.colorspace; pix_mp->xfer_func = ctx->state.xfer_func; pix_mp->ycbcr_enc = ctx->state.ycbcr_enc; pix_mp->quantization = ctx->state.quantization; break; default: return -EINVAL; } return vidioc_try_fmt(ctx, f); } static int vidioc_try_fmt_vid_out(struct file *file, void *priv, struct v4l2_format *f) { struct vicodec_ctx *ctx = file2ctx(file); struct v4l2_pix_format_mplane *pix_mp; struct v4l2_pix_format *pix; switch (f->type) { case V4L2_BUF_TYPE_VIDEO_OUTPUT: if (multiplanar) return -EINVAL; pix = &f->fmt.pix; if (ctx->is_enc) pix->pixelformat = find_fmt(pix->pixelformat)->id; else if (ctx->is_stateless) pix->pixelformat = V4L2_PIX_FMT_FWHT_STATELESS; else pix->pixelformat = V4L2_PIX_FMT_FWHT; if (!pix->colorspace) pix->colorspace = V4L2_COLORSPACE_REC709; break; case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE: if (!multiplanar) return -EINVAL; pix_mp = &f->fmt.pix_mp; if (ctx->is_enc) pix_mp->pixelformat = find_fmt(pix_mp->pixelformat)->id; else if (ctx->is_stateless) pix_mp->pixelformat = V4L2_PIX_FMT_FWHT_STATELESS; else pix_mp->pixelformat = V4L2_PIX_FMT_FWHT; if (!pix_mp->colorspace) pix_mp->colorspace = V4L2_COLORSPACE_REC709; break; default: return -EINVAL; } return vidioc_try_fmt(ctx, f); } static int vidioc_s_fmt(struct vicodec_ctx *ctx, struct v4l2_format *f) { struct vicodec_q_data *q_data; struct vb2_queue *vq; bool fmt_changed = true; struct v4l2_pix_format_mplane *pix_mp; struct v4l2_pix_format *pix; vq = v4l2_m2m_get_vq(ctx->fh.m2m_ctx, f->type); if (!vq) return -EINVAL; q_data = get_q_data(ctx, f->type); if (!q_data) return -EINVAL; switch (f->type) { case V4L2_BUF_TYPE_VIDEO_CAPTURE: case V4L2_BUF_TYPE_VIDEO_OUTPUT: pix = &f->fmt.pix; if (ctx->is_enc && V4L2_TYPE_IS_OUTPUT(f->type)) fmt_changed = !q_data->info || q_data->info->id != pix->pixelformat || q_data->coded_width != pix->width || q_data->coded_height != pix->height; if (vb2_is_busy(vq) && fmt_changed) return -EBUSY; if (pix->pixelformat == V4L2_PIX_FMT_FWHT) q_data->info = &pixfmt_fwht; else if (pix->pixelformat == V4L2_PIX_FMT_FWHT_STATELESS) q_data->info = &pixfmt_stateless_fwht; else q_data->info = find_fmt(pix->pixelformat); q_data->coded_width = pix->width; q_data->coded_height = pix->height; q_data->sizeimage = pix->sizeimage; break; case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE: case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE: pix_mp = &f->fmt.pix_mp; if (ctx->is_enc && V4L2_TYPE_IS_OUTPUT(f->type)) fmt_changed = !q_data->info || q_data->info->id != pix_mp->pixelformat || q_data->coded_width != pix_mp->width || q_data->coded_height != pix_mp->height; if (vb2_is_busy(vq) && fmt_changed) return -EBUSY; if (pix_mp->pixelformat == V4L2_PIX_FMT_FWHT) q_data->info = &pixfmt_fwht; else if (pix_mp->pixelformat == V4L2_PIX_FMT_FWHT_STATELESS) q_data->info = &pixfmt_stateless_fwht; else q_data->info = find_fmt(pix_mp->pixelformat); q_data->coded_width = pix_mp->width; q_data->coded_height = pix_mp->height; q_data->sizeimage = pix_mp->plane_fmt[0].sizeimage; break; default: return -EINVAL; } dprintk(ctx->dev, "Setting format for type %d, coded wxh: %dx%d, fourcc: 0x%08x\n", f->type, q_data->coded_width, q_data->coded_height, q_data->info->id); return 0; } static int vidioc_s_fmt_vid_cap(struct file *file, void *priv, struct v4l2_format *f) { int ret; ret = vidioc_try_fmt_vid_cap(file, priv, f); if (ret) return ret; return vidioc_s_fmt(file2ctx(file), f); } static int vidioc_s_fmt_vid_out(struct file *file, void *priv, struct v4l2_format *f) { struct vicodec_ctx *ctx = file2ctx(file); struct vicodec_q_data *q_data; struct vicodec_q_data *q_data_cap; struct v4l2_pix_format *pix; struct v4l2_pix_format_mplane *pix_mp; u32 coded_w = 0, coded_h = 0; unsigned int size = 0; int ret; q_data = get_q_data(ctx, f->type); q_data_cap = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_CAPTURE); ret = vidioc_try_fmt_vid_out(file, priv, f); if (ret) return ret; if (ctx->is_enc) { struct vb2_queue *vq = v4l2_m2m_get_vq(ctx->fh.m2m_ctx, f->type); struct vb2_queue *vq_cap = v4l2_m2m_get_vq(ctx->fh.m2m_ctx, V4L2_BUF_TYPE_VIDEO_CAPTURE); const struct v4l2_fwht_pixfmt_info *info = ctx->is_stateless ? &pixfmt_stateless_fwht : &pixfmt_fwht; if (f->type == V4L2_BUF_TYPE_VIDEO_OUTPUT) { coded_w = f->fmt.pix.width; coded_h = f->fmt.pix.height; } else { coded_w = f->fmt.pix_mp.width; coded_h = f->fmt.pix_mp.height; } if (vb2_is_busy(vq) && (coded_w != q_data->coded_width || coded_h != q_data->coded_height)) return -EBUSY; size = coded_w * coded_h * info->sizeimage_mult / info->sizeimage_div; if (!ctx->is_stateless) size += sizeof(struct fwht_cframe_hdr); if (vb2_is_busy(vq_cap) && size > q_data_cap->sizeimage) return -EBUSY; } ret = vidioc_s_fmt(file2ctx(file), f); if (!ret) { if (ctx->is_enc) { q_data->visible_width = coded_w; q_data->visible_height = coded_h; q_data_cap->coded_width = coded_w; q_data_cap->coded_height = coded_h; q_data_cap->sizeimage = size; } switch (f->type) { case V4L2_BUF_TYPE_VIDEO_OUTPUT: pix = &f->fmt.pix; ctx->state.colorspace = pix->colorspace; ctx->state.xfer_func = pix->xfer_func; ctx->state.ycbcr_enc = pix->ycbcr_enc; ctx->state.quantization = pix->quantization; break; case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE: pix_mp = &f->fmt.pix_mp; ctx->state.colorspace = pix_mp->colorspace; ctx->state.xfer_func = pix_mp->xfer_func; ctx->state.ycbcr_enc = pix_mp->ycbcr_enc; ctx->state.quantization = pix_mp->quantization; break; default: break; } } return ret; } static int vidioc_g_selection(struct file *file, void *priv, struct v4l2_selection *s) { struct vicodec_ctx *ctx = file2ctx(file); struct vicodec_q_data *q_data; q_data = get_q_data(ctx, s->type); if (!q_data) return -EINVAL; /* * encoder supports only cropping on the OUTPUT buffer * decoder supports only composing on the CAPTURE buffer */ if (ctx->is_enc && s->type == V4L2_BUF_TYPE_VIDEO_OUTPUT) { switch (s->target) { case V4L2_SEL_TGT_CROP: s->r.left = 0; s->r.top = 0; s->r.width = q_data->visible_width; s->r.height = q_data->visible_height; return 0; case V4L2_SEL_TGT_CROP_DEFAULT: case V4L2_SEL_TGT_CROP_BOUNDS: s->r.left = 0; s->r.top = 0; s->r.width = q_data->coded_width; s->r.height = q_data->coded_height; return 0; } } else if (!ctx->is_enc && s->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) { switch (s->target) { case V4L2_SEL_TGT_COMPOSE: s->r.left = 0; s->r.top = 0; s->r.width = q_data->visible_width; s->r.height = q_data->visible_height; return 0; case V4L2_SEL_TGT_COMPOSE_DEFAULT: case V4L2_SEL_TGT_COMPOSE_BOUNDS: s->r.left = 0; s->r.top = 0; s->r.width = q_data->coded_width; s->r.height = q_data->coded_height; return 0; } } return -EINVAL; } static int vidioc_s_selection(struct file *file, void *priv, struct v4l2_selection *s) { struct vicodec_ctx *ctx = file2ctx(file); struct vicodec_q_data *q_data; if (s->type != V4L2_BUF_TYPE_VIDEO_OUTPUT) return -EINVAL; q_data = get_q_data(ctx, s->type); if (!q_data) return -EINVAL; if (!ctx->is_enc || s->target != V4L2_SEL_TGT_CROP) return -EINVAL; s->r.left = 0; s->r.top = 0; q_data->visible_width = clamp(s->r.width, MIN_WIDTH, q_data->coded_width); s->r.width = q_data->visible_width; q_data->visible_height = clamp(s->r.height, MIN_HEIGHT, q_data->coded_height); s->r.height = q_data->visible_height; return 0; } static int vicodec_encoder_cmd(struct file *file, void *fh, struct v4l2_encoder_cmd *ec) { struct vicodec_ctx *ctx = file2ctx(file); int ret; ret = v4l2_m2m_ioctl_try_encoder_cmd(file, fh, ec); if (ret < 0) return ret; if (!vb2_is_streaming(&ctx->fh.m2m_ctx->cap_q_ctx.q) || !vb2_is_streaming(&ctx->fh.m2m_ctx->out_q_ctx.q)) return 0; ret = v4l2_m2m_ioctl_encoder_cmd(file, fh, ec); if (ret < 0) return ret; if (ec->cmd == V4L2_ENC_CMD_STOP && v4l2_m2m_has_stopped(ctx->fh.m2m_ctx)) v4l2_event_queue_fh(&ctx->fh, &vicodec_eos_event); if (ec->cmd == V4L2_ENC_CMD_START && v4l2_m2m_has_stopped(ctx->fh.m2m_ctx)) vb2_clear_last_buffer_dequeued(&ctx->fh.m2m_ctx->cap_q_ctx.q); return 0; } static int vicodec_decoder_cmd(struct file *file, void *fh, struct v4l2_decoder_cmd *dc) { struct vicodec_ctx *ctx = file2ctx(file); int ret; ret = v4l2_m2m_ioctl_try_decoder_cmd(file, fh, dc); if (ret < 0) return ret; if (!vb2_is_streaming(&ctx->fh.m2m_ctx->cap_q_ctx.q) || !vb2_is_streaming(&ctx->fh.m2m_ctx->out_q_ctx.q)) return 0; ret = v4l2_m2m_ioctl_decoder_cmd(file, fh, dc); if (ret < 0) return ret; if (dc->cmd == V4L2_DEC_CMD_STOP && v4l2_m2m_has_stopped(ctx->fh.m2m_ctx)) v4l2_event_queue_fh(&ctx->fh, &vicodec_eos_event); if (dc->cmd == V4L2_DEC_CMD_START && v4l2_m2m_has_stopped(ctx->fh.m2m_ctx)) vb2_clear_last_buffer_dequeued(&ctx->fh.m2m_ctx->cap_q_ctx.q); return 0; } static int vicodec_enum_framesizes(struct file *file, void *fh, struct v4l2_frmsizeenum *fsize) { switch (fsize->pixel_format) { case V4L2_PIX_FMT_FWHT_STATELESS: break; case V4L2_PIX_FMT_FWHT: break; default: if (find_fmt(fsize->pixel_format)->id == fsize->pixel_format) break; return -EINVAL; } if (fsize->index) return -EINVAL; fsize->type = V4L2_FRMSIZE_TYPE_STEPWISE; fsize->stepwise.min_width = MIN_WIDTH; fsize->stepwise.max_width = MAX_WIDTH; fsize->stepwise.step_width = 8; fsize->stepwise.min_height = MIN_HEIGHT; fsize->stepwise.max_height = MAX_HEIGHT; fsize->stepwise.step_height = 8; return 0; } static int vicodec_subscribe_event(struct v4l2_fh *fh, const struct v4l2_event_subscription *sub) { struct vicodec_ctx *ctx = container_of(fh, struct vicodec_ctx, fh); switch (sub->type) { case V4L2_EVENT_SOURCE_CHANGE: if (ctx->is_enc) return -EINVAL; fallthrough; case V4L2_EVENT_EOS: if (ctx->is_stateless) return -EINVAL; return v4l2_event_subscribe(fh, sub, 0, NULL); default: return v4l2_ctrl_subscribe_event(fh, sub); } } static const struct v4l2_ioctl_ops vicodec_ioctl_ops = { .vidioc_querycap = vidioc_querycap, .vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap, .vidioc_g_fmt_vid_cap = vidioc_g_fmt_vid_cap, .vidioc_try_fmt_vid_cap = vidioc_try_fmt_vid_cap, .vidioc_s_fmt_vid_cap = vidioc_s_fmt_vid_cap, .vidioc_g_fmt_vid_cap_mplane = vidioc_g_fmt_vid_cap, .vidioc_try_fmt_vid_cap_mplane = vidioc_try_fmt_vid_cap, .vidioc_s_fmt_vid_cap_mplane = vidioc_s_fmt_vid_cap, .vidioc_enum_fmt_vid_out = vidioc_enum_fmt_vid_out, .vidioc_g_fmt_vid_out = vidioc_g_fmt_vid_out, .vidioc_try_fmt_vid_out = vidioc_try_fmt_vid_out, .vidioc_s_fmt_vid_out = vidioc_s_fmt_vid_out, .vidioc_g_fmt_vid_out_mplane = vidioc_g_fmt_vid_out, .vidioc_try_fmt_vid_out_mplane = vidioc_try_fmt_vid_out, .vidioc_s_fmt_vid_out_mplane = vidioc_s_fmt_vid_out, .vidioc_reqbufs = v4l2_m2m_ioctl_reqbufs, .vidioc_querybuf = v4l2_m2m_ioctl_querybuf, .vidioc_qbuf = v4l2_m2m_ioctl_qbuf, .vidioc_dqbuf = v4l2_m2m_ioctl_dqbuf, .vidioc_prepare_buf = v4l2_m2m_ioctl_prepare_buf, .vidioc_create_bufs = v4l2_m2m_ioctl_create_bufs, .vidioc_expbuf = v4l2_m2m_ioctl_expbuf, .vidioc_streamon = v4l2_m2m_ioctl_streamon, .vidioc_streamoff = v4l2_m2m_ioctl_streamoff, .vidioc_g_selection = vidioc_g_selection, .vidioc_s_selection = vidioc_s_selection, .vidioc_try_encoder_cmd = v4l2_m2m_ioctl_try_encoder_cmd, .vidioc_encoder_cmd = vicodec_encoder_cmd, .vidioc_try_decoder_cmd = v4l2_m2m_ioctl_try_decoder_cmd, .vidioc_decoder_cmd = vicodec_decoder_cmd, .vidioc_enum_framesizes = vicodec_enum_framesizes, .vidioc_subscribe_event = vicodec_subscribe_event, .vidioc_unsubscribe_event = v4l2_event_unsubscribe, }; /* * Queue operations */ static int vicodec_queue_setup(struct vb2_queue *vq, unsigned int *nbuffers, unsigned int *nplanes, unsigned int sizes[], struct device *alloc_devs[]) { struct vicodec_ctx *ctx = vb2_get_drv_priv(vq); struct vicodec_q_data *q_data = get_q_data(ctx, vq->type); unsigned int size = q_data->sizeimage; if (*nplanes) return sizes[0] < size ? -EINVAL : 0; *nplanes = 1; sizes[0] = size; q_data->vb2_sizeimage = size; return 0; } static int vicodec_buf_out_validate(struct vb2_buffer *vb) { struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb); vbuf->field = V4L2_FIELD_NONE; return 0; } static int vicodec_buf_prepare(struct vb2_buffer *vb) { struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb); struct vicodec_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue); struct vicodec_q_data *q_data; dprintk(ctx->dev, "type: %d\n", vb->vb2_queue->type); q_data = get_q_data(ctx, vb->vb2_queue->type); if (V4L2_TYPE_IS_OUTPUT(vb->vb2_queue->type)) { if (vbuf->field == V4L2_FIELD_ANY) vbuf->field = V4L2_FIELD_NONE; if (vbuf->field != V4L2_FIELD_NONE) { dprintk(ctx->dev, "%s field isn't supported\n", __func__); return -EINVAL; } } if (vb2_plane_size(vb, 0) < q_data->vb2_sizeimage) { dprintk(ctx->dev, "%s data will not fit into plane (%lu < %lu)\n", __func__, vb2_plane_size(vb, 0), (long)q_data->vb2_sizeimage); return -EINVAL; } return 0; } static void vicodec_buf_queue(struct vb2_buffer *vb) { struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb); struct vicodec_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue); unsigned int sz = vb2_get_plane_payload(&vbuf->vb2_buf, 0); u8 *p_src = vb2_plane_vaddr(&vbuf->vb2_buf, 0); u8 *p = p_src; struct vb2_queue *vq_out = v4l2_m2m_get_vq(ctx->fh.m2m_ctx, V4L2_BUF_TYPE_VIDEO_OUTPUT); struct vb2_queue *vq_cap = v4l2_m2m_get_vq(ctx->fh.m2m_ctx, V4L2_BUF_TYPE_VIDEO_CAPTURE); bool header_valid = false; static const struct v4l2_event rs_event = { .type = V4L2_EVENT_SOURCE_CHANGE, .u.src_change.changes = V4L2_EVENT_SRC_CH_RESOLUTION, }; if (V4L2_TYPE_IS_CAPTURE(vb->vb2_queue->type) && vb2_is_streaming(vb->vb2_queue) && v4l2_m2m_dst_buf_is_last(ctx->fh.m2m_ctx)) { unsigned int i; for (i = 0; i < vb->num_planes; i++) vb2_set_plane_payload(vb, i, 0); vbuf->field = V4L2_FIELD_NONE; vbuf->sequence = get_q_data(ctx, vb->vb2_queue->type)->sequence++; v4l2_m2m_last_buffer_done(ctx->fh.m2m_ctx, vbuf); v4l2_event_queue_fh(&ctx->fh, &vicodec_eos_event); return; } /* buf_queue handles only the first source change event */ if (ctx->first_source_change_sent) { v4l2_m2m_buf_queue(ctx->fh.m2m_ctx, vbuf); return; } /* * if both queues are streaming, the source change event is * handled in job_ready */ if (vb2_is_streaming(vq_cap) && vb2_is_streaming(vq_out)) { v4l2_m2m_buf_queue(ctx->fh.m2m_ctx, vbuf); return; } /* * source change event is relevant only for the stateful decoder * in the compressed stream */ if (ctx->is_stateless || ctx->is_enc || V4L2_TYPE_IS_CAPTURE(vb->vb2_queue->type)) { v4l2_m2m_buf_queue(ctx->fh.m2m_ctx, vbuf); return; } do { enum vb2_buffer_state state = get_next_header(ctx, &p, p_src + sz - p); if (ctx->header_size < sizeof(struct fwht_cframe_hdr)) { v4l2_m2m_buf_done(vbuf, state); return; } header_valid = is_header_valid(&ctx->state.header); /* * p points right after the end of the header in the * buffer. If the header is invalid we set p to point * to the next byte after the start of the header */ if (!header_valid) { p = p - sizeof(struct fwht_cframe_hdr) + 1; if (p < p_src) p = p_src; ctx->header_size = 0; ctx->comp_magic_cnt = 0; } } while (!header_valid); ctx->cur_buf_offset = p - p_src; update_capture_data_from_header(ctx); ctx->first_source_change_sent = true; v4l2_event_queue_fh(&ctx->fh, &rs_event); v4l2_m2m_buf_queue(ctx->fh.m2m_ctx, vbuf); } static void vicodec_return_bufs(struct vb2_queue *q, u32 state) { struct vicodec_ctx *ctx = vb2_get_drv_priv(q); struct vb2_v4l2_buffer *vbuf; for (;;) { if (V4L2_TYPE_IS_OUTPUT(q->type)) vbuf = v4l2_m2m_src_buf_remove(ctx->fh.m2m_ctx); else vbuf = v4l2_m2m_dst_buf_remove(ctx->fh.m2m_ctx); if (vbuf == NULL) return; v4l2_ctrl_request_complete(vbuf->vb2_buf.req_obj.req, &ctx->hdl); spin_lock(ctx->lock); v4l2_m2m_buf_done(vbuf, state); spin_unlock(ctx->lock); } } static unsigned int total_frame_size(struct vicodec_q_data *q_data) { unsigned int size; unsigned int chroma_div; if (!q_data->info) { WARN_ON(1); return 0; } size = q_data->coded_width * q_data->coded_height; chroma_div = q_data->info->width_div * q_data->info->height_div; if (q_data->info->components_num == 4) return 2 * size + 2 * (size / chroma_div); else if (q_data->info->components_num == 3) return size + 2 * (size / chroma_div); return size; } static int vicodec_start_streaming(struct vb2_queue *q, unsigned int count) { struct vicodec_ctx *ctx = vb2_get_drv_priv(q); struct vicodec_q_data *q_data = get_q_data(ctx, q->type); struct v4l2_fwht_state *state = &ctx->state; const struct v4l2_fwht_pixfmt_info *info = q_data->info; unsigned int size = q_data->coded_width * q_data->coded_height; unsigned int chroma_div; unsigned int total_planes_size; u8 *new_comp_frame = NULL; chroma_div = info->width_div * info->height_div; q_data->sequence = 0; v4l2_m2m_update_start_streaming_state(ctx->fh.m2m_ctx, q); state->gop_cnt = 0; if ((V4L2_TYPE_IS_OUTPUT(q->type) && !ctx->is_enc) || (V4L2_TYPE_IS_CAPTURE(q->type) && ctx->is_enc)) return 0; if (info->id == V4L2_PIX_FMT_FWHT || info->id == V4L2_PIX_FMT_FWHT_STATELESS) { vicodec_return_bufs(q, VB2_BUF_STATE_QUEUED); return -EINVAL; } total_planes_size = total_frame_size(q_data); ctx->comp_max_size = total_planes_size; state->visible_width = q_data->visible_width; state->visible_height = q_data->visible_height; state->coded_width = q_data->coded_width; state->coded_height = q_data->coded_height; state->stride = q_data->coded_width * info->bytesperline_mult; if (ctx->is_stateless) { state->ref_stride = state->stride; return 0; } state->ref_stride = q_data->coded_width * info->luma_alpha_step; state->ref_frame.buf = kvmalloc(total_planes_size, GFP_KERNEL); state->ref_frame.luma = state->ref_frame.buf; new_comp_frame = kvmalloc(ctx->comp_max_size, GFP_KERNEL); if (!state->ref_frame.luma || !new_comp_frame) { kvfree(state->ref_frame.luma); kvfree(new_comp_frame); vicodec_return_bufs(q, VB2_BUF_STATE_QUEUED); return -ENOMEM; } /* * if state->compressed_frame was already allocated then * it contain data of the first frame of the new resolution */ if (state->compressed_frame) { if (ctx->comp_size > ctx->comp_max_size) ctx->comp_size = ctx->comp_max_size; memcpy(new_comp_frame, state->compressed_frame, ctx->comp_size); } kvfree(state->compressed_frame); state->compressed_frame = new_comp_frame; if (info->components_num < 3) { state->ref_frame.cb = NULL; state->ref_frame.cr = NULL; state->ref_frame.alpha = NULL; return 0; } state->ref_frame.cb = state->ref_frame.luma + size; state->ref_frame.cr = state->ref_frame.cb + size / chroma_div; if (info->components_num == 4) state->ref_frame.alpha = state->ref_frame.cr + size / chroma_div; else state->ref_frame.alpha = NULL; return 0; } static void vicodec_stop_streaming(struct vb2_queue *q) { struct vicodec_ctx *ctx = vb2_get_drv_priv(q); vicodec_return_bufs(q, VB2_BUF_STATE_ERROR); v4l2_m2m_update_stop_streaming_state(ctx->fh.m2m_ctx, q); if (V4L2_TYPE_IS_OUTPUT(q->type) && v4l2_m2m_has_stopped(ctx->fh.m2m_ctx)) v4l2_event_queue_fh(&ctx->fh, &vicodec_eos_event); if (!ctx->is_enc && V4L2_TYPE_IS_OUTPUT(q->type)) ctx->first_source_change_sent = false; if ((!V4L2_TYPE_IS_OUTPUT(q->type) && !ctx->is_enc) || (V4L2_TYPE_IS_OUTPUT(q->type) && ctx->is_enc)) { if (!ctx->is_stateless) kvfree(ctx->state.ref_frame.buf); ctx->state.ref_frame.buf = NULL; ctx->state.ref_frame.luma = NULL; ctx->comp_max_size = 0; ctx->source_changed = false; } if (V4L2_TYPE_IS_OUTPUT(q->type) && !ctx->is_enc) { ctx->cur_buf_offset = 0; ctx->comp_size = 0; ctx->header_size = 0; ctx->comp_magic_cnt = 0; ctx->comp_has_frame = false; ctx->comp_has_next_frame = false; } } static void vicodec_buf_request_complete(struct vb2_buffer *vb) { struct vicodec_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue); v4l2_ctrl_request_complete(vb->req_obj.req, &ctx->hdl); } static const struct vb2_ops vicodec_qops = { .queue_setup = vicodec_queue_setup, .buf_out_validate = vicodec_buf_out_validate, .buf_prepare = vicodec_buf_prepare, .buf_queue = vicodec_buf_queue, .buf_request_complete = vicodec_buf_request_complete, .start_streaming = vicodec_start_streaming, .stop_streaming = vicodec_stop_streaming, .wait_prepare = vb2_ops_wait_prepare, .wait_finish = vb2_ops_wait_finish, }; static int queue_init(void *priv, struct vb2_queue *src_vq, struct vb2_queue *dst_vq) { struct vicodec_ctx *ctx = priv; int ret; src_vq->type = (multiplanar ? V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE : V4L2_BUF_TYPE_VIDEO_OUTPUT); src_vq->io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF; src_vq->drv_priv = ctx; src_vq->buf_struct_size = sizeof(struct v4l2_m2m_buffer); src_vq->ops = &vicodec_qops; src_vq->mem_ops = &vb2_vmalloc_memops; src_vq->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_COPY; if (ctx->is_enc) src_vq->lock = &ctx->dev->stateful_enc.mutex; else if (ctx->is_stateless) src_vq->lock = &ctx->dev->stateless_dec.mutex; else src_vq->lock = &ctx->dev->stateful_dec.mutex; src_vq->supports_requests = ctx->is_stateless; src_vq->requires_requests = ctx->is_stateless; ret = vb2_queue_init(src_vq); if (ret) return ret; dst_vq->type = (multiplanar ? V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE : V4L2_BUF_TYPE_VIDEO_CAPTURE); dst_vq->io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF; dst_vq->drv_priv = ctx; dst_vq->buf_struct_size = sizeof(struct v4l2_m2m_buffer); dst_vq->ops = &vicodec_qops; dst_vq->mem_ops = &vb2_vmalloc_memops; dst_vq->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_COPY; dst_vq->lock = src_vq->lock; return vb2_queue_init(dst_vq); } static int vicodec_try_ctrl(struct v4l2_ctrl *ctrl) { struct vicodec_ctx *ctx = container_of(ctrl->handler, struct vicodec_ctx, hdl); const struct v4l2_ctrl_fwht_params *params; struct vicodec_q_data *q_dst = get_q_data(ctx, V4L2_BUF_TYPE_VIDEO_CAPTURE); switch (ctrl->id) { case V4L2_CID_STATELESS_FWHT_PARAMS: if (!q_dst->info) return -EINVAL; params = ctrl->p_new.p_fwht_params; if (params->width > q_dst->coded_width || params->width < MIN_WIDTH || params->height > q_dst->coded_height || params->height < MIN_HEIGHT) return -EINVAL; if (!validate_by_version(params->flags, params->version)) return -EINVAL; if (!validate_stateless_params_flags(params, q_dst->info)) return -EINVAL; return 0; default: return 0; } return 0; } static void update_header_from_stateless_params(struct vicodec_ctx *ctx, const struct v4l2_ctrl_fwht_params *params) { struct fwht_cframe_hdr *p_hdr = &ctx->state.header; p_hdr->magic1 = FWHT_MAGIC1; p_hdr->magic2 = FWHT_MAGIC2; p_hdr->version = htonl(params->version); p_hdr->width = htonl(params->width); p_hdr->height = htonl(params->height); p_hdr->flags = htonl(params->flags); p_hdr->colorspace = htonl(params->colorspace); p_hdr->xfer_func = htonl(params->xfer_func); p_hdr->ycbcr_enc = htonl(params->ycbcr_enc); p_hdr->quantization = htonl(params->quantization); } static int vicodec_s_ctrl(struct v4l2_ctrl *ctrl) { struct vicodec_ctx *ctx = container_of(ctrl->handler, struct vicodec_ctx, hdl); const struct v4l2_ctrl_fwht_params *params; switch (ctrl->id) { case V4L2_CID_MPEG_VIDEO_GOP_SIZE: ctx->state.gop_size = ctrl->val; return 0; case V4L2_CID_FWHT_I_FRAME_QP: ctx->state.i_frame_qp = ctrl->val; return 0; case V4L2_CID_FWHT_P_FRAME_QP: ctx->state.p_frame_qp = ctrl->val; return 0; case V4L2_CID_STATELESS_FWHT_PARAMS: params = ctrl->p_new.p_fwht_params; update_header_from_stateless_params(ctx, params); ctx->state.ref_frame_ts = params->backward_ref_ts; return 0; } return -EINVAL; } static const struct v4l2_ctrl_ops vicodec_ctrl_ops = { .s_ctrl = vicodec_s_ctrl, .try_ctrl = vicodec_try_ctrl, }; static const struct v4l2_ctrl_config vicodec_ctrl_stateless_state = { .ops = &vicodec_ctrl_ops, .id = V4L2_CID_STATELESS_FWHT_PARAMS, .elem_size = sizeof(struct v4l2_ctrl_fwht_params), }; /* * File operations */ static int vicodec_open(struct file *file) { const struct v4l2_fwht_pixfmt_info *info = v4l2_fwht_get_pixfmt(0); struct video_device *vfd = video_devdata(file); struct vicodec_dev *dev = video_drvdata(file); struct vicodec_ctx *ctx = NULL; struct v4l2_ctrl_handler *hdl; unsigned int raw_size; unsigned int comp_size; int rc = 0; if (mutex_lock_interruptible(vfd->lock)) return -ERESTARTSYS; ctx = kzalloc(sizeof(*ctx), GFP_KERNEL); if (!ctx) { rc = -ENOMEM; goto open_unlock; } if (vfd == &dev->stateful_enc.vfd) ctx->is_enc = true; else if (vfd == &dev->stateless_dec.vfd) ctx->is_stateless = true; v4l2_fh_init(&ctx->fh, video_devdata(file)); file->private_data = &ctx->fh; ctx->dev = dev; hdl = &ctx->hdl; v4l2_ctrl_handler_init(hdl, 5); v4l2_ctrl_new_std(hdl, &vicodec_ctrl_ops, V4L2_CID_MPEG_VIDEO_GOP_SIZE, 1, 16, 1, 10); v4l2_ctrl_new_std(hdl, &vicodec_ctrl_ops, V4L2_CID_FWHT_I_FRAME_QP, 1, 31, 1, 20); v4l2_ctrl_new_std(hdl, &vicodec_ctrl_ops, V4L2_CID_FWHT_P_FRAME_QP, 1, 31, 1, 20); if (ctx->is_enc) v4l2_ctrl_new_std(hdl, &vicodec_ctrl_ops, V4L2_CID_MIN_BUFFERS_FOR_OUTPUT, 1, 1, 1, 1); if (ctx->is_stateless) v4l2_ctrl_new_custom(hdl, &vicodec_ctrl_stateless_state, NULL); if (hdl->error) { rc = hdl->error; v4l2_ctrl_handler_free(hdl); kfree(ctx); goto open_unlock; } ctx->fh.ctrl_handler = hdl; v4l2_ctrl_handler_setup(hdl); if (ctx->is_enc) ctx->q_data[V4L2_M2M_SRC].info = info; else if (ctx->is_stateless) ctx->q_data[V4L2_M2M_SRC].info = &pixfmt_stateless_fwht; else ctx->q_data[V4L2_M2M_SRC].info = &pixfmt_fwht; ctx->q_data[V4L2_M2M_SRC].coded_width = 1280; ctx->q_data[V4L2_M2M_SRC].coded_height = 720; ctx->q_data[V4L2_M2M_SRC].visible_width = 1280; ctx->q_data[V4L2_M2M_SRC].visible_height = 720; raw_size = 1280 * 720 * info->sizeimage_mult / info->sizeimage_div; comp_size = 1280 * 720 * pixfmt_fwht.sizeimage_mult / pixfmt_fwht.sizeimage_div; if (ctx->is_enc) ctx->q_data[V4L2_M2M_SRC].sizeimage = raw_size; else if (ctx->is_stateless) ctx->q_data[V4L2_M2M_SRC].sizeimage = comp_size; else ctx->q_data[V4L2_M2M_SRC].sizeimage = comp_size + sizeof(struct fwht_cframe_hdr); ctx->q_data[V4L2_M2M_DST] = ctx->q_data[V4L2_M2M_SRC]; if (ctx->is_enc) { ctx->q_data[V4L2_M2M_DST].info = &pixfmt_fwht; ctx->q_data[V4L2_M2M_DST].sizeimage = comp_size + sizeof(struct fwht_cframe_hdr); } else { ctx->q_data[V4L2_M2M_DST].info = info; ctx->q_data[V4L2_M2M_DST].sizeimage = raw_size; } ctx->state.colorspace = V4L2_COLORSPACE_REC709; if (ctx->is_enc) { ctx->fh.m2m_ctx = v4l2_m2m_ctx_init(dev->stateful_enc.m2m_dev, ctx, &queue_init); ctx->lock = &dev->stateful_enc.lock; } else if (ctx->is_stateless) { ctx->fh.m2m_ctx = v4l2_m2m_ctx_init(dev->stateless_dec.m2m_dev, ctx, &queue_init); ctx->lock = &dev->stateless_dec.lock; } else { ctx->fh.m2m_ctx = v4l2_m2m_ctx_init(dev->stateful_dec.m2m_dev, ctx, &queue_init); ctx->lock = &dev->stateful_dec.lock; } if (IS_ERR(ctx->fh.m2m_ctx)) { rc = PTR_ERR(ctx->fh.m2m_ctx); v4l2_ctrl_handler_free(hdl); v4l2_fh_exit(&ctx->fh); kfree(ctx); goto open_unlock; } v4l2_fh_add(&ctx->fh); open_unlock: mutex_unlock(vfd->lock); return rc; } static int vicodec_release(struct file *file) { struct video_device *vfd = video_devdata(file); struct vicodec_ctx *ctx = file2ctx(file); mutex_lock(vfd->lock); v4l2_m2m_ctx_release(ctx->fh.m2m_ctx); mutex_unlock(vfd->lock); v4l2_fh_del(&ctx->fh); v4l2_fh_exit(&ctx->fh); v4l2_ctrl_handler_free(&ctx->hdl); kvfree(ctx->state.compressed_frame); kfree(ctx); return 0; } static int vicodec_request_validate(struct media_request *req) { struct media_request_object *obj; struct v4l2_ctrl_handler *parent_hdl, *hdl; struct vicodec_ctx *ctx = NULL; struct v4l2_ctrl *ctrl; unsigned int count; list_for_each_entry(obj, &req->objects, list) { struct vb2_buffer *vb; if (vb2_request_object_is_buffer(obj)) { vb = container_of(obj, struct vb2_buffer, req_obj); ctx = vb2_get_drv_priv(vb->vb2_queue); break; } } if (!ctx) { pr_err("No buffer was provided with the request\n"); return -ENOENT; } count = vb2_request_buffer_cnt(req); if (!count) { v4l2_info(&ctx->dev->v4l2_dev, "No buffer was provided with the request\n"); return -ENOENT; } else if (count > 1) { v4l2_info(&ctx->dev->v4l2_dev, "More than one buffer was provided with the request\n"); return -EINVAL; } parent_hdl = &ctx->hdl; hdl = v4l2_ctrl_request_hdl_find(req, parent_hdl); if (!hdl) { v4l2_info(&ctx->dev->v4l2_dev, "Missing codec control\n"); return -ENOENT; } ctrl = v4l2_ctrl_request_hdl_ctrl_find(hdl, vicodec_ctrl_stateless_state.id); v4l2_ctrl_request_hdl_put(hdl); if (!ctrl) { v4l2_info(&ctx->dev->v4l2_dev, "Missing required codec control\n"); return -ENOENT; } return vb2_request_validate(req); } static const struct v4l2_file_operations vicodec_fops = { .owner = THIS_MODULE, .open = vicodec_open, .release = vicodec_release, .poll = v4l2_m2m_fop_poll, .unlocked_ioctl = video_ioctl2, .mmap = v4l2_m2m_fop_mmap, }; static const struct video_device vicodec_videodev = { .name = VICODEC_NAME, .vfl_dir = VFL_DIR_M2M, .fops = &vicodec_fops, .ioctl_ops = &vicodec_ioctl_ops, .minor = -1, .release = video_device_release_empty, }; static const struct media_device_ops vicodec_m2m_media_ops = { .req_validate = vicodec_request_validate, .req_queue = v4l2_m2m_request_queue, }; static const struct v4l2_m2m_ops m2m_ops = { .device_run = device_run, .job_ready = job_ready, }; static int register_instance(struct vicodec_dev *dev, struct vicodec_dev_instance *dev_instance, const char *name, bool is_enc) { struct video_device *vfd; int ret; spin_lock_init(&dev_instance->lock); mutex_init(&dev_instance->mutex); dev_instance->m2m_dev = v4l2_m2m_init(&m2m_ops); if (IS_ERR(dev_instance->m2m_dev)) { v4l2_err(&dev->v4l2_dev, "Failed to init vicodec enc device\n"); return PTR_ERR(dev_instance->m2m_dev); } dev_instance->vfd = vicodec_videodev; vfd = &dev_instance->vfd; vfd->lock = &dev_instance->mutex; vfd->v4l2_dev = &dev->v4l2_dev; strscpy(vfd->name, name, sizeof(vfd->name)); vfd->device_caps = V4L2_CAP_STREAMING | (multiplanar ? V4L2_CAP_VIDEO_M2M_MPLANE : V4L2_CAP_VIDEO_M2M); if (is_enc) { v4l2_disable_ioctl(vfd, VIDIOC_DECODER_CMD); v4l2_disable_ioctl(vfd, VIDIOC_TRY_DECODER_CMD); } else { v4l2_disable_ioctl(vfd, VIDIOC_ENCODER_CMD); v4l2_disable_ioctl(vfd, VIDIOC_TRY_ENCODER_CMD); } video_set_drvdata(vfd, dev); ret = video_register_device(vfd, VFL_TYPE_VIDEO, 0); if (ret) { v4l2_err(&dev->v4l2_dev, "Failed to register video device '%s'\n", name); v4l2_m2m_release(dev_instance->m2m_dev); return ret; } v4l2_info(&dev->v4l2_dev, "Device '%s' registered as /dev/video%d\n", name, vfd->num); return 0; } static void vicodec_v4l2_dev_release(struct v4l2_device *v4l2_dev) { struct vicodec_dev *dev = container_of(v4l2_dev, struct vicodec_dev, v4l2_dev); v4l2_device_unregister(&dev->v4l2_dev); v4l2_m2m_release(dev->stateful_enc.m2m_dev); v4l2_m2m_release(dev->stateful_dec.m2m_dev); v4l2_m2m_release(dev->stateless_dec.m2m_dev); #ifdef CONFIG_MEDIA_CONTROLLER media_device_cleanup(&dev->mdev); #endif kfree(dev); } static int vicodec_probe(struct platform_device *pdev) { struct vicodec_dev *dev; int ret; dev = kzalloc(sizeof(*dev), GFP_KERNEL); if (!dev) return -ENOMEM; ret = v4l2_device_register(&pdev->dev, &dev->v4l2_dev); if (ret) goto free_dev; dev->v4l2_dev.release = vicodec_v4l2_dev_release; #ifdef CONFIG_MEDIA_CONTROLLER dev->mdev.dev = &pdev->dev; strscpy(dev->mdev.model, "vicodec", sizeof(dev->mdev.model)); strscpy(dev->mdev.bus_info, "platform:vicodec", sizeof(dev->mdev.bus_info)); media_device_init(&dev->mdev); dev->mdev.ops = &vicodec_m2m_media_ops; dev->v4l2_dev.mdev = &dev->mdev; #endif platform_set_drvdata(pdev, dev); ret = register_instance(dev, &dev->stateful_enc, "stateful-encoder", true); if (ret) goto unreg_dev; ret = register_instance(dev, &dev->stateful_dec, "stateful-decoder", false); if (ret) goto unreg_sf_enc; ret = register_instance(dev, &dev->stateless_dec, "stateless-decoder", false); if (ret) goto unreg_sf_dec; #ifdef CONFIG_MEDIA_CONTROLLER ret = v4l2_m2m_register_media_controller(dev->stateful_enc.m2m_dev, &dev->stateful_enc.vfd, MEDIA_ENT_F_PROC_VIDEO_ENCODER); if (ret) { v4l2_err(&dev->v4l2_dev, "Failed to init mem2mem media controller for enc\n"); goto unreg_m2m; } ret = v4l2_m2m_register_media_controller(dev->stateful_dec.m2m_dev, &dev->stateful_dec.vfd, MEDIA_ENT_F_PROC_VIDEO_DECODER); if (ret) { v4l2_err(&dev->v4l2_dev, "Failed to init mem2mem media controller for dec\n"); goto unreg_m2m_sf_enc_mc; } ret = v4l2_m2m_register_media_controller(dev->stateless_dec.m2m_dev, &dev->stateless_dec.vfd, MEDIA_ENT_F_PROC_VIDEO_DECODER); if (ret) { v4l2_err(&dev->v4l2_dev, "Failed to init mem2mem media controller for stateless dec\n"); goto unreg_m2m_sf_dec_mc; } ret = media_device_register(&dev->mdev); if (ret) { v4l2_err(&dev->v4l2_dev, "Failed to register mem2mem media device\n"); goto unreg_m2m_sl_dec_mc; } #endif return 0; #ifdef CONFIG_MEDIA_CONTROLLER unreg_m2m_sl_dec_mc: v4l2_m2m_unregister_media_controller(dev->stateless_dec.m2m_dev); unreg_m2m_sf_dec_mc: v4l2_m2m_unregister_media_controller(dev->stateful_dec.m2m_dev); unreg_m2m_sf_enc_mc: v4l2_m2m_unregister_media_controller(dev->stateful_enc.m2m_dev); unreg_m2m: video_unregister_device(&dev->stateless_dec.vfd); v4l2_m2m_release(dev->stateless_dec.m2m_dev); #endif unreg_sf_dec: video_unregister_device(&dev->stateful_dec.vfd); v4l2_m2m_release(dev->stateful_dec.m2m_dev); unreg_sf_enc: video_unregister_device(&dev->stateful_enc.vfd); v4l2_m2m_release(dev->stateful_enc.m2m_dev); unreg_dev: v4l2_device_unregister(&dev->v4l2_dev); free_dev: kfree(dev); return ret; } static void vicodec_remove(struct platform_device *pdev) { struct vicodec_dev *dev = platform_get_drvdata(pdev); v4l2_info(&dev->v4l2_dev, "Removing " VICODEC_NAME); #ifdef CONFIG_MEDIA_CONTROLLER media_device_unregister(&dev->mdev); v4l2_m2m_unregister_media_controller(dev->stateful_enc.m2m_dev); v4l2_m2m_unregister_media_controller(dev->stateful_dec.m2m_dev); v4l2_m2m_unregister_media_controller(dev->stateless_dec.m2m_dev); #endif video_unregister_device(&dev->stateful_enc.vfd); video_unregister_device(&dev->stateful_dec.vfd); video_unregister_device(&dev->stateless_dec.vfd); v4l2_device_put(&dev->v4l2_dev); } static struct platform_driver vicodec_pdrv = { .probe = vicodec_probe, .remove_new = vicodec_remove, .driver = { .name = VICODEC_NAME, }, }; static void __exit vicodec_exit(void) { platform_driver_unregister(&vicodec_pdrv); platform_device_unregister(&vicodec_pdev); } static int __init vicodec_init(void) { int ret; ret = platform_device_register(&vicodec_pdev); if (ret) return ret; ret = platform_driver_register(&vicodec_pdrv); if (ret) platform_device_unregister(&vicodec_pdev); return ret; } module_init(vicodec_init); module_exit(vicodec_exit);
linux-master
drivers/media/test-drivers/vicodec/vicodec-core.c
// SPDX-License-Identifier: GPL-2.0 /* * Vidtv serves as a reference DVB driver and helps validate the existing APIs * in the media subsystem. It can also aid developers working on userspace * applications. * * This file contains the logic to translate the ES data for one access unit * from an encoder into MPEG TS packets. It does so by first encapsulating it * with a PES header and then splitting it into TS packets. * * Copyright (C) 2020 Daniel W. S. Almeida */ #define pr_fmt(fmt) KBUILD_MODNAME ":%s, %d: " fmt, __func__, __LINE__ #include <linux/types.h> #include <linux/printk.h> #include <linux/ratelimit.h> #include "vidtv_pes.h" #include "vidtv_common.h" #include "vidtv_encoder.h" #include "vidtv_ts.h" #define PRIVATE_STREAM_1_ID 0xbd /* private_stream_1. See SMPTE 302M-2007 p.6 */ #define PES_HEADER_MAX_STUFFING_BYTES 32 #define PES_TS_HEADER_MAX_STUFFING_BYTES 182 static u32 vidtv_pes_op_get_len(bool send_pts, bool send_dts) { u32 len = 0; /* the flags must always be sent */ len += sizeof(struct vidtv_pes_optional); /* From all optionals, we might send these for now */ if (send_pts && send_dts) len += sizeof(struct vidtv_pes_optional_pts_dts); else if (send_pts) len += sizeof(struct vidtv_pes_optional_pts); return len; } #define SIZE_PCR (6 + sizeof(struct vidtv_mpeg_ts_adaption)) static u32 vidtv_pes_h_get_len(bool send_pts, bool send_dts) { u32 len = 0; /* PES header length notwithstanding stuffing bytes */ len += sizeof(struct vidtv_mpeg_pes); len += vidtv_pes_op_get_len(send_pts, send_dts); return len; } static u32 vidtv_pes_write_header_stuffing(struct pes_header_write_args *args) { /* * This is a fixed 8-bit value equal to '0xFF' that can be inserted * by the encoder, for example to meet the requirements of the channel. * It is discarded by the decoder. No more than 32 stuffing bytes shall * be present in one PES packet header. */ if (args->n_pes_h_s_bytes > PES_HEADER_MAX_STUFFING_BYTES) { pr_warn_ratelimited("More than %d stuffing bytes in PES packet header\n", PES_HEADER_MAX_STUFFING_BYTES); args->n_pes_h_s_bytes = PES_HEADER_MAX_STUFFING_BYTES; } return vidtv_memset(args->dest_buf, args->dest_offset, args->dest_buf_sz, TS_FILL_BYTE, args->n_pes_h_s_bytes); } static u32 vidtv_pes_write_pts_dts(struct pes_header_write_args *args) { u32 nbytes = 0; /* the number of bytes written by this function */ struct vidtv_pes_optional_pts pts = {}; struct vidtv_pes_optional_pts_dts pts_dts = {}; void *op = NULL; size_t op_sz = 0; u64 mask1; u64 mask2; u64 mask3; if (!args->send_pts && args->send_dts) return 0; mask1 = GENMASK_ULL(32, 30); mask2 = GENMASK_ULL(29, 15); mask3 = GENMASK_ULL(14, 0); /* see ISO/IEC 13818-1 : 2000 p. 32 */ if (args->send_pts && args->send_dts) { pts_dts.pts1 = (0x3 << 4) | ((args->pts & mask1) >> 29) | 0x1; pts_dts.pts2 = cpu_to_be16(((args->pts & mask2) >> 14) | 0x1); pts_dts.pts3 = cpu_to_be16(((args->pts & mask3) << 1) | 0x1); pts_dts.dts1 = (0x1 << 4) | ((args->dts & mask1) >> 29) | 0x1; pts_dts.dts2 = cpu_to_be16(((args->dts & mask2) >> 14) | 0x1); pts_dts.dts3 = cpu_to_be16(((args->dts & mask3) << 1) | 0x1); op = &pts_dts; op_sz = sizeof(pts_dts); } else if (args->send_pts) { pts.pts1 = (0x1 << 5) | ((args->pts & mask1) >> 29) | 0x1; pts.pts2 = cpu_to_be16(((args->pts & mask2) >> 14) | 0x1); pts.pts3 = cpu_to_be16(((args->pts & mask3) << 1) | 0x1); op = &pts; op_sz = sizeof(pts); } /* copy PTS/DTS optional */ nbytes += vidtv_memcpy(args->dest_buf, args->dest_offset + nbytes, args->dest_buf_sz, op, op_sz); return nbytes; } static u32 vidtv_pes_write_h(struct pes_header_write_args *args) { u32 nbytes = 0; /* the number of bytes written by this function */ struct vidtv_mpeg_pes pes_header = {}; struct vidtv_pes_optional pes_optional = {}; struct pes_header_write_args pts_dts_args; u32 stream_id = (args->encoder_id == S302M) ? PRIVATE_STREAM_1_ID : args->stream_id; u16 pes_opt_bitfield = 0x01 << 15; pes_header.bitfield = cpu_to_be32((PES_START_CODE_PREFIX << 8) | stream_id); pes_header.length = cpu_to_be16(vidtv_pes_op_get_len(args->send_pts, args->send_dts) + args->access_unit_len); if (args->send_pts && args->send_dts) pes_opt_bitfield |= (0x3 << 6); else if (args->send_pts) pes_opt_bitfield |= (0x1 << 7); pes_optional.bitfield = cpu_to_be16(pes_opt_bitfield); pes_optional.length = vidtv_pes_op_get_len(args->send_pts, args->send_dts) + args->n_pes_h_s_bytes - sizeof(struct vidtv_pes_optional); /* copy header */ nbytes += vidtv_memcpy(args->dest_buf, args->dest_offset + nbytes, args->dest_buf_sz, &pes_header, sizeof(pes_header)); /* copy optional header bits */ nbytes += vidtv_memcpy(args->dest_buf, args->dest_offset + nbytes, args->dest_buf_sz, &pes_optional, sizeof(pes_optional)); /* copy the timing information */ pts_dts_args = *args; pts_dts_args.dest_offset = args->dest_offset + nbytes; nbytes += vidtv_pes_write_pts_dts(&pts_dts_args); /* write any PES header stuffing */ nbytes += vidtv_pes_write_header_stuffing(args); return nbytes; } static u32 vidtv_pes_write_pcr_bits(u8 *to, u32 to_offset, u64 pcr) { /* Exact same from ffmpeg. PCR is a counter driven by a 27Mhz clock */ u64 div; u64 rem; u8 *buf = to + to_offset; u64 pcr_low; u64 pcr_high; div = div64_u64_rem(pcr, 300, &rem); pcr_low = rem; /* pcr_low = pcr % 300 */ pcr_high = div; /* pcr_high = pcr / 300 */ *buf++ = pcr_high >> 25; *buf++ = pcr_high >> 17; *buf++ = pcr_high >> 9; *buf++ = pcr_high >> 1; *buf++ = pcr_high << 7 | pcr_low >> 8 | 0x7e; *buf++ = pcr_low; return 6; } static u32 vidtv_pes_write_stuffing(struct pes_ts_header_write_args *args, u32 dest_offset, bool need_pcr, u64 *last_pcr) { struct vidtv_mpeg_ts_adaption ts_adap = {}; int stuff_nbytes; u32 nbytes = 0; if (!args->n_stuffing_bytes) return 0; ts_adap.random_access = 1; /* length _immediately_ following 'adaptation_field_length' */ if (need_pcr) { ts_adap.PCR = 1; ts_adap.length = SIZE_PCR; } else { ts_adap.length = sizeof(ts_adap); } stuff_nbytes = args->n_stuffing_bytes - ts_adap.length; ts_adap.length -= sizeof(ts_adap.length); if (unlikely(stuff_nbytes < 0)) stuff_nbytes = 0; ts_adap.length += stuff_nbytes; /* write the adap after the TS header */ nbytes += vidtv_memcpy(args->dest_buf, dest_offset + nbytes, args->dest_buf_sz, &ts_adap, sizeof(ts_adap)); /* write the optional PCR */ if (need_pcr) { nbytes += vidtv_pes_write_pcr_bits(args->dest_buf, dest_offset + nbytes, args->pcr); *last_pcr = args->pcr; } /* write the stuffing bytes, if are there anything left */ if (stuff_nbytes) nbytes += vidtv_memset(args->dest_buf, dest_offset + nbytes, args->dest_buf_sz, TS_FILL_BYTE, stuff_nbytes); /* * The n_stuffing_bytes contain a pre-calculated value of * the amount of data that this function would read, made from * vidtv_pes_h_get_len(). If something went wrong, print a warning */ if (nbytes != args->n_stuffing_bytes) pr_warn_ratelimited("write size was %d, expected %d\n", nbytes, args->n_stuffing_bytes); return nbytes; } static u32 vidtv_pes_write_ts_h(struct pes_ts_header_write_args args, bool need_pcr, u64 *last_pcr) { /* number of bytes written by this function */ u32 nbytes = 0; struct vidtv_mpeg_ts ts_header = {}; u16 payload_start = !args.wrote_pes_header; ts_header.sync_byte = TS_SYNC_BYTE; ts_header.bitfield = cpu_to_be16((payload_start << 14) | args.pid); ts_header.scrambling = 0; ts_header.adaptation_field = (args.n_stuffing_bytes) > 0; ts_header.payload = (args.n_stuffing_bytes) < PES_TS_HEADER_MAX_STUFFING_BYTES; ts_header.continuity_counter = *args.continuity_counter; vidtv_ts_inc_cc(args.continuity_counter); /* write the TS header */ nbytes += vidtv_memcpy(args.dest_buf, args.dest_offset + nbytes, args.dest_buf_sz, &ts_header, sizeof(ts_header)); /* write stuffing, if any */ nbytes += vidtv_pes_write_stuffing(&args, args.dest_offset + nbytes, need_pcr, last_pcr); return nbytes; } u32 vidtv_pes_write_into(struct pes_write_args *args) { u32 unaligned_bytes = (args->dest_offset % TS_PACKET_LEN); struct pes_ts_header_write_args ts_header_args = { .dest_buf = args->dest_buf, .dest_buf_sz = args->dest_buf_sz, .pid = args->pid, .pcr = args->pcr, .continuity_counter = args->continuity_counter, }; struct pes_header_write_args pes_header_args = { .dest_buf = args->dest_buf, .dest_buf_sz = args->dest_buf_sz, .encoder_id = args->encoder_id, .send_pts = args->send_pts, .pts = args->pts, .send_dts = args->send_dts, .dts = args->dts, .stream_id = args->stream_id, .n_pes_h_s_bytes = args->n_pes_h_s_bytes, .access_unit_len = args->access_unit_len, }; u32 remaining_len = args->access_unit_len; bool wrote_pes_header = false; u64 last_pcr = args->pcr; bool need_pcr = true; u32 available_space; u32 payload_size; u32 stuff_bytes; u32 nbytes = 0; if (unaligned_bytes) { pr_warn_ratelimited("buffer is misaligned, while starting PES\n"); /* forcibly align and hope for the best */ nbytes += vidtv_memset(args->dest_buf, args->dest_offset + nbytes, args->dest_buf_sz, TS_FILL_BYTE, TS_PACKET_LEN - unaligned_bytes); } while (remaining_len) { available_space = TS_PAYLOAD_LEN; /* * The amount of space initially available in the TS packet. * if this is the beginning of the PES packet, take into account * the space needed for the TS header _and_ for the PES header */ if (!wrote_pes_header) available_space -= vidtv_pes_h_get_len(args->send_pts, args->send_dts); /* * if the encoder has inserted stuffing bytes in the PES * header, account for them. */ available_space -= args->n_pes_h_s_bytes; /* Take the extra adaptation into account if need to send PCR */ if (need_pcr) { available_space -= SIZE_PCR; stuff_bytes = SIZE_PCR; } else { stuff_bytes = 0; } /* * how much of the _actual_ payload should be written in this * packet. */ if (remaining_len >= available_space) { payload_size = available_space; } else { /* Last frame should ensure 188-bytes PS alignment */ payload_size = remaining_len; stuff_bytes += available_space - payload_size; /* * Ensure that the stuff bytes will be within the * allowed range, decrementing the number of payload * bytes to write if needed. */ if (stuff_bytes > PES_TS_HEADER_MAX_STUFFING_BYTES) { u32 tmp = stuff_bytes - PES_TS_HEADER_MAX_STUFFING_BYTES; stuff_bytes = PES_TS_HEADER_MAX_STUFFING_BYTES; payload_size -= tmp; } } /* write ts header */ ts_header_args.dest_offset = args->dest_offset + nbytes; ts_header_args.wrote_pes_header = wrote_pes_header; ts_header_args.n_stuffing_bytes = stuff_bytes; nbytes += vidtv_pes_write_ts_h(ts_header_args, need_pcr, &last_pcr); need_pcr = false; if (!wrote_pes_header) { /* write the PES header only once */ pes_header_args.dest_offset = args->dest_offset + nbytes; nbytes += vidtv_pes_write_h(&pes_header_args); wrote_pes_header = true; } /* write as much of the payload as we possibly can */ nbytes += vidtv_memcpy(args->dest_buf, args->dest_offset + nbytes, args->dest_buf_sz, args->from, payload_size); args->from += payload_size; remaining_len -= payload_size; } return nbytes; }
linux-master
drivers/media/test-drivers/vidtv/vidtv_pes.c
// SPDX-License-Identifier: GPL-2.0 /* * Vidtv serves as a reference DVB driver and helps validate the existing APIs * in the media subsystem. It can also aid developers working on userspace * applications. * * This file contains the code for a 'channel' abstraction. * * When vidtv boots, it will create some hardcoded channels. * Their services will be concatenated to populate the SDT. * Their programs will be concatenated to populate the PAT * Their events will be concatenated to populate the EIT * For each program in the PAT, a PMT section will be created * The PMT section for a channel will be assigned its streams. * Every stream will have its corresponding encoder polled to produce TS packets * These packets may be interleaved by the mux and then delivered to the bridge * * * Copyright (C) 2020 Daniel W. S. Almeida */ #include <linux/dev_printk.h> #include <linux/ratelimit.h> #include <linux/slab.h> #include <linux/types.h> #include "vidtv_channel.h" #include "vidtv_common.h" #include "vidtv_encoder.h" #include "vidtv_mux.h" #include "vidtv_psi.h" #include "vidtv_s302m.h" static void vidtv_channel_encoder_destroy(struct vidtv_encoder *e) { struct vidtv_encoder *tmp = NULL; struct vidtv_encoder *curr = e; while (curr) { /* forward the call to the derived type */ tmp = curr; curr = curr->next; tmp->destroy(tmp); } } #define ENCODING_ISO8859_15 "\x0b" #define TS_NIT_PID 0x10 /* * init an audio only channel with a s302m encoder */ struct vidtv_channel *vidtv_channel_s302m_init(struct vidtv_channel *head, u16 transport_stream_id) { const __be32 s302m_fid = cpu_to_be32(VIDTV_S302M_FORMAT_IDENTIFIER); char *event_text = ENCODING_ISO8859_15 "Bagatelle No. 25 in A minor for solo piano, also known as F\xfcr Elise, composed by Ludwig van Beethoven"; char *event_name = ENCODING_ISO8859_15 "Ludwig van Beethoven: F\xfcr Elise"; struct vidtv_s302m_encoder_init_args encoder_args = {}; char *iso_language_code = ENCODING_ISO8859_15 "eng"; char *provider = ENCODING_ISO8859_15 "LinuxTV.org"; char *name = ENCODING_ISO8859_15 "Beethoven"; const u16 s302m_es_pid = 0x111; /* packet id for the ES */ const u16 s302m_program_pid = 0x101; /* packet id for PMT*/ const u16 s302m_service_id = 0x880; const u16 s302m_program_num = 0x880; const u16 s302m_beethoven_event_id = 1; struct vidtv_channel *s302m; s302m = kzalloc(sizeof(*s302m), GFP_KERNEL); if (!s302m) return NULL; s302m->name = kstrdup(name, GFP_KERNEL); if (!s302m->name) goto free_s302m; s302m->service = vidtv_psi_sdt_service_init(NULL, s302m_service_id, false, true); if (!s302m->service) goto free_name; s302m->service->descriptor = (struct vidtv_psi_desc *) vidtv_psi_service_desc_init(NULL, DIGITAL_RADIO_SOUND_SERVICE, name, provider); if (!s302m->service->descriptor) goto free_service; s302m->transport_stream_id = transport_stream_id; s302m->program = vidtv_psi_pat_program_init(NULL, s302m_service_id, s302m_program_pid); if (!s302m->program) goto free_service; s302m->program_num = s302m_program_num; s302m->streams = vidtv_psi_pmt_stream_init(NULL, STREAM_PRIVATE_DATA, s302m_es_pid); if (!s302m->streams) goto free_program; s302m->streams->descriptor = (struct vidtv_psi_desc *) vidtv_psi_registration_desc_init(NULL, s302m_fid, NULL, 0); if (!s302m->streams->descriptor) goto free_streams; encoder_args.es_pid = s302m_es_pid; s302m->encoders = vidtv_s302m_encoder_init(encoder_args); if (!s302m->encoders) goto free_streams; s302m->events = vidtv_psi_eit_event_init(NULL, s302m_beethoven_event_id); if (!s302m->events) goto free_encoders; s302m->events->descriptor = (struct vidtv_psi_desc *) vidtv_psi_short_event_desc_init(NULL, iso_language_code, event_name, event_text); if (!s302m->events->descriptor) goto free_events; if (head) { while (head->next) head = head->next; head->next = s302m; } return s302m; free_events: vidtv_psi_eit_event_destroy(s302m->events); free_encoders: vidtv_s302m_encoder_destroy(s302m->encoders); free_streams: vidtv_psi_pmt_stream_destroy(s302m->streams); free_program: vidtv_psi_pat_program_destroy(s302m->program); free_service: vidtv_psi_sdt_service_destroy(s302m->service); free_name: kfree(s302m->name); free_s302m: kfree(s302m); return NULL; } static struct vidtv_psi_table_eit_event *vidtv_channel_eit_event_cat_into_new(struct vidtv_mux *m) { /* Concatenate the events */ const struct vidtv_channel *cur_chnl = m->channels; struct vidtv_psi_table_eit_event *curr = NULL; struct vidtv_psi_table_eit_event *head = NULL; struct vidtv_psi_table_eit_event *tail = NULL; struct vidtv_psi_desc *desc = NULL; u16 event_id; if (!cur_chnl) return NULL; while (cur_chnl) { curr = cur_chnl->events; if (!curr) dev_warn_ratelimited(m->dev, "No events found for channel %s\n", cur_chnl->name); while (curr) { event_id = be16_to_cpu(curr->event_id); tail = vidtv_psi_eit_event_init(tail, event_id); if (!tail) { vidtv_psi_eit_event_destroy(head); return NULL; } desc = vidtv_psi_desc_clone(curr->descriptor); vidtv_psi_desc_assign(&tail->descriptor, desc); if (!head) head = tail; curr = curr->next; } cur_chnl = cur_chnl->next; } return head; } static struct vidtv_psi_table_sdt_service *vidtv_channel_sdt_serv_cat_into_new(struct vidtv_mux *m) { /* Concatenate the services */ const struct vidtv_channel *cur_chnl = m->channels; struct vidtv_psi_table_sdt_service *curr = NULL; struct vidtv_psi_table_sdt_service *head = NULL; struct vidtv_psi_table_sdt_service *tail = NULL; struct vidtv_psi_desc *desc = NULL; u16 service_id; if (!cur_chnl) return NULL; while (cur_chnl) { curr = cur_chnl->service; if (!curr) dev_warn_ratelimited(m->dev, "No services found for channel %s\n", cur_chnl->name); while (curr) { service_id = be16_to_cpu(curr->service_id); tail = vidtv_psi_sdt_service_init(tail, service_id, curr->EIT_schedule, curr->EIT_present_following); if (!tail) goto free; desc = vidtv_psi_desc_clone(curr->descriptor); if (!desc) goto free_tail; vidtv_psi_desc_assign(&tail->descriptor, desc); if (!head) head = tail; curr = curr->next; } cur_chnl = cur_chnl->next; } return head; free_tail: vidtv_psi_sdt_service_destroy(tail); free: vidtv_psi_sdt_service_destroy(head); return NULL; } static struct vidtv_psi_table_pat_program* vidtv_channel_pat_prog_cat_into_new(struct vidtv_mux *m) { /* Concatenate the programs */ const struct vidtv_channel *cur_chnl = m->channels; struct vidtv_psi_table_pat_program *curr = NULL; struct vidtv_psi_table_pat_program *head = NULL; struct vidtv_psi_table_pat_program *tail = NULL; u16 serv_id; u16 pid; if (!cur_chnl) return NULL; while (cur_chnl) { curr = cur_chnl->program; if (!curr) dev_warn_ratelimited(m->dev, "No programs found for channel %s\n", cur_chnl->name); while (curr) { serv_id = be16_to_cpu(curr->service_id); pid = vidtv_psi_get_pat_program_pid(curr); tail = vidtv_psi_pat_program_init(tail, serv_id, pid); if (!tail) { vidtv_psi_pat_program_destroy(head); return NULL; } if (!head) head = tail; curr = curr->next; } cur_chnl = cur_chnl->next; } /* Add the NIT table */ vidtv_psi_pat_program_init(tail, 0, TS_NIT_PID); return head; } /* * Match channels to their respective PMT sections, then assign the * streams */ static void vidtv_channel_pmt_match_sections(struct vidtv_channel *channels, struct vidtv_psi_table_pmt **sections, u32 nsections) { struct vidtv_psi_table_pmt *curr_section = NULL; struct vidtv_psi_table_pmt_stream *head = NULL; struct vidtv_psi_table_pmt_stream *tail = NULL; struct vidtv_psi_table_pmt_stream *s = NULL; struct vidtv_channel *cur_chnl = channels; struct vidtv_psi_desc *desc = NULL; u16 e_pid; /* elementary stream pid */ u16 curr_id; u32 j; while (cur_chnl) { for (j = 0; j < nsections; ++j) { curr_section = sections[j]; if (!curr_section) continue; curr_id = be16_to_cpu(curr_section->header.id); /* we got a match */ if (curr_id == cur_chnl->program_num) { s = cur_chnl->streams; /* clone the streams for the PMT */ while (s) { e_pid = vidtv_psi_pmt_stream_get_elem_pid(s); tail = vidtv_psi_pmt_stream_init(tail, s->type, e_pid); if (!head) head = tail; desc = vidtv_psi_desc_clone(s->descriptor); vidtv_psi_desc_assign(&tail->descriptor, desc); s = s->next; } vidtv_psi_pmt_stream_assign(curr_section, head); break; } } cur_chnl = cur_chnl->next; } } static void vidtv_channel_destroy_service_list(struct vidtv_psi_desc_service_list_entry *e) { struct vidtv_psi_desc_service_list_entry *tmp; while (e) { tmp = e; e = e->next; kfree(tmp); } } static struct vidtv_psi_desc_service_list_entry *vidtv_channel_build_service_list(struct vidtv_psi_table_sdt_service *s) { struct vidtv_psi_desc_service_list_entry *curr_e = NULL; struct vidtv_psi_desc_service_list_entry *head_e = NULL; struct vidtv_psi_desc_service_list_entry *prev_e = NULL; struct vidtv_psi_desc *desc = s->descriptor; struct vidtv_psi_desc_service *s_desc; while (s) { while (desc) { if (s->descriptor->type != SERVICE_DESCRIPTOR) goto next_desc; s_desc = (struct vidtv_psi_desc_service *)desc; curr_e = kzalloc(sizeof(*curr_e), GFP_KERNEL); if (!curr_e) { vidtv_channel_destroy_service_list(head_e); return NULL; } curr_e->service_id = s->service_id; curr_e->service_type = s_desc->service_type; if (!head_e) head_e = curr_e; if (prev_e) prev_e->next = curr_e; prev_e = curr_e; next_desc: desc = desc->next; } s = s->next; } return head_e; } int vidtv_channel_si_init(struct vidtv_mux *m) { struct vidtv_psi_desc_service_list_entry *service_list = NULL; struct vidtv_psi_table_pat_program *programs = NULL; struct vidtv_psi_table_sdt_service *services = NULL; struct vidtv_psi_table_eit_event *events = NULL; m->si.pat = vidtv_psi_pat_table_init(m->transport_stream_id); if (!m->si.pat) return -ENOMEM; m->si.sdt = vidtv_psi_sdt_table_init(m->network_id, m->transport_stream_id); if (!m->si.sdt) goto free_pat; programs = vidtv_channel_pat_prog_cat_into_new(m); if (!programs) goto free_sdt; services = vidtv_channel_sdt_serv_cat_into_new(m); if (!services) goto free_programs; events = vidtv_channel_eit_event_cat_into_new(m); if (!events) goto free_services; /* look for a service descriptor for every service */ service_list = vidtv_channel_build_service_list(services); if (!service_list) goto free_events; /* use these descriptors to build the NIT */ m->si.nit = vidtv_psi_nit_table_init(m->network_id, m->transport_stream_id, m->network_name, service_list); if (!m->si.nit) goto free_service_list; m->si.eit = vidtv_psi_eit_table_init(m->network_id, m->transport_stream_id, programs->service_id); if (!m->si.eit) goto free_nit; /* assemble all programs and assign to PAT */ vidtv_psi_pat_program_assign(m->si.pat, programs); /* assemble all services and assign to SDT */ vidtv_psi_sdt_service_assign(m->si.sdt, services); /* assemble all events and assign to EIT */ vidtv_psi_eit_event_assign(m->si.eit, events); m->si.pmt_secs = vidtv_psi_pmt_create_sec_for_each_pat_entry(m->si.pat, m->pcr_pid); if (!m->si.pmt_secs) goto free_eit; vidtv_channel_pmt_match_sections(m->channels, m->si.pmt_secs, m->si.pat->num_pmt); vidtv_channel_destroy_service_list(service_list); return 0; free_eit: vidtv_psi_eit_table_destroy(m->si.eit); free_nit: vidtv_psi_nit_table_destroy(m->si.nit); free_service_list: vidtv_channel_destroy_service_list(service_list); free_events: vidtv_psi_eit_event_destroy(events); free_services: vidtv_psi_sdt_service_destroy(services); free_programs: vidtv_psi_pat_program_destroy(programs); free_sdt: vidtv_psi_sdt_table_destroy(m->si.sdt); free_pat: vidtv_psi_pat_table_destroy(m->si.pat); return 0; } void vidtv_channel_si_destroy(struct vidtv_mux *m) { u32 i; for (i = 0; i < m->si.pat->num_pmt; ++i) vidtv_psi_pmt_table_destroy(m->si.pmt_secs[i]); vidtv_psi_pat_table_destroy(m->si.pat); kfree(m->si.pmt_secs); vidtv_psi_sdt_table_destroy(m->si.sdt); vidtv_psi_nit_table_destroy(m->si.nit); vidtv_psi_eit_table_destroy(m->si.eit); } int vidtv_channels_init(struct vidtv_mux *m) { /* this is the place to add new 'channels' for vidtv */ m->channels = vidtv_channel_s302m_init(NULL, m->transport_stream_id); if (!m->channels) return -ENOMEM; return 0; } void vidtv_channels_destroy(struct vidtv_mux *m) { struct vidtv_channel *curr = m->channels; struct vidtv_channel *tmp = NULL; while (curr) { kfree(curr->name); vidtv_psi_sdt_service_destroy(curr->service); vidtv_psi_pat_program_destroy(curr->program); vidtv_psi_pmt_stream_destroy(curr->streams); vidtv_channel_encoder_destroy(curr->encoders); vidtv_psi_eit_event_destroy(curr->events); tmp = curr; curr = curr->next; kfree(tmp); } }
linux-master
drivers/media/test-drivers/vidtv/vidtv_channel.c
// SPDX-License-Identifier: GPL-2.0 /* * The Virtual DVB test driver serves as a reference DVB driver and helps * validate the existing APIs in the media subsystem. It can also aid * developers working on userspace applications. * * Copyright (C) 2020 Daniel W. S. Almeida */ #define pr_fmt(fmt) KBUILD_MODNAME ":%s, %d: " fmt, __func__, __LINE__ #include <linux/printk.h> #include <linux/ratelimit.h> #include <linux/string.h> #include <linux/types.h> #include "vidtv_common.h" /** * vidtv_memcpy() - wrapper routine to be used by MPEG-TS * generator, in order to avoid going past the * output buffer. * @to: Starting element to where a MPEG-TS packet will * be copied. * @to_offset: Starting position of the @to buffer to be filled. * @to_size: Size of the @to buffer. * @from: Starting element of the buffer to be copied. * @len: Number of elements to be copy from @from buffer * into @to+ @to_offset buffer. * * Note: * Real digital TV demod drivers should not have memcpy * wrappers. We use it here because emulating MPEG-TS * generation at kernelspace requires some extra care. * * Return: * Returns the number of bytes written */ u32 vidtv_memcpy(void *to, size_t to_offset, size_t to_size, const void *from, size_t len) { if (unlikely(to_offset + len > to_size)) { pr_err_ratelimited("overflow detected, skipping. Try increasing the buffer size. Needed %zu, had %zu\n", to_offset + len, to_size); return 0; } memcpy(to + to_offset, from, len); return len; } /** * vidtv_memset() - wrapper routine to be used by MPEG-TS * generator, in order to avoid going past the * output buffer. * @to: Starting element to set * @to_offset: Starting position of the @to buffer to be filled. * @to_size: Size of the @to buffer. * @c: The value to set the memory to. * @len: Number of elements to be copy from @from buffer * into @to+ @to_offset buffer. * * Note: * Real digital TV demod drivers should not have memset * wrappers. We use it here because emulating MPEG-TS * generation at kernelspace requires some extra care. * * Return: * Returns the number of bytes written */ u32 vidtv_memset(void *to, size_t to_offset, size_t to_size, const int c, size_t len) { if (unlikely(to_offset + len > to_size)) { pr_err_ratelimited("overflow detected, skipping. Try increasing the buffer size. Needed %zu, had %zu\n", to_offset + len, to_size); return 0; } memset(to + to_offset, c, len); return len; }
linux-master
drivers/media/test-drivers/vidtv/vidtv_common.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * The Virtual DVB test driver serves as a reference DVB driver and helps * validate the existing APIs in the media subsystem. It can also aid * developers working on userspace applications. * * Copyright (C) 2020 Daniel W. S. Almeida * Based on the example driver written by Emard <[email protected]> */ #include <linux/errno.h> #include <linux/i2c.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/printk.h> #include <linux/random.h> #include <linux/ratelimit.h> #include <linux/slab.h> #include <linux/string.h> #include <linux/workqueue.h> #include <media/dvb_frontend.h> #include "vidtv_demod.h" #define POLL_THRD_TIME 2000 /* ms */ static const struct vidtv_demod_cnr_to_qual_s vidtv_demod_c_cnr_2_qual[] = { /* from libdvbv5 source code, in milli db */ { QAM_256, FEC_NONE, 34000, 38000}, { QAM_64, FEC_NONE, 30000, 34000}, }; static const struct vidtv_demod_cnr_to_qual_s vidtv_demod_s_cnr_2_qual[] = { /* from libdvbv5 source code, in milli db */ { QPSK, FEC_1_2, 7000, 10000}, { QPSK, FEC_2_3, 9000, 12000}, { QPSK, FEC_3_4, 10000, 13000}, { QPSK, FEC_5_6, 11000, 14000}, { QPSK, FEC_7_8, 12000, 15000}, }; static const struct vidtv_demod_cnr_to_qual_s vidtv_demod_s2_cnr_2_qual[] = { /* from libdvbv5 source code, in milli db */ { QPSK, FEC_1_2, 9000, 12000}, { QPSK, FEC_2_3, 11000, 14000}, { QPSK, FEC_3_4, 12000, 15000}, { QPSK, FEC_5_6, 12000, 15000}, { QPSK, FEC_8_9, 13000, 16000}, { QPSK, FEC_9_10, 13500, 16500}, { PSK_8, FEC_2_3, 14500, 17500}, { PSK_8, FEC_3_4, 16000, 19000}, { PSK_8, FEC_5_6, 17500, 20500}, { PSK_8, FEC_8_9, 19000, 22000}, }; static const struct vidtv_demod_cnr_to_qual_s vidtv_demod_t_cnr_2_qual[] = { /* from libdvbv5 source code, in milli db*/ { QPSK, FEC_1_2, 4100, 5900}, { QPSK, FEC_2_3, 6100, 9600}, { QPSK, FEC_3_4, 7200, 12400}, { QPSK, FEC_5_6, 8500, 15600}, { QPSK, FEC_7_8, 9200, 17500}, { QAM_16, FEC_1_2, 9800, 11800}, { QAM_16, FEC_2_3, 12100, 15300}, { QAM_16, FEC_3_4, 13400, 18100}, { QAM_16, FEC_5_6, 14800, 21300}, { QAM_16, FEC_7_8, 15700, 23600}, { QAM_64, FEC_1_2, 14000, 16000}, { QAM_64, FEC_2_3, 19900, 25400}, { QAM_64, FEC_3_4, 24900, 27900}, { QAM_64, FEC_5_6, 21300, 23300}, { QAM_64, FEC_7_8, 22000, 24000}, }; static const struct vidtv_demod_cnr_to_qual_s *vidtv_match_cnr_s(struct dvb_frontend *fe) { const struct vidtv_demod_cnr_to_qual_s *cnr2qual = NULL; struct device *dev = fe->dvb->device; struct dtv_frontend_properties *c; u32 array_size = 0; u32 i; c = &fe->dtv_property_cache; switch (c->delivery_system) { case SYS_DVBT: case SYS_DVBT2: cnr2qual = vidtv_demod_t_cnr_2_qual; array_size = ARRAY_SIZE(vidtv_demod_t_cnr_2_qual); break; case SYS_DVBS: cnr2qual = vidtv_demod_s_cnr_2_qual; array_size = ARRAY_SIZE(vidtv_demod_s_cnr_2_qual); break; case SYS_DVBS2: cnr2qual = vidtv_demod_s2_cnr_2_qual; array_size = ARRAY_SIZE(vidtv_demod_s2_cnr_2_qual); break; case SYS_DVBC_ANNEX_A: cnr2qual = vidtv_demod_c_cnr_2_qual; array_size = ARRAY_SIZE(vidtv_demod_c_cnr_2_qual); break; default: dev_warn_ratelimited(dev, "%s: unsupported delivery system: %u\n", __func__, c->delivery_system); break; } for (i = 0; i < array_size; i++) if (cnr2qual[i].modulation == c->modulation && cnr2qual[i].fec == c->fec_inner) return &cnr2qual[i]; return NULL; /* not found */ } static void vidtv_clean_stats(struct dvb_frontend *fe) { struct dtv_frontend_properties *c = &fe->dtv_property_cache; /* Fill the length of each status counter */ /* Signal is always available */ c->strength.len = 1; c->strength.stat[0].scale = FE_SCALE_DECIBEL; c->strength.stat[0].svalue = 0; /* Usually available only after Viterbi lock */ c->cnr.stat[0].scale = FE_SCALE_NOT_AVAILABLE; c->cnr.stat[0].svalue = 0; c->cnr.len = 1; /* Those depends on full lock */ c->pre_bit_error.stat[0].scale = FE_SCALE_NOT_AVAILABLE; c->pre_bit_error.stat[0].uvalue = 0; c->pre_bit_error.len = 1; c->pre_bit_count.stat[0].scale = FE_SCALE_NOT_AVAILABLE; c->pre_bit_count.stat[0].uvalue = 0; c->pre_bit_count.len = 1; c->post_bit_error.stat[0].scale = FE_SCALE_NOT_AVAILABLE; c->post_bit_error.stat[0].uvalue = 0; c->post_bit_error.len = 1; c->post_bit_count.stat[0].scale = FE_SCALE_NOT_AVAILABLE; c->post_bit_count.stat[0].uvalue = 0; c->post_bit_count.len = 1; c->block_error.stat[0].scale = FE_SCALE_NOT_AVAILABLE; c->block_error.stat[0].uvalue = 0; c->block_error.len = 1; c->block_count.stat[0].scale = FE_SCALE_NOT_AVAILABLE; c->block_count.stat[0].uvalue = 0; c->block_count.len = 1; } static void vidtv_demod_update_stats(struct dvb_frontend *fe) { struct dtv_frontend_properties *c = &fe->dtv_property_cache; struct vidtv_demod_state *state = fe->demodulator_priv; u32 scale; if (state->status & FE_HAS_LOCK) { scale = FE_SCALE_COUNTER; c->cnr.stat[0].scale = FE_SCALE_DECIBEL; } else { scale = FE_SCALE_NOT_AVAILABLE; c->cnr.stat[0].scale = scale; } c->pre_bit_error.stat[0].scale = scale; c->pre_bit_count.stat[0].scale = scale; c->post_bit_error.stat[0].scale = scale; c->post_bit_count.stat[0].scale = scale; c->block_error.stat[0].scale = scale; c->block_count.stat[0].scale = scale; /* * Add a 0.5% of randomness at the signal strength and CNR, * and make them different, as we want to have something closer * to a real case scenario. * * Also, usually, signal strength is a negative number in dBm. */ c->strength.stat[0].svalue = state->tuner_cnr; c->strength.stat[0].svalue -= get_random_u32_below(state->tuner_cnr / 50); c->strength.stat[0].svalue -= 68000; /* Adjust to a better range */ c->cnr.stat[0].svalue = state->tuner_cnr; c->cnr.stat[0].svalue -= get_random_u32_below(state->tuner_cnr / 50); } static int vidtv_demod_read_status(struct dvb_frontend *fe, enum fe_status *status) { struct vidtv_demod_state *state = fe->demodulator_priv; const struct vidtv_demod_cnr_to_qual_s *cnr2qual = NULL; struct vidtv_demod_config *config = &state->config; u16 snr = 0; /* Simulate random lost of signal due to a bad-tuned channel */ cnr2qual = vidtv_match_cnr_s(&state->frontend); if (cnr2qual && state->tuner_cnr < cnr2qual->cnr_good && state->frontend.ops.tuner_ops.get_rf_strength) { state->frontend.ops.tuner_ops.get_rf_strength(&state->frontend, &snr); if (snr < cnr2qual->cnr_ok) { /* eventually lose the TS lock */ if (get_random_u32_below(100) < config->drop_tslock_prob_on_low_snr) state->status = 0; } else { /* recover if the signal improves */ if (get_random_u32_below(100) < config->recover_tslock_prob_on_good_snr) state->status = FE_HAS_SIGNAL | FE_HAS_CARRIER | FE_HAS_VITERBI | FE_HAS_SYNC | FE_HAS_LOCK; } } vidtv_demod_update_stats(&state->frontend); *status = state->status; return 0; } static int vidtv_demod_read_signal_strength(struct dvb_frontend *fe, u16 *strength) { struct dtv_frontend_properties *c = &fe->dtv_property_cache; *strength = c->strength.stat[0].uvalue; return 0; } /* * NOTE: * This is implemented here just to be used as an example for real * demod drivers. * * Should only be implemented if it actually reads something from the hardware. * Also, it should check for the locks, in order to avoid report wrong data * to userspace. */ static int vidtv_demod_get_frontend(struct dvb_frontend *fe, struct dtv_frontend_properties *p) { return 0; } static int vidtv_demod_set_frontend(struct dvb_frontend *fe) { struct vidtv_demod_state *state = fe->demodulator_priv; u32 tuner_status = 0; int ret; if (!fe->ops.tuner_ops.set_params) return 0; fe->ops.tuner_ops.set_params(fe); /* store the CNR returned by the tuner */ ret = fe->ops.tuner_ops.get_rf_strength(fe, &state->tuner_cnr); if (ret < 0) return ret; fe->ops.tuner_ops.get_status(fe, &tuner_status); state->status = (state->tuner_cnr > 0) ? FE_HAS_SIGNAL | FE_HAS_CARRIER | FE_HAS_VITERBI | FE_HAS_SYNC | FE_HAS_LOCK : 0; vidtv_demod_update_stats(fe); if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 0); return 0; } /* * NOTE: * This is implemented here just to be used as an example for real * demod drivers. * * Should only be implemented if the demod has support for DVB-S or DVB-S2 */ static int vidtv_demod_set_tone(struct dvb_frontend *fe, enum fe_sec_tone_mode tone) { return 0; } /* * NOTE: * This is implemented here just to be used as an example for real * demod drivers. * * Should only be implemented if the demod has support for DVB-S or DVB-S2 */ static int vidtv_demod_set_voltage(struct dvb_frontend *fe, enum fe_sec_voltage voltage) { return 0; } /* * NOTE: * This is implemented here just to be used as an example for real * demod drivers. * * Should only be implemented if the demod has support for DVB-S or DVB-S2 */ static int vidtv_send_diseqc_msg(struct dvb_frontend *fe, struct dvb_diseqc_master_cmd *cmd) { return 0; } /* * NOTE: * This is implemented here just to be used as an example for real * demod drivers. * * Should only be implemented if the demod has support for DVB-S or DVB-S2 */ static int vidtv_diseqc_send_burst(struct dvb_frontend *fe, enum fe_sec_mini_cmd burst) { return 0; } static void vidtv_demod_release(struct dvb_frontend *fe) { struct vidtv_demod_state *state = fe->demodulator_priv; kfree(state); } static const struct dvb_frontend_ops vidtv_demod_ops = { .delsys = { SYS_DVBT, SYS_DVBT2, SYS_DVBC_ANNEX_A, SYS_DVBS, SYS_DVBS2, }, .info = { .name = "Dummy demod for DVB-T/T2/C/S/S2", .frequency_min_hz = 51 * MHz, .frequency_max_hz = 2150 * MHz, .frequency_stepsize_hz = 62500, .frequency_tolerance_hz = 29500 * kHz, .symbol_rate_min = 1000000, .symbol_rate_max = 45000000, .caps = FE_CAN_FEC_1_2 | FE_CAN_FEC_2_3 | FE_CAN_FEC_3_4 | FE_CAN_FEC_4_5 | FE_CAN_FEC_5_6 | FE_CAN_FEC_6_7 | FE_CAN_FEC_7_8 | FE_CAN_FEC_8_9 | FE_CAN_QAM_16 | FE_CAN_QAM_64 | FE_CAN_QAM_32 | FE_CAN_QAM_128 | FE_CAN_QAM_256 | FE_CAN_QAM_AUTO | FE_CAN_QPSK | FE_CAN_FEC_AUTO | FE_CAN_INVERSION_AUTO | FE_CAN_TRANSMISSION_MODE_AUTO | FE_CAN_GUARD_INTERVAL_AUTO | FE_CAN_HIERARCHY_AUTO, }, .release = vidtv_demod_release, .set_frontend = vidtv_demod_set_frontend, .get_frontend = vidtv_demod_get_frontend, .read_status = vidtv_demod_read_status, .read_signal_strength = vidtv_demod_read_signal_strength, /* For DVB-S/S2 */ .set_voltage = vidtv_demod_set_voltage, .set_tone = vidtv_demod_set_tone, .diseqc_send_master_cmd = vidtv_send_diseqc_msg, .diseqc_send_burst = vidtv_diseqc_send_burst, }; static const struct i2c_device_id vidtv_demod_i2c_id_table[] = { {"dvb_vidtv_demod", 0}, {} }; MODULE_DEVICE_TABLE(i2c, vidtv_demod_i2c_id_table); static int vidtv_demod_i2c_probe(struct i2c_client *client) { struct vidtv_tuner_config *config = client->dev.platform_data; struct vidtv_demod_state *state; /* allocate memory for the internal state */ state = kzalloc(sizeof(*state), GFP_KERNEL); if (!state) return -ENOMEM; /* create dvb_frontend */ memcpy(&state->frontend.ops, &vidtv_demod_ops, sizeof(struct dvb_frontend_ops)); memcpy(&state->config, config, sizeof(state->config)); state->frontend.demodulator_priv = state; i2c_set_clientdata(client, state); vidtv_clean_stats(&state->frontend); return 0; } static void vidtv_demod_i2c_remove(struct i2c_client *client) { struct vidtv_demod_state *state = i2c_get_clientdata(client); kfree(state); } static struct i2c_driver vidtv_demod_i2c_driver = { .driver = { .name = "dvb_vidtv_demod", .suppress_bind_attrs = true, }, .probe = vidtv_demod_i2c_probe, .remove = vidtv_demod_i2c_remove, .id_table = vidtv_demod_i2c_id_table, }; module_i2c_driver(vidtv_demod_i2c_driver); MODULE_DESCRIPTION("Virtual DVB Demodulator Driver"); MODULE_AUTHOR("Daniel W. S. Almeida"); MODULE_LICENSE("GPL");
linux-master
drivers/media/test-drivers/vidtv/vidtv_demod.c
// SPDX-License-Identifier: GPL-2.0 /* * Vidtv serves as a reference DVB driver and helps validate the existing APIs * in the media subsystem. It can also aid developers working on userspace * applications. * * This file contains the code for an AES3 (also known as AES/EBU) encoder. * It is based on EBU Tech 3250 and SMPTE 302M technical documents. * * This encoder currently supports 16bit AES3 subframes using 16bit signed * integers. * * Note: AU stands for Access Unit, and AAU stands for Audio Access Unit * * Copyright (C) 2020 Daniel W. S. Almeida */ #define pr_fmt(fmt) KBUILD_MODNAME ":%s, %d: " fmt, __func__, __LINE__ #include <linux/bug.h> #include <linux/crc32.h> #include <linux/fixp-arith.h> #include <linux/jiffies.h> #include <linux/kernel.h> #include <linux/math64.h> #include <linux/printk.h> #include <linux/ratelimit.h> #include <linux/slab.h> #include <linux/string.h> #include <linux/types.h> #include <linux/vmalloc.h> #include "vidtv_common.h" #include "vidtv_encoder.h" #include "vidtv_s302m.h" #define S302M_SAMPLING_RATE_HZ 48000 #define PES_PRIVATE_STREAM_1 0xbd /* PES: private_stream_1 */ #define S302M_BLOCK_SZ 192 #define S302M_SIN_LUT_NUM_ELEM 1024 /* these are retrieved empirically from ffmpeg/libavcodec */ #define FF_S302M_DEFAULT_NUM_FRAMES 1115 #define FF_S302M_DEFAULT_PTS_INCREMENT 2090 #define FF_S302M_DEFAULT_PTS_OFFSET 100000 /* Used by the tone generator: number of samples for PI */ #define PI 180 static const u8 reverse[256] = { /* from ffmpeg */ 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0, 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0, 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8, 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8, 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4, 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4, 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC, 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC, 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2, 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2, 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA, 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA, 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6, 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6, 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE, 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE, 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1, 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1, 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9, 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9, 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5, 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5, 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED, 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD, 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3, 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3, 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB, 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB, 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7, 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7, 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF, 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF, }; struct tone_duration { enum musical_notes note; int duration; }; #define COMPASS 100 /* beats per minute */ static const struct tone_duration beethoven_fur_elise[] = { { NOTE_SILENT, 512}, { NOTE_E_6, 128}, { NOTE_DS_6, 128}, { NOTE_E_6, 128}, { NOTE_DS_6, 128}, { NOTE_E_6, 128}, { NOTE_B_5, 128}, { NOTE_D_6, 128}, { NOTE_C_6, 128}, { NOTE_A_3, 128}, { NOTE_E_4, 128}, { NOTE_A_4, 128}, { NOTE_C_5, 128}, { NOTE_E_5, 128}, { NOTE_A_5, 128}, { NOTE_E_3, 128}, { NOTE_E_4, 128}, { NOTE_GS_4, 128}, { NOTE_E_5, 128}, { NOTE_GS_5, 128}, { NOTE_B_5, 128}, { NOTE_A_3, 128}, { NOTE_E_4, 128}, { NOTE_A_4, 128}, { NOTE_E_5, 128}, { NOTE_E_6, 128}, { NOTE_DS_6, 128}, { NOTE_E_6, 128}, { NOTE_DS_6, 128}, { NOTE_E_6, 128}, { NOTE_B_5, 128}, { NOTE_D_6, 128}, { NOTE_C_6, 128}, { NOTE_A_3, 128}, { NOTE_E_4, 128}, { NOTE_A_4, 128}, { NOTE_C_5, 128}, { NOTE_E_5, 128}, { NOTE_A_5, 128}, { NOTE_E_3, 128}, { NOTE_E_4, 128}, { NOTE_GS_4, 128}, { NOTE_E_5, 128}, { NOTE_C_6, 128}, { NOTE_B_5, 128}, { NOTE_A_3, 128}, { NOTE_E_4, 128}, { NOTE_A_4, 128}, { NOTE_SILENT, 128}, { NOTE_E_6, 128}, { NOTE_DS_6, 128}, { NOTE_E_6, 128}, { NOTE_DS_6, 128}, { NOTE_E_6, 128}, { NOTE_B_5, 128}, { NOTE_D_6, 128}, { NOTE_C_6, 128}, { NOTE_A_3, 128}, { NOTE_E_4, 128}, { NOTE_A_4, 128}, { NOTE_C_5, 128}, { NOTE_E_5, 128}, { NOTE_A_5, 128}, { NOTE_E_3, 128}, { NOTE_E_4, 128}, { NOTE_GS_4, 128}, { NOTE_E_5, 128}, { NOTE_GS_5, 128}, { NOTE_B_5, 128}, { NOTE_A_3, 128}, { NOTE_E_4, 128}, { NOTE_A_4, 128}, { NOTE_E_5, 128}, { NOTE_E_6, 128}, { NOTE_DS_6, 128}, { NOTE_E_6, 128}, { NOTE_DS_6, 128}, { NOTE_E_6, 128}, { NOTE_B_5, 128}, { NOTE_D_6, 128}, { NOTE_C_6, 128}, { NOTE_A_3, 128}, { NOTE_E_4, 128}, { NOTE_A_4, 128}, { NOTE_C_5, 128}, { NOTE_E_5, 128}, { NOTE_A_5, 128}, { NOTE_E_3, 128}, { NOTE_E_4, 128}, { NOTE_GS_4, 128}, { NOTE_E_5, 128}, { NOTE_C_6, 128}, { NOTE_B_5, 128}, { NOTE_A_3, 128}, { NOTE_E_4, 128}, { NOTE_A_4, 128}, { NOTE_B_4, 128}, { NOTE_C_5, 128}, { NOTE_D_5, 128}, { NOTE_C_4, 128}, { NOTE_G_4, 128}, { NOTE_C_5, 128}, { NOTE_G_4, 128}, { NOTE_F_5, 128}, { NOTE_E_5, 128}, { NOTE_G_3, 128}, { NOTE_G_4, 128}, { NOTE_B_3, 128}, { NOTE_F_4, 128}, { NOTE_E_5, 128}, { NOTE_D_5, 128}, { NOTE_A_3, 128}, { NOTE_E_4, 128}, { NOTE_A_4, 128}, { NOTE_E_4, 128}, { NOTE_D_5, 128}, { NOTE_C_5, 128}, { NOTE_E_3, 128}, { NOTE_E_4, 128}, { NOTE_E_5, 128}, { NOTE_E_5, 128}, { NOTE_E_6, 128}, { NOTE_E_5, 128}, { NOTE_E_6, 128}, { NOTE_E_5, 128}, { NOTE_E_5, 128}, { NOTE_DS_5, 128}, { NOTE_E_5, 128}, { NOTE_DS_6, 128}, { NOTE_E_6, 128}, { NOTE_DS_5, 128}, { NOTE_E_5, 128}, { NOTE_DS_6, 128}, { NOTE_E_6, 128}, { NOTE_DS_6, 128}, { NOTE_E_6, 128}, { NOTE_DS_6, 128}, { NOTE_E_6, 128}, { NOTE_B_5, 128}, { NOTE_D_6, 128}, { NOTE_C_6, 128}, { NOTE_A_3, 128}, { NOTE_E_4, 128}, { NOTE_A_4, 128}, { NOTE_C_5, 128}, { NOTE_E_5, 128}, { NOTE_A_5, 128}, { NOTE_E_3, 128}, { NOTE_E_4, 128}, { NOTE_GS_4, 128}, { NOTE_E_5, 128}, { NOTE_GS_5, 128}, { NOTE_B_5, 128}, { NOTE_A_3, 128}, { NOTE_E_4, 128}, { NOTE_A_4, 128}, { NOTE_E_5, 128}, { NOTE_E_6, 128}, { NOTE_DS_6, 128}, { NOTE_E_6, 128}, { NOTE_DS_6, 128}, { NOTE_E_6, 128}, { NOTE_B_5, 128}, { NOTE_D_6, 128}, { NOTE_C_6, 128}, { NOTE_A_3, 128}, { NOTE_E_4, 128}, { NOTE_A_4, 128}, { NOTE_C_5, 128}, { NOTE_E_5, 128}, { NOTE_A_5, 128}, { NOTE_E_3, 128}, { NOTE_E_4, 128}, { NOTE_GS_4, 128}, { NOTE_E_5, 128}, { NOTE_C_6, 128}, { NOTE_B_5, 128}, { NOTE_A_5, 512}, { NOTE_SILENT, 256}, }; static struct vidtv_access_unit *vidtv_s302m_access_unit_init(struct vidtv_access_unit *head) { struct vidtv_access_unit *au; au = kzalloc(sizeof(*au), GFP_KERNEL); if (!au) return NULL; if (head) { while (head->next) head = head->next; head->next = au; } return au; } static void vidtv_s302m_access_unit_destroy(struct vidtv_encoder *e) { struct vidtv_access_unit *head = e->access_units; struct vidtv_access_unit *tmp = NULL; while (head) { tmp = head; head = head->next; kfree(tmp); } e->access_units = NULL; } static void vidtv_s302m_alloc_au(struct vidtv_encoder *e) { struct vidtv_access_unit *sync_au = NULL; struct vidtv_access_unit *temp = NULL; if (e->sync && e->sync->is_video_encoder) { sync_au = e->sync->access_units; while (sync_au) { temp = vidtv_s302m_access_unit_init(e->access_units); if (!e->access_units) e->access_units = temp; sync_au = sync_au->next; } return; } e->access_units = vidtv_s302m_access_unit_init(NULL); } static void vidtv_s302m_compute_sample_count_from_video(struct vidtv_encoder *e) { struct vidtv_access_unit *sync_au = e->sync->access_units; struct vidtv_access_unit *au = e->access_units; u32 sample_duration_usecs; u32 vau_duration_usecs; u32 s; vau_duration_usecs = USEC_PER_SEC / e->sync->sampling_rate_hz; sample_duration_usecs = USEC_PER_SEC / e->sampling_rate_hz; while (au && sync_au) { s = DIV_ROUND_UP(vau_duration_usecs, sample_duration_usecs); au->num_samples = s; au = au->next; sync_au = sync_au->next; } } static void vidtv_s302m_compute_pts_from_video(struct vidtv_encoder *e) { struct vidtv_access_unit *au = e->access_units; struct vidtv_access_unit *sync_au = e->sync->access_units; /* use the same pts from the video access unit*/ while (au && sync_au) { au->pts = sync_au->pts; au = au->next; sync_au = sync_au->next; } } static u16 vidtv_s302m_get_sample(struct vidtv_encoder *e) { u16 sample; int pos; struct vidtv_s302m_ctx *ctx = e->ctx; if (!e->src_buf) { /* * Simple tone generator: play the tones at the * beethoven_fur_elise array. */ if (ctx->last_duration <= 0) { if (e->src_buf_offset >= ARRAY_SIZE(beethoven_fur_elise)) e->src_buf_offset = 0; ctx->last_tone = beethoven_fur_elise[e->src_buf_offset].note; ctx->last_duration = beethoven_fur_elise[e->src_buf_offset].duration * S302M_SAMPLING_RATE_HZ / COMPASS / 5; e->src_buf_offset++; ctx->note_offset = 0; } else { ctx->last_duration--; } /* Handle pause notes */ if (!ctx->last_tone) return 0x8000; pos = (2 * PI * ctx->note_offset * ctx->last_tone) / S302M_SAMPLING_RATE_HZ; ctx->note_offset++; return (fixp_sin32(pos % (2 * PI)) >> 16) + 0x8000; } /* bug somewhere */ if (e->src_buf_offset > e->src_buf_sz) { pr_err_ratelimited("overflow detected: %d > %d, wrapping.\n", e->src_buf_offset, e->src_buf_sz); e->src_buf_offset = 0; } if (e->src_buf_offset >= e->src_buf_sz) { /* let the source know we are out of data */ if (e->last_sample_cb) e->last_sample_cb(e->sample_count); e->src_buf_offset = 0; } sample = *(u16 *)(e->src_buf + e->src_buf_offset); return sample; } static u32 vidtv_s302m_write_frame(struct vidtv_encoder *e, u16 sample) { struct vidtv_s302m_ctx *ctx = e->ctx; struct vidtv_s302m_frame_16 f = {}; u32 nbytes = 0; /* from ffmpeg: see s302enc.c */ u8 vucf = ctx->frame_index == 0 ? 0x10 : 0; f.data[0] = sample & 0xFF; f.data[1] = (sample & 0xFF00) >> 8; f.data[2] = ((sample & 0x0F) << 4) | vucf; f.data[3] = (sample & 0x0FF0) >> 4; f.data[4] = (sample & 0xF000) >> 12; f.data[0] = reverse[f.data[0]]; f.data[1] = reverse[f.data[1]]; f.data[2] = reverse[f.data[2]]; f.data[3] = reverse[f.data[3]]; f.data[4] = reverse[f.data[4]]; nbytes += vidtv_memcpy(e->encoder_buf, e->encoder_buf_offset, VIDTV_S302M_BUF_SZ, &f, sizeof(f)); e->encoder_buf_offset += nbytes; ctx->frame_index++; if (ctx->frame_index >= S302M_BLOCK_SZ) ctx->frame_index = 0; return nbytes; } static u32 vidtv_s302m_write_h(struct vidtv_encoder *e, u32 p_sz) { struct vidtv_smpte_s302m_es h = {}; u32 nbytes = 0; /* 2 channels, ident: 0, 16 bits per sample */ h.bitfield = cpu_to_be32((p_sz << 16)); nbytes += vidtv_memcpy(e->encoder_buf, e->encoder_buf_offset, e->encoder_buf_sz, &h, sizeof(h)); e->encoder_buf_offset += nbytes; return nbytes; } static void vidtv_s302m_write_frames(struct vidtv_encoder *e) { struct vidtv_access_unit *au = e->access_units; struct vidtv_s302m_ctx *ctx = e->ctx; u32 nbytes_per_unit = 0; u32 nbytes = 0; u32 au_sz = 0; u16 sample; u32 j; while (au) { au_sz = au->num_samples * sizeof(struct vidtv_s302m_frame_16); nbytes_per_unit = vidtv_s302m_write_h(e, au_sz); for (j = 0; j < au->num_samples; ++j) { sample = vidtv_s302m_get_sample(e); nbytes_per_unit += vidtv_s302m_write_frame(e, sample); if (e->src_buf) e->src_buf_offset += sizeof(u16); e->sample_count++; } au->nbytes = nbytes_per_unit; if (au_sz + sizeof(struct vidtv_smpte_s302m_es) != nbytes_per_unit) { pr_warn_ratelimited("write size was %u, expected %zu\n", nbytes_per_unit, au_sz + sizeof(struct vidtv_smpte_s302m_es)); } nbytes += nbytes_per_unit; au->offset = nbytes - nbytes_per_unit; nbytes_per_unit = 0; ctx->au_count++; au = au->next; } } static void *vidtv_s302m_encode(struct vidtv_encoder *e) { struct vidtv_s302m_ctx *ctx = e->ctx; /* * According to SMPTE 302M, an audio access unit is specified as those * AES3 words that are associated with a corresponding video frame. * Therefore, there is one audio access unit for every video access unit * in the corresponding video encoder ('sync'), using the same values * for PTS as used by the video encoder. * * Assuming that it is also possible to send audio without any * associated video, as in a radio-like service, a single audio access unit * is created with values for 'num_samples' and 'pts' taken empirically from * ffmpeg */ vidtv_s302m_access_unit_destroy(e); vidtv_s302m_alloc_au(e); if (e->sync && e->sync->is_video_encoder) { vidtv_s302m_compute_sample_count_from_video(e); vidtv_s302m_compute_pts_from_video(e); } else { e->access_units->num_samples = FF_S302M_DEFAULT_NUM_FRAMES; e->access_units->pts = (ctx->au_count * FF_S302M_DEFAULT_PTS_INCREMENT) + FF_S302M_DEFAULT_PTS_OFFSET; } vidtv_s302m_write_frames(e); return e->encoder_buf; } static u32 vidtv_s302m_clear(struct vidtv_encoder *e) { struct vidtv_access_unit *au = e->access_units; u32 count = 0; while (au) { count++; au = au->next; } vidtv_s302m_access_unit_destroy(e); memset(e->encoder_buf, 0, VIDTV_S302M_BUF_SZ); e->encoder_buf_offset = 0; return count; } struct vidtv_encoder *vidtv_s302m_encoder_init(struct vidtv_s302m_encoder_init_args args) { u32 priv_sz = sizeof(struct vidtv_s302m_ctx); struct vidtv_s302m_ctx *ctx; struct vidtv_encoder *e; e = kzalloc(sizeof(*e), GFP_KERNEL); if (!e) return NULL; e->id = S302M; if (args.name) e->name = kstrdup(args.name, GFP_KERNEL); e->encoder_buf = vzalloc(VIDTV_S302M_BUF_SZ); if (!e->encoder_buf) goto out_kfree_e; e->encoder_buf_sz = VIDTV_S302M_BUF_SZ; e->encoder_buf_offset = 0; e->sample_count = 0; e->src_buf = (args.src_buf) ? args.src_buf : NULL; e->src_buf_sz = (args.src_buf) ? args.src_buf_sz : 0; e->src_buf_offset = 0; e->is_video_encoder = false; ctx = kzalloc(priv_sz, GFP_KERNEL); if (!ctx) goto out_kfree_buf; e->ctx = ctx; ctx->last_duration = 0; e->encode = vidtv_s302m_encode; e->clear = vidtv_s302m_clear; e->es_pid = cpu_to_be16(args.es_pid); e->stream_id = cpu_to_be16(PES_PRIVATE_STREAM_1); e->sync = args.sync; e->sampling_rate_hz = S302M_SAMPLING_RATE_HZ; e->last_sample_cb = args.last_sample_cb; e->destroy = vidtv_s302m_encoder_destroy; if (args.head) { while (args.head->next) args.head = args.head->next; args.head->next = e; } e->next = NULL; return e; out_kfree_buf: vfree(e->encoder_buf); out_kfree_e: kfree(e->name); kfree(e); return NULL; } void vidtv_s302m_encoder_destroy(struct vidtv_encoder *e) { if (e->id != S302M) { pr_err_ratelimited("Encoder type mismatch, skipping.\n"); return; } vidtv_s302m_access_unit_destroy(e); kfree(e->name); vfree(e->encoder_buf); kfree(e->ctx); kfree(e); }
linux-master
drivers/media/test-drivers/vidtv/vidtv_s302m.c
// SPDX-License-Identifier: GPL-2.0 /* * Vidtv serves as a reference DVB driver and helps validate the existing APIs * in the media subsystem. It can also aid developers working on userspace * applications. * * This file contains the multiplexer logic for TS packets from different * elementary streams * * Loosely based on libavcodec/mpegtsenc.c * * Copyright (C) 2020 Daniel W. S. Almeida */ #include <linux/delay.h> #include <linux/dev_printk.h> #include <linux/jiffies.h> #include <linux/kernel.h> #include <linux/math64.h> #include <linux/ratelimit.h> #include <linux/slab.h> #include <linux/types.h> #include <linux/vmalloc.h> #include "vidtv_channel.h" #include "vidtv_common.h" #include "vidtv_encoder.h" #include "vidtv_mux.h" #include "vidtv_pes.h" #include "vidtv_psi.h" #include "vidtv_ts.h" static struct vidtv_mux_pid_ctx *vidtv_mux_get_pid_ctx(struct vidtv_mux *m, u16 pid) { struct vidtv_mux_pid_ctx *ctx; hash_for_each_possible(m->pid_ctx, ctx, h, pid) if (ctx->pid == pid) return ctx; return NULL; } static struct vidtv_mux_pid_ctx *vidtv_mux_create_pid_ctx_once(struct vidtv_mux *m, u16 pid) { struct vidtv_mux_pid_ctx *ctx; ctx = vidtv_mux_get_pid_ctx(m, pid); if (ctx) return ctx; ctx = kzalloc(sizeof(*ctx), GFP_KERNEL); if (!ctx) return NULL; ctx->pid = pid; ctx->cc = 0; hash_add(m->pid_ctx, &ctx->h, pid); return ctx; } static void vidtv_mux_pid_ctx_destroy(struct vidtv_mux *m) { struct vidtv_mux_pid_ctx *ctx; struct hlist_node *tmp; int bkt; hash_for_each_safe(m->pid_ctx, bkt, tmp, ctx, h) { hash_del(&ctx->h); kfree(ctx); } } static int vidtv_mux_pid_ctx_init(struct vidtv_mux *m) { struct vidtv_psi_table_pat_program *p = m->si.pat->program; u16 pid; hash_init(m->pid_ctx); /* push the pcr pid ctx */ if (!vidtv_mux_create_pid_ctx_once(m, m->pcr_pid)) return -ENOMEM; /* push the NULL packet pid ctx */ if (!vidtv_mux_create_pid_ctx_once(m, TS_NULL_PACKET_PID)) goto free; /* push the PAT pid ctx */ if (!vidtv_mux_create_pid_ctx_once(m, VIDTV_PAT_PID)) goto free; /* push the SDT pid ctx */ if (!vidtv_mux_create_pid_ctx_once(m, VIDTV_SDT_PID)) goto free; /* push the NIT pid ctx */ if (!vidtv_mux_create_pid_ctx_once(m, VIDTV_NIT_PID)) goto free; /* push the EIT pid ctx */ if (!vidtv_mux_create_pid_ctx_once(m, VIDTV_EIT_PID)) goto free; /* add a ctx for all PMT sections */ while (p) { pid = vidtv_psi_get_pat_program_pid(p); vidtv_mux_create_pid_ctx_once(m, pid); p = p->next; } return 0; free: vidtv_mux_pid_ctx_destroy(m); return -ENOMEM; } static void vidtv_mux_update_clk(struct vidtv_mux *m) { /* call this at every thread iteration */ u64 elapsed_time; m->timing.past_jiffies = m->timing.current_jiffies; m->timing.current_jiffies = get_jiffies_64(); elapsed_time = jiffies_to_usecs(m->timing.current_jiffies - m->timing.past_jiffies); /* update the 27Mhz clock proportionally to the elapsed time */ m->timing.clk += (CLOCK_UNIT_27MHZ / USEC_PER_SEC) * elapsed_time; } static u32 vidtv_mux_push_si(struct vidtv_mux *m) { struct vidtv_psi_pat_write_args pat_args = { .buf = m->mux_buf, .buf_sz = m->mux_buf_sz, .pat = m->si.pat, }; struct vidtv_psi_pmt_write_args pmt_args = { .buf = m->mux_buf, .buf_sz = m->mux_buf_sz, .pcr_pid = m->pcr_pid, }; struct vidtv_psi_sdt_write_args sdt_args = { .buf = m->mux_buf, .buf_sz = m->mux_buf_sz, .sdt = m->si.sdt, }; struct vidtv_psi_nit_write_args nit_args = { .buf = m->mux_buf, .buf_sz = m->mux_buf_sz, .nit = m->si.nit, }; struct vidtv_psi_eit_write_args eit_args = { .buf = m->mux_buf, .buf_sz = m->mux_buf_sz, .eit = m->si.eit, }; u32 initial_offset = m->mux_buf_offset; struct vidtv_mux_pid_ctx *pat_ctx; struct vidtv_mux_pid_ctx *pmt_ctx; struct vidtv_mux_pid_ctx *sdt_ctx; struct vidtv_mux_pid_ctx *nit_ctx; struct vidtv_mux_pid_ctx *eit_ctx; u32 nbytes; u16 pmt_pid; u32 i; pat_ctx = vidtv_mux_get_pid_ctx(m, VIDTV_PAT_PID); sdt_ctx = vidtv_mux_get_pid_ctx(m, VIDTV_SDT_PID); nit_ctx = vidtv_mux_get_pid_ctx(m, VIDTV_NIT_PID); eit_ctx = vidtv_mux_get_pid_ctx(m, VIDTV_EIT_PID); pat_args.offset = m->mux_buf_offset; pat_args.continuity_counter = &pat_ctx->cc; m->mux_buf_offset += vidtv_psi_pat_write_into(&pat_args); for (i = 0; i < m->si.pat->num_pmt; ++i) { pmt_pid = vidtv_psi_pmt_get_pid(m->si.pmt_secs[i], m->si.pat); if (pmt_pid > TS_LAST_VALID_PID) { dev_warn_ratelimited(m->dev, "PID: %d not found\n", pmt_pid); continue; } pmt_ctx = vidtv_mux_get_pid_ctx(m, pmt_pid); pmt_args.offset = m->mux_buf_offset; pmt_args.pmt = m->si.pmt_secs[i]; pmt_args.pid = pmt_pid; pmt_args.continuity_counter = &pmt_ctx->cc; /* write each section into buffer */ m->mux_buf_offset += vidtv_psi_pmt_write_into(&pmt_args); } sdt_args.offset = m->mux_buf_offset; sdt_args.continuity_counter = &sdt_ctx->cc; m->mux_buf_offset += vidtv_psi_sdt_write_into(&sdt_args); nit_args.offset = m->mux_buf_offset; nit_args.continuity_counter = &nit_ctx->cc; m->mux_buf_offset += vidtv_psi_nit_write_into(&nit_args); eit_args.offset = m->mux_buf_offset; eit_args.continuity_counter = &eit_ctx->cc; m->mux_buf_offset += vidtv_psi_eit_write_into(&eit_args); nbytes = m->mux_buf_offset - initial_offset; m->num_streamed_si++; return nbytes; } static u32 vidtv_mux_push_pcr(struct vidtv_mux *m) { struct pcr_write_args args = {}; struct vidtv_mux_pid_ctx *ctx; u32 nbytes = 0; ctx = vidtv_mux_get_pid_ctx(m, m->pcr_pid); args.dest_buf = m->mux_buf; args.pid = m->pcr_pid; args.buf_sz = m->mux_buf_sz; args.continuity_counter = &ctx->cc; /* the 27Mhz clock will feed both parts of the PCR bitfield */ args.pcr = m->timing.clk; nbytes += vidtv_ts_pcr_write_into(args); m->mux_buf_offset += nbytes; m->num_streamed_pcr++; return nbytes; } static bool vidtv_mux_should_push_pcr(struct vidtv_mux *m) { u64 next_pcr_at; if (m->num_streamed_pcr == 0) return true; next_pcr_at = m->timing.start_jiffies + usecs_to_jiffies(m->num_streamed_pcr * m->timing.pcr_period_usecs); return time_after64(m->timing.current_jiffies, next_pcr_at); } static bool vidtv_mux_should_push_si(struct vidtv_mux *m) { u64 next_si_at; if (m->num_streamed_si == 0) return true; next_si_at = m->timing.start_jiffies + usecs_to_jiffies(m->num_streamed_si * m->timing.si_period_usecs); return time_after64(m->timing.current_jiffies, next_si_at); } static u32 vidtv_mux_packetize_access_units(struct vidtv_mux *m, struct vidtv_encoder *e) { struct pes_write_args args = { .dest_buf = m->mux_buf, .dest_buf_sz = m->mux_buf_sz, .pid = be16_to_cpu(e->es_pid), .encoder_id = e->id, .stream_id = be16_to_cpu(e->stream_id), .send_pts = true, /* forbidden value '01'... */ .send_dts = false, /* ...for PTS_DTS flags */ }; struct vidtv_access_unit *au = e->access_units; u32 initial_offset = m->mux_buf_offset; struct vidtv_mux_pid_ctx *pid_ctx; u32 nbytes = 0; u8 *buf = NULL; /* see SMPTE 302M clause 6.4 */ if (args.encoder_id == S302M) { args.send_dts = false; args.send_pts = true; } pid_ctx = vidtv_mux_create_pid_ctx_once(m, be16_to_cpu(e->es_pid)); args.continuity_counter = &pid_ctx->cc; while (au) { buf = e->encoder_buf + au->offset; args.from = buf; args.access_unit_len = au->nbytes; args.dest_offset = m->mux_buf_offset; args.pts = au->pts; args.pcr = m->timing.clk; m->mux_buf_offset += vidtv_pes_write_into(&args); au = au->next; } /* * clear the encoder state once the ES data has been written to the mux * buffer */ e->clear(e); nbytes = m->mux_buf_offset - initial_offset; return nbytes; } static u32 vidtv_mux_poll_encoders(struct vidtv_mux *m) { struct vidtv_channel *cur_chnl = m->channels; struct vidtv_encoder *e = NULL; u32 nbytes = 0; u32 au_nbytes; while (cur_chnl) { e = cur_chnl->encoders; while (e) { e->encode(e); /* get the TS packets into the mux buffer */ au_nbytes = vidtv_mux_packetize_access_units(m, e); nbytes += au_nbytes; m->mux_buf_offset += au_nbytes; /* grab next encoder */ e = e->next; } /* grab the next channel */ cur_chnl = cur_chnl->next; } return nbytes; } static u32 vidtv_mux_pad_with_nulls(struct vidtv_mux *m, u32 npkts) { struct null_packet_write_args args = { .dest_buf = m->mux_buf, .buf_sz = m->mux_buf_sz, .dest_offset = m->mux_buf_offset, }; u32 initial_offset = m->mux_buf_offset; struct vidtv_mux_pid_ctx *ctx; u32 nbytes; u32 i; ctx = vidtv_mux_get_pid_ctx(m, TS_NULL_PACKET_PID); args.continuity_counter = &ctx->cc; for (i = 0; i < npkts; ++i) { m->mux_buf_offset += vidtv_ts_null_write_into(args); args.dest_offset = m->mux_buf_offset; } nbytes = m->mux_buf_offset - initial_offset; /* sanity check */ if (nbytes != npkts * TS_PACKET_LEN) dev_err_ratelimited(m->dev, "%d != %d\n", nbytes, npkts * TS_PACKET_LEN); return nbytes; } static void vidtv_mux_clear(struct vidtv_mux *m) { /* clear the packets currently in the mux */ memset(m->mux_buf, 0, m->mux_buf_sz * sizeof(*m->mux_buf)); /* point to the beginning of the buffer again */ m->mux_buf_offset = 0; } #define ERR_RATE 10000000 static void vidtv_mux_tick(struct work_struct *work) { struct vidtv_mux *m = container_of(work, struct vidtv_mux, mpeg_thread); struct dtv_frontend_properties *c = &m->fe->dtv_property_cache; u32 tot_bits = 0; u32 nbytes; u32 npkts; while (m->streaming) { nbytes = 0; vidtv_mux_update_clk(m); if (vidtv_mux_should_push_pcr(m)) nbytes += vidtv_mux_push_pcr(m); if (vidtv_mux_should_push_si(m)) nbytes += vidtv_mux_push_si(m); nbytes += vidtv_mux_poll_encoders(m); nbytes += vidtv_mux_pad_with_nulls(m, 256); npkts = nbytes / TS_PACKET_LEN; /* if the buffer is not aligned there is a bug somewhere */ if (nbytes % TS_PACKET_LEN) dev_err_ratelimited(m->dev, "Misaligned buffer\n"); if (m->on_new_packets_available_cb) m->on_new_packets_available_cb(m->priv, m->mux_buf, npkts); vidtv_mux_clear(m); /* * Update bytes and packet counts at DVBv5 stats * * For now, both pre and post bit counts are identical, * but post BER count can be lower than pre BER, if the error * correction logic discards packages. */ c->pre_bit_count.stat[0].uvalue = nbytes * 8; c->post_bit_count.stat[0].uvalue = nbytes * 8; c->block_count.stat[0].uvalue += npkts; /* * Even without any visible errors for the user, the pre-BER * stats usually have an error range up to 1E-6. So, * add some random error increment count to it. * * Please notice that this is a poor guy's implementation, * as it will produce one corrected bit error every time * ceil(total bytes / ERR_RATE) is incremented, without * any sort of (pseudo-)randomness. */ tot_bits += nbytes * 8; if (tot_bits > ERR_RATE) { c->pre_bit_error.stat[0].uvalue++; tot_bits -= ERR_RATE; } usleep_range(VIDTV_SLEEP_USECS, VIDTV_MAX_SLEEP_USECS); } } void vidtv_mux_start_thread(struct vidtv_mux *m) { if (m->streaming) { dev_warn_ratelimited(m->dev, "Already streaming. Skipping.\n"); return; } m->streaming = true; m->timing.start_jiffies = get_jiffies_64(); schedule_work(&m->mpeg_thread); } void vidtv_mux_stop_thread(struct vidtv_mux *m) { if (m->streaming) { m->streaming = false; /* thread will quit */ cancel_work_sync(&m->mpeg_thread); } } struct vidtv_mux *vidtv_mux_init(struct dvb_frontend *fe, struct device *dev, struct vidtv_mux_init_args *args) { struct vidtv_mux *m; m = kzalloc(sizeof(*m), GFP_KERNEL); if (!m) return NULL; m->dev = dev; m->fe = fe; m->timing.pcr_period_usecs = args->pcr_period_usecs; m->timing.si_period_usecs = args->si_period_usecs; m->mux_rate_kbytes_sec = args->mux_rate_kbytes_sec; m->on_new_packets_available_cb = args->on_new_packets_available_cb; m->mux_buf = vzalloc(args->mux_buf_sz); if (!m->mux_buf) goto free_mux; m->mux_buf_sz = args->mux_buf_sz; m->pcr_pid = args->pcr_pid; m->transport_stream_id = args->transport_stream_id; m->priv = args->priv; m->network_id = args->network_id; m->network_name = kstrdup(args->network_name, GFP_KERNEL); m->timing.current_jiffies = get_jiffies_64(); if (args->channels) m->channels = args->channels; else if (vidtv_channels_init(m) < 0) goto free_mux_buf; /* will alloc data for pmt_sections after initializing pat */ if (vidtv_channel_si_init(m) < 0) goto free_channels; INIT_WORK(&m->mpeg_thread, vidtv_mux_tick); if (vidtv_mux_pid_ctx_init(m) < 0) goto free_channel_si; return m; free_channel_si: vidtv_channel_si_destroy(m); free_channels: vidtv_channels_destroy(m); free_mux_buf: vfree(m->mux_buf); free_mux: kfree(m); return NULL; } void vidtv_mux_destroy(struct vidtv_mux *m) { vidtv_mux_stop_thread(m); vidtv_mux_pid_ctx_destroy(m); vidtv_channel_si_destroy(m); vidtv_channels_destroy(m); kfree(m->network_name); vfree(m->mux_buf); kfree(m); }
linux-master
drivers/media/test-drivers/vidtv/vidtv_mux.c
// SPDX-License-Identifier: GPL-2.0 /* * The Virtual DVB test driver serves as a reference DVB driver and helps * validate the existing APIs in the media subsystem. It can also aid * developers working on userspace applications. * * Copyright (C) 2020 Daniel W. S. Almeida */ #define pr_fmt(fmt) KBUILD_MODNAME ":%s, %d: " fmt, __func__, __LINE__ #include <linux/math64.h> #include <linux/printk.h> #include <linux/ratelimit.h> #include <linux/types.h> #include "vidtv_common.h" #include "vidtv_ts.h" static u32 vidtv_ts_write_pcr_bits(u8 *to, u32 to_offset, u64 pcr) { /* Exact same from ffmpeg. PCR is a counter driven by a 27Mhz clock */ u64 div; u64 rem; u8 *buf = to + to_offset; u64 pcr_low; u64 pcr_high; div = div64_u64_rem(pcr, 300, &rem); pcr_low = rem; /* pcr_low = pcr % 300 */ pcr_high = div; /* pcr_high = pcr / 300 */ *buf++ = pcr_high >> 25; *buf++ = pcr_high >> 17; *buf++ = pcr_high >> 9; *buf++ = pcr_high >> 1; *buf++ = pcr_high << 7 | pcr_low >> 8 | 0x7e; *buf++ = pcr_low; return 6; } void vidtv_ts_inc_cc(u8 *continuity_counter) { ++*continuity_counter; if (*continuity_counter > TS_CC_MAX_VAL) *continuity_counter = 0; } u32 vidtv_ts_null_write_into(struct null_packet_write_args args) { u32 nbytes = 0; struct vidtv_mpeg_ts ts_header = {}; ts_header.sync_byte = TS_SYNC_BYTE; ts_header.bitfield = cpu_to_be16(TS_NULL_PACKET_PID); ts_header.payload = 1; ts_header.continuity_counter = *args.continuity_counter; /* copy TS header */ nbytes += vidtv_memcpy(args.dest_buf, args.dest_offset + nbytes, args.buf_sz, &ts_header, sizeof(ts_header)); vidtv_ts_inc_cc(args.continuity_counter); /* fill the rest with empty data */ nbytes += vidtv_memset(args.dest_buf, args.dest_offset + nbytes, args.buf_sz, TS_FILL_BYTE, TS_PACKET_LEN - nbytes); /* we should have written exactly _one_ 188byte packet */ if (nbytes != TS_PACKET_LEN) pr_warn_ratelimited("Expected exactly %d bytes, got %d\n", TS_PACKET_LEN, nbytes); return nbytes; } u32 vidtv_ts_pcr_write_into(struct pcr_write_args args) { u32 nbytes = 0; struct vidtv_mpeg_ts ts_header = {}; struct vidtv_mpeg_ts_adaption ts_adap = {}; ts_header.sync_byte = TS_SYNC_BYTE; ts_header.bitfield = cpu_to_be16(args.pid); ts_header.scrambling = 0; /* cc is not incremented, but it is needed. see 13818-1 clause 2.4.3.3 */ ts_header.continuity_counter = *args.continuity_counter; ts_header.payload = 0; ts_header.adaptation_field = 1; /* 13818-1 clause 2.4.3.5 */ ts_adap.length = 183; ts_adap.PCR = 1; /* copy TS header */ nbytes += vidtv_memcpy(args.dest_buf, args.dest_offset + nbytes, args.buf_sz, &ts_header, sizeof(ts_header)); /* write the adap after the TS header */ nbytes += vidtv_memcpy(args.dest_buf, args.dest_offset + nbytes, args.buf_sz, &ts_adap, sizeof(ts_adap)); /* write the PCR optional */ nbytes += vidtv_ts_write_pcr_bits(args.dest_buf, args.dest_offset + nbytes, args.pcr); nbytes += vidtv_memset(args.dest_buf, args.dest_offset + nbytes, args.buf_sz, TS_FILL_BYTE, TS_PACKET_LEN - nbytes); /* we should have written exactly _one_ 188byte packet */ if (nbytes != TS_PACKET_LEN) pr_warn_ratelimited("Expected exactly %d bytes, got %d\n", TS_PACKET_LEN, nbytes); return nbytes; }
linux-master
drivers/media/test-drivers/vidtv/vidtv_ts.c
// SPDX-License-Identifier: GPL-2.0 /* * The Virtual DVB test driver serves as a reference DVB driver and helps * validate the existing APIs in the media subsystem. It can also aid * developers working on userspace applications. * * The vidtv tuner should support common TV standards such as * DVB-T/T2/S/S2, ISDB-T and ATSC when completed. * * Copyright (C) 2020 Daniel W. S. Almeida */ #include <linux/errno.h> #include <linux/i2c.h> #include <linux/module.h> #include <linux/printk.h> #include <linux/ratelimit.h> #include <linux/slab.h> #include <linux/types.h> #include <media/dvb_frontend.h> #include "vidtv_tuner.h" struct vidtv_tuner_cnr_to_qual_s { /* attempt to use the same values as libdvbv5 */ u32 modulation; u32 fec; u32 cnr_ok; u32 cnr_good; }; static const struct vidtv_tuner_cnr_to_qual_s vidtv_tuner_c_cnr_2_qual[] = { /* from libdvbv5 source code, in milli db */ { QAM_256, FEC_NONE, 34000, 38000}, { QAM_64, FEC_NONE, 30000, 34000}, }; static const struct vidtv_tuner_cnr_to_qual_s vidtv_tuner_s_cnr_2_qual[] = { /* from libdvbv5 source code, in milli db */ { QPSK, FEC_1_2, 7000, 10000}, { QPSK, FEC_2_3, 9000, 12000}, { QPSK, FEC_3_4, 10000, 13000}, { QPSK, FEC_5_6, 11000, 14000}, { QPSK, FEC_7_8, 12000, 15000}, }; static const struct vidtv_tuner_cnr_to_qual_s vidtv_tuner_s2_cnr_2_qual[] = { /* from libdvbv5 source code, in milli db */ { QPSK, FEC_1_2, 9000, 12000}, { QPSK, FEC_2_3, 11000, 14000}, { QPSK, FEC_3_4, 12000, 15000}, { QPSK, FEC_5_6, 12000, 15000}, { QPSK, FEC_8_9, 13000, 16000}, { QPSK, FEC_9_10, 13500, 16500}, { PSK_8, FEC_2_3, 14500, 17500}, { PSK_8, FEC_3_4, 16000, 19000}, { PSK_8, FEC_5_6, 17500, 20500}, { PSK_8, FEC_8_9, 19000, 22000}, }; static const struct vidtv_tuner_cnr_to_qual_s vidtv_tuner_t_cnr_2_qual[] = { /* from libdvbv5 source code, in milli db*/ { QPSK, FEC_1_2, 4100, 5900}, { QPSK, FEC_2_3, 6100, 9600}, { QPSK, FEC_3_4, 7200, 12400}, { QPSK, FEC_5_6, 8500, 15600}, { QPSK, FEC_7_8, 9200, 17500}, { QAM_16, FEC_1_2, 9800, 11800}, { QAM_16, FEC_2_3, 12100, 15300}, { QAM_16, FEC_3_4, 13400, 18100}, { QAM_16, FEC_5_6, 14800, 21300}, { QAM_16, FEC_7_8, 15700, 23600}, { QAM_64, FEC_1_2, 14000, 16000}, { QAM_64, FEC_2_3, 19900, 25400}, { QAM_64, FEC_3_4, 24900, 27900}, { QAM_64, FEC_5_6, 21300, 23300}, { QAM_64, FEC_7_8, 22000, 24000}, }; /** * struct vidtv_tuner_hardware_state - Simulate the tuner hardware status * @asleep: whether the tuner is asleep, i.e whether _sleep() or _suspend() was * called. * @lock_status: Whether the tuner has managed to lock on the requested * frequency. * @if_frequency: The tuner's intermediate frequency. Hardcoded for the purposes * of simulation. * @tuned_frequency: The actual tuned frequency. * @bandwidth: The actual bandwidth. * * This structure is meant to simulate the status of the tuner hardware, as if * we had a physical tuner hardware. */ struct vidtv_tuner_hardware_state { bool asleep; u32 lock_status; u32 if_frequency; u32 tuned_frequency; u32 bandwidth; }; /** * struct vidtv_tuner_dev - The tuner struct * @fe: A pointer to the dvb_frontend structure allocated by vidtv_demod * @hw_state: A struct to simulate the tuner's hardware state as if we had a * physical tuner hardware. * @config: The configuration used to start the tuner module, usually filled * by a bridge driver. For vidtv, this is filled by vidtv_bridge before the * tuner module is probed. */ struct vidtv_tuner_dev { struct dvb_frontend *fe; struct vidtv_tuner_hardware_state hw_state; struct vidtv_tuner_config config; }; static struct vidtv_tuner_dev* vidtv_tuner_get_dev(struct dvb_frontend *fe) { return i2c_get_clientdata(fe->tuner_priv); } static int vidtv_tuner_check_frequency_shift(struct dvb_frontend *fe) { struct vidtv_tuner_dev *tuner_dev = vidtv_tuner_get_dev(fe); struct dtv_frontend_properties *c = &fe->dtv_property_cache; struct vidtv_tuner_config config = tuner_dev->config; u32 *valid_freqs = NULL; u32 array_sz = 0; u32 i; u32 shift; switch (c->delivery_system) { case SYS_DVBT: case SYS_DVBT2: valid_freqs = config.vidtv_valid_dvb_t_freqs; array_sz = ARRAY_SIZE(config.vidtv_valid_dvb_t_freqs); break; case SYS_DVBS: case SYS_DVBS2: valid_freqs = config.vidtv_valid_dvb_s_freqs; array_sz = ARRAY_SIZE(config.vidtv_valid_dvb_s_freqs); break; case SYS_DVBC_ANNEX_A: valid_freqs = config.vidtv_valid_dvb_c_freqs; array_sz = ARRAY_SIZE(config.vidtv_valid_dvb_c_freqs); break; default: dev_warn(fe->dvb->device, "%s: unsupported delivery system: %u\n", __func__, c->delivery_system); return -EINVAL; } for (i = 0; i < array_sz; i++) { if (!valid_freqs[i]) break; shift = abs(c->frequency - valid_freqs[i]); if (!shift) return 0; /* * This will provide a value from 0 to 100 that would * indicate how far is the tuned frequency from the * right one. */ if (shift < config.max_frequency_shift_hz) return shift * 100 / config.max_frequency_shift_hz; } return -EINVAL; } static int vidtv_tuner_get_signal_strength(struct dvb_frontend *fe, u16 *strength) { struct dtv_frontend_properties *c = &fe->dtv_property_cache; struct vidtv_tuner_dev *tuner_dev = vidtv_tuner_get_dev(fe); const struct vidtv_tuner_cnr_to_qual_s *cnr2qual = NULL; struct device *dev = fe->dvb->device; u32 array_size = 0; s32 shift; u32 i; shift = vidtv_tuner_check_frequency_shift(fe); if (shift < 0) { tuner_dev->hw_state.lock_status = 0; *strength = 0; return 0; } switch (c->delivery_system) { case SYS_DVBT: case SYS_DVBT2: cnr2qual = vidtv_tuner_t_cnr_2_qual; array_size = ARRAY_SIZE(vidtv_tuner_t_cnr_2_qual); break; case SYS_DVBS: cnr2qual = vidtv_tuner_s_cnr_2_qual; array_size = ARRAY_SIZE(vidtv_tuner_s_cnr_2_qual); break; case SYS_DVBS2: cnr2qual = vidtv_tuner_s2_cnr_2_qual; array_size = ARRAY_SIZE(vidtv_tuner_s2_cnr_2_qual); break; case SYS_DVBC_ANNEX_A: cnr2qual = vidtv_tuner_c_cnr_2_qual; array_size = ARRAY_SIZE(vidtv_tuner_c_cnr_2_qual); break; default: dev_warn_ratelimited(dev, "%s: unsupported delivery system: %u\n", __func__, c->delivery_system); return -EINVAL; } for (i = 0; i < array_size; i++) { if (cnr2qual[i].modulation != c->modulation || cnr2qual[i].fec != c->fec_inner) continue; if (!shift) { *strength = cnr2qual[i].cnr_good; return 0; } /* * Channel tuned at wrong frequency. Simulate that the * Carrier S/N ratio is not too good. */ *strength = cnr2qual[i].cnr_ok - (cnr2qual[i].cnr_good - cnr2qual[i].cnr_ok); return 0; } /* * do a linear interpolation between 34dB and 10dB if we can't * match against the table */ *strength = 34000 - 24000 * shift / 100; return 0; } static int vidtv_tuner_init(struct dvb_frontend *fe) { struct vidtv_tuner_dev *tuner_dev = vidtv_tuner_get_dev(fe); struct vidtv_tuner_config config = tuner_dev->config; msleep_interruptible(config.mock_power_up_delay_msec); tuner_dev->hw_state.asleep = false; tuner_dev->hw_state.if_frequency = 5000; return 0; } static int vidtv_tuner_sleep(struct dvb_frontend *fe) { struct vidtv_tuner_dev *tuner_dev = vidtv_tuner_get_dev(fe); tuner_dev->hw_state.asleep = true; return 0; } static int vidtv_tuner_suspend(struct dvb_frontend *fe) { struct vidtv_tuner_dev *tuner_dev = vidtv_tuner_get_dev(fe); tuner_dev->hw_state.asleep = true; return 0; } static int vidtv_tuner_resume(struct dvb_frontend *fe) { struct vidtv_tuner_dev *tuner_dev = vidtv_tuner_get_dev(fe); tuner_dev->hw_state.asleep = false; return 0; } static int vidtv_tuner_set_params(struct dvb_frontend *fe) { struct vidtv_tuner_dev *tuner_dev = vidtv_tuner_get_dev(fe); struct vidtv_tuner_config config = tuner_dev->config; struct dtv_frontend_properties *c = &fe->dtv_property_cache; s32 shift; u32 min_freq = fe->ops.tuner_ops.info.frequency_min_hz; u32 max_freq = fe->ops.tuner_ops.info.frequency_max_hz; u32 min_bw = fe->ops.tuner_ops.info.bandwidth_min; u32 max_bw = fe->ops.tuner_ops.info.bandwidth_max; if (c->frequency < min_freq || c->frequency > max_freq || c->bandwidth_hz < min_bw || c->bandwidth_hz > max_bw) { tuner_dev->hw_state.lock_status = 0; return -EINVAL; } tuner_dev->hw_state.tuned_frequency = c->frequency; tuner_dev->hw_state.bandwidth = c->bandwidth_hz; tuner_dev->hw_state.lock_status = TUNER_STATUS_LOCKED; msleep_interruptible(config.mock_tune_delay_msec); shift = vidtv_tuner_check_frequency_shift(fe); if (shift < 0) { tuner_dev->hw_state.lock_status = 0; return shift; } return 0; } static int vidtv_tuner_set_config(struct dvb_frontend *fe, void *priv_cfg) { struct vidtv_tuner_dev *tuner_dev = vidtv_tuner_get_dev(fe); memcpy(&tuner_dev->config, priv_cfg, sizeof(tuner_dev->config)); return 0; } static int vidtv_tuner_get_frequency(struct dvb_frontend *fe, u32 *frequency) { struct vidtv_tuner_dev *tuner_dev = vidtv_tuner_get_dev(fe); *frequency = tuner_dev->hw_state.tuned_frequency; return 0; } static int vidtv_tuner_get_bandwidth(struct dvb_frontend *fe, u32 *bandwidth) { struct vidtv_tuner_dev *tuner_dev = vidtv_tuner_get_dev(fe); *bandwidth = tuner_dev->hw_state.bandwidth; return 0; } static int vidtv_tuner_get_if_frequency(struct dvb_frontend *fe, u32 *frequency) { struct vidtv_tuner_dev *tuner_dev = vidtv_tuner_get_dev(fe); *frequency = tuner_dev->hw_state.if_frequency; return 0; } static int vidtv_tuner_get_status(struct dvb_frontend *fe, u32 *status) { struct vidtv_tuner_dev *tuner_dev = vidtv_tuner_get_dev(fe); *status = tuner_dev->hw_state.lock_status; return 0; } static const struct dvb_tuner_ops vidtv_tuner_ops = { .init = vidtv_tuner_init, .sleep = vidtv_tuner_sleep, .suspend = vidtv_tuner_suspend, .resume = vidtv_tuner_resume, .set_params = vidtv_tuner_set_params, .set_config = vidtv_tuner_set_config, .get_bandwidth = vidtv_tuner_get_bandwidth, .get_frequency = vidtv_tuner_get_frequency, .get_if_frequency = vidtv_tuner_get_if_frequency, .get_status = vidtv_tuner_get_status, .get_rf_strength = vidtv_tuner_get_signal_strength }; static const struct i2c_device_id vidtv_tuner_i2c_id_table[] = { {"dvb_vidtv_tuner", 0}, {} }; MODULE_DEVICE_TABLE(i2c, vidtv_tuner_i2c_id_table); static int vidtv_tuner_i2c_probe(struct i2c_client *client) { struct vidtv_tuner_config *config = client->dev.platform_data; struct dvb_frontend *fe = config->fe; struct vidtv_tuner_dev *tuner_dev = NULL; tuner_dev = kzalloc(sizeof(*tuner_dev), GFP_KERNEL); if (!tuner_dev) return -ENOMEM; tuner_dev->fe = config->fe; i2c_set_clientdata(client, tuner_dev); memcpy(&fe->ops.tuner_ops, &vidtv_tuner_ops, sizeof(struct dvb_tuner_ops)); memcpy(&tuner_dev->config, config, sizeof(tuner_dev->config)); fe->tuner_priv = client; return 0; } static void vidtv_tuner_i2c_remove(struct i2c_client *client) { struct vidtv_tuner_dev *tuner_dev = i2c_get_clientdata(client); kfree(tuner_dev); } static struct i2c_driver vidtv_tuner_i2c_driver = { .driver = { .name = "dvb_vidtv_tuner", .suppress_bind_attrs = true, }, .probe = vidtv_tuner_i2c_probe, .remove = vidtv_tuner_i2c_remove, .id_table = vidtv_tuner_i2c_id_table, }; module_i2c_driver(vidtv_tuner_i2c_driver); MODULE_DESCRIPTION("Virtual DVB Tuner"); MODULE_AUTHOR("Daniel W. S. Almeida"); MODULE_LICENSE("GPL");
linux-master
drivers/media/test-drivers/vidtv/vidtv_tuner.c
// SPDX-License-Identifier: GPL-2.0 /* * This file contains the logic to work with MPEG Program-Specific Information. * These are defined both in ISO/IEC 13818-1 (systems) and ETSI EN 300 468. * PSI is carried in the form of table structures, and although each table might * technically be broken into one or more sections, we do not do this here, * hence 'table' and 'section' are interchangeable for vidtv. * * Copyright (C) 2020 Daniel W. S. Almeida */ #define pr_fmt(fmt) KBUILD_MODNAME ":%s, %d: " fmt, __func__, __LINE__ #include <linux/bcd.h> #include <linux/crc32.h> #include <linux/kernel.h> #include <linux/ktime.h> #include <linux/printk.h> #include <linux/ratelimit.h> #include <linux/slab.h> #include <linux/string.h> #include <linux/time.h> #include <linux/types.h> #include "vidtv_common.h" #include "vidtv_psi.h" #include "vidtv_ts.h" #define CRC_SIZE_IN_BYTES 4 #define MAX_VERSION_NUM 32 #define INITIAL_CRC 0xffffffff #define ISO_LANGUAGE_CODE_LEN 3 static const u32 CRC_LUT[256] = { /* from libdvbv5 */ 0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005, 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61, 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd, 0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9, 0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75, 0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3, 0x709f7b7a, 0x745e66cd, 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039, 0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5, 0xbe2b5b58, 0xbaea46ef, 0xb7a96036, 0xb3687d81, 0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d, 0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49, 0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95, 0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1, 0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d, 0x34867077, 0x30476dc0, 0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072, 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16, 0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca, 0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde, 0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02, 0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, 0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba, 0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b, 0xbb60adfc, 0xb6238b25, 0xb2e29692, 0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6, 0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a, 0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e, 0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2, 0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34, 0xdc3abded, 0xd8fba05a, 0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637, 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb, 0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f, 0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53, 0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5, 0x3f9b762c, 0x3b5a6b9b, 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff, 0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623, 0xf12f560e, 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7, 0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b, 0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f, 0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3, 0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7, 0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b, 0x9b3660c6, 0x9ff77d71, 0x92b45ba8, 0x9675461f, 0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3, 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640, 0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c, 0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8, 0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24, 0x119b4be9, 0x155a565e, 0x18197087, 0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec, 0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d, 0x2056cd3a, 0x2d15ebe3, 0x29d4f654, 0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0, 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c, 0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18, 0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4, 0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662, 0x933eb0bb, 0x97ffad0c, 0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668, 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4 }; static u32 dvb_crc32(u32 crc, u8 *data, u32 len) { /* from libdvbv5 */ while (len--) crc = (crc << 8) ^ CRC_LUT[((crc >> 24) ^ *data++) & 0xff]; return crc; } static void vidtv_psi_update_version_num(struct vidtv_psi_table_header *h) { h->version++; } static u16 vidtv_psi_get_sec_len(struct vidtv_psi_table_header *h) { u16 mask; mask = GENMASK(11, 0); return be16_to_cpu(h->bitfield) & mask; } u16 vidtv_psi_get_pat_program_pid(struct vidtv_psi_table_pat_program *p) { u16 mask; mask = GENMASK(12, 0); return be16_to_cpu(p->bitfield) & mask; } u16 vidtv_psi_pmt_stream_get_elem_pid(struct vidtv_psi_table_pmt_stream *s) { u16 mask; mask = GENMASK(12, 0); return be16_to_cpu(s->bitfield) & mask; } static void vidtv_psi_set_desc_loop_len(__be16 *bitfield, u16 new_len, u8 desc_len_nbits) { __be16 new; u16 mask; mask = GENMASK(15, desc_len_nbits); new = cpu_to_be16((be16_to_cpu(*bitfield) & mask) | new_len); *bitfield = new; } static void vidtv_psi_set_sec_len(struct vidtv_psi_table_header *h, u16 new_len) { u16 old_len = vidtv_psi_get_sec_len(h); __be16 new; u16 mask; mask = GENMASK(15, 13); new = cpu_to_be16((be16_to_cpu(h->bitfield) & mask) | new_len); if (old_len > MAX_SECTION_LEN) pr_warn_ratelimited("section length: %d > %d, old len was %d\n", new_len, MAX_SECTION_LEN, old_len); h->bitfield = new; } /* * Packetize PSI sections into TS packets: * push a TS header (4bytes) every 184 bytes * manage the continuity_counter * add stuffing (i.e. padding bytes) after the CRC */ static u32 vidtv_psi_ts_psi_write_into(struct psi_write_args *args) { struct vidtv_mpeg_ts ts_header = { .sync_byte = TS_SYNC_BYTE, .bitfield = cpu_to_be16((args->new_psi_section << 14) | args->pid), .scrambling = 0, .payload = 1, .adaptation_field = 0, /* no adaptation field */ }; u32 nbytes_past_boundary = (args->dest_offset % TS_PACKET_LEN); bool aligned = (nbytes_past_boundary == 0); u32 remaining_len = args->len; u32 payload_write_len = 0; u32 payload_offset = 0; u32 nbytes = 0; if (!args->crc && !args->is_crc) pr_warn_ratelimited("Missing CRC for chunk\n"); if (args->crc) *args->crc = dvb_crc32(*args->crc, args->from, args->len); if (args->new_psi_section && !aligned) { pr_warn_ratelimited("Cannot write a new PSI section in a misaligned buffer\n"); /* forcibly align and hope for the best */ nbytes += vidtv_memset(args->dest_buf, args->dest_offset + nbytes, args->dest_buf_sz, TS_FILL_BYTE, TS_PACKET_LEN - nbytes_past_boundary); } while (remaining_len) { nbytes_past_boundary = (args->dest_offset + nbytes) % TS_PACKET_LEN; aligned = (nbytes_past_boundary == 0); if (aligned) { /* if at a packet boundary, write a new TS header */ ts_header.continuity_counter = *args->continuity_counter; nbytes += vidtv_memcpy(args->dest_buf, args->dest_offset + nbytes, args->dest_buf_sz, &ts_header, sizeof(ts_header)); /* * This will trigger a discontinuity if the buffer is full, * effectively dropping the packet. */ vidtv_ts_inc_cc(args->continuity_counter); } /* write the pointer_field in the first byte of the payload */ if (args->new_psi_section) nbytes += vidtv_memset(args->dest_buf, args->dest_offset + nbytes, args->dest_buf_sz, 0x0, 1); /* write as much of the payload as possible */ nbytes_past_boundary = (args->dest_offset + nbytes) % TS_PACKET_LEN; payload_write_len = min(TS_PACKET_LEN - nbytes_past_boundary, remaining_len); nbytes += vidtv_memcpy(args->dest_buf, args->dest_offset + nbytes, args->dest_buf_sz, args->from + payload_offset, payload_write_len); /* 'payload_write_len' written from a total of 'len' requested*/ remaining_len -= payload_write_len; payload_offset += payload_write_len; } /* * fill the rest of the packet if there is any remaining space unused */ nbytes_past_boundary = (args->dest_offset + nbytes) % TS_PACKET_LEN; if (args->is_crc) nbytes += vidtv_memset(args->dest_buf, args->dest_offset + nbytes, args->dest_buf_sz, TS_FILL_BYTE, TS_PACKET_LEN - nbytes_past_boundary); return nbytes; } static u32 table_section_crc32_write_into(struct crc32_write_args *args) { struct psi_write_args psi_args = { .dest_buf = args->dest_buf, .from = &args->crc, .len = CRC_SIZE_IN_BYTES, .dest_offset = args->dest_offset, .pid = args->pid, .new_psi_section = false, .continuity_counter = args->continuity_counter, .is_crc = true, .dest_buf_sz = args->dest_buf_sz, }; /* the CRC is the last entry in the section */ return vidtv_psi_ts_psi_write_into(&psi_args); } static void vidtv_psi_desc_chain(struct vidtv_psi_desc *head, struct vidtv_psi_desc *desc) { if (head) { while (head->next) head = head->next; head->next = desc; } } struct vidtv_psi_desc_service *vidtv_psi_service_desc_init(struct vidtv_psi_desc *head, enum service_type service_type, char *service_name, char *provider_name) { struct vidtv_psi_desc_service *desc; u32 service_name_len = service_name ? strlen(service_name) : 0; u32 provider_name_len = provider_name ? strlen(provider_name) : 0; desc = kzalloc(sizeof(*desc), GFP_KERNEL); if (!desc) return NULL; desc->type = SERVICE_DESCRIPTOR; desc->length = sizeof_field(struct vidtv_psi_desc_service, service_type) + sizeof_field(struct vidtv_psi_desc_service, provider_name_len) + provider_name_len + sizeof_field(struct vidtv_psi_desc_service, service_name_len) + service_name_len; desc->service_type = service_type; desc->service_name_len = service_name_len; if (service_name && service_name_len) desc->service_name = kstrdup(service_name, GFP_KERNEL); desc->provider_name_len = provider_name_len; if (provider_name && provider_name_len) desc->provider_name = kstrdup(provider_name, GFP_KERNEL); vidtv_psi_desc_chain(head, (struct vidtv_psi_desc *)desc); return desc; } struct vidtv_psi_desc_registration *vidtv_psi_registration_desc_init(struct vidtv_psi_desc *head, __be32 format_id, u8 *additional_ident_info, u32 additional_info_len) { struct vidtv_psi_desc_registration *desc; desc = kzalloc(sizeof(*desc) + sizeof(format_id) + additional_info_len, GFP_KERNEL); if (!desc) return NULL; desc->type = REGISTRATION_DESCRIPTOR; desc->length = sizeof_field(struct vidtv_psi_desc_registration, format_id) + additional_info_len; desc->format_id = format_id; if (additional_ident_info && additional_info_len) memcpy(desc->additional_identification_info, additional_ident_info, additional_info_len); vidtv_psi_desc_chain(head, (struct vidtv_psi_desc *)desc); return desc; } struct vidtv_psi_desc_network_name *vidtv_psi_network_name_desc_init(struct vidtv_psi_desc *head, char *network_name) { u32 network_name_len = network_name ? strlen(network_name) : 0; struct vidtv_psi_desc_network_name *desc; desc = kzalloc(sizeof(*desc), GFP_KERNEL); if (!desc) return NULL; desc->type = NETWORK_NAME_DESCRIPTOR; desc->length = network_name_len; if (network_name && network_name_len) desc->network_name = kstrdup(network_name, GFP_KERNEL); vidtv_psi_desc_chain(head, (struct vidtv_psi_desc *)desc); return desc; } struct vidtv_psi_desc_service_list *vidtv_psi_service_list_desc_init(struct vidtv_psi_desc *head, struct vidtv_psi_desc_service_list_entry *entry) { struct vidtv_psi_desc_service_list_entry *curr_e = NULL; struct vidtv_psi_desc_service_list_entry *head_e = NULL; struct vidtv_psi_desc_service_list_entry *prev_e = NULL; struct vidtv_psi_desc_service_list *desc; u16 length = 0; desc = kzalloc(sizeof(*desc), GFP_KERNEL); if (!desc) return NULL; desc->type = SERVICE_LIST_DESCRIPTOR; while (entry) { curr_e = kzalloc(sizeof(*curr_e), GFP_KERNEL); if (!curr_e) { while (head_e) { curr_e = head_e; head_e = head_e->next; kfree(curr_e); } kfree(desc); return NULL; } curr_e->service_id = entry->service_id; curr_e->service_type = entry->service_type; length += sizeof(struct vidtv_psi_desc_service_list_entry) - sizeof(struct vidtv_psi_desc_service_list_entry *); if (!head_e) head_e = curr_e; if (prev_e) prev_e->next = curr_e; prev_e = curr_e; entry = entry->next; } desc->length = length; desc->service_list = head_e; vidtv_psi_desc_chain(head, (struct vidtv_psi_desc *)desc); return desc; } struct vidtv_psi_desc_short_event *vidtv_psi_short_event_desc_init(struct vidtv_psi_desc *head, char *iso_language_code, char *event_name, char *text) { u32 iso_len = iso_language_code ? strlen(iso_language_code) : 0; u32 event_name_len = event_name ? strlen(event_name) : 0; struct vidtv_psi_desc_short_event *desc; u32 text_len = text ? strlen(text) : 0; desc = kzalloc(sizeof(*desc), GFP_KERNEL); if (!desc) return NULL; desc->type = SHORT_EVENT_DESCRIPTOR; desc->length = ISO_LANGUAGE_CODE_LEN + sizeof_field(struct vidtv_psi_desc_short_event, event_name_len) + event_name_len + sizeof_field(struct vidtv_psi_desc_short_event, text_len) + text_len; desc->event_name_len = event_name_len; desc->text_len = text_len; if (iso_len != ISO_LANGUAGE_CODE_LEN) iso_language_code = "eng"; desc->iso_language_code = kstrdup(iso_language_code, GFP_KERNEL); if (event_name && event_name_len) desc->event_name = kstrdup(event_name, GFP_KERNEL); if (text && text_len) desc->text = kstrdup(text, GFP_KERNEL); vidtv_psi_desc_chain(head, (struct vidtv_psi_desc *)desc); return desc; } struct vidtv_psi_desc *vidtv_psi_desc_clone(struct vidtv_psi_desc *desc) { struct vidtv_psi_desc_network_name *desc_network_name; struct vidtv_psi_desc_service_list *desc_service_list; struct vidtv_psi_desc_short_event *desc_short_event; struct vidtv_psi_desc_service *service; struct vidtv_psi_desc *head = NULL; struct vidtv_psi_desc *prev = NULL; struct vidtv_psi_desc *curr = NULL; while (desc) { switch (desc->type) { case SERVICE_DESCRIPTOR: service = (struct vidtv_psi_desc_service *)desc; curr = (struct vidtv_psi_desc *) vidtv_psi_service_desc_init(head, service->service_type, service->service_name, service->provider_name); break; case NETWORK_NAME_DESCRIPTOR: desc_network_name = (struct vidtv_psi_desc_network_name *)desc; curr = (struct vidtv_psi_desc *) vidtv_psi_network_name_desc_init(head, desc_network_name->network_name); break; case SERVICE_LIST_DESCRIPTOR: desc_service_list = (struct vidtv_psi_desc_service_list *)desc; curr = (struct vidtv_psi_desc *) vidtv_psi_service_list_desc_init(head, desc_service_list->service_list); break; case SHORT_EVENT_DESCRIPTOR: desc_short_event = (struct vidtv_psi_desc_short_event *)desc; curr = (struct vidtv_psi_desc *) vidtv_psi_short_event_desc_init(head, desc_short_event->iso_language_code, desc_short_event->event_name, desc_short_event->text); break; case REGISTRATION_DESCRIPTOR: default: curr = kmemdup(desc, sizeof(*desc) + desc->length, GFP_KERNEL); if (!curr) return NULL; } if (!curr) return NULL; curr->next = NULL; if (!head) head = curr; if (prev) prev->next = curr; prev = curr; desc = desc->next; } return head; } void vidtv_psi_desc_destroy(struct vidtv_psi_desc *desc) { struct vidtv_psi_desc_service_list_entry *sl_entry_tmp = NULL; struct vidtv_psi_desc_service_list_entry *sl_entry = NULL; struct vidtv_psi_desc *curr = desc; struct vidtv_psi_desc *tmp = NULL; while (curr) { tmp = curr; curr = curr->next; switch (tmp->type) { case SERVICE_DESCRIPTOR: kfree(((struct vidtv_psi_desc_service *)tmp)->provider_name); kfree(((struct vidtv_psi_desc_service *)tmp)->service_name); break; case REGISTRATION_DESCRIPTOR: /* nothing to do */ break; case NETWORK_NAME_DESCRIPTOR: kfree(((struct vidtv_psi_desc_network_name *)tmp)->network_name); break; case SERVICE_LIST_DESCRIPTOR: sl_entry = ((struct vidtv_psi_desc_service_list *)tmp)->service_list; while (sl_entry) { sl_entry_tmp = sl_entry; sl_entry = sl_entry->next; kfree(sl_entry_tmp); } break; case SHORT_EVENT_DESCRIPTOR: kfree(((struct vidtv_psi_desc_short_event *)tmp)->iso_language_code); kfree(((struct vidtv_psi_desc_short_event *)tmp)->event_name); kfree(((struct vidtv_psi_desc_short_event *)tmp)->text); break; default: pr_warn_ratelimited("Possible leak: not handling descriptor type %d\n", tmp->type); break; } kfree(tmp); } } static u16 vidtv_psi_desc_comp_loop_len(struct vidtv_psi_desc *desc) { u32 length = 0; if (!desc) return 0; while (desc) { length += sizeof_field(struct vidtv_psi_desc, type); length += sizeof_field(struct vidtv_psi_desc, length); length += desc->length; /* from 'length' field until the end of the descriptor */ desc = desc->next; } return length; } void vidtv_psi_desc_assign(struct vidtv_psi_desc **to, struct vidtv_psi_desc *desc) { if (desc == *to) return; if (*to) vidtv_psi_desc_destroy(*to); *to = desc; } void vidtv_pmt_desc_assign(struct vidtv_psi_table_pmt *pmt, struct vidtv_psi_desc **to, struct vidtv_psi_desc *desc) { vidtv_psi_desc_assign(to, desc); vidtv_psi_pmt_table_update_sec_len(pmt); if (vidtv_psi_get_sec_len(&pmt->header) > MAX_SECTION_LEN) vidtv_psi_desc_assign(to, NULL); vidtv_psi_update_version_num(&pmt->header); } void vidtv_sdt_desc_assign(struct vidtv_psi_table_sdt *sdt, struct vidtv_psi_desc **to, struct vidtv_psi_desc *desc) { vidtv_psi_desc_assign(to, desc); vidtv_psi_sdt_table_update_sec_len(sdt); if (vidtv_psi_get_sec_len(&sdt->header) > MAX_SECTION_LEN) vidtv_psi_desc_assign(to, NULL); vidtv_psi_update_version_num(&sdt->header); } static u32 vidtv_psi_desc_write_into(struct desc_write_args *args) { struct psi_write_args psi_args = { .dest_buf = args->dest_buf, .from = &args->desc->type, .pid = args->pid, .new_psi_section = false, .continuity_counter = args->continuity_counter, .is_crc = false, .dest_buf_sz = args->dest_buf_sz, .crc = args->crc, .len = sizeof_field(struct vidtv_psi_desc, type) + sizeof_field(struct vidtv_psi_desc, length), }; struct vidtv_psi_desc_service_list_entry *serv_list_entry = NULL; u32 nbytes = 0; psi_args.dest_offset = args->dest_offset + nbytes; nbytes += vidtv_psi_ts_psi_write_into(&psi_args); switch (args->desc->type) { case SERVICE_DESCRIPTOR: psi_args.dest_offset = args->dest_offset + nbytes; psi_args.len = sizeof_field(struct vidtv_psi_desc_service, service_type) + sizeof_field(struct vidtv_psi_desc_service, provider_name_len); psi_args.from = &((struct vidtv_psi_desc_service *)args->desc)->service_type; nbytes += vidtv_psi_ts_psi_write_into(&psi_args); psi_args.dest_offset = args->dest_offset + nbytes; psi_args.len = ((struct vidtv_psi_desc_service *)args->desc)->provider_name_len; psi_args.from = ((struct vidtv_psi_desc_service *)args->desc)->provider_name; nbytes += vidtv_psi_ts_psi_write_into(&psi_args); psi_args.dest_offset = args->dest_offset + nbytes; psi_args.len = sizeof_field(struct vidtv_psi_desc_service, service_name_len); psi_args.from = &((struct vidtv_psi_desc_service *)args->desc)->service_name_len; nbytes += vidtv_psi_ts_psi_write_into(&psi_args); psi_args.dest_offset = args->dest_offset + nbytes; psi_args.len = ((struct vidtv_psi_desc_service *)args->desc)->service_name_len; psi_args.from = ((struct vidtv_psi_desc_service *)args->desc)->service_name; nbytes += vidtv_psi_ts_psi_write_into(&psi_args); break; case NETWORK_NAME_DESCRIPTOR: psi_args.dest_offset = args->dest_offset + nbytes; psi_args.len = args->desc->length; psi_args.from = ((struct vidtv_psi_desc_network_name *)args->desc)->network_name; nbytes += vidtv_psi_ts_psi_write_into(&psi_args); break; case SERVICE_LIST_DESCRIPTOR: serv_list_entry = ((struct vidtv_psi_desc_service_list *)args->desc)->service_list; while (serv_list_entry) { psi_args.dest_offset = args->dest_offset + nbytes; psi_args.len = sizeof(struct vidtv_psi_desc_service_list_entry) - sizeof(struct vidtv_psi_desc_service_list_entry *); psi_args.from = serv_list_entry; nbytes += vidtv_psi_ts_psi_write_into(&psi_args); serv_list_entry = serv_list_entry->next; } break; case SHORT_EVENT_DESCRIPTOR: psi_args.dest_offset = args->dest_offset + nbytes; psi_args.len = ISO_LANGUAGE_CODE_LEN; psi_args.from = ((struct vidtv_psi_desc_short_event *) args->desc)->iso_language_code; nbytes += vidtv_psi_ts_psi_write_into(&psi_args); psi_args.dest_offset = args->dest_offset + nbytes; psi_args.len = sizeof_field(struct vidtv_psi_desc_short_event, event_name_len); psi_args.from = &((struct vidtv_psi_desc_short_event *) args->desc)->event_name_len; nbytes += vidtv_psi_ts_psi_write_into(&psi_args); psi_args.dest_offset = args->dest_offset + nbytes; psi_args.len = ((struct vidtv_psi_desc_short_event *)args->desc)->event_name_len; psi_args.from = ((struct vidtv_psi_desc_short_event *)args->desc)->event_name; nbytes += vidtv_psi_ts_psi_write_into(&psi_args); psi_args.dest_offset = args->dest_offset + nbytes; psi_args.len = sizeof_field(struct vidtv_psi_desc_short_event, text_len); psi_args.from = &((struct vidtv_psi_desc_short_event *)args->desc)->text_len; nbytes += vidtv_psi_ts_psi_write_into(&psi_args); psi_args.dest_offset = args->dest_offset + nbytes; psi_args.len = ((struct vidtv_psi_desc_short_event *)args->desc)->text_len; psi_args.from = ((struct vidtv_psi_desc_short_event *)args->desc)->text; nbytes += vidtv_psi_ts_psi_write_into(&psi_args); break; case REGISTRATION_DESCRIPTOR: default: psi_args.dest_offset = args->dest_offset + nbytes; psi_args.len = args->desc->length; psi_args.from = &args->desc->data; nbytes += vidtv_psi_ts_psi_write_into(&psi_args); break; } return nbytes; } static u32 vidtv_psi_table_header_write_into(struct header_write_args *args) { struct psi_write_args psi_args = { .dest_buf = args->dest_buf, .from = args->h, .len = sizeof(struct vidtv_psi_table_header), .dest_offset = args->dest_offset, .pid = args->pid, .new_psi_section = true, .continuity_counter = args->continuity_counter, .is_crc = false, .dest_buf_sz = args->dest_buf_sz, .crc = args->crc, }; return vidtv_psi_ts_psi_write_into(&psi_args); } void vidtv_psi_pat_table_update_sec_len(struct vidtv_psi_table_pat *pat) { u16 length = 0; u32 i; /* see ISO/IEC 13818-1 : 2000 p.43 */ /* from immediately after 'section_length' until 'last_section_number'*/ length += PAT_LEN_UNTIL_LAST_SECTION_NUMBER; /* do not count the pointer */ for (i = 0; i < pat->num_pat; ++i) length += sizeof(struct vidtv_psi_table_pat_program) - sizeof(struct vidtv_psi_table_pat_program *); length += CRC_SIZE_IN_BYTES; vidtv_psi_set_sec_len(&pat->header, length); } void vidtv_psi_pmt_table_update_sec_len(struct vidtv_psi_table_pmt *pmt) { struct vidtv_psi_table_pmt_stream *s = pmt->stream; u16 desc_loop_len; u16 length = 0; /* see ISO/IEC 13818-1 : 2000 p.46 */ /* from immediately after 'section_length' until 'program_info_length'*/ length += PMT_LEN_UNTIL_PROGRAM_INFO_LENGTH; desc_loop_len = vidtv_psi_desc_comp_loop_len(pmt->descriptor); vidtv_psi_set_desc_loop_len(&pmt->bitfield2, desc_loop_len, 10); length += desc_loop_len; while (s) { /* skip both pointers at the end */ length += sizeof(struct vidtv_psi_table_pmt_stream) - sizeof(struct vidtv_psi_desc *) - sizeof(struct vidtv_psi_table_pmt_stream *); desc_loop_len = vidtv_psi_desc_comp_loop_len(s->descriptor); vidtv_psi_set_desc_loop_len(&s->bitfield2, desc_loop_len, 10); length += desc_loop_len; s = s->next; } length += CRC_SIZE_IN_BYTES; vidtv_psi_set_sec_len(&pmt->header, length); } void vidtv_psi_sdt_table_update_sec_len(struct vidtv_psi_table_sdt *sdt) { struct vidtv_psi_table_sdt_service *s = sdt->service; u16 desc_loop_len; u16 length = 0; /* see ETSI EN 300 468 V 1.10.1 p.24 */ /* * from immediately after 'section_length' until * 'reserved_for_future_use' */ length += SDT_LEN_UNTIL_RESERVED_FOR_FUTURE_USE; while (s) { /* skip both pointers at the end */ length += sizeof(struct vidtv_psi_table_sdt_service) - sizeof(struct vidtv_psi_desc *) - sizeof(struct vidtv_psi_table_sdt_service *); desc_loop_len = vidtv_psi_desc_comp_loop_len(s->descriptor); vidtv_psi_set_desc_loop_len(&s->bitfield, desc_loop_len, 12); length += desc_loop_len; s = s->next; } length += CRC_SIZE_IN_BYTES; vidtv_psi_set_sec_len(&sdt->header, length); } struct vidtv_psi_table_pat_program* vidtv_psi_pat_program_init(struct vidtv_psi_table_pat_program *head, u16 service_id, u16 program_map_pid) { struct vidtv_psi_table_pat_program *program; const u16 RESERVED = 0x07; program = kzalloc(sizeof(*program), GFP_KERNEL); if (!program) return NULL; program->service_id = cpu_to_be16(service_id); /* pid for the PMT section in the TS */ program->bitfield = cpu_to_be16((RESERVED << 13) | program_map_pid); program->next = NULL; if (head) { while (head->next) head = head->next; head->next = program; } return program; } void vidtv_psi_pat_program_destroy(struct vidtv_psi_table_pat_program *p) { struct vidtv_psi_table_pat_program *tmp = NULL; struct vidtv_psi_table_pat_program *curr = p; while (curr) { tmp = curr; curr = curr->next; kfree(tmp); } } /* This function transfers ownership of p to the table */ void vidtv_psi_pat_program_assign(struct vidtv_psi_table_pat *pat, struct vidtv_psi_table_pat_program *p) { struct vidtv_psi_table_pat_program *program; u16 program_count; do { program_count = 0; program = p; if (p == pat->program) return; while (program) { ++program_count; program = program->next; } pat->num_pat = program_count; pat->program = p; /* Recompute section length */ vidtv_psi_pat_table_update_sec_len(pat); p = NULL; } while (vidtv_psi_get_sec_len(&pat->header) > MAX_SECTION_LEN); vidtv_psi_update_version_num(&pat->header); } struct vidtv_psi_table_pat *vidtv_psi_pat_table_init(u16 transport_stream_id) { struct vidtv_psi_table_pat *pat; const u16 SYNTAX = 0x1; const u16 ZERO = 0x0; const u16 ONES = 0x03; pat = kzalloc(sizeof(*pat), GFP_KERNEL); if (!pat) return NULL; pat->header.table_id = 0x0; pat->header.bitfield = cpu_to_be16((SYNTAX << 15) | (ZERO << 14) | (ONES << 12)); pat->header.id = cpu_to_be16(transport_stream_id); pat->header.current_next = 0x1; pat->header.version = 0x1f; pat->header.one2 = 0x03; pat->header.section_id = 0x0; pat->header.last_section = 0x0; vidtv_psi_pat_table_update_sec_len(pat); return pat; } u32 vidtv_psi_pat_write_into(struct vidtv_psi_pat_write_args *args) { struct vidtv_psi_table_pat_program *p = args->pat->program; struct header_write_args h_args = { .dest_buf = args->buf, .dest_offset = args->offset, .pid = VIDTV_PAT_PID, .h = &args->pat->header, .continuity_counter = args->continuity_counter, .dest_buf_sz = args->buf_sz, }; struct psi_write_args psi_args = { .dest_buf = args->buf, .pid = VIDTV_PAT_PID, .new_psi_section = false, .continuity_counter = args->continuity_counter, .is_crc = false, .dest_buf_sz = args->buf_sz, }; struct crc32_write_args c_args = { .dest_buf = args->buf, .pid = VIDTV_PAT_PID, .dest_buf_sz = args->buf_sz, }; u32 crc = INITIAL_CRC; u32 nbytes = 0; vidtv_psi_pat_table_update_sec_len(args->pat); h_args.crc = &crc; nbytes += vidtv_psi_table_header_write_into(&h_args); /* note that the field 'u16 programs' is not really part of the PAT */ psi_args.crc = &crc; while (p) { /* copy the PAT programs */ psi_args.from = p; /* skip the pointer */ psi_args.len = sizeof(*p) - sizeof(struct vidtv_psi_table_pat_program *); psi_args.dest_offset = args->offset + nbytes; psi_args.continuity_counter = args->continuity_counter; nbytes += vidtv_psi_ts_psi_write_into(&psi_args); p = p->next; } c_args.dest_offset = args->offset + nbytes; c_args.continuity_counter = args->continuity_counter; c_args.crc = cpu_to_be32(crc); /* Write the CRC32 at the end */ nbytes += table_section_crc32_write_into(&c_args); return nbytes; } void vidtv_psi_pat_table_destroy(struct vidtv_psi_table_pat *p) { vidtv_psi_pat_program_destroy(p->program); kfree(p); } struct vidtv_psi_table_pmt_stream* vidtv_psi_pmt_stream_init(struct vidtv_psi_table_pmt_stream *head, enum vidtv_psi_stream_types stream_type, u16 es_pid) { struct vidtv_psi_table_pmt_stream *stream; const u16 RESERVED1 = 0x07; const u16 RESERVED2 = 0x0f; const u16 ZERO = 0x0; u16 desc_loop_len; stream = kzalloc(sizeof(*stream), GFP_KERNEL); if (!stream) return NULL; stream->type = stream_type; stream->bitfield = cpu_to_be16((RESERVED1 << 13) | es_pid); desc_loop_len = vidtv_psi_desc_comp_loop_len(stream->descriptor); stream->bitfield2 = cpu_to_be16((RESERVED2 << 12) | (ZERO << 10) | desc_loop_len); stream->next = NULL; if (head) { while (head->next) head = head->next; head->next = stream; } return stream; } void vidtv_psi_pmt_stream_destroy(struct vidtv_psi_table_pmt_stream *s) { struct vidtv_psi_table_pmt_stream *tmp_stream = NULL; struct vidtv_psi_table_pmt_stream *curr_stream = s; while (curr_stream) { tmp_stream = curr_stream; curr_stream = curr_stream->next; vidtv_psi_desc_destroy(tmp_stream->descriptor); kfree(tmp_stream); } } void vidtv_psi_pmt_stream_assign(struct vidtv_psi_table_pmt *pmt, struct vidtv_psi_table_pmt_stream *s) { do { /* This function transfers ownership of s to the table */ if (s == pmt->stream) return; pmt->stream = s; vidtv_psi_pmt_table_update_sec_len(pmt); s = NULL; } while (vidtv_psi_get_sec_len(&pmt->header) > MAX_SECTION_LEN); vidtv_psi_update_version_num(&pmt->header); } u16 vidtv_psi_pmt_get_pid(struct vidtv_psi_table_pmt *section, struct vidtv_psi_table_pat *pat) { struct vidtv_psi_table_pat_program *program = pat->program; /* * service_id is the same as program_number in the * corresponding program_map_section * see ETSI EN 300 468 v1.15.1 p. 24 */ while (program) { if (program->service_id == section->header.id) return vidtv_psi_get_pat_program_pid(program); program = program->next; } return TS_LAST_VALID_PID + 1; /* not found */ } struct vidtv_psi_table_pmt *vidtv_psi_pmt_table_init(u16 program_number, u16 pcr_pid) { struct vidtv_psi_table_pmt *pmt; const u16 RESERVED1 = 0x07; const u16 RESERVED2 = 0x0f; const u16 SYNTAX = 0x1; const u16 ONES = 0x03; const u16 ZERO = 0x0; u16 desc_loop_len; pmt = kzalloc(sizeof(*pmt), GFP_KERNEL); if (!pmt) return NULL; if (!pcr_pid) pcr_pid = 0x1fff; pmt->header.table_id = 0x2; pmt->header.bitfield = cpu_to_be16((SYNTAX << 15) | (ZERO << 14) | (ONES << 12)); pmt->header.id = cpu_to_be16(program_number); pmt->header.current_next = 0x1; pmt->header.version = 0x1f; pmt->header.one2 = ONES; pmt->header.section_id = 0; pmt->header.last_section = 0; pmt->bitfield = cpu_to_be16((RESERVED1 << 13) | pcr_pid); desc_loop_len = vidtv_psi_desc_comp_loop_len(pmt->descriptor); pmt->bitfield2 = cpu_to_be16((RESERVED2 << 12) | (ZERO << 10) | desc_loop_len); vidtv_psi_pmt_table_update_sec_len(pmt); return pmt; } u32 vidtv_psi_pmt_write_into(struct vidtv_psi_pmt_write_args *args) { struct vidtv_psi_desc *table_descriptor = args->pmt->descriptor; struct vidtv_psi_table_pmt_stream *stream = args->pmt->stream; struct vidtv_psi_desc *stream_descriptor; u32 crc = INITIAL_CRC; u32 nbytes = 0; struct header_write_args h_args = { .dest_buf = args->buf, .dest_offset = args->offset, .h = &args->pmt->header, .pid = args->pid, .continuity_counter = args->continuity_counter, .dest_buf_sz = args->buf_sz, }; struct psi_write_args psi_args = { .dest_buf = args->buf, .from = &args->pmt->bitfield, .len = sizeof_field(struct vidtv_psi_table_pmt, bitfield) + sizeof_field(struct vidtv_psi_table_pmt, bitfield2), .pid = args->pid, .new_psi_section = false, .is_crc = false, .dest_buf_sz = args->buf_sz, .crc = &crc, }; struct desc_write_args d_args = { .dest_buf = args->buf, .desc = table_descriptor, .pid = args->pid, .dest_buf_sz = args->buf_sz, }; struct crc32_write_args c_args = { .dest_buf = args->buf, .pid = args->pid, .dest_buf_sz = args->buf_sz, }; vidtv_psi_pmt_table_update_sec_len(args->pmt); h_args.crc = &crc; nbytes += vidtv_psi_table_header_write_into(&h_args); /* write the two bitfields */ psi_args.dest_offset = args->offset + nbytes; psi_args.continuity_counter = args->continuity_counter; nbytes += vidtv_psi_ts_psi_write_into(&psi_args); while (table_descriptor) { /* write the descriptors, if any */ d_args.dest_offset = args->offset + nbytes; d_args.continuity_counter = args->continuity_counter; d_args.crc = &crc; nbytes += vidtv_psi_desc_write_into(&d_args); table_descriptor = table_descriptor->next; } psi_args.len += sizeof_field(struct vidtv_psi_table_pmt_stream, type); while (stream) { /* write the streams, if any */ psi_args.from = stream; psi_args.dest_offset = args->offset + nbytes; psi_args.continuity_counter = args->continuity_counter; nbytes += vidtv_psi_ts_psi_write_into(&psi_args); stream_descriptor = stream->descriptor; while (stream_descriptor) { /* write the stream descriptors, if any */ d_args.dest_offset = args->offset + nbytes; d_args.desc = stream_descriptor; d_args.continuity_counter = args->continuity_counter; d_args.crc = &crc; nbytes += vidtv_psi_desc_write_into(&d_args); stream_descriptor = stream_descriptor->next; } stream = stream->next; } c_args.dest_offset = args->offset + nbytes; c_args.crc = cpu_to_be32(crc); c_args.continuity_counter = args->continuity_counter; /* Write the CRC32 at the end */ nbytes += table_section_crc32_write_into(&c_args); return nbytes; } void vidtv_psi_pmt_table_destroy(struct vidtv_psi_table_pmt *pmt) { vidtv_psi_desc_destroy(pmt->descriptor); vidtv_psi_pmt_stream_destroy(pmt->stream); kfree(pmt); } struct vidtv_psi_table_sdt *vidtv_psi_sdt_table_init(u16 network_id, u16 transport_stream_id) { struct vidtv_psi_table_sdt *sdt; const u16 RESERVED = 0xff; const u16 SYNTAX = 0x1; const u16 ONES = 0x03; const u16 ONE = 0x1; sdt = kzalloc(sizeof(*sdt), GFP_KERNEL); if (!sdt) return NULL; sdt->header.table_id = 0x42; sdt->header.bitfield = cpu_to_be16((SYNTAX << 15) | (ONE << 14) | (ONES << 12)); /* * This is a 16-bit field which serves as a label for identification * of the TS, about which the SDT informs, from any other multiplex * within the delivery system. */ sdt->header.id = cpu_to_be16(transport_stream_id); sdt->header.current_next = ONE; sdt->header.version = 0x1f; sdt->header.one2 = ONES; sdt->header.section_id = 0; sdt->header.last_section = 0; /* * FIXME: The network_id range from 0xFF01 to 0xFFFF is used to * indicate temporary private use. For now, let's use the first * value. * This can be changed to something more useful, when support for * NIT gets added */ sdt->network_id = cpu_to_be16(network_id); sdt->reserved = RESERVED; vidtv_psi_sdt_table_update_sec_len(sdt); return sdt; } u32 vidtv_psi_sdt_write_into(struct vidtv_psi_sdt_write_args *args) { struct header_write_args h_args = { .dest_buf = args->buf, .dest_offset = args->offset, .h = &args->sdt->header, .pid = VIDTV_SDT_PID, .dest_buf_sz = args->buf_sz, }; struct psi_write_args psi_args = { .dest_buf = args->buf, .len = sizeof_field(struct vidtv_psi_table_sdt, network_id) + sizeof_field(struct vidtv_psi_table_sdt, reserved), .pid = VIDTV_SDT_PID, .new_psi_section = false, .is_crc = false, .dest_buf_sz = args->buf_sz, }; struct desc_write_args d_args = { .dest_buf = args->buf, .pid = VIDTV_SDT_PID, .dest_buf_sz = args->buf_sz, }; struct crc32_write_args c_args = { .dest_buf = args->buf, .pid = VIDTV_SDT_PID, .dest_buf_sz = args->buf_sz, }; struct vidtv_psi_table_sdt_service *service = args->sdt->service; struct vidtv_psi_desc *service_desc; u32 nbytes = 0; u32 crc = INITIAL_CRC; /* see ETSI EN 300 468 v1.15.1 p. 11 */ vidtv_psi_sdt_table_update_sec_len(args->sdt); h_args.continuity_counter = args->continuity_counter; h_args.crc = &crc; nbytes += vidtv_psi_table_header_write_into(&h_args); psi_args.from = &args->sdt->network_id; psi_args.dest_offset = args->offset + nbytes; psi_args.continuity_counter = args->continuity_counter; psi_args.crc = &crc; /* copy u16 network_id + u8 reserved)*/ nbytes += vidtv_psi_ts_psi_write_into(&psi_args); /* skip both pointers at the end */ psi_args.len = sizeof(struct vidtv_psi_table_sdt_service) - sizeof(struct vidtv_psi_desc *) - sizeof(struct vidtv_psi_table_sdt_service *); while (service) { /* copy the services, if any */ psi_args.from = service; psi_args.dest_offset = args->offset + nbytes; psi_args.continuity_counter = args->continuity_counter; nbytes += vidtv_psi_ts_psi_write_into(&psi_args); service_desc = service->descriptor; while (service_desc) { /* copy the service descriptors, if any */ d_args.dest_offset = args->offset + nbytes; d_args.desc = service_desc; d_args.continuity_counter = args->continuity_counter; d_args.crc = &crc; nbytes += vidtv_psi_desc_write_into(&d_args); service_desc = service_desc->next; } service = service->next; } c_args.dest_offset = args->offset + nbytes; c_args.crc = cpu_to_be32(crc); c_args.continuity_counter = args->continuity_counter; /* Write the CRC at the end */ nbytes += table_section_crc32_write_into(&c_args); return nbytes; } void vidtv_psi_sdt_table_destroy(struct vidtv_psi_table_sdt *sdt) { vidtv_psi_sdt_service_destroy(sdt->service); kfree(sdt); } struct vidtv_psi_table_sdt_service *vidtv_psi_sdt_service_init(struct vidtv_psi_table_sdt_service *head, u16 service_id, bool eit_schedule, bool eit_present_following) { struct vidtv_psi_table_sdt_service *service; service = kzalloc(sizeof(*service), GFP_KERNEL); if (!service) return NULL; /* * ETSI 300 468: this is a 16bit field which serves as a label to * identify this service from any other service within the TS. * The service id is the same as the program number in the * corresponding program_map_section */ service->service_id = cpu_to_be16(service_id); service->EIT_schedule = eit_schedule; service->EIT_present_following = eit_present_following; service->reserved = 0x3f; service->bitfield = cpu_to_be16(RUNNING << 13); if (head) { while (head->next) head = head->next; head->next = service; } return service; } void vidtv_psi_sdt_service_destroy(struct vidtv_psi_table_sdt_service *service) { struct vidtv_psi_table_sdt_service *curr = service; struct vidtv_psi_table_sdt_service *tmp = NULL; while (curr) { tmp = curr; curr = curr->next; vidtv_psi_desc_destroy(tmp->descriptor); kfree(tmp); } } void vidtv_psi_sdt_service_assign(struct vidtv_psi_table_sdt *sdt, struct vidtv_psi_table_sdt_service *service) { do { if (service == sdt->service) return; sdt->service = service; /* recompute section length */ vidtv_psi_sdt_table_update_sec_len(sdt); service = NULL; } while (vidtv_psi_get_sec_len(&sdt->header) > MAX_SECTION_LEN); vidtv_psi_update_version_num(&sdt->header); } /* * PMTs contain information about programs. For each program, * there is one PMT section. This function will create a section * for each program found in the PAT */ struct vidtv_psi_table_pmt** vidtv_psi_pmt_create_sec_for_each_pat_entry(struct vidtv_psi_table_pat *pat, u16 pcr_pid) { struct vidtv_psi_table_pat_program *program; struct vidtv_psi_table_pmt **pmt_secs; u32 i = 0, num_pmt = 0; /* * The number of PMT entries is the number of PAT entries * that contain service_id. That exclude special tables, like NIT */ program = pat->program; while (program) { if (program->service_id) num_pmt++; program = program->next; } pmt_secs = kcalloc(num_pmt, sizeof(struct vidtv_psi_table_pmt *), GFP_KERNEL); if (!pmt_secs) return NULL; for (program = pat->program; program; program = program->next) { if (!program->service_id) continue; pmt_secs[i] = vidtv_psi_pmt_table_init(be16_to_cpu(program->service_id), pcr_pid); if (!pmt_secs[i]) { while (i > 0) { i--; vidtv_psi_pmt_table_destroy(pmt_secs[i]); } return NULL; } i++; } pat->num_pmt = num_pmt; return pmt_secs; } /* find the PMT section associated with 'program_num' */ struct vidtv_psi_table_pmt *vidtv_psi_find_pmt_sec(struct vidtv_psi_table_pmt **pmt_sections, u16 nsections, u16 program_num) { struct vidtv_psi_table_pmt *sec = NULL; u32 i; for (i = 0; i < nsections; ++i) { sec = pmt_sections[i]; if (be16_to_cpu(sec->header.id) == program_num) return sec; } return NULL; /* not found */ } static void vidtv_psi_nit_table_update_sec_len(struct vidtv_psi_table_nit *nit) { u16 length = 0; struct vidtv_psi_table_transport *t = nit->transport; u16 desc_loop_len; u16 transport_loop_len = 0; /* * from immediately after 'section_length' until * 'network_descriptor_length' */ length += NIT_LEN_UNTIL_NETWORK_DESCRIPTOR_LEN; desc_loop_len = vidtv_psi_desc_comp_loop_len(nit->descriptor); vidtv_psi_set_desc_loop_len(&nit->bitfield, desc_loop_len, 12); length += desc_loop_len; length += sizeof_field(struct vidtv_psi_table_nit, bitfield2); while (t) { /* skip both pointers at the end */ transport_loop_len += sizeof(struct vidtv_psi_table_transport) - sizeof(struct vidtv_psi_desc *) - sizeof(struct vidtv_psi_table_transport *); length += transport_loop_len; desc_loop_len = vidtv_psi_desc_comp_loop_len(t->descriptor); vidtv_psi_set_desc_loop_len(&t->bitfield, desc_loop_len, 12); length += desc_loop_len; t = t->next; } // Actually sets the transport stream loop len, maybe rename this function later vidtv_psi_set_desc_loop_len(&nit->bitfield2, transport_loop_len, 12); length += CRC_SIZE_IN_BYTES; vidtv_psi_set_sec_len(&nit->header, length); } struct vidtv_psi_table_nit *vidtv_psi_nit_table_init(u16 network_id, u16 transport_stream_id, char *network_name, struct vidtv_psi_desc_service_list_entry *service_list) { struct vidtv_psi_table_transport *transport; struct vidtv_psi_table_nit *nit; const u16 SYNTAX = 0x1; const u16 ONES = 0x03; const u16 ONE = 0x1; nit = kzalloc(sizeof(*nit), GFP_KERNEL); if (!nit) return NULL; transport = kzalloc(sizeof(*transport), GFP_KERNEL); if (!transport) goto free_nit; nit->header.table_id = 0x40; // ACTUAL_NETWORK nit->header.bitfield = cpu_to_be16((SYNTAX << 15) | (ONE << 14) | (ONES << 12)); nit->header.id = cpu_to_be16(network_id); nit->header.current_next = ONE; nit->header.version = 0x1f; nit->header.one2 = ONES; nit->header.section_id = 0; nit->header.last_section = 0; nit->bitfield = cpu_to_be16(0xf); nit->bitfield2 = cpu_to_be16(0xf); nit->descriptor = (struct vidtv_psi_desc *) vidtv_psi_network_name_desc_init(NULL, network_name); if (!nit->descriptor) goto free_transport; transport->transport_id = cpu_to_be16(transport_stream_id); transport->network_id = cpu_to_be16(network_id); transport->bitfield = cpu_to_be16(0xf); transport->descriptor = (struct vidtv_psi_desc *) vidtv_psi_service_list_desc_init(NULL, service_list); if (!transport->descriptor) goto free_nit_desc; nit->transport = transport; vidtv_psi_nit_table_update_sec_len(nit); return nit; free_nit_desc: vidtv_psi_desc_destroy((struct vidtv_psi_desc *)nit->descriptor); free_transport: kfree(transport); free_nit: kfree(nit); return NULL; } u32 vidtv_psi_nit_write_into(struct vidtv_psi_nit_write_args *args) { struct header_write_args h_args = { .dest_buf = args->buf, .dest_offset = args->offset, .h = &args->nit->header, .pid = VIDTV_NIT_PID, .dest_buf_sz = args->buf_sz, }; struct psi_write_args psi_args = { .dest_buf = args->buf, .from = &args->nit->bitfield, .len = sizeof_field(struct vidtv_psi_table_nit, bitfield), .pid = VIDTV_NIT_PID, .new_psi_section = false, .is_crc = false, .dest_buf_sz = args->buf_sz, }; struct desc_write_args d_args = { .dest_buf = args->buf, .pid = VIDTV_NIT_PID, .dest_buf_sz = args->buf_sz, }; struct crc32_write_args c_args = { .dest_buf = args->buf, .pid = VIDTV_NIT_PID, .dest_buf_sz = args->buf_sz, }; struct vidtv_psi_desc *table_descriptor = args->nit->descriptor; struct vidtv_psi_table_transport *transport = args->nit->transport; struct vidtv_psi_desc *transport_descriptor; u32 crc = INITIAL_CRC; u32 nbytes = 0; vidtv_psi_nit_table_update_sec_len(args->nit); h_args.continuity_counter = args->continuity_counter; h_args.crc = &crc; nbytes += vidtv_psi_table_header_write_into(&h_args); /* write the bitfield */ psi_args.dest_offset = args->offset + nbytes; psi_args.continuity_counter = args->continuity_counter; psi_args.crc = &crc; nbytes += vidtv_psi_ts_psi_write_into(&psi_args); while (table_descriptor) { /* write the descriptors, if any */ d_args.dest_offset = args->offset + nbytes; d_args.desc = table_descriptor; d_args.continuity_counter = args->continuity_counter; d_args.crc = &crc; nbytes += vidtv_psi_desc_write_into(&d_args); table_descriptor = table_descriptor->next; } /* write the second bitfield */ psi_args.from = &args->nit->bitfield2; psi_args.len = sizeof_field(struct vidtv_psi_table_nit, bitfield2); psi_args.dest_offset = args->offset + nbytes; nbytes += vidtv_psi_ts_psi_write_into(&psi_args); psi_args.len = sizeof_field(struct vidtv_psi_table_transport, transport_id) + sizeof_field(struct vidtv_psi_table_transport, network_id) + sizeof_field(struct vidtv_psi_table_transport, bitfield); while (transport) { /* write the transport sections, if any */ psi_args.from = transport; psi_args.dest_offset = args->offset + nbytes; nbytes += vidtv_psi_ts_psi_write_into(&psi_args); transport_descriptor = transport->descriptor; while (transport_descriptor) { /* write the transport descriptors, if any */ d_args.dest_offset = args->offset + nbytes; d_args.desc = transport_descriptor; d_args.continuity_counter = args->continuity_counter; d_args.crc = &crc; nbytes += vidtv_psi_desc_write_into(&d_args); transport_descriptor = transport_descriptor->next; } transport = transport->next; } c_args.dest_offset = args->offset + nbytes; c_args.crc = cpu_to_be32(crc); c_args.continuity_counter = args->continuity_counter; /* Write the CRC32 at the end */ nbytes += table_section_crc32_write_into(&c_args); return nbytes; } static void vidtv_psi_transport_destroy(struct vidtv_psi_table_transport *t) { struct vidtv_psi_table_transport *tmp_t = NULL; struct vidtv_psi_table_transport *curr_t = t; while (curr_t) { tmp_t = curr_t; curr_t = curr_t->next; vidtv_psi_desc_destroy(tmp_t->descriptor); kfree(tmp_t); } } void vidtv_psi_nit_table_destroy(struct vidtv_psi_table_nit *nit) { vidtv_psi_desc_destroy(nit->descriptor); vidtv_psi_transport_destroy(nit->transport); kfree(nit); } void vidtv_psi_eit_table_update_sec_len(struct vidtv_psi_table_eit *eit) { struct vidtv_psi_table_eit_event *e = eit->event; u16 desc_loop_len; u16 length = 0; /* * from immediately after 'section_length' until * 'last_table_id' */ length += EIT_LEN_UNTIL_LAST_TABLE_ID; while (e) { /* skip both pointers at the end */ length += sizeof(struct vidtv_psi_table_eit_event) - sizeof(struct vidtv_psi_desc *) - sizeof(struct vidtv_psi_table_eit_event *); desc_loop_len = vidtv_psi_desc_comp_loop_len(e->descriptor); vidtv_psi_set_desc_loop_len(&e->bitfield, desc_loop_len, 12); length += desc_loop_len; e = e->next; } length += CRC_SIZE_IN_BYTES; vidtv_psi_set_sec_len(&eit->header, length); } void vidtv_psi_eit_event_assign(struct vidtv_psi_table_eit *eit, struct vidtv_psi_table_eit_event *e) { do { if (e == eit->event) return; eit->event = e; vidtv_psi_eit_table_update_sec_len(eit); e = NULL; } while (vidtv_psi_get_sec_len(&eit->header) > EIT_MAX_SECTION_LEN); vidtv_psi_update_version_num(&eit->header); } struct vidtv_psi_table_eit *vidtv_psi_eit_table_init(u16 network_id, u16 transport_stream_id, __be16 service_id) { struct vidtv_psi_table_eit *eit; const u16 SYNTAX = 0x1; const u16 ONE = 0x1; const u16 ONES = 0x03; eit = kzalloc(sizeof(*eit), GFP_KERNEL); if (!eit) return NULL; eit->header.table_id = 0x4e; //actual_transport_stream: present/following eit->header.bitfield = cpu_to_be16((SYNTAX << 15) | (ONE << 14) | (ONES << 12)); eit->header.id = service_id; eit->header.current_next = ONE; eit->header.version = 0x1f; eit->header.one2 = ONES; eit->header.section_id = 0; eit->header.last_section = 0; eit->transport_id = cpu_to_be16(transport_stream_id); eit->network_id = cpu_to_be16(network_id); eit->last_segment = eit->header.last_section; /* not implemented */ eit->last_table_id = eit->header.table_id; /* not implemented */ vidtv_psi_eit_table_update_sec_len(eit); return eit; } u32 vidtv_psi_eit_write_into(struct vidtv_psi_eit_write_args *args) { struct header_write_args h_args = { .dest_buf = args->buf, .dest_offset = args->offset, .h = &args->eit->header, .pid = VIDTV_EIT_PID, .dest_buf_sz = args->buf_sz, }; struct psi_write_args psi_args = { .dest_buf = args->buf, .len = sizeof_field(struct vidtv_psi_table_eit, transport_id) + sizeof_field(struct vidtv_psi_table_eit, network_id) + sizeof_field(struct vidtv_psi_table_eit, last_segment) + sizeof_field(struct vidtv_psi_table_eit, last_table_id), .pid = VIDTV_EIT_PID, .new_psi_section = false, .is_crc = false, .dest_buf_sz = args->buf_sz, }; struct desc_write_args d_args = { .dest_buf = args->buf, .pid = VIDTV_EIT_PID, .dest_buf_sz = args->buf_sz, }; struct crc32_write_args c_args = { .dest_buf = args->buf, .pid = VIDTV_EIT_PID, .dest_buf_sz = args->buf_sz, }; struct vidtv_psi_table_eit_event *event = args->eit->event; struct vidtv_psi_desc *event_descriptor; u32 crc = INITIAL_CRC; u32 nbytes = 0; vidtv_psi_eit_table_update_sec_len(args->eit); h_args.continuity_counter = args->continuity_counter; h_args.crc = &crc; nbytes += vidtv_psi_table_header_write_into(&h_args); psi_args.from = &args->eit->transport_id; psi_args.dest_offset = args->offset + nbytes; psi_args.continuity_counter = args->continuity_counter; psi_args.crc = &crc; nbytes += vidtv_psi_ts_psi_write_into(&psi_args); /* skip both pointers at the end */ psi_args.len = sizeof(struct vidtv_psi_table_eit_event) - sizeof(struct vidtv_psi_desc *) - sizeof(struct vidtv_psi_table_eit_event *); while (event) { /* copy the events, if any */ psi_args.from = event; psi_args.dest_offset = args->offset + nbytes; nbytes += vidtv_psi_ts_psi_write_into(&psi_args); event_descriptor = event->descriptor; while (event_descriptor) { /* copy the event descriptors, if any */ d_args.dest_offset = args->offset + nbytes; d_args.desc = event_descriptor; d_args.continuity_counter = args->continuity_counter; d_args.crc = &crc; nbytes += vidtv_psi_desc_write_into(&d_args); event_descriptor = event_descriptor->next; } event = event->next; } c_args.dest_offset = args->offset + nbytes; c_args.crc = cpu_to_be32(crc); c_args.continuity_counter = args->continuity_counter; /* Write the CRC at the end */ nbytes += table_section_crc32_write_into(&c_args); return nbytes; } struct vidtv_psi_table_eit_event *vidtv_psi_eit_event_init(struct vidtv_psi_table_eit_event *head, u16 event_id) { static const u8 DURATION[] = {0x23, 0x59, 0x59}; /* BCD encoded */ struct vidtv_psi_table_eit_event *e; struct timespec64 ts; struct tm time; int mjd, l; __be16 mjd_be; e = kzalloc(sizeof(*e), GFP_KERNEL); if (!e) return NULL; e->event_id = cpu_to_be16(event_id); ts = ktime_to_timespec64(ktime_get_real()); time64_to_tm(ts.tv_sec, 0, &time); /* Convert date to Modified Julian Date - per EN 300 468 Annex C */ if (time.tm_mon < 2) l = 1; else l = 0; mjd = 14956 + time.tm_mday; mjd += (time.tm_year - l) * 36525 / 100; mjd += (time.tm_mon + 2 + l * 12) * 306001 / 10000; mjd_be = cpu_to_be16(mjd); /* * Store MJD and hour/min/sec to the event. * * Let's make the event to start on a full hour */ memcpy(e->start_time, &mjd_be, sizeof(mjd_be)); e->start_time[2] = bin2bcd(time.tm_hour); e->start_time[3] = 0; e->start_time[4] = 0; /* * TODO: for now, the event will last for a day. Should be * enough for testing purposes, but if one runs the driver * for more than that, the current event will become invalid. * So, we need a better code here in order to change the start * time once the event expires. */ memcpy(e->duration, DURATION, sizeof(e->duration)); e->bitfield = cpu_to_be16(RUNNING << 13); if (head) { while (head->next) head = head->next; head->next = e; } return e; } void vidtv_psi_eit_event_destroy(struct vidtv_psi_table_eit_event *e) { struct vidtv_psi_table_eit_event *tmp_e = NULL; struct vidtv_psi_table_eit_event *curr_e = e; while (curr_e) { tmp_e = curr_e; curr_e = curr_e->next; vidtv_psi_desc_destroy(tmp_e->descriptor); kfree(tmp_e); } } void vidtv_psi_eit_table_destroy(struct vidtv_psi_table_eit *eit) { vidtv_psi_eit_event_destroy(eit->event); kfree(eit); }
linux-master
drivers/media/test-drivers/vidtv/vidtv_psi.c
// SPDX-License-Identifier: GPL-2.0 /* * The Virtual DTV test driver serves as a reference DVB driver and helps * validate the existing APIs in the media subsystem. It can also aid * developers working on userspace applications. * * When this module is loaded, it will attempt to modprobe 'dvb_vidtv_tuner' * and 'dvb_vidtv_demod'. * * Copyright (C) 2020 Daniel W. S. Almeida */ #include <linux/dev_printk.h> #include <linux/moduleparam.h> #include <linux/mutex.h> #include <linux/platform_device.h> #include <linux/time.h> #include <linux/types.h> #include <linux/workqueue.h> #include <media/dvbdev.h> #include <media/media-device.h> #include "vidtv_bridge.h" #include "vidtv_common.h" #include "vidtv_demod.h" #include "vidtv_mux.h" #include "vidtv_ts.h" #include "vidtv_tuner.h" #define MUX_BUF_MIN_SZ 90164 #define MUX_BUF_MAX_SZ (MUX_BUF_MIN_SZ * 10) #define TUNER_DEFAULT_ADDR 0x68 #define DEMOD_DEFAULT_ADDR 0x60 #define VIDTV_DEFAULT_NETWORK_ID 0xff44 #define VIDTV_DEFAULT_NETWORK_NAME "LinuxTV.org" #define VIDTV_DEFAULT_TS_ID 0x4081 /* * The LNBf fake parameters here are the ranges used by an * Universal (extended) European LNBf, which is likely the most common LNBf * found on Satellite digital TV system nowadays. */ #define LNB_CUT_FREQUENCY 11700000 /* high IF frequency */ #define LNB_LOW_FREQ 9750000 /* low IF frequency */ #define LNB_HIGH_FREQ 10600000 /* transition frequency */ static unsigned int drop_tslock_prob_on_low_snr; module_param(drop_tslock_prob_on_low_snr, uint, 0); MODULE_PARM_DESC(drop_tslock_prob_on_low_snr, "Probability of losing the TS lock if the signal quality is bad"); static unsigned int recover_tslock_prob_on_good_snr; module_param(recover_tslock_prob_on_good_snr, uint, 0); MODULE_PARM_DESC(recover_tslock_prob_on_good_snr, "Probability recovering the TS lock when the signal improves"); static unsigned int mock_power_up_delay_msec; module_param(mock_power_up_delay_msec, uint, 0); MODULE_PARM_DESC(mock_power_up_delay_msec, "Simulate a power up delay"); static unsigned int mock_tune_delay_msec; module_param(mock_tune_delay_msec, uint, 0); MODULE_PARM_DESC(mock_tune_delay_msec, "Simulate a tune delay"); static unsigned int vidtv_valid_dvb_t_freqs[NUM_VALID_TUNER_FREQS] = { 474000000 }; module_param_array(vidtv_valid_dvb_t_freqs, uint, NULL, 0); MODULE_PARM_DESC(vidtv_valid_dvb_t_freqs, "Valid DVB-T frequencies to simulate, in Hz"); static unsigned int vidtv_valid_dvb_c_freqs[NUM_VALID_TUNER_FREQS] = { 474000000 }; module_param_array(vidtv_valid_dvb_c_freqs, uint, NULL, 0); MODULE_PARM_DESC(vidtv_valid_dvb_c_freqs, "Valid DVB-C frequencies to simulate, in Hz"); static unsigned int vidtv_valid_dvb_s_freqs[NUM_VALID_TUNER_FREQS] = { 11362000 }; module_param_array(vidtv_valid_dvb_s_freqs, uint, NULL, 0); MODULE_PARM_DESC(vidtv_valid_dvb_s_freqs, "Valid DVB-S/S2 frequencies to simulate at Ku-Band, in kHz"); static unsigned int max_frequency_shift_hz; module_param(max_frequency_shift_hz, uint, 0); MODULE_PARM_DESC(max_frequency_shift_hz, "Maximum shift in HZ allowed when tuning in a channel"); DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nums); /* * Influences the signal acquisition time. See ISO/IEC 13818-1 : 2000. p. 113. */ static unsigned int si_period_msec = 40; module_param(si_period_msec, uint, 0); MODULE_PARM_DESC(si_period_msec, "How often to send SI packets. Default: 40ms"); static unsigned int pcr_period_msec = 40; module_param(pcr_period_msec, uint, 0); MODULE_PARM_DESC(pcr_period_msec, "How often to send PCR packets. Default: 40ms"); static unsigned int mux_rate_kbytes_sec = 4096; module_param(mux_rate_kbytes_sec, uint, 0); MODULE_PARM_DESC(mux_rate_kbytes_sec, "Mux rate: will pad stream if below"); static unsigned int pcr_pid = 0x200; module_param(pcr_pid, uint, 0); MODULE_PARM_DESC(pcr_pid, "PCR PID for all channels: defaults to 0x200"); static unsigned int mux_buf_sz_pkts; module_param(mux_buf_sz_pkts, uint, 0); MODULE_PARM_DESC(mux_buf_sz_pkts, "Size for the internal mux buffer in multiples of 188 bytes"); static u32 vidtv_bridge_mux_buf_sz_for_mux_rate(void) { u32 max_elapsed_time_msecs = VIDTV_MAX_SLEEP_USECS / USEC_PER_MSEC; u32 mux_buf_sz = mux_buf_sz_pkts * TS_PACKET_LEN; u32 nbytes_expected; nbytes_expected = mux_rate_kbytes_sec; nbytes_expected *= max_elapsed_time_msecs; mux_buf_sz = roundup(nbytes_expected, TS_PACKET_LEN); mux_buf_sz += mux_buf_sz / 10; if (mux_buf_sz < MUX_BUF_MIN_SZ) mux_buf_sz = MUX_BUF_MIN_SZ; if (mux_buf_sz > MUX_BUF_MAX_SZ) mux_buf_sz = MUX_BUF_MAX_SZ; return mux_buf_sz; } static bool vidtv_bridge_check_demod_lock(struct vidtv_dvb *dvb, u32 n) { enum fe_status status; dvb->fe[n]->ops.read_status(dvb->fe[n], &status); return status == (FE_HAS_SIGNAL | FE_HAS_CARRIER | FE_HAS_VITERBI | FE_HAS_SYNC | FE_HAS_LOCK); } /* * called on a separate thread by the mux when new packets become available */ static void vidtv_bridge_on_new_pkts_avail(void *priv, u8 *buf, u32 npkts) { struct vidtv_dvb *dvb = priv; /* drop packets if we lose the lock */ if (vidtv_bridge_check_demod_lock(dvb, 0)) dvb_dmx_swfilter_packets(&dvb->demux, buf, npkts); } static int vidtv_start_streaming(struct vidtv_dvb *dvb) { struct vidtv_mux_init_args mux_args = { .mux_rate_kbytes_sec = mux_rate_kbytes_sec, .on_new_packets_available_cb = vidtv_bridge_on_new_pkts_avail, .pcr_period_usecs = pcr_period_msec * USEC_PER_MSEC, .si_period_usecs = si_period_msec * USEC_PER_MSEC, .pcr_pid = pcr_pid, .transport_stream_id = VIDTV_DEFAULT_TS_ID, .network_id = VIDTV_DEFAULT_NETWORK_ID, .network_name = VIDTV_DEFAULT_NETWORK_NAME, .priv = dvb, }; struct device *dev = &dvb->pdev->dev; u32 mux_buf_sz; if (dvb->streaming) { dev_warn_ratelimited(dev, "Already streaming. Skipping.\n"); return 0; } if (mux_buf_sz_pkts) mux_buf_sz = mux_buf_sz_pkts; else mux_buf_sz = vidtv_bridge_mux_buf_sz_for_mux_rate(); mux_args.mux_buf_sz = mux_buf_sz; dvb->streaming = true; dvb->mux = vidtv_mux_init(dvb->fe[0], dev, &mux_args); if (!dvb->mux) return -ENOMEM; vidtv_mux_start_thread(dvb->mux); dev_dbg_ratelimited(dev, "Started streaming\n"); return 0; } static int vidtv_stop_streaming(struct vidtv_dvb *dvb) { struct device *dev = &dvb->pdev->dev; dvb->streaming = false; vidtv_mux_stop_thread(dvb->mux); vidtv_mux_destroy(dvb->mux); dvb->mux = NULL; dev_dbg_ratelimited(dev, "Stopped streaming\n"); return 0; } static int vidtv_start_feed(struct dvb_demux_feed *feed) { struct dvb_demux *demux = feed->demux; struct vidtv_dvb *dvb = demux->priv; int ret; int rc; if (!demux->dmx.frontend) return -EINVAL; mutex_lock(&dvb->feed_lock); dvb->nfeeds++; rc = dvb->nfeeds; if (dvb->nfeeds == 1) { ret = vidtv_start_streaming(dvb); if (ret < 0) rc = ret; } mutex_unlock(&dvb->feed_lock); return rc; } static int vidtv_stop_feed(struct dvb_demux_feed *feed) { struct dvb_demux *demux = feed->demux; struct vidtv_dvb *dvb = demux->priv; int err = 0; mutex_lock(&dvb->feed_lock); dvb->nfeeds--; if (!dvb->nfeeds) err = vidtv_stop_streaming(dvb); mutex_unlock(&dvb->feed_lock); return err; } static struct dvb_frontend *vidtv_get_frontend_ptr(struct i2c_client *c) { struct vidtv_demod_state *state = i2c_get_clientdata(c); /* the demod will set this when its probe function runs */ return &state->frontend; } static int vidtv_master_xfer(struct i2c_adapter *i2c_adap, struct i2c_msg msgs[], int num) { /* * Right now, this virtual driver doesn't really send or receive * messages from I2C. A real driver will require an implementation * here. */ return 0; } static u32 vidtv_i2c_func(struct i2c_adapter *adapter) { return I2C_FUNC_I2C; } static const struct i2c_algorithm vidtv_i2c_algorithm = { .master_xfer = vidtv_master_xfer, .functionality = vidtv_i2c_func, }; static int vidtv_bridge_i2c_register_adap(struct vidtv_dvb *dvb) { struct i2c_adapter *i2c_adapter = &dvb->i2c_adapter; strscpy(i2c_adapter->name, "vidtv_i2c", sizeof(i2c_adapter->name)); i2c_adapter->owner = THIS_MODULE; i2c_adapter->algo = &vidtv_i2c_algorithm; i2c_adapter->algo_data = NULL; i2c_adapter->timeout = 500; i2c_adapter->retries = 3; i2c_adapter->dev.parent = &dvb->pdev->dev; i2c_set_adapdata(i2c_adapter, dvb); return i2c_add_adapter(&dvb->i2c_adapter); } static int vidtv_bridge_register_adap(struct vidtv_dvb *dvb) { int ret = 0; ret = dvb_register_adapter(&dvb->adapter, KBUILD_MODNAME, THIS_MODULE, &dvb->i2c_adapter.dev, adapter_nums); return ret; } static int vidtv_bridge_dmx_init(struct vidtv_dvb *dvb) { dvb->demux.dmx.capabilities = DMX_TS_FILTERING | DMX_SECTION_FILTERING; dvb->demux.priv = dvb; dvb->demux.filternum = 256; dvb->demux.feednum = 256; dvb->demux.start_feed = vidtv_start_feed; dvb->demux.stop_feed = vidtv_stop_feed; return dvb_dmx_init(&dvb->demux); } static int vidtv_bridge_dmxdev_init(struct vidtv_dvb *dvb) { dvb->dmx_dev.filternum = 256; dvb->dmx_dev.demux = &dvb->demux.dmx; dvb->dmx_dev.capabilities = 0; return dvb_dmxdev_init(&dvb->dmx_dev, &dvb->adapter); } static int vidtv_bridge_probe_demod(struct vidtv_dvb *dvb, u32 n) { struct vidtv_demod_config cfg = { .drop_tslock_prob_on_low_snr = drop_tslock_prob_on_low_snr, .recover_tslock_prob_on_good_snr = recover_tslock_prob_on_good_snr, }; dvb->i2c_client_demod[n] = dvb_module_probe("dvb_vidtv_demod", NULL, &dvb->i2c_adapter, DEMOD_DEFAULT_ADDR, &cfg); /* driver will not work anyways so bail out */ if (!dvb->i2c_client_demod[n]) return -ENODEV; /* retrieve a ptr to the frontend state */ dvb->fe[n] = vidtv_get_frontend_ptr(dvb->i2c_client_demod[n]); return 0; } static int vidtv_bridge_probe_tuner(struct vidtv_dvb *dvb, u32 n) { struct vidtv_tuner_config cfg = { .fe = dvb->fe[n], .mock_power_up_delay_msec = mock_power_up_delay_msec, .mock_tune_delay_msec = mock_tune_delay_msec, }; u32 freq; int i; /* TODO: check if the frequencies are at a valid range */ memcpy(cfg.vidtv_valid_dvb_t_freqs, vidtv_valid_dvb_t_freqs, sizeof(vidtv_valid_dvb_t_freqs)); memcpy(cfg.vidtv_valid_dvb_c_freqs, vidtv_valid_dvb_c_freqs, sizeof(vidtv_valid_dvb_c_freqs)); /* * Convert Satellite frequencies from Ku-band in kHZ into S-band * frequencies in Hz. */ for (i = 0; i < ARRAY_SIZE(vidtv_valid_dvb_s_freqs); i++) { freq = vidtv_valid_dvb_s_freqs[i]; if (freq) { if (freq < LNB_CUT_FREQUENCY) freq = abs(freq - LNB_LOW_FREQ); else freq = abs(freq - LNB_HIGH_FREQ); } cfg.vidtv_valid_dvb_s_freqs[i] = freq; } cfg.max_frequency_shift_hz = max_frequency_shift_hz; dvb->i2c_client_tuner[n] = dvb_module_probe("dvb_vidtv_tuner", NULL, &dvb->i2c_adapter, TUNER_DEFAULT_ADDR, &cfg); return (dvb->i2c_client_tuner[n]) ? 0 : -ENODEV; } static int vidtv_bridge_dvb_init(struct vidtv_dvb *dvb) { int ret, i, j; ret = vidtv_bridge_i2c_register_adap(dvb); if (ret < 0) goto fail_i2c; ret = vidtv_bridge_register_adap(dvb); if (ret < 0) goto fail_adapter; dvb_register_media_controller(&dvb->adapter, &dvb->mdev); for (i = 0; i < NUM_FE; ++i) { ret = vidtv_bridge_probe_demod(dvb, i); if (ret < 0) goto fail_demod_probe; ret = vidtv_bridge_probe_tuner(dvb, i); if (ret < 0) goto fail_tuner_probe; ret = dvb_register_frontend(&dvb->adapter, dvb->fe[i]); if (ret < 0) goto fail_fe; } ret = vidtv_bridge_dmx_init(dvb); if (ret < 0) goto fail_dmx; ret = vidtv_bridge_dmxdev_init(dvb); if (ret < 0) goto fail_dmx_dev; for (j = 0; j < NUM_FE; ++j) { ret = dvb->demux.dmx.connect_frontend(&dvb->demux.dmx, &dvb->dmx_fe[j]); if (ret < 0) goto fail_dmx_conn; /* * The source of the demux is a frontend connected * to the demux. */ dvb->dmx_fe[j].source = DMX_FRONTEND_0; } return ret; fail_dmx_conn: for (j = j - 1; j >= 0; --j) dvb->demux.dmx.remove_frontend(&dvb->demux.dmx, &dvb->dmx_fe[j]); dvb_dmxdev_release(&dvb->dmx_dev); fail_dmx_dev: dvb_dmx_release(&dvb->demux); fail_dmx: fail_demod_probe: for (i = i - 1; i >= 0; --i) { dvb_unregister_frontend(dvb->fe[i]); fail_fe: dvb_module_release(dvb->i2c_client_tuner[i]); fail_tuner_probe: dvb_module_release(dvb->i2c_client_demod[i]); } fail_adapter: dvb_unregister_adapter(&dvb->adapter); fail_i2c: i2c_del_adapter(&dvb->i2c_adapter); return ret; } static int vidtv_bridge_probe(struct platform_device *pdev) { struct vidtv_dvb *dvb; int ret; dvb = kzalloc(sizeof(*dvb), GFP_KERNEL); if (!dvb) return -ENOMEM; dvb->pdev = pdev; #ifdef CONFIG_MEDIA_CONTROLLER_DVB dvb->mdev.dev = &pdev->dev; strscpy(dvb->mdev.model, "vidtv", sizeof(dvb->mdev.model)); strscpy(dvb->mdev.bus_info, "platform:vidtv", sizeof(dvb->mdev.bus_info)); media_device_init(&dvb->mdev); #endif ret = vidtv_bridge_dvb_init(dvb); if (ret < 0) goto err_dvb; mutex_init(&dvb->feed_lock); platform_set_drvdata(pdev, dvb); #ifdef CONFIG_MEDIA_CONTROLLER_DVB ret = media_device_register(&dvb->mdev); if (ret) { dev_err(dvb->mdev.dev, "media device register failed (err=%d)\n", ret); goto err_media_device_register; } #endif /* CONFIG_MEDIA_CONTROLLER_DVB */ dev_info(&pdev->dev, "Successfully initialized vidtv!\n"); return ret; #ifdef CONFIG_MEDIA_CONTROLLER_DVB err_media_device_register: media_device_cleanup(&dvb->mdev); #endif /* CONFIG_MEDIA_CONTROLLER_DVB */ err_dvb: kfree(dvb); return ret; } static void vidtv_bridge_remove(struct platform_device *pdev) { struct vidtv_dvb *dvb; u32 i; dvb = platform_get_drvdata(pdev); #ifdef CONFIG_MEDIA_CONTROLLER_DVB media_device_unregister(&dvb->mdev); media_device_cleanup(&dvb->mdev); #endif /* CONFIG_MEDIA_CONTROLLER_DVB */ mutex_destroy(&dvb->feed_lock); for (i = 0; i < NUM_FE; ++i) { dvb_unregister_frontend(dvb->fe[i]); dvb_module_release(dvb->i2c_client_tuner[i]); dvb_module_release(dvb->i2c_client_demod[i]); } dvb_dmxdev_release(&dvb->dmx_dev); dvb_dmx_release(&dvb->demux); dvb_unregister_adapter(&dvb->adapter); dev_info(&pdev->dev, "Successfully removed vidtv\n"); } static void vidtv_bridge_dev_release(struct device *dev) { struct vidtv_dvb *dvb; dvb = dev_get_drvdata(dev); kfree(dvb); } static struct platform_device vidtv_bridge_dev = { .name = VIDTV_PDEV_NAME, .dev.release = vidtv_bridge_dev_release, }; static struct platform_driver vidtv_bridge_driver = { .driver = { .name = VIDTV_PDEV_NAME, }, .probe = vidtv_bridge_probe, .remove_new = vidtv_bridge_remove, }; static void __exit vidtv_bridge_exit(void) { platform_driver_unregister(&vidtv_bridge_driver); platform_device_unregister(&vidtv_bridge_dev); } static int __init vidtv_bridge_init(void) { int ret; ret = platform_device_register(&vidtv_bridge_dev); if (ret) return ret; ret = platform_driver_register(&vidtv_bridge_driver); if (ret) platform_device_unregister(&vidtv_bridge_dev); return ret; } module_init(vidtv_bridge_init); module_exit(vidtv_bridge_exit); MODULE_DESCRIPTION("Virtual Digital TV Test Driver"); MODULE_AUTHOR("Daniel W. S. Almeida"); MODULE_LICENSE("GPL"); MODULE_ALIAS("vidtv"); MODULE_ALIAS("dvb_vidtv");
linux-master
drivers/media/test-drivers/vidtv/vidtv_bridge.c
// SPDX-License-Identifier: GPL-2.0+ /* * Debugfs tracing for bitstream buffers. This is similar to VA-API's * LIBVA_TRACE_BUFDATA in that the raw bitstream can be dumped as a debugging * aid. * * Produces one file per OUTPUT buffer. Files are automatically cleared on * STREAMOFF unless the module parameter "keep_bitstream_buffers" is set. */ #include <linux/debugfs.h> #include <linux/list.h> #include <linux/mutex.h> #include <media/v4l2-mem2mem.h> #include "visl-debugfs.h" int visl_debugfs_init(struct visl_dev *dev) { dev->debugfs_root = debugfs_create_dir("visl", NULL); INIT_LIST_HEAD(&dev->bitstream_blobs); mutex_init(&dev->bitstream_lock); if (IS_ERR(dev->debugfs_root)) return PTR_ERR(dev->debugfs_root); return visl_debugfs_bitstream_init(dev); } int visl_debugfs_bitstream_init(struct visl_dev *dev) { dev->bitstream_debugfs = debugfs_create_dir("bitstream", dev->debugfs_root); if (IS_ERR(dev->bitstream_debugfs)) return PTR_ERR(dev->bitstream_debugfs); return 0; } void visl_trace_bitstream(struct visl_ctx *ctx, struct visl_run *run) { u8 *vaddr = vb2_plane_vaddr(&run->src->vb2_buf, 0); struct visl_blob *blob; size_t data_sz = vb2_get_plane_payload(&run->src->vb2_buf, 0); struct dentry *dentry; char name[32]; blob = kzalloc(sizeof(*blob), GFP_KERNEL); if (!blob) return; blob->blob.data = vzalloc(data_sz); if (!blob->blob.data) goto err_vmalloc; blob->blob.size = data_sz; snprintf(name, 32, "bitstream%d", run->src->sequence); memcpy(blob->blob.data, vaddr, data_sz); dentry = debugfs_create_blob(name, 0444, ctx->dev->bitstream_debugfs, &blob->blob); if (IS_ERR(dentry)) goto err_debugfs; blob->dentry = dentry; mutex_lock(&ctx->dev->bitstream_lock); list_add_tail(&blob->list, &ctx->dev->bitstream_blobs); mutex_unlock(&ctx->dev->bitstream_lock); return; err_debugfs: vfree(blob->blob.data); err_vmalloc: kfree(blob); } void visl_debugfs_clear_bitstream(struct visl_dev *dev) { struct visl_blob *blob; struct visl_blob *tmp; mutex_lock(&dev->bitstream_lock); if (list_empty(&dev->bitstream_blobs)) goto unlock; list_for_each_entry_safe(blob, tmp, &dev->bitstream_blobs, list) { list_del(&blob->list); debugfs_remove(blob->dentry); vfree(blob->blob.data); kfree(blob); } unlock: mutex_unlock(&dev->bitstream_lock); } void visl_debugfs_bitstream_deinit(struct visl_dev *dev) { visl_debugfs_clear_bitstream(dev); debugfs_remove_recursive(dev->bitstream_debugfs); dev->bitstream_debugfs = NULL; } void visl_debugfs_deinit(struct visl_dev *dev) { visl_debugfs_bitstream_deinit(dev); debugfs_remove_recursive(dev->debugfs_root); dev->debugfs_root = NULL; }
linux-master
drivers/media/test-drivers/visl/visl-debugfs.c
// SPDX-License-Identifier: GPL-2.0 /* * A virtual stateless decoder device for stateless uAPI development purposes. * * This tool's objective is to help the development and testing of userspace * applications that use the V4L2 stateless API to decode media. * * A userspace implementation can use visl to run a decoding loop even when no * hardware is available or when the kernel uAPI for the codec has not been * upstreamed yet. This can reveal bugs at an early stage. * * This driver can also trace the contents of the V4L2 controls submitted to it. * It can also dump the contents of the vb2 buffers through a debugfs * interface. This is in many ways similar to the tracing infrastructure * available for other popular encode/decode APIs out there and can help develop * a userspace application by using another (working) one as a reference. * * Note that no actual decoding of video frames is performed by visl. The V4L2 * test pattern generator is used to write various debug information to the * capture buffers instead. * * Copyright (C) 2022 Collabora, Ltd. * * Based on the vim2m driver, that is: * * Copyright (c) 2009-2010 Samsung Electronics Co., Ltd. * Pawel Osciak, <[email protected]> * Marek Szyprowski, <[email protected]> * * Based on the vicodec driver, that is: * * Copyright 2018 Cisco Systems, Inc. and/or its affiliates. All rights reserved. * * Based on the Cedrus VPU driver, that is: * * Copyright (C) 2016 Florent Revest <[email protected]> * Copyright (C) 2018 Paul Kocialkowski <[email protected]> * Copyright (C) 2018 Bootlin */ #include <linux/debugfs.h> #include <linux/module.h> #include <linux/platform_device.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-device.h> #include <media/v4l2-ioctl.h> #include <media/v4l2-mem2mem.h> #include "visl.h" #include "visl-dec.h" #include "visl-debugfs.h" #include "visl-video.h" unsigned int visl_debug; module_param(visl_debug, uint, 0644); MODULE_PARM_DESC(visl_debug, " activates debug info"); unsigned int visl_transtime_ms; module_param(visl_transtime_ms, uint, 0644); MODULE_PARM_DESC(visl_transtime_ms, " simulated process time in milliseconds."); /* * dprintk can be slow through serial. This lets one limit the tracing to a * particular number of frames */ int visl_dprintk_frame_start = -1; module_param(visl_dprintk_frame_start, int, 0); MODULE_PARM_DESC(visl_dprintk_frame_start, " a frame number to start tracing with dprintk"); unsigned int visl_dprintk_nframes; module_param(visl_dprintk_nframes, uint, 0); MODULE_PARM_DESC(visl_dprintk_nframes, " the number of frames to trace with dprintk"); bool keep_bitstream_buffers; module_param(keep_bitstream_buffers, bool, false); MODULE_PARM_DESC(keep_bitstream_buffers, " keep bitstream buffers in debugfs after streaming is stopped"); int bitstream_trace_frame_start = -1; module_param(bitstream_trace_frame_start, int, 0); MODULE_PARM_DESC(bitstream_trace_frame_start, " a frame number to start dumping the bitstream through debugfs"); unsigned int bitstream_trace_nframes; module_param(bitstream_trace_nframes, uint, 0); MODULE_PARM_DESC(bitstream_trace_nframes, " the number of frames to dump the bitstream through debugfs"); static const struct visl_ctrl_desc visl_fwht_ctrl_descs[] = { { .cfg.id = V4L2_CID_STATELESS_FWHT_PARAMS, }, }; const struct visl_ctrls visl_fwht_ctrls = { .ctrls = visl_fwht_ctrl_descs, .num_ctrls = ARRAY_SIZE(visl_fwht_ctrl_descs) }; static const struct visl_ctrl_desc visl_mpeg2_ctrl_descs[] = { { .cfg.id = V4L2_CID_STATELESS_MPEG2_SEQUENCE, }, { .cfg.id = V4L2_CID_STATELESS_MPEG2_PICTURE, }, { .cfg.id = V4L2_CID_STATELESS_MPEG2_QUANTISATION, }, }; const struct visl_ctrls visl_mpeg2_ctrls = { .ctrls = visl_mpeg2_ctrl_descs, .num_ctrls = ARRAY_SIZE(visl_mpeg2_ctrl_descs), }; static const struct visl_ctrl_desc visl_vp8_ctrl_descs[] = { { .cfg.id = V4L2_CID_STATELESS_VP8_FRAME, }, }; const struct visl_ctrls visl_vp8_ctrls = { .ctrls = visl_vp8_ctrl_descs, .num_ctrls = ARRAY_SIZE(visl_vp8_ctrl_descs), }; static const struct visl_ctrl_desc visl_vp9_ctrl_descs[] = { { .cfg.id = V4L2_CID_STATELESS_VP9_FRAME, }, { .cfg.id = V4L2_CID_STATELESS_VP9_COMPRESSED_HDR, }, }; const struct visl_ctrls visl_vp9_ctrls = { .ctrls = visl_vp9_ctrl_descs, .num_ctrls = ARRAY_SIZE(visl_vp9_ctrl_descs), }; static const struct visl_ctrl_desc visl_h264_ctrl_descs[] = { { .cfg.id = V4L2_CID_STATELESS_H264_DECODE_PARAMS, }, { .cfg.id = V4L2_CID_STATELESS_H264_SPS, }, { .cfg.id = V4L2_CID_STATELESS_H264_PPS, }, { .cfg.id = V4L2_CID_STATELESS_H264_SCALING_MATRIX, }, { .cfg.id = V4L2_CID_STATELESS_H264_DECODE_MODE, }, { .cfg.id = V4L2_CID_STATELESS_H264_START_CODE, }, { .cfg.id = V4L2_CID_STATELESS_H264_SLICE_PARAMS, }, { .cfg.id = V4L2_CID_STATELESS_H264_PRED_WEIGHTS, }, }; const struct visl_ctrls visl_h264_ctrls = { .ctrls = visl_h264_ctrl_descs, .num_ctrls = ARRAY_SIZE(visl_h264_ctrl_descs), }; static const struct visl_ctrl_desc visl_hevc_ctrl_descs[] = { { .cfg.id = V4L2_CID_STATELESS_HEVC_SPS, }, { .cfg.id = V4L2_CID_STATELESS_HEVC_PPS, }, { .cfg.id = V4L2_CID_STATELESS_HEVC_SLICE_PARAMS, /* The absolute maximum for level > 6 */ .cfg.dims = { 600 }, }, { .cfg.id = V4L2_CID_STATELESS_HEVC_SCALING_MATRIX, }, { .cfg.id = V4L2_CID_STATELESS_HEVC_DECODE_PARAMS, }, { .cfg.id = V4L2_CID_STATELESS_HEVC_DECODE_MODE, }, { .cfg.id = V4L2_CID_STATELESS_HEVC_START_CODE, }, { .cfg.id = V4L2_CID_STATELESS_HEVC_ENTRY_POINT_OFFSETS, .cfg.dims = { 256 }, .cfg.max = 0xffffffff, .cfg.step = 1, }, }; const struct visl_ctrls visl_hevc_ctrls = { .ctrls = visl_hevc_ctrl_descs, .num_ctrls = ARRAY_SIZE(visl_hevc_ctrl_descs), }; struct v4l2_ctrl *visl_find_control(struct visl_ctx *ctx, u32 id) { struct v4l2_ctrl_handler *hdl = &ctx->hdl; return v4l2_ctrl_find(hdl, id); } void *visl_find_control_data(struct visl_ctx *ctx, u32 id) { struct v4l2_ctrl *ctrl; ctrl = visl_find_control(ctx, id); if (ctrl) return ctrl->p_cur.p; return NULL; } u32 visl_control_num_elems(struct visl_ctx *ctx, u32 id) { struct v4l2_ctrl *ctrl; ctrl = visl_find_control(ctx, id); if (ctrl) return ctrl->elems; return 0; } static void visl_device_release(struct video_device *vdev) { struct visl_dev *dev = container_of(vdev, struct visl_dev, vfd); v4l2_device_unregister(&dev->v4l2_dev); v4l2_m2m_release(dev->m2m_dev); media_device_cleanup(&dev->mdev); visl_debugfs_deinit(dev); kfree(dev); } #define VISL_CONTROLS_COUNT ARRAY_SIZE(visl_controls) static int visl_init_ctrls(struct visl_ctx *ctx) { struct visl_dev *dev = ctx->dev; struct v4l2_ctrl_handler *hdl = &ctx->hdl; unsigned int ctrl_cnt = 0; unsigned int i; unsigned int j; const struct visl_ctrls *ctrls; for (i = 0; i < num_coded_fmts; i++) ctrl_cnt += visl_coded_fmts[i].ctrls->num_ctrls; v4l2_ctrl_handler_init(hdl, ctrl_cnt); for (i = 0; i < num_coded_fmts; i++) { ctrls = visl_coded_fmts[i].ctrls; for (j = 0; j < ctrls->num_ctrls; j++) v4l2_ctrl_new_custom(hdl, &ctrls->ctrls[j].cfg, NULL); } if (hdl->error) { v4l2_err(&dev->v4l2_dev, "Failed to initialize control handler\n"); v4l2_ctrl_handler_free(hdl); return hdl->error; } ctx->fh.ctrl_handler = hdl; v4l2_ctrl_handler_setup(hdl); return 0; } static int visl_open(struct file *file) { struct visl_dev *dev = video_drvdata(file); struct visl_ctx *ctx = NULL; int rc = 0; if (mutex_lock_interruptible(&dev->dev_mutex)) return -ERESTARTSYS; ctx = kzalloc(sizeof(*ctx), GFP_KERNEL); if (!ctx) { rc = -ENOMEM; goto unlock; } ctx->tpg_str_buf = kzalloc(TPG_STR_BUF_SZ, GFP_KERNEL); v4l2_fh_init(&ctx->fh, video_devdata(file)); file->private_data = &ctx->fh; ctx->dev = dev; rc = visl_init_ctrls(ctx); if (rc) goto free_ctx; ctx->fh.m2m_ctx = v4l2_m2m_ctx_init(dev->m2m_dev, ctx, &visl_queue_init); mutex_init(&ctx->vb_mutex); if (IS_ERR(ctx->fh.m2m_ctx)) { rc = PTR_ERR(ctx->fh.m2m_ctx); goto free_hdl; } rc = visl_set_default_format(ctx); if (rc) goto free_m2m_ctx; v4l2_fh_add(&ctx->fh); dprintk(dev, "Created instance: %p, m2m_ctx: %p\n", ctx, ctx->fh.m2m_ctx); mutex_unlock(&dev->dev_mutex); return rc; free_m2m_ctx: v4l2_m2m_ctx_release(ctx->fh.m2m_ctx); free_hdl: v4l2_ctrl_handler_free(&ctx->hdl); v4l2_fh_exit(&ctx->fh); free_ctx: kfree(ctx->tpg_str_buf); kfree(ctx); unlock: mutex_unlock(&dev->dev_mutex); return rc; } static int visl_release(struct file *file) { struct visl_dev *dev = video_drvdata(file); struct visl_ctx *ctx = visl_file_to_ctx(file); dprintk(dev, "Releasing instance %p\n", ctx); tpg_free(&ctx->tpg); v4l2_fh_del(&ctx->fh); v4l2_fh_exit(&ctx->fh); v4l2_ctrl_handler_free(&ctx->hdl); mutex_lock(&dev->dev_mutex); v4l2_m2m_ctx_release(ctx->fh.m2m_ctx); mutex_unlock(&dev->dev_mutex); kfree(ctx->tpg_str_buf); kfree(ctx); return 0; } static const struct v4l2_file_operations visl_fops = { .owner = THIS_MODULE, .open = visl_open, .release = visl_release, .poll = v4l2_m2m_fop_poll, .unlocked_ioctl = video_ioctl2, .mmap = v4l2_m2m_fop_mmap, }; static const struct video_device visl_videodev = { .name = VISL_NAME, .vfl_dir = VFL_DIR_M2M, .fops = &visl_fops, .ioctl_ops = &visl_ioctl_ops, .minor = -1, .release = visl_device_release, .device_caps = V4L2_CAP_VIDEO_M2M_MPLANE | V4L2_CAP_STREAMING, }; static const struct v4l2_m2m_ops visl_m2m_ops = { .device_run = visl_device_run, }; static const struct media_device_ops visl_m2m_media_ops = { .req_validate = visl_request_validate, .req_queue = v4l2_m2m_request_queue, }; static int visl_probe(struct platform_device *pdev) { struct visl_dev *dev; struct video_device *vfd; int ret; int rc; dev = kzalloc(sizeof(*dev), GFP_KERNEL); if (!dev) return -ENOMEM; ret = v4l2_device_register(&pdev->dev, &dev->v4l2_dev); if (ret) goto error_visl_dev; mutex_init(&dev->dev_mutex); dev->vfd = visl_videodev; vfd = &dev->vfd; vfd->lock = &dev->dev_mutex; vfd->v4l2_dev = &dev->v4l2_dev; video_set_drvdata(vfd, dev); platform_set_drvdata(pdev, dev); dev->m2m_dev = v4l2_m2m_init(&visl_m2m_ops); if (IS_ERR(dev->m2m_dev)) { v4l2_err(&dev->v4l2_dev, "Failed to init mem2mem device\n"); ret = PTR_ERR(dev->m2m_dev); dev->m2m_dev = NULL; goto error_dev; } dev->mdev.dev = &pdev->dev; strscpy(dev->mdev.model, "visl", sizeof(dev->mdev.model)); strscpy(dev->mdev.bus_info, "platform:visl", sizeof(dev->mdev.bus_info)); media_device_init(&dev->mdev); dev->mdev.ops = &visl_m2m_media_ops; dev->v4l2_dev.mdev = &dev->mdev; ret = video_register_device(vfd, VFL_TYPE_VIDEO, -1); if (ret) { v4l2_err(&dev->v4l2_dev, "Failed to register video device\n"); goto error_m2m; } v4l2_info(&dev->v4l2_dev, "Device registered as /dev/video%d\n", vfd->num); ret = v4l2_m2m_register_media_controller(dev->m2m_dev, vfd, MEDIA_ENT_F_PROC_VIDEO_DECODER); if (ret) { v4l2_err(&dev->v4l2_dev, "Failed to init mem2mem media controller\n"); goto error_v4l2; } ret = media_device_register(&dev->mdev); if (ret) { v4l2_err(&dev->v4l2_dev, "Failed to register mem2mem media device\n"); goto error_m2m_mc; } rc = visl_debugfs_init(dev); if (rc) dprintk(dev, "visl_debugfs_init failed: %d\n" "Continuing without debugfs support\n", rc); return 0; error_m2m_mc: v4l2_m2m_unregister_media_controller(dev->m2m_dev); error_v4l2: video_unregister_device(&dev->vfd); /* visl_device_release called by video_unregister_device to release various objects */ return ret; error_m2m: v4l2_m2m_release(dev->m2m_dev); error_dev: v4l2_device_unregister(&dev->v4l2_dev); error_visl_dev: kfree(dev); return ret; } static void visl_remove(struct platform_device *pdev) { struct visl_dev *dev = platform_get_drvdata(pdev); v4l2_info(&dev->v4l2_dev, "Removing " VISL_NAME); #ifdef CONFIG_MEDIA_CONTROLLER if (media_devnode_is_registered(dev->mdev.devnode)) { media_device_unregister(&dev->mdev); v4l2_m2m_unregister_media_controller(dev->m2m_dev); } #endif video_unregister_device(&dev->vfd); } static struct platform_driver visl_pdrv = { .probe = visl_probe, .remove_new = visl_remove, .driver = { .name = VISL_NAME, }, }; static void visl_dev_release(struct device *dev) {} static struct platform_device visl_pdev = { .name = VISL_NAME, .dev.release = visl_dev_release, }; static void __exit visl_exit(void) { platform_driver_unregister(&visl_pdrv); platform_device_unregister(&visl_pdev); } static int __init visl_init(void) { int ret; ret = platform_device_register(&visl_pdev); if (ret) return ret; ret = platform_driver_register(&visl_pdrv); if (ret) platform_device_unregister(&visl_pdev); return ret; } MODULE_DESCRIPTION("Virtual stateless decoder device"); MODULE_AUTHOR("Daniel Almeida <[email protected]>"); MODULE_LICENSE("GPL"); module_init(visl_init); module_exit(visl_exit);
linux-master
drivers/media/test-drivers/visl/visl-core.c
// SPDX-License-Identifier: GPL-2.0 /* * Contains the driver implementation for the V4L2 stateless interface. */ #include <linux/debugfs.h> #include <linux/font.h> #include <media/v4l2-event.h> #include <media/v4l2-ioctl.h> #include <media/videobuf2-vmalloc.h> #include <media/videobuf2-v4l2.h> #include "visl-video.h" #include "visl.h" #include "visl-debugfs.h" #define MIN_CODED_SZ (1024U * 256U) static void visl_set_current_codec(struct visl_ctx *ctx) { u32 fourcc = ctx->coded_fmt.fmt.pix_mp.pixelformat; switch (fourcc) { case V4L2_PIX_FMT_FWHT_STATELESS: ctx->current_codec = VISL_CODEC_FWHT; break; case V4L2_PIX_FMT_MPEG2_SLICE: ctx->current_codec = VISL_CODEC_MPEG2; break; case V4L2_PIX_FMT_VP8_FRAME: ctx->current_codec = VISL_CODEC_VP8; break; case V4L2_PIX_FMT_VP9_FRAME: ctx->current_codec = VISL_CODEC_VP9; break; case V4L2_PIX_FMT_H264_SLICE: ctx->current_codec = VISL_CODEC_H264; break; case V4L2_PIX_FMT_HEVC_SLICE: ctx->current_codec = VISL_CODEC_HEVC; break; default: dprintk(ctx->dev, "Warning: unsupported fourcc: %d\n", fourcc); ctx->current_codec = VISL_CODEC_NONE; break; } } static void visl_print_fmt(struct visl_ctx *ctx, const struct v4l2_format *f) { const struct v4l2_pix_format_mplane *pix_mp = &f->fmt.pix_mp; u32 i; dprintk(ctx->dev, "width: %d\n", pix_mp->width); dprintk(ctx->dev, "height: %d\n", pix_mp->height); dprintk(ctx->dev, "pixelformat: %c%c%c%c\n", pix_mp->pixelformat, (pix_mp->pixelformat >> 8) & 0xff, (pix_mp->pixelformat >> 16) & 0xff, (pix_mp->pixelformat >> 24) & 0xff); dprintk(ctx->dev, "field: %d\n", pix_mp->field); dprintk(ctx->dev, "colorspace: %d\n", pix_mp->colorspace); dprintk(ctx->dev, "num_planes: %d\n", pix_mp->num_planes); dprintk(ctx->dev, "flags: %d\n", pix_mp->flags); dprintk(ctx->dev, "quantization: %d\n", pix_mp->quantization); dprintk(ctx->dev, "xfer_func: %d\n", pix_mp->xfer_func); for (i = 0; i < pix_mp->num_planes; i++) { dprintk(ctx->dev, "plane[%d]: sizeimage: %d\n", i, pix_mp->plane_fmt[i].sizeimage); dprintk(ctx->dev, "plane[%d]: bytesperline: %d\n", i, pix_mp->plane_fmt[i].bytesperline); } } static int visl_tpg_init(struct visl_ctx *ctx) { const struct font_desc *font; const char *font_name = "VGA8x16"; int ret; u32 width = ctx->decoded_fmt.fmt.pix_mp.width; u32 height = ctx->decoded_fmt.fmt.pix_mp.height; struct v4l2_pix_format_mplane *f = &ctx->decoded_fmt.fmt.pix_mp; tpg_free(&ctx->tpg); font = find_font(font_name); if (font) { tpg_init(&ctx->tpg, width, height); ret = tpg_alloc(&ctx->tpg, width); if (ret) goto err_alloc; tpg_set_font(font->data); ret = tpg_s_fourcc(&ctx->tpg, f->pixelformat); if (!ret) goto err_fourcc; tpg_reset_source(&ctx->tpg, width, height, f->field); tpg_s_pattern(&ctx->tpg, TPG_PAT_75_COLORBAR); tpg_s_field(&ctx->tpg, f->field, false); tpg_s_colorspace(&ctx->tpg, f->colorspace); tpg_s_ycbcr_enc(&ctx->tpg, f->ycbcr_enc); tpg_s_quantization(&ctx->tpg, f->quantization); tpg_s_xfer_func(&ctx->tpg, f->xfer_func); } else { v4l2_err(&ctx->dev->v4l2_dev, "Font %s not found\n", font_name); return -EINVAL; } dprintk(ctx->dev, "Initialized the V4L2 test pattern generator, w=%d, h=%d, max_w=%d\n", width, height, width); return 0; err_alloc: return ret; err_fourcc: tpg_free(&ctx->tpg); return ret; } static const u32 visl_decoded_fmts[] = { V4L2_PIX_FMT_NV12, V4L2_PIX_FMT_YUV420, }; const struct visl_coded_format_desc visl_coded_fmts[] = { { .pixelformat = V4L2_PIX_FMT_FWHT_STATELESS, .frmsize = { .min_width = 640, .max_width = 4096, .step_width = 1, .min_height = 360, .max_height = 2160, .step_height = 1, }, .ctrls = &visl_fwht_ctrls, .num_decoded_fmts = ARRAY_SIZE(visl_decoded_fmts), .decoded_fmts = visl_decoded_fmts, }, { .pixelformat = V4L2_PIX_FMT_MPEG2_SLICE, .frmsize = { .min_width = 16, .max_width = 1920, .step_width = 1, .min_height = 16, .max_height = 1152, .step_height = 1, }, .ctrls = &visl_mpeg2_ctrls, .num_decoded_fmts = ARRAY_SIZE(visl_decoded_fmts), .decoded_fmts = visl_decoded_fmts, }, { .pixelformat = V4L2_PIX_FMT_VP8_FRAME, .frmsize = { .min_width = 64, .max_width = 16383, .step_width = 1, .min_height = 64, .max_height = 16383, .step_height = 1, }, .ctrls = &visl_vp8_ctrls, .num_decoded_fmts = ARRAY_SIZE(visl_decoded_fmts), .decoded_fmts = visl_decoded_fmts, }, { .pixelformat = V4L2_PIX_FMT_VP9_FRAME, .frmsize = { .min_width = 64, .max_width = 8192, .step_width = 1, .min_height = 64, .max_height = 4352, .step_height = 1, }, .ctrls = &visl_vp9_ctrls, .num_decoded_fmts = ARRAY_SIZE(visl_decoded_fmts), .decoded_fmts = visl_decoded_fmts, }, { .pixelformat = V4L2_PIX_FMT_H264_SLICE, .frmsize = { .min_width = 64, .max_width = 4096, .step_width = 1, .min_height = 64, .max_height = 2304, .step_height = 1, }, .ctrls = &visl_h264_ctrls, .num_decoded_fmts = ARRAY_SIZE(visl_decoded_fmts), .decoded_fmts = visl_decoded_fmts, }, { .pixelformat = V4L2_PIX_FMT_HEVC_SLICE, .frmsize = { .min_width = 64, .max_width = 4096, .step_width = 1, .min_height = 64, .max_height = 2304, .step_height = 1, }, .ctrls = &visl_hevc_ctrls, .num_decoded_fmts = ARRAY_SIZE(visl_decoded_fmts), .decoded_fmts = visl_decoded_fmts, }, }; const size_t num_coded_fmts = ARRAY_SIZE(visl_coded_fmts); static const struct visl_coded_format_desc* visl_find_coded_fmt_desc(u32 fourcc) { unsigned int i; for (i = 0; i < ARRAY_SIZE(visl_coded_fmts); i++) { if (visl_coded_fmts[i].pixelformat == fourcc) return &visl_coded_fmts[i]; } return NULL; } static void visl_init_fmt(struct v4l2_format *f, u32 fourcc) { memset(f, 0, sizeof(*f)); f->fmt.pix_mp.pixelformat = fourcc; f->fmt.pix_mp.field = V4L2_FIELD_NONE; f->fmt.pix_mp.colorspace = V4L2_COLORSPACE_REC709; f->fmt.pix_mp.ycbcr_enc = V4L2_YCBCR_ENC_DEFAULT; f->fmt.pix_mp.quantization = V4L2_QUANTIZATION_DEFAULT; f->fmt.pix_mp.xfer_func = V4L2_XFER_FUNC_DEFAULT; } static void visl_reset_coded_fmt(struct visl_ctx *ctx) { struct v4l2_format *f = &ctx->coded_fmt; struct v4l2_pix_format_mplane *pix_mp = &f->fmt.pix_mp; ctx->coded_format_desc = &visl_coded_fmts[0]; visl_init_fmt(f, ctx->coded_format_desc->pixelformat); f->type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; f->fmt.pix_mp.width = ctx->coded_format_desc->frmsize.min_width; f->fmt.pix_mp.height = ctx->coded_format_desc->frmsize.min_height; pix_mp->num_planes = 1; pix_mp->plane_fmt[0].sizeimage = pix_mp->width * pix_mp->height * 8; dprintk(ctx->dev, "OUTPUT format was set to:\n"); visl_print_fmt(ctx, &ctx->coded_fmt); visl_set_current_codec(ctx); } static int visl_reset_decoded_fmt(struct visl_ctx *ctx) { struct v4l2_format *f = &ctx->decoded_fmt; u32 decoded_fmt = ctx->coded_format_desc[0].decoded_fmts[0]; visl_init_fmt(f, decoded_fmt); f->type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; v4l2_fill_pixfmt_mp(&f->fmt.pix_mp, ctx->coded_format_desc->decoded_fmts[0], ctx->coded_fmt.fmt.pix_mp.width, ctx->coded_fmt.fmt.pix_mp.height); dprintk(ctx->dev, "CAPTURE format was set to:\n"); visl_print_fmt(ctx, &ctx->decoded_fmt); return visl_tpg_init(ctx); } int visl_set_default_format(struct visl_ctx *ctx) { visl_reset_coded_fmt(ctx); return visl_reset_decoded_fmt(ctx); } static struct visl_q_data *get_q_data(struct visl_ctx *ctx, enum v4l2_buf_type type) { switch (type) { case V4L2_BUF_TYPE_VIDEO_OUTPUT: case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE: return &ctx->q_data[V4L2_M2M_SRC]; case V4L2_BUF_TYPE_VIDEO_CAPTURE: case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE: return &ctx->q_data[V4L2_M2M_DST]; default: break; } return NULL; } static int visl_querycap(struct file *file, void *priv, struct v4l2_capability *cap) { strscpy(cap->driver, VISL_NAME, sizeof(cap->driver)); strscpy(cap->card, VISL_NAME, sizeof(cap->card)); snprintf(cap->bus_info, sizeof(cap->bus_info), "platform:%s", VISL_NAME); return 0; } static int visl_enum_fmt_vid_cap(struct file *file, void *priv, struct v4l2_fmtdesc *f) { struct visl_ctx *ctx = visl_file_to_ctx(file); if (f->index >= ctx->coded_format_desc->num_decoded_fmts) return -EINVAL; f->pixelformat = ctx->coded_format_desc->decoded_fmts[f->index]; return 0; } static int visl_enum_fmt_vid_out(struct file *file, void *priv, struct v4l2_fmtdesc *f) { if (f->index >= ARRAY_SIZE(visl_coded_fmts)) return -EINVAL; f->pixelformat = visl_coded_fmts[f->index].pixelformat; return 0; } static int visl_g_fmt_vid_cap(struct file *file, void *priv, struct v4l2_format *f) { struct visl_ctx *ctx = visl_file_to_ctx(file); *f = ctx->decoded_fmt; return 0; } static int visl_g_fmt_vid_out(struct file *file, void *priv, struct v4l2_format *f) { struct visl_ctx *ctx = visl_file_to_ctx(file); *f = ctx->coded_fmt; return 0; } static int visl_try_fmt_vid_cap(struct file *file, void *priv, struct v4l2_format *f) { struct v4l2_pix_format_mplane *pix_mp = &f->fmt.pix_mp; struct visl_ctx *ctx = visl_file_to_ctx(file); const struct visl_coded_format_desc *coded_desc; unsigned int i; coded_desc = ctx->coded_format_desc; for (i = 0; i < coded_desc->num_decoded_fmts; i++) { if (coded_desc->decoded_fmts[i] == pix_mp->pixelformat) break; } if (i == coded_desc->num_decoded_fmts) pix_mp->pixelformat = coded_desc->decoded_fmts[0]; v4l2_apply_frmsize_constraints(&pix_mp->width, &pix_mp->height, &coded_desc->frmsize); v4l2_fill_pixfmt_mp(pix_mp, pix_mp->pixelformat, pix_mp->width, pix_mp->height); pix_mp->field = V4L2_FIELD_NONE; return 0; } static int visl_try_fmt_vid_out(struct file *file, void *priv, struct v4l2_format *f) { struct v4l2_pix_format_mplane *pix_mp = &f->fmt.pix_mp; const struct visl_coded_format_desc *coded_desc; coded_desc = visl_find_coded_fmt_desc(pix_mp->pixelformat); if (!coded_desc) { pix_mp->pixelformat = visl_coded_fmts[0].pixelformat; coded_desc = &visl_coded_fmts[0]; } v4l2_apply_frmsize_constraints(&pix_mp->width, &pix_mp->height, &coded_desc->frmsize); pix_mp->field = V4L2_FIELD_NONE; pix_mp->num_planes = 1; if (pix_mp->plane_fmt[0].sizeimage == 0) pix_mp->plane_fmt[0].sizeimage = max(MIN_CODED_SZ, pix_mp->width * pix_mp->height * 3); return 0; } static int visl_s_fmt_vid_out(struct file *file, void *priv, struct v4l2_format *f) { struct visl_ctx *ctx = visl_file_to_ctx(file); struct v4l2_m2m_ctx *m2m_ctx = ctx->fh.m2m_ctx; const struct visl_coded_format_desc *desc; struct vb2_queue *peer_vq; int ret; peer_vq = v4l2_m2m_get_vq(m2m_ctx, V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE); if (vb2_is_busy(peer_vq)) return -EBUSY; dprintk(ctx->dev, "Trying to set the OUTPUT format to:\n"); visl_print_fmt(ctx, f); ret = visl_try_fmt_vid_out(file, priv, f); if (ret) return ret; desc = visl_find_coded_fmt_desc(f->fmt.pix_mp.pixelformat); ctx->coded_format_desc = desc; ctx->coded_fmt = *f; ret = visl_reset_decoded_fmt(ctx); if (ret) return ret; ctx->decoded_fmt.fmt.pix_mp.colorspace = f->fmt.pix_mp.colorspace; ctx->decoded_fmt.fmt.pix_mp.xfer_func = f->fmt.pix_mp.xfer_func; ctx->decoded_fmt.fmt.pix_mp.ycbcr_enc = f->fmt.pix_mp.ycbcr_enc; ctx->decoded_fmt.fmt.pix_mp.quantization = f->fmt.pix_mp.quantization; dprintk(ctx->dev, "OUTPUT format was set to:\n"); visl_print_fmt(ctx, &ctx->coded_fmt); visl_set_current_codec(ctx); return 0; } static int visl_s_fmt_vid_cap(struct file *file, void *priv, struct v4l2_format *f) { struct visl_ctx *ctx = visl_file_to_ctx(file); int ret; dprintk(ctx->dev, "Trying to set the CAPTURE format to:\n"); visl_print_fmt(ctx, f); ret = visl_try_fmt_vid_cap(file, priv, f); if (ret) return ret; ctx->decoded_fmt = *f; dprintk(ctx->dev, "CAPTURE format was set to:\n"); visl_print_fmt(ctx, &ctx->decoded_fmt); visl_tpg_init(ctx); return 0; } static int visl_enum_framesizes(struct file *file, void *priv, struct v4l2_frmsizeenum *fsize) { const struct visl_coded_format_desc *fmt; struct visl_ctx *ctx = visl_file_to_ctx(file); if (fsize->index != 0) return -EINVAL; fmt = visl_find_coded_fmt_desc(fsize->pixel_format); if (!fmt) { dprintk(ctx->dev, "Unsupported format for the OUTPUT queue: %d\n", fsize->pixel_format); return -EINVAL; } fsize->type = V4L2_FRMSIZE_TYPE_STEPWISE; fsize->stepwise = fmt->frmsize; return 0; } const struct v4l2_ioctl_ops visl_ioctl_ops = { .vidioc_querycap = visl_querycap, .vidioc_enum_framesizes = visl_enum_framesizes, .vidioc_enum_fmt_vid_cap = visl_enum_fmt_vid_cap, .vidioc_g_fmt_vid_cap_mplane = visl_g_fmt_vid_cap, .vidioc_try_fmt_vid_cap_mplane = visl_try_fmt_vid_cap, .vidioc_s_fmt_vid_cap_mplane = visl_s_fmt_vid_cap, .vidioc_enum_fmt_vid_out = visl_enum_fmt_vid_out, .vidioc_g_fmt_vid_out_mplane = visl_g_fmt_vid_out, .vidioc_try_fmt_vid_out_mplane = visl_try_fmt_vid_out, .vidioc_s_fmt_vid_out_mplane = visl_s_fmt_vid_out, .vidioc_reqbufs = v4l2_m2m_ioctl_reqbufs, .vidioc_querybuf = v4l2_m2m_ioctl_querybuf, .vidioc_qbuf = v4l2_m2m_ioctl_qbuf, .vidioc_dqbuf = v4l2_m2m_ioctl_dqbuf, .vidioc_prepare_buf = v4l2_m2m_ioctl_prepare_buf, .vidioc_create_bufs = v4l2_m2m_ioctl_create_bufs, .vidioc_expbuf = v4l2_m2m_ioctl_expbuf, .vidioc_streamon = v4l2_m2m_ioctl_streamon, .vidioc_streamoff = v4l2_m2m_ioctl_streamoff, .vidioc_subscribe_event = v4l2_ctrl_subscribe_event, .vidioc_unsubscribe_event = v4l2_event_unsubscribe, }; static int visl_queue_setup(struct vb2_queue *vq, unsigned int *nbuffers, unsigned int *num_planes, unsigned int sizes[], struct device *alloc_devs[]) { struct visl_ctx *ctx = vb2_get_drv_priv(vq); struct v4l2_format *f; u32 i; char *qname; if (V4L2_TYPE_IS_OUTPUT(vq->type)) { f = &ctx->coded_fmt; qname = "Output"; } else { f = &ctx->decoded_fmt; qname = "Capture"; } if (*num_planes) { if (*num_planes != f->fmt.pix_mp.num_planes) return -EINVAL; for (i = 0; i < f->fmt.pix_mp.num_planes; i++) { if (sizes[i] < f->fmt.pix_mp.plane_fmt[i].sizeimage) return -EINVAL; } } else { *num_planes = f->fmt.pix_mp.num_planes; for (i = 0; i < f->fmt.pix_mp.num_planes; i++) sizes[i] = f->fmt.pix_mp.plane_fmt[i].sizeimage; } dprintk(ctx->dev, "%s: %d buffer(s) requested, num_planes=%d.\n", qname, *nbuffers, *num_planes); for (i = 0; i < f->fmt.pix_mp.num_planes; i++) dprintk(ctx->dev, "plane[%d].sizeimage=%d\n", i, f->fmt.pix_mp.plane_fmt[i].sizeimage); return 0; } static void visl_queue_cleanup(struct vb2_queue *vq, u32 state) { struct visl_ctx *ctx = vb2_get_drv_priv(vq); struct vb2_v4l2_buffer *vbuf; dprintk(ctx->dev, "Cleaning up queues\n"); for (;;) { if (V4L2_TYPE_IS_OUTPUT(vq->type)) vbuf = v4l2_m2m_src_buf_remove(ctx->fh.m2m_ctx); else vbuf = v4l2_m2m_dst_buf_remove(ctx->fh.m2m_ctx); if (!vbuf) break; v4l2_ctrl_request_complete(vbuf->vb2_buf.req_obj.req, &ctx->hdl); dprintk(ctx->dev, "Marked request %p as complete\n", vbuf->vb2_buf.req_obj.req); v4l2_m2m_buf_done(vbuf, state); dprintk(ctx->dev, "Marked buffer %llu as done, state is %d\n", vbuf->vb2_buf.timestamp, state); } } static int visl_buf_out_validate(struct vb2_buffer *vb) { struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb); vbuf->field = V4L2_FIELD_NONE; return 0; } static int visl_buf_prepare(struct vb2_buffer *vb) { struct vb2_queue *vq = vb->vb2_queue; struct visl_ctx *ctx = vb2_get_drv_priv(vq); u32 plane_sz = vb2_plane_size(vb, 0); struct v4l2_pix_format *pix_fmt; if (V4L2_TYPE_IS_OUTPUT(vq->type)) { pix_fmt = &ctx->coded_fmt.fmt.pix; } else { pix_fmt = &ctx->decoded_fmt.fmt.pix; vb2_set_plane_payload(vb, 0, pix_fmt->sizeimage); } if (plane_sz < pix_fmt->sizeimage) { v4l2_err(&ctx->dev->v4l2_dev, "plane[0] size is %d, sizeimage is %d\n", plane_sz, pix_fmt->sizeimage); return -EINVAL; } return 0; } static int visl_start_streaming(struct vb2_queue *vq, unsigned int count) { struct visl_ctx *ctx = vb2_get_drv_priv(vq); struct visl_q_data *q_data = get_q_data(ctx, vq->type); int rc = 0; if (!q_data) { rc = -EINVAL; goto err; } q_data->sequence = 0; if (V4L2_TYPE_IS_CAPTURE(vq->type)) { ctx->capture_streamon_jiffies = get_jiffies_64(); return 0; } if (WARN_ON(!ctx->coded_format_desc)) { rc = -EINVAL; goto err; } return 0; err: visl_queue_cleanup(vq, VB2_BUF_STATE_QUEUED); return rc; } static void visl_stop_streaming(struct vb2_queue *vq) { struct visl_ctx *ctx = vb2_get_drv_priv(vq); dprintk(ctx->dev, "Stop streaming\n"); visl_queue_cleanup(vq, VB2_BUF_STATE_ERROR); if (!keep_bitstream_buffers) visl_debugfs_clear_bitstream(ctx->dev); } static void visl_buf_queue(struct vb2_buffer *vb) { struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb); struct visl_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue); v4l2_m2m_buf_queue(ctx->fh.m2m_ctx, vbuf); } static void visl_buf_request_complete(struct vb2_buffer *vb) { struct visl_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue); v4l2_ctrl_request_complete(vb->req_obj.req, &ctx->hdl); } static const struct vb2_ops visl_qops = { .queue_setup = visl_queue_setup, .buf_out_validate = visl_buf_out_validate, .buf_prepare = visl_buf_prepare, .buf_queue = visl_buf_queue, .start_streaming = visl_start_streaming, .stop_streaming = visl_stop_streaming, .wait_prepare = vb2_ops_wait_prepare, .wait_finish = vb2_ops_wait_finish, .buf_request_complete = visl_buf_request_complete, }; int visl_queue_init(void *priv, struct vb2_queue *src_vq, struct vb2_queue *dst_vq) { struct visl_ctx *ctx = priv; int ret; src_vq->type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; src_vq->io_modes = VB2_MMAP | VB2_DMABUF; src_vq->drv_priv = ctx; src_vq->buf_struct_size = sizeof(struct v4l2_m2m_buffer); src_vq->ops = &visl_qops; src_vq->mem_ops = &vb2_vmalloc_memops; src_vq->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_COPY; src_vq->lock = &ctx->vb_mutex; src_vq->supports_requests = true; src_vq->subsystem_flags |= VB2_V4L2_FL_SUPPORTS_M2M_HOLD_CAPTURE_BUF; ret = vb2_queue_init(src_vq); if (ret) return ret; dst_vq->type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; dst_vq->io_modes = VB2_MMAP | VB2_DMABUF; dst_vq->drv_priv = ctx; dst_vq->buf_struct_size = sizeof(struct v4l2_m2m_buffer); dst_vq->ops = &visl_qops; dst_vq->mem_ops = &vb2_vmalloc_memops; dst_vq->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_COPY; dst_vq->lock = &ctx->vb_mutex; return vb2_queue_init(dst_vq); } int visl_request_validate(struct media_request *req) { struct media_request_object *obj; struct visl_ctx *ctx = NULL; unsigned int count; list_for_each_entry(obj, &req->objects, list) { struct vb2_buffer *vb; if (vb2_request_object_is_buffer(obj)) { vb = container_of(obj, struct vb2_buffer, req_obj); ctx = vb2_get_drv_priv(vb->vb2_queue); break; } } if (!ctx) return -ENOENT; count = vb2_request_buffer_cnt(req); if (!count) { v4l2_err(&ctx->dev->v4l2_dev, "No buffer was provided with the request\n"); return -ENOENT; } else if (count > 1) { v4l2_err(&ctx->dev->v4l2_dev, "More than one buffer was provided with the request\n"); return -EINVAL; } return vb2_request_validate(req); }
linux-master
drivers/media/test-drivers/visl/visl-video.c
// SPDX-License-Identifier: GPL-2.0 #include "visl.h" #define CREATE_TRACE_POINTS #include "visl-trace-fwht.h" #include "visl-trace-mpeg2.h" #include "visl-trace-vp8.h" #include "visl-trace-vp9.h" #include "visl-trace-h264.h" #include "visl-trace-hevc.h"
linux-master
drivers/media/test-drivers/visl/visl-trace-points.c
// SPDX-License-Identifier: GPL-2.0 /* * Contains the virtual decoder logic. The functions here control the * tracing/TPG on a per-frame basis */ #include "visl.h" #include "visl-debugfs.h" #include "visl-dec.h" #include "visl-trace-fwht.h" #include "visl-trace-mpeg2.h" #include "visl-trace-vp8.h" #include "visl-trace-vp9.h" #include "visl-trace-h264.h" #include "visl-trace-hevc.h" #include <linux/delay.h> #include <linux/workqueue.h> #include <media/v4l2-mem2mem.h> #include <media/tpg/v4l2-tpg.h> static void *plane_vaddr(struct tpg_data *tpg, struct vb2_buffer *buf, u32 p, u32 bpl[TPG_MAX_PLANES], u32 h) { u32 i; void *vbuf; if (p == 0 || tpg_g_buffers(tpg) > 1) return vb2_plane_vaddr(buf, p); vbuf = vb2_plane_vaddr(buf, 0); for (i = 0; i < p; i++) vbuf += bpl[i] * h / tpg->vdownsampling[i]; return vbuf; } static void visl_get_ref_frames(struct visl_ctx *ctx, u8 *buf, __kernel_size_t buflen, struct visl_run *run) { struct vb2_queue *cap_q = &ctx->fh.m2m_ctx->cap_q_ctx.q; char header[] = "Reference frames:\n"; u32 i; u32 len; len = scnprintf(buf, buflen, header); buf += len; buflen -= len; switch (ctx->current_codec) { case VISL_CODEC_NONE: break; case VISL_CODEC_FWHT: { struct vb2_buffer *vb2_buf; vb2_buf = vb2_find_buffer(cap_q, run->fwht.params->backward_ref_ts); scnprintf(buf, buflen, "backwards_ref_ts: %lld, vb2_idx: %d", run->fwht.params->backward_ref_ts, vb2_buf ? vb2_buf->index : -1); break; } case VISL_CODEC_MPEG2: { struct vb2_buffer *b_ref; struct vb2_buffer *f_ref; b_ref = vb2_find_buffer(cap_q, run->mpeg2.pic->backward_ref_ts); f_ref = vb2_find_buffer(cap_q, run->mpeg2.pic->forward_ref_ts); scnprintf(buf, buflen, "backward_ref_ts: %llu, vb2_idx: %d\n" "forward_ref_ts: %llu, vb2_idx: %d\n", run->mpeg2.pic->backward_ref_ts, b_ref ? b_ref->index : -1, run->mpeg2.pic->forward_ref_ts, f_ref ? f_ref->index : -1); break; } case VISL_CODEC_VP8: { struct vb2_buffer *last; struct vb2_buffer *golden; struct vb2_buffer *alt; last = vb2_find_buffer(cap_q, run->vp8.frame->last_frame_ts); golden = vb2_find_buffer(cap_q, run->vp8.frame->golden_frame_ts); alt = vb2_find_buffer(cap_q, run->vp8.frame->alt_frame_ts); scnprintf(buf, buflen, "last_ref_ts: %llu, vb2_idx: %d\n" "golden_ref_ts: %llu, vb2_idx: %d\n" "alt_ref_ts: %llu, vb2_idx: %d\n", run->vp8.frame->last_frame_ts, last ? last->index : -1, run->vp8.frame->golden_frame_ts, golden ? golden->index : -1, run->vp8.frame->alt_frame_ts, alt ? alt->index : -1); break; } case VISL_CODEC_VP9: { struct vb2_buffer *last; struct vb2_buffer *golden; struct vb2_buffer *alt; last = vb2_find_buffer(cap_q, run->vp9.frame->last_frame_ts); golden = vb2_find_buffer(cap_q, run->vp9.frame->golden_frame_ts); alt = vb2_find_buffer(cap_q, run->vp9.frame->alt_frame_ts); scnprintf(buf, buflen, "last_ref_ts: %llu, vb2_idx: %d\n" "golden_ref_ts: %llu, vb2_idx: %d\n" "alt_ref_ts: %llu, vb2_idx: %d\n", run->vp9.frame->last_frame_ts, last ? last->index : -1, run->vp9.frame->golden_frame_ts, golden ? golden->index : -1, run->vp9.frame->alt_frame_ts, alt ? alt->index : -1); break; } case VISL_CODEC_H264: { char entry[] = "dpb[%d]:%u, vb2_index: %d\n"; struct vb2_buffer *vb2_buf; for (i = 0; i < ARRAY_SIZE(run->h264.dpram->dpb); i++) { vb2_buf = vb2_find_buffer(cap_q, run->h264.dpram->dpb[i].reference_ts); len = scnprintf(buf, buflen, entry, i, run->h264.dpram->dpb[i].reference_ts, vb2_buf ? vb2_buf->index : -1); buf += len; buflen -= len; } break; } case VISL_CODEC_HEVC: { char entry[] = "dpb[%d]:%u, vb2_index: %d\n"; struct vb2_buffer *vb2_buf; for (i = 0; i < ARRAY_SIZE(run->hevc.dpram->dpb); i++) { vb2_buf = vb2_find_buffer(cap_q, run->hevc.dpram->dpb[i].timestamp); len = scnprintf(buf, buflen, entry, i, run->hevc.dpram->dpb[i].timestamp, vb2_buf ? vb2_buf->index : -1); buf += len; buflen -= len; } break; } } } static char *visl_get_vb2_state(enum vb2_buffer_state state) { switch (state) { case VB2_BUF_STATE_DEQUEUED: return "Dequeued"; case VB2_BUF_STATE_IN_REQUEST: return "In request"; case VB2_BUF_STATE_PREPARING: return "Preparing"; case VB2_BUF_STATE_QUEUED: return "Queued"; case VB2_BUF_STATE_ACTIVE: return "Active"; case VB2_BUF_STATE_DONE: return "Done"; case VB2_BUF_STATE_ERROR: return "Error"; default: return ""; } } static int visl_fill_bytesused(struct vb2_v4l2_buffer *v4l2_vb2_buf, char *buf, size_t bufsz) { int len = 0; u32 i; for (i = 0; i < v4l2_vb2_buf->vb2_buf.num_planes; i++) len += scnprintf(buf, bufsz, "bytesused[%u]: %u length[%u]: %u data_offset[%u]: %u", i, v4l2_vb2_buf->planes[i].bytesused, i, v4l2_vb2_buf->planes[i].length, i, v4l2_vb2_buf->planes[i].data_offset); return len; } static void visl_tpg_fill_sequence(struct visl_ctx *ctx, struct visl_run *run, char buf[], size_t bufsz) { u32 stream_ms; stream_ms = jiffies_to_msecs(get_jiffies_64() - ctx->capture_streamon_jiffies); scnprintf(buf, bufsz, "stream time: %02d:%02d:%02d:%03d sequence:%u timestamp:%lld field:%s", (stream_ms / (60 * 60 * 1000)) % 24, (stream_ms / (60 * 1000)) % 60, (stream_ms / 1000) % 60, stream_ms % 1000, run->dst->sequence, run->dst->vb2_buf.timestamp, (run->dst->field == V4L2_FIELD_ALTERNATE) ? (run->dst->field == V4L2_FIELD_TOP ? " top" : " bottom") : "none"); } static void visl_tpg_fill(struct visl_ctx *ctx, struct visl_run *run) { u8 *basep[TPG_MAX_PLANES][2]; char *buf = ctx->tpg_str_buf; char *tmp = buf; char *line_str; u32 line = 1; const u32 line_height = 16; u32 len; struct vb2_queue *out_q = &ctx->fh.m2m_ctx->out_q_ctx.q; struct vb2_queue *cap_q = &ctx->fh.m2m_ctx->cap_q_ctx.q; struct v4l2_pix_format_mplane *coded_fmt = &ctx->coded_fmt.fmt.pix_mp; struct v4l2_pix_format_mplane *decoded_fmt = &ctx->decoded_fmt.fmt.pix_mp; u32 p; u32 i; for (p = 0; p < tpg_g_planes(&ctx->tpg); p++) { void *vbuf = plane_vaddr(&ctx->tpg, &run->dst->vb2_buf, p, ctx->tpg.bytesperline, ctx->tpg.buf_height); tpg_calc_text_basep(&ctx->tpg, basep, p, vbuf); tpg_fill_plane_buffer(&ctx->tpg, 0, p, vbuf); } visl_tpg_fill_sequence(ctx, run, buf, TPG_STR_BUF_SZ); tpg_gen_text(&ctx->tpg, basep, line++ * line_height, 16, buf); frame_dprintk(ctx->dev, run->dst->sequence, "%s\n", buf); frame_dprintk(ctx->dev, run->dst->sequence, ""); line++; visl_get_ref_frames(ctx, buf, TPG_STR_BUF_SZ, run); while ((line_str = strsep(&tmp, "\n")) && strlen(line_str)) { tpg_gen_text(&ctx->tpg, basep, line++ * line_height, 16, line_str); frame_dprintk(ctx->dev, run->dst->sequence, "%s\n", line_str); } frame_dprintk(ctx->dev, run->dst->sequence, ""); line++; scnprintf(buf, TPG_STR_BUF_SZ, "OUTPUT pixelformat: %c%c%c%c, resolution: %dx%d, num_planes: %d", coded_fmt->pixelformat, (coded_fmt->pixelformat >> 8) & 0xff, (coded_fmt->pixelformat >> 16) & 0xff, (coded_fmt->pixelformat >> 24) & 0xff, coded_fmt->width, coded_fmt->height, coded_fmt->num_planes); tpg_gen_text(&ctx->tpg, basep, line++ * line_height, 16, buf); frame_dprintk(ctx->dev, run->dst->sequence, "%s\n", buf); for (i = 0; i < coded_fmt->num_planes; i++) { scnprintf(buf, TPG_STR_BUF_SZ, "plane[%d]: bytesperline: %d, sizeimage: %d", i, coded_fmt->plane_fmt[i].bytesperline, coded_fmt->plane_fmt[i].sizeimage); tpg_gen_text(&ctx->tpg, basep, line++ * line_height, 16, buf); frame_dprintk(ctx->dev, run->dst->sequence, "%s\n", buf); } line++; frame_dprintk(ctx->dev, run->dst->sequence, ""); scnprintf(buf, TPG_STR_BUF_SZ, "Output queue status:"); tpg_gen_text(&ctx->tpg, basep, line++ * line_height, 16, buf); frame_dprintk(ctx->dev, run->dst->sequence, "%s\n", buf); len = 0; for (i = 0; i < out_q->num_buffers; i++) { char entry[] = "index: %u, state: %s, request_fd: %d, "; u32 old_len = len; char *q_status = visl_get_vb2_state(out_q->bufs[i]->state); len += scnprintf(&buf[len], TPG_STR_BUF_SZ - len, entry, i, q_status, to_vb2_v4l2_buffer(out_q->bufs[i])->request_fd); len += visl_fill_bytesused(to_vb2_v4l2_buffer(out_q->bufs[i]), &buf[len], TPG_STR_BUF_SZ - len); tpg_gen_text(&ctx->tpg, basep, line++ * line_height, 16, &buf[old_len]); frame_dprintk(ctx->dev, run->dst->sequence, "%s", &buf[old_len]); } line++; frame_dprintk(ctx->dev, run->dst->sequence, ""); scnprintf(buf, TPG_STR_BUF_SZ, "CAPTURE pixelformat: %c%c%c%c, resolution: %dx%d, num_planes: %d", decoded_fmt->pixelformat, (decoded_fmt->pixelformat >> 8) & 0xff, (decoded_fmt->pixelformat >> 16) & 0xff, (decoded_fmt->pixelformat >> 24) & 0xff, decoded_fmt->width, decoded_fmt->height, decoded_fmt->num_planes); tpg_gen_text(&ctx->tpg, basep, line++ * line_height, 16, buf); frame_dprintk(ctx->dev, run->dst->sequence, "%s\n", buf); for (i = 0; i < decoded_fmt->num_planes; i++) { scnprintf(buf, TPG_STR_BUF_SZ, "plane[%d]: bytesperline: %d, sizeimage: %d", i, decoded_fmt->plane_fmt[i].bytesperline, decoded_fmt->plane_fmt[i].sizeimage); tpg_gen_text(&ctx->tpg, basep, line++ * line_height, 16, buf); frame_dprintk(ctx->dev, run->dst->sequence, "%s\n", buf); } line++; frame_dprintk(ctx->dev, run->dst->sequence, ""); scnprintf(buf, TPG_STR_BUF_SZ, "Capture queue status:"); tpg_gen_text(&ctx->tpg, basep, line++ * line_height, 16, buf); frame_dprintk(ctx->dev, run->dst->sequence, "%s\n", buf); len = 0; for (i = 0; i < cap_q->num_buffers; i++) { u32 old_len = len; char *q_status = visl_get_vb2_state(cap_q->bufs[i]->state); len += scnprintf(&buf[len], TPG_STR_BUF_SZ - len, "index: %u, status: %s, timestamp: %llu, is_held: %d", cap_q->bufs[i]->index, q_status, cap_q->bufs[i]->timestamp, to_vb2_v4l2_buffer(cap_q->bufs[i])->is_held); tpg_gen_text(&ctx->tpg, basep, line++ * line_height, 16, &buf[old_len]); frame_dprintk(ctx->dev, run->dst->sequence, "%s", &buf[old_len]); } } static void visl_trace_ctrls(struct visl_ctx *ctx, struct visl_run *run) { int i; switch (ctx->current_codec) { default: case VISL_CODEC_NONE: break; case VISL_CODEC_FWHT: trace_v4l2_ctrl_fwht_params(run->fwht.params); break; case VISL_CODEC_MPEG2: trace_v4l2_ctrl_mpeg2_sequence(run->mpeg2.seq); trace_v4l2_ctrl_mpeg2_picture(run->mpeg2.pic); trace_v4l2_ctrl_mpeg2_quantisation(run->mpeg2.quant); break; case VISL_CODEC_VP8: trace_v4l2_ctrl_vp8_frame(run->vp8.frame); trace_v4l2_ctrl_vp8_entropy(run->vp8.frame); break; case VISL_CODEC_VP9: trace_v4l2_ctrl_vp9_frame(run->vp9.frame); trace_v4l2_ctrl_vp9_compressed_hdr(run->vp9.probs); trace_v4l2_ctrl_vp9_compressed_coeff(run->vp9.probs); trace_v4l2_vp9_mv_probs(&run->vp9.probs->mv); break; case VISL_CODEC_H264: trace_v4l2_ctrl_h264_sps(run->h264.sps); trace_v4l2_ctrl_h264_pps(run->h264.pps); trace_v4l2_ctrl_h264_scaling_matrix(run->h264.sm); trace_v4l2_ctrl_h264_slice_params(run->h264.spram); for (i = 0; i < ARRAY_SIZE(run->h264.spram->ref_pic_list0); i++) trace_v4l2_h264_ref_pic_list0(&run->h264.spram->ref_pic_list0[i], i); for (i = 0; i < ARRAY_SIZE(run->h264.spram->ref_pic_list0); i++) trace_v4l2_h264_ref_pic_list1(&run->h264.spram->ref_pic_list1[i], i); trace_v4l2_ctrl_h264_decode_params(run->h264.dpram); for (i = 0; i < ARRAY_SIZE(run->h264.dpram->dpb); i++) trace_v4l2_h264_dpb_entry(&run->h264.dpram->dpb[i], i); trace_v4l2_ctrl_h264_pred_weights(run->h264.pwht); break; case VISL_CODEC_HEVC: trace_v4l2_ctrl_hevc_sps(run->hevc.sps); trace_v4l2_ctrl_hevc_pps(run->hevc.pps); trace_v4l2_ctrl_hevc_slice_params(run->hevc.spram); trace_v4l2_ctrl_hevc_scaling_matrix(run->hevc.sm); trace_v4l2_ctrl_hevc_decode_params(run->hevc.dpram); for (i = 0; i < ARRAY_SIZE(run->hevc.dpram->dpb); i++) trace_v4l2_hevc_dpb_entry(&run->hevc.dpram->dpb[i]); trace_v4l2_hevc_pred_weight_table(&run->hevc.spram->pred_weight_table); break; } } void visl_device_run(void *priv) { struct visl_ctx *ctx = priv; struct visl_run run = {}; struct media_request *src_req; run.src = v4l2_m2m_next_src_buf(ctx->fh.m2m_ctx); run.dst = v4l2_m2m_next_dst_buf(ctx->fh.m2m_ctx); /* Apply request(s) controls if needed. */ src_req = run.src->vb2_buf.req_obj.req; if (src_req) v4l2_ctrl_request_setup(src_req, &ctx->hdl); v4l2_m2m_buf_copy_metadata(run.src, run.dst, true); run.dst->sequence = ctx->q_data[V4L2_M2M_DST].sequence++; run.src->sequence = ctx->q_data[V4L2_M2M_SRC].sequence++; run.dst->field = ctx->decoded_fmt.fmt.pix.field; switch (ctx->current_codec) { default: case VISL_CODEC_NONE: break; case VISL_CODEC_FWHT: run.fwht.params = visl_find_control_data(ctx, V4L2_CID_STATELESS_FWHT_PARAMS); break; case VISL_CODEC_MPEG2: run.mpeg2.seq = visl_find_control_data(ctx, V4L2_CID_STATELESS_MPEG2_SEQUENCE); run.mpeg2.pic = visl_find_control_data(ctx, V4L2_CID_STATELESS_MPEG2_PICTURE); run.mpeg2.quant = visl_find_control_data(ctx, V4L2_CID_STATELESS_MPEG2_QUANTISATION); break; case VISL_CODEC_VP8: run.vp8.frame = visl_find_control_data(ctx, V4L2_CID_STATELESS_VP8_FRAME); break; case VISL_CODEC_VP9: run.vp9.frame = visl_find_control_data(ctx, V4L2_CID_STATELESS_VP9_FRAME); run.vp9.probs = visl_find_control_data(ctx, V4L2_CID_STATELESS_VP9_COMPRESSED_HDR); break; case VISL_CODEC_H264: run.h264.sps = visl_find_control_data(ctx, V4L2_CID_STATELESS_H264_SPS); run.h264.pps = visl_find_control_data(ctx, V4L2_CID_STATELESS_H264_PPS); run.h264.sm = visl_find_control_data(ctx, V4L2_CID_STATELESS_H264_SCALING_MATRIX); run.h264.spram = visl_find_control_data(ctx, V4L2_CID_STATELESS_H264_SLICE_PARAMS); run.h264.dpram = visl_find_control_data(ctx, V4L2_CID_STATELESS_H264_DECODE_PARAMS); run.h264.pwht = visl_find_control_data(ctx, V4L2_CID_STATELESS_H264_PRED_WEIGHTS); break; case VISL_CODEC_HEVC: run.hevc.sps = visl_find_control_data(ctx, V4L2_CID_STATELESS_HEVC_SPS); run.hevc.pps = visl_find_control_data(ctx, V4L2_CID_STATELESS_HEVC_PPS); run.hevc.spram = visl_find_control_data(ctx, V4L2_CID_STATELESS_HEVC_SLICE_PARAMS); run.hevc.sm = visl_find_control_data(ctx, V4L2_CID_STATELESS_HEVC_SCALING_MATRIX); run.hevc.dpram = visl_find_control_data(ctx, V4L2_CID_STATELESS_HEVC_DECODE_PARAMS); break; } frame_dprintk(ctx->dev, run.dst->sequence, "Got OUTPUT buffer sequence %d, timestamp %llu\n", run.src->sequence, run.src->vb2_buf.timestamp); frame_dprintk(ctx->dev, run.dst->sequence, "Got CAPTURE buffer sequence %d, timestamp %llu\n", run.dst->sequence, run.dst->vb2_buf.timestamp); visl_tpg_fill(ctx, &run); visl_trace_ctrls(ctx, &run); if (bitstream_trace_frame_start > -1 && run.dst->sequence >= bitstream_trace_frame_start && run.dst->sequence < bitstream_trace_frame_start + bitstream_trace_nframes) visl_trace_bitstream(ctx, &run); /* Complete request(s) controls if needed. */ if (src_req) v4l2_ctrl_request_complete(src_req, &ctx->hdl); if (visl_transtime_ms) usleep_range(visl_transtime_ms * 1000, 2 * visl_transtime_ms * 1000); v4l2_m2m_buf_done_and_job_finish(ctx->dev->m2m_dev, ctx->fh.m2m_ctx, VB2_BUF_STATE_DONE); }
linux-master
drivers/media/test-drivers/visl/visl-dec.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Driver for Microtune MT2060 "Single chip dual conversion broadband tuner" * * Copyright (c) 2006 Olivier DANET <[email protected]> */ /* In that file, frequencies are expressed in kiloHertz to avoid 32 bits overflows */ #include <linux/module.h> #include <linux/delay.h> #include <linux/dvb/frontend.h> #include <linux/i2c.h> #include <linux/slab.h> #include <media/dvb_frontend.h> #include "mt2060.h" #include "mt2060_priv.h" static int debug; module_param(debug, int, 0644); MODULE_PARM_DESC(debug, "Turn on/off debugging (default:off)."); #define dprintk(args...) do { if (debug) {printk(KERN_DEBUG "MT2060: " args); printk("\n"); }} while (0) // Reads a single register static int mt2060_readreg(struct mt2060_priv *priv, u8 reg, u8 *val) { struct i2c_msg msg[2] = { { .addr = priv->cfg->i2c_address, .flags = 0, .len = 1 }, { .addr = priv->cfg->i2c_address, .flags = I2C_M_RD, .len = 1 }, }; int rc = 0; u8 *b; b = kmalloc(2, GFP_KERNEL); if (!b) return -ENOMEM; b[0] = reg; b[1] = 0; msg[0].buf = b; msg[1].buf = b + 1; if (i2c_transfer(priv->i2c, msg, 2) != 2) { printk(KERN_WARNING "mt2060 I2C read failed\n"); rc = -EREMOTEIO; } *val = b[1]; kfree(b); return rc; } // Writes a single register static int mt2060_writereg(struct mt2060_priv *priv, u8 reg, u8 val) { struct i2c_msg msg = { .addr = priv->cfg->i2c_address, .flags = 0, .len = 2 }; u8 *buf; int rc = 0; buf = kmalloc(2, GFP_KERNEL); if (!buf) return -ENOMEM; buf[0] = reg; buf[1] = val; msg.buf = buf; if (i2c_transfer(priv->i2c, &msg, 1) != 1) { printk(KERN_WARNING "mt2060 I2C write failed\n"); rc = -EREMOTEIO; } kfree(buf); return rc; } // Writes a set of consecutive registers static int mt2060_writeregs(struct mt2060_priv *priv,u8 *buf, u8 len) { int rem, val_len; u8 *xfer_buf; int rc = 0; struct i2c_msg msg = { .addr = priv->cfg->i2c_address, .flags = 0 }; xfer_buf = kmalloc(16, GFP_KERNEL); if (!xfer_buf) return -ENOMEM; msg.buf = xfer_buf; for (rem = len - 1; rem > 0; rem -= priv->i2c_max_regs) { val_len = min_t(int, rem, priv->i2c_max_regs); msg.len = 1 + val_len; xfer_buf[0] = buf[0] + len - 1 - rem; memcpy(&xfer_buf[1], &buf[1 + len - 1 - rem], val_len); if (i2c_transfer(priv->i2c, &msg, 1) != 1) { printk(KERN_WARNING "mt2060 I2C write failed (len=%i)\n", val_len); rc = -EREMOTEIO; break; } } kfree(xfer_buf); return rc; } // Initialisation sequences // LNABAND=3, NUM1=0x3C, DIV1=0x74, NUM2=0x1080, DIV2=0x49 static u8 mt2060_config1[] = { REG_LO1C1, 0x3F, 0x74, 0x00, 0x08, 0x93 }; // FMCG=2, GP2=0, GP1=0 static u8 mt2060_config2[] = { REG_MISC_CTRL, 0x20, 0x1E, 0x30, 0xff, 0x80, 0xff, 0x00, 0x2c, 0x42 }; // VGAG=3, V1CSE=1 #ifdef MT2060_SPURCHECK /* The function below calculates the frequency offset between the output frequency if2 and the closer cross modulation subcarrier between lo1 and lo2 up to the tenth harmonic */ static int mt2060_spurcalc(u32 lo1,u32 lo2,u32 if2) { int I,J; int dia,diamin,diff; diamin=1000000; for (I = 1; I < 10; I++) { J = ((2*I*lo1)/lo2+1)/2; diff = I*(int)lo1-J*(int)lo2; if (diff < 0) diff=-diff; dia = (diff-(int)if2); if (dia < 0) dia=-dia; if (diamin > dia) diamin=dia; } return diamin; } #define BANDWIDTH 4000 // kHz /* Calculates the frequency offset to add to avoid spurs. Returns 0 if no offset is needed */ static int mt2060_spurcheck(u32 lo1,u32 lo2,u32 if2) { u32 Spur,Sp1,Sp2; int I,J; I=0; J=1000; Spur=mt2060_spurcalc(lo1,lo2,if2); if (Spur < BANDWIDTH) { /* Potential spurs detected */ dprintk("Spurs before : f_lo1: %d f_lo2: %d (kHz)", (int)lo1,(int)lo2); I=1000; Sp1 = mt2060_spurcalc(lo1+I,lo2+I,if2); Sp2 = mt2060_spurcalc(lo1-I,lo2-I,if2); if (Sp1 < Sp2) { J=-J; I=-I; Spur=Sp2; } else Spur=Sp1; while (Spur < BANDWIDTH) { I += J; Spur = mt2060_spurcalc(lo1+I,lo2+I,if2); } dprintk("Spurs after : f_lo1: %d f_lo2: %d (kHz)", (int)(lo1+I),(int)(lo2+I)); } return I; } #endif #define IF2 36150 // IF2 frequency = 36.150 MHz #define FREF 16000 // Quartz oscillator 16 MHz static int mt2060_set_params(struct dvb_frontend *fe) { struct dtv_frontend_properties *c = &fe->dtv_property_cache; struct mt2060_priv *priv; int i=0; u32 freq; u8 lnaband; u32 f_lo1,f_lo2; u32 div1,num1,div2,num2; u8 b[8]; u32 if1; priv = fe->tuner_priv; if1 = priv->if1_freq; b[0] = REG_LO1B1; b[1] = 0xFF; if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 1); /* open i2c_gate */ mt2060_writeregs(priv,b,2); freq = c->frequency / 1000; /* Hz -> kHz */ f_lo1 = freq + if1 * 1000; f_lo1 = (f_lo1 / 250) * 250; f_lo2 = f_lo1 - freq - IF2; // From the Comtech datasheet, the step used is 50kHz. The tuner chip could be more precise f_lo2 = ((f_lo2 + 25) / 50) * 50; priv->frequency = (f_lo1 - f_lo2 - IF2) * 1000; #ifdef MT2060_SPURCHECK // LO-related spurs detection and correction num1 = mt2060_spurcheck(f_lo1,f_lo2,IF2); f_lo1 += num1; f_lo2 += num1; #endif //Frequency LO1 = 16MHz * (DIV1 + NUM1/64 ) num1 = f_lo1 / (FREF / 64); div1 = num1 / 64; num1 &= 0x3f; // Frequency LO2 = 16MHz * (DIV2 + NUM2/8192 ) num2 = f_lo2 * 64 / (FREF / 128); div2 = num2 / 8192; num2 &= 0x1fff; if (freq <= 95000) lnaband = 0xB0; else if (freq <= 180000) lnaband = 0xA0; else if (freq <= 260000) lnaband = 0x90; else if (freq <= 335000) lnaband = 0x80; else if (freq <= 425000) lnaband = 0x70; else if (freq <= 480000) lnaband = 0x60; else if (freq <= 570000) lnaband = 0x50; else if (freq <= 645000) lnaband = 0x40; else if (freq <= 730000) lnaband = 0x30; else if (freq <= 810000) lnaband = 0x20; else lnaband = 0x10; b[0] = REG_LO1C1; b[1] = lnaband | ((num1 >>2) & 0x0F); b[2] = div1; b[3] = (num2 & 0x0F) | ((num1 & 3) << 4); b[4] = num2 >> 4; b[5] = ((num2 >>12) & 1) | (div2 << 1); dprintk("IF1: %dMHz",(int)if1); dprintk("PLL freq=%dkHz f_lo1=%dkHz f_lo2=%dkHz",(int)freq,(int)f_lo1,(int)f_lo2); dprintk("PLL div1=%d num1=%d div2=%d num2=%d",(int)div1,(int)num1,(int)div2,(int)num2); dprintk("PLL [1..5]: %2x %2x %2x %2x %2x",(int)b[1],(int)b[2],(int)b[3],(int)b[4],(int)b[5]); mt2060_writeregs(priv,b,6); //Waits for pll lock or timeout i = 0; do { mt2060_readreg(priv,REG_LO_STATUS,b); if ((b[0] & 0x88)==0x88) break; msleep(4); i++; } while (i<10); if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 0); /* close i2c_gate */ return 0; } static void mt2060_calibrate(struct mt2060_priv *priv) { u8 b = 0; int i = 0; if (mt2060_writeregs(priv,mt2060_config1,sizeof(mt2060_config1))) return; if (mt2060_writeregs(priv,mt2060_config2,sizeof(mt2060_config2))) return; /* initialize the clock output */ mt2060_writereg(priv, REG_VGAG, (priv->cfg->clock_out << 6) | 0x30); do { b |= (1 << 6); // FM1SS; mt2060_writereg(priv, REG_LO2C1,b); msleep(20); if (i == 0) { b |= (1 << 7); // FM1CA; mt2060_writereg(priv, REG_LO2C1,b); b &= ~(1 << 7); // FM1CA; msleep(20); } b &= ~(1 << 6); // FM1SS mt2060_writereg(priv, REG_LO2C1,b); msleep(20); i++; } while (i < 9); i = 0; while (i++ < 10 && mt2060_readreg(priv, REG_MISC_STAT, &b) == 0 && (b & (1 << 6)) == 0) msleep(20); if (i <= 10) { mt2060_readreg(priv, REG_FM_FREQ, &priv->fmfreq); // now find out, what is fmreq used for :) dprintk("calibration was successful: %d", (int)priv->fmfreq); } else dprintk("FMCAL timed out"); } static int mt2060_get_frequency(struct dvb_frontend *fe, u32 *frequency) { struct mt2060_priv *priv = fe->tuner_priv; *frequency = priv->frequency; return 0; } static int mt2060_get_if_frequency(struct dvb_frontend *fe, u32 *frequency) { *frequency = IF2 * 1000; return 0; } static int mt2060_init(struct dvb_frontend *fe) { struct mt2060_priv *priv = fe->tuner_priv; int ret; if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 1); /* open i2c_gate */ if (priv->sleep) { ret = mt2060_writereg(priv, REG_MISC_CTRL, 0x20); if (ret) goto err_i2c_gate_ctrl; } ret = mt2060_writereg(priv, REG_VGAG, (priv->cfg->clock_out << 6) | 0x33); err_i2c_gate_ctrl: if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 0); /* close i2c_gate */ return ret; } static int mt2060_sleep(struct dvb_frontend *fe) { struct mt2060_priv *priv = fe->tuner_priv; int ret; if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 1); /* open i2c_gate */ ret = mt2060_writereg(priv, REG_VGAG, (priv->cfg->clock_out << 6) | 0x30); if (ret) goto err_i2c_gate_ctrl; if (priv->sleep) ret = mt2060_writereg(priv, REG_MISC_CTRL, 0xe8); err_i2c_gate_ctrl: if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 0); /* close i2c_gate */ return ret; } static void mt2060_release(struct dvb_frontend *fe) { kfree(fe->tuner_priv); fe->tuner_priv = NULL; } static const struct dvb_tuner_ops mt2060_tuner_ops = { .info = { .name = "Microtune MT2060", .frequency_min_hz = 48 * MHz, .frequency_max_hz = 860 * MHz, .frequency_step_hz = 50 * kHz, }, .release = mt2060_release, .init = mt2060_init, .sleep = mt2060_sleep, .set_params = mt2060_set_params, .get_frequency = mt2060_get_frequency, .get_if_frequency = mt2060_get_if_frequency, }; /* This functions tries to identify a MT2060 tuner by reading the PART/REV register. This is hasty. */ struct dvb_frontend * mt2060_attach(struct dvb_frontend *fe, struct i2c_adapter *i2c, struct mt2060_config *cfg, u16 if1) { struct mt2060_priv *priv = NULL; u8 id = 0; priv = kzalloc(sizeof(struct mt2060_priv), GFP_KERNEL); if (priv == NULL) return NULL; priv->cfg = cfg; priv->i2c = i2c; priv->if1_freq = if1; priv->i2c_max_regs = ~0; if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 1); /* open i2c_gate */ if (mt2060_readreg(priv,REG_PART_REV,&id) != 0) { kfree(priv); return NULL; } if (id != PART_REV) { kfree(priv); return NULL; } printk(KERN_INFO "MT2060: successfully identified (IF1 = %d)\n", if1); memcpy(&fe->ops.tuner_ops, &mt2060_tuner_ops, sizeof(struct dvb_tuner_ops)); fe->tuner_priv = priv; mt2060_calibrate(priv); if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 0); /* close i2c_gate */ return fe; } EXPORT_SYMBOL_GPL(mt2060_attach); static int mt2060_probe(struct i2c_client *client) { struct mt2060_platform_data *pdata = client->dev.platform_data; struct dvb_frontend *fe; struct mt2060_priv *dev; int ret; u8 chip_id; dev_dbg(&client->dev, "\n"); if (!pdata) { dev_err(&client->dev, "Cannot proceed without platform data\n"); ret = -EINVAL; goto err; } dev = devm_kzalloc(&client->dev, sizeof(*dev), GFP_KERNEL); if (!dev) { ret = -ENOMEM; goto err; } fe = pdata->dvb_frontend; dev->config.i2c_address = client->addr; dev->config.clock_out = pdata->clock_out; dev->cfg = &dev->config; dev->i2c = client->adapter; dev->if1_freq = pdata->if1 ? pdata->if1 : 1220; dev->client = client; dev->i2c_max_regs = pdata->i2c_write_max ? pdata->i2c_write_max - 1 : ~0; dev->sleep = true; ret = mt2060_readreg(dev, REG_PART_REV, &chip_id); if (ret) { ret = -ENODEV; goto err; } dev_dbg(&client->dev, "chip id=%02x\n", chip_id); if (chip_id != PART_REV) { ret = -ENODEV; goto err; } /* Power on, calibrate, sleep */ ret = mt2060_writereg(dev, REG_MISC_CTRL, 0x20); if (ret) goto err; mt2060_calibrate(dev); ret = mt2060_writereg(dev, REG_MISC_CTRL, 0xe8); if (ret) goto err; dev_info(&client->dev, "Microtune MT2060 successfully identified\n"); memcpy(&fe->ops.tuner_ops, &mt2060_tuner_ops, sizeof(fe->ops.tuner_ops)); fe->ops.tuner_ops.release = NULL; fe->tuner_priv = dev; i2c_set_clientdata(client, dev); return 0; err: dev_dbg(&client->dev, "failed=%d\n", ret); return ret; } static void mt2060_remove(struct i2c_client *client) { dev_dbg(&client->dev, "\n"); } static const struct i2c_device_id mt2060_id_table[] = { {"mt2060", 0}, {} }; MODULE_DEVICE_TABLE(i2c, mt2060_id_table); static struct i2c_driver mt2060_driver = { .driver = { .name = "mt2060", .suppress_bind_attrs = true, }, .probe = mt2060_probe, .remove = mt2060_remove, .id_table = mt2060_id_table, }; module_i2c_driver(mt2060_driver); MODULE_AUTHOR("Olivier DANET"); MODULE_DESCRIPTION("Microtune MT2060 silicon tuner driver"); MODULE_LICENSE("GPL");
linux-master
drivers/media/tuners/mt2060.c
// SPDX-License-Identifier: GPL-2.0-only /* * i2c tv tuner chip device driver * controls microtune tuners, mt2032 + mt2050 at the moment. * * This "mt20xx" module was split apart from the original "tuner" module. */ #include <linux/delay.h> #include <linux/i2c.h> #include <linux/slab.h> #include <linux/videodev2.h> #include "tuner-i2c.h" #include "mt20xx.h" static int debug; module_param(debug, int, 0644); MODULE_PARM_DESC(debug, "enable verbose debug messages"); /* ---------------------------------------------------------------------- */ static unsigned int optimize_vco = 1; module_param(optimize_vco, int, 0644); static unsigned int tv_antenna = 1; module_param(tv_antenna, int, 0644); static unsigned int radio_antenna; module_param(radio_antenna, int, 0644); /* ---------------------------------------------------------------------- */ #define MT2032 0x04 #define MT2030 0x06 #define MT2040 0x07 #define MT2050 0x42 static char *microtune_part[] = { [ MT2030 ] = "MT2030", [ MT2032 ] = "MT2032", [ MT2040 ] = "MT2040", [ MT2050 ] = "MT2050", }; struct microtune_priv { struct tuner_i2c_props i2c_props; unsigned int xogc; //unsigned int radio_if2; u32 frequency; }; static void microtune_release(struct dvb_frontend *fe) { kfree(fe->tuner_priv); fe->tuner_priv = NULL; } static int microtune_get_frequency(struct dvb_frontend *fe, u32 *frequency) { struct microtune_priv *priv = fe->tuner_priv; *frequency = priv->frequency; return 0; } // IsSpurInBand()? static int mt2032_spurcheck(struct dvb_frontend *fe, int f1, int f2, int spectrum_from,int spectrum_to) { struct microtune_priv *priv = fe->tuner_priv; int n1=1,n2,f; f1=f1/1000; //scale to kHz to avoid 32bit overflows f2=f2/1000; spectrum_from/=1000; spectrum_to/=1000; tuner_dbg("spurcheck f1=%d f2=%d from=%d to=%d\n", f1,f2,spectrum_from,spectrum_to); do { n2=-n1; f=n1*(f1-f2); do { n2--; f=f-f2; tuner_dbg("spurtest n1=%d n2=%d ftest=%d\n",n1,n2,f); if( (f>spectrum_from) && (f<spectrum_to)) tuner_dbg("mt2032 spurcheck triggered: %d\n",n1); } while ( (f>(f2-spectrum_to)) || (n2>-5)); n1++; } while (n1<5); return 1; } static int mt2032_compute_freq(struct dvb_frontend *fe, unsigned int rfin, unsigned int if1, unsigned int if2, unsigned int spectrum_from, unsigned int spectrum_to, unsigned char *buf, int *ret_sel, unsigned int xogc) //all in Hz { struct microtune_priv *priv = fe->tuner_priv; unsigned int fref,lo1,lo1n,lo1a,s,sel,lo1freq, desired_lo1, desired_lo2,lo2,lo2n,lo2a,lo2num,lo2freq; fref= 5250 *1000; //5.25MHz desired_lo1=rfin+if1; lo1=(2*(desired_lo1/1000)+(fref/1000)) / (2*fref/1000); lo1n=lo1/8; lo1a=lo1-(lo1n*8); s=rfin/1000/1000+1090; if(optimize_vco) { if(s>1890) sel=0; else if(s>1720) sel=1; else if(s>1530) sel=2; else if(s>1370) sel=3; else sel=4; // >1090 } else { if(s>1790) sel=0; // <1958 else if(s>1617) sel=1; else if(s>1449) sel=2; else if(s>1291) sel=3; else sel=4; // >1090 } *ret_sel=sel; lo1freq=(lo1a+8*lo1n)*fref; tuner_dbg("mt2032: rfin=%d lo1=%d lo1n=%d lo1a=%d sel=%d, lo1freq=%d\n", rfin,lo1,lo1n,lo1a,sel,lo1freq); desired_lo2=lo1freq-rfin-if2; lo2=(desired_lo2)/fref; lo2n=lo2/8; lo2a=lo2-(lo2n*8); lo2num=((desired_lo2/1000)%(fref/1000))* 3780/(fref/1000); //scale to fit in 32bit arith lo2freq=(lo2a+8*lo2n)*fref + lo2num*(fref/1000)/3780*1000; tuner_dbg("mt2032: rfin=%d lo2=%d lo2n=%d lo2a=%d num=%d lo2freq=%d\n", rfin,lo2,lo2n,lo2a,lo2num,lo2freq); if (lo1a > 7 || lo1n < 17 || lo1n > 48 || lo2a > 7 || lo2n < 17 || lo2n > 30) { tuner_info("mt2032: frequency parameters out of range: %d %d %d %d\n", lo1a, lo1n, lo2a,lo2n); return(-1); } mt2032_spurcheck(fe, lo1freq, desired_lo2, spectrum_from, spectrum_to); // should recalculate lo1 (one step up/down) // set up MT2032 register map for transfer over i2c buf[0]=lo1n-1; buf[1]=lo1a | (sel<<4); buf[2]=0x86; // LOGC buf[3]=0x0f; //reserved buf[4]=0x1f; buf[5]=(lo2n-1) | (lo2a<<5); if(rfin >400*1000*1000) buf[6]=0xe4; else buf[6]=0xf4; // set PKEN per rev 1.2 buf[7]=8+xogc; buf[8]=0xc3; //reserved buf[9]=0x4e; //reserved buf[10]=0xec; //reserved buf[11]=(lo2num&0xff); buf[12]=(lo2num>>8) |0x80; // Lo2RST return 0; } static int mt2032_check_lo_lock(struct dvb_frontend *fe) { struct microtune_priv *priv = fe->tuner_priv; int try,lock=0; unsigned char buf[2]; for(try=0;try<10;try++) { buf[0]=0x0e; tuner_i2c_xfer_send(&priv->i2c_props,buf,1); tuner_i2c_xfer_recv(&priv->i2c_props,buf,1); tuner_dbg("mt2032 Reg.E=0x%02x\n",buf[0]); lock=buf[0] &0x06; if (lock==6) break; tuner_dbg("mt2032: pll wait 1ms for lock (0x%2x)\n",buf[0]); udelay(1000); } return lock; } static int mt2032_optimize_vco(struct dvb_frontend *fe,int sel,int lock) { struct microtune_priv *priv = fe->tuner_priv; unsigned char buf[2]; int tad1; buf[0]=0x0f; tuner_i2c_xfer_send(&priv->i2c_props,buf,1); tuner_i2c_xfer_recv(&priv->i2c_props,buf,1); tuner_dbg("mt2032 Reg.F=0x%02x\n",buf[0]); tad1=buf[0]&0x07; if(tad1 ==0) return lock; if(tad1 ==1) return lock; if(tad1==2) { if(sel==0) return lock; else sel--; } else { if(sel<4) sel++; else return lock; } tuner_dbg("mt2032 optimize_vco: sel=%d\n",sel); buf[0]=0x0f; buf[1]=sel; tuner_i2c_xfer_send(&priv->i2c_props,buf,2); lock=mt2032_check_lo_lock(fe); return lock; } static void mt2032_set_if_freq(struct dvb_frontend *fe, unsigned int rfin, unsigned int if1, unsigned int if2, unsigned int from, unsigned int to) { unsigned char buf[21]; int lint_try,ret,sel,lock=0; struct microtune_priv *priv = fe->tuner_priv; tuner_dbg("mt2032_set_if_freq rfin=%d if1=%d if2=%d from=%d to=%d\n", rfin,if1,if2,from,to); buf[0]=0; ret=tuner_i2c_xfer_send(&priv->i2c_props,buf,1); tuner_i2c_xfer_recv(&priv->i2c_props,buf,21); buf[0]=0; ret=mt2032_compute_freq(fe,rfin,if1,if2,from,to,&buf[1],&sel,priv->xogc); if (ret<0) return; // send only the relevant registers per Rev. 1.2 buf[0]=0; ret=tuner_i2c_xfer_send(&priv->i2c_props,buf,4); buf[5]=5; ret=tuner_i2c_xfer_send(&priv->i2c_props,buf+5,4); buf[11]=11; ret=tuner_i2c_xfer_send(&priv->i2c_props,buf+11,3); if(ret!=3) tuner_warn("i2c i/o error: rc == %d (should be 3)\n",ret); // wait for PLLs to lock (per manual), retry LINT if not. for(lint_try=0; lint_try<2; lint_try++) { lock=mt2032_check_lo_lock(fe); if(optimize_vco) lock=mt2032_optimize_vco(fe,sel,lock); if(lock==6) break; tuner_dbg("mt2032: re-init PLLs by LINT\n"); buf[0]=7; buf[1]=0x80 +8+priv->xogc; // set LINT to re-init PLLs tuner_i2c_xfer_send(&priv->i2c_props,buf,2); mdelay(10); buf[1]=8+priv->xogc; tuner_i2c_xfer_send(&priv->i2c_props,buf,2); } if (lock!=6) tuner_warn("MT2032 Fatal Error: PLLs didn't lock.\n"); buf[0]=2; buf[1]=0x20; // LOGC for optimal phase noise ret=tuner_i2c_xfer_send(&priv->i2c_props,buf,2); if (ret!=2) tuner_warn("i2c i/o error: rc == %d (should be 2)\n",ret); } static int mt2032_set_tv_freq(struct dvb_frontend *fe, struct analog_parameters *params) { int if2,from,to; // signal bandwidth and picture carrier if (params->std & V4L2_STD_525_60) { // NTSC from = 40750*1000; to = 46750*1000; if2 = 45750*1000; } else { // PAL from = 32900*1000; to = 39900*1000; if2 = 38900*1000; } mt2032_set_if_freq(fe, params->frequency*62500, 1090*1000*1000, if2, from, to); return 0; } static int mt2032_set_radio_freq(struct dvb_frontend *fe, struct analog_parameters *params) { struct microtune_priv *priv = fe->tuner_priv; int if2; if (params->std & V4L2_STD_525_60) { tuner_dbg("pinnacle ntsc\n"); if2 = 41300 * 1000; } else { tuner_dbg("pinnacle pal\n"); if2 = 33300 * 1000; } // per Manual for FM tuning: first if center freq. 1085 MHz mt2032_set_if_freq(fe, params->frequency * 125 / 2, 1085*1000*1000,if2,if2,if2); return 0; } static int mt2032_set_params(struct dvb_frontend *fe, struct analog_parameters *params) { struct microtune_priv *priv = fe->tuner_priv; int ret = -EINVAL; switch (params->mode) { case V4L2_TUNER_RADIO: ret = mt2032_set_radio_freq(fe, params); priv->frequency = params->frequency * 125 / 2; break; case V4L2_TUNER_ANALOG_TV: case V4L2_TUNER_DIGITAL_TV: ret = mt2032_set_tv_freq(fe, params); priv->frequency = params->frequency * 62500; break; } return ret; } static const struct dvb_tuner_ops mt2032_tuner_ops = { .set_analog_params = mt2032_set_params, .release = microtune_release, .get_frequency = microtune_get_frequency, }; // Initialization as described in "MT203x Programming Procedures", Rev 1.2, Feb.2001 static int mt2032_init(struct dvb_frontend *fe) { struct microtune_priv *priv = fe->tuner_priv; unsigned char buf[21]; int ret,xogc,xok=0; // Initialize Registers per spec. buf[1]=2; // Index to register 2 buf[2]=0xff; buf[3]=0x0f; buf[4]=0x1f; ret=tuner_i2c_xfer_send(&priv->i2c_props,buf+1,4); buf[5]=6; // Index register 6 buf[6]=0xe4; buf[7]=0x8f; buf[8]=0xc3; buf[9]=0x4e; buf[10]=0xec; ret=tuner_i2c_xfer_send(&priv->i2c_props,buf+5,6); buf[12]=13; // Index register 13 buf[13]=0x32; ret=tuner_i2c_xfer_send(&priv->i2c_props,buf+12,2); // Adjust XOGC (register 7), wait for XOK xogc=7; do { tuner_dbg("mt2032: xogc = 0x%02x\n",xogc&0x07); mdelay(10); buf[0]=0x0e; tuner_i2c_xfer_send(&priv->i2c_props,buf,1); tuner_i2c_xfer_recv(&priv->i2c_props,buf,1); xok=buf[0]&0x01; tuner_dbg("mt2032: xok = 0x%02x\n",xok); if (xok == 1) break; xogc--; tuner_dbg("mt2032: xogc = 0x%02x\n",xogc&0x07); if (xogc == 3) { xogc=4; // min. 4 per spec break; } buf[0]=0x07; buf[1]=0x88 + xogc; ret=tuner_i2c_xfer_send(&priv->i2c_props,buf,2); if (ret!=2) tuner_warn("i2c i/o error: rc == %d (should be 2)\n",ret); } while (xok != 1 ); priv->xogc=xogc; memcpy(&fe->ops.tuner_ops, &mt2032_tuner_ops, sizeof(struct dvb_tuner_ops)); return(1); } static void mt2050_set_antenna(struct dvb_frontend *fe, unsigned char antenna) { struct microtune_priv *priv = fe->tuner_priv; unsigned char buf[2]; buf[0] = 6; buf[1] = antenna ? 0x11 : 0x10; tuner_i2c_xfer_send(&priv->i2c_props, buf, 2); tuner_dbg("mt2050: enabled antenna connector %d\n", antenna); } static void mt2050_set_if_freq(struct dvb_frontend *fe,unsigned int freq, unsigned int if2) { struct microtune_priv *priv = fe->tuner_priv; unsigned int if1=1218*1000*1000; unsigned int f_lo1,f_lo2,lo1,lo2,f_lo1_modulo,f_lo2_modulo,num1,num2,div1a,div1b,div2a,div2b; int ret; unsigned char buf[6]; tuner_dbg("mt2050_set_if_freq freq=%d if1=%d if2=%d\n", freq,if1,if2); f_lo1=freq+if1; f_lo1=(f_lo1/1000000)*1000000; f_lo2=f_lo1-freq-if2; f_lo2=(f_lo2/50000)*50000; lo1=f_lo1/4000000; lo2=f_lo2/4000000; f_lo1_modulo= f_lo1-(lo1*4000000); f_lo2_modulo= f_lo2-(lo2*4000000); num1=4*f_lo1_modulo/4000000; num2=4096*(f_lo2_modulo/1000)/4000; // todo spurchecks div1a=(lo1/12)-1; div1b=lo1-(div1a+1)*12; div2a=(lo2/8)-1; div2b=lo2-(div2a+1)*8; if (debug > 1) { tuner_dbg("lo1 lo2 = %d %d\n", lo1, lo2); tuner_dbg("num1 num2 div1a div1b div2a div2b= %x %x %x %x %x %x\n", num1,num2,div1a,div1b,div2a,div2b); } buf[0]=1; buf[1]= 4*div1b + num1; if(freq<275*1000*1000) buf[1] = buf[1]|0x80; buf[2]=div1a; buf[3]=32*div2b + num2/256; buf[4]=num2-(num2/256)*256; buf[5]=div2a; if(num2!=0) buf[5]=buf[5]|0x40; if (debug > 1) tuner_dbg("bufs is: %*ph\n", 6, buf); ret=tuner_i2c_xfer_send(&priv->i2c_props,buf,6); if (ret!=6) tuner_warn("i2c i/o error: rc == %d (should be 6)\n",ret); } static int mt2050_set_tv_freq(struct dvb_frontend *fe, struct analog_parameters *params) { unsigned int if2; if (params->std & V4L2_STD_525_60) { // NTSC if2 = 45750*1000; } else { // PAL if2 = 38900*1000; } if (V4L2_TUNER_DIGITAL_TV == params->mode) { // DVB (pinnacle 300i) if2 = 36150*1000; } mt2050_set_if_freq(fe, params->frequency*62500, if2); mt2050_set_antenna(fe, tv_antenna); return 0; } static int mt2050_set_radio_freq(struct dvb_frontend *fe, struct analog_parameters *params) { struct microtune_priv *priv = fe->tuner_priv; int if2; if (params->std & V4L2_STD_525_60) { tuner_dbg("pinnacle ntsc\n"); if2 = 41300 * 1000; } else { tuner_dbg("pinnacle pal\n"); if2 = 33300 * 1000; } mt2050_set_if_freq(fe, params->frequency * 125 / 2, if2); mt2050_set_antenna(fe, radio_antenna); return 0; } static int mt2050_set_params(struct dvb_frontend *fe, struct analog_parameters *params) { struct microtune_priv *priv = fe->tuner_priv; int ret = -EINVAL; switch (params->mode) { case V4L2_TUNER_RADIO: ret = mt2050_set_radio_freq(fe, params); priv->frequency = params->frequency * 125 / 2; break; case V4L2_TUNER_ANALOG_TV: case V4L2_TUNER_DIGITAL_TV: ret = mt2050_set_tv_freq(fe, params); priv->frequency = params->frequency * 62500; break; } return ret; } static const struct dvb_tuner_ops mt2050_tuner_ops = { .set_analog_params = mt2050_set_params, .release = microtune_release, .get_frequency = microtune_get_frequency, }; static int mt2050_init(struct dvb_frontend *fe) { struct microtune_priv *priv = fe->tuner_priv; unsigned char buf[2]; buf[0] = 6; buf[1] = 0x10; tuner_i2c_xfer_send(&priv->i2c_props, buf, 2); /* power */ buf[0] = 0x0f; buf[1] = 0x0f; tuner_i2c_xfer_send(&priv->i2c_props, buf, 2); /* m1lo */ buf[0] = 0x0d; tuner_i2c_xfer_send(&priv->i2c_props, buf, 1); tuner_i2c_xfer_recv(&priv->i2c_props, buf, 1); tuner_dbg("mt2050: sro is %x\n", buf[0]); memcpy(&fe->ops.tuner_ops, &mt2050_tuner_ops, sizeof(struct dvb_tuner_ops)); return 0; } struct dvb_frontend *microtune_attach(struct dvb_frontend *fe, struct i2c_adapter* i2c_adap, u8 i2c_addr) { struct microtune_priv *priv = NULL; char *name; unsigned char buf[21]; int company_code; priv = kzalloc(sizeof(struct microtune_priv), GFP_KERNEL); if (priv == NULL) return NULL; fe->tuner_priv = priv; priv->i2c_props.addr = i2c_addr; priv->i2c_props.adap = i2c_adap; priv->i2c_props.name = "mt20xx"; //priv->radio_if2 = 10700 * 1000; /* 10.7MHz - FM radio */ memset(buf,0,sizeof(buf)); name = "unknown"; tuner_i2c_xfer_send(&priv->i2c_props,buf,1); tuner_i2c_xfer_recv(&priv->i2c_props,buf,21); if (debug) tuner_dbg("MT20xx hexdump: %*ph\n", 21, buf); company_code = buf[0x11] << 8 | buf[0x12]; tuner_info("microtune: companycode=%04x part=%02x rev=%02x\n", company_code,buf[0x13],buf[0x14]); if (buf[0x13] < ARRAY_SIZE(microtune_part) && NULL != microtune_part[buf[0x13]]) name = microtune_part[buf[0x13]]; switch (buf[0x13]) { case MT2032: mt2032_init(fe); break; case MT2050: mt2050_init(fe); break; default: tuner_info("microtune %s found, not (yet?) supported, sorry :-/\n", name); return NULL; } strscpy(fe->ops.tuner_ops.info.name, name, sizeof(fe->ops.tuner_ops.info.name)); tuner_info("microtune %s found, OK\n",name); return fe; } EXPORT_SYMBOL_GPL(microtune_attach); MODULE_DESCRIPTION("Microtune tuner driver"); MODULE_AUTHOR("Ralph Metzler, Gerd Knorr, Gunther Mayer"); MODULE_LICENSE("GPL");
linux-master
drivers/media/tuners/mt20xx.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Driver for Maxim MAX2165 silicon tuner * * Copyright (c) 2009 David T. L. Wong <[email protected]> */ #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/videodev2.h> #include <linux/delay.h> #include <linux/dvb/frontend.h> #include <linux/i2c.h> #include <linux/slab.h> #include <media/dvb_frontend.h> #include "max2165.h" #include "max2165_priv.h" #include "tuner-i2c.h" #define dprintk(args...) \ do { \ if (debug) \ printk(KERN_DEBUG "max2165: " args); \ } while (0) static int debug; module_param(debug, int, 0644); MODULE_PARM_DESC(debug, "Turn on/off debugging (default:off)."); static int max2165_write_reg(struct max2165_priv *priv, u8 reg, u8 data) { int ret; u8 buf[] = { reg, data }; struct i2c_msg msg = { .flags = 0, .buf = buf, .len = 2 }; msg.addr = priv->config->i2c_address; if (debug >= 2) dprintk("%s: reg=0x%02X, data=0x%02X\n", __func__, reg, data); ret = i2c_transfer(priv->i2c, &msg, 1); if (ret != 1) dprintk("%s: error reg=0x%x, data=0x%x, ret=%i\n", __func__, reg, data, ret); return (ret != 1) ? -EIO : 0; } static int max2165_read_reg(struct max2165_priv *priv, u8 reg, u8 *p_data) { int ret; u8 dev_addr = priv->config->i2c_address; u8 b0[] = { reg }; u8 b1[] = { 0 }; struct i2c_msg msg[] = { { .addr = dev_addr, .flags = 0, .buf = b0, .len = 1 }, { .addr = dev_addr, .flags = I2C_M_RD, .buf = b1, .len = 1 }, }; ret = i2c_transfer(priv->i2c, msg, 2); if (ret != 2) { dprintk("%s: error reg=0x%x, ret=%i\n", __func__, reg, ret); return -EIO; } *p_data = b1[0]; if (debug >= 2) dprintk("%s: reg=0x%02X, data=0x%02X\n", __func__, reg, b1[0]); return 0; } static int max2165_mask_write_reg(struct max2165_priv *priv, u8 reg, u8 mask, u8 data) { int ret; u8 v; data &= mask; ret = max2165_read_reg(priv, reg, &v); if (ret != 0) return ret; v &= ~mask; v |= data; ret = max2165_write_reg(priv, reg, v); return ret; } static int max2165_read_rom_table(struct max2165_priv *priv) { u8 dat[3]; int i; for (i = 0; i < 3; i++) { max2165_write_reg(priv, REG_ROM_TABLE_ADDR, i + 1); max2165_read_reg(priv, REG_ROM_TABLE_DATA, &dat[i]); } priv->tf_ntch_low_cfg = dat[0] >> 4; priv->tf_ntch_hi_cfg = dat[0] & 0x0F; priv->tf_balun_low_ref = dat[1] & 0x0F; priv->tf_balun_hi_ref = dat[1] >> 4; priv->bb_filter_7mhz_cfg = dat[2] & 0x0F; priv->bb_filter_8mhz_cfg = dat[2] >> 4; dprintk("tf_ntch_low_cfg = 0x%X\n", priv->tf_ntch_low_cfg); dprintk("tf_ntch_hi_cfg = 0x%X\n", priv->tf_ntch_hi_cfg); dprintk("tf_balun_low_ref = 0x%X\n", priv->tf_balun_low_ref); dprintk("tf_balun_hi_ref = 0x%X\n", priv->tf_balun_hi_ref); dprintk("bb_filter_7mhz_cfg = 0x%X\n", priv->bb_filter_7mhz_cfg); dprintk("bb_filter_8mhz_cfg = 0x%X\n", priv->bb_filter_8mhz_cfg); return 0; } static int max2165_set_osc(struct max2165_priv *priv, u8 osc /*MHz*/) { u8 v; v = (osc / 2); if (v == 2) v = 0x7; else v -= 8; max2165_mask_write_reg(priv, REG_PLL_CFG, 0x07, v); return 0; } static int max2165_set_bandwidth(struct max2165_priv *priv, u32 bw) { u8 val; if (bw == 8000000) val = priv->bb_filter_8mhz_cfg; else val = priv->bb_filter_7mhz_cfg; max2165_mask_write_reg(priv, REG_BASEBAND_CTRL, 0xF0, val << 4); return 0; } static int fixpt_div32(u32 dividend, u32 divisor, u32 *quotient, u32 *fraction) { u32 remainder; u32 q, f = 0; int i; if (0 == divisor) return -EINVAL; q = dividend / divisor; remainder = dividend - q * divisor; for (i = 0; i < 31; i++) { remainder <<= 1; if (remainder >= divisor) { f += 1; remainder -= divisor; } f <<= 1; } *quotient = q; *fraction = f; return 0; } static int max2165_set_rf(struct max2165_priv *priv, u32 freq) { u8 tf; u8 tf_ntch; u32 t; u32 quotient, fraction; int ret; /* Set PLL divider according to RF frequency */ ret = fixpt_div32(freq / 1000, priv->config->osc_clk * 1000, &quotient, &fraction); if (ret != 0) return ret; /* 20-bit fraction */ fraction >>= 12; max2165_write_reg(priv, REG_NDIV_INT, quotient); max2165_mask_write_reg(priv, REG_NDIV_FRAC2, 0x0F, fraction >> 16); max2165_write_reg(priv, REG_NDIV_FRAC1, fraction >> 8); max2165_write_reg(priv, REG_NDIV_FRAC0, fraction); /* Norch Filter */ tf_ntch = (freq < 725000000) ? priv->tf_ntch_low_cfg : priv->tf_ntch_hi_cfg; /* Tracking filter balun */ t = priv->tf_balun_low_ref; t += (priv->tf_balun_hi_ref - priv->tf_balun_low_ref) * (freq / 1000 - 470000) / (780000 - 470000); tf = t; dprintk("tf = %X\n", tf); tf |= tf_ntch << 4; max2165_write_reg(priv, REG_TRACK_FILTER, tf); return 0; } static void max2165_debug_status(struct max2165_priv *priv) { u8 status, autotune; u8 auto_vco_success, auto_vco_active; u8 pll_locked; u8 dc_offset_low, dc_offset_hi; u8 signal_lv_over_threshold; u8 vco, vco_sub_band, adc; max2165_read_reg(priv, REG_STATUS, &status); max2165_read_reg(priv, REG_AUTOTUNE, &autotune); auto_vco_success = (status >> 6) & 0x01; auto_vco_active = (status >> 5) & 0x01; pll_locked = (status >> 4) & 0x01; dc_offset_low = (status >> 3) & 0x01; dc_offset_hi = (status >> 2) & 0x01; signal_lv_over_threshold = status & 0x01; vco = autotune >> 6; vco_sub_band = (autotune >> 3) & 0x7; adc = autotune & 0x7; dprintk("auto VCO active: %d, auto VCO success: %d\n", auto_vco_active, auto_vco_success); dprintk("PLL locked: %d\n", pll_locked); dprintk("DC offset low: %d, DC offset high: %d\n", dc_offset_low, dc_offset_hi); dprintk("Signal lvl over threshold: %d\n", signal_lv_over_threshold); dprintk("VCO: %d, VCO Sub-band: %d, ADC: %d\n", vco, vco_sub_band, adc); } static int max2165_set_params(struct dvb_frontend *fe) { struct max2165_priv *priv = fe->tuner_priv; struct dtv_frontend_properties *c = &fe->dtv_property_cache; int ret; switch (c->bandwidth_hz) { case 7000000: case 8000000: priv->frequency = c->frequency; break; default: printk(KERN_INFO "MAX2165: bandwidth %d Hz not supported.\n", c->bandwidth_hz); return -EINVAL; } dprintk("%s() frequency=%d\n", __func__, c->frequency); if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 1); max2165_set_bandwidth(priv, c->bandwidth_hz); ret = max2165_set_rf(priv, priv->frequency); mdelay(50); max2165_debug_status(priv); if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 0); if (ret != 0) return -EREMOTEIO; return 0; } static int max2165_get_frequency(struct dvb_frontend *fe, u32 *freq) { struct max2165_priv *priv = fe->tuner_priv; dprintk("%s()\n", __func__); *freq = priv->frequency; return 0; } static int max2165_get_bandwidth(struct dvb_frontend *fe, u32 *bw) { struct max2165_priv *priv = fe->tuner_priv; dprintk("%s()\n", __func__); *bw = priv->bandwidth; return 0; } static int max2165_get_status(struct dvb_frontend *fe, u32 *status) { struct max2165_priv *priv = fe->tuner_priv; u16 lock_status = 0; dprintk("%s()\n", __func__); if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 1); max2165_debug_status(priv); *status = lock_status; if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 0); return 0; } static int max2165_sleep(struct dvb_frontend *fe) { dprintk("%s()\n", __func__); return 0; } static int max2165_init(struct dvb_frontend *fe) { struct max2165_priv *priv = fe->tuner_priv; dprintk("%s()\n", __func__); if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 1); /* Setup initial values */ /* Fractional Mode on */ max2165_write_reg(priv, REG_NDIV_FRAC2, 0x18); /* LNA on */ max2165_write_reg(priv, REG_LNA, 0x01); max2165_write_reg(priv, REG_PLL_CFG, 0x7A); max2165_write_reg(priv, REG_TEST, 0x08); max2165_write_reg(priv, REG_SHUTDOWN, 0x40); max2165_write_reg(priv, REG_VCO_CTRL, 0x84); max2165_write_reg(priv, REG_BASEBAND_CTRL, 0xC3); max2165_write_reg(priv, REG_DC_OFFSET_CTRL, 0x75); max2165_write_reg(priv, REG_DC_OFFSET_DAC, 0x00); max2165_write_reg(priv, REG_ROM_TABLE_ADDR, 0x00); max2165_set_osc(priv, priv->config->osc_clk); max2165_read_rom_table(priv); max2165_set_bandwidth(priv, 8000000); if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 0); return 0; } static void max2165_release(struct dvb_frontend *fe) { struct max2165_priv *priv = fe->tuner_priv; dprintk("%s()\n", __func__); kfree(priv); fe->tuner_priv = NULL; } static const struct dvb_tuner_ops max2165_tuner_ops = { .info = { .name = "Maxim MAX2165", .frequency_min_hz = 470 * MHz, .frequency_max_hz = 862 * MHz, .frequency_step_hz = 50 * kHz, }, .release = max2165_release, .init = max2165_init, .sleep = max2165_sleep, .set_params = max2165_set_params, .set_analog_params = NULL, .get_frequency = max2165_get_frequency, .get_bandwidth = max2165_get_bandwidth, .get_status = max2165_get_status }; struct dvb_frontend *max2165_attach(struct dvb_frontend *fe, struct i2c_adapter *i2c, struct max2165_config *cfg) { struct max2165_priv *priv = NULL; dprintk("%s(%d-%04x)\n", __func__, i2c ? i2c_adapter_id(i2c) : -1, cfg ? cfg->i2c_address : -1); priv = kzalloc(sizeof(struct max2165_priv), GFP_KERNEL); if (priv == NULL) return NULL; memcpy(&fe->ops.tuner_ops, &max2165_tuner_ops, sizeof(struct dvb_tuner_ops)); priv->config = cfg; priv->i2c = i2c; fe->tuner_priv = priv; max2165_init(fe); max2165_debug_status(priv); return fe; } EXPORT_SYMBOL_GPL(max2165_attach); MODULE_AUTHOR("David T. L. Wong <[email protected]>"); MODULE_DESCRIPTION("Maxim MAX2165 silicon tuner driver"); MODULE_LICENSE("GPL");
linux-master
drivers/media/tuners/max2165.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * ITE IT913X silicon tuner driver * * Copyright (C) 2011 Malcolm Priestley ([email protected]) * IT9137 Copyright (C) ITE Tech Inc. */ #include "it913x.h" #include <linux/platform_device.h> #include <linux/regmap.h> struct it913x_dev { struct platform_device *pdev; struct regmap *regmap; struct dvb_frontend *fe; u8 chip_ver:2; u8 role:2; u16 xtal; u8 fdiv; u8 clk_mode; u32 fn_min; bool active; }; static int it913x_init(struct dvb_frontend *fe) { struct it913x_dev *dev = fe->tuner_priv; struct platform_device *pdev = dev->pdev; int ret; unsigned int utmp; u8 iqik_m_cal, nv_val, buf[2]; static const u8 nv[] = {48, 32, 24, 16, 12, 8, 6, 4, 2}; unsigned long timeout; dev_dbg(&pdev->dev, "role %u\n", dev->role); ret = regmap_write(dev->regmap, 0x80ec4c, 0x68); if (ret) goto err; usleep_range(10000, 100000); ret = regmap_read(dev->regmap, 0x80ec86, &utmp); if (ret) goto err; switch (utmp) { case 0: /* 12.000 MHz */ dev->clk_mode = utmp; dev->xtal = 2000; dev->fdiv = 3; iqik_m_cal = 16; break; case 1: /* 20.480 MHz */ dev->clk_mode = utmp; dev->xtal = 640; dev->fdiv = 1; iqik_m_cal = 6; break; default: dev_err(&pdev->dev, "unknown clock identifier %d\n", utmp); ret = -EINVAL; goto err; } ret = regmap_read(dev->regmap, 0x80ed03, &utmp); if (ret) goto err; else if (utmp < ARRAY_SIZE(nv)) nv_val = nv[utmp]; else nv_val = 2; #define TIMEOUT 50 timeout = jiffies + msecs_to_jiffies(TIMEOUT); while (!time_after(jiffies, timeout)) { ret = regmap_bulk_read(dev->regmap, 0x80ed23, buf, 2); if (ret) goto err; utmp = (buf[1] << 8) | (buf[0] << 0); if (utmp) break; } dev_dbg(&pdev->dev, "r_fbc_m_bdry took %u ms, val %u\n", jiffies_to_msecs(jiffies) - (jiffies_to_msecs(timeout) - TIMEOUT), utmp); dev->fn_min = dev->xtal * utmp; dev->fn_min /= (dev->fdiv * nv_val); dev->fn_min *= 1000; dev_dbg(&pdev->dev, "fn_min %u\n", dev->fn_min); /* * Chip version BX never sets that flag so we just wait 50ms in that * case. It is possible poll BX similarly than AX and then timeout in * order to get 50ms delay, but that causes about 120 extra I2C * messages. As for now, we just wait and reduce IO. */ if (dev->chip_ver == 1) { #define TIMEOUT 50 timeout = jiffies + msecs_to_jiffies(TIMEOUT); while (!time_after(jiffies, timeout)) { ret = regmap_read(dev->regmap, 0x80ec82, &utmp); if (ret) goto err; if (utmp) break; } dev_dbg(&pdev->dev, "p_tsm_init_mode took %u ms, val %u\n", jiffies_to_msecs(jiffies) - (jiffies_to_msecs(timeout) - TIMEOUT), utmp); } else { msleep(50); } ret = regmap_write(dev->regmap, 0x80ed81, iqik_m_cal); if (ret) goto err; ret = regmap_write(dev->regmap, 0x80ec57, 0x00); if (ret) goto err; ret = regmap_write(dev->regmap, 0x80ec58, 0x00); if (ret) goto err; ret = regmap_write(dev->regmap, 0x80ec40, 0x01); if (ret) goto err; dev->active = true; return 0; err: dev_dbg(&pdev->dev, "failed %d\n", ret); return ret; } static int it913x_sleep(struct dvb_frontend *fe) { struct it913x_dev *dev = fe->tuner_priv; struct platform_device *pdev = dev->pdev; int ret, len; dev_dbg(&pdev->dev, "role %u\n", dev->role); dev->active = false; ret = regmap_bulk_write(dev->regmap, 0x80ec40, "\x00", 1); if (ret) goto err; /* * Writing '0x00' to master tuner register '0x80ec08' causes slave tuner * communication lost. Due to that, we cannot put master full sleep. */ if (dev->role == IT913X_ROLE_DUAL_MASTER) len = 4; else len = 15; dev_dbg(&pdev->dev, "role %u, len %d\n", dev->role, len); ret = regmap_bulk_write(dev->regmap, 0x80ec02, "\x3f\x1f\x3f\x3e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", len); if (ret) goto err; ret = regmap_bulk_write(dev->regmap, 0x80ec12, "\x00\x00\x00\x00", 4); if (ret) goto err; ret = regmap_bulk_write(dev->regmap, 0x80ec17, "\x00\x00\x00\x00\x00\x00\x00\x00\x00", 9); if (ret) goto err; ret = regmap_bulk_write(dev->regmap, 0x80ec22, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 10); if (ret) goto err; ret = regmap_bulk_write(dev->regmap, 0x80ec20, "\x00", 1); if (ret) goto err; ret = regmap_bulk_write(dev->regmap, 0x80ec3f, "\x01", 1); if (ret) goto err; return 0; err: dev_dbg(&pdev->dev, "failed %d\n", ret); return ret; } static int it913x_set_params(struct dvb_frontend *fe) { struct it913x_dev *dev = fe->tuner_priv; struct platform_device *pdev = dev->pdev; struct dtv_frontend_properties *c = &fe->dtv_property_cache; int ret; unsigned int utmp; u32 pre_lo_freq, t_cal_freq; u16 iqik_m_cal, n_div; u8 u8tmp, n, l_band, lna_band; dev_dbg(&pdev->dev, "role=%u, frequency %u, bandwidth_hz %u\n", dev->role, c->frequency, c->bandwidth_hz); if (!dev->active) { ret = -EINVAL; goto err; } if (c->frequency <= 74000000) { n_div = 48; n = 0; } else if (c->frequency <= 111000000) { n_div = 32; n = 1; } else if (c->frequency <= 148000000) { n_div = 24; n = 2; } else if (c->frequency <= 222000000) { n_div = 16; n = 3; } else if (c->frequency <= 296000000) { n_div = 12; n = 4; } else if (c->frequency <= 445000000) { n_div = 8; n = 5; } else if (c->frequency <= dev->fn_min) { n_div = 6; n = 6; } else if (c->frequency <= 950000000) { n_div = 4; n = 7; } else { n_div = 2; n = 0; } ret = regmap_read(dev->regmap, 0x80ed81, &utmp); if (ret) goto err; iqik_m_cal = utmp * n_div; if (utmp < 0x20) { if (dev->clk_mode == 0) iqik_m_cal = (iqik_m_cal * 9) >> 5; else iqik_m_cal >>= 1; } else { iqik_m_cal = 0x40 - iqik_m_cal; if (dev->clk_mode == 0) iqik_m_cal = ~((iqik_m_cal * 9) >> 5); else iqik_m_cal = ~(iqik_m_cal >> 1); } t_cal_freq = (c->frequency / 1000) * n_div * dev->fdiv; pre_lo_freq = t_cal_freq / dev->xtal; utmp = pre_lo_freq * dev->xtal; if ((t_cal_freq - utmp) >= (dev->xtal >> 1)) pre_lo_freq++; pre_lo_freq += (u32) n << 13; /* Frequency OMEGA_IQIK_M_CAL_MID*/ t_cal_freq = pre_lo_freq + (u32)iqik_m_cal; dev_dbg(&pdev->dev, "t_cal_freq %u, pre_lo_freq %u\n", t_cal_freq, pre_lo_freq); if (c->frequency <= 440000000) { l_band = 0; lna_band = 0; } else if (c->frequency <= 484000000) { l_band = 1; lna_band = 1; } else if (c->frequency <= 533000000) { l_band = 1; lna_band = 2; } else if (c->frequency <= 587000000) { l_band = 1; lna_band = 3; } else if (c->frequency <= 645000000) { l_band = 1; lna_band = 4; } else if (c->frequency <= 710000000) { l_band = 1; lna_band = 5; } else if (c->frequency <= 782000000) { l_band = 1; lna_band = 6; } else if (c->frequency <= 860000000) { l_band = 1; lna_band = 7; } else if (c->frequency <= 1492000000) { l_band = 1; lna_band = 0; } else if (c->frequency <= 1685000000) { l_band = 1; lna_band = 1; } else { ret = -EINVAL; goto err; } /* XXX: latest windows driver does not set that at all */ ret = regmap_write(dev->regmap, 0x80ee06, lna_band); if (ret) goto err; if (c->bandwidth_hz <= 5000000) u8tmp = 0; else if (c->bandwidth_hz <= 6000000) u8tmp = 2; else if (c->bandwidth_hz <= 7000000) u8tmp = 4; else u8tmp = 6; /* 8000000 */ ret = regmap_write(dev->regmap, 0x80ec56, u8tmp); if (ret) goto err; /* XXX: latest windows driver sets different value (a8 != 68) */ ret = regmap_write(dev->regmap, 0x80ec4c, 0xa0 | (l_band << 3)); if (ret) goto err; ret = regmap_write(dev->regmap, 0x80ec4d, (t_cal_freq >> 0) & 0xff); if (ret) goto err; ret = regmap_write(dev->regmap, 0x80ec4e, (t_cal_freq >> 8) & 0xff); if (ret) goto err; ret = regmap_write(dev->regmap, 0x80011e, (pre_lo_freq >> 0) & 0xff); if (ret) goto err; ret = regmap_write(dev->regmap, 0x80011f, (pre_lo_freq >> 8) & 0xff); if (ret) goto err; return 0; err: dev_dbg(&pdev->dev, "failed %d\n", ret); return ret; } static const struct dvb_tuner_ops it913x_tuner_ops = { .info = { .name = "ITE IT913X", .frequency_min_hz = 174 * MHz, .frequency_max_hz = 862 * MHz, }, .init = it913x_init, .sleep = it913x_sleep, .set_params = it913x_set_params, }; static int it913x_probe(struct platform_device *pdev) { struct it913x_platform_data *pdata = pdev->dev.platform_data; struct dvb_frontend *fe = pdata->fe; struct it913x_dev *dev; const struct platform_device_id *id = platform_get_device_id(pdev); int ret; char *chip_ver_str; dev = kzalloc(sizeof(struct it913x_dev), GFP_KERNEL); if (dev == NULL) { ret = -ENOMEM; dev_err(&pdev->dev, "kzalloc() failed\n"); goto err; } dev->pdev = pdev; dev->regmap = pdata->regmap; dev->fe = pdata->fe; dev->chip_ver = id->driver_data; dev->role = pdata->role; fe->tuner_priv = dev; memcpy(&fe->ops.tuner_ops, &it913x_tuner_ops, sizeof(struct dvb_tuner_ops)); platform_set_drvdata(pdev, dev); if (dev->chip_ver == 1) chip_ver_str = "AX"; else if (dev->chip_ver == 2) chip_ver_str = "BX"; else chip_ver_str = "??"; dev_info(&pdev->dev, "ITE IT913X %s successfully attached\n", chip_ver_str); dev_dbg(&pdev->dev, "chip_ver %u, role %u\n", dev->chip_ver, dev->role); return 0; err: dev_dbg(&pdev->dev, "failed %d\n", ret); return ret; } static void it913x_remove(struct platform_device *pdev) { struct it913x_dev *dev = platform_get_drvdata(pdev); struct dvb_frontend *fe = dev->fe; dev_dbg(&pdev->dev, "\n"); memset(&fe->ops.tuner_ops, 0, sizeof(struct dvb_tuner_ops)); fe->tuner_priv = NULL; kfree(dev); } static const struct platform_device_id it913x_id_table[] = { {"it9133ax-tuner", 1}, {"it9133bx-tuner", 2}, {}, }; MODULE_DEVICE_TABLE(platform, it913x_id_table); static struct platform_driver it913x_driver = { .driver = { .name = "it913x", .suppress_bind_attrs = true, }, .probe = it913x_probe, .remove_new = it913x_remove, .id_table = it913x_id_table, }; module_platform_driver(it913x_driver); MODULE_DESCRIPTION("ITE IT913X silicon tuner driver"); MODULE_AUTHOR("Antti Palosaari <[email protected]>"); MODULE_LICENSE("GPL");
linux-master
drivers/media/tuners/it913x.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Driver for Freescale MC44S803 Low Power CMOS Broadband Tuner * * Copyright (c) 2009 Jochen Friedrich <[email protected]> */ #include <linux/module.h> #include <linux/delay.h> #include <linux/dvb/frontend.h> #include <linux/i2c.h> #include <linux/slab.h> #include <media/dvb_frontend.h> #include "mc44s803.h" #include "mc44s803_priv.h" #define mc_printk(level, format, arg...) \ printk(level "mc44s803: " format , ## arg) /* Writes a single register */ static int mc44s803_writereg(struct mc44s803_priv *priv, u32 val) { u8 buf[3]; struct i2c_msg msg = { .addr = priv->cfg->i2c_address, .flags = 0, .buf = buf, .len = 3 }; buf[0] = (val & 0xff0000) >> 16; buf[1] = (val & 0xff00) >> 8; buf[2] = (val & 0xff); if (i2c_transfer(priv->i2c, &msg, 1) != 1) { mc_printk(KERN_WARNING, "I2C write failed\n"); return -EREMOTEIO; } return 0; } /* Reads a single register */ static int mc44s803_readreg(struct mc44s803_priv *priv, u8 reg, u32 *val) { u32 wval; u8 buf[3]; int ret; struct i2c_msg msg[] = { { .addr = priv->cfg->i2c_address, .flags = I2C_M_RD, .buf = buf, .len = 3 }, }; wval = MC44S803_REG_SM(MC44S803_REG_DATAREG, MC44S803_ADDR) | MC44S803_REG_SM(reg, MC44S803_D); ret = mc44s803_writereg(priv, wval); if (ret) return ret; if (i2c_transfer(priv->i2c, msg, 1) != 1) { mc_printk(KERN_WARNING, "I2C read failed\n"); return -EREMOTEIO; } *val = (buf[0] << 16) | (buf[1] << 8) | buf[2]; return 0; } static void mc44s803_release(struct dvb_frontend *fe) { struct mc44s803_priv *priv = fe->tuner_priv; fe->tuner_priv = NULL; kfree(priv); } static int mc44s803_init(struct dvb_frontend *fe) { struct mc44s803_priv *priv = fe->tuner_priv; u32 val; int err; if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 1); /* Reset chip */ val = MC44S803_REG_SM(MC44S803_REG_RESET, MC44S803_ADDR) | MC44S803_REG_SM(1, MC44S803_RS); err = mc44s803_writereg(priv, val); if (err) goto exit; val = MC44S803_REG_SM(MC44S803_REG_RESET, MC44S803_ADDR); err = mc44s803_writereg(priv, val); if (err) goto exit; /* Power Up and Start Osc */ val = MC44S803_REG_SM(MC44S803_REG_REFOSC, MC44S803_ADDR) | MC44S803_REG_SM(0xC0, MC44S803_REFOSC) | MC44S803_REG_SM(1, MC44S803_OSCSEL); err = mc44s803_writereg(priv, val); if (err) goto exit; val = MC44S803_REG_SM(MC44S803_REG_POWER, MC44S803_ADDR) | MC44S803_REG_SM(0x200, MC44S803_POWER); err = mc44s803_writereg(priv, val); if (err) goto exit; msleep(10); val = MC44S803_REG_SM(MC44S803_REG_REFOSC, MC44S803_ADDR) | MC44S803_REG_SM(0x40, MC44S803_REFOSC) | MC44S803_REG_SM(1, MC44S803_OSCSEL); err = mc44s803_writereg(priv, val); if (err) goto exit; msleep(20); /* Setup Mixer */ val = MC44S803_REG_SM(MC44S803_REG_MIXER, MC44S803_ADDR) | MC44S803_REG_SM(1, MC44S803_TRI_STATE) | MC44S803_REG_SM(0x7F, MC44S803_MIXER_RES); err = mc44s803_writereg(priv, val); if (err) goto exit; /* Setup Cirquit Adjust */ val = MC44S803_REG_SM(MC44S803_REG_CIRCADJ, MC44S803_ADDR) | MC44S803_REG_SM(1, MC44S803_G1) | MC44S803_REG_SM(1, MC44S803_G3) | MC44S803_REG_SM(0x3, MC44S803_CIRCADJ_RES) | MC44S803_REG_SM(1, MC44S803_G6) | MC44S803_REG_SM(priv->cfg->dig_out, MC44S803_S1) | MC44S803_REG_SM(0x3, MC44S803_LP) | MC44S803_REG_SM(1, MC44S803_CLRF) | MC44S803_REG_SM(1, MC44S803_CLIF); err = mc44s803_writereg(priv, val); if (err) goto exit; val = MC44S803_REG_SM(MC44S803_REG_CIRCADJ, MC44S803_ADDR) | MC44S803_REG_SM(1, MC44S803_G1) | MC44S803_REG_SM(1, MC44S803_G3) | MC44S803_REG_SM(0x3, MC44S803_CIRCADJ_RES) | MC44S803_REG_SM(1, MC44S803_G6) | MC44S803_REG_SM(priv->cfg->dig_out, MC44S803_S1) | MC44S803_REG_SM(0x3, MC44S803_LP); err = mc44s803_writereg(priv, val); if (err) goto exit; /* Setup Digtune */ val = MC44S803_REG_SM(MC44S803_REG_DIGTUNE, MC44S803_ADDR) | MC44S803_REG_SM(3, MC44S803_XOD); err = mc44s803_writereg(priv, val); if (err) goto exit; /* Setup AGC */ val = MC44S803_REG_SM(MC44S803_REG_LNAAGC, MC44S803_ADDR) | MC44S803_REG_SM(1, MC44S803_AT1) | MC44S803_REG_SM(1, MC44S803_AT2) | MC44S803_REG_SM(1, MC44S803_AGC_AN_DIG) | MC44S803_REG_SM(1, MC44S803_AGC_READ_EN) | MC44S803_REG_SM(1, MC44S803_LNA0); err = mc44s803_writereg(priv, val); if (err) goto exit; if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 0); return 0; exit: if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 0); mc_printk(KERN_WARNING, "I/O Error\n"); return err; } static int mc44s803_set_params(struct dvb_frontend *fe) { struct mc44s803_priv *priv = fe->tuner_priv; struct dtv_frontend_properties *c = &fe->dtv_property_cache; u32 r1, r2, n1, n2, lo1, lo2, freq, val; int err; priv->frequency = c->frequency; r1 = MC44S803_OSC / 1000000; r2 = MC44S803_OSC / 100000; n1 = (c->frequency + MC44S803_IF1 + 500000) / 1000000; freq = MC44S803_OSC / r1 * n1; lo1 = ((60 * n1) + (r1 / 2)) / r1; freq = freq - c->frequency; n2 = (freq - MC44S803_IF2 + 50000) / 100000; lo2 = ((60 * n2) + (r2 / 2)) / r2; if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 1); val = MC44S803_REG_SM(MC44S803_REG_REFDIV, MC44S803_ADDR) | MC44S803_REG_SM(r1-1, MC44S803_R1) | MC44S803_REG_SM(r2-1, MC44S803_R2) | MC44S803_REG_SM(1, MC44S803_REFBUF_EN); err = mc44s803_writereg(priv, val); if (err) goto exit; val = MC44S803_REG_SM(MC44S803_REG_LO1, MC44S803_ADDR) | MC44S803_REG_SM(n1-2, MC44S803_LO1); err = mc44s803_writereg(priv, val); if (err) goto exit; val = MC44S803_REG_SM(MC44S803_REG_LO2, MC44S803_ADDR) | MC44S803_REG_SM(n2-2, MC44S803_LO2); err = mc44s803_writereg(priv, val); if (err) goto exit; val = MC44S803_REG_SM(MC44S803_REG_DIGTUNE, MC44S803_ADDR) | MC44S803_REG_SM(1, MC44S803_DA) | MC44S803_REG_SM(lo1, MC44S803_LO_REF) | MC44S803_REG_SM(1, MC44S803_AT); err = mc44s803_writereg(priv, val); if (err) goto exit; val = MC44S803_REG_SM(MC44S803_REG_DIGTUNE, MC44S803_ADDR) | MC44S803_REG_SM(2, MC44S803_DA) | MC44S803_REG_SM(lo2, MC44S803_LO_REF) | MC44S803_REG_SM(1, MC44S803_AT); err = mc44s803_writereg(priv, val); if (err) goto exit; if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 0); return 0; exit: if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 0); mc_printk(KERN_WARNING, "I/O Error\n"); return err; } static int mc44s803_get_frequency(struct dvb_frontend *fe, u32 *frequency) { struct mc44s803_priv *priv = fe->tuner_priv; *frequency = priv->frequency; return 0; } static int mc44s803_get_if_frequency(struct dvb_frontend *fe, u32 *frequency) { *frequency = MC44S803_IF2; /* 36.125 MHz */ return 0; } static const struct dvb_tuner_ops mc44s803_tuner_ops = { .info = { .name = "Freescale MC44S803", .frequency_min_hz = 48 * MHz, .frequency_max_hz = 1000 * MHz, .frequency_step_hz = 100 * kHz, }, .release = mc44s803_release, .init = mc44s803_init, .set_params = mc44s803_set_params, .get_frequency = mc44s803_get_frequency, .get_if_frequency = mc44s803_get_if_frequency, }; /* This functions tries to identify a MC44S803 tuner by reading the ID register. This is hasty. */ struct dvb_frontend *mc44s803_attach(struct dvb_frontend *fe, struct i2c_adapter *i2c, struct mc44s803_config *cfg) { struct mc44s803_priv *priv; u32 reg; u8 id; int ret; reg = 0; priv = kzalloc(sizeof(struct mc44s803_priv), GFP_KERNEL); if (priv == NULL) return NULL; priv->cfg = cfg; priv->i2c = i2c; priv->fe = fe; if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 1); /* open i2c_gate */ ret = mc44s803_readreg(priv, MC44S803_REG_ID, &reg); if (ret) goto error; id = MC44S803_REG_MS(reg, MC44S803_ID); if (id != 0x14) { mc_printk(KERN_ERR, "unsupported ID (%x should be 0x14)\n", id); goto error; } mc_printk(KERN_INFO, "successfully identified (ID = %x)\n", id); memcpy(&fe->ops.tuner_ops, &mc44s803_tuner_ops, sizeof(struct dvb_tuner_ops)); fe->tuner_priv = priv; if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 0); /* close i2c_gate */ return fe; error: if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 0); /* close i2c_gate */ kfree(priv); return NULL; } EXPORT_SYMBOL_GPL(mc44s803_attach); MODULE_AUTHOR("Jochen Friedrich"); MODULE_DESCRIPTION("Freescale MC44S803 silicon tuner driver"); MODULE_LICENSE("GPL");
linux-master
drivers/media/tuners/mc44s803.c