Revert "hoc-clk: add live vdd2, live boost clock and basic pwm dimming"

This reverts commit 15b7df8ef1.
This commit is contained in:
souldbminersmwc
2025-11-09 16:14:52 -05:00
parent 22ec140738
commit 21a3f953d7
3804 changed files with 435 additions and 570162 deletions

View File

@@ -1,159 +0,0 @@
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "tio_file_server.hpp"
#include "tio_file_server_packet.hpp"
#include "tio_file_server_htcs_server.hpp"
#include "tio_file_server_processor.hpp"
#include "tio_sd_card_observer.hpp"
namespace ams::tio {
namespace {
constexpr inline auto NumDispatchThreads = 2;
constexpr inline auto DispatchThreadPriority = 21;
constexpr inline size_t RequestBufferSize = 1_MB + util::AlignUp(0x40 + fs::EntryNameLengthMax, 1_KB);
struct FileServerRequest {
int socket;
FileServerRequestHeader header;
u8 body[RequestBufferSize];
};
constexpr const char HtcsPortName[] = "iywys@$TioServer_FileServer";
alignas(os::ThreadStackAlignment) u8 g_server_stack[os::MemoryPageSize];
alignas(os::ThreadStackAlignment) u8 g_observer_stack[os::MemoryPageSize];
alignas(os::ThreadStackAlignment) u8 g_dispatch_stacks[NumDispatchThreads][os::MemoryPageSize];
constinit FileServerHtcsServer g_file_server_htcs_server;
constinit FileServerProcessor g_file_server_processor(g_file_server_htcs_server);
constinit SdCardObserver g_sd_card_observer;
constinit os::ThreadType g_file_server_dispatch_threads[NumDispatchThreads];
constinit FileServerRequest g_requests[NumDispatchThreads];
constinit os::MessageQueueType g_free_mq;
constinit os::MessageQueueType g_dispatch_mq;
constinit uintptr_t g_free_mq_storage[NumDispatchThreads];
constinit uintptr_t g_dispatch_mq_storage[NumDispatchThreads];
void OnSdCardInsertionChanged(bool inserted) {
g_file_server_processor.SetInserted(inserted);
}
void OnFileServerHtcsSocketAccepted(int fd) {
/* Service requests, while we can. */
while (true) {
/* Receive a free request. */
uintptr_t request_address;
os::ReceiveMessageQueue(std::addressof(request_address), std::addressof(g_free_mq));
/* Ensure we manage our request properly. */
auto req_guard = SCOPE_GUARD { os::SendMessageQueue(std::addressof(g_free_mq), request_address); };
/* Receive the request header. */
FileServerRequest *request = reinterpret_cast<FileServerRequest *>(request_address);
if (htcs::Recv(fd, std::addressof(request->header), sizeof(request->header), htcs::HTCS_MSG_WAITALL) != sizeof(request->header)) {
break;
}
/* Receive the request body, if necessary. */
if (request->header.body_size > 0) {
if (htcs::Recv(fd, request->body, request->header.body_size, htcs::HTCS_MSG_WAITALL) != request->header.body_size) {
break;
}
}
/* Dispatch the request. */
req_guard.Cancel();
request->socket = fd;
os::SendMessageQueue(std::addressof(g_dispatch_mq), request_address);
}
/* Our socket is no longer making requests, so close it. */
htcs::Close(fd);
/* Clean up any server resources. */
g_file_server_processor.Unmount();
}
void FileServerDispatchThreadFunction(void *) {
while (true) {
/* Receive a request. */
uintptr_t request_address;
os::ReceiveMessageQueue(std::addressof(request_address), std::addressof(g_dispatch_mq));
/* Process the request. */
FileServerRequest *request = reinterpret_cast<FileServerRequest *>(request_address);
if (!g_file_server_processor.ProcessRequest(std::addressof(request->header), request->body, request->socket)) {
htcs::Close(request->socket);
}
/* Free the request. */
os::SendMessageQueue(std::addressof(g_free_mq), request_address);
}
}
}
void InitializeFileServer() {
/* Initialize the htcs server. */
g_file_server_htcs_server.Initialize(HtcsPortName, g_server_stack, sizeof(g_server_stack), OnFileServerHtcsSocketAccepted);
/* Initialize SD card observer. */
g_sd_card_observer.Initialize(g_observer_stack, sizeof(g_observer_stack));
g_sd_card_observer.SetCallback(OnSdCardInsertionChanged);
/* Initialize the command processor. */
g_file_server_processor.SetInserted(g_sd_card_observer.IsSdCardInserted());
g_file_server_processor.SetRequestBufferSize(RequestBufferSize);
/* Initialize the dispatch message queues. */
os::InitializeMessageQueue(std::addressof(g_free_mq), g_free_mq_storage, util::size(g_free_mq_storage));
os::InitializeMessageQueue(std::addressof(g_dispatch_mq), g_dispatch_mq_storage, util::size(g_dispatch_mq_storage));
/* Begin with all requests free. */
for (auto i = 0; i < NumDispatchThreads; ++i) {
os::SendMessageQueue(std::addressof(g_free_mq), reinterpret_cast<uintptr_t>(g_requests + i));
}
/* Initialize the dispatch threads. */
/* NOTE: Nintendo does not name these threads. */
for (auto i = 0; i < NumDispatchThreads; ++i) {
R_ABORT_UNLESS(os::CreateThread(g_file_server_dispatch_threads + i, FileServerDispatchThreadFunction, nullptr, g_dispatch_stacks + i, sizeof(g_dispatch_stacks[i]), DispatchThreadPriority));
}
}
void StartFileServer() {
/* Start the htcs server. */
g_file_server_htcs_server.Start();
/* Start the dispatch threads. */
for (auto i = 0; i < NumDispatchThreads; ++i) {
os::StartThread(g_file_server_dispatch_threads + i);
}
}
void WaitFileServer() {
/* Wait for the htcs server to finish. */
g_file_server_htcs_server.Wait();
}
}

