2014-12-03 15:49:51 -08:00
|
|
|
// Copyright 2014 Citra Emulator Project
|
2014-12-16 21:38:14 -08:00
|
|
|
// Licensed under GPLv2 or any later version
|
2014-12-03 15:49:51 -08:00
|
|
|
// Refer to the license.txt file included.
|
|
|
|
|
2015-05-06 00:06:12 -07:00
|
|
|
#include "common/assert.h"
|
2014-12-03 15:49:51 -08:00
|
|
|
|
|
|
|
#include "core/hle/kernel/kernel.h"
|
|
|
|
#include "core/hle/kernel/semaphore.h"
|
|
|
|
#include "core/hle/kernel/thread.h"
|
|
|
|
|
|
|
|
namespace Kernel {
|
|
|
|
|
2015-01-31 16:56:59 -08:00
|
|
|
Semaphore::Semaphore() {}
|
|
|
|
Semaphore::~Semaphore() {}
|
|
|
|
|
2015-01-11 07:53:11 -08:00
|
|
|
ResultVal<SharedPtr<Semaphore>> Semaphore::Create(s32 initial_count, s32 max_count,
|
|
|
|
std::string name) {
|
2014-12-04 08:40:36 -08:00
|
|
|
|
2014-12-12 17:46:52 -08:00
|
|
|
if (initial_count > max_count)
|
|
|
|
return ResultCode(ErrorDescription::InvalidCombination, ErrorModule::Kernel,
|
|
|
|
ErrorSummary::WrongArgument, ErrorLevel::Permanent);
|
|
|
|
|
2015-01-11 07:53:11 -08:00
|
|
|
SharedPtr<Semaphore> semaphore(new Semaphore);
|
2014-12-03 15:49:51 -08:00
|
|
|
|
2014-12-04 08:55:13 -08:00
|
|
|
// When the semaphore is created, some slots are reserved for other threads,
|
|
|
|
// and the rest is reserved for the caller thread
|
2014-12-12 17:46:52 -08:00
|
|
|
semaphore->max_count = max_count;
|
2014-12-12 19:22:11 -08:00
|
|
|
semaphore->available_count = initial_count;
|
2015-01-11 07:53:11 -08:00
|
|
|
semaphore->name = std::move(name);
|
2014-12-03 15:49:51 -08:00
|
|
|
|
2015-01-11 07:53:11 -08:00
|
|
|
return MakeResult<SharedPtr<Semaphore>>(std::move(semaphore));
|
2014-12-04 08:40:36 -08:00
|
|
|
}
|
|
|
|
|
2015-01-11 07:53:11 -08:00
|
|
|
bool Semaphore::ShouldWait() {
|
|
|
|
return available_count <= 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
void Semaphore::Acquire() {
|
2015-01-20 17:16:47 -08:00
|
|
|
ASSERT_MSG(!ShouldWait(), "object unavailable!");
|
2015-01-11 07:53:11 -08:00
|
|
|
--available_count;
|
|
|
|
}
|
2014-12-04 08:40:36 -08:00
|
|
|
|
2015-01-11 07:53:11 -08:00
|
|
|
ResultVal<s32> Semaphore::Release(s32 release_count) {
|
|
|
|
if (max_count - available_count < release_count)
|
2014-12-04 08:40:36 -08:00
|
|
|
return ResultCode(ErrorDescription::OutOfRange, ErrorModule::Kernel,
|
|
|
|
ErrorSummary::InvalidArgument, ErrorLevel::Permanent);
|
|
|
|
|
2015-01-11 07:53:11 -08:00
|
|
|
s32 previous_count = available_count;
|
|
|
|
available_count += release_count;
|
2014-12-04 08:40:36 -08:00
|
|
|
|
|
|
|
// Notify some of the threads that the semaphore has been released
|
|
|
|
// stop once the semaphore is full again or there are no more waiting threads
|
2015-01-11 07:53:11 -08:00
|
|
|
while (!ShouldWait() && WakeupNextThread() != nullptr) {
|
|
|
|
Acquire();
|
2014-12-04 08:40:36 -08:00
|
|
|
}
|
|
|
|
|
2015-01-11 07:53:11 -08:00
|
|
|
return MakeResult<s32>(previous_count);
|
2014-12-03 15:49:51 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
} // namespace
|