Latest / CyberSecurity Summary / Linux Device Driver Development: Everything you need to start with device driver development for Linux kernel and embedded Linux
Transcript
- 0:00Speaker 1: Welcome to the deep dive. Today, we're jumping into the
- 0:03Speaker 1: Linux kernel, specifically how it handles hardware. If you've ever
- 0:07Speaker 1: wanted to write a device driver, or you know, just
- 0:10Speaker 1: understand how your keyboard actually talks to your OS, this
- 0:13Speaker 1: is for you. We're building the conceptual map exactly.
- 0:16Speaker 2: Our mission today is really about the architecture. We've looked
- 0:20Speaker 2: at some pretty comprehensive guides on kernel and driver development,
- 0:25Speaker 2: and we want to quickly lay out that core blueprint.
- 0:27Speaker 2: You know, what do you have to know? What's different?
- 0:29Speaker 2: How does the kernel see the world of devices?
- 0:31Speaker 1: Okay, so starting basic the device driver, it's fundamentally a
- 0:35Speaker 1: translator right sitting in the middle.
- 0:37Speaker 2: It's the crucial link. Yeah, it's that specialized code connecting
- 0:40Speaker 2: your apps, your user space stuff to the actual physical
- 0:43Speaker 2: hardware and it all goes to the kernel. You could
- 0:45Speaker 2: almost say it's the only bit of software allowed to
- 0:48Speaker 2: like directly touch the hardware ports.
- 0:50Speaker 1: Got it. Okay, So let's start where most drivers start,
- 0:53Speaker 1: the kernel module. This is how Linux stays flexible. Right,
- 0:56Speaker 1: Let's you add stuff without a.
- 0:57Speaker 2: Full reboot precisely, modules like you extend the kernel dynamically
- 1:02Speaker 2: at run time, and our sources. Definitely emphasize this isn't
- 1:07Speaker 2: for absolute beginners. You need solid C skills and to
- 1:10Speaker 2: be comfortable on the Linux command line before you really
- 1:13Speaker 2: dive into writing kernel code.
- 1:14Speaker 1: Right, So, if we're building one, we need the basic structure,
- 1:18Speaker 1: an entry point, and ideally an exit point.
- 1:21Speaker 2: That's the core. You use module in it that declares
- 1:25Speaker 2: the function that runs when your module gets loaded you
- 1:28Speaker 2: know withins modern mod probe. And then module exit declares
- 1:31Speaker 2: the cleanup function for when you unload it with a romedet.
- 1:34Speaker 1: Okay, now here's where it gets interesting. Compared to normal programming.
- 1:37Speaker 1: Memory optimization. Yeah, the kernel uses these macros in and exit.
- 1:42Speaker 1: Why are they so important? Ah?
- 1:43Speaker 2: Yeah, they're not just comments. There are instructions for the
- 1:45Speaker 2: compiler and linker really important. When you mark your in
- 1:49Speaker 2: it function within it, you're telling the linker put this
- 1:52Speaker 2: code in a special memory section.
- 1:54Speaker 1: And what's special about that section?
- 1:55Speaker 2: Well, if your module is built into the kernel statically compiled,
- 1:59Speaker 2: the kernel actually freeze that memory once the init function
- 2:02Speaker 2: is done, because, I mean, it's never going to call
- 2:04Speaker 2: that in it function again until the next reboot, right,
- 2:06Speaker 2: so why keep the code around. It's a smart optimization.
- 2:09Speaker 2: Use it, lose it.
- 2:10Speaker 1: That is clever proactively cleaning up its own startup code.
- 2:13Speaker 1: And exit is that the flip side pretty much? Yeah.
- 2:17Speaker 2: Exit tills the compiler to just leave out the exit
- 2:21Speaker 2: functions code entirely if the module is built in, because
- 2:24Speaker 2: if it's built in, you can unload it anyway, so
- 2:26Speaker 2: save space removes code you'd never run.
- 2:28Speaker 1: Okay, moving to metadata. Every module needs info like module author,
- 2:34Speaker 1: But the big one seems to be module license. Why
- 2:37Speaker 1: is that one so sensitive?
- 2:40Speaker 2: It really is. It's about the GPL and the kernel's ecosystem.
- 2:43Speaker 2: You must declare a GPL compatible license using module license,
- 2:47Speaker 2: especially if you want your module to use certain kernel functions,
- 2:50Speaker 2: ones that are specifically exported only for GPL modules using
- 2:53Speaker 2: exports symbol GPL.
- 2:54Speaker 1: And if you don't, or if you use a proprietary.
- 2:56Speaker 2: License, then boot your kernel gets more distainted. The kernel
- 2:59Speaker 2: sits a fly. It basically says warning, non open or
- 3:02Speaker 2: untrusted code has been loaded. If you then get a
- 3:05Speaker 2: crash a kernel panic, well good luck getting help from
- 3:09Speaker 2: the community. They'll likely see the taint flag and you know,
- 3:12Speaker 2: say they can't support it because proprietary code might be
- 3:15Speaker 2: the cause. It's a serious line.
- 3:17Speaker 1: Okay, that definitely sets the stage. Now let's make that
- 3:20Speaker 1: mental shift. We're not writing userspace programs anymore. We're inside
- 3:24Speaker 1: the kernel. The rules change, the safety nets.
- 3:27Speaker 2: Gone completely gone. In user space, if something goes terribly wrong,
- 3:31Speaker 2: your program crashes. The OS cleans up fine. In the kernel,
- 3:34Speaker 2: no way. If you allocate memory, grab an ieoport, whatever,
- 3:39Speaker 2: you must clean it up yourself before your function returns.
- 3:41Speaker 2: Fail to do that and your risk leaks instability, maybe
- 3:44Speaker 2: even a full system crash.
- 3:45Speaker 1: So error handling is totally different. No more just returning
- 3:48Speaker 1: zero for success and one for failure.
- 3:50Speaker 2: Right. The standard is really strict. Kernel functions that interact
- 3:53Speaker 2: with system calls. They must return errors as negative values
- 3:57Speaker 2: like return error code. So you'll see you're an AIO
- 4:00Speaker 2: for an IO error or an enulmum if you couldn't
- 4:03Speaker 2: get memory. It's a clear convention, so errors get passed
- 4:05Speaker 2: up correctly, and.
- 4:06Speaker 1: To manage that cleanup, especially if you have say five
- 4:09Speaker 1: steps that work then the sixth one fails. The kernel
- 4:12Speaker 1: style actually recommends using go to. That sounds controversial. It does.
- 4:17Speaker 2: It goes against a lot of Standard C teaching, but
- 4:19Speaker 2: in the kernel it's pragmatic. You use go to strictly
- 4:23Speaker 2: for error cleanup paths. You set up labels like air free, buffer,
- 4:26Speaker 2: air release, lock, maybe out. When an error happens, you
- 4:29Speaker 2: go to the appropriate label. This jumps you straight into
- 4:31Speaker 2: the sequence of cleanup steps needed, executed in reverse order
- 4:34Speaker 2: of allocation.
- 4:35Speaker 1: But doesn't that make the code harder to follow all
- 4:38Speaker 1: those jumps.
- 4:39Speaker 2: You'd think so, but it actually tends to make it cleaner.
- 4:41Speaker 2: In this context. The alternative is deeply nested eifles blocks
- 4:45Speaker 2: which get really hard to read and are super easy
- 4:48Speaker 2: to mess up, like forgetting a cleanup step inside one branch.
- 4:52Speaker 2: The go to approach enforces a clear, linear cleanup path.
- 4:56Speaker 2: It's considered the safest and most readable pattern for kernel
- 4:59Speaker 2: error handling. Strange but true.
- 5:01Speaker 1: Okay, I can see the logic there, given the stakes.
- 5:03Speaker 1: What about functions that need to return a pointer but
- 5:06Speaker 1: might also fail. You can't return both a pointer and
- 5:09Speaker 1: a negative error code, ah.
- 5:10Speaker 2: Classic C problem. The kernel has neat macros for this,
- 5:13Speaker 2: or ptr iSER and per tier. If your function fails
- 5:17Speaker 2: and needs to return say anviol invalid argument instead of
- 5:20Speaker 2: a pointer, it uses airptr and ball fail. This converts
- 5:24Speaker 2: the air code into a special pointer value. The code
- 5:27Speaker 2: calling that function then checks the return pointer using iSER.
- 5:30Speaker 2: If it returns true, it means it's an error pointer.
- 5:32Speaker 2: Then if you need the actual air code back, you
- 5:34Speaker 2: use ptr on that pointer and it gives you ANVOL.
- 5:37Speaker 2: It avoids ambiguity with returning anal MP.
- 5:39Speaker 1: That's ill again. Okay, last bit on the programming shift logging,
- 5:43Speaker 1: we're supposed to move beyond just using print, right.
- 5:46Speaker 2: Yeah. While print is still the underlying engine, the recommendation
- 5:49Speaker 2: is strongly towards using specific elper functions. Don't just use
- 5:53Speaker 2: print with log levels directly, use things like prayer or
- 5:57Speaker 2: prinfo for general module messages. But and this is important,
- 6:02Speaker 2: if you're in a device driver, use the dev versions
- 6:05Speaker 2: UH or dev infostruct device DEV.
- 6:08Speaker 1: And why the dev prefix ones specifically for drivers.
- 6:11Speaker 2: Because they automatically include context about the specific device the
- 6:15Speaker 2: message is coming from, its name is positioned in the system,
- 6:18Speaker 2: makes debugging way easier when you have multiple identical devices.
- 6:21Speaker 2: They're even netdev versions for network drivers. They all tie
- 6:24Speaker 2: the message to a specific kernel object.
- 6:26Speaker 1: Got it? And if we want our modules messages to
- 6:28Speaker 1: stand out in the flood of kernel logs, how do
- 6:30Speaker 1: we add a prefix?
- 6:32Speaker 2: Simple. You use the prfmt macro, you define hashtag, define
- 6:36Speaker 2: prfmt fmt KDI. You're building the devmt at the top
- 6:39Speaker 2: of your source file, Katie. Build mode name gets set
- 6:42Speaker 2: automatically during the build to your module's name. So now
- 6:44Speaker 2: every print FO, dev etc. Automatically prints like my driver
- 6:48Speaker 2: error occurred. Super helpful.
- 6:50Speaker 1: Okay, we've got the rules of engagement down. Now. The
- 6:53Speaker 1: big danger zone concurrency, especially on SMP systems symmetric multiprocessing,
- 6:58Speaker 1: where multiple CPU use can access the same memory the
- 7:01Speaker 1: same hardware simultaneously. Locks are essential.
- 7:05Speaker 2: This is absolutely where things get tricky, even for experienced devs.
- 7:09Speaker 2: The key is understanding the context. Are you in code
- 7:12Speaker 2: that can sleep user context or code that absolutely cannot sleep,
- 7:16Speaker 2: like an interrupt handler atomic context.
- 7:18Speaker 1: Let's start with the fast ones. Spin locks meant for
- 7:21Speaker 1: short atomic operation.
- 7:22Speaker 2: Exactly very short critical sections. When a CPU grabs a
- 7:25Speaker 2: standard spin lock. Using spin lock, it disables preemption on
- 7:28Speaker 2: that specific CPU, so other tasks in the same core
- 7:31Speaker 2: won't interrupt it. But and this is the critical part,
- 7:34Speaker 2: a standard spin lock does not stop hardware interrupts from
- 7:37Speaker 2: firing on that cpu.
- 7:38Speaker 1: Ah, and that's the classic deadlock scenario waiting to happen sisily.
- 7:42Speaker 2: Imagine task A on CPU zero called spin lock to
- 7:45Speaker 2: protect some data. Then bam, hardware interrupt fires on CPU zero.
- 7:50Speaker 2: The CPU jumps to the interrupt handler IRQ. Now, if
- 7:53Speaker 2: that IRQ handler needs the same data and tries to
- 7:56Speaker 2: acquire the same spin lock, the IRQ spins forever, waiting
- 8:00Speaker 2: task A to release the lock. But Task A is
- 8:02Speaker 2: preempted by the IRQ and can't run to release.
- 8:04Speaker 1: It out catastrophic. So the rule is, if data protected
- 8:09Speaker 1: by a spin lock might also be touched by an
- 8:11Speaker 1: interrupt handler, you need something more.
- 8:13Speaker 2: Yes, unless you are absolutely one hundred percent certain that
- 8:16Speaker 2: no interrupt handler will ever try to access that data
- 8:18Speaker 2: or acquire that lock, you must use the IRQ save variants.
- 8:22Speaker 2: Those are functions like spin locker save and spin a
- 8:24Speaker 2: locker store. They do two things, disable preemption and disabled
- 8:27Speaker 2: hardware interrupts on the local CPU. This makes the critical
- 8:30Speaker 2: section truly atomic on that core. It's a vital lesson.
- 8:33Speaker 1: Okay, So spin locks are for short atomic contexts, possibly
- 8:36Speaker 1: needing IRQ disabling. How do utexts differ?
- 8:39Speaker 2: Mutexes are conceptually simpler but have different rules they're built
- 8:43Speaker 2: using spin locks underneath, but their behavior is different. If
- 8:46Speaker 2: task B tries to acquire a mutex held by task A,
- 8:50Speaker 2: instead of spinning, task B is put to sleep. The
- 8:53Speaker 2: kernel puts it on a weight queue and lets the
- 8:55Speaker 2: CPU schedule some other.
- 8:56Speaker 1: Task, so they yield the CPU much more better for
- 9:00Speaker 1: potentially longer critical sections.
- 9:02Speaker 2: Then, yes, much better for contention and longer holds. But
- 9:06Speaker 2: and this is a huge butt because they involve sleeping.
- 9:09Speaker 2: You can only use mutexes in context where sleeping is allowed.
- 9:12Speaker 2: That mean primarily user context like when handling a system call.
- 9:15Speaker 2: You can never acquire a mutex from an interrupt handler
- 9:18Speaker 2: or any other atomic context because those contexts absolutely cannot
- 9:21Speaker 2: sleep using a mutex. There boom, system panic, got it.
- 9:25Speaker 1: Spin locks for atomic mutexes for sleeping contexts. Let's briefly
- 9:28Speaker 1: touch on time. We hear about Jiffey's but things are
- 9:30Speaker 1: more abstract now.
- 9:31Speaker 2: Yeah, Chiffees was the old way. It is. The kernel
- 9:33Speaker 2: counter the increments at a certain frequency defined by the
- 9:36Speaker 2: h z value. It gave fairly low resolution timing. The
- 9:40Speaker 2: modern kernel abstracts this. It relies on two types of
- 9:43Speaker 2: hardware components. For time.
- 9:45Speaker 1: The things that track time and the things that schedule
- 9:47Speaker 1: events in time.
- 9:48Speaker 2: You got it. First, clock source devices. These provide a
- 9:52Speaker 2: high resolution, always increasing monotonic counter. Think of it as
- 9:56Speaker 2: the master clock for accurate time stamps. Second clock event
- 10:00Speaker 2: devices these are the programmable timers. They can be told
- 10:05Speaker 2: fire and interrupt exactly n nanoseconds from now. They're crucial
- 10:09Speaker 2: for things like high resolution timers or timers much more
- 10:12Speaker 2: precise than Jiffy's.
- 10:13Speaker 1: Okay, and before we leave this area, tasklts they were
- 10:17Speaker 1: for deferring work from interrupts, right the bottom half.
- 10:19Speaker 2: Yes, they were a common mechanism. Yeah, but the sources
- 10:22Speaker 2: we looked at had a very very strong warning. Task
- 10:24Speaker 2: lits are being actively deprecated. They're slated for removal. You
- 10:28Speaker 2: should not use them in any new code. They really
- 10:30Speaker 2: only exist now for historical pedagogic reasons.
- 10:32Speaker 1: Okay, loud and clear. So for deferring work now, the
- 10:35Speaker 1: answer is work cues.
- 10:36Speaker 2: Absolutely use workques. They provide a much more flexible and
- 10:40Speaker 2: robust way to q work to be executed by dedicated
- 10:43Speaker 2: kernel threads. Those threads can sleep, so they can handle
- 10:45Speaker 2: much longer, more complex tasks safely.
- 10:48Speaker 1: Right. Let's zoom out now to the big picture, how
- 10:51Speaker 1: the kernel organizes all this hardware, the Linux Device Model LDM.
- 10:55Speaker 1: This is how physical stuff turns into those directories we
- 10:57Speaker 1: see insists.
- 10:58Speaker 2: LDM is the framework, the glue it creates that hierarchy.
- 11:02Speaker 2: Buses contain devices, drivers attached to devices, and it uses
- 11:06Speaker 2: three core low level structures. At the very bottom, the
- 11:09Speaker 2: most fundamental piece is the object. A cobject isn't a
- 11:12Speaker 2: device itself or a driver. It represents the connection or
- 11:16Speaker 2: an object that can appear in sifts. Basically, every single
- 11:19Speaker 2: directory you navigate in the CYS Virtual file system corresponds
- 11:23Speaker 2: to a object in kernel memory. It's the basic building
- 11:26Speaker 2: block of that hierarchy.
- 11:27Speaker 1: Ah okay, So cobject is the foundation for creating that
- 11:30Speaker 1: topology and exposing attributes out to user space through sifts.
- 11:34Speaker 1: That clicks.
- 11:35Speaker 2: It's fundamental. These objects are then grouped into ksets, which
- 11:38Speaker 2: often correspond to directories containing multiple objects, and they have
- 11:41Speaker 2: associated cobduy types which define behavior like attribute handling. Together
- 11:46Speaker 2: they build the whole.
- 11:46Speaker 1: Structure, and within the structure we find different kinds of buses.
- 11:49Speaker 2: Broadly, yeah, you have discoverable buses. Think PCI USB. You
- 11:54Speaker 2: plug something in the bus itself can figure out what
- 11:57Speaker 2: it is until the kernel the hardware handles the numeration.
- 12:00Speaker 2: Then you have nondiscoverable buses. The platform bus is a
- 12:04Speaker 2: common example, especially in embedded systems, where peripherals are just
- 12:07Speaker 2: hardwired to the CPU. The bus itself doesn't announce devices.
- 12:11Speaker 2: For these, the kernel needs to be told that a
- 12:13Speaker 2: device exists at a certain address or uses certain resources.
- 12:17Speaker 2: This information needs to be provided somehow.
- 12:19Speaker 1: Which brings us neatly to the modern way of providing
- 12:22Speaker 1: that information, the device tree. This replaced the old hard
- 12:25Speaker 1: coded board files exactly.
- 12:27Speaker 2: Device tree or DT is a huge step for portability.
- 12:31Speaker 2: Instead of c code describing the hardware layout for one
- 12:34Speaker 2: specific board, you use a textual format dot DTS source files.
- 12:37Speaker 2: These files describe the hardware using nodes representing devices, buses,
- 12:41Speaker 2: and properties like memory addresses, interrupt numbers. This dot dts
- 12:45Speaker 2: file is compiled into a binary blob, the dot DTB
- 12:48Speaker 2: or FDT Flatten device tree. The bootloader loads the dot
- 12:51Speaker 2: DPB into memory, and the kernel parses it at boot
- 12:53Speaker 2: time to learn about the non discoverable hardware present.
- 12:56Speaker 1: What about adding hardware after boot or changing configurations dynamic.
- 13:00Speaker 2: That's where dtoverlays come in. These are smaller partial dot
- 13:04Speaker 2: DTBO device tree blob overlay files. They act like patches.
- 13:08Speaker 2: You can load it dot DTB at runtime, usually via
- 13:10Speaker 2: can figs, and it modifies the live in memory device tree,
- 13:14Speaker 2: maybe enabling an interface, changing a pin configuration, adding a
- 13:17Speaker 2: new IT two C device. It's very powerful.
- 13:19Speaker 1: So when my driver starts up and it needs to
- 13:21Speaker 1: know its memory address or its interrupt number, how does
- 13:24Speaker 1: it get that from the device tree? Reliably?
- 13:26Speaker 2: It uses specific API calls to query the tree. Crucially,
- 13:29Speaker 2: the device tree uses named properties, so instead of asking
- 13:33Speaker 2: for the first interrupts, your driver asked for the interrupt
- 13:35Speaker 2: named four or similar functions like platforms yourt resource by
- 13:39Speaker 2: name or of property read thirty two. Let the driver
- 13:41Speaker 2: request resources by name as defined in the dot dts.
- 13:44Speaker 2: This decouples the driver from the exact physical wiring order.
- 13:47Speaker 1: Makes sense, Okay, last piece, let's connect this architecture to
- 13:51Speaker 1: a real world subsystem. The example given was industrial io
- 13:54Speaker 1: iiO right io is.
- 13:56Speaker 2: A great example. It's a whole kernel subsystem specifically designed
- 13:59Speaker 2: for sensors. Analog to digital converters ADCs, Digital to analog
- 14:04Speaker 2: converters dcs basically data acquisition hardware.
- 14:07Speaker 1: It manages all the complexity of reading raw sens or values,
- 14:10Speaker 1: scaling them, handling triggers.
- 14:12Speaker 2: Exactly, But how does it expose that data to userspace.
- 14:16Speaker 2: It doesn't require custom applications for every sensor.
- 14:19Speaker 1: It uses the device model and sifts precisely.
- 14:22Speaker 2: The io framework models sensors and their data points as channels.
- 14:25Speaker 2: Each channel like the X axis acceleration or temperature reading,
- 14:29Speaker 2: gets exposed as attributes within sifts, So reading the raw
- 14:33Speaker 2: value from an accelerometer might be as simple as reading
- 14:35Speaker 2: a file like cispusiodevi COO dot device zero in SLX.
- 14:40Speaker 2: User space just interacts with these standard file interfaces underpinned
- 14:44Speaker 2: by LDM and the cobject structure representing that channel attribute.
- 14:47Speaker 1: Wow. Okay, we've covered a lot, from those tiny innit
- 14:50Speaker 1: macros affecting memory all the way up to these complex
- 14:52Speaker 1: frameworks like iiO built on the core architecture.
- 14:55Speaker 2: Yeah, we hit the big points. The mindset shift for
- 14:58Speaker 2: kernel programming error clean up with go to logging, then
- 15:03Speaker 2: the concurrency mindfield spin locks versus mutex is, atomic versus
- 15:06Speaker 2: sleeping contexts.
- 15:08Speaker 1: And then the overall structure. How the Linux device model
- 15:11Speaker 1: uses cobjects to build the hierarchy, how the device tree
- 15:14Speaker 1: describes hardware, and how subsystems like iiO plug into that.
- 15:18Speaker 2: So if there's one final thought to leave you with,
- 15:20Speaker 2: it's this, remember that object. It seems abstract, almost trivial,
- 15:25Speaker 2: but everything in the device hierarchy, from the simplest led
- 15:29Speaker 2: driver to the most complex network interface or iiO sensor framework,
- 15:33Speaker 2: ultimately relies on objects to establish its existence and its
- 15:36Speaker 2: attributes within the kernel's world, making it visible and controllable
- 15:40Speaker 2: through sifts. That tiny structure is the bedrock of Linux's
- 15:44Speaker 2: entire device organization.
- 15:45Speaker 1: Amazing how that one fundamental piece underpins so much complexity.
- 15:49Speaker 1: That's a great takeaway. Thank you for walking us through this.
- 15:51Speaker 2: My pleasure is fascinating stuff.
- 15:53Speaker 1: It really is. We'll catch you next time for another
- 15:55Speaker 1: deep dive.