View File

@@ -1,25 +0,0 @@
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <stratosphere.hpp>
namespace ams::tio {
void InitializeFileServer();
void StartFileServer();
void WaitFileServer();
}

View File

@@ -1,94 +0,0 @@
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "tio_file_server_htcs_server.hpp"
namespace ams::tio {
void FileServerHtcsServer::Initialize(const char *port_name, void *thread_stack, size_t thread_stack_size, SocketAcceptedCallback on_socket_accepted) {
/* Set our port name. */
std::strcpy(m_port_name.name, port_name);
/* Set our callback. */
m_on_socket_accepted = on_socket_accepted;
/* Setup our thread. */
R_ABORT_UNLESS(os::CreateThread(std::addressof(m_thread), ThreadEntry, this, thread_stack, thread_stack_size, AMS_GET_SYSTEM_THREAD_PRIORITY(TioServer, FileServerHtcsServer)));
/* Set our thread name pointer. */
os::SetThreadNamePointer(std::addressof(m_thread), AMS_GET_SYSTEM_THREAD_NAME(TioServer, FileServerHtcsServer));
}
void FileServerHtcsServer::Start() {
os::StartThread(std::addressof(m_thread));
}
void FileServerHtcsServer::Wait() {
os::WaitThread(std::addressof(m_thread));
}
void FileServerHtcsServer::ThreadFunc() {
/* Loop forever, servicing sockets. */
while (true) {
/* Get a socket. */
int fd;
while ((fd = htcs::Socket()) == -1) {
os::SleepThread(TimeSpan::FromSeconds(1));
}
/* Ensure we cleanup the socket when we're done with it. */
ON_SCOPE_EXIT {
htcs::Close(fd);
os::SleepThread(TimeSpan::FromSeconds(1));
};
/* Create a sock addr for our server. */
htcs::SockAddrHtcs addr;
addr.family = htcs::HTCS_AF_HTCS;
addr.peer_name = htcs::GetPeerNameAny();
addr.port_name = m_port_name;
/* Bind. */
if (htcs::Bind(fd, std::addressof(addr)) == -1) {
continue;
}
/* Listen on our port. */
while (htcs::Listen(fd, 0) == 0) {
/* Continue accepting clients, so long as we can. */
int client_fd;
while (true) {
/* Try to accept a client. */
if (client_fd = htcs::Accept(fd, std::addressof(addr)); client_fd < 0) {
break;
}
/* Handle the client. */
m_on_socket_accepted(client_fd);
}
/* NOTE: This seems unnecessary (client_fd guaranteed < 0 here), but Nintendo does it. */
htcs::Close(client_fd);
}
}
}
ssize_t FileServerHtcsServer::Send(s32 desc, const void *buffer, size_t buffer_size, s32 flags) {
AMS_ASSERT(m_mutex.IsLockedByCurrentThread());
return htcs::Send(desc, buffer, buffer_size, flags);
}
}

View File

@@ -1,47 +0,0 @@
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <stratosphere.hpp>
namespace ams::tio {
using SocketAcceptedCallback = void(*)(s32 desc);
class FileServerHtcsServer {
private:
SocketAcceptedCallback m_on_socket_accepted;
htcs::HtcsPortName m_port_name;
os::ThreadType m_thread;
os::SdkMutex m_mutex;
public:
constexpr FileServerHtcsServer() : m_on_socket_accepted(nullptr), m_port_name{}, m_thread{}, m_mutex{} { /* ... */ }
private:
static void ThreadEntry(void *arg) {
static_cast<FileServerHtcsServer *>(arg)->ThreadFunc();
}
void ThreadFunc();
public:
os::SdkMutex &GetMutex() { return m_mutex; }
public:
void Initialize(const char *port_name, void *thread_stack, size_t thread_stack_size, SocketAcceptedCallback on_socket_accepted);
void Start();
void Wait();
ssize_t Send(s32 desc, const void *buffer, size_t buffer_size, s32 flags);
};
}

