Skip to content

Make Field macro a volatile cast - #11255

Merged
xavierleroy merged 5 commits into
ocaml:trunkfrom
kayceesrk:volatile_field
Jul 11, 2022
Merged

xavierleroy merged 5 commits into
ocaml:trunkfrom
kayceesrk:volatile_field

Conversation

@kayceesrk

@kayceesrk kayceesrk commented May 12, 2022 •

Copy link
Copy Markdown
Contributor

The PR addresses the issue with C FFI and the OCaml memory model. For context see, #10992.

The first commit make Field macro a volatile cast, and the second commit introduces Load_field macro that is not an l-value and performs an acquire load of the given field.

Goal

The comment at #10992 (comment) gives a detailed description of the aim of the PR. I shall try to summarize the issue and the aim of the PR.

The PR #10972 performs a compilation of the OCaml memory model to C11 (caml_modify, caml_atomic_*, etc) and hardware models (x86 and ARMv8). This compilation covers all of the FFI functions except Field, which is the focus on #10992. Field macro on trunk performs non-atomic reads. Since this is C, data races using the Field macro will have catch fire semantics.

Can we make Field macro an _Atomic cast to avoid catch-fire semantics? No. Field macro is also an l-value and making Field and _Atomic cast will make it not be an l-value. Our previous experience with the concurrent major GC shows that making Field not an l-value breaks an awful lot of packages. Hence, we make Field a volatile cast, which, in practice, avoids catch-fire semantics. See Linux kernel memory model https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p0124r7.html#Variable%20Access.

We also introduce Load_field macro which does an acquire load. The aim of the Load_field macro is to provide a mechanism for users to read fields in C11 compatible fashion (and not "in practice" assumptions that comes with volatile fields) that also preserves the ordering necessary for OCaml memory model. We shall encourage our users to start using Load_field in places where Field is used as an r-value. Technically, Load_field is only necessary for mutable fields, and immutable fields can be accessed using Field macro. However, for users, it will be easier to switch to Load_field unconditionally.

Possible backwards compatibility concern

Given that Field has been made volatile, the uses of &Field(..) will have the type volatile value *. This will cause C compiler to raise a warning about discarded quantifiers when functions that take a value * argument are passed volatile value * value.

error: passing argument 1 of ‘foo’ discards ‘volatile’ qualifier from pointer target type [-Werror=discarded-qualifiers]

The PR includes changes to the types of certain functions (caml_modify, caml_initialize, ...) to make the C compiler happy.

Todo

  • Performance benchmarking -- Run Sandmark on this branch to measure the impact of the change.
  • Assess the impact of backwards &Field(..) using opam health check.

CC @gadmm @stedolan.

@Octachron Octachron added this to the 5.0.0 milestone May 12, 2022
@kayceesrk

kayceesrk commented May 13, 2022 •

Copy link
Copy Markdown
Contributor Author

image

The graph above shows the normalized running time for this PR against trunk on macro benchmarks from Sandmark. The results show that there is neither a definitive slowdown nor a speedup overall; there's a max 4% swing in both directions. Given that this PR is necessary for correctness, I would consider that there is nothing to be done on the performance side.

@kayceesrk

Copy link
Copy Markdown
Contributor Author

@dra27 ran opam health check on this PR as well as this patch applied to 4.14. For 5.0.0+trunk, there are no new breakages. Every package that builds on trunk builds with this PR. For 4.14, the only breakage is ocamlnet. ocamlnet is broken on 5.0.0 already. Thanks, @dra27 for running opam health check.

@gasche

gasche commented May 14, 2022

Copy link
Copy Markdown
Member

The Sandmark results are a bit weird, as we don't see how the change could possibly improve performance. (Using volatile is supposed to disable some compiler optimizations only.) This suggests that the changes we observe, at least on the "speed up" part of the graph, are mostly tooling-related noise (maybe the different code generation creates weird code-placement effects, or maybe it is actually faster in some case to force the compiler to recompute reads, etc.). Given that the "slow down" parts seem comparable in magnitude to the "speed up" part, it's hard to tell if the results are actually meaningful.

