On Fri, Feb 05, 2021 at 04:50:13PM +0100, Lino Sanfilippo wrote: > > On 05.02.21 16:15, Jason Gunthorpe wrote: > > > > No, the cdev layer holds the refcount on the device while open is > > being called. > > > Yes, but the reference that is responsible for the chip deallocation is chip->dev > which is linked to chip->cdev and represents /dev/tpm, not /dev/tpmrm. > You are right, we dont have the issue with /dev/tpm for the reason you mentioned. > But /dev/tpmrm is represented by chip->cdevs and keeping this ref held by the cdev > layer wont protect us from the chip being freed (which is the reason why we need > the chip->dev reference in the first place). No, they are all chained together because they are all in the same struct: struct tpm_chip { struct device dev; struct device devs; struct cdev cdev; struct cdev cdevs; dev holds the refcount on memory, when it goes 0 the whole thing is kfreed. The rule is dev's refcount can't go to zero while any other refcount is != 0. For instance devs holds a get on dev that is put back only when devs goes to 0: static void tpm_devs_release(struct device *dev) { struct tpm_chip *chip = container_of(dev, struct tpm_chip, devs); /* release the master device reference */ put_device(&chip->dev); } Both cdev elements do something similar inside the cdev layer. The net result is during any open() the tpm_chip is guarenteed to have a positive refcount. Jason