runtime: release worldsema before Gosched in STW GC mode

After CL 182657 we no longer hold worldsema across the GC, we hold
gcsema instead.

However in STW GC mode we don't release worldsema before calling Gosched
on the user goroutine (note that user goroutines are disabled during STW
GC) so that user goroutine holds onto it. When the GC is done and the
runtime inevitably wants to "stop the world" again (though there isn't
much to stop) it'll sit there waiting for worldsema which won't be
released until the aforementioned goroutine is scheduled, which it won't
be until the GC is done!

So, we have a deadlock.

The fix is easy: just release worldsema before calling Gosched.

Fixes #34736.

Change-Id: Ia50db22ebed3176114e7e60a7edaf82f8535c1b4
Reviewed-on: https://go-review.googlesource.com/c/go/+/208379
Run-TryBot: Michael Knyszek <mknyszek@google.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Cherry Zhang <cherryyz@google.com>
diff --git a/src/runtime/mgc.go b/src/runtime/mgc.go
index 0bc5568..bda8ead 100644
--- a/src/runtime/mgc.go
+++ b/src/runtime/mgc.go
@@ -1368,6 +1368,13 @@
 		work.pauseNS += now - work.pauseStart
 		work.tMark = now
 	})
+
+	// Release the world sema before Gosched() in STW mode
+	// because we will need to reacquire it later but before
+	// this goroutine becomes runnable again, and we could
+	// self-deadlock otherwise.
+	semrelease(&worldsema)
+
 	// In STW mode, we could block the instant systemstack
 	// returns, so don't do anything important here. Make sure we
 	// block rather than returning to user code.
@@ -1375,7 +1382,6 @@
 		Gosched()
 	}
 
-	semrelease(&worldsema)
 	semrelease(&work.startSema)
 }