Said otherwise: for a change that should not impact performance at all, maybe what we should expect to observe in practice, because life is complicated, is for speedup/slowdown results to fall along a gaussian distribution centered at 0. I wonder whether the results here fit this model.

@kayceesrk

Copy link
Copy Markdown
Contributor Author

I analyzed the outliers. The observed results are reproducible and not an artifact of sandmark.

test_decrompress (max speedup)

Hyperfine

kc@kaveri:~/repos/sandmark/_build$ hyperfine './5.0.0+trunk_1/benchmarks/decompress/test_decompress.exe 64 524_288' './5.0.0+trunk+volatile_field_1/benchmarks/decompress/test_decompress.exe 64 524_288'
Benchmark #1: ./5.0.0+trunk_1/benchmarks/decompress/test_decompress.exe 64 524_288
  Time (mean ± σ):      3.189 s ±  0.041 s    [User: 3.179 s, System: 0.009 s]
  Range (min … max):    3.130 s …  3.274 s    10 runs
 
Benchmark #2: ./5.0.0+trunk+volatile_field_1/benchmarks/decompress/test_decompress.exe 64 524_288
  Time (mean ± σ):      3.060 s ±  0.028 s    [User: 3.048 s, System: 0.012 s]
  Range (min … max):    3.012 s …  3.090 s    10 runs
 
Summary
  './5.0.0+trunk+volatile_field_1/benchmarks/decompress/test_decompress.exe 64 524_288' ran
    1.04 ± 0.02 times faster than './5.0.0+trunk_1/benchmarks/decompress/test_decompress.exe 64 524_288'

Perf

Here are the perf results:

trunk:

kc@kaveri:~/repos/sandmark/_build$ perf stat ./5.0.0+trunk_1/benchmarks/decompress/test_decompress.exe 64 524_288

 Performance counter stats for './5.0.0+trunk_1/benchmarks/decompress/test_decompress.exe 64 524_288':

          3,148.70 msec task-clock                #    1.000 CPUs utilized          
                 5      context-switches          #    0.002 K/sec                  
                 0      cpu-migrations            #    0.000 K/sec                  
             5,265      page-faults               #    0.002 M/sec                  
     9,240,551,815      cycles                    #    2.935 GHz                    
    28,028,690,152      instructions              #    3.03  insn per cycle         
     5,057,837,328      branches                  # 1606.328 M/sec                  
        10,103,793      branch-misses             #    0.20% of all branches        

       3.149228619 seconds time elapsed

       3.145162000 seconds user
       0.004001000 seconds sys

this PR:

kc@kaveri:~/repos/sandmark/_build$ perf stat ./5.0.0+trunk+volatile_field_1/benchmarks/decompress/test_decompress.exe 64 524_288

 Performance counter stats for './5.0.0+trunk+volatile_field_1/benchmarks/decompress/test_decompress.exe 64 524_288':

          3,139.49 msec task-clock                #    1.000 CPUs utilized          
                 9      context-switches          #    0.003 K/sec                  
                 0      cpu-migrations            #    0.000 K/sec                  
             7,013      page-faults               #    0.002 M/sec                  
     9,136,767,429      cycles                    #    2.910 GHz                    
    28,114,813,808      instructions              #    3.08  insn per cycle         
     5,058,882,903      branches                  # 1611.370 M/sec                  
        10,492,631      branch-misses             #    0.21% of all branches        

       3.140096681 seconds time elapsed

       3.123928000 seconds user
       0.015999000 seconds sys

This PR seems to cause 0.3% more instructions to be executed (28.114B vs 28.028B), due to missed compiler optimisations(?). But those instructions are executed faster (3.08 insn per cycle vs 3.03 insn per cycle).

kb (max slowdown)

Hyperfine

kc@kaveri:~/repos/sandmark/_build$ hyperfine './5.0.0+trunk_1/benchmarks/kb/kb.exe' './5.0.0+trunk+volatile_field_1/benchmarks/kb/kb.exe'
Benchmark #1: ./5.0.0+trunk_1/benchmarks/kb/kb.exe
  Time (mean ± σ):      2.832 s ±  0.018 s    [User: 2.825 s, System: 0.007 s]
  Range (min … max):    2.816 s …  2.866 s    10 runs
 
