summaryrefslogtreecommitdiff
path: root/Kernel/TTY/PTYMultiplexer.cpp
blob: 541e5e9a8e10a1c925b67d5cfd07adaf84e406bd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
 * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <AK/Singleton.h>
#include <Kernel/API/POSIX/errno.h>
#include <Kernel/Debug.h>
#include <Kernel/FileSystem/OpenFileDescription.h>
#include <Kernel/Sections.h>
#include <Kernel/TTY/MasterPTY.h>
#include <Kernel/TTY/PTYMultiplexer.h>

namespace Kernel {

static Singleton<PTYMultiplexer> s_the;

PTYMultiplexer& PTYMultiplexer::the()
{
    return *s_the;
}

UNMAP_AFTER_INIT PTYMultiplexer::PTYMultiplexer()
    : CharacterDevice(5, 2)
{
    m_freelist.with([&](auto& freelist) {
        freelist.ensure_capacity(max_pty_pairs);
        for (int i = max_pty_pairs; i > 0; --i)
            freelist.unchecked_append(i - 1);
    });
}

UNMAP_AFTER_INIT PTYMultiplexer::~PTYMultiplexer() = default;

UNMAP_AFTER_INIT void PTYMultiplexer::initialize()
{
    MUST(the().after_inserting());
}

ErrorOr<NonnullRefPtr<OpenFileDescription>> PTYMultiplexer::open(int options)
{
    return m_freelist.with([&](auto& freelist) -> ErrorOr<NonnullRefPtr<OpenFileDescription>> {
        if (freelist.is_empty())
            return EBUSY;

        auto master_index = freelist.take_last();
        auto master = TRY(MasterPTY::try_create(master_index));
        dbgln_if(PTMX_DEBUG, "PTYMultiplexer::open: Vending master {}", master->index());
        auto description = TRY(OpenFileDescription::try_create(*master));
        description->set_rw_mode(options);
        description->set_file_flags(options);
        return description;
    });
}

void PTYMultiplexer::notify_master_destroyed(Badge<MasterPTY>, unsigned index)
{
    m_freelist.with([&](auto& freelist) {
        freelist.append(index);
        dbgln_if(PTMX_DEBUG, "PTYMultiplexer: {} added to freelist", index);
    });
}

}