Re: [PATCH 10/22] gpiolib: cdev: fix minor race in GET_LINEINFO_WATCH

From: Kent Gibson
Date: Wed Jun 24 2020 - 18:58:14 EST


On Wed, Jun 24, 2020 at 11:57:14PM +0800, Kent Gibson wrote:
> On Wed, Jun 24, 2020 at 05:46:33PM +0300, Andy Shevchenko wrote:
> > On Tue, Jun 23, 2020 at 7:03 AM Kent Gibson <warthog618@xxxxxxxxx> wrote:
> > >
> > > Merge separate usage of test_bit/set_bit into test_and_set_bit to remove
> > > the possibility of a race between the test and set.
> > >
> > > Similarly test_bit and clear_bit.
> > >
> > > In the existing code it is possible for two threads to race past the
> > > test_bit and then set or clear the watch bit, and neither return EBUSY.
> >
> > I stumbled over this myself, but...
> >
> > > - if (test_bit(hwgpio, gcdev->watched_lines))
> > > + if (test_and_set_bit(hwgpio, gcdev->watched_lines))
> > > return -EBUSY;
> > >
> > > gpio_desc_to_lineinfo(desc, &lineinfo);
> > > @@ -897,7 +897,6 @@ static long gpio_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
> > > if (copy_to_user(ip, &lineinfo, sizeof(lineinfo)))
> > > return -EFAULT;
> > >
> > > - set_bit(hwgpio, gcdev->watched_lines);
> > > return 0;
> >
> > ...I think it's not an equivalent despite races involved. If you set
> > bit and return error code, you will have the wrong state.
> >
>
> Not quite sure what you mean. There is only an error if the bit is
> already set, so you've changed nothing.
>
> And the watched state is not part of the lineinfo, so the state returned is
> the same either way.
>

Perhaps you are referring to the case where the copy_to_user fails?
To be honest I considered that to be so unlikely that I ignored it.
Is there a relevant failure mode that I'm missing?

Cheers,
Kent.