ktypes vs. devices classes (struct class)

Greg KH greg at kroah.com
Sun Oct 1 06:28:32 EDT 2023


On Sun, Oct 01, 2023 at 11:50:46AM +0200, Greg KH wrote:
> On Sat, Sep 30, 2023 at 08:17:26PM +0200, Richard wrote:
> > Hi,
> > 
> > I appreciate your answer, thank you for your time.
> > 
> > > 
> > > Look closer.  Tell me what "struct class" is for vs. what "struct
> > > kobj_type" is for and see if they both could be used for the same thing?
> > 
> > I've looked at the definitions in include/linux and thought a bit about the
> > semantics.
> > 
> > struct kobj_type defines behaviour (sysfs_ops and default_attrs) that is
> > common for multiple kobjects. But those kobjects could be embedded in
> > drivers, devices or a bus.
> > 
> > I think one core difference is that "struct class" is strictly for devices
> > so it's more specific and contains a lot of members that are only relevant
> > for devices.
> 
> Close.
> 
> "struct class" represents how userspace interacts with a device (tty /
> input / block / etc.)
> 
> "struct kobj_type" is needed to describe what "type" of struct kobject a
> specific kobject is.  It defines a number of operations that handle the
> lifespan of the kobject.
> 
> > My digging however has brought me to a few new questions:
> > 
> > Do all devices (their kobjects to be more precise) in one class (e.g.
> > /sys/class/net ) belong to the same ktype?
> 
> ktype is "lower" than classes.  ktype is not used for things in the
> driver model, it's used for things "lower" than the driver model (and to
> implement the driver model itself.)
> 
> So no driver should ever be messing with a ktype.  If you want to have a
> different "type" of device on the same bus or class, use "struct
> device_type" as that's what that is for.
> 
> > Is it possible that one device belongs to several classes?
> 
> No.

Oops, well yes.  Depends on what you are thinking is a "device" here.

In the kernel, yes, a 'struct device' on a bus can then register itself
with multiple subsystems that handle different classes, and then
individual 'struct device' are created for those classes that have a
parent of the original 'struct device' on the bus.

But within a 'struct class', there can only be one "struct device" for
that class for that specific class type (we used to call them "struct
class_device" but that got removed a long time ago as the objects really
all did the same thing.)

It's a bit confusing, yes, sorry, but creating a unified object model of
all devices in the system turns out to be complex due to the huge range
of devices that an operating system needs to manage, which is probably
why most other operating systems have never attempted to do such a
thing.

When Pat and I created it, we were young and naive and thought "this
should be simple!"  Famous last words...

thanks,

greg k-h



More information about the Kernelnewbies mailing list