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.
|
|
|
|
|
2015-05-06 03:06:12 -04:00
|
|
|
#include "common/assert.h"
|
2014-12-03 18:49:51 -05:00
|
|
|
#include "core/hle/kernel/kernel.h"
|
2016-09-21 02:52:38 -04:00
|
|
|
#include "core/hle/kernel/semaphore.h"
|
2014-12-03 18:49:51 -05:00
|
|
|
#include "core/hle/kernel/thread.h"
|
|
|
|
|
|
|
|
namespace Kernel {
|
|
|
|
|
2016-09-18 21:01:46 -04:00
|
|
|
Semaphore::Semaphore() {}
|
|
|
|
Semaphore::~Semaphore() {}
|
2015-01-31 19:56:59 -05:00
|
|
|
|
2015-01-11 10:53:11 -05:00
|
|
|
ResultVal<SharedPtr<Semaphore>> Semaphore::Create(s32 initial_count, s32 max_count,
|
2016-09-17 20:38:01 -04:00
|
|
|
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
|
|
|
}
|
|
|
|
|
2017-01-01 16:53:22 -05:00
|
|
|
bool Semaphore::ShouldWait(Thread* thread) const {
|
2015-01-11 10:53:11 -05:00
|
|
|
return available_count <= 0;
|
|
|
|
}
|
|
|
|
|
2017-01-01 16:53:22 -05:00
|
|
|
void Semaphore::Acquire(Thread* thread) {
|
2017-01-01 19:07:37 -05:00
|
|
|
if (available_count <= 0)
|
|
|
|
return;
|
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)
|
2015-05-25 14:34:09 -04:00
|
|
|
return ResultCode(ErrorDescription::OutOfRange, ErrorModule::Kernel,
|
2014-12-04 11:40:36 -05:00
|
|
|
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
|
|
|
|
2015-06-07 23:39:37 -04:00
|
|
|
WakeupAllWaitingThreads();
|
2015-05-19 20:24:30 -04:00
|
|
|
|
2015-01-11 10:53:11 -05:00
|
|
|
return MakeResult<s32>(previous_count);
|
2014-12-03 18:49:51 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
} // namespace
|