View File

@@ -1,187 +0,0 @@
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <stratosphere.hpp>
namespace ams::tio {
enum class PacketType : u32 {
/* Control commands. */
Connect = 0,
Disconnect = 1,
/* Direct filesystem access. */
CreateDirectory = 500,
DeleteDirectory = 501,
DeleteDirectoryRecursively = 502,
OpenDirectory = 503,
CloseDirectory = 504,
RenameDirectory = 505,
CreateFile = 506,
DeleteFile = 507,
OpenFile = 508,
FlushFile = 509,
CloseFile = 510,
RenameFile = 511,
ReadFile = 512,
WriteFile = 513,
GetEntryType = 514,
ReadDirectory = 515,
GetFileSize = 516,
SetFileSize = 517,
GetTotalSpaceSize = 518,
GetFreeSpaceSize = 519,
/* Utilities. */
Stat = 1000,
ListDirectory = 1001,
};
struct FileServerRequestHeader {
u64 request_id;
PacketType packet_type;
u32 body_size;
};
struct FileServerResponseHeader {
u64 request_id;
Result result;
u32 body_size;
};
static_assert(sizeof(FileServerRequestHeader) == sizeof(FileServerResponseHeader));
struct CreateDirectoryParam {
u32 path_len;
char path[];
};
struct DeleteDirectoryParam {
u32 path_len;
char path[];
};
struct DeleteDirectoryRecursivelyParam {
u32 path_len;
char path[];
};
struct OpenDirectoryParam {
u32 path_len;
fs::OpenDirectoryMode open_mode;
char path[];
};
static_assert(sizeof(OpenDirectoryParam) == 0x8);
struct CloseDirectoryParam {
u64 handle;
};
struct RenameDirectoryParam {
u32 old_len;
u32 new_len;
char data[];
};
struct CreateFileParam {
s64 size;
u32 path_len;
fs::CreateOption option;
char path[];
};
static_assert(sizeof(CreateFileParam) == 0x10);
struct DeleteFileParam {
u32 path_len;
char path[];
};
struct OpenFileParam {
u32 path_len;
fs::OpenMode mode;
char path[];
};
static_assert(sizeof(OpenFileParam) == 0x8);
struct FlushFileParam {
u64 handle;
};
struct CloseFileParam {
u64 handle;
};
struct RenameFileParam {
u32 old_len;
u32 new_len;
char data[];
};
struct ReadFileParam {
u64 handle;
s64 offset;
u64 size;
fs::ReadOption option;
};
static_assert(sizeof(ReadFileParam) == 0x20);
struct WriteFileParam {
u64 handle;
s64 offset;
u64 size;
fs::WriteOption option;
};
static_assert(sizeof(WriteFileParam) == 0x20);
struct GetEntryTypeParam {
u32 path_len;
char path[];
};
struct ReadDirectoryParam {
u64 handle;
s64 count;
};
struct GetFileSizeParam {
u64 handle;
};
struct SetFileSizeParam {
u64 handle;
s64 size;
};
struct GetTotalSpaceSizeParam {
u32 path_len;
char path[];
};
struct GetFreeSpaceSizeParam {
u32 path_len;
char path[];
};
struct StatParam {
u32 path_len;
char path[];
};
struct ListDirectoryParam {
u32 path_len;
char path[];
};
}

View File