Benchmark #2: ./5.0.0+trunk+volatile_field_1/benchmarks/kb/kb.exe
  Time (mean ± σ):      2.915 s ±  0.036 s    [User: 2.909 s, System: 0.006 s]
  Range (min … max):    2.852 s …  2.979 s    10 runs
 
Summary
  './5.0.0+trunk_1/benchmarks/kb/kb.exe' ran
    1.03 ± 0.01 times faster than './5.0.0+trunk+volatile_field_1/benchmarks/kb/kb.exe'

Perf

trunk:

kc@kaveri:~/repos/sandmark/_build$ perf stat ./5.0.0+trunk_1/benchmarks/kb/kb.exe

 Performance counter stats for './5.0.0+trunk_1/benchmarks/kb/kb.exe':

          2,810.43 msec task-clock                #    1.000 CPUs utilized          
                 4      context-switches          #    0.001 K/sec                  
                 0      cpu-migrations            #    0.000 K/sec                  
             2,137      page-faults               #    0.760 K/sec                  
     8,244,770,572      cycles                    #    2.934 GHz                    
    16,000,114,884      instructions              #    1.94  insn per cycle         
     3,626,059,322      branches                  # 1290.216 M/sec                  
       141,430,823      branch-misses             #    3.90% of all branches        

       2.810932906 seconds time elapsed

       2.810875000 seconds user
       0.000000000 seconds sys

this PR:

kc@kaveri:~/repos/sandmark/_build$ perf stat ./5.0.0+trunk+volatile_field_1/benchmarks/kb/kb.exe

 Performance counter stats for './5.0.0+trunk+volatile_field_1/benchmarks/kb/kb.exe':

          2,943.68 msec task-clock                #    1.000 CPUs utilized          
                 4      context-switches          #    0.001 K/sec                  
                 0      cpu-migrations            #    0.000 K/sec                  
             2,134      page-faults               #    0.725 K/sec                  
     8,682,540,315      cycles                    #    2.950 GHz                    
    16,015,244,224      instructions              #    1.84  insn per cycle         
     3,625,079,871      branches                  # 1231.477 M/sec                  
       148,965,798      branch-misses             #    4.11% of all branches        

       2.944208362 seconds time elapsed

       2.936149000 seconds user
       0.008000000 seconds sys

This PR causes 0.09% more instructions to be executed. But they're executed at a slower rate than trunk (1.94 vs 1.84 insn per cycle).

Observation

We can see that the results are not due to measurement noise but are observable. But I'm not sure whether these are actionable since this looks like micro-architectural behaviours at play.

@gasche

gasche commented May 14, 2022 •

Copy link
Copy Markdown
Member

I would say that there are different sorts of noise. Some sources of noise generate variance from one run of the benchmark to the other (and the benchmark setup is trying to eliminate it), or from one machine to the next. But there are other sorts of noise that still qualify as noise, because they are small changes in result that do not come from a fundamental change in runtime behavior, but unpredictable complex systems placed between our source code and the behaviors we observe (for example, CPUs and their micro-architectural effects).

That latter source of "noise" (which I called "tooling noise") is what seems to be going on here. In this noise category, the performance difference that we observe on one benchmark is a deterministic function of the benchmark, but the effect on a family of benchmarks (the function from a benchmark to the performance difference) could be random/arbitrary. Maybe we can model the impact of this change as a random speedup/slowdown for each benchmark, following a Gaussian centered at 0 -- many programs seeing their performance unchanged, and a small number of benchmarks seeing small speedups or slowdowns. (Or maybe there is a mix of "micro-architectural effects with winners and losers" and actual real slowdowns, caused by say a specific runtime function being pessimized; in that case the average speedup/slowdown would be tilted towards the "slowdown" part, but if such an effect exists it is not clear in the benchmark suite.)

