Skip to content

Fix shutdown with TRACY_NO_EXIT=1 on Android. - #134

Merged
wolfpld merged 7 commits into
wolfpld:masterfrom
bjacob:deadlock
Nov 26, 2020
Merged

wolfpld merged 7 commits into
wolfpld:masterfrom
bjacob:deadlock

Conversation

@bjacob

@bjacob bjacob commented Nov 24, 2020 •

Copy link
Copy Markdown
Contributor

With TRACY_NO_EXIT=1 on Android, the profiled program was never terminating, not even after Tracy UI connected, finished getting data and terminated itself.

Debugging this, I first found that the break here is only breaking out of the inner loop, so we're back to the outer for(;;) loop, so we need to also break out of it. That's the first line in this commit.

(Side note: I would be very interested in an explanation of why this code uses std::memory_order_relaxed - what is providing the memory ordering relationships here? Anyway, I played with that too but that wasn't relevant to the observed issue.)

Once I had fixed the above, it still wasn't terminating. Then I noticed that the tracy_systrace process was still running on the device. Killing it allowed the profiled program to terminate. That also explained why we were getting errors as follows while trying to create tracy_systrace: we were failing to overwrite this binary as it was still running.

sh: can't create /data/tracy_systrace: Text file busy

According to ps on the device, tracy_systrace was sleeping:

flame:/ # ps -A | grep -i tracy                                                                                                                                                                           
root         11817 11787   33160   2628 SyS_nanosleep       0 S tracy_systrace

So this wasn't a matter of just waitpid on it. I tried calling kill(2) on it with SIGKILL but that didn't work; in hindsight that might be a permissions problem; i could retry with the usual su technique as elsewhere in this file, but...

At this point I remembered that on recent Android devices we don't seem to need tracy_systrace at all, as cat /sys/kernel/debug/tracing/trace_pipe seems to be working fine. So I changed the exec'd command to try that first, and fall back to tracy_systrace otherwise (note - I needed to implement that in the shell command, whence the || shell operator, and not in C++, because exec never returns unless in some basic error cases, and here it likely won't return even if cat /sys/kernel/debug/tracing/trace_pipe fails).

Then I added the waitpid to wait on this child, which works fine as long as we are taking the cat /sys/kernel/debug/tracing/trace_pipe code path.

So we still have (I guess) the never-terminating issue in the tracy_systrace code path, but that is now only a legacy fallback.

@wolfpld

wolfpld commented Nov 24, 2020

Copy link
Copy Markdown
Owner

With TRACY_NO_EXIT=1 on Android, the profiled program was never terminating, not even after Tracy UI connected, finished getting data and terminated itself.

Debugging this, I first found that the break here is only breaking out of the inner loop, so we're back to the outer for(;;) loop, so we need to also break out of it. That's the first line in this commit.

Nicely found.

(Side note: I would be very interested in an explanation of why this code uses std::memory_order_relaxed - what is providing the memory ordering relationships here? Anyway, I played with that too but that wasn't relevant to the observed issue.)

There is no relationship to order here. It's just a status variable that indicates when threads should exit.

At this point I remembered that on recent Android devices we don't seem to need tracy_systrace at all, as cat /sys/kernel/debug/tracing/trace_pipe seems to be working fine.

It doesn't work fine. cat will spinlock waiting for kernel data, effectively keeping one CPU core occupied all the time.

So we still have (I guess) the never-terminating issue in the tracy_systrace code path

Maybe checking if stdout is still open in tracy_systrace will help here? The sources are in extra/systrace, along with a build script. The resulting executable has to be then converted to an array accessible by client (TracySysTracePayload.hpp), which can be created using binary_to_compressed_c utility provided by ImGui.

@bjacob

bjacob commented Nov 24, 2020

Copy link
Copy Markdown
Contributor Author

There is no relationship to order here. It's just a status variable that indicates when threads should exit.

More precise questions:

  1. What is preventing the compiler from moving the traceActive.load( std::memory_order_relaxed ) out of the loop, as an optimization (assume that load() gets inlined, so that thanks to std::memory_order_relaxed it is just an ordinary memory access) ?
  2. Likewise on the store side,
    TraceWrite( TracingOn, sizeof( TracingOn ), "0", 2 );
    traceActive.store( false, std::memory_order_relaxed );
    , what is ensuring that the effect of the store is visible to the sampling thread after the effect of the TraceWrite in the line above? Is it because TraceWrite performs IO and that makes it act as an implied barrier?

It doesn't work fine. cat will spinlock waiting for kernel data, effectively keeping one CPU core occupied all the time.

Ah, thanks for explaining the rationale for tracy_systrace.

I'm runnin Android 10 and cat isn't spinlocking here.

$ top -n1 | grep trace_pipe | grep -v grep                                                                                                                                                        
13553 root         20   0  35M 3.4M 2.8M S  0.0   0.0   0:00.00 cat /sys/kernel/debug/tracing/trace_pipe

(One of the 0.0 here is CPU usage).

Actually if I strace it,

# strace cat /sys/kernel/debug/tracing/trace_pipe   
 ... lots of junk ...
openat(AT_FDCWD, "/sys/kernel/debug/tracing/trace_pipe", O_RDONLY|O_CLOEXEC) = 3
read(3, 

so it is passively waiting on a blocking read.

Out of curiosity is this about the implementation of cat in Magisk?

Would dd if=/sys/kernel/debug/tracing/trace_pipe be a better replacement? Here, just like cat, stracing it shows it waiting in a blocking read.

@wolfpld

wolfpld commented Nov 24, 2020

Copy link
Copy Markdown
Owner

What is preventing the compiler from moving the traceActive.load( std::memory_order_relaxed ) out of the loop, as an optimization (assume that load() gets inlined, so that thanks to std::memory_order_relaxed it is just an ordinary memory access) ?

Complexity of code? :) Joking aside, you are probably right here. The C++ standard wording once again manages to be clear as mud.

what is ensuring that the effect of the store is visible to the sampling thread after the effect of the TraceWrite in the line above? Is it because TraceWrite performs IO and that makes it act as an implied barrier?

It doesn't matter. Signalling the thread that it should exit and disabling tracing on the kernel side are two separate things that don't depend on each other.

I'm runnin Android 10 and cat isn't spinlocking here.
Actually if I strace it, it is passively waiting on a blocking read.

I think you are skipping kernel time here. What I do is use Tracy to see what is happening at the scheduler level. For example, this is cat:

obraz

obraz

And tracy_systrace:

obraz

obraz

Despite the same application name, these are two different workloads. The second one is utilizing an external SDK to capture video, which makes the system more busy, as can be seen by number of scheduled threads. Unfortunately, this is what I currently have available. You may reproduce these measurements using both methods with your application, to see if there's an observable difference on your device. There should be, as constant wakeups of cat produce extra scheduler data for it to handle.

In some cases using cat is pathological:

obraz

Evidently the OS tries to save power here, keeping just one core active, which results in constant preemption of the profiled application's thread, which in this example is actively trying to do something (not waiting).

@bjacob

bjacob commented Nov 25, 2020 •

Copy link
Copy Markdown
Contributor Author

Thanks a lot for the explanation. Now I understand what tracy_systrace is all about, and I learned something I had no idea about (blocking reads being implemented with such aggressive polling inside the linux kernel).

Please review; this code works for me on Android 10 / Aarch64. I have tested that the tracy_systrace binary also works on armv7 (it does dump trace_pipe) but I haven't tested the end-to-end integration on armv7.

I edited the build.sh script to make it work for me (pointing to CC and STRIP in Android NDK r21d). Unfortunately I had to drop 2 aspects of it:

  • sstrip: I could not find a Debian package for it. So I made it optional in build.sh, you can point it to it and it will use it.
  • -R .gnu.hash: this was preventing the binary from loading on Android 10. The binary loader was complaining specifically about the missing hash! I don't know why I had this issue while the existing binary was loading fine on my device.

I also made another change: removed that dup2 redirecting tracy_systrace's stderr to stdout. I did it at a point when I was debugging it by letting it write to stderr, and that was causing TracySysTrace to crash parsing the output. Then I thought, is there any reason for this redirection? Since unexpected data in this pipe causes TracySysTrace to crash parsing it, do we want to redirect error messages into it? Without the redirection, these error messages show in the terminal. If that is unwanted, we could instead dup2 to open("/dev/null", O_WRONLY).

Regarding C++ atomics: this is definitely a hairy topic, C++ standardization on it is still iterating on it, and the lead person on it has been giving advice like this: (see these slides, go to slide 34) "Weakly ordered atomics are hard! Avoid when possible!"
So I think it makes sense to only use explicit memory orders with std::atomic when that's motivated by a really specific perfomance reason. In the present file, we are using relaxed memory order in places where that doesn't seem to be necessary for performance, since we are doing much more expensive things immediately before or after anyway. The overhead of a sequentially consistent atomic is hard to quantify since that has side effects on how the compiler can reorder code AND on how an out-of-order CPU can also reorder code internally at runtime, but the CPU-level synchronization primitive (LDXR/STXR or ARMv8.1 atomic instruction such as LDADD) is typically 60 cycles in the uncontended case on typical current Android devices ARM CPUs. So, round that up to 100 cycles to account for slightly worse code generation and execution (no reordering across it). By contrast, the cheapest system call (outside of VDSO ones) is hundreds of cycles. So in a context where we are doing any system calls (let alone actual IO!) I would suggest to stick with default std::atomic memory order, not explicit.

@wolfpld

wolfpld commented Nov 25, 2020

Copy link
Copy Markdown
Owner

sstrip: I could not find a Debian package for it. So I made it optional in build.sh, you can point it to it and it will use it.

It is contained in the elfkickers package, which seems to be not available in debian. You can get it from https://github.com/BR903/ELFkickers.

-R .gnu.hash: this was preventing the binary from loading on Android 10. The binary loader was complaining specifically about the missing hash! I don't know why I had this issue while the existing binary was loading fine on my device.

Probably something changed in how the binary is built by the compiler in the meantime. The original list of sections to remove was created by trying to remove all that was there and checking if the binary still runs.

I also made another change: removed that dup2 redirecting tracy_systrace's stderr to stdout. I did it at a point when I was debugging it by letting it write to stderr, and that was causing TracySysTrace to crash parsing the output. Then I thought, is there any reason for this redirection? Since unexpected data in this pipe causes TracySysTrace to crash parsing it, do we want to redirect error messages into it? Without the redirection, these error messages show in the terminal. If that is unwanted, we could instead dup2 to open("/dev/null", O_WRONLY).

Good point. I think redirecting to /dev/null will be fine.

I think it makes sense to only use explicit memory orders with std::atomic when that's motivated by a really specific perfomance reason.

There always is a performance reason :)

side effects on how the compiler can reorder code AND on how an out-of-order CPU can also reorder code internally at runtime

I don't think instruction reordering (be it by compiler or by CPU) has an impact here. My resasoning here is as follows: I fully expect a number of "incorrect" loop iterations until the memory controller finally catches up to the value stored by the other thread. This is not a problem, as this cost is only paid once (when the state is changing), and this approach reduces the 100 cycles per-read stall to just a normal memory read cost during normal operation, when the value is not changing.

I would suggest to stick with default std::atomic memory order, not explicit.

I believe the default (seq_cst) to be always quite bad? If there was to be a change, I would expect to use release and acquire ordering.

Generally speaking, I hear you there, but I'm not sure I want to act right now. There are other places in code where this pattern is used, for example:

for(;;)
{
if( m_exit.load( std::memory_order_relaxed ) == true ) return;
if( m_signalSwitch.load( std::memory_order_relaxed ) == true ) break;
YieldThread();
}

To make things worse, the relaxed ordering is also used in an example at https://en.cppreference.com/w/cpp/atomic/atomic_flag:

             while (lock.test(std::memory_order_relaxed))     // test lock
                 ; // spin

@bjacob

bjacob commented Nov 26, 2020

Copy link
Copy Markdown
Contributor Author

Thanks for the review and answers. Now this is with sstrip and we recover the sizes that these files used to have (it's even shrunk on armv7).

I tried again with -R .gnu.hash but got this message again - pasting it here for the record:

CANNOT LINK EXECUTABLE "/data/tracy_systrace": empty/missing DT_HASH/DT_GNU_HASH in "/data/tracy_systrace" (new hash type from the future?)

Regarding memory_order_relaxed, it looks like compilers are treating relaxed atomics as side effects (so they can't optimized apparently redundant accesses like they would for regular memory accesses) even if I can't find where in the spec it says that they have to.

@wolfpld
wolfpld merged commit dfdf70a into wolfpld:master Nov 26, 2020
bjacob added a commit to bjacob/iree that referenced this pull request Nov 26, 2020
bjacob added a commit to iree-org/iree that referenced this pull request Nov 26, 2020
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.

2 participants