2014-12-03 18:49:51 -05:00
|
|
|
// Copyright 2014 Citra Emulator Project
|
2014-12-17 00:38:14 -05:00
|
|
|
// Licensed under GPLv2 or any later version
|
2014-12-03 18:49:51 -05:00
|
|
|
// Refer to the license.txt file included.
|
|
|
|
|
|
|
|
#include "common/common.h"
|
|
|
|
|
|
|
|
#include "core/hle/kernel/kernel.h"
|
|
|
|
#include "core/hle/kernel/semaphore.h"
|
|
|
|
#include "core/hle/kernel/thread.h"
|
|
|
|
|
|
|
|
namespace Kernel {
|
|
|
|
|
2015-01-31 19:56:59 -05:00
|
|
|
Semaphore::Semaphore() {}
|
|
|
|
Semaphore::~Semaphore() {}
|
|
|
|
|
2015-01-11 10:53:11 -05:00
|
|
|
ResultVal<SharedPtr<Semaphore>> Semaphore::Create(s32 initial_count, s32 max_count,
|
|
|
|
std::string name) {
|
2014-12-04 11:40:36 -05:00
|
|
|
|
2014-12-12 20:46:52 -05:00
|
|
|
if (initial_count > max_count)
|
|
|
|
return ResultCode(ErrorDescription::InvalidCombination, ErrorModule::Kernel,
|
|
|
|
ErrorSummary::WrongArgument, ErrorLevel::Permanent);
|
|
|
|
|
2015-01-11 10:53:11 -05:00
|
|
|
SharedPtr<Semaphore> semaphore(new Semaphore);
|
2014-12-03 18:49:51 -05:00
|
|
|
|
2014-12-04 11:55:13 -05: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 20:46:52 -05:00
|
|
|
semaphore->max_count = max_count;
|
2014-12-12 22:22:11 -05:00
|
|
|
semaphore->available_count = initial_count;
|
2015-01-11 10:53:11 -05:00
|
|
|
semaphore->name = std::move(name);
|
2014-12-03 18:49:51 -05:00
|
|
|
|
2015-01-11 10:53:11 -05:00
|
|
|
return MakeResult<SharedPtr<Semaphore>>(std::move(semaphore));
|
2014-12-04 11:40:36 -05:00
|
|
|
}
|
|
|
|
|
2015-01-11 10:53:11 -05:00
|
|
|
bool Semaphore::ShouldWait() {
|
|
|
|
return available_count <= 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
void Semaphore::Acquire() {
|
2015-01-20 20:16:47 -05:00
|
|
|
ASSERT_MSG(!ShouldWait(), "object unavailable!");
|
2015-01-11 10:53:11 -05:00
|
|
|
--available_count;
|
|
|
|
}
|
2014-12-04 11:40:36 -05:00
|
|
|
|
2015-01-11 10:53:11 -05:00
|
|
|
ResultVal<s32> Semaphore::Release(s32 release_count) {
|
|
|
|
if (max_count - available_count < release_count)
|
2014-12-04 11:40:36 -05:00
|
|
|
return ResultCode(ErrorDescription::OutOfRange, ErrorModule::Kernel,
|
|
|
|
ErrorSummary::InvalidArgument, ErrorLevel::Permanent);
|
|
|
|
|
2015-01-11 10:53:11 -05:00
|
|
|
s32 previous_count = available_count;
|
|
|
|
available_count += release_count;
|
2014-12-04 11:40:36 -05: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 10:53:11 -05:00
|
|
|
while (!ShouldWait() && WakeupNextThread() != nullptr) {
|
|
|
|
Acquire();
|
2014-12-04 11:40:36 -05:00
|
|
|
}
|
|
|
|
|
2015-01-11 10:53:11 -05:00
|
|
|
return MakeResult<s32>(previous_count);
|
2014-12-03 18:49:51 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
} // namespace
|