A camera sensor boots only if the driver powers it in the right order. Fill in a driver, bind it with a device tree, and watch one stream start after 6.2 ms of mandatory waiting.
On a Linux board, a camera is a chip on an I2C bus with three power rails, a clock and a reset pin. The kernel only sees a picture after a small driver has brought all of that to life.
Press Start the stream, then break the driver one way at a time. Watch which step fails and what the symptom looks like. Then we build, piece by piece, every part of the driver you just broke.
You need a rough idea of what a driver is (code that lets an operating system talk to a chip) and a little C. We build the rest from zero.
Built from the Linux kernel’s own sensor-driver documentation and the real Sony IMX219 driver, drivers/media/i2c/imx219.c, written by Dave Stevenson. Part of the Firmware from Zero to Expertise series. Sources are listed in the Field Guide.
A model, not a real board. The 6.2 ms wait is the real constant in the IMX219 driver (200 µs plus 6,000 µs from the sensor datasheet timing). The other step times are illustrative.
Chapter 0
See why a sensor chip stays silent until a driver powers, clocks, resets and configures it in order
You wire a small camera board to a Linux board with a ribbon cable. You power on. You type ls /dev/video* and the board answers that no such file exists. The camera has power. The cable is seated. Nothing happens.
This is the normal first day with a camera sensor. A camera sensor is a chip with a grid of light-sensitive cells and some control logic. It does not wake up when you plug it in. It waits for someone to switch on its power rails, feed it a clock, release its reset pin and write its settings over a small serial bus. That someone is a driver: a piece of kernel code that knows how to talk to one kind of chip.
The hero showed ten steps. Break any one of them and the stream does not start. This lesson builds each step, in the order the kernel runs them. By the end you can read a real driver, the Sony IMX219 sensor driver in the Linux tree, and say what every call does.
A picture needs several pieces to cross the board. Start at the glass and walk toward the app.
The sensor chip sits behind the lens. It has an I2C control port (a two-wire bus for reading and writing small registers), power inputs, a clock input, a reset pin and a MIPI CSI-2 output (a fast serial link that carries pixels on one or more pairs of wires called lanes). The earlier lesson Sensor Bring-Up shows that side on a virtual bench.
On the other end of the CSI-2 link sits a receiver, often called the bridge driver in Linux. It is part of the SoC (system on a chip, the main processor). It catches the pixels, writes them to memory with DMA and presents them as a video device. The SoC vendor writes this driver. You usually do not.
Between them sits your code: the sensor subdev driver. A subdev is the Linux name for a part of a video pipeline that is not the final video device. The sensor is one subdev. The receiver asks it to start and stop, to report its image size and to change exposure.
Above the kernel sits user space. A program opens /dev/video0 and calls ioctl (a system call that sends a command to a driver). The planned Linux lessons on the device model, on writing a driver and on the V4L2 buffer queue cover that API. Here we need only one fact: V4L2 (Video for Linux 2) is the kernel’s interface for cameras, and the sensor subdev is the piece of it you write.
Six layers, top to bottom. The line between the first two is the kernel and user space boundary. Pick a layer to see who writes it and what it must do.
The line count is the IMX219 driver file as it stood in the Linux master tree when this lesson was written: 1,367 lines, of which the part you write for a new sensor is the same shape but a different register list.
Sensors differ. One chip uses 16-bit register addresses and another uses 8-bit. One wants three rails in a fixed order and another does not care. One needs 6.2 ms after reset and another needs 20 ms. The kernel solves this with one small driver per chip family and one shared set of rules for how a driver presents itself. Everything above the driver sees the same V4L2 shape.
The device tree solves the other half. The driver knows the chip. It does not know your board: which I2C bus the chip is on, which pin resets it, which regulator makes its analog rail, how many CSI-2 lanes are wired. A device tree is a text file that describes the board to the kernel. Chapter 2 writes the node for the IMX219.
Take two boards that carry the same IMX219. Board A runs the sensor from a fixed 24 MHz crystal oscillator and uses two CSI-2 lanes. Board B uses four lanes and a clock that the SoC generates. The driver file is the same on both. Only the device tree node changes: the number of lanes, the link frequency, the clock reference. This is the point of the design. One tested driver, many boards.
Now count what a bad day costs. If the driver hard-coded Board A’s lane count, Board B would show a black frame with no error message. The device tree makes the choice visible and checkable. The binding file (the schema for the node) even lists link-frequencies as required for this sensor, so a missing value fails at build time instead of at the bench.
You will not run firmware on a chip here. A browser cannot do that. Each device in this lesson is an honest model: a sequence diagram, a log, a register inspector. The code is real, taken from the Linux IMX219 driver. Each chapter ends with an “On real hardware” note that names a board and a measurement to repeat.
The road below follows the order in which the kernel runs your driver.
On real hardware. On a Raspberry Pi with an IMX219 camera, or any board whose kernel includes the driver, run dmesg | grep -i imx219 after boot. A healthy start prints nothing alarming. A failed one prints an error from the probe function. Note the exact line. We will learn to read it by Chapter 8.
Chapter 1
Match a device tree node to a driver by compatible string and watch probe run
The board boots. Early in start-up the kernel reads a small binary file, the device tree, and finds a line that says: on I2C bus 1, at address 0x10, there is a device called sony,imx219. The kernel has never heard of your sensor in any special way. It has a list of drivers and a list of devices. Its job is to pair them.
This is the Linux device model. A bus (here, I2C) holds a list of devices that exist and a list of drivers that are loaded. Whenever either list grows, the bus tries every pairing. When a driver says “I can handle this device”, the kernel calls the driver’s probe function with the device. Probe is where your driver starts to work. A driver does nothing else until probe runs.
How does a driver say what it can handle? With a table of compatible strings. A compatible string is text such as sony,imx219: a vendor name, a comma, a chip name. The device tree node carries one. The driver carries a table. If a string in the node equals an entry in the table, the pair matches.
c (from drivers/media/i2c/imx219.c)static const struct of_device_id imx219_dt_ids[] = { { .compatible = "sony,imx219" }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(of, imx219_dt_ids); static struct i2c_driver imx219_i2c_driver = { .driver = { .name = "imx219", .of_match_table = imx219_dt_ids, .pm = &imx219_pm_ops, }, .probe = imx219_probe, .remove = imx219_remove, }; module_i2c_driver(imx219_i2c_driver);
Read it from the bottom. module_i2c_driver registers the driver with the I2C bus when the module loads. The struct names two functions the kernel will call, probe and remove. The table holds one compatible string. The final empty entry is a sentinel, a marker that says the table ends here.
The string must match exactly. imx219 without the vendor prefix does not match. sony,imx291 is a different chip and matches a different driver. A single wrong character leaves the device without a driver, and the kernel stays silent. It has no way to know you meant something else.
Choose the compatible string and the address in the node. Toggle the regulator driver to see deferral. Then press Boot the board and read the log.
A model of the Linux bus-matching rules. The error number 517 for deferral and the IMX219 driver’s own messages are real. Timestamps and the exact kernel wording around them are illustrative.
Here is a trap that catches every new driver author. At boot, devices appear in no fixed order. Your sensor may be found before the regulator driver that powers it has loaded. When probe asks for a regulator that does not exist yet, it must not fail for good.
Instead probe returns a special error, -EPROBE_DEFER (the number is -517). It means “a supplier is not ready; try me again later”. The kernel puts the device on a waiting list. Each time any other driver binds, it retries. Eventually the supplier appears and probe succeeds. The IMX219 driver reports most failures through dev_err_probe, which returns the error and stays quiet when the error is a deferral.
The helpers that fetch resources, such as devm_regulator_bulk_get, carry a second idea. The devm_ prefix means device-managed: the kernel frees the resource for you when the device goes away or when probe fails. You write the happy path, and cleanup is automatic. Without devm_ you must undo every step by hand on every error path.
The IMX219 probe function does these things, and the rest of this lesson takes them one at a time. First it allocates its state and calls v4l2_i2c_subdev_init. It checks the hardware description. It creates a register map. It gets the clock, then the regulators, then the reset pin. It powers the chip, reads the chip ID, builds its controls, sets up its pad, and finally registers itself. The order matters: you cannot read a register before power, and you must not announce the sensor to the receiver before it is complete.
A worked failure shows why. Suppose the node says reg = <0x11> but the chip answers at 0x10. The compatible string matches, so probe runs. Probe powers the chip and reads register 0x0000, the chip ID. Nothing at 0x11 acknowledges, the read fails, and the driver prints failed to read chip id 219. The number 219 is the expected ID, 0x0219, printed in hex. Probe returns an error and the sensor never registers.
Notice what this tells you. A silent boot means the match failed: look at the compatible string. A printed chip ID message means the match worked and the wire did not: look at the address, the power and the reset.
On real hardware. On a Raspberry Pi or any Linux board with an I2C camera, list /sys/bus/i2c/devices/. Find the entry that ends in -0010. If it has a driver link inside, the match worked. If it has none, the compatible string or the driver module is missing. Repeat the check after you change the node.
Chapter 2
Describe the board once and see which driver call reads each property
You are the board author. A teammate hands you a schematic. The sensor has an I2C port wired to bus 1, a 24 MHz oscillator on its clock pin, three voltage regulators on its power pins, a GPIO wired to its reset pin and two CSI-2 lanes going to the SoC. The driver exists. Your job is to write down these facts in a form the driver can read.
That form is the device tree: a tree of nodes, where each node is one piece of hardware and each line inside it is a property, a name with a value. The kernel parses it at boot and gives each driver a view of its own node. The device tree holds no code. It holds facts about the board. The Linux embedded Linux lesson shows the whole file; the planned Linux lessons on the device model cover the syntax in depth. For firmware engineers used to a board support package, this is the same job in another format: the file that says which pin goes where. The lesson Zephyr in Practice shows the same idea in another RTOS.
How does a board author know which properties to write? A binding is the written contract between a driver and its device tree nodes. In today’s kernel it is a YAML schema file, and a tool checks every node against it at build time. For the IMX219 the file is Documentation/devicetree/bindings/media/i2c/sony,imx219.yaml. It lists seven required properties at the top level (compatible, reg, clocks, three supplies and port) and one more inside the endpoint (link-frequencies). That is eight.
Now read a real node, the example from that binding. Each line below is tied to one call in the driver.
Tap a line to see who reads it. Press Remove this property to see what breaks. The reset pin number is illustrative; every other line is the binding’s own example.
Property names, required lists and voltages come from the binding file for sony,imx219. The consequence lines come from the driver source. A real build runs the schema checker (dt_binding_check); this device only counts the required properties.
compatible is the match key from Chapter 1. reg = <0x10> is the I2C address. The binding says the address is fixed at 0x10 by the sensor datasheet, so the I2C core reads this value to create the device on the bus, and the node is named sensor@10 after it.
clocks points at a clock source with a phandle, a reference written as &label that names another node. The driver asks the clock framework for that clock. Then it checks the rate. The driver accepts only 24,000,000 Hz and refuses anything else with xclk frequency not supported. The kernel documentation is blunt about why: the clock comes out of the SoC, and only the frequencies the system was designed for are safe. On a device tree system, the node can pin the frequency with assigned-clock-rates.
The three supply lines are the key to power. The property name is VANA-supply: the name the driver passes, VANA, plus the suffix -supply. The driver holds an array of three names, VANA, VDIG and VDDL, and the regulator framework turns each into a property lookup. The binding gives the voltages: 2.8 V for the analog supply, 1.8 V for digital I/O and 1.2 V for the digital core. Misspell the property and the lookup finds nothing.
reset-gpios is optional. The driver fetches it with devm_gpiod_get_optional, which returns an empty pointer when the property is missing. The binding says to release the pin, setting it high, only after all supplies are applied. If your board ties the reset pin to a rail and has no GPIO, you leave the line out and the driver adapts.
The port and endpoint nodes describe the CSI-2 link. data-lanes = <1 2> means two lanes. The binding says four lanes are assumed if the line is missing, and that the two-lane form must be exactly <1 2>. link-frequencies gives the lane clock in hertz. The example uses 456,000,000. The driver checks the number against its own short list and refuses to probe on a frequency it does not know: Link frequency not supported. The remote-endpoint line points at the receiver’s endpoint, so the two drivers can find each other. Chapter 5 uses it.
Count what a lazy node would lose. Remove VDDL-supply and the schema check reports one missing required property: seven of eight present. Remove reset-gpios and the check still passes, because that line was never required. Which is worse? The second. The build is green, the driver loads, and the sensor never gets a proper reset. The failure appears later as a sensor that works on some cold boots and not on warm ones.
A startup delay belongs in the tree too. The driver comment says the delay for the supplies is not part of the driver: with a fixed regulator you describe it with the startup-delay-us property. The driver adds its own 6.2 ms wait after the reset pin rises, and not a microsecond for the rails. Chapter 3 shows why that split exists.
On real hardware. On a Raspberry Pi 4 or any board with a camera connector, run dtc -I fs -O dts /proc/device-tree and find the sensor node, or look in /sys/firmware/devicetree/base. Compare every property with the list above. Check one at a time with a multimeter: the 2.8 V analog rail must read 2.8 V with the board powered.
Chapter 3
Power the sensor up in a safe order and wait the time its datasheet demands
Picture a sleepy person at 6 a.m. You can shout questions at them the moment they sit up, but the answers will be nonsense. A sensor chip is the same. After you give it power and release its reset pin, it spends a few milliseconds starting its internal circuits. A write sent too soon is lost, or worse, half-applied.
The driver’s job in this chapter is a three-part ritual: switch on the power rails, start the clock, release the reset pin, then wait. Each part uses a different kernel framework. The kernel calls them regulator, clock and GPIO. Here is each in plain words.
A regulator is a chip or circuit that makes a steady voltage. The regulator framework lets a driver ask for one by name and switch it on and off. Your driver does not know whether the rail comes from a power management chip or a fixed supply. It calls regulator_bulk_enable and the framework does the right thing. “Bulk” means an array of several supplies handled in one call.
The clock framework gives a driver a handle to a clock signal and lets it switch the signal on with clk_prepare_enable. The sensor needs an external clock, called XCLK, from which its internal PLL builds the fast clocks. For the IMX219 this input is 24 MHz.
A GPIO (general-purpose input/output) is a pin the CPU can drive high or low. The modern kernel API, gpiod, works with logical levels: 1 means “asserted”, and the device tree flag says whether asserted is physically high or low. The sensor’s reset input is named XCLR. Held low, the chip is in reset. Driven high, it runs.
c (from drivers/media/i2c/imx219.c)static int imx219_power_on(struct device *dev) { /* ...to_imx219(sd) lookup... */ ret = regulator_bulk_enable(IMX219_NUM_SUPPLIES, imx219->supplies); if (ret) return ret; ret = clk_prepare_enable(imx219->xclk); if (ret) goto reg_off; gpiod_set_value_cansleep(imx219->reset_gpio, 1); /* XCLR high: leave reset */ usleep_range(IMX219_XCLR_MIN_DELAY_US, /* 6200 */ IMX219_XCLR_MIN_DELAY_US + IMX219_XCLR_DELAY_RANGE_US); /* +1000 */ return 0; reg_off: regulator_bulk_disable(IMX219_NUM_SUPPLIES, imx219->supplies); return ret; }
Read the order: rails, clock, reset, wait. The driver comment next to the supply names says the supplies “can be enabled in any order” for this sensor. Other sensors do not allow that, and their datasheets give a sequence. The error path undoes only what succeeded: if the clock fails, the label reg_off switches the rails back off. The power-off function runs the reverse: reset low, rails off, clock off.
The driver does not guess its delay. A long comment in the source derives it from three datasheet times. After XCLR goes high, the sensor needs t4, then the larger of t5 and (t6 plus the time the I2C writes take). In the comment, t4 is at most 200 µs, t5 is fixed at 6,000 µs, and t6 is up to 32,000 clock periods of the external clock.
The datasheet allows the external clock to run from 6 MHz to 27 MHz. So t6 ranges from 32,000 / 27 MHz = 1,185 µs to 32,000 / 6 MHz = 5,333 µs. Both are less than t5. So t5 always wins, and the safe wait is t4 + t5 = 200 + 6,000 = 6,200 µs. That is IMX219_XCLR_MIN_DELAY_US.
The scope shows the reset pin rising at 0 ms. Drag the first I2C write earlier or later. Change the external clock to see where t6 lands. Blue is the sensor’s start-up window; the yellow line is the wait the driver uses.
t4 (at most 200 µs), t5 (6,000 µs) and t6 (at most 32,000 clock periods) are the values in the IMX219 driver comment, taken from the sensor datasheet. Whether a too-early write is lost is the driver comment’s warning; the exact failure on your chip is for the bench to show.
Try it. At 24 MHz, t6 is 32,000 / 24 MHz = 1,333 µs. Drag the clock to 6 MHz and t6 grows to 5,333 µs, still short of t5. Now drag the write to 3 ms: you are inside t5, 3.2 ms short of the 6.2 ms mark. That write may be lost.
The delay uses usleep_range, which takes a minimum and a maximum. The kernel may wake the thread anywhere inside that window, and it uses the slack to merge timers and save power. The driver asks for 6,200 to 7,200 µs. The minimum is the safe wait. The maximum is the price you accept for efficiency. A plain udelay would burn the CPU for 6 ms and add nothing.
A camera that stays powered all day wastes the battery. The kernel offers runtime PM (runtime power management): a counter per device. When the count rises from zero, the kernel calls the driver’s resume callback to power the device up. When it falls to zero, the kernel calls the suspend callback after an optional delay.
The sensor documentation in the kernel states the rules. Drivers must use runtime PM, enable it at probe, disable it at remove, and enable autosuspend. The callbacks handle clocks, regulators and GPIOs. A driver takes a reference with pm_runtime_resume_and_get when streaming starts and drops it with pm_runtime_put_autosuspend when streaming stops. The IMX219 driver registers its two power functions as the runtime callbacks and sets the autosuspend delay to 1,000 ms. After you stop streaming, the rails stay up for one more second in case you start again at once. Then they drop.
One failure here deserves a name. Suppose you stop and restart a stream, and the second start fails. Symptom: the first capture works and a later one prints an I2C error. Measurement: probe the 2.8 V rail with a scope across the stop; it drops after the 1,000 ms delay, then the next start does not wait for it to ramp. Fix: keep the wait in power_on, not in probe, so every power-up pays it.
A last trap is the reset polarity. A normal reset pin is asserted when the logical value is 1. XCLR is the opposite: logical 1 here means “pin high, running”. The driver carries a comment that says exactly this, and warns not to copy it. When you write a new driver, define reset in the device tree flags so that logical 1 means reset asserted, and write the sequence to match your sensor’s datasheet.
On real hardware. On a Raspberry Pi with an IMX219 module, or any board with a scope, probe the XCLR line and an I2C SDA line together. Trigger on the XCLR rising edge. Measure the time to the first I2C start condition. It should be at least 6.2 ms. Then stop the stream and time how long the rail stays up: about 1 s.
Chapter 4
Turn a named register and a value into the exact bytes on the I2C wire
The sensor is awake. You want to set its exposure to 1,600 lines. In the datasheet, exposure lives in a 16-bit register at address 0x015A. In your C code you want to write one line, not count bytes. And you want that line to put exactly the right bytes on the I2C wire, in the right order.
A register is a small memory cell inside a chip, with an address, that controls one feature. A sensor has hundreds. Setting up a mode means writing dozens. This chapter shows how the driver names registers once and lets a library turn each write into bytes.
I2C is a two-wire bus. The controller (the SoC) drives the clock line and starts every transfer. The target (the sensor) answers. Every byte is eight bits followed by one acknowledge bit, so each byte costs nine clock pulses. The first byte of a transfer is the 7-bit target address shifted left, with the lowest bit saying write (0) or read (1). The IMX219 sits at 0x10, so a write starts with 0x20 and a read with 0x21.
This sensor has 16-bit register addresses. So a write is: the address byte, the high byte of the register address, the low byte, then the data bytes. Writing 0x0640 to register 0x015A sends 0x20, 0x01, 0x5A, 0x06, 0x40. Five bytes. A read sends the address first, then restarts the bus with a read address and clocks the data out.
Every I2C chip has the same chores: format the address, order the bytes, retry, report errors. regmap is the kernel library that does them. You describe the bus once (here, 16-bit register addresses and 8-bit values), and regmap turns read and write calls into transfers.
Camera sensors add a wrinkle: registers come in different widths, 8, 16 and sometimes 24 or 32 bits, mixed on one chip. The kernel has a helper for this, CCI (the Camera Control Interface, a MIPI standard for sensor registers over I2C). Its header packs the register width into the constant that names the register. The driver defines each register once:
c (from drivers/media/i2c/imx219.c)/* name = CCI_REG{bytes}(address) */ #define IMX219_REG_CHIP_ID CCI_REG16(0x0000) #define IMX219_REG_MODE_SELECT CCI_REG8(0x0100) #define IMX219_REG_ANALOG_GAIN CCI_REG8(0x0157) #define IMX219_REG_EXPOSURE CCI_REG16(0x015a) imx219->regmap = devm_cci_regmap_init_i2c(client, 16); /* 16-bit addresses */ cci_write(imx219->regmap, IMX219_REG_EXPOSURE, 1600, &ret); cci_read(imx219->regmap, IMX219_REG_CHIP_ID, &val, NULL);
Under the macro, bits 16 to 19 hold the width in bytes and bits 0 to 15 hold the address. For a 16-bit register the helper puts the high byte first (big-endian), unless the name uses the _LE form. Then it calls regmap_bulk_write. The regmap was created with reg_bits 16 and val_bits 8, so every value is a list of bytes.
Look at the last argument of cci_write. It is an error pointer. If an earlier call already stored an error there, the next call returns it at once without touching the bus. So you can write a long run of registers and check once at the end. The control handler in Chapter 6 uses this.
Pick a register operation and set a value. Each box is one byte on the I2C wire. Then switch on the byte-order bug to see what the sensor would store.
Register names, addresses and widths are the IMX219 driver’s. The target address 0x10 is from the binding. Timing assumes the 400 kHz fast mode (2.5 µs per clock pulse), ignores the start and stop conditions, and is a calculation, not a measurement.
Choose Write EXPOSURE with the value 1,600. In hex that is 0x0640. The high byte is 0x06 and the low byte is 0x40. The bytes are 0x20 (address 0x10, write), 0x01, 0x5A (register address 0x015A), 0x06, 0x40. That is five bytes, 45 clock pulses, 112.5 µs at 400 kHz.
Now switch on the wrong byte order. The two data bytes swap: 0x40 then 0x06. The sensor reads them as 0x4006, which is 16,390. The driver set exposure to 1,600 lines and the sensor got ten times that. The frame is only about 3,500 lines tall, so the exposure is far out of range. The picture will be washed out or the sensor will clamp the value.
Real sensors need dozens of settings before they stream. The IMX219 driver keeps them in a table of pairs, imx219_common_regs. It has 23 entries. Some set the mode select register to standby, six unlock a hidden register range, twelve are marked undocumented in the driver (values from the vendor), two set pixel skipping, one sets the PHY timing mode and one writes the external clock frequency. That last entry is 24 times 256 = 6,144 = 0x1800, written to register 0x012A: the sensor must be told its own input clock.
Count the cost. Twenty-two of the 23 entries are 8-bit writes of four bytes each: 36 clock pulses, 90 µs. One is a 16-bit write of five bytes: 112.5 µs. The table takes 22 × 90 + 112.5 = 2,092.5 µs, about 2.1 ms at 400 kHz, before software overhead. At 100 kHz it takes four times longer, about 8.4 ms. The bus speed is a number your device tree and the I2C controller set, and it adds to the start-up time of every stream.
Why a table and not code? A table is easy to diff against the vendor’s list. It is data, not logic. Each mode (full size, 1080p, binned) is another small table. The driver loops over the arrays with cci_multi_reg_write.
The first thing probe does after power-up is read the chip ID register, 0x0000, and compare the value with 0x0219. This single read proves three things at once: the address in the device tree is right, the power sequence worked, and the register width and byte order are right. If the ID reads as 0x1902, you have swapped the bytes. If the read fails, nothing answered. Symptom: the message failed to read chip id or chip id mismatch. Measurement: put a logic analyzer on SDA and SCL and look for the 0x20 address byte and its acknowledge. Fix: address, power or reset first; byte order second.
On real hardware. On a Raspberry Pi with an IMX219, run i2cdetect on the camera I2C bus while the camera is powered. A device at 0x10 is the sensor. If the bus is quiet, return to Chapter 3. Then read two bytes from register 0x0000 with i2ctransfer and confirm 0x02 0x19. Do this only with the driver unloaded, so two programs do not share the chip.
Chapter 5
Register the sensor so the receiver driver finds it, whichever probes first
Your sensor is powered, identified and talking. But no one else in the kernel knows it exists. The receiver driver on the SoC wants a camera, and it has no list to look through. Two drivers must find each other, and either one may probe first.
This chapter is about that introduction. It has four parts: the subdev object, the pad it exposes, the formats that cross that pad, and the asynchronous registration that joins the two drivers.
A v4l2_subdev is a small kernel structure that stands for one block of a video pipeline. Your driver embeds one in its own state structure, and fills it with a table of functions, the ops. The kernel documentation groups the ops by area: core, video, pad and others. A bridge calls an op through a macro that checks for a missing function and returns an error instead of crashing.
The IMX219 fills two groups. The video group has one entry, s_stream, set to a kernel helper that turns the older call into the newer enable_streams. The pad group has seven: list the pixel codes, list the frame sizes, get a format, set a format, get a crop rectangle, enable streams and disable streams. That is the whole interface the receiver needs.
c (from drivers/media/i2c/imx219.c)static const struct v4l2_subdev_pad_ops imx219_pad_ops = { .enum_mbus_code = imx219_enum_mbus_code, .get_fmt = v4l2_subdev_get_fmt, .set_fmt = imx219_set_pad_format, .get_selection = imx219_get_selection, .enum_frame_size = imx219_enum_frame_size, .enable_streams = imx219_enable_streams, .disable_streams = imx219_disable_streams, };
The media controller describes a camera pipeline as a graph. Each block is an entity. Each entity has pads, its connection points, and a pad is either a source (output) or a sink (input). A link joins a source pad to a sink pad. Your sensor has one entity, flagged as a camera sensor, with one source pad. The probe code sets both with two lines.
What flows through a link is a media bus format: a pixel code plus a width and height. The IMX219 offers 10-bit raw codes first, with names such as MEDIA_BUS_FMT_SRGGB10_1X10, and 8-bit raw codes after them. In that name, S means sensor raw, RGGB gives the colour filter order, 10 is the bits per pixel and 1X10 means one 10-bit sample per bus cycle. A table lists four codes for each depth, because a horizontal or vertical flip changes which colour comes first. Flip the image and the Bayer pattern changes name.
Size comes from a mode table. The first mode is 3,280 by 2,464. Others are 1,920 by 1,080, 1,640 by 1,232 and 640 by 480. When the receiver asks for a size, set_fmt picks the nearest listed mode with v4l2_find_nearest_size and returns what it chose. A sensor that cannot do the requested size says so by answering with a different one. It does not fail.
Now the hard part. On a device tree system, the sensor and the receiver are separate nodes, found at separate times. Neither knows whether the other has probed. The kernel solves this with asynchronous registration.
The sensor calls v4l2_async_register_subdev_sensor as the last step of probe. This puts the finished sensor on a global list. The receiver driver, as the bridge, creates a notifier: a waiting request that names the firmware node of the remote endpoint, the very remote-endpoint line from Chapter 2. When the sensor shows up on the list, or when a notifier appears that matches a sensor already waiting, the two bind. When every awaited subdev has bound, the notifier completes, links are created, and the device nodes appear. The kernel documentation also states a rule: do all initialization of the sub-device before this call, because the moment you register, someone may use it.
Choose who probes first, then press Next event to step through the boot. Watch the graph form only when both sides are present.
A model of the async notifier rules in the kernel documentation. Event wording is illustrative. The three boot orders are all legal on a device tree system.
Run all three. The count of events differs (five, four and five) but the final graph is the same: sensor source pad to receiver sink pad to the video node. That is the design goal. Your driver must not depend on being first.
Two flags in probe make the sensor visible to tools. One makes the kernel create a device node for it, /dev/v4l-subdevX, so that programs such as v4l2-ctl can reach it directly. The other sets the entity function to MEDIA_ENT_F_CAM_SENSOR, so media-ctl -p labels the box as a camera.
Symptom: the sensor probes cleanly and prints no error, yet there is no /dev/video0. Measurement: run media-ctl -p. If the sensor entity is listed but has no link, the receiver never bound it. Check the device tree: the sensor’s endpoint must point at the receiver’s endpoint, and the standard graph binding normally writes remote-endpoint on both sides. Also check that the receiver’s own driver is loaded. Fix: correct the graph links; no change to the sensor driver is needed.
On real hardware. On a Raspberry Pi with a camera, run media-ctl -p and find the entity named like imx219 10-0010. Note its pad, its format and the link flags. Then run dmesg and find the line where the notifier completes. Count the seconds from boot to that line.
Chapter 6
Expose the knobs a camera app turns and keep their limits honest
A user opens a camera app. The picture is too dark. They drag a slider. A second later the picture is brighter. Somewhere a number changed in a sensor register. The question for the driver is: how did the slider find the register, and what stops the user from typing a value the chip cannot take?
The answer is the V4L2 control framework. A control is a named knob with an ID, a minimum, a maximum, a step and a default. The driver declares its knobs once. The framework stores their values, checks every new value against the limits, and calls one function of the driver when a value changes. Apps discover the knobs by asking the device what controls it has.
Probe calls v4l2_ctrl_handler_init to create a handler, the container for the controls. Then it adds each knob with v4l2_ctrl_new_std. The IMX219 declares, among others:
c (from drivers/media/i2c/imx219.c)ctrl_hdlr = &imx219->ctrl_handler; ret = v4l2_ctrl_handler_init(ctrl_hdlr, 12); /* read-only: tell the receiver how fast pixels leave the sensor */ imx219->pixel_rate = v4l2_ctrl_new_std(ctrl_hdlr, &imx219_ctrl_ops, V4L2_CID_PIXEL_RATE, rate, rate, 1, rate); imx219->exposure = v4l2_ctrl_new_std(ctrl_hdlr, &imx219_ctrl_ops, V4L2_CID_EXPOSURE, 4, exposure_max, 1, exposure_def); v4l2_ctrl_new_std(ctrl_hdlr, &imx219_ctrl_ops, V4L2_CID_ANALOGUE_GAIN, 0, 232, 1, 0); /* the handler.error field collects every failure above */
Look at the pixel-rate control. Its minimum, maximum and default are all the same number. That makes it a constant, and the driver marks it read-only. The receiver reads it to learn how fast data will arrive. For two lanes the number is 182,400,000 pixels per second. You can verify that from the device tree: a link frequency of 456 MHz, double data rate (two bits per clock) on two lanes, gives 456 × 2 × 2 = 1,824 Mbit/s. At 10 bits per pixel, that is 182.4 Mpixel/s.
The handler also collects errors. If any call fails, the handler records it, and probe checks ctrl_hdlr->error once at the end. This is the same trick as the error pointer in Chapter 4.
Sensors do not stream pixels back to back. After each line they idle for a few clocks, the horizontal blanking (hblank). After each frame they idle for a few lines, the vertical blanking (vblank). These idle periods are not wasted. They give the receiver time to finish a line and give the sensor time to reset. And they are the knob that sets the frame rate.
Work it with the defaults. The line length is 3,280 + 168 = 3,448 pixels. The frame length is 2,464 + 1,062 = 3,526 lines. One frame holds 3,448 × 3,526 = 12,157,648 pixel clocks. At 182.4 million per second that is 66.7 ms, or 15.0 fps. This matches the “8 MPix 15 fps” comment in the driver’s mode table. One line takes 3,448 / 182.4 MHz = 18.9 µs.
The bar is one frame. Blue is the image readout, grey is vertical blanking, and the yellow bracket is the exposure. Drag vblank down for a faster frame, then watch the exposure limit follow.
The mode (3,280 by 2,464), pixel rate (182.4 MHz, two lanes), the blanking limits (vblank at least 32; hblank from 168 in steps of 8) and the exposure rule (frame length minus 4 lines) are from the IMX219 driver. The slider ranges here are shortened. Frame-rate numbers are computed, not measured.
Drag vblank to 32. The frame length falls to 2,496 lines and the rate rises to 182.4 MHz / (3,448 × 2,496) = 21.2 fps. Watch the exposure slider: its maximum falls from 3,522 to 2,492 lines. Exposure may never exceed the frame, less 4 lines. The driver enforces this. When vblank changes, s_ctrl calls __v4l2_ctrl_modify_range on the exposure control with the new maximum, and the framework clamps the value for you.
Every write goes through one switch. The framework has already checked the limits. The function writes the right register:
c (from imx219_set_ctrl, trimmed)/* only touch the chip if it is powered and streaming */ if (pm_runtime_get_if_in_use(&client->dev) == 0) return 0; switch (ctrl->id) { case V4L2_CID_EXPOSURE: cci_write(regmap, IMX219_REG_EXPOSURE, ctrl->val / rate_factor, &ret); break; case V4L2_CID_VBLANK: cci_write(regmap, IMX219_REG_FRM_LENGTH_A, (format->height + ctrl->val) / rate_factor, &ret); break; } pm_runtime_put(&client->dev);
The first lines hold the key rule. If the sensor is powered down, pm_runtime_get_if_in_use returns zero and the function returns without touching the bus. The new value is still stored in the framework. It reaches the chip later, when streaming starts and the driver replays every stored value (Chapter 7). The kernel documentation adds a warning: do not call the replay function from the runtime resume callback, because the callback cannot tell what the power state really is.
Failure: the user sets exposure before starting the stream, then sees the default exposure in the first frame. Symptom: the first frames ignore the setting. Measurement: add a trace on s_ctrl and see it return early with no I2C traffic. Fix: confirm the replay call runs in the enable-streams path, before the stream-on write.
On real hardware. On a Raspberry Pi with an IMX219, run v4l2-ctl -d /dev/v4l-subdev0 --list-ctrls and read the min, max and default of exposure, vertical_blanking and pixel_rate. Check them against the numbers above. Change vertical_blanking while streaming and watch the frame rate change.
Chapter 7
Step through the exact order of calls that turns an idle sensor into a video source
A user presses record. Half a second later frames flow. Between the press and the first frame, about a dozen things happen in a fixed order, in four layers of software and one chip. If you can say the order, you can debug any camera that fails to start.
This chapter is the sequence diagram promised in the hero, drawn one step at a time. Every step is a function you met in an earlier chapter.
The app calls VIDIOC_STREAMON on the video device. The kernel documentation says capture hardware is disabled, and no buffers are filled, until this call. The receiver driver starts its DMA engine and then asks every sensor upstream to start, through the subdev op enable_streams (the older s_stream op is routed there by a helper). From here the sensor driver owns the sequence.
Here is the real function, trimmed to its calls:
c (from imx219_enable_streams)ret = pm_runtime_resume_and_get(&client->dev); /* 1: power up if needed */ ret = cci_multi_reg_write(regmap, imx219_common_regs, 23, NULL); /* 2: init table */ ret = imx219_configure_lanes(imx219); /* 3: PLL + lane mode */ ret = imx219_set_framefmt(imx219, state); /* 4: crop, size, bit depth */ ret = __v4l2_ctrl_handler_setup(sd->ctrl_handler); /* 5: replay stored controls */ ret = cci_write(regmap, IMX219_REG_MODE_SELECT, IMX219_MODE_STREAMING, NULL); /* 6: stream on */ __v4l2_ctrl_grab(imx219->vflip, true); /* flips locked while streaming */ __v4l2_ctrl_grab(imx219->hflip, true); /* on any failure: pm_runtime_put_autosuspend() and return the error */
Step through it. Step 1 may do a lot or nothing. If the sensor was off, the runtime PM core calls the resume callback, which is imx219_power_on from Chapter 3: rails, clock, reset, and a wait of at least 6.2 ms. If the sensor is still on, because the last stream stopped less than the 1,000 ms autosuspend delay ago, this call returns at once.
Step 2 sends the 23 common registers, Chapter 4’s table. Step 3 sends the PLL settings and lane mode for the number of lanes in the device tree. For two lanes that is eight registers. Notice a link to Chapter 2: the table contains PLL multipliers 57 and 114. Work it: 24 MHz divided by the pre-divider 3 is 8 MHz, times 114 is 912 MHz, and half of that is 456 MHz, the link-frequencies value in the device tree. This is why the driver rejects any other link frequency. The tree and the register table must agree.
Step 4 writes the crop window, the output size, the binning and the bit depth: twelve registers. Step 5 replays every stored control, Chapter 6’s promise, so the first frame uses the exposure the user chose. Step 6 is a single write that flips the chip from standby to streaming. After it, the chip sends CSI-2 data, and the receiver sees its first start of frame.
Press Next step to run each call. The bar adds up the time. Then switch on Restarted within 1 s and run it again to see what autosuspend saves.
Register-write counts are from the IMX219 driver (23, 8 and 12 writes). Times are calculated at 400 kHz I2C from byte counts (Chapter 4), not measured. The 6.2 ms wait is the driver’s minimum. The control replay time (11 writes, about 1 ms) is an estimate. The frame time uses the default 15 fps timing from Chapter 6.
Run it cold. The steps add up to about 11.4 ms before the stream-on write completes: 6.2 + 2.09 + 0.77 + 1.28 + 1.0 + 0.09. Then the sensor must expose and read out its first frame, which at the default timing takes about 66.7 ms. So the first picture arrives roughly 78 ms after the app asked, and the kernel’s share is the first 11 ms. Run it warm: the 6.2 ms disappears and the start-up falls to about 5.2 ms.
Stopping is short. disable_streams writes standby to MODE_SELECT, releases the flip controls, and drops its PM reference with pm_runtime_put_autosuspend. The rails stay up for another second, then drop.
One real-world quirk shows up in probe. A comment in the IMX219 driver says the sensor does not enter the LP-11 state on power up until streaming has been started. LP-11 is the idle state of the CSI-2 wires, both lines high; the receiver waits for it before it expects a frame. So probe turns streaming on, waits 100 µs, turns it off, waits another 100 µs, and the lines then settle in LP-11. This is not in the datasheet logic you would guess. It is exactly the kind of fact a bring-up engineer finds with a scope.
Failure: the receiver times out on the first start after boot, then later starts work. Symptom: one failed capture with a timeout in the receiver log. Measurement: scope the CSI-2 clock and data pair at the receiver; the wires are not at the LP-11 idle level when STREAMON arrives. Fix: the start/stop pulse in probe. If a new sensor does this, the vendor reference driver usually has the same trick.
On real hardware. On a Raspberry Pi with an IMX219, run v4l2-ctl --stream-mmap --stream-count=1 -d /dev/video0 with a probe on the 2.8 V rail and the XCLR pin, or measure the call with strace -T. Time from the call to the first frame. Then repeat within one second and compare. The gap is the power-up cost you now understand.
Chapter 8
Fill in the skeleton yourself, then walk a symptom down to its layer
You now know every piece. Time to put them together. Imagine you receive a datasheet for a new sensor and an empty file. What goes where? This chapter has two jobs: assemble the probe function in the right order, then learn to walk a symptom down to the layer that caused it.
Probe is a recipe with strict ordering rules. Each rule comes from something you have already seen:
Below is the probe of the IMX219 with six calls left blank. Pick the right call for each line. Wrong picks explain themselves.
Six blanks. Choose a call for each, then press Check my driver. Green means right, red means wrong with a reason.
The skeleton follows imx219_probe in the Linux tree. Some unrelated lines (hardware config check, error labels) are left out to keep it short. Wrong options are plausible mistakes, not real driver code.
Suppose the new sensor has a different chip ID, an 8-bit register address, two supplies and a reset that is active low. What changes? Very little, and all of it is data. Change the chip ID constant. Change the register width argument in the regmap call, from 16 to 8. Change the supply name array to two names. Change the polarity of reset in your power functions and in the device tree flags. Replace the init table with the vendor’s list. The shape of probe, the ops, the controls and the streaming order stay the same. That is why drivers for different sensors look alike, and why the kernel docs point new authors at an existing driver like the IMX219 as the one to copy.
A camera that does not work gives you one fact: no picture. Your job is to find the layer. The trick is to move from the cheapest check to the dearest, and to ask of each layer one yes or no question.
Is there a driver bound? Is the chip powered? Does it answer? Does the link carry data? Does the graph exist? Do the controls reach the chip? Each question maps to a chapter. Pick a symptom below to see the layer, the measurement and the fix.
Pick what you see. The ladder lights the layer to check first.
The symptoms and fixes combine the driver messages quoted in Chapters 1 to 7 with standard bench practice. Which exact line your kernel prints depends on the driver and kernel version.
Work two examples. First: the chip ID read fails. The match worked (probe ran), the description is probably right, so the fault is at power or the bus. You put a scope on the 2.8 V analog rail and on XCLR. If the rail is 0 V, the regulator is not enabled: the supply in the device tree points at the wrong node. If the rail is fine and XCLR never rises, the reset pin is mis-declared. If both are fine, put a logic analyzer on SDA and look for an acknowledge on 0x20.
Second: the receiver times out though the chip ID reads fine. You have proven power and bus, so the fault lies after the register writes. Check the link frequency and lane count in the device tree against the PLL table (Chapter 7). A 2-lane board described as 4-lane gives a receiver that listens on lanes that carry nothing. Then scope the CSI-2 clock lane for activity after stream-on.
A good debug note records the layer and the measurement, not just the fix. The next sensor has the same layers.
On real hardware. On a Raspberry Pi with an IMX219, deliberately break one thing in an overlay: set reg to 0x11, then read the log. Restore it, and change link-frequencies to 400000000, then read the log again. Each change should print one of the messages in this lesson. Write down which.
Chapter 9
Keep the numbers, the checklist, the core code and the sources
A camera sensor driver is a short list of jobs done in a fixed order. The device tree states what the board has. Probe fetches clock, rails and reset, powers the chip, reads its ID, builds controls and a pad, and registers last. Runtime PM keeps the chip off until a stream starts. Streaming replays the register tables and the stored controls, then flips one register. Everything else is detail around that spine.
| What | Number | Why it matters |
|---|---|---|
| IMX219 I2C address | 0x10 (write byte 0x20, read byte 0x21) | Fixed by the sensor; goes in reg |
| Chip ID register | 0x0000 reads 0x0219 | First proof that power, address and byte order work |
| Supplies | VANA 2.8 V, VDIG 1.8 V, VDDL 1.2 V | Three -supply properties; any order for this sensor |
| External clock | 24,000,000 Hz (datasheet range 6 to 27 MHz) | The driver refuses any other rate |
| Reset to first I2C write | 6,200 µs minimum (t4 200 + t5 6,000) | t6 stays between 1,185 and 5,333 µs, so t5 always dominates |
| Autosuspend delay | 1,000 ms | A restart inside it skips the power-up |
| Init table | 23 common writes, about 2.1 ms at 400 kHz | Bus speed adds to every stream start |
| Link frequency, 2 lanes | 456 MHz; pixel rate 182.4 MHz | 456 × 2 × 2 / 10 bits; must match the PLL table |
| Full mode timing | 3,448 × 3,526 clocks = 15.0 fps; line 18.9 µs | Frame rate comes from blanking |
| Exposure range | 4 to frame length minus 4 lines (3,522 at default) | The driver changes the limit when vblank changes |
| EPROBE_DEFER | -517 | Means a supplier is not ready; the kernel retries |
| Term | Plain meaning | Chapter |
|---|---|---|
| compatible | The string that pairs a node with a driver | 1 |
| probe / devm_ | The start function; resources freed for you | 1 |
| binding | The written contract for a node’s properties | 2 |
| regulator, clock, gpiod | The frameworks for rails, clock and pins | 3 |
| runtime PM | A use counter that powers the device on demand | 3 |
| regmap / CCI | Register access with the width in the name | 4 |
| subdev, pad, entity | A pipeline block, its port, its graph node | 5 |
| async notifier | A wait that joins two drivers in either order | 5 |
| control, blanking | A named knob; idle time that sets frame rate | 6 |
| LP-11 | The idle state of CSI-2 wires | 7 |
c (the spine of imx219.c, trimmed)static int imx219_probe(struct i2c_client *client) { v4l2_i2c_subdev_init(&imx219->sd, client, &imx219_subdev_ops); imx219->regmap = devm_cci_regmap_init_i2c(client, 16); imx219->xclk = devm_v4l2_sensor_clk_get(dev, NULL); /* must be 24 MHz */ ret = devm_regulator_bulk_get(dev, 3, imx219->supplies); /* VANA VDIG VDDL */ imx219->reset_gpio = devm_gpiod_get_optional(dev, "reset", GPIOD_OUT_HIGH); ret = imx219_power_on(dev); /* rails, clock, XCLR, 6.2 ms */ ret = imx219_identify_module(imx219); /* 0x0000 == 0x0219 */ ret = imx219_init_controls(imx219); ret = media_entity_pads_init(&imx219->sd.entity, 1, &imx219->pad); pm_runtime_set_active(dev); pm_runtime_enable(dev); ret = v4l2_async_register_subdev_sensor(&imx219->sd); /* last */ pm_runtime_set_autosuspend_delay(dev, 1000); pm_runtime_use_autosuspend(dev); return 0; } static int imx219_enable_streams(struct v4l2_subdev *sd, ...) { ret = pm_runtime_resume_and_get(&client->dev); /* power on if needed */ cci_multi_reg_write(regmap, imx219_common_regs, 23, NULL); imx219_configure_lanes(imx219); imx219_set_framefmt(imx219, state); __v4l2_ctrl_handler_setup(sd->ctrl_handler); /* replay controls */ cci_write(regmap, IMX219_REG_MODE_SELECT, IMX219_MODE_STREAMING, NULL); return 0; }
Sensor drivers in Linux follow this shape for hundreds of chips. Two designs exist. A register-list-based driver such as the IMX219 keeps fixed mode tables. A freely configurable driver such as the CCS driver computes timings from the sensor’s capabilities. The kernel documentation names both as good examples, plus the IMX319. Above the sensor, the receiver, the ISP (image signal processor) and the 3A loop (auto exposure, white balance, focus) use the controls you published. On microcontrollers there is no driver model: the camera lives in your own code, as in the lesson on parallel cameras and JPEG.
The planned Physical AI lessons on the Linux device model, writing a driver, the V4L2 buffer queue, ISP and 3A, and multi-camera links will deepen the layers above and below this one.
These sources describe the IMX219 as a worked example. Your chip’s datasheet, not this lesson, sets your delays and registers. The in-page devices are models; the code and numbers are quoted from the sources above.
Now press Present or Teach and explain, from memory, what happens between VIDIOC_STREAMON and the first frame. Name each call, the chapter it came from and the time it costs. Then go back to the stream at the top, break the driver each of the four ways and say, before the diagram shows it, which step will fail.