RFC locking and rate limit updates for i2c?
Hi All,
Requesting information on two issues, taking a the lock for read/modify/write i2c chip update cycles, and rate limiting write access to i2c bus to prevent user-space DoS on the i2c bus with continuous update requests.
i2c locking:
Thinking about the fan_div setting, it is a read/modify/write (RMW) operation to a chip register, should we take action to prevent another process accessing the chip on i2c during this RMW action?
What I'm thinking is sort of:
..
if new_div not in (valid_divisor_set)
return error message
~
read old_div
if (new_div = old_div)
goto exit
read fan_min
adjust fan_min
write new_div
write fan_min
exit:
~
..
Should we hold exclusive access to i2c bus + chip between the tildes above? Or is my thinking bounding too far into highly unlikely events?
preventing DoS, updating i2c bus chips
Another query, we take care not to read chip too frequently, what stops user-space DoS'ing the i2c bus with continuous writes by constant update requests?
Two methods come to mind:
a cheap block until minimum write interval elapsed enforced perhaps by not granting lock_request until minimum period elapsed?
a more expensive delayed write data buffer (~100 .. ~500ms?) would allow aggregation of update operations and take over the i2c bus at a controlled maximum duty cycle.
The first method may upset user-space with a delay between updates, but is easy/safe to implement.
The second method is far more invasive -- not all drivers have clean data structures that reflect the chip registers, eliminating them from this type of cleanup until they're fixed.
Thanks,
Grant.
Hi Khali,
Quoted 11 lines · Jean Delvare
Quoted 3 lines
I still go for lm85 locking model, perhaps overdone but seems clearly safe. Certainly easy to point at lm85 as reference model for write locking in the author / porter guide.
Absolutely.
Quoted 2 lines
Then think of reader locking, can drivers simply return -error_update_in_progress_uncertain_data_value_try_again ?
With what benefit, when we can wait a fraction of second and return a valid value?
How driver wait for that? If writer taken lock, is reader blocked?
Not as far as I see.
Perhaps need yet another lock to do this properly, writer takes exclusive lock, reader takes non-exclusive lock that will block update writers but not other readers.
I'll leave this for now as I have other concerns with value readers that may be resolved as I gain some knowledge of the drivers in action.
Quoted 5 lines
Quoted 4 lines
Moving on:
What I do need is a list of drivers that will be handled by others, then I'll update the 'orphans', as well as continue theDIV_TO_REGremoval work in progress.
Quoted 7 lines
Consider all the drivers 'orphans' ;) I mean, changes to a driver are not reserved to its author. The original author will certainly check your patches, and give some kind of approval, but that's about it.
Quoted 1 line
Is it time for me to learn the 'ticket' system?
What do you mean?
Somewhere I read on lm_sensors to take out 'tickets' so others know what is being developed.
Quoted 4 lines
Quoted 2 lines
Who is documenting this?
You? :)
Yes, well, I did start this particular mess :)
I'll repost via686a against -mm2 as new thread.
Cheers,
Grant.
Hi Grant:
Quoted 7 lines · Grant Coady
Hi All,
Requesting information on two issues, taking a the lock for read/modify/write i2c chip update cycles, and rate limiting write access to i2c bus to prevent user-space DoS on the i2c bus with continuous update requests.
Quoted 6 lines
i2c locking:
Thinking about the
fan_divsetting, it is a read/modify/write (RMW) operation to a chip register, should we take action to prevent another process accessing the chip on i2c during this RMW action?
Looks like Philip addressed this one.
Quoted 5 lines
preventing DoS, updating i2c bus chips
Another query, we take care not to read chip too frequently, what stops user-space DoS'ing the i2c bus with continuous writes by constant update requests?
Nothing prevents it, except that you need root to do those writes/updates. Considering all the other damage you can do as root... there's not much point in any further protection for the I2C bus.
Regards,
Signature · 2 lines
Mark M. Hoffman [email protected]
Hi Grant,
Quoted 5 lines
I'm thinking that there is a very small window between reading a register, modifying some bits and writing it back out, where another process also does it. Say SMP and one CPU update
fan_div1while other updatefan_div2-- adm1026 has eight of these over two bytes to potentially interfere with each other.
Correct, you convinced me.
Quoted 2 lines
But if the update request event stream is serialised by sysfs or elsewhere on its way to the driver then there is no problem.
No, it isn't.
Quoted 2 lines
If the i2c bus driver rate limits write traffic to bus, then again there is no issue. I simply do not know. I ask to learn.
The bus driver doesn't limit the traffic, it only makes sure that no more than one transfer happens at any given time. This alone doesn't cover the case above, as register modifications consists in two separate messages, and another message can slip inbetween.
Thanks,
Signature · 1 line
Jean Delvare
Hi Grant,
Quoted 3 lines
I still go for lm85 locking model, perhaps overdone but seems clearly safe. Certainly easy to point at lm85 as reference model for write locking in the author / porter guide.
Absolutely.
Quoted 2 lines
Then think of reader locking, can drivers simply return -error_update_in_progress_uncertain_data_value_try_again ?
With what benefit, when we can wait a fraction of second and return a valid value?
Quoted 2 lines
Does sysfs have normal unix filelocking: exclusive write, non-exclusive read?
I am told they are, but...
Quoted 2 lines
Or is that what the driver is enforcing?
Or is advisory locking too hard to clue-bat end user with?
..filesystem locking is about locking files individually. What we have here is much more general than that. Concurrent accesses (with at least one write) to different files may cause a race condition. So the driver must handle it, exactly like is done in lm85.
Quoted 4 lines
Moving on:
What I do need is a list of drivers that will be handled by others, then I'll update the 'orphans', as well as continue theDIV_TO_REGremoval work in progress.
Consider all the drivers 'orphans' ;) I mean, changes to a driver are not reserved to its author. The original author will certainly check your patches, and give some kind of approval, but that's about it.
Quoted 1 line
Is it time for me to learn the 'ticket' system?
What do you mean?
Quoted 1 line
Who is documenting this?
You? :)
Signature · 1 line
Jean Delvare
Hi Khali,
Much happened while I sleep :) In few weeks we'll be nine hours out of step when some of .au goes out of daylight saving.
Quoted 1 line · Jean Delvare
Quoted 1 line
Surveyed
drivers/i2c/chips/*.ccontaining "_write_value(" and...
^^^^^^^^^^^^^
maybe your drivers didn't use this string?
Quoted 6 lines
Quoted 1 line
it87.cno locking ??What do you mean? It has the same
update_lockthe other drivers have, used only for the big update so far. A quick look shows that it needs locks for at least the same reason the adm1021 does, let alone possible multiple functions registers.
?? was I know this is SuperIO and different issues involved -- forgot to expand the ?? for email
Quoted 5 lines
Quoted 1 line
[0] assuming lock not required until after client init completed
Assumption is correct, locking makes no sense until we create at least one sysfs file, and sysfs file creations happens after init (if not this is considered a bug and shall be fixed).
I'm not sure if sysfs file creations immediately allow access? But if they done as last task before exit init then no problem, all registers written before chip interface exposed.
Quoted 7 lines
Quoted 2 lines
[1]
down()may be before or after: val =simple_strtol(buf, NULL, 10); Is this a problem? Can anthing can stomp 'buf'?"buf" is ours. There is no reason to hold the lock during the
simple_strtol, so for better performance thedown()should be moved below it.
Quoted 8 lines
Quoted 3 lines
Query: Should all drivers follow lm85 model where lock taken by write accessors prior to reading
data->somevaluethrough to completion?I think so. Shame on me for not realizing before. I think I remember it was already discussed here before, and back then I didn't realize what the issue was, and possibly gave bad advice to drivers porters. Please forgive me.
Stuff happens -- Someone just stomped in and started asking questions. That same someone has lots of time and needs a challenge :)
Quoted 10 lines
Quoted 3 lines
As far as i2c bus saturation or rate limiting goes, that is not something for the chip drivers, I now think it it belongs to the i2c bus driver.
It doesn't. For one thing, rate limitation is chip-specific, because the value update time differs from chip to chip. For another, some chips must *not* be limited in any way, or they become useless (think I/O expanders). Even for chips where we have a rate limitation, it doesn't apply to all parts of the driver, so there is no way this can be moved outside of the driver.
Okay, I was thinking of i2c bus saturation from communications point of view (or resource contention). It is a separate issue to locking.
Quoted 3 lines
Quoted 1 line
'Somebody Else's Problem' --Douglas Adams
In which book is this?
Wish I could remember, I think the same one where "flying is the trick of falling over and not hitting the ground"... many years ago.
Quoted 1 line · Philip Pokorny
I'm not sure. Do my comments clarify things at all?
Perfectly, I will not touch drivers you mention.
Grant.
The ADM1026 and LM85 drivers should be requesting the semaphore on the internal per-chip data structure before doing any modification of the fan_div. In that way there is only one writer to the data structure and consistency should be enforced. If someone pokes at the hardware without going through the driver there isn't much we can do...
With 2.6 (and perhaps 2.4?) there are one-writer or multiple reader locks that might be more appropriate for locking the per chip data structures...
:v)
Quoted 35 lines · Grant Coady
Hi All,
Requesting information on two issues, taking a the lock for read/modify/write i2c chip update cycles, and rate limiting write access to i2c bus to prevent user-space DoS on the i2c bus with continuous update requests.
i2c locking:
Thinking about the
fan_divsetting, it is a read/modify/write (RMW) operation to a chip register, should we take action to prevent another process accessing the chip on i2c during this RMW action?What I'm thinking is sort of:
..
ifnew_divnot in (valid_divisor_set)
return error message
~
readold_div
if (new_div=old_div)
goto exit
readfan_min
adjustfan_min
writenew_div
writefan_min
exit:~..
Should we hold exclusive access to i2c bus + chip between the tildes above? Or is my thinking bounding too far into highly unlikely events?
Quoted 11 lines · Grant Coady
Quoted 3 lines · Philip Pokorny
The ADM1026 and LM85 drivers should be requesting the semaphore on the
^^^^^^^-- off my work list as it requires too much change
for an obvious fix, care to comment on partial patch?
A fix for what? Locking or rate limiting?
Quoted 4 lines
I stopped when I realised it had an odd data structure and fixing that is too invasive as I cannot go further than compile test.
I'm trying to explain that the locking is already *there* in the adm1026 and lm85 drivers. The semaphore "data->update_lock" is taken whenever lm85_update_device is called to *read* the chip and whenever any of the set_ functions is called to *write* to the chip. Therefore all reads and writes are serialized and locked by the data->update_lock semaphore.
Further the functions that set the fan_div and fan_min also take the semaphore making those multi-value updates atomic as well.
Quoted 5 lines
Per register access locking achieves nothing for a read/modify/write cycle as another proces may change that register during the modify phase if i2c bus released.
Just to re-iterate, the update_lock is held the entire time we're updating the values. No other process can change a register because it will have to wait on the update_lock.
Quoted 5 lines
On one hand I've been told not to trust cache coherency with chip registers, thus implying read/modify/write cycle, which should take exclusive access to i2c bus for the read and writeback operations.
There is no cache in this case. The i2c devices are not accessed directly, so there should not be any cache coherency issues.
However, it is also true that hardware does not always read back what was last written. Sometimes bits (like alarms) are cleared when written with a one.
Quoted 2 lines
Does that clarify my query?
I'm not sure. Do my comments clarify things at all?
:v)
Quoted 11 lines · Grant Coady
Hi Mark,
Quoted 6 lines · Mark M. Hoffman
Quoted 6 lines
Thinking about the
fan_divsetting, it is a read/modify/write (RMW) operation to a chip register, should we take action to prevent another process accessing the chip on i2c during this RMW action?
Quoted 7 lines
Quoted 3 lines
Looks like Philip addressed this one.
Not at all.
I'm sorry, I didn't mean to offend.
In addition to the way I know my drivers worked, I believe that all other drivers have an update_lock semaphore that could be used to protect read-modify-write's in the same way.
:v)
Quoted 6 lines · Grant Coady
You ever focus on wrong issues and build wrong model of what is important? That's where I'm at trying to build understanding of a system I don't even have end-user experience with yet.
Certainly, wouldn't be an experiecned programmer if I hadn't.
Quoted 5 lines
I get to the stage of cherry-picking the best ideas I've seen in the drivers, not one driver has struck me as a model driver.
Quoted 9 lines
Quoted 5 lines
In addition to the way I know my drivers worked, I believe that all other drivers have an
update_locksemaphore that could be used to protect read-modify-write's in the same way.But they don't, and I wonder if they should?
Ahh... That's where I haven't really done a good job explaining myself. I fully agree with you that they should. It's obvious to me that the functions that *set* the values need to be protected to prevent an SMP machine from borking things up. That's why I added the down/up calls in all of the write paths of the drivers I wrote.
Perhaps I should have made a bigger deal about this when I first realized it in the drivers I created and submitted patches for the other drivers... Would have saved you the trouble...
:v)
Quoted 30 lines · Jean Delvare
Hi Grant,
Quoted 9 lines
Surveyed
drivers/i2c/chips/*.ccontaining "_write_value(" and...The winner is
lm85.c:o)driver write lock taken status [0] -------------- --------------------------------------------------- adm1021.c no, appears to not need itOut of curiousity, I took a look. See what I found:
data->value = TEMP_TO_REG(temp); adm1021_write_value(client, reg, data->value);As long as we don't hold
update_lockhere, it could happen thatdata->valueis overwritten by an update right inbetween these two lines, right? Causing the write to become silently useless, which is no good. So, either the lock should be held even in this most simple write case, or we should use a temporary variable and put the lines the other way around:w = TEMP_TO_REG(temp); adm1021_write_value(client, reg, w); data->value = w;
Quoted 11 lines
This should be concurrent-update-safe as far as I can see. I don't know what is preferable, performance-wise. At least, locking is a general solution to the problem. Temporary variables might be fine for simple cases like the one above, but it might become a mess for more complex functions. Also, using locks make it clear to the user that a concurrent access issue exists. The trick of using local variables isn't as obvious, and future code cleanup attempts might break it. So all in all I believe that using the lock is better.
I think both cases are problematic. It doesn't matter which order you do the writes, if you attempt to cache the value written to the register, then you must do that atomically. Otherwise, the following can potentially occur and lead to the wrong result:
Thread A Thread B
Write first value
Write first value
Write second value
Write second value
End result is second value is Thread A and first value is Thread B.
Without locking, this sort of sequence is possible. As long as you have to update two values in different locations, you've got to have some kind of locking or synchronization.
:v)
Hi Mark,
Quoted 6 lines · Mark M. Hoffman
Quoted 4 lines
Thinking about the
fan_divsetting, it is a read/modify/write (RMW) operation to a chip register, should we take action to prevent another process accessing the chip on i2c during this RMW action?Looks like Philip addressed this one.
Not at all.
Quoted 9 lines
Quoted 5 lines
preventing DoS, updating i2c bus chips
Another query, we take care not to read chip too frequently, what stops user-space DoS'ing the i2c bus with continuous writes by constant update requests?
Nothing prevents it, except that you need root to do those writes/updates. Considering all the other damage you can do as root... there's not much point in any further protection for the I2C bus.
Your answer tells me it is not an issue. "Don't do that"
Cheers,
Grant.
Hi Philip,
Quoted 3 lines · Philip Pokorny
Quoted 1 line
Not at all.
I'm sorry, I didn't mean to offend.
Not offended, upset at not being able to work out how all this fits together, now that I'm passed the silly errors, learning how people build symbols inside macros and other weird stuff.
So, we have yourself and Mark telling me not to worry, but I'm uneasy about the model or mental picture I build to describe what may be. And yes, I don't have evidence yet, but these are areas I'm treating with suspicion, if you like.
You ever focus on wrong issues and build wrong model of what is important? That's where I'm at trying to build understanding of a system I don't even have end-user experience with yet.
I get to the stage of cherry-picking the best ideas I've seen in the drivers, not one driver has struck me as a model driver.
Quoted 3 lines
In addition to the way I know my drivers worked, I believe that all other drivers have an
update_locksemaphore that could be used to protect read-modify-write's in the same way.
But they don't, and I wonder if they should?
Of course, I may have missed something... I doubt I'll submit a non-compile-tested patch again, f'instance. :o)
Cheers,
Grant.
Hi Grant,
Quoted 4 lines
Thinking about the
fan_divsetting, it is a read/modify/write (RMW) operation to a chip register, should we take action to prevent another process accessing the chip on i2c during this RMW action?
Can you (or anyone) point out a concrete example where the lack of locking on write could cause a problem that locking would actually resolve? It's better to know what we are trying to fix before we change anything.
Thanks,
--
Jean Delvare
Hi Philip, all,
Quoted 4 lines
It's obvious to me
that the functions that *set* the values need to be protected to prevent an SMP machine from borking things up. That's why I added the down/up calls in all of the write paths of the drivers I wrote.
It looks to me like locking is only needed when we R/U/WB a register which has more than one "function", like is the case for fan clock dividers for the ADM1026. In the case a given register has only one function of interest to our driver, is there still a benefit in using the lock? Concrete example anyone?
Thanks,
--
Jean Delvare
Hi Grant,
Quoted 7 lines
Surveyed
drivers/i2c/chips/*.ccontaining "_write_value(" and...The winner is
lm85.c:o)driver write lock taken status [0] -------------- --------------------------------------------------- adm1021.c no, appears to not need it
Out of curiousity, I took a look. See what I found:
data->value = TEMP_TO_REG(temp); adm1021_write_value(client, reg, data->value);
As long as we don't hold update_lock here, it could happen that data->value is overwritten by an update right inbetween these two lines, right? Causing the write to become silently useless, which is no good. So, either the lock should be held even in this most simple write case, or we should use a temporary variable and put the lines the other way around:
w = TEMP_TO_REG(temp); adm1021_write_value(client, reg, w); data->value = w;
This should be concurrent-update-safe as far as I can see. I don't know what is preferable, performance-wise. At least, locking is a general solution to the problem. Temporary variables might be fine for simple cases like the one above, but it might become a mess for more complex functions. Also, using locks make it clear to the user that a concurrent access issue exists. The trick of using local variables isn't as obvious, and future code cleanup attempts might break it. So all in all I believe that using the lock is better.
Quoted 1 line
asb100.cno locking, needs it 357
True. Currently, data->fan_div[nr] might be overwritten by a concurrent update.
Quoted 4 lines
ds1621.c no, appears to not need it fscher.c no, appears to not need it fscpos.c no, appears to not need it gl518sm.c no, appears to not need it
I believe they all do, exactly for the same reason adm1021 does. As long as data->anything is used to store a new value before it is written to a register, locking is needed.
Quoted 1 line
gl520sm.cno locking, needs it 371
That's right, if both fan1_min and fan2_min are set at the same time, the current code may miss one of them.
Quoted 1 line
it87.cno locking ??
What do you mean? It has the same update_lock the other drivers have, used only for the big update so far. A quick look shows that it needs locks for at least the same reason the adm1021 does, let alone possible multiple functions registers.
Skipping the other ones, as obviously all drivers need lock on register write for one reason or another.
Quoted 1 line
lm85.cYes -- full locking from data-> access to completion!
How different is it from adm1026 and adm1031? These two ones look all right to me too.
What about the drivers not listed here? adm1025, lm83, lm90, lm92, w83l785ts (surprisingly enough, all mine)?
Quoted 1 line
[0] assuming lock not required until after client init completed
Assumption is correct, locking makes no sense until we create at least one sysfs file, and sysfs file creations happens after init (if not this is considered a bug and shall be fixed).
Quoted 2 lines
[1]
down()may be before or after: val =simple_strtol(buf, NULL, 10); Is this a problem? Can anthing can stomp 'buf'?
"buf" is ours. There is no reason to hold the lock during the simple_strtol, so for better performance the down() should be moved below it.
Quoted 3 lines
Query: Should all drivers follow lm85 model where lock taken by write accessors prior to reading
data->somevaluethrough to completion?
I think so. Shame on me for not realizing before. I think I remember it was already discussed here before, and back then I didn't realize what the issue was, and possibly gave bad advice to drivers porters. Please forgive me.
Quoted 3 lines
As far as i2c bus saturation or rate limiting goes, that is not something for the chip drivers, I now think it it belongs to the i2c bus driver.
It doesn't. For one thing, rate limitation is chip-specific, because the value update time differs from chip to chip. For another, some chips must *not* be limited in any way, or they become useless (think I/O expanders). Even for chips where we have a rate limitation, it doesn't apply to all parts of the driver, so there is no way this can be moved outside of the driver.
Quoted 1 line
'Somebody Else's Problem' --Douglas Adams
In which book is this?
Thanks,
--
Jean Delvare
Hi Philip,
Quoted 11 lines
I think both cases are problematic. It doesn't matter which order you do the writes, if you attempt to cache the value written to the register, then you must do that atomically. Otherwise, the following can potentially occur and lead to the wrong result:
Thread A Thread B
Write first value
Write first value
Write second value
Write second value
Quoted 5 lines
End result is second value is Thread A and first value is Thread B.
Without locking, this sort of sequence is possible. As long as you have to update two values in different locations, you've got to have some kind of locking or synchronization.
My original case was different as it had only one value being written, but you got point in that there *are* cases where we actually write to several registers.
All in all, I think we made it clear that all sysfs callbacks which write to a register and update the cache need locking. If a few ones don't need it for obscure reasons, it's probably not a problem to still lock there, as this will prevent the introduction of race conditions in the future for a very small price.
Thanks,
--
Jean Delvare
Hi Grant,
Quoted 9 lines
Quoted 5 lines
Quoted 2 lines
Then think of reader locking, can drivers simply return -error_update_in_progress_uncertain_data_value_try_again ?
With what benefit, when we can wait a fraction of second and return a valid value?
How driver wait for that? If writer taken lock, is reader blocked?
Not as far as I see.
It is blocked. It will wait until the lock is released and can be acquired again. This is why forgetting to release a lock leads to a driver lockup.
Quoted 3 lines
Perhaps need yet another lock to do this properly, writer takes exclusive lock, reader takes non-exclusive lock that will block update writers but not other readers.
We don't need this. There are no "pure readers" in our model. The update function reads from the chip registers and writes to the data structure. The sysfs write callbacks write to the data structure and write to the chip registers. So everyone is writing to the data structure, which means that the lock must be exclusive for everyone. It's exactly what the lm85, adm1026 and adm1031 drivers do.
Quoted 2 lines
Somewhere I read on
lm_sensorsto take out 'tickets' so others know what is being developed.
Don't trust what you read on this page. it's dead old and outdated (and hopefully soon gone). This mailing-list is where things are discussed, so it's already done.
Quoted 1 line
I'll repost via686a against -mm2 as new thread.
Ok, will review. Sorry I couldn't test your patch as planned yesterday evening, but I had other tests going on the same machine.
I will (try to) provide patches for the following drivers today: lm63, lm80, lm83, lm87, lm90, lm92, pc87360. As a side note, the w83l785ts driver is read-only so it obviously doesn'y need to be updated.
Thanks,
--
Jean Delvare
Hi Grant,
Quoted 3 lines
Okay, appended is via686a as it was the cleanest conversion to new set
fan_divwith the suggested locking. This patch has twice been proposed for comment. Hopefully a little better each time.
True, improving over time and tries. Not perfect yet though (sorry). See right below.
Quoted 3 lines
Next step is to force a delay before driver can reacquire the lock to guarantee any particular driver cannot DoS the i2c bus. Then I would feel much more at ease with system operation.
As Mark explained, typically only root can write, and root is omnipotent anyway. There is no point in attempting to prevent him/her from doing anything. Also this would significantly slow down "sensors -s". Significant drawback, little benefit (if any). Don't do it! ;)
Quoted 4 lines
This patch updates via686a to report an error when an unsupported set
fan_divvalue is requested, the patch also skips update where there is no change and takes theupdate_lockduring the read, update, write chips register cycle.
Sounds good.
Quoted 1 line
Compile tested. No hardware for functional test.
I have a disconnected via686 chip at home, I'll give a try to your patch this evening.
Review
Quoted 7 lines
(quoted diff) +7
-0+/* + * DIV_TO_REG subsumed into this function + * Add error reporting for invalid fan divisor input + * Skip updating when no change in divisor + * Adjust fan_min to match new divisor + */ +
Your comments should focus on what the driver now does, and not the changes made. In the future, the comment about DIV_TO_REG will make no sense to the reader, since this function is gone. Same goes for "Add", what really matters is what the function does now, not the fact that it used not to do it. Oh, and no blank line between comment and function please.
Review
Quoted 2 lines
(quoted diff) +1
-1- int val = simple_strtol(buf, NULL, 10); + int new, val = simple_strtol(buf, NULL, 10);
If you'd add "new" on its own line, it would make the patch more readable, and reduce the risk of patch rejection.
Quoted 1 line
int old = via686a_read_value(client, VIA686A_REG_FANDIV);
Move variable declaration to the top of the block. Your compiler might not care, but olders do. Could be made an u8, BTW.
Review
Quoted 2 lines
(quoted diff) +2
-0+ long min = FAN_FROM_REG(data->fan_min[nr], + DIV_FROM_REG(data->fan_div[nr]));
Ditto. Maybe this should be made unsigned, too.
These details left apart, looks functionally correct.
Thanks,
--
Jean Delvare
Hi Khali,
Quoted 2 lines · Jean Delvare
I have a disconnected via686 chip at home, I'll give a try to your patch this evening.
okay, here are changes as requested, compile tested :)
Cheers,
Grant.
This patch for via686a driver updates set_fan_div
Added: Reports error when given invalid values for new fan divisor. Updating fan divisor is skipped when no change to reduce i2c bus traffic. The fan speed minimum limit is adjusted to suit new divisor so not to confuse user.
Driver now holds update_lock during the read, update, write cycle.
drivers/i2c/chips/via686a.c +33 -3
@@ -297,7 +297,6 @@#define ALARMS_FROM_REG (val) (val)#define DIV_FROM_REG (val) (1 << (val)) -#define DIV_TO_REG (val) ((val)=8?3:(val)=4?2:(val)=1?0:1)/* For the VIA686A, we need to keep some data in memory. The structure is dynamically allocated, at the same time when a new
@@ -506,15 +505,46 @@via686a_write_value (client,VIA686A_REG_FAN_MIN (nr+1 ), data->fan_min[nr]);return count; } + +/* +* Set fan divisor. Reports error when invalid divisor value requested. +* Skip update when no change in divisor to reduce i2c bus traffic, and +* adjust fan_min to match the new divisor providing 'least astonishment'. +*/ static ssize_t set_fan_div (struct device *dev,const char *buf,size_t count,int nr) {struct i2c_client *client =to_i2c_client (dev);struct via686a_data *data =i2c_get_clientdata (client);int val =simple_strtol (buf,NULL ,10 ); -int old =via686a_read_value (client,VIA686A_REG_FANDIV ); - data->fan_div[nr] =DIV_TO_REG (val); +u8 new, old; +unsigned long min; + +switch (val) { +case 1 : new =0 ;break ; +case 2 : new =1 ;break ; +case 4 : new =2 ;break ; +case 8 : new =3 ;break ; +default : +dev_err (&client->dev,"fan_div value %d not supported. " +"Choose one of 1, 2, 4, or 8!\n" , val); +return -EINVAL ; + } +if (new = data->fan_div[nr]) + goto exit; + +down (&data->update_lock); + + old =via686a_read_value (client,VIA686A_REG_FANDIV ); + min =FAN_FROM_REG (data->fan_min[nr], +DIV_FROM_REG (data->fan_div[nr])); + data->fan_div[nr] = new; old = (old &0x0f ) | (data->fan_div[1 ] <<6 ) | (data->fan_div[0 ] <<4 );via686a_write_value (client,VIA686A_REG_FANDIV , old); + data->fan_min[nr] =FAN_TO_REG (min,DIV_FROM_REG (data->fan_div[nr])); +via686a_write_value (client,VIA686A_REG_FAN_MIN (nr +1 ), + data->fan_min[nr]); +up (&data->update_lock); +exit:return count; }
Greetings,
Quoted 8 lines · Jean Delvare
Quoted 5 lines
I'm thinking that there is a very small window between reading a register, modifying some bits and writing it back out, where another process also does it. Say SMP and one CPU update
fan_div1while other updatefan_div2-- adm1026 has eight of these over two bytes to potentially interfere with each other.Correct, you convinced me.
Surveyed drivers/i2c/chips/*.c containing "_write_value(" and...
The winner is lm85.c :o)
driver write lock taken status [0] -------------- ------------------------------------------------------------ adm1021.c no, appears to not need it adm1026.c Yes [1] adm1031.c Yes [1] asb100.c no locking, needs it 357 ds1621.c no, appears to not need it fscher.c no, appears to not need it fscpos.c no, appears to not need it gl518sm.c no, appears to not need it gl520sm.c no locking, needs it 371 it87.c no locking ?? lm75.c no, appears to not need it lm77.c maybe? see line 171 double write temp + hyst lm78.c no locking, needs it 369 lm80.c no locking, needs it 292 lm85.c Yes -- full locking from data-> access to completion! lm87.c no locking, needs it 424 sis5595.c no locking, needs it 399 smsc47m1.c no locking, needs it 237 via686a.c no locking, needs it -- patched, but rest need check w83627hf.c no locking, needs it 697 w83781d.c no locking, needs it 559
[0] assuming lock not required until after client init completed
[1] down() may be before or after: val = simple_strtol(buf, NULL, 10); Is this a problem? Can anthing can stomp 'buf'?
Query: Should all drivers follow lm85 model where lock taken by write accessors prior to reading data->somevalue through to completion?
And eyeballing all that code is about it for me today. Items with line number appear to have clear evidence of need The two marked [1] are trivial to make match lm85 model The rest are easy enough to do, can't see it breaking anything.
As far as i2c bus saturation or rate limiting goes, that is not something for the chip drivers, I now think it it belongs to the
i2c bus driver. 'Somebody Else's Problem' --Douglas Adams
Cheers,
Grant.
Quoted 1 line · Philip Pokorny
The ADM1026 and LM85 drivers should be requesting the semaphore on the
^^^^^^^-- off my work list as it requires too much change
for an obvious fix, care to comment on partial patch?
I stopped when I realised it had an odd data structure and fixing that is too invasive as I cannot go further than compile test.
Per register access locking achieves nothing for a read/modify/write cycle as another proces may change that register during the modify phase if i2c bus released.
On one hand I've been told not to trust cache coherency with chip registers, thus implying read/modify/write cycle, which should take exclusive access to i2c bus for the read and writeback operations.
Does that clarify my query?
Thnaks,
Grant.
Hi Khali,
Quoted 9 lines · Jean Delvare
Quoted 4 lines
Thinking about the
fan_divsetting, it is a read/modify/write (RMW) operation to a chip register, should we take action to prevent another process accessing the chip on i2c during this RMW action?Can you (or anyone) point out a concrete example where the lack of locking on write could cause a problem that locking would actually resolve? It's better to know what we are trying to fix before we change anything.
I'm thinking that there is a very small window between reading a register, modifying some bits and writing it back out, where another process also does it. Say SMP and one CPU update fan_div1 while other update fan_div2 -- adm1026 has eight of these over two bytes to potentially interfere with each other.
But if the update request event stream is serialised by sysfs or elsewhere on its way to the driver then there is no problem.
If the i2c bus driver rate limits write traffic to bus, then again there is no issue. I simply do not know. I ask to learn.
I've attempted to not access the chip if divisor didn't change, which now makes it trivial to add locking around the read/modify/write, if the notion is deemed worthwhile.
Defensive programming. From what? Perhaps nothing.
Perhaps the query would make more sense with relevant patch?
Cheers,
Grant.
Greetings,
Quoted 8 lines · Jean Delvare
Quoted 5 lines
I'm thinking that there is a very small window between reading a register, modifying some bits and writing it back out, where another process also does it. Say SMP and one CPU update
fan_div1while other updatefan_div2-- adm1026 has eight of these over two bytes to potentially interfere with each other.Correct, you convinced me.
Okay, appended is via686a as it was the cleanest conversion to new set fan_div with the suggested locking. This patch has twice been proposed for comment. Hopefully a little better each time.
Next step is to force a delay before driver can reacquire the lock to guarantee any particular driver cannot DoS the i2c bus. Then I would feel much more at ease with system operation.
Cheers,
Grant.
This patch updates via686a to report an error when an unsupported set fan_div value is requested, the patch also skipd update where there is no change and takes the update_lock during the read, update, write chips register cycle.
Compile tested. No hardware for functional test.
drivers/i2c/chips/via686a.c +33 -3
@@ -297,7 +297,6 @@#define ALARMS_FROM_REG (val) (val)#define DIV_FROM_REG (val) (1 << (val)) -#define DIV_TO_REG (val) ((val)=8?3:(val)=4?2:(val)=1?0:1)/* For the VIA686A, we need to keep some data in memory. The structure is dynamically allocated, at the same time when a new
@@ -506,15 +505,46 @@via686a_write_value (client,VIA686A_REG_FAN_MIN (nr+1 ), data->fan_min[nr]);return count; } + +/* +* DIV_TO_REG subsumed into this function +* Add error reporting for invalid fan divisor input +* Skip updating when no change in divisor +* Adjust fan_min to match new divisor +*/ +static ssize_t set_fan_div (struct device *dev,const char *buf,size_t count,int nr) {struct i2c_client *client =to_i2c_client (dev);struct via686a_data *data =i2c_get_clientdata (client); -int val =simple_strtol (buf,NULL ,10 ); +int new, val =simple_strtol (buf,NULL ,10 ); + +switch (val) { +case 1 : new =0 ;break ; +case 2 : new =1 ;break ; +case 4 : new =2 ;break ; +case 8 : new =3 ;break ; +default : +dev_err (&client->dev,"fan_div value %d not supported. " +"Choose one of 1, 2, 4, or 8!\n" , val); +return -EINVAL ; + } +if (new = data->fan_div[nr]) + goto exit; + +down (&data->update_lock); +int old =via686a_read_value (client,VIA686A_REG_FANDIV ); - data->fan_div[nr] =DIV_TO_REG (val); +long min =FAN_FROM_REG (data->fan_min[nr], +DIV_FROM_REG (data->fan_div[nr])); + data->fan_div[nr] = new; old = (old &0x0f ) | (data->fan_div[1 ] <<6 ) | (data->fan_div[0 ] <<4 );via686a_write_value (client,VIA686A_REG_FANDIV , old); + data->fan_min[nr] =FAN_TO_REG (min,DIV_FROM_REG (data->fan_div[nr])); +via686a_write_value (client,VIA686A_REG_FAN_MIN (nr +1 ), + data->fan_min[nr]); +up (&data->update_lock); +exit:return count; }
Hi Khali, Philip,
On Thu, 24 Mar 2005 17:02:29 +0100 (CET), "Jean Delvare" <[email protected]> wrote:
..
Quoted 5 lines
All in all, I think we made it clear that all sysfs callbacks which write to a register and update the cache need locking. If a few ones don't need it for obscure reasons, it's probably not a problem to still lock there, as this will prevent the introduction of race conditions in the future for a very small price.
And leads to a simple guideline for porters/authors, unnecessary locking is harmless, a missing lock may become an obsure buglet.
I still go for lm85 locking model, perhaps overdone but seems clearly safe. Certainly easy to point at lm85 as reference model for write locking in the author / porter guide.
Then think of reader locking, can drivers simply return -error_update_in_progress_uncertain_data_value_try_again ?
Does sysfs have normal unix filelocking: exclusive write, non-exclusive read? Or is that what the driver is enforcing? Or is advisory locking too hard to clue-bat end user with?
Moving on:
What I do need is a list of drivers that will be handled by others, then I'll update the 'orphans', as well as continue the DIV_TO_REG removal work in progress.
Is it time for me to learn the 'ticket' system?
Who is documenting this?
Cheers,
Grant.
Hi Grant,
Quoted 11 lines
lm85.cline 409...static
ssize_tshow_fan_min(struct device *dev, char *buf, int nr)
{
structlm85_data*data =lm85_update_device(dev); <<= lock taken for data refresh cycleanother updater process may change data while reader not holding lock here, harmless?
return sprintf(buf,"%d\n", FAN_FROM_REG(data->fan_min[nr]) ); <<= data read without lock }
I see your point, as I figured as much today. But come to think of it, nothing bad can really happen at this point. You might actually return a different value of data->fan_min[nr] than the one lm85_update_device had set. And now what? This is just a new value, which is at least as valid as the old one was. So I see no problem here.
Now, there *might* be some readers which do more complex things with the values, for which special care (i.e. locking) would be required. But that's not the common case as far as I can see.
Quoted 6 lines
Quoted 3 lines
That's nice, please keep it up-to-date. You could name the person who worked on each driver (i.e. you or me so far) so it is easier to spot misses.
Will do.
I'l merge all the drivers into it and mark what we have so far
I have put my patches here:
http://jdelvare.net1.nerim.net/sensors/lock-on-set/
Feel free to review and comment.
As a side note, you'll notice that I did *not* add locking for data->vrm. This is not a miss, I did on purpose. data->vrm isn't read frop the chip, so it's not changed by the update function. The sysfs change function is the only place where the value can change (let alone init time), so the lock isn't necessary (until someone can prove otherwise).
Quoted 6 lines
Since you're zooming through most of these, how shall I handle my
fan_divpatches? Revertfan_divand do just locking so you can finish that issue?Then I can do
fan_divat slower pace later as it is less important change than correcting locking.
Absolutely, this would be the better approach. Once we have all the locking fixes, we can do a big patch, co-sign it and send it to Greg. After that, you are free to go on with whatever fixes you want.
Quoted 1 line
Fun stuff, me jumping into the deep end?
Yeah, but I'm glad you found these problems. This means that you are reading the code carefully and you understand how things work (or, in this case, should have worked). Good for the future.
Thanks,
Signature · 1 line
Jean Delvare
Hi Grant,
Quoted 2 lines
Methinks I'll change mine to not move 'val' assignment under lock and add blank in macro -- follow similar style.
Absolutely, I failed to comment on this - I am admittedly lost in the flow of mails (which is why I want us to do one thing at a time).
As I said there is no point in locking during simple_strtol, so moving it outside is better for performance and understanding, I think.
Signature · 1 line
Jean Delvare
Hi Grant,
Quoted 5 lines
Quoted 3 lines
It is blocked. It will wait until the lock is released and can be acquired again. This is why forgetting to release a lock leads to a driver lockup.
readers don't check or take the lock? only
set_somethingcallbacks?
If you look at the code, readers call the update function, which requests the lock. Reader callbacks do never access the chip directly.
Quoted 2 lines
Quoted 2 lines
I will (try to) provide patches for the following drivers today: lm63, lm80, lm83, lm87, lm90, lm92, pc87360.
All done. I'll go on with the lm 75, lm77 and lm78, so that the lm series is all done. I'll take care of both smsc drivers as well, and the adm1025 since it's not on your list.
Quoted 2 lines
Then I go check ones didn't appear on survey list because they use different names. Oh, they are off my list, they're yours? :)
Correct. The grep command you used was quite arbitrary, and the drivers I wrote or ported myself happened not to get matched.
Quoted 5 lines
my work list list at:
http://scatter.mine.nu/lmsensors/list-driver-write-locking-checkwill add others to it as I see patches appear, just to scoreboard progress on locking issue.
That's nice, please keep it up-to-date. You could name the person who worked on each driver (i.e. you or me so far) so it is easier to spot misses.
Quoted 8 lines
semi-related:
I need a policy call on adm1026, adm1031 as they don't comply with other drivers data store, savingfan_divother than 0..3 value. It makefan_divupdate needlessly complex and different to other drivers I've encountered so far. The conversion of 0..3 to 1,2,4,8 is a single '<<' operation, the reverse is more complex if-then-else-if-then-else... statement only needed once in other drivers.
That's a different issue, please don't merge it in there. Best patches change only one thing, so that they can easily be reviewed, applied, ported and reverted if needed. I know it's hard not to fix things as you see them. I had to refrain myself from doing some changes to the drivers I just worked on. Just take notes, and do the other changes later. Even your via686a patch (which by the way won't apply here?) does two things at once, which is no good. Ideally, we should be able to prepare a big patch fixing all locking issues, and doing only that. The rest can be done before, or later.
Thanks,
--
Jean Delvare
On Fri, 25 Mar 2005 21:19:40 +0100, Jean Delvare <[email protected]> wrote:
. . .
Quoted 4 lines
I have put my patches here:
http://jdelvare.net1.nerim.net/sensors/lock-on-set/Feel free to review and comment.
Methinks I'll change mine to not move 'val' assignment under lock and add blank in macro -- follow similar style.
And you've answered my other query, multiple exit okay:
default:
dev_err(&client->dev, "fan_div value %ld not "
"supported. Choose one of 1, 2, 4 or 8!\n", val);
+ up(&data->update_lock);
return -EINVAL;
}
rather than do nasty thing to 'count' with patches I posted
Quoted 6 lines
As a side note, you'll notice that I did *not* add locking for
data->vrm. This is not a miss, I did on purpose.data->vrmisn't read frop the chip, so it's not changed by the update function. The sysfs change function is the only place where the value can change (let alone init time), so the lock isn't necessary (until someone can prove otherwise).
Agree. Two for, any against?
. . .
Quoted 6 lines
Quoted 2 lines
Then I can do
fan_divat slower pace later as it is less important change than correcting locking.Absolutely, this would be the better approach. Once we have all the locking fixes, we can do a big patch, co-sign it and send it to Greg. After that, you are free to go on with whatever fixes you want.
Am setting up -mm3 now, redo my patches against that once it compiles.
Cheers,
Grant.
Quoted 7 lines · Jean Delvare
Quoted 3 lines
How driver wait for that? If writer taken lock, is reader blocked?
Not as far as I see.It is blocked. It will wait until the lock is released and can be acquired again. This is why forgetting to release a lock leads to a driver lockup.
readers don't check or take the lock? only set_something callbacks?
Quoted 4 lines
I will (try to) provide patches for the following drivers today: lm63, lm80, lm83, lm87, lm90, lm92, pc87360. As a side note, the w83l785ts driver is read-only so it obviously doesn'y need to be updated.
I have one more sitting here, fscher.c, waiting for feedback on what I post already. Glad I didn't get to lm?? then :)
Then I go check ones didn't appear on survey list because they use different names. Oh, they are off my list, they're yours? :)
my work list list at:
http://scatter.mine.nu/lmsensors/list-driver-write-locking-check
will add others to it as I see patches appear, just to scoreboard progress on locking issue.
semi-related:
I need a policy call on adm1026, adm1031 as they don't comply with other drivers data store, saving fan_div other than 0..3 value. It make fan_div update needlessly complex and different to other drivers I've encountered so far. The conversion of 0..3 to 1,2,4,8 is a single '<<' operation, the reverse is more complex if-then-else-if-then-else... statement only needed once in other drivers.
Cheers,
Grant.