In summary: we observe speedups of 4% that have no clear reason (possibly: obscure microarchitectural effects), which suggests that we can discard all performance effects of up to 4% as just weird magic. Only much larger changes would be representative, and there are none in this benchmark suite.

@kayceesrk

Copy link
Copy Markdown
Contributor Author

Thanks for the summary. In the past, we have had features that introduce swings of 2-4% in both directions. A good approximation of the overall change is the geometric mean of the normalised running times. For this PR, the geomean is 0.9998. That is, with this PR, the benchmarks run very marginally faster than trunk (by 0.02%).

@Octachron

Octachron commented May 16, 2022 •

Copy link
Copy Markdown
Member

A possible testable null-hypothesis is that the change is no more likely to decrease performance than to increase them.
Thus, if we consider the number of test with decreased performance minus D after N i.i.d test, its distribution should be a binomial:

P(D = d) = (1/2)^N N!/((N-D)!D!

With 50 samples, this hypothesis can be rejected with a p-value of 5% if we observe 31 samples with decreased performances. Since this is not the case, this null hypothesis is not observably wrong.

For testing a gaussian hypothesis, I would need to know the variance. @kayceesrk , if you send me the raw data I can have a look. However, I am not sure that the extremal values observed in the benchmark are compatible with a gaussian hypothesis: with 50 samples, it is possible to reject a gaussian hypothesis with 5% p-value if the maximum is greater than 3.08 σ and that might be the case here.

@gasche

gasche commented May 16, 2022

Copy link
Copy Markdown
Member

It's surprisingly hard to find clear explanation on this problem that looks common, important and affecting people who are not experts in benchmark design. (What's the expected distribution of the performance impact of microarchitectural effects these days?) All I could find was STABILIZER: statistically sound performance evaluation, Curtsinger and Berger, 2013, a paper on a complex system to dynamically randomize the (code, heap, stack) layout of running programs, performed using instrumentation at the LLVM level. (It looks like it would be quite some amount of work to reproduce it in the OCaml compiler, but we could actually try to enable this on the OCaml runtime code.) They report that, using their randomization tool, they observe that layout effects follow a Gaussian distribution ("very often"; they don't on two specific benchmarks).

@xavierleroy

Copy link
Copy Markdown
Contributor

Maybe we could have this general discussion (on interpreting Sandmark results) separately from this PR. But, yes, differences in code placement can affect execution times by several percents. To evaluate the impact of optimizations, I prefer to count the number of instructions executed, there's less noise this way.

@xavierleroy xavierleroy left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's a few extra points in the code where you could avoid a (value *) cast by declaring some variables or struct fields volatile value *. On the one hand, I like it when there are fewer casts. On the other hand those volatile declarations add noise. I don't feel strongly either way.

Comment thread runtime/array.c Resolved
Comment thread runtime/compare.c Resolved
Comment thread runtime/extern.c Resolved
Comment thread runtime/intern.c Resolved
Comment thread runtime/interp.c Resolved
Comment thread runtime/minor_gc.c Resolved
@kayceesrk

kayceesrk commented May 22, 2022 •

Copy link
Copy Markdown
Contributor Author

Building upon @xavierleroy's comments, I refactored the PR further to remove almost all of the casts of volatile value* to value* by declaring variables as volatile value*. The code feels easier to reason about than casting to remove the volatile qualifier.

The only two places where we explicitly cast volatile value* to value* are

  1. In the call to memmove, where the type cast is necessary.
  2. In Ref_table_add. All ref tables are local to a particular domain.

@gasche gasche left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like the new patchset, it's clean, and the rationale for the change has been discussed at length. We haven't been able to detect a performance regression in the benchmarks, as we expected.

(I wondered if it would make sense to introduce an alias for volatile value *, maybe lvalue :-' but this is no priority.)

@gasche

gasche commented May 23, 2022

Copy link
Copy Markdown
Member

I think that a Changes entry would make sense: this is a user-visible change, including compared to 4.x, and it would be useful to provide clear context for it and also to credit Guillaume's contribution.

@xavierleroy xavierleroy left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks very good to me. Thanks!

@gadmm

gadmm commented May 23, 2022

Copy link
Copy Markdown
Contributor

I would like to have a look at this PR, it seems like I will have various comments. Can you please leave me the time to review it later?

In the meanwhile, I have not seen much discussion about the proposal at #10992 (comment) which motivates this PR. Would some memory-model expert who feel involved with OCaml please tell us what they think about it?

@kayceesrk

Copy link
Copy Markdown
Contributor Author

Can you please leave me the time to review it later?

Sounds good. Thanks for having a look. I'll wait until the review is completed to write the Changes entry.

@xavierleroy

Copy link
Copy Markdown
Contributor

We need to make progress towards the 5.0 release, so @gadmm please review ASAP or tell us you can't do it, but don't make us wait.

@gadmm

gadmm commented Jun 3, 2022

Copy link
Copy Markdown
Contributor

I'll give it a try over the week-end.

@gadmm

gadmm commented Jun 5, 2022

Copy link
Copy Markdown
Contributor

The PR addresses the issue with C FFI and the OCaml memory model. For context see, #10992.

To be clearer, this PR does not close #10992 by itself.

The first commit make Field macro a volatile cast, and the second commit introduces Load_field macro that is not an l-value and performs an acquire load of the given field.

I would like that Load_field is added in a separate PR. First, the proposal is to add an acquire fence when going from OCaml to C to reflect losing track of data dependencies, so that an expert user does not have to use Load_field for immutable fields. It will be the occasion to discuss my reasoning or tell me that it is not necessary (the counter-example is a mutable load operated on the OCaml side followed by two nested immutable loads on the C side, maybe one is enough). Adding the fence involves changes to the .S files, and perhaps benchmarking the change (e.g. do you also add it to noalloc calls or is it too costly?). Second, it would be good if the PR could include its documentation so we can be sure that we agree on its recommended usage.

The PR #10972 performs a compilation of the OCaml memory model to C11 (caml_modify, caml_atomic_*, etc) and hardware models (x86 and ARMv8). This compilation covers all of the FFI functions except Field, which is the focus on #10992.

Does this PR include a review that there are no other macros similar to Field?

Can we make Field macro an _Atomic cast to avoid catch-fire semantics? No. Field macro is also an l-value and making Field and _Atomic cast will make it not be an l-value. Our previous experience with the concurrent major GC shows that making Field not an l-value breaks an awful lot of packages.

With #define Field(x, i) (((_Atomic(value) *)(x)) [i]) it can be used both as an l- and r-value. However, this translates into SC-store/loads, which have a prohibitive cost on all platforms. It would however avoid catch-fire semantics both in practice and theory unlike volatile. I agree that what dooms it is the too great effort needed for users to replace all the occurrences of Field in existing code (including initializing stores) by something more sensible (even progressively).

Given that Field has been made volatile, the uses of &Field(..) will have the type volatile value *. This will cause C compiler to raise a warning about discarded quantifiers when functions that take a value * argument are passed volatile value * value.

error: passing argument 1 of ‘foo’ discards ‘volatile’ qualifier from pointer target type [-Werror=discarded-qualifiers]

The PR includes changes to the types of certain functions (caml_modify, caml_initialize, ...) to make the C compiler happy.

This is a bigger change than I expected.

First, I think that volatile should remain an implementation detail since it is not an official part of the memory model in our proposal (Load_field is, instead). So I would prefer if it is hidden for users behind a typedef.

But I am also worried that changing the signature of caml_modify and caml_initialize simply moves the problem around. Opam health check can be useful to find examples of how code can break, but by definition it cannot show that no code breaks. Here the lesson is you have found in OCaml's own code an example of how code can break (which does not look very specific to code that would only be used internally).

This, together with the risks of users avoiding Load_field altogether, makes me rethink the opportunity of adding a volatile cast to the Field macro, instead of nothing at all.

Todo

[x] Performance benchmarking -- Run Sandmark on this branch to measure the impact of the change.

I was wondering (here and for other multicore benchmarks that show similar fluctuations) if you have tried to vary the compiler and the compilation options. Some compilation options create a different code layout, which can sometimes be enough to convince whether the performance swing is relevant or not. (In terms of Florian's qualitative criterion, it gives you more independent data points.)

Can you please point me at the specs of the machine?

[x] Assess the impact of backwards &Field(..) using opam health check.

Does opam health check catch new warnings, or does it only catch them in the cases where the warning is turned into an error?

@kayceesrk

Copy link
Copy Markdown
Contributor Author

I would like that Load_field is added in a separate PR.

Sure. It would be a good chance to include the documentation for Load_field in that PR.

Does this PR include a review that there are no other macros similar to Field?

No.

With #define Field(x, i) (((_Atomic(value) *)(x)) [i]) it can be used both as an l- and r-value. However, this translates into SC-store/loads, which have a prohibitive cost on all platforms. It would however avoid catch-fire semantics both in practice and theory unlike volatile.

Good point. Thanks for clarifying.

Ideally, it would have been better than volatile cast if we were able to write #define Field(x, i) (((_Atomic(relaxed) value *)(x)) [i]) which treats the loads and stores as having relaxed ordering. Such a facility does not exist in C11.

Does opam health check catch new warnings, or does it only catch them in the cases where the warning is turned into an error?

Right. The runtime is built -Werror, which is why the error

error: passing argument 1 of ‘foo’ discards ‘volatile’ qualifier from pointer target type [-Werror=discarded-qualifiers]

shows up. Unless the C parts of the libraries are also built with -Werror, the build will not error out. @dra27 Does dune based compilation of C libraries already do -Werror?

If not, I wonder whether we can do something simple like:

alias gcc="gcc -Werror"

to get an assessment of the failing packages.

I was wondering (here and for other multicore benchmarks that show similar fluctuations) if you have tried to vary the compiler and the compilation options. Some compilation options create a different code layout, which can sometimes be enough to convince whether the performance swing is relevant or not. (In terms of Florian's qualitative criterion, it gives you more independent data points.)

No. We don't currently perform benchmarking with changing compiler and compiler options regularly. We will see fluctuations by changing the compilation option. However, it is hard to translate the observed fluctuations into actionable information. That said, what has been useful is to use the sandmark results as a starting point to analyse the performance of outliers in detail as I have done in #11255 (comment). Firstly, in addition to looking at the running time, the change in the number of instructions executed is useful to look at. But this can also throw surprising results. For the program which runs fastest with this PR compared to trunk (test_decompress), the program actually executes 0.3% more instructions. The CPU happens to run them faster. We already have enough fluctuations even without changing the compiler options due to micro-architectural optimizations.

From my perspective, this PR is needed for correctness. Since the performance impact is not significant, I would consider the performance impact to be acceptable.

Can you please point me at the specs of the machine?

https://sandmark.tarides.com/#machines-used-for-generating-results

First, I think that volatile should remain an implementation detail since it is not an official part of the memory model in our proposal (Load_field is, instead). So I would prefer if it is hidden for users behind a typedef.

Are you thinking about something like typedef volatile value* valueptr?

@xavierleroy

Copy link
Copy Markdown
Contributor

The PR includes changes to the types of certain functions (caml_modify, caml_initialize, ...) to make the C compiler happy.

This is a bigger change than I expected.

From an API user's perspective, the big visible change is that &Field(x,i) is no longer of value * type. Adding a volatile modifier to the first argument of caml_modify is transparent, since you can still pass a plain value *.

This proposal does make the assumption that few third-party codes take pointers inside blocks &Field(x,i) except to pass them to caml_modify or caml_initialize. Indeed, codes that do this have a high chance of breaking the GC interface. It would be interesting to see what uses can be found in the wild.

Assuming third-party code should better not work with pointers inside blocks, there's no need for a typedef. I like the verbosity of volatile value *: it reminds us that something fishy is going on :-)

@dra27

dra27 commented Jun 6, 2022

Copy link
Copy Markdown
Member

Dune doesn't add -Werror for C files, no - that's only done for OCaml files in the dev profile. Projects can opt-in to that by adding (env (dev (c_flags :standard -Werror))) to dune files.

However, we don't do this in OCaml's build system either - for a release tag / tarball we also compile C objects without -Werror. That's point of doing this change with volatile, though - single-domain code continues to compile, just with additional warnings, developers should develop with -Werror turned on, and can then address poor/incorrect uses of Field in subsequent releases.

I don't think there's a reliable way to turn on -Werror for all packages to do a health-check run, but I'm not sure that it's worth it (unless I'm still missing something)?

@kayceesrk

Copy link
Copy Markdown
Contributor Author

Thanks for the response @dra27.

I was under the false assumption that the lack of new failures with this PR indicated that third-party code was not taking internal pointers to blocks and using them in interesting ways. Like @xavierleroy, it would be interesting to see whether this pattern does occur in the wild, and how many packages are broken due to this change. That said, I don't think that the result of such an analysis should block this PR.

@gadmm

gadmm commented Jun 7, 2022

Copy link
Copy Markdown
Contributor

It would be nice to have a look if any other macro needs the volatile cast so they are all fixed at once (Field was only meant as an example of problem).

Yes I am thinking about something like typedef volatile value * value_ref. This might depend on usages of value * in the wild. I am not convinced that the API discourages the use of pointers. In fact, even OCaml uses value pointers in its API (see caml_named_value, which incidentally should certainly return const volatile value * instead of const value * given that parallel mutations are possible via caml_register_named_value). There is also the question of whether people who use value * are encouraged or not to switch entirely to volatile value * when pointing inside the OCaml heap (if they are careful, they only need to use Load_field in the right places).

I agree that adding volatile to caml_modify/initialize is better than merely moving the problem, for reasons said.

@Octachron

Copy link
Copy Markdown
Member

Am I reading correctly that every one agree that this PR is a good compromise and a step forward? If so, I would propose to first merge this PR, and then move to reviewing other macros in subsequent PRs or issues.

xavierleroy added a commit to kayceesrk/ocaml that referenced this pull request Jul 11, 2022
@xavierleroy

Copy link
Copy Markdown
Contributor

I agree this PR is in good shape. I just rebased to fix conflicts and added a Changes entry. Will run CI precheck next.

@xavierleroy

Copy link
Copy Markdown
Contributor

CI precheck is positive. Let's merge!

@xavierleroy
xavierleroy merged commit 0e09dc4 into ocaml:trunk Jul 11, 2022
@xavierleroy

Copy link
Copy Markdown
Contributor

I'll wait for more CI to run on trunk, then pick to 5.0.

@kayceesrk

Copy link
Copy Markdown
Contributor Author

Thanks for pushing the PR across the line @Octachron and @xavierleroy.

xavierleroy pushed a commit that referenced this pull request Jul 11, 2022
`Field(v,i)` is now `volatile`-qualified, to better handle races with concurrent updates in C or in OCaml.
(More complete discussion at #10992.)

`&Field(v,i)` now has type `volatile value *`. Add `volatile` qualifiers to `caml_modify`, `caml_initialize`,
and in internal parts of the runtime system.

(cherry picked from commit 0e09dc4)
@xavierleroy

Copy link
Copy Markdown
Contributor

CI looks globally good, so here is the 5.0 cherry-pick: 7b76f07

@gadmm

gadmm commented Jul 11, 2022

Copy link
Copy Markdown
Contributor

I opened an issue with my comment left without reply at #11426.

Comment thread runtime/caml/mlvalues.h
#define Op_atomic_val(x) ((atomic_value *) (x))
/* Fields are numbered from 0. */
#define Field(x, i) (((value *)(x)) [i]) /* Also an l-value. */
#define Field(x, i) (((volatile value *)(x)) [i]) /* Also an l-value. */

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Field(x, 0) and Op_val(x) previously had the exact same behavior, but Field is now a volatile cast whereas Op_val went unchanged in this PR.

Was this on purpose?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had missed it, but perhaps #11426 will take care of that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants