summaryrefslogtreecommitdiff
path: root/Kernel/Time/RTC.cpp
blob: 34b928644f185fa359516bda15c58a1d535420e6 (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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
 * Copyright (c) 2020, Liav A. <liavalb@hotmail.co.il>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <Kernel/Arch/x86/IO.h>
#include <Kernel/Arch/x86/InterruptDisabler.h>
#include <Kernel/CMOS.h>
#include <Kernel/Time/RTC.h>
#include <Kernel/Time/TimeManagement.h>

namespace Kernel {
#define IRQ_TIMER 8
#define MAX_FREQUENCY 8000

NonnullRefPtr<RealTimeClock> RealTimeClock::create(Function<void(const RegisterState&)> callback)
{
    return adopt_ref(*new RealTimeClock(move(callback)));
}
RealTimeClock::RealTimeClock(Function<void(const RegisterState&)> callback)
    : HardwareTimer(IRQ_TIMER, move(callback))
{
    InterruptDisabler disabler;
    NonMaskableInterruptDisabler nmi_disabler;
    enable_irq();
    CMOS::write(0x8B, CMOS::read(0xB) | 0x40);
    reset_to_default_ticks_per_second();
}
bool RealTimeClock::handle_irq(const RegisterState& regs)
{
    auto result = HardwareTimer::handle_irq(regs);
    CMOS::read(0x8C);
    return result;
}

size_t RealTimeClock::ticks_per_second() const
{
    return m_frequency;
}

void RealTimeClock::reset_to_default_ticks_per_second()
{
    InterruptDisabler disabler;
    bool success = try_to_set_frequency(1024);
    VERIFY(success);
}

// FIXME: This is a quick & dirty log base 2 with a parameter. Please provide something better in the future.
static int quick_log2(size_t number)
{
    int count = 0;
    while (number >>= 1)
        count++;
    return count;
}

bool RealTimeClock::try_to_set_frequency(size_t frequency)
{
    InterruptDisabler disabler;
    if (!is_capable_of_frequency(frequency))
        return false;
    disable_irq();
    u8 previous_rate = CMOS::read(0x8A);
    u8 rate = quick_log2(32768 / frequency) + 1;
    dbgln("RTC: Set rate to {}", rate);
    CMOS::write(0x8A, (previous_rate & 0xF0) | rate);
    m_frequency = frequency;
    dbgln("RTC: Set frequency to {} Hz", frequency);
    enable_irq();
    return true;
}
bool RealTimeClock::is_capable_of_frequency(size_t frequency) const
{
    VERIFY(frequency != 0);
    if (frequency > MAX_FREQUENCY)
        return false;
    if (32768 % frequency)
        return false;

    u16 divider = 32768 / frequency;
    return (divider <= 16384 && divider >= 4); // Frequency can be in range of 2 Hz to 8 KHz
}
size_t RealTimeClock::calculate_nearest_possible_frequency(size_t frequency) const
{
    VERIFY(frequency != 0);
    return frequency;
}

}