@@ -1,735 +0,0 @@
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "tio_file_server_processor.hpp"
namespace ams::tio {
namespace {
constexpr inline int ProtocolVersion = 1;
}
void FileServerProcessor::Unmount() {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Close all our directories. */
if (m_open_directory_count > 0) {
for (size_t i = 0; i < util::size(m_directories); ++i) {
if (m_directories[i].handle != nullptr) {
fs::CloseDirectory(m_directories[i]);
m_directories[i] = {};
--m_open_directory_count;
}
}
}
AMS_ABORT_UNLESS(m_open_directory_count == 0);
/* Close all our files. */
if (m_open_file_count > 0) {
for (size_t i = 0; i < util::size(m_files); ++i) {
if (m_files[i].handle != nullptr) {
fs::CloseFile(m_files[i]);
m_files[i] = {};
--m_open_file_count;
}
}
}
AMS_ABORT_UNLESS(m_open_file_count == 0);
/* If we're mounted, unmount the sd card. */
if (m_is_mounted) {
m_is_mounted = false;
fs::Unmount("sd");
}
}
bool FileServerProcessor::ProcessRequest(FileServerRequestHeader *header, u8 *body, int socket) {
/* Declare a response header for us to use. */
FileServerResponseHeader response_header = {
.request_id = header->request_id,
.result = ResultSuccess(),
.body_size = 0,
};
/* Handle the special control commands. */
if (header->packet_type == PacketType::Connect) {
/* If the SD card isn't already mounted, try to mount it. */
if (!m_is_mounted) {
/* Mount the sd card. */
m_is_mounted = !fs::ResultSdCardAccessFailed::Includes(fs::MountSdCard("sd"));
/* Prepare the response. */
char *response_body = reinterpret_cast<char *>(body);
util::SNPrintf(response_body, 0x100, "{\"bufferSize\":%zu, \"sdcardMounted\":%s, \"sdcardInserted\":%s, \"version\":%d}",
m_request_buffer_size,
m_is_mounted ? "true" : "false",
m_is_inserted ? "true" : "false",
ProtocolVersion);
/* Get the response length. */
response_header.body_size = std::strlen(response_body);
}
return this->SendResponse(response_header, body, socket);
} else if (header->packet_type == PacketType::Disconnect) {
/* If we need to, unmount the sd card. */
if (m_is_mounted) {
this->Unmount();
}
/* Send the response. */
return this->SendResponse(response_header, body, socket);
}
/* The SD card must be inserted and mounted for us to process requests. */
if (m_is_inserted && m_is_mounted) {
switch (header->packet_type) {
case PacketType::CreateDirectory:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const CreateDirectoryParam *>(body);
if (header->body_size != sizeof(*param) + param->path_len) {
return false;
}
/* Create the directory. */
response_header.result = fs::CreateDirectory(param->path);
}
break;
case PacketType::DeleteDirectory:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const DeleteDirectoryParam *>(body);
if (header->body_size != sizeof(*param) + param->path_len) {
return false;
}
/* Delete the directory. */
response_header.result = fs::DeleteDirectory(param->path);
}
break;
case PacketType::DeleteDirectoryRecursively:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const DeleteDirectoryRecursivelyParam *>(body);
if (header->body_size != sizeof(*param) + param->path_len) {
return false;
}
/* Delete the directory. */
response_header.result = fs::DeleteDirectoryRecursively(param->path);
}
break;
case PacketType::OpenDirectory:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const OpenDirectoryParam *>(body);
if (header->body_size != sizeof(*param) + param->path_len) {
return false;
}
/* Open the directory. */
fs::DirectoryHandle handle;
response_header.result = fs::OpenDirectory(std::addressof(handle), param->path, param->open_mode);
if (R_SUCCEEDED(response_header.result)) {
std::scoped_lock lk(m_mutex);
if (m_open_directory_count < util::size(m_directories)) {
/* Insert the directory into our table. */
u64 index = std::numeric_limits<u64>::max();
for (size_t i = 0; i < util::size(m_directories); ++i) {
if (m_directories[i].handle == nullptr) {
m_directories[i] = handle;
index = i;
++m_open_directory_count;
break;
}
}
AMS_ABORT_UNLESS(index < util::size(m_directories));
/* Return the index. */
response_header.body_size = sizeof(index);
std::memcpy(body, std::addressof(index), sizeof(index));
} else {
/* We can't actually open the directory. */
fs::CloseDirectory(handle);
response_header.result = fs::ResultOpenCountLimit();
}
}
}
break;
case PacketType::CloseDirectory:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const CloseDirectoryParam *>(body);
if (header->body_size != sizeof(*param)) {
return false;
}
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that the directory handle is valid. */
if (param->handle >= util::size(m_directories) || m_directories[param->handle].handle == nullptr) {
response_header.result = fs::ResultDataCorrupted();
break;
}
/* Lock the filesystem. */
std::scoped_lock lk2(m_fs_mutex);
/* Close the directory. */
fs::CloseDirectory(m_directories[param->handle]);
m_directories[param->handle].handle = {};
--m_open_directory_count;
}
break;
case PacketType::RenameDirectory:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const RenameDirectoryParam *>(body);
if (header->body_size != sizeof(*param) + param->old_len + param->new_len) {
return false;
}
/* Delete the directory. */
const char *old_path = param->data + 0;
const char *new_path = param->data + param->old_len;
response_header.result = fs::RenameDirectory(old_path, new_path);
}
break;
case PacketType::CreateFile:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const CreateFileParam *>(body);
if (header->body_size != sizeof(*param) + param->path_len) {
return false;
}
/* Create the file. */
response_header.result = fs::CreateFile(param->path, param->size, static_cast<int>(param->option));
}
break;
case PacketType::DeleteFile:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const DeleteFileParam *>(body);
if (header->body_size != sizeof(*param) + param->path_len) {
return false;
}
/* Delete the file. */
response_header.result = fs::DeleteFile(param->path);
}
break;
case PacketType::OpenFile:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const OpenFileParam *>(body);
if (header->body_size != sizeof(*param) + param->path_len) {
return false;
}
/* Open the file. */
fs::FileHandle handle;
response_header.result = fs::OpenFile(std::addressof(handle), param->path, param->mode);
if (R_SUCCEEDED(response_header.result)) {
std::scoped_lock lk(m_mutex);
if (m_open_file_count < util::size(m_files)) {
/* Insert the file into our table. */
u64 index = std::numeric_limits<u64>::max();
for (size_t i = 0; i < util::size(m_files); ++i) {
if (m_files[i].handle == nullptr) {
m_files[i] = handle;
index = i;
++m_open_file_count;
break;
}
}
AMS_ABORT_UNLESS(index < util::size(m_files));
/* Return the index. */
response_header.body_size = sizeof(index);
std::memcpy(body, std::addressof(index), sizeof(index));
} else {
/* We can't actually open the file. */
fs::CloseFile(handle);
response_header.result = fs::ResultOpenCountLimit();
}
}
}
break;
case PacketType::FlushFile:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const FlushFileParam *>(body);
if (header->body_size != sizeof(*param)) {
return false;
}
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that the file handle is valid. */
if (param->handle >= util::size(m_files) || m_files[param->handle].handle == nullptr) {
response_header.result = fs::ResultDataCorrupted();
break;
}
/* Lock the filesystem. */
std::scoped_lock lk2(m_fs_mutex);
/* Flush the file. */
response_header.result = fs::FlushFile(m_files[param->handle]);
}
break;
case PacketType::CloseFile:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const CloseFileParam *>(body);
if (header->body_size != sizeof(*param)) {
return false;
}
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that the file handle is valid. */
if (param->handle >= util::size(m_files) || m_files[param->handle].handle == nullptr) {
response_header.result = fs::ResultDataCorrupted();
break;
}
/* Lock the filesystem. */
std::scoped_lock lk2(m_fs_mutex);
/* Close the directory. */
fs::CloseFile(m_files[param->handle]);
m_files[param->handle].handle = {};
--m_open_file_count;
}
break;
case PacketType::RenameFile:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const RenameFileParam *>(body);
if (header->body_size != sizeof(*param) + param->old_len + param->new_len) {
return false;
}
/* Delete the directory. */
const char *old_path = param->data + 0;
const char *new_path = param->data + param->old_len;
response_header.result = fs::RenameFile(old_path, new_path);
}
break;
case PacketType::ReadFile:
{
/* Get the parameters. */
const auto param = *reinterpret_cast<const ReadFileParam *>(body);
if (header->body_size != sizeof(param)) {
return false;
}
/* Check that the read is valid. */
if (param.size + sizeof(u64) > m_request_buffer_size) {
response_header.result = fs::ResultDataCorrupted();
break;
}
/* Prepare response variables. */
u64 *out_size = reinterpret_cast<u64 *>(body);
void *dst = out_size + 1;
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that the file handle is valid. */
if (param.handle >= util::size(m_files) || m_files[param.handle].handle == nullptr) {
response_header.result = fs::ResultDataCorrupted();
break;
}
/* Read the file. */
size_t read_size;
response_header.result = fs::ReadFile(std::addressof(read_size), m_files[param.handle], param.offset, dst, param.size);
if (R_SUCCEEDED(response_header.result)) {
*out_size = read_size;
response_header.body_size = sizeof(u64) + read_size;
}
}
break;
case PacketType::WriteFile:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const WriteFileParam *>(body);
if (header->body_size != sizeof(*param) + param->size) {
return false;
}
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that the file handle is valid. */
if (param->handle >= util::size(m_files) || m_files[param->handle].handle == nullptr) {
response_header.result = fs::ResultDataCorrupted();
break;
}
/* Lock the filesystem. */
std::scoped_lock lk2(m_fs_mutex);
/* Write the file. */
response_header.result = fs::WriteFile(m_files[param->handle], param->offset, body + sizeof(*param), param->size, param->option);
}
break;
case PacketType::GetEntryType:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const GetEntryTypeParam *>(body);
if (header->body_size != sizeof(*param) + param->path_len) {
return false;
}
/* Get the entry type. */
fs::DirectoryEntryType type;
response_header.result = fs::GetEntryType(std::addressof(type), param->path);
if (R_SUCCEEDED(response_header.result)) {
/* Return the type. */
response_header.body_size = sizeof(type);
std::memcpy(body, std::addressof(type), sizeof(type));
static_assert(sizeof(type) == sizeof(u32));
}
}
break;
case PacketType::ReadDirectory:
{
/* Get the parameters. */
const auto param = *reinterpret_cast<const ReadDirectoryParam *>(body);
if (header->body_size != sizeof(param)) {
return false;
}
/* Check that the read is valid. */
if (sizeof(s64) + param.count * sizeof(fs::DirectoryEntry) > m_request_buffer_size) {
response_header.result = fs::ResultDataCorrupted();
break;
}
/* Prepare response variables. */
s64 *out_count = reinterpret_cast<s64 *>(body);
fs::DirectoryEntry *dst = reinterpret_cast<fs::DirectoryEntry *>(out_count + 1);
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that the directory handle is valid. */
if (param.handle >= util::size(m_directories) || m_directories[param.handle].handle == nullptr) {
response_header.result = fs::ResultDataCorrupted();
break;
}
/* Read the directory. */
response_header.result = fs::ReadDirectory(out_count, dst, m_directories[param.handle], param.count);
if (R_SUCCEEDED(response_header.result)) {
response_header.body_size = sizeof(s64) + *out_count * sizeof(fs::DirectoryEntry);
}
}
break;
case PacketType::GetFileSize:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const GetFileSizeParam *>(body);
if (header->body_size != sizeof(*param)) {
return false;
}
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that the file handle is valid. */
if (param->handle >= util::size(m_files) || m_files[param->handle].handle == nullptr) {
response_header.result = fs::ResultDataCorrupted();
break;
}
/* Get the file size. */
response_header.result = fs::GetFileSize(reinterpret_cast<s64 *>(body), m_files[param->handle]);
if (R_SUCCEEDED(response_header.result)) {
response_header.body_size = sizeof(s64);
}
}
break;
case PacketType::SetFileSize:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const SetFileSizeParam *>(body);
if (header->body_size != sizeof(*param)) {
return false;
}
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that the file handle is valid. */
if (param->handle >= util::size(m_files) || m_files[param->handle].handle == nullptr) {
response_header.result = fs::ResultDataCorrupted();
break;
}
/* Lock the filesystem. */
std::scoped_lock lk2(m_fs_mutex);
/* Get the file size. */
response_header.result = fs::SetFileSize(m_files[param->handle], param->size);
}
break;
case PacketType::GetTotalSpaceSize:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const GetTotalSpaceSizeParam *>(body);
if (header->body_size != sizeof(*param) + param->path_len) {
return false;
}
/* Get the total space size. */
s64 size;
response_header.result = fs::GetTotalSpaceSize(std::addressof(size), param->path);
if (R_SUCCEEDED(response_header.result)) {
/* Return the size. */
response_header.body_size = sizeof(size);
std::memcpy(body, std::addressof(size), sizeof(size));
}
}
break;
case PacketType::GetFreeSpaceSize:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const GetFreeSpaceSizeParam *>(body);
if (header->body_size != sizeof(*param) + param->path_len) {
return false;
}
/* Get the free space size. */
s64 size;
response_header.result = fs::GetFreeSpaceSize(std::addressof(size), param->path);
if (R_SUCCEEDED(response_header.result)) {
/* Return the size. */
response_header.body_size = sizeof(size);
std::memcpy(body, std::addressof(size), sizeof(size));
}
}
break;
case PacketType::Stat:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const StatParam *>(body);
if (header->body_size != sizeof(*param) + param->path_len) {
return false;
}
/* Prepare a response stat structure. */
struct {
fs::DirectoryEntryType type;
s64 file_size;
fs::FileTimeStampRaw file_timestamp;
} out = {};
static_assert(sizeof(out) == 0x30);
/* Get the entry type. */
response_header.result = fs::GetEntryType(std::addressof(out.type), param->path);
if (R_FAILED(response_header.result)) {
break;
}
/* If the path is a file, get further information. */
if (out.type == fs::DirectoryEntryType_File) {
/* Try to get the file size. */
{
fs::FileHandle handle;
const auto open_result = fs::OpenFile(std::addressof(handle), param->path, fs::OpenMode_Read);
if (R_SUCCEEDED(open_result)) {
ON_SCOPE_EXIT { fs::CloseFile(handle); };
response_header.result = fs::GetFileSize(std::addressof(out.file_size), handle);
if (R_FAILED(response_header.result)) {
break;
}
} else {
if (fs::ResultTargetLocked::Includes(open_result)) {
out.file_size = 0;
} else {
response_header.result = open_result;
break;
}
}
}
/* Get the file timestamp. */
response_header.result = fs::impl::GetFileTimeStampRawForDebug(std::addressof(out.file_timestamp), param->path);
if (R_FAILED(response_header.result)) {
break;
}
}
/* If we successfully got the stat information, send it as response. */
if (R_SUCCEEDED(response_header.result)) {
response_header.body_size = sizeof(out);
std::memcpy(body, std::addressof(out), sizeof(out));
}
}
break;
case PacketType::ListDirectory:
{
/* Get the parameters. */
const auto *param = reinterpret_cast<const ListDirectoryParam *>(body);
if (header->body_size != sizeof(*param) + param->path_len) {
return false;
}
/* Open the directory. */
fs::DirectoryHandle handle;
response_header.result = fs::OpenDirectory(std::addressof(handle), param->path, fs::OpenDirectoryMode_All);
if (R_FAILED(response_header.result)) {
break;
}
/* When we're done, close the handle. */
ON_SCOPE_EXIT { fs::CloseDirectory(handle); };
/* Get the directory entry count. */
s64 count;
response_header.result = fs::GetDirectoryEntryCount(std::addressof(count), handle);
if (R_FAILED(response_header.result)) {
break;
}
/* Determine whether we can send the response in one go. */
const size_t needed_size = sizeof(s64) + sizeof(u64) + sizeof(fs::DirectoryEntry) * count;
if (needed_size <= m_request_buffer_size) {
/* We can perform the entire read in one send. */
struct {
s64 count;
u64 size;
fs::DirectoryEntry entries[];
} *out = reinterpret_cast<decltype(out)>(body);
s64 read_count;
response_header.result = fs::ReadDirectory(std::addressof(read_count), out->entries, handle, count);
if (R_FAILED(response_header.result)) {
break;
}
/* Set the output. */
out->count = read_count;
out->size = read_count * sizeof(fs::DirectoryEntry);
/* Set the response body size. */
response_header.body_size = sizeof(*out) + out->size;
} else {
/* We have to use multiple sends. */
/* Lock our server. */
std::scoped_lock lk(m_htcs_server.GetMutex());
/* Send the response header. */
response_header.body_size = needed_size;
if (m_htcs_server.Send(socket, std::addressof(header), sizeof(header), 0) != sizeof(header)) {
return false;
}
/* Send the body header. */
struct {
s64 count;
u64 size;
} out = { count, count * sizeof(fs::DirectoryEntry) };
if (m_htcs_server.Send(socket, std::addressof(out), sizeof(out), 0) != sizeof(out)) {
return false;
}
/* Loop sending entries. */
s64 remaining = count;
do {
/* Determine how many entries we can read. */
const s64 cur = std::min<s64>(remaining, static_cast<s64>(m_request_buffer_size / sizeof(fs::DirectoryEntry)));
/* NOTE: Nintendo does not check the output of this call. */
s64 read_count = 0;
fs::ReadDirectory(std::addressof(read_count), reinterpret_cast<fs::DirectoryEntry *>(body), handle, cur);
/* Send the current entries. */
const ssize_t cur_size = read_count * sizeof(fs::DirectoryEntry);
if (m_htcs_server.Send(socket, body, cur_size, 0) != cur_size) {
return false;
}
/* Advance. */
remaining -= read_count;
} while (remaining > 0);
/* We've sent the entirety of our response, so early return. */
return true;
}
}
break;
default:
/* Unsupported packet. */
return false;
}
/* Send the response. */
return this->SendResponse(response_header, body, socket);
} else if (m_is_mounted) {
/* The SD card is mounted but not inserted, so we should unmount it. */
this->Unmount();
}
/* We failed to process the request due to SD card not being inserted or mounted. */
response_header.result = fs::ResultSdCardAccessFailed();
return this->SendResponse(response_header, body, socket);
}
bool FileServerProcessor::SendResponse(const FileServerResponseHeader &header, const void *body, int socket) {
/* Lock our server. */
std::scoped_lock lk(m_htcs_server.GetMutex());
/* Send the response header. */
if (m_htcs_server.Send(socket, std::addressof(header), sizeof(header), 0) != sizeof(header)) {
return false;
}
/* If we don't have a body, we're done. */
if (header.body_size == 0) {
return true;
}
/* Send the body. */
return m_htcs_server.Send(socket, body, header.body_size, 0) == header.body_size;
}
}

