// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

//go:build dragonfly || freebsd || linux

package runtime

import (
	
	
)

// We use the uintptr mutex.key and note.key as a uint32.
//
//go:nosplit
func key32( *uintptr) *uint32 {
	return (*uint32)(unsafe.Pointer())
}

// One-time notifications.
func noteclear( *note) {
	.key = 0
}

func notewakeup( *note) {
	 := atomic.Xchg(key32(&.key), 1)
	if  != 0 {
		print("notewakeup - double wakeup (", , ")\n")
		throw("notewakeup - double wakeup")
	}
	futexwakeup(key32(&.key), 1)
}

func notesleep( *note) {
	 := getg()
	if  != .m.g0 {
		throw("notesleep not on g0")
	}
	 := int64(-1)
	if *cgo_yield != nil {
		// Sleep for an arbitrary-but-moderate interval to poll libc interceptors.
		 = 10e6
	}
	for atomic.Load(key32(&.key)) == 0 {
		.m.blocked = true
		futexsleep(key32(&.key), 0, )
		if *cgo_yield != nil {
			asmcgocall(*cgo_yield, nil)
		}
		.m.blocked = false
	}
}

// May run with m.p==nil if called from notetsleep, so write barriers
// are not allowed.
//
//go:nosplit
//go:nowritebarrier
func notetsleep_internal( *note,  int64) bool {
	 := getg()

	if  < 0 {
		if *cgo_yield != nil {
			// Sleep for an arbitrary-but-moderate interval to poll libc interceptors.
			 = 10e6
		}
		for atomic.Load(key32(&.key)) == 0 {
			.m.blocked = true
			futexsleep(key32(&.key), 0, )
			if *cgo_yield != nil {
				asmcgocall(*cgo_yield, nil)
			}
			.m.blocked = false
		}
		return true
	}

	if atomic.Load(key32(&.key)) != 0 {
		return true
	}

	 := nanotime() + 
	for {
		if *cgo_yield != nil &&  > 10e6 {
			 = 10e6
		}
		.m.blocked = true
		futexsleep(key32(&.key), 0, )
		if *cgo_yield != nil {
			asmcgocall(*cgo_yield, nil)
		}
		.m.blocked = false
		if atomic.Load(key32(&.key)) != 0 {
			break
		}
		 := nanotime()
		if  >=  {
			break
		}
		 =  - 
	}
	return atomic.Load(key32(&.key)) != 0
}

func notetsleep( *note,  int64) bool {
	 := getg()
	if  != .m.g0 && .m.preemptoff != "" {
		throw("notetsleep not on g0")
	}

	return notetsleep_internal(, )
}

// same as runtimeĀ·notetsleep, but called on user g (not g0)
// calls only nosplit functions between entersyscallblock/exitsyscall.
func notetsleepg( *note,  int64) bool {
	 := getg()
	if  == .m.g0 {
		throw("notetsleepg on g0")
	}

	entersyscallblock()
	 := notetsleep_internal(, )
	exitsyscall()
	return 
}

func beforeIdle(int64, int64) (*g, bool) {
	return nil, false
}

func checkTimeouts() {}

//go:nosplit
func semacreate( *m) {}

//go:nosplit
func semasleep( int64) int32 {
	 := getg().m

	for  := atomic.Xadd(&.waitsema, -1); ;  = atomic.Load(&.waitsema) {
		if int32() >= 0 {
			return 0
		}
		futexsleep(&.waitsema, , )
		if  >= 0 {
			if int32() >= 0 {
				return 0
			} else {
				return -1
			}
		}
	}
}

//go:nosplit
func semawakeup( *m) {
	 := atomic.Xadd(&.waitsema, 1)
	if  == 0 {
		futexwakeup(&.waitsema, 1)
	}
}