summaryrefslogtreecommitdiffstats
path: root/src/video_core/renderer_vulkan/vk_master_semaphore.h
blob: 2c7ed654dbe8e6b8ca2f7f182dfe760336f74567 (plain) (blame)
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
// Copyright 2020 yuzu Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.

#pragma once

#include <atomic>
#include <thread>

#include "common/common_types.h"
#include "video_core/vulkan_common/vulkan_wrapper.h"

namespace Vulkan {

class Device;

class MasterSemaphore {
public:
    explicit MasterSemaphore(const Device& device);
    ~MasterSemaphore();

    /// Returns the current logical tick.
    [[nodiscard]] u64 CurrentTick() const noexcept {
        return current_tick.load(std::memory_order_relaxed);
    }

    /// Returns the last known GPU tick.
    [[nodiscard]] u64 KnownGpuTick() const noexcept {
        return gpu_tick.load(std::memory_order_relaxed);
    }

    /// Returns the timeline semaphore handle.
    [[nodiscard]] VkSemaphore Handle() const noexcept {
        return *semaphore;
    }

    /// Returns true when a tick has been hit by the GPU.
    [[nodiscard]] bool IsFree(u64 tick) {
        return gpu_tick.load(std::memory_order_relaxed) >= tick;
    }

    /// Advance to the logical tick.
    void NextTick() noexcept {
        ++current_tick;
    }

    /// Refresh the known GPU tick
    void Refresh() {
        gpu_tick.store(semaphore.GetCounter(), std::memory_order_relaxed);
    }

    /// Waits for a tick to be hit on the GPU
    void Wait(u64 tick) {
        // No need to wait if the GPU is ahead of the tick
        if (IsFree(tick)) {
            return;
        }
        // Update the GPU tick and try again
        Refresh();
        if (IsFree(tick)) {
            return;
        }
        // If none of the above is hit, fallback to a regular wait
        semaphore.Wait(tick);
    }

private:
    vk::Semaphore semaphore;           ///< Timeline semaphore.
    std::atomic<u64> gpu_tick{0};      ///< Current known GPU tick.
    std::atomic<u64> current_tick{1};  ///< Current logical tick.
    std::atomic<bool> shutdown{false}; ///< True when the object is being destroyed.
    std::thread debug_thread;          ///< Debug thread to workaround validation layer bugs.
};

} // namespace Vulkan