View File

@@ -1,48 +0,0 @@
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <stratosphere.hpp>
#include "tio_file_server_htcs_server.hpp"
#include "tio_file_server_packet.hpp"
namespace ams::tio {
class FileServerProcessor {
private:
bool m_is_inserted{};
bool m_is_mounted{};
size_t m_request_buffer_size{};
FileServerHtcsServer &m_htcs_server;
size_t m_open_file_count{};
size_t m_open_directory_count{};
fs::FileHandle m_files[0x80]{};
fs::DirectoryHandle m_directories[0x80]{};
os::SdkMutex m_fs_mutex{};
os::SdkMutex m_mutex{};
public:
constexpr FileServerProcessor(FileServerHtcsServer &htcs_server) : m_htcs_server(htcs_server) { /* ... */ }
void SetInserted(bool ins) { m_is_inserted = ins; }
void SetRequestBufferSize(size_t size) { m_request_buffer_size = size; }
public:
bool ProcessRequest(FileServerRequestHeader *header, u8 *body, int socket);
void Unmount();
private:
bool SendResponse(const FileServerResponseHeader &header, const void *body, int socket);
};
}

View File

@@ -1,93 +0,0 @@
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "tio_file_server.hpp"
namespace ams {
namespace tio {
namespace {
alignas(0x40) constinit u8 g_fs_heap_buffer[64_KB];
alignas(0x40) constinit u8 g_htcs_buffer[1_KB];
lmem::HeapHandle g_fs_heap_handle;
void *AllocateForFs(size_t size) {
return lmem::AllocateFromExpHeap(g_fs_heap_handle, size);
}
void DeallocateForFs(void *p, size_t size) {
AMS_UNUSED(size);
return lmem::FreeToExpHeap(g_fs_heap_handle, p);
}
void InitializeFsHeap() {
/* Setup fs allocator. */
g_fs_heap_handle = lmem::CreateExpHeap(g_fs_heap_buffer, sizeof(g_fs_heap_buffer), lmem::CreateOption_ThreadSafe);
}
}
}
namespace init {
void InitializeSystemModule() {
/* Initialize heap. */
tio::InitializeFsHeap();
/* Initialize our connection to sm. */
R_ABORT_UNLESS(sm::Initialize());
/* Initialize fs. */
fs::InitializeForSystem();
fs::SetAllocator(tio::AllocateForFs, tio::DeallocateForFs);
fs::SetEnabledAutoAbort(false);
/* Verify that we can sanely execute. */
ams::CheckApiVersion();
}
void FinalizeSystemModule() { /* ... */ }
void Startup() { /* ... */ }
}
void Main() {
/* Set thread name. */
os::SetThreadNamePointer(os::GetCurrentThread(), AMS_GET_SYSTEM_THREAD_NAME(TioServer, Main));
AMS_ASSERT(os::GetThreadPriority(os::GetCurrentThread()) == AMS_GET_SYSTEM_THREAD_PRIORITY(TioServer, Main));
/* Initialize htcs. */
constexpr auto HtcsSocketCountMax = 2;
const size_t buffer_size = htcs::GetWorkingMemorySize(HtcsSocketCountMax);
AMS_ABORT_UNLESS(sizeof(tio::g_htcs_buffer) >= buffer_size);
htcs::InitializeForSystem(tio::g_htcs_buffer, buffer_size, HtcsSocketCountMax);
/* Initialize the file server. */
tio::InitializeFileServer();
/* Start the file server. */
tio::StartFileServer();
/* Wait for the file server to finish. */
tio::WaitFileServer();
}
}

