summaryrefslogtreecommitdiff
path: root/Kernel/TTY/PTYMultiplexer.cpp
blob: 6a9b645e0c7941fa353a3563d91c33c3f4b13a65 (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
#include "PTYMultiplexer.h"
#include "MasterPTY.h"
#include <Kernel/FileSystem/FileDescription.h>
#include <Kernel/Process.h>
#include <LibC/errno_numbers.h>

//#define PTMX_DEBUG

static const unsigned s_max_pty_pairs = 8;
static PTYMultiplexer* s_the;

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

PTYMultiplexer::PTYMultiplexer()
    : CharacterDevice(5, 2)
{
    s_the = this;
    m_freelist.ensure_capacity(s_max_pty_pairs);
    for (int i = s_max_pty_pairs; i > 0; --i)
        m_freelist.unchecked_append(i - 1);
}

PTYMultiplexer::~PTYMultiplexer()
{
}

KResultOr<NonnullRefPtr<FileDescription>> PTYMultiplexer::open(int options)
{
    UNUSED_PARAM(options);
    LOCKER(m_lock);
    if (m_freelist.is_empty())
        return KResult(-EBUSY);
    auto master_index = m_freelist.take_last();
    auto master = adopt(*new MasterPTY(master_index));
#ifdef PTMX_DEBUG
    dbgprintf("PTYMultiplexer::open: Vending master %u\n", master->index());
#endif
    return FileDescription::create(master.ptr());
}

void PTYMultiplexer::notify_master_destroyed(Badge<MasterPTY>, unsigned index)
{
    LOCKER(m_lock);
    m_freelist.append(index);
#ifdef PTMX_DEBUG
    dbgprintf("PTYMultiplexer: %u added to freelist\n", index);
#endif
}