View File

@@ -1,64 +0,0 @@
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "tio_sd_card_observer.hpp"
namespace ams::tio {
void SdCardObserver::Initialize(void *thread_stack, size_t thread_stack_size) {
/* Setup our thread. */
R_ABORT_UNLESS(os::CreateThread(std::addressof(m_thread), ThreadEntry, this, thread_stack, thread_stack_size, AMS_GET_SYSTEM_THREAD_PRIORITY(TioServer, SdCardObserver)));
/* Set our thread name pointer. */
os::SetThreadNamePointer(std::addressof(m_thread), AMS_GET_SYSTEM_THREAD_NAME(TioServer, SdCardObserver));
/* Set our initial insertion state. */
m_inserted = fs::IsSdCardInserted();
}
void SdCardObserver::SetCallback(SdCardInsertionCallback callback) {
/* Check that we don't already have a callback. */
AMS_ABORT_UNLESS(m_callback == nullptr);
/* Set our callback. */
m_callback = callback;
}
void SdCardObserver::ThreadFunc() {
/* Open detection event notifier. */
std::unique_ptr<fs::IEventNotifier> notifier;
R_ABORT_UNLESS(fs::OpenSdCardDetectionEventNotifier(std::addressof(notifier)));
/* Bind the detection event. */
os::SystemEventType event;
R_ABORT_UNLESS(notifier->BindEvent(std::addressof(event), os::EventClearMode_AutoClear));
/* Loop, waiting for insertion events. */
while (true) {
/* Wait for an event. */
os::WaitSystemEvent(std::addressof(event));
/* Update our insertion state. */
m_inserted = fs::IsSdCardInserted();
/* Invoke our callback. */
if (m_callback) {
m_callback(m_inserted);
}
}
}
}

View File

@@ -1,43 +0,0 @@
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <stratosphere.hpp>
namespace ams::tio {
using SdCardInsertionCallback = void(*)(bool inserted);
class SdCardObserver {
private:
bool m_inserted;
SdCardInsertionCallback m_callback;
os::ThreadType m_thread;
public:
constexpr SdCardObserver() : m_inserted(false), m_callback(nullptr), m_thread{} { /* ... */ }
bool IsSdCardInserted() const { return m_inserted; }
private:
static void ThreadEntry(void *arg) {
static_cast<SdCardObserver *>(arg)->ThreadFunc();
}
void ThreadFunc();
public:
void Initialize(void *thread_stack, size_t thread_stack_size);
void SetCallback(SdCardInsertionCallback callback);
};
}