<commit_before>#ifndef SFML_INPUT_HANDLER_HPP
#define SFML_INPUT_HANDLER_HPP
#include <unordered_map>
#include <SFML/Window.hpp>
#include "hash_pair.hpp"

class InputHandler
{
public:
	struct MousePosition
	{
		MousePosition():
		x(0),y(0){}
		int x;
		int y;
	};
	InputHandler(){}
	~InputHandler(){}

	void update()
	{
		#if !(INPUT_DISABLE_KEYBOARD)
		keyUpdate();
		#endif
		#if !(INPUT_DISABLE_MOUSE)
		mouseUpdate();
		#endif
		#if !(INPUT_DISABLE_JOYSTICK)
		joystickUpdate();
		#endif
	}

	void handleEvent(const sf::Event& event)
	{
		#if !(INPUT_DISABLE_KEYBOARD)
		if (keyEvent(event)) return;
		#endif
		#if !(INPUT_DISABLE_MOUSE)
		if (mouseEvent(event)) return;
		#endif
		#if !(INPUT_DISABLE_JOYSTICK)
		if (joystickEvent(event)) return;
		#endif
	}

#if !(INPUT_DISABLE_KEYBOARD)
	bool isKeyPressed(sf::Keyboard::Key key)
	{
		return p_key_pressed[key];
	}

	bool isKeyDown(sf::Keyboard::Key key)
	{
		return p_key_down[key];
	}

	bool isKeyReleased(sf::Keyboard::Key key)
	{
		return p_key_released[key];
	}
#endif

#if !(INPUT_DISABLE_MOUSE)
	bool mouseMoved()
	{
		return p_mouse_move_event;
	}

	const MousePosition& getMouseCurrentPosition()
	{
		return p_current_mouse_info;
	}

	const MousePosition& getMousePreviousPosition()
	{
		return p_previous_mouse_info;
	}

	bool isMouseButtonPressed(sf::Mouse::Button button)
	{
		return p_mouse_button_pressed[button];
	}

	bool isMouseButtonDown(sf::Mouse::Button button)
	{
		return p_mouse_button_down[button];
	}

	bool isMouseButtonReleased(sf::Mouse::Button button)
	{
		return p_mouse_button_released[button];
	}

	bool mouseWheelScrolled()
	{
		return p_mouse_wheel_scrolled;
	}

	float getMouseWheelScrollDelta()
	{
		return p_mouse_scroll_delta;
	}
#endif

#if !(INPUT_DISABLE_JOYSTICK)
	bool isJoystickConnected(unsigned int joystickId)
	{
		return p_joystick_connected[joystickId];
	}

	bool isJoystickActive(unsigned int joystickId)
	{
		return p_joystick_active[joystickId];
	}

	bool isJoystickDisconnected(unsigned int joystickId)
	{
		return p_joystick_disconnected[joystickId];
	}

	bool isJoystickButtonPressed(unsigned int joystickId, unsigned int button)
	{
		return p_joystick_button_pressed[std::pair<unsigned int, unsigned int>(joystickId, button)];
	}

	bool isJoystickButtonDown(unsigned int joystickId, unsigned int button)
	{
		return p_joystick_button_down[std::pair<unsigned int, unsigned int>(joystickId, button)];
	}

	bool isJoystickButtonReleased(unsigned int joystickId, unsigned int button)
	{
		return p_joystick_button_released[std::pair<unsigned int, unsigned int>(joystickId, button)];
	}

	float getJoystickAxisPosition(unsigned int joystickId, sf::Joystick::Axis axis)
	{
		return p_joystick_axis_position[std::pair<unsigned int, unsigned int>(joystickId, axis)];
	}
#endif

private:
#if !(INPUT_DISABLE_KEYBOARD)
	void keyUpdate()
	{
		for (auto it = p_key_pressed.begin(); it != p_key_pressed.end(); ++it)
		{
			if (it->second)
			{
				p_key_down[it->first] = true;
				it->second = false;
			}
		}

		for (auto it = p_key_released.begin(); it != p_key_released.end(); ++it)
		{
			if (it->second)
				it->second = false;
		}
	}

	bool keyEvent(const sf::Event& event)
	{
		if (event.type == sf::Event::KeyPressed)
		{
			p_key_pressed[event.key.code] = not p_key_down[event.key.code];
			p_key_released[event.key.code] = false;
			return true;
		}
		else if (event.type == sf::Event::KeyReleased)
		{
			p_key_pressed[event.key.code] = false;
			p_key_down[event.key.code] = false;
			p_key_released[event.key.code] = true;
			return true;
		}
		return false;
	}

	std::unordered_map<unsigned int, bool> p_key_pressed;
	std::unordered_map<unsigned int, bool> p_key_down;
	std::unordered_map<unsigned int, bool> p_key_released;
#endif

#if !(INPUT_DISABLE_MOUSE)
	void mouseUpdate()
	{
		p_mouse_move_event = false;

		for (auto it = p_mouse_button_pressed.begin(); it != p_mouse_button_pressed.end(); ++it)
		{
			if (it->second)
			{
				p_mouse_button_down[it->first] = true;
				it->second = false;
			}
		}

		for (auto it = p_mouse_button_released.begin(); it != p_mouse_button_released.end(); ++it)
		{
			if (it->second)
				it->second = false;
		}

		if (p_mouse_wheel_scrolled)
		{
			p_mouse_wheel_scrolled = false;
			p_mouse_scroll_delta = 0.0f;
		}
	}

	bool mouseEvent(const sf::Event& event)
	{
		if (event.type == sf::Event::MouseButtonPressed)
		{
			p_mouse_button_pressed[event.mouseButton.button] = not p_mouse_button_down[event.mouseButton.button];
			p_mouse_button_released[event.mouseButton.button] = false;
			return true;
		}
		else if (event.type == sf::Event::MouseButtonReleased)
		{
			p_mouse_button_pressed[event.mouseButton.button] = false;
			p_mouse_button_down[event.mouseButton.button] = false;
			p_mouse_button_released[event.mouseButton.button] = true;
			return true;
		}
		else if (event.type == sf::Event::MouseMoved)
		{
			p_previous_mouse_info = p_current_mouse_info;
			MousePosition mouse;
			mouse.x = event.mouseMove.x;
			mouse.y = event.mouseMove.y;
			p_current_mouse_info = mouse;
			p_mouse_move_event = true;
			return true;
		}
		else if (event.type == sf::Event::MouseWheelMoved)
		{
			p_mouse_wheel_scrolled = true;
			p_mouse_scroll_delta = event.mouseWheel.delta;
			return true;
		}
		return false;
	}

	bool p_mouse_move_event;
	bool p_mouse_wheel_scrolled;
	float p_mouse_scroll_delta;
	MousePosition p_current_mouse_info;
	MousePosition p_previous_mouse_info;

	std::unordered_map<unsigned int, bool> p_mouse_button_pressed;
	std::unordered_map<unsigned int, bool> p_mouse_button_down;
	std::unordered_map<unsigned int, bool> p_mouse_button_released;
#endif

#if !(INPUT_DISABLE_JOYSTICK)
	void joystickUpdate()
	{
		for (auto it = p_joystick_button_pressed.begin(); it != p_joystick_button_pressed.end(); ++it)
		{
			if (it->second)
			{
				p_joystick_button_down[it->first] = true;
				it->second = false;
			}
		}

		for (auto it = p_joystick_button_released.begin(); it != p_joystick_button_released.end(); ++it)
		{
			if (it->second)
				it->second = false;
		}

		for (auto it = p_joystick_connected.begin(); it != p_joystick_connected.end(); ++it)
		{
			if (it->second)
			{
				p_joystick_active[it->first] = true;
				it->second = false;
			}
		}

		for (auto it = p_joystick_disconnected.begin(); it != p_joystick_disconnected.end(); ++it)
		{
			if (it->second)
				it->second = false;
		}
	}

	bool joystickEvent(const sf::Event& event)
	{
		if (event.type == sf::Event::JoystickConnected)
		{
			p_joystick_connected[event.joystickConnect.joystickId] = not p_joystick_active[event.joystickConnect.joystickId];
			p_joystick_disconnected[event.joystickConnect.joystickId] = false;
			return true;
		}
		else if (event.type == sf::Event::JoystickDisconnected)
		{
			p_joystick_connected[event.joystickConnect.joystickId] = false;
			p_joystick_active[event.joystickConnect.joystickId] = false;
			p_joystick_disconnected[event.joystickConnect.joystickId] = true;
			return true;
		}
		else if (event.type == sf::Event::JoystickButtonPressed)
		{
			std::pair<unsigned int, unsigned int> k(event.joystickButton.joystickId, event.joystickButton.button);
			p_joystick_button_pressed[k] = not p_joystick_button_down[k];
			p_joystick_button_released[k] = false;
			return true;
		}
		else if (event.type == sf::Event::JoystickButtonReleased)
		{
			std::pair<unsigned int, unsigned int> k(event.joystickButton.joystickId, event.joystickButton.button);
			p_joystick_button_pressed[k] = false;
			p_joystick_button_down[k] = false;
			p_joystick_button_released[k] = true;
			return true;
		}
		else if (event.type == sf::Event::JoystickMoved)
		{
			std::pair<unsigned int, unsigned int> k(event.joystickMove.joystickId, event.joystickMove.axis);
			p_joystick_axis_position[k] = event.joystickMove.position;
			return true;
		}
		return false;
	}

	std::unordered_map<unsigned int, bool> p_joystick_connected;
	std::unordered_map<unsigned int, bool> p_joystick_active;
	std::unordered_map<unsigned int, bool> p_joystick_disconnected;
	std::unordered_map<std::pair<unsigned int, unsigned int>, bool> p_joystick_button_pressed;
	std::unordered_map<std::pair<unsigned int, unsigned int>, bool> p_joystick_button_down;
	std::unordered_map<std::pair<unsigned int, unsigned int>, bool> p_joystick_button_released;
	std::unordered_map<std::pair<unsigned int, unsigned int>, float> p_joystick_axis_position;
#endif

};
#endif<commit_msg>Fixed bug with mouse position on start<commit_after>#ifndef SFML_INPUT_HANDLER_HPP
#define SFML_INPUT_HANDLER_HPP
#include <unordered_map>
#include <SFML/Window.hpp>
#include "hash_pair.hpp"

class InputHandler
{
public:
	struct MousePosition
	{
		MousePosition():
		x(0),y(0){}
		int x;
		int y;
	};
	InputHandler()
	{
		auto p = sf::Mouse::getPosition();
		p_current_mouse_info.x = p.x;
		p_current_mouse_info.y = p.y;
		p_previous_mouse_info = p_current_mouse_info;
	}
	~InputHandler(){}

	void update()
	{
		#if !(INPUT_DISABLE_KEYBOARD)
		keyUpdate();
		#endif
		#if !(INPUT_DISABLE_MOUSE)
		mouseUpdate();
		#endif
		#if !(INPUT_DISABLE_JOYSTICK)
		joystickUpdate();
		#endif
	}

	void handleEvent(const sf::Event& event)
	{
		#if !(INPUT_DISABLE_KEYBOARD)
		if (keyEvent(event)) return;
		#endif
		#if !(INPUT_DISABLE_MOUSE)
		if (mouseEvent(event)) return;
		#endif
		#if !(INPUT_DISABLE_JOYSTICK)
		if (joystickEvent(event)) return;
		#endif
	}

#if !(INPUT_DISABLE_KEYBOARD)
	bool isKeyPressed(sf::Keyboard::Key key)
	{
		return p_key_pressed[key];
	}

	bool isKeyDown(sf::Keyboard::Key key)
	{
		return p_key_down[key];
	}

	bool isKeyReleased(sf::Keyboard::Key key)
	{
		return p_key_released[key];
	}
#endif

#if !(INPUT_DISABLE_MOUSE)
	bool mouseMoved()
	{
		return p_mouse_move_event;
	}

	const MousePosition& getMouseCurrentPosition()
	{
		return p_current_mouse_info;
	}

	const MousePosition& getMousePreviousPosition()
	{
		return p_previous_mouse_info;
	}

	bool isMouseButtonPressed(sf::Mouse::Button button)
	{
		return p_mouse_button_pressed[button];
	}

	bool isMouseButtonDown(sf::Mouse::Button button)
	{
		return p_mouse_button_down[button];
	}

	bool isMouseButtonReleased(sf::Mouse::Button button)
	{
		return p_mouse_button_released[button];
	}

	bool mouseWheelScrolled()
	{
		return p_mouse_wheel_scrolled;
	}

	float getMouseWheelScrollDelta()
	{
		return p_mouse_scroll_delta;
	}
#endif

#if !(INPUT_DISABLE_JOYSTICK)
	bool isJoystickConnected(unsigned int joystickId)
	{
		return p_joystick_connected[joystickId];
	}

	bool isJoystickActive(unsigned int joystickId)
	{
		return p_joystick_active[joystickId];
	}

	bool isJoystickDisconnected(unsigned int joystickId)
	{
		return p_joystick_disconnected[joystickId];
	}

	bool isJoystickButtonPressed(unsigned int joystickId, unsigned int button)
	{
		return p_joystick_button_pressed[std::pair<unsigned int, unsigned int>(joystickId, button)];
	}

	bool isJoystickButtonDown(unsigned int joystickId, unsigned int button)
	{
		return p_joystick_button_down[std::pair<unsigned int, unsigned int>(joystickId, button)];
	}

	bool isJoystickButtonReleased(unsigned int joystickId, unsigned int button)
	{
		return p_joystick_button_released[std::pair<unsigned int, unsigned int>(joystickId, button)];
	}

	float getJoystickAxisPosition(unsigned int joystickId, sf::Joystick::Axis axis)
	{
		return p_joystick_axis_position[std::pair<unsigned int, unsigned int>(joystickId, axis)];
	}
#endif

private:
#if !(INPUT_DISABLE_KEYBOARD)
	void keyUpdate()
	{
		for (auto it = p_key_pressed.begin(); it != p_key_pressed.end(); ++it)
		{
			if (it->second)
			{
				p_key_down[it->first] = true;
				it->second = false;
			}
		}

		for (auto it = p_key_released.begin(); it != p_key_released.end(); ++it)
		{
			if (it->second)
				it->second = false;
		}
	}

	bool keyEvent(const sf::Event& event)
	{
		if (event.type == sf::Event::KeyPressed)
		{
			p_key_pressed[event.key.code] = not p_key_down[event.key.code];
			p_key_released[event.key.code] = false;
			return true;
		}
		else if (event.type == sf::Event::KeyReleased)
		{
			p_key_pressed[event.key.code] = false;
			p_key_down[event.key.code] = false;
			p_key_released[event.key.code] = true;
			return true;
		}
		return false;
	}

	std::unordered_map<unsigned int, bool> p_key_pressed;
	std::unordered_map<unsigned int, bool> p_key_down;
	std::unordered_map<unsigned int, bool> p_key_released;
#endif

#if !(INPUT_DISABLE_MOUSE)
	void mouseUpdate()
	{
		p_mouse_move_event = false;

		for (auto it = p_mouse_button_pressed.begin(); it != p_mouse_button_pressed.end(); ++it)
		{
			if (it->second)
			{
				p_mouse_button_down[it->first] = true;
				it->second = false;
			}
		}

		for (auto it = p_mouse_button_released.begin(); it != p_mouse_button_released.end(); ++it)
		{
			if (it->second)
				it->second = false;
		}

		if (p_mouse_wheel_scrolled)
		{
			p_mouse_wheel_scrolled = false;
			p_mouse_scroll_delta = 0.0f;
		}
	}

	bool mouseEvent(const sf::Event& event)
	{
		if (event.type == sf::Event::MouseButtonPressed)
		{
			p_mouse_button_pressed[event.mouseButton.button] = not p_mouse_button_down[event.mouseButton.button];
			p_mouse_button_released[event.mouseButton.button] = false;
			return true;
		}
		else if (event.type == sf::Event::MouseButtonReleased)
		{
			p_mouse_button_pressed[event.mouseButton.button] = false;
			p_mouse_button_down[event.mouseButton.button] = false;
			p_mouse_button_released[event.mouseButton.button] = true;
			return true;
		}
		else if (event.type == sf::Event::MouseMoved)
		{
			p_previous_mouse_info = p_current_mouse_info;
			MousePosition mouse;
			mouse.x = event.mouseMove.x;
			mouse.y = event.mouseMove.y;
			p_current_mouse_info = mouse;
			p_mouse_move_event = true;
			return true;
		}
		else if (event.type == sf::Event::MouseWheelMoved)
		{
			p_mouse_wheel_scrolled = true;
			p_mouse_scroll_delta = event.mouseWheel.delta;
			return true;
		}
		return false;
	}

	bool p_mouse_move_event;
	bool p_mouse_wheel_scrolled;
	float p_mouse_scroll_delta;
	MousePosition p_current_mouse_info;
	MousePosition p_previous_mouse_info;

	std::unordered_map<unsigned int, bool> p_mouse_button_pressed;
	std::unordered_map<unsigned int, bool> p_mouse_button_down;
	std::unordered_map<unsigned int, bool> p_mouse_button_released;
#endif

#if !(INPUT_DISABLE_JOYSTICK)
	void joystickUpdate()
	{
		for (auto it = p_joystick_button_pressed.begin(); it != p_joystick_button_pressed.end(); ++it)
		{
			if (it->second)
			{
				p_joystick_button_down[it->first] = true;
				it->second = false;
			}
		}

		for (auto it = p_joystick_button_released.begin(); it != p_joystick_button_released.end(); ++it)
		{
			if (it->second)
				it->second = false;
		}

		for (auto it = p_joystick_connected.begin(); it != p_joystick_connected.end(); ++it)
		{
			if (it->second)
			{
				p_joystick_active[it->first] = true;
				it->second = false;
			}
		}

		for (auto it = p_joystick_disconnected.begin(); it != p_joystick_disconnected.end(); ++it)
		{
			if (it->second)
				it->second = false;
		}
	}

	bool joystickEvent(const sf::Event& event)
	{
		if (event.type == sf::Event::JoystickConnected)
		{
			p_joystick_connected[event.joystickConnect.joystickId] = not p_joystick_active[event.joystickConnect.joystickId];
			p_joystick_disconnected[event.joystickConnect.joystickId] = false;
			return true;
		}
		else if (event.type == sf::Event::JoystickDisconnected)
		{
			p_joystick_connected[event.joystickConnect.joystickId] = false;
			p_joystick_active[event.joystickConnect.joystickId] = false;
			p_joystick_disconnected[event.joystickConnect.joystickId] = true;
			return true;
		}
		else if (event.type == sf::Event::JoystickButtonPressed)
		{
			std::pair<unsigned int, unsigned int> k(event.joystickButton.joystickId, event.joystickButton.button);
			p_joystick_button_pressed[k] = not p_joystick_button_down[k];
			p_joystick_button_released[k] = false;
			return true;
		}
		else if (event.type == sf::Event::JoystickButtonReleased)
		{
			std::pair<unsigned int, unsigned int> k(event.joystickButton.joystickId, event.joystickButton.button);
			p_joystick_button_pressed[k] = false;
			p_joystick_button_down[k] = false;
			p_joystick_button_released[k] = true;
			return true;
		}
		else if (event.type == sf::Event::JoystickMoved)
		{
			std::pair<unsigned int, unsigned int> k(event.joystickMove.joystickId, event.joystickMove.axis);
			p_joystick_axis_position[k] = event.joystickMove.position;
			return true;
		}
		return false;
	}

	std::unordered_map<unsigned int, bool> p_joystick_connected;
	std::unordered_map<unsigned int, bool> p_joystick_active;
	std::unordered_map<unsigned int, bool> p_joystick_disconnected;
	std::unordered_map<std::pair<unsigned int, unsigned int>, bool> p_joystick_button_pressed;
	std::unordered_map<std::pair<unsigned int, unsigned int>, bool> p_joystick_button_down;
	std::unordered_map<std::pair<unsigned int, unsigned int>, bool> p_joystick_button_released;
	std::unordered_map<std::pair<unsigned int, unsigned int>, float> p_joystick_axis_position;
#endif

};
#endif
<|endoftext|>


<commit_before>#define RLUA_REPLACE
#include "../rlua.h"
#if defined(_WIN32)
#include <binding/lua_unicode.cpp>
#include <Windows.h>
#include <tlhelp32.h>
#else
#include <bee/lua/binding.h>
#endif
#include <bee/filesystem.h>
#include <bee/platform.h>
#include <signal.h>

namespace rdebug_utility {
    static int fs_absolute(lua_State* L) {
#if defined(_WIN32)
#define FS_ABSOLUTE(path) fs::absolute(path)
#else
#define FS_ABSOLUTE(path) fs::absolute(path).lexically_normal()
#endif
        try {
            auto res = FS_ABSOLUTE(fs::path(bee::lua::tostring<fs::path::string_type>(L, 1))).generic_u8string();
            lua_pushlstring(L, res.data(), res.size());
            return 1;
        } catch (const std::exception& e) {
            return bee::lua::push_error(L, e);
        }
    }
    static int platform_os(lua_State* L) {
        lua_pushstring(L, BEE_OS_NAME);
        return 1;
    }

#if defined(_WIN32)
    static int getThreadId(int pid) {
        HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
        if (h != INVALID_HANDLE_VALUE) {
            THREADENTRY32 te;
            te.dwSize = sizeof(te);
            for (BOOL ok = Thread32First(h, &te); ok; ok = Thread32Next(h, &te)) {
                if (te.th32OwnerProcessID == pid) {
                    CloseHandle(h);
                    return te.th32ThreadID;
                }
            }
        }
        CloseHandle(h);
        return 0;
    }
    static void closeWindow() {
        int tid = getThreadId(GetCurrentProcessId());
        PostThreadMessageW(tid, WM_CLOSE, 0, 0);
        PostThreadMessageW(tid, WM_QUIT, 0, 0);
    }
    bool isConsoleExe(const wchar_t* exe) {
        HANDLE hExe = CreateFileW(exe, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
        if (hExe == 0) {
            return false;
        }
        DWORD read;
        char data[sizeof IMAGE_NT_HEADERS + sizeof IMAGE_DOS_HEADER];
        SetFilePointer(hExe, 0, NULL, FILE_BEGIN);
        if (!ReadFile(hExe, data, sizeof IMAGE_DOS_HEADER, &read, NULL)) {
            CloseHandle(hExe);
            return false;
        }
        SetFilePointer(hExe, ((PIMAGE_DOS_HEADER)data)->e_lfanew, NULL, FILE_BEGIN);
        if (!ReadFile(hExe, data, sizeof IMAGE_NT_HEADERS, &read, NULL)) {
            CloseHandle(hExe);
            return false;
        }
        CloseHandle(hExe);
        return ((PIMAGE_NT_HEADERS)data)->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI;
    }
    static bool isConsoleProcess() {
        wchar_t exe[MAX_PATH] = { 0 };
        GetModuleFileNameW(NULL, exe, MAX_PATH);
        return isConsoleExe(exe);
    }
#endif

    static int closeprocess(lua_State* L) {
#if defined(_WIN32)
        closeWindow();
        if (isConsoleProcess()) {
            raise(SIGINT);
        }
#else
        raise(SIGINT);
#endif
        return 0;
    }
}

RLUA_FUNC
int luaopen_remotedebug_utility(lua_State* L) {
#if defined(_WIN32)
    luaopen_bee_unicode(L);
#else
    lua_newtable(L);
#endif
    luaL_Reg lib[] = {
        {"fs_absolute", rdebug_utility::fs_absolute},
        {"platform_os", rdebug_utility::platform_os},
        {"closeprocess", rdebug_utility::closeprocess},
        {NULL, NULL}};
    luaL_setfuncs(L, lib, 0);
    return 1;
}
<commit_msg>给每个线程都发一遍<commit_after>#define RLUA_REPLACE
#include "../rlua.h"
#if defined(_WIN32)
#include <binding/lua_unicode.cpp>
#include <Windows.h>
#include <tlhelp32.h>
#else
#include <bee/lua/binding.h>
#endif
#include <bee/filesystem.h>
#include <bee/platform.h>
#include <signal.h>

namespace rdebug_utility {
    static int fs_absolute(lua_State* L) {
#if defined(_WIN32)
#define FS_ABSOLUTE(path) fs::absolute(path)
#else
#define FS_ABSOLUTE(path) fs::absolute(path).lexically_normal()
#endif
        try {
            auto res = FS_ABSOLUTE(fs::path(bee::lua::tostring<fs::path::string_type>(L, 1))).generic_u8string();
            lua_pushlstring(L, res.data(), res.size());
            return 1;
        } catch (const std::exception& e) {
            return bee::lua::push_error(L, e);
        }
    }
    static int platform_os(lua_State* L) {
        lua_pushstring(L, BEE_OS_NAME);
        return 1;
    }

#if defined(_WIN32)
    static void closeWindow() {
        HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
        if (h != INVALID_HANDLE_VALUE) {
            THREADENTRY32 te;
            te.dwSize = sizeof(te);
            for (BOOL ok = Thread32First(h, &te); ok; ok = Thread32Next(h, &te)) {
                if (te.th32OwnerProcessID == GetCurrentProcessId()) {
                    PostThreadMessageW(te.th32ThreadID, WM_QUIT, 0, 0);
                }
            }
        }
        CloseHandle(h);
    }
    bool isConsoleExe(const wchar_t* exe) {
        HANDLE hExe = CreateFileW(exe, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
        if (hExe == 0) {
            return false;
        }
        DWORD read;
        char data[sizeof IMAGE_NT_HEADERS + sizeof IMAGE_DOS_HEADER];
        SetFilePointer(hExe, 0, NULL, FILE_BEGIN);
        if (!ReadFile(hExe, data, sizeof IMAGE_DOS_HEADER, &read, NULL)) {
            CloseHandle(hExe);
            return false;
        }
        SetFilePointer(hExe, ((PIMAGE_DOS_HEADER)data)->e_lfanew, NULL, FILE_BEGIN);
        if (!ReadFile(hExe, data, sizeof IMAGE_NT_HEADERS, &read, NULL)) {
            CloseHandle(hExe);
            return false;
        }
        CloseHandle(hExe);
        return ((PIMAGE_NT_HEADERS)data)->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI;
    }
    static bool isConsoleProcess() {
        wchar_t exe[MAX_PATH] = { 0 };
        GetModuleFileNameW(NULL, exe, MAX_PATH);
        return isConsoleExe(exe);
    }
#endif

    static int closeprocess(lua_State* L) {
#if defined(_WIN32)
        closeWindow();
        if (isConsoleProcess()) {
            raise(SIGINT);
        }
#else
        raise(SIGINT);
#endif
        return 0;
    }
}

RLUA_FUNC
int luaopen_remotedebug_utility(lua_State* L) {
#if defined(_WIN32)
    luaopen_bee_unicode(L);
#else
    lua_newtable(L);
#endif
    luaL_Reg lib[] = {
        {"fs_absolute", rdebug_utility::fs_absolute},
        {"platform_os", rdebug_utility::platform_os},
        {"closeprocess", rdebug_utility::closeprocess},
        {NULL, NULL}};
    luaL_setfuncs(L, lib, 0);
    return 1;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2014-2020 Real Logic Limited.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <array>
#include <cstdint>

#include <gtest/gtest.h>

extern "C"
{
#include <concurrent/aeron_counters_manager.h>
}

#define CAPACITY (1024)
#define METADATA_CAPACITY (CAPACITY * 2)
#define MSG_TYPE_ID (101)

typedef std::array<std::uint8_t, CAPACITY> values_buffer_t;
typedef std::array<std::uint8_t, METADATA_CAPACITY> metadata_buffer_t;

static const int REUSE_TIMEOUT = 5000;

class CountersTest : public testing::Test
{
public:

    CountersTest()
    {
        m_valuesBuffer.fill(0);
        m_metadataBuffer.fill(0);
        aeron_counters_manager_init(
            &m_manager, m_metadataBuffer.data(), m_metadataBuffer.size(), m_valuesBuffer.data(), m_valuesBuffer.size(),
            aeron_epoch_clock, REUSE_TIMEOUT);
        aeron_counters_reader_init(
            &m_reader, m_metadataBuffer.data(), m_metadataBuffer.size(), m_valuesBuffer.data(), m_valuesBuffer.size());
    }

    virtual ~CountersTest()
    {
        aeron_counters_manager_close(&m_manager);
    }

protected:
    values_buffer_t m_valuesBuffer;
    metadata_buffer_t m_metadataBuffer;
    aeron_counters_reader_t m_reader;
    aeron_counters_manager_t m_manager;
};

TEST_F(CountersTest, shouldReadCounterState)
{
    int32_t state;

    EXPECT_EQ(0, aeron_counters_reader_counter_state(&m_reader, 0, &state));
    EXPECT_EQ(AERON_COUNTER_RECORD_UNUSED, state);

    int32_t id = aeron_counters_manager_allocate(&m_manager, 1234, NULL, 0, NULL, 0);

    EXPECT_EQ(0, aeron_counters_reader_counter_state(&m_reader, id, &state));
    EXPECT_EQ(AERON_COUNTER_RECORD_ALLOCATED, state);

    aeron_counters_manager_free(&m_manager, id);

    EXPECT_EQ(0, aeron_counters_reader_counter_state(&m_reader, id, &state));
    EXPECT_EQ(AERON_COUNTER_RECORD_RECLAIMED, state);

    EXPECT_EQ(-1, aeron_counters_reader_counter_state(&m_reader, m_reader.max_counter_id, &state));
    EXPECT_EQ(-1, aeron_counters_reader_counter_state(&m_reader, -1, &state));
}

TEST_F(CountersTest, shouldReadCounterLabel)
{
    const char *label = "label as text";
    char buffer[AERON_COUNTERS_MANAGER_METADATA_LENGTH];
    memset(buffer, 0, AERON_COUNTERS_MANAGER_METADATA_LENGTH);

    EXPECT_EQ(0, aeron_counters_reader_counter_label(&m_reader, 0, buffer, AERON_COUNTERS_MANAGER_METADATA_LENGTH));

    int32_t id = aeron_counters_manager_allocate(&m_manager, 1234, NULL, 0, label, strlen(label));

    EXPECT_EQ(
        (int32_t)strlen(label),
        aeron_counters_reader_counter_label(&m_reader, id, buffer, AERON_COUNTERS_MANAGER_METADATA_LENGTH));
    EXPECT_STREQ(label, buffer);

    aeron_counters_manager_free(&m_manager, id);

    // We don't reject or change records when freed.
    EXPECT_EQ(13, aeron_counters_reader_counter_label(&m_reader, 0, buffer, AERON_COUNTERS_MANAGER_METADATA_LENGTH));

    EXPECT_EQ(-1, aeron_counters_reader_counter_label(&m_reader, -1, buffer, AERON_COUNTERS_MANAGER_METADATA_LENGTH));
    EXPECT_EQ(-1, aeron_counters_reader_counter_label(
        &m_reader, m_reader.max_counter_id, buffer, AERON_COUNTERS_MANAGER_METADATA_LENGTH));
}

TEST_F(CountersTest, shouldReadTimeToReuse)
{
    int64_t deadline;
    EXPECT_EQ(0, aeron_counters_reader_free_to_reuse_deadline_ms(&m_reader, 0, &deadline));

    int32_t id = aeron_counters_manager_allocate(&m_manager, 1234, NULL, 0, NULL, 0);

    EXPECT_EQ(0, aeron_counters_reader_free_to_reuse_deadline_ms(&m_reader, id, &deadline));
    EXPECT_EQ(AERON_COUNTER_NOT_FREE_TO_REUSE, deadline);

    int64_t current_time_ms = aeron_epoch_clock();
    aeron_counters_manager_free(&m_manager, id);

    EXPECT_EQ(0, aeron_counters_reader_free_to_reuse_deadline_ms(&m_reader, id, &deadline));
    EXPECT_LE(current_time_ms + REUSE_TIMEOUT, deadline);

    EXPECT_EQ(-1, aeron_counters_reader_free_to_reuse_deadline_ms(&m_reader, m_reader.max_counter_id, &deadline));
    EXPECT_EQ(-1, aeron_counters_reader_free_to_reuse_deadline_ms(&m_reader, -1, &deadline));
}

<commit_msg>[C] Fix warnings in counters tests.<commit_after>/*
 * Copyright 2014-2020 Real Logic Limited.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <array>
#include <cstdint>

#include <gtest/gtest.h>

extern "C"
{
#include <concurrent/aeron_counters_manager.h>
}

#define CAPACITY (1024)
#define METADATA_CAPACITY (CAPACITY * 2)
#define MSG_TYPE_ID (101)

typedef std::array<std::uint8_t, CAPACITY> values_buffer_t;
typedef std::array<std::uint8_t, METADATA_CAPACITY> metadata_buffer_t;

static const int REUSE_TIMEOUT = 5000;

class CountersTest : public testing::Test
{
public:

    CountersTest()
    {
        m_valuesBuffer.fill(0);
        m_metadataBuffer.fill(0);
        aeron_counters_manager_init(
            &m_manager,
            m_metadataBuffer.data(),
            m_metadataBuffer.size(),
            m_valuesBuffer.data(),
            m_valuesBuffer.size(),
            aeron_epoch_clock,
            REUSE_TIMEOUT);
        aeron_counters_reader_init(
            &m_reader,
            m_metadataBuffer.data(),
            m_metadataBuffer.size(),
            m_valuesBuffer.data(),
            m_valuesBuffer.size());
    }

    virtual ~CountersTest()
    {
        aeron_counters_manager_close(&m_manager);
    }

protected:
    values_buffer_t m_valuesBuffer;
    metadata_buffer_t m_metadataBuffer;
    aeron_counters_reader_t m_reader;
    aeron_counters_manager_t m_manager;
};

TEST_F(CountersTest, shouldReadCounterState)
{
    int32_t state;

    EXPECT_EQ(0, aeron_counters_reader_counter_state(&m_reader, 0, &state));
    EXPECT_EQ(AERON_COUNTER_RECORD_UNUSED, state);

    int32_t id = aeron_counters_manager_allocate(&m_manager, 1234, NULL, 0, NULL, 0);

    EXPECT_EQ(0, aeron_counters_reader_counter_state(&m_reader, id, &state));
    EXPECT_EQ(AERON_COUNTER_RECORD_ALLOCATED, state);

    aeron_counters_manager_free(&m_manager, id);

    EXPECT_EQ(0, aeron_counters_reader_counter_state(&m_reader, id, &state));
    EXPECT_EQ(AERON_COUNTER_RECORD_RECLAIMED, state);

    EXPECT_EQ(-1, aeron_counters_reader_counter_state(&m_reader, (int32_t)m_reader.max_counter_id, &state));
    EXPECT_EQ(-1, aeron_counters_reader_counter_state(&m_reader, -1, &state));
}

TEST_F(CountersTest, shouldReadCounterLabel)
{
    const char *label = "label as text";
    char buffer[AERON_COUNTERS_MANAGER_METADATA_LENGTH];
    memset(buffer, 0, AERON_COUNTERS_MANAGER_METADATA_LENGTH);

    EXPECT_EQ(0, aeron_counters_reader_counter_label(&m_reader, 0, buffer, AERON_COUNTERS_MANAGER_METADATA_LENGTH));

    int32_t id = aeron_counters_manager_allocate(&m_manager, 1234, NULL, 0, label, strlen(label));

    EXPECT_EQ(
        (int32_t)strlen(label),
        aeron_counters_reader_counter_label(&m_reader, id, buffer, AERON_COUNTERS_MANAGER_METADATA_LENGTH));
    EXPECT_STREQ(label, buffer);

    aeron_counters_manager_free(&m_manager, id);

    // We don't reject or change records when freed.
    EXPECT_EQ(13, aeron_counters_reader_counter_label(&m_reader, 0, buffer, AERON_COUNTERS_MANAGER_METADATA_LENGTH));

    EXPECT_EQ(-1, aeron_counters_reader_counter_label(&m_reader, -1, buffer, AERON_COUNTERS_MANAGER_METADATA_LENGTH));
    EXPECT_EQ(-1, aeron_counters_reader_counter_label(
        &m_reader, (int32_t)m_reader.max_counter_id, buffer, AERON_COUNTERS_MANAGER_METADATA_LENGTH));
}

TEST_F(CountersTest, shouldReadTimeToReuse)
{
    int64_t deadline;
    EXPECT_EQ(0, aeron_counters_reader_free_to_reuse_deadline_ms(&m_reader, 0, &deadline));

    int32_t id = aeron_counters_manager_allocate(&m_manager, 1234, NULL, 0, NULL, 0);

    EXPECT_EQ(0, aeron_counters_reader_free_to_reuse_deadline_ms(&m_reader, id, &deadline));
    EXPECT_EQ(AERON_COUNTER_NOT_FREE_TO_REUSE, deadline);

    int64_t current_time_ms = aeron_epoch_clock();
    aeron_counters_manager_free(&m_manager, id);

    EXPECT_EQ(0, aeron_counters_reader_free_to_reuse_deadline_ms(&m_reader, id, &deadline));
    EXPECT_LE(current_time_ms + REUSE_TIMEOUT, deadline);

    EXPECT_EQ(
        -1, aeron_counters_reader_free_to_reuse_deadline_ms(&m_reader, (int32_t)m_reader.max_counter_id, &deadline));
    EXPECT_EQ(-1, aeron_counters_reader_free_to_reuse_deadline_ms(&m_reader, -1, &deadline));
}
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)
//          with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
//   Felix Schindler (2013 - 2017)
//   Rene Milk       (2014, 2016 - 2017)
//   Tobias Leibner  (2014, 2016)

#ifndef DUNE_GDT_PROLONGATIONS_HH
#define DUNE_GDT_PROLONGATIONS_HH

#include <dune/xt/functions/reinterpret.hh>
#include <dune/xt/la/container/vector-interface.hh>

#include <dune/gdt/discretefunction/default.hh>
#include <dune/gdt/discretefunction/reinterpret.hh>
#include <dune/gdt/interpolations.hh>
#include <dune/gdt/spaces/interface.hh>

namespace Dune {
namespace GDT {

/**
 * \brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [most general
 *        variant].
 *
 * \note This does not clear target.dofs().vector(). Thus, if prolongation_grid_view only covers a part of the domain of
 *       target.space().grid_view(), other contributions in target remain (which is on purpose).
 *
 * \sa interpolate
 * \sa reinterpret
 */
template <class SV, class SGV, size_t r, size_t rC, class SR, class TV, class TGV, class TR, class PGV>
std::enable_if_t<std::is_same<XT::Grid::extract_entity_t<TGV>, typename PGV::Grid::template Codim<0>::Entity>::value,
                 void>
prolong(const DiscreteFunction<SV, SGV, r, rC, SR>& source,
        DiscreteFunction<TV, TGV, r, rC, TR>& target,
        const GridView<PGV>& prolongation_grid_view)
{
  interpolate(reinterpret(source, prolongation_grid_view), target, prolongation_grid_view);
}

/**
 * \brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [uses
 *        target.space().grid_view() as prolongation_grid_view].
 */
template <class SV, class SGV, size_t r, size_t rC, class SR, class TV, class TGV, class TR>
void prolong(const DiscreteFunction<SV, SGV, r, rC, SR>& source, DiscreteFunction<TV, TGV, r, rC, TR>& target)
{
  prolong(source, target, target.space().grid_view());
}

/**
 * \brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates
 *        suitable target_function, TargetVectorType has to be provided].
 *
 * Use as in
\code
auto target_function = prolong<TargetVectorType>(source, target_space, prolongation_grid_view);
\endcode
 */
template <class TargetVectorType, class SV, class SGV, size_t r, size_t rC, class SR, class TGV, class TR, class PGV>
std::enable_if_t<std::is_same<XT::Grid::extract_entity_t<TGV>, typename PGV::Grid::template Codim<0>::Entity>::value,
                 DiscreteFunction<TargetVectorType, TGV, r, rC, TR>>
prolong(const DiscreteFunction<SV, SGV, r, rC, SR>& source,
        const SpaceInterface<TGV, r, rC, TR>& target_space,
        const GridView<PGV>& prolongation_grid_view)
{
  auto target_function = make_discrete_function<TargetVectorType>(target_space);
  prolong(source, target_function, prolongation_grid_view);
  return target_function;
}

/**
 * \brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates
 *        suitable target_function, TargetVectorType has to be provided, uses target.space().grid_view() as
 *        prolongation_grid_view].
 *
 * Use as in
\code
auto target_function = prolong<TargetVectorType>(source, target_space);
\endcode
 */
template <class TargetVectorType, class SV, class SGV, size_t r, size_t rC, class SR, class TGV, class TR>
DiscreteFunction<TargetVectorType, TGV, r, rC, TR> prolong(const DiscreteFunction<SV, SGV, r, rC, SR>& source,
                                                           const SpaceInterface<TGV, r, rC, TR>& target_space)
{
  auto target_function = make_discrete_function<TargetVectorType>(target_space);
  prolong(source, target_function);
  return target_function;
}

/**
 * \brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates
 *        suitable target_function with same VectorType as source].
 */
template <class V, class SGV, size_t r, size_t rC, class SR, class TGV, class TR, class PGV>
std::enable_if_t<std::is_same<XT::Grid::extract_entity_t<TGV>, typename PGV::Grid::template Codim<0>::Entity>::value,
                 DiscreteFunction<V, TGV, r, rC, TR>>
prolong(const DiscreteFunction<V, SGV, r, rC, SR>& source,
        const SpaceInterface<TGV, r, rC, TR>& target_space,
        const GridView<PGV>& prolongation_grid_view)
{
  auto target_function = make_discrete_function<V>(target_space);
  prolong(source, target_function, prolongation_grid_view);
  return target_function;
}

/**
 * \brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates
 *        suitable target_function with same VectorType as source, uses target.space().grid_view() as
 *        prolongation_grid_view].
 */
template <class V, class SGV, size_t r, size_t rC, class SR, class TGV, class TR>
DiscreteFunction<V, TGV, r, rC, TR> prolong(const DiscreteFunction<V, SGV, r, rC, SR>& source,
                                            const SpaceInterface<TGV, r, rC, TR>& target_space)
{
  auto target_function = make_discrete_function<V>(target_space);
  prolong(source, target_function);
  return target_function;
}

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_PROLONGATIONS_HH
<commit_msg>[prolongations] implement for time-dependent functions<commit_after>// This file is part of the dune-gdt project:
//   https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)
//          with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
//   Felix Schindler (2013 - 2017)
//   Rene Milk       (2014, 2016 - 2017)
//   Tobias Leibner  (2014, 2016)

#ifndef DUNE_GDT_PROLONGATIONS_HH
#define DUNE_GDT_PROLONGATIONS_HH

#include <vector>

#include <dune/common/dynvector.hh>

#include <dune/xt/functions/reinterpret.hh>
#include <dune/xt/la/container/vector-interface.hh>

#include <dune/gdt/discretefunction/bochner.hh>
#include <dune/gdt/discretefunction/default.hh>
#include <dune/gdt/discretefunction/reinterpret.hh>
#include <dune/gdt/interpolations.hh>
#include <dune/gdt/spaces/bochner.hh>
#include <dune/gdt/spaces/interface.hh>

namespace Dune {
namespace GDT {

// ## Variants for a DiscreteFunction ##

/**
 * \brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [most general
 *        variant].
 *
 * \note This does not clear target.dofs().vector(). Thus, if prolongation_grid_view only covers a part of the domain of
 *       target.space().grid_view(), other contributions in target remain (which is on purpose).
 *
 * \sa interpolate
 * \sa reinterpret
 */
template <class SV, class SGV, size_t r, size_t rC, class SR, class TV, class TGV, class TR, class PGV>
std::enable_if_t<std::is_same<XT::Grid::extract_entity_t<TGV>, typename PGV::Grid::template Codim<0>::Entity>::value,
                 void>
prolong(const DiscreteFunction<SV, SGV, r, rC, SR>& source,
        DiscreteFunction<TV, TGV, r, rC, TR>& target,
        const GridView<PGV>& prolongation_grid_view)
{
  interpolate(reinterpret(source, prolongation_grid_view), target, prolongation_grid_view);
}

/**
 * \brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [uses
 *        target.space().grid_view() as prolongation_grid_view].
 */
template <class SV, class SGV, size_t r, size_t rC, class SR, class TV, class TGV, class TR>
void prolong(const DiscreteFunction<SV, SGV, r, rC, SR>& source, DiscreteFunction<TV, TGV, r, rC, TR>& target)
{
  prolong(source, target, target.space().grid_view());
}

/**
 * \brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates
 *        suitable target_function, TargetVectorType has to be provided].
 *
 * Use as in
\code
auto target_function = prolong<TargetVectorType>(source, target_space, prolongation_grid_view);
\endcode
 */
template <class TargetVectorType, class SV, class SGV, size_t r, size_t rC, class SR, class TGV, class TR, class PGV>
std::enable_if_t<XT::LA::is_vector<TargetVectorType>::value
                     && std::is_same<XT::Grid::extract_entity_t<TGV>,
                                     typename PGV::Grid::template Codim<0>::Entity>::value,
                 DiscreteFunction<TargetVectorType, TGV, r, rC, TR>>
prolong(const DiscreteFunction<SV, SGV, r, rC, SR>& source,
        const SpaceInterface<TGV, r, rC, TR>& target_space,
        const GridView<PGV>& prolongation_grid_view)
{
  auto target_function = make_discrete_function<TargetVectorType>(target_space);
  prolong(source, target_function, prolongation_grid_view);
  return target_function;
}

/**
 * \brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates
 *        suitable target_function, TargetVectorType has to be provided, uses target.space().grid_view() as
 *        prolongation_grid_view].
 *
 * Use as in
\code
auto target_function = prolong<TargetVectorType>(source, target_space);
\endcode
 */
template <class TargetVectorType, class SV, class SGV, size_t r, size_t rC, class SR, class TGV, class TR>
std::enable_if_t<XT::LA::is_vector<TargetVectorType>::value, DiscreteFunction<TargetVectorType, TGV, r, rC, TR>>
prolong(const DiscreteFunction<SV, SGV, r, rC, SR>& source, const SpaceInterface<TGV, r, rC, TR>& target_space)
{
  auto target_function = make_discrete_function<TargetVectorType>(target_space);
  prolong(source, target_function);
  return target_function;
}

/**
 * \brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates
 *        suitable target_function with same VectorType as source].
 */
template <class V, class SGV, size_t r, size_t rC, class SR, class TGV, class TR, class PGV>
std::enable_if_t<std::is_same<XT::Grid::extract_entity_t<TGV>, typename PGV::Grid::template Codim<0>::Entity>::value,
                 DiscreteFunction<V, TGV, r, rC, TR>>
prolong(const DiscreteFunction<V, SGV, r, rC, SR>& source,
        const SpaceInterface<TGV, r, rC, TR>& target_space,
        const GridView<PGV>& prolongation_grid_view)
{
  auto target_function = make_discrete_function<V>(target_space);
  prolong(source, target_function, prolongation_grid_view);
  return target_function;
}

/**
 * \brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates
 *        suitable target_function with same VectorType as source, uses target.space().grid_view() as
 *        prolongation_grid_view].
 */
template <class V, class SGV, size_t r, size_t rC, class SR, class TGV, class TR>
DiscreteFunction<V, TGV, r, rC, TR> prolong(const DiscreteFunction<V, SGV, r, rC, SR>& source,
                                            const SpaceInterface<TGV, r, rC, TR>& target_space)
{
  auto target_function = make_discrete_function<V>(target_space);
  prolong(source, target_function);
  return target_function;
}

// ## Variants for a DiscreteBochnerFunction ##

/**
 * \brief Prolongs a DiscreteBochnerFunction from one (usually coarser) time grid onto another (usually finer) one [most
 *        general variant].
 *
 * \note Uses prolong() in space.
 *
 * \sa prolong
 * \sa interpolate
 * \sa reinterpret
 */
template <class SV, class SGV, class TV, class TGV, class PGV>
void prolong(const DiscreteBochnerFunction<SV, SGV>& source,
             DiscreteBochnerFunction<TV, TGV>& target,
             const GridView<PGV>& spatial_prolongation_grid_view)
{
  // prepare
  target.dof_vectors().set_all(0.);
  const auto& temporal_space = target.space().temporal_space();
  DynamicVector<size_t> local_dof_indices(temporal_space.mapper().max_local_size());
  std::vector<bool> dof_has_been_handled(temporal_space.mapper().size(), false);
  // walk the time intervals
  for (auto&& time_interval : elements(temporal_space.grid_view())) {
    temporal_space.mapper().global_indices(time_interval, local_dof_indices);
    const auto& lagrange_points_in_time =
        temporal_space.finite_element(time_interval.geometry().type()).lagrange_points();
    for (size_t ii = 0; ii < lagrange_points_in_time.size(); ++ii) {
      const size_t global_dof_index = local_dof_indices[ii];
      if (!dof_has_been_handled[global_dof_index]) {
        const auto& point_in_time = time_interval.geometry().global(lagrange_points_in_time[ii]);
        // evaluate in time
        const auto coarse_spatial_function =
            make_discrete_function(source.space().spatial_space(), source.evaluate(point_in_time));
        // prolong in space
        auto fine_spatial_function =
            make_discrete_function(target.space().spatial_space(), target.dof_vectors()[global_dof_index]);
        prolong(coarse_spatial_function, fine_spatial_function, spatial_prolongation_grid_view);
        dof_has_been_handled[global_dof_index] = true;
      }
    }
  }
} // ... prolong(...)

/**
 * \brief Prolongs a DiscreteBochnerFunction from one (usually coarser) time grid onto another (usually finer) one [uses
 *        target.space().spatial_space().grid_view() as spatial_prolongation_grid_view].
 *
 * \note Uses prolong() in space.
 *
 * \sa prolong
 * \sa interpolate
 * \sa reinterpret
 */
template <class SV, class SGV, class TV, class TGV>
void prolong(const DiscreteBochnerFunction<SV, SGV>& source, DiscreteBochnerFunction<TV, TGV>& target)
{
  prolong(source, target, target.space().spatial_space().grid_view());
}

/**
 * \brief Prolongs a DiscreteBochnerFunction from one (usually coarser) time grid onto another (usually finer) one
 *        [creates suitable target_function, TargetVectorType has to be provided].
 *
 * Use as in
\code
auto target_function = prolong<TargetVectorType>(source, target_space, spatial_prolongation_grid_view);
\endcode
 */
template <class TargetVectorType, class SV, class SGV, class TGV, size_t r, size_t rC, class R, class PGV>
std::enable_if_t<XT::LA::is_vector<TargetVectorType>::value
                     && std::is_same<XT::Grid::extract_entity_t<TGV>,
                                     typename PGV::Grid::template Codim<0>::Entity>::value,
                 DiscreteBochnerFunction<TargetVectorType, TGV, r, rC, R>>
prolong(const DiscreteBochnerFunction<SV, SGV>& source,
        const BochnerSpace<TGV, r, rC, R>& target_space,
        const GridView<PGV>& spatial_prolongation_grid_view)
{
  auto target_function = make_discrete_bochner_function<TargetVectorType>(target_space);
  prolong(source, target_function, spatial_prolongation_grid_view);
  return target_function;
}

template <class TargetVectorType, class SV, class SGV, class TGV, size_t r, size_t rC, class R>
std::enable_if_t<XT::LA::is_vector<TargetVectorType>::value, DiscreteBochnerFunction<TargetVectorType, TGV, r, rC, R>>
prolong(const DiscreteBochnerFunction<SV, SGV>& source, const BochnerSpace<TGV, r, rC, R>& target_space)
{
  return prolong<TargetVectorType>(source, target_space, target_space.spatial_space().grid_view());
}

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_PROLONGATIONS_HH
<|endoftext|>


<commit_before>//=============================================================================================================
/**
* @file     mnertclientsquidcontroldgl.cpp
* @author   Limin Sun <liminsun@nmr.mgh.harvard.edu>;
*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version  1.0
* @date     May, 2013
*
* @section  LICENSE
*
* Copyright (C) 2013, Limin Sun and Matti Hamalainen. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the
*       following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
*       the following disclaimer in the documentation and/or other materials provided with the distribution.
*     * Neither the name of the Massachusetts General Hospital nor the names of its contributors may be used
*       to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MASSACHUSETTS GENERAL HOSPITAL BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* @brief    Contains the implementation of the mnertclientSQUIDControlDgl class.
*
*/

//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "../mnertclient.h"
#include "mnertclientsquidcontroldgl.h"
#include "ui_mnertclientsquidcontroldgl.h"

//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace MneRtClientPlugin;

//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================

mnertclientSQUIDControlDgl::mnertclientSQUIDControlDgl(MneRtClient* p_pMneRtClient,QWidget *parent) :
    QDialog(parent),
    m_pMneRtClient(p_pMneRtClient),
    ui(new Ui::mnertclientSQUIDControlDgl)
{
    ui->setupUi(this);

    // retune
    connect(ui->m_Qbn_retune, &QPushButton::released, this, &mnertclientSQUIDControlDgl::SendRetune);

}

mnertclientSQUIDControlDgl::~mnertclientSQUIDControlDgl()
{
    delete ui;
}

void mnertclientSQUIDControlDgl::SendRetune()
{
    // Send FLL command to cmdclient
    if(m_pMneRtClient->m_bCmdClientIsConnected)
    {
        this->ui->m_tx_info->setText(QString("Send Retune Command"));
        QString t_sReply = m_pMneRtClient->m_pRtCmdClient->sendCLICommand(QString("RETUNE"));
        this->ui->m_tx_info->setText(QString("Reply:")+t_sReply);
    }
}
<commit_msg>add one FLL routine<commit_after>//=============================================================================================================
/**
* @file     mnertclientsquidcontroldgl.cpp
* @author   Limin Sun <liminsun@nmr.mgh.harvard.edu>;
*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version  1.0
* @date     May, 2013
*
* @section  LICENSE
*
* Copyright (C) 2013, Limin Sun and Matti Hamalainen. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the
*       following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
*       the following disclaimer in the documentation and/or other materials provided with the distribution.
*     * Neither the name of the Massachusetts General Hospital nor the names of its contributors may be used
*       to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MASSACHUSETTS GENERAL HOSPITAL BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* @brief    Contains the implementation of the mnertclientSQUIDControlDgl class.
*
*/

//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "../mnertclient.h"
#include "mnertclientsquidcontroldgl.h"
#include "ui_mnertclientsquidcontroldgl.h"

//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace MneRtClientPlugin;

//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================

mnertclientSQUIDControlDgl::mnertclientSQUIDControlDgl(MneRtClient* p_pMneRtClient,QWidget *parent) :
    QDialog(parent),
    m_pMneRtClient(p_pMneRtClient),
    ui(new Ui::mnertclientSQUIDControlDgl)
{
    ui->setupUi(this);

    // retune
    connect(ui->m_Qbn_retune, &QPushButton::released, this, &mnertclientSQUIDControlDgl::SendRetune);

}

mnertclientSQUIDControlDgl::~mnertclientSQUIDControlDgl()
{
    delete ui;
}

void mnertclientSQUIDControlDgl::SendRetune()
{
    QString t_sJsonCommand =
            "{"
            "   \"commands\": {"
            "       \"FLL\": {"
            "           \"description\": \"FLL hardware control\","
            "           \"parameters\": {}"
            "        }"
            "    }"
            "}";

    // Send FLL command to cmdclient
    if(m_pMneRtClient->m_bCmdClientIsConnected)
    {
        this->ui->m_tx_info->setText(QString("Send Retune Command"));
        QString t_sReply = m_pMneRtClient->m_pRtCmdClient->sendCLICommandFLL(t_sJsonCommand);
        this->ui->m_tx_info->setText(QString("Reply:")+t_sReply);
    }
}
<|endoftext|>


<commit_before><commit_msg>add languages/program_on_cpp/In_Depth_C++_11/chapter5-thread/async.cpp<commit_after><|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/phy/adr32s.H $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file adr32s.H
/// @brief Subroutines for the PHY ADR32S registers
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB

#ifndef _MSS_ADR32S_H_
#define _MSS_ADR32S_H_

#include <fapi2.H>
#include <p9_mc_scom_addresses.H>
#include <p9_mc_scom_addresses_fld.H>

#include <lib/shared/mss_const.H>
#include <lib/utils/scom.H>

namespace mss
{

// I have a dream that the PHY code can be shared among controllers. So, I drive the
// engine from a set of traits. This might be folly. Allow me to dream. BRS

///
/// @class adr32sTraits
/// @brief a collection of traits associated with the PHY ADR32S interface
/// @tparam T fapi2::TargetType representing the PHY
///
template< fapi2::TargetType T >
class adr32sTraits;

///
/// @class adr32sTraits
/// @brief a collection of traits associated with the Centaur PHY ADR32S interface
///
template<>
class adr32sTraits<fapi2::TARGET_TYPE_MBA>
{
};

///
/// @class adr32sTraits
/// @brief a collection of traits associated with the Nimbus PHY ADR32S
///
template<>
class adr32sTraits<fapi2::TARGET_TYPE_MCA>
{
    public:

        // Number of ADR32S units
        static constexpr uint64_t ADR32S_COUNT = 2;

        // MCA ADR32S control registers all come in pairs.
        static const std::vector<uint64_t> DLL_CNFG_REG;

        enum
        {
            DLL_CNTL_INIT_RXDLL_CAL_RESET = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_INIT_RXDLL_CAL_RESET,
            DLL_CNTL_INIT_RXDLL_CAL_UPDATE = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_INIT_RXDLL_CAL_UPDATE,
            DLL_CNTL_REGS_RXDLL_CAL_SKIP = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_REGS_RXDLL_CAL_SKIP,
            DLL_CNTL_REGS_RXDLL_CAL_SKIP_LEN = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_REGS_RXDLL_CAL_SKIP_LEN,
            DLL_CNTL_REGS_RXDLL_COARSE_ADJ_BY2 = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_REGS_RXDLL_COARSE_ADJ_BY2,
            DLL_CNTL_RXREG_FILTER_LENGTH_DC = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_RXREG_FILTER_LENGTH_DC,
            DLL_CNTL_RXREG_FILTER_LENGTH_DC_LEN = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_RXREG_FILTER_LENGTH_DC_LEN,
            DLL_CNTL_RXREG_LEAD_LAG_SEPARATION_DC = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_RXREG_LEAD_LAG_SEPARATION_DC,
            DLL_CNTL_RXREG_LEAD_LAG_SEPARATION_DC_LEN =
                MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_RXREG_LEAD_LAG_SEPARATION_DC_LEN,
            DLL_CNTL_EN_DRIVER_INVFB_DC = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_EN_DRIVER_INVFB_DC,
            DLL_CNTL_RXREG_FINECAL_2XILSB_DC = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_RXREG_FINECAL_2XILSB_DC,
            DLL_CNTL_CAL_GOOD = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_CAL_GOOD,
            DLL_CNTL_CAL_ERROR = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_CAL_ERROR,
            DLL_CNTL_CAL_ERROR_FINE = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_CAL_ERROR_FINE,

        };

};

namespace adr32s
{

///
/// @brief Read DLL_CNTL
/// @tparam I ADR32S instance e.g., 0 or 1 for a 64 bit implementation of the PHY
/// @tparam T fapi2 Target Type - derived
/// @tparam TT traits type defaults to adr32sTraits<T>
/// @param[in] i_target the fapi2 target of the port
/// @param[out] o_data the value of the register
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template< uint64_t I, fapi2::TargetType T, typename TT = adr32sTraits<T> >
inline fapi2::ReturnCode read_dll_cntl( const fapi2::Target<T>& i_target, fapi2::buffer<uint64_t>& o_data )
{
    static_assert( I < TT::ADR32S_COUNT, "adr32s instance out of range");
    FAPI_TRY( mss::getScom(i_target, TT::DLL_CNFG_REG[I], o_data) );
    FAPI_INF("dll_cntl adrs32%d: 0x%016lx", I, o_data);
fapi_try_exit:
    return fapi2::current_err;
}

///
/// @brief Write DLL_CNTL_ADR32S0
/// @tparam I ADR32S instance e.g., 0 or 1 for a 64 bit implementation of the PHY
/// @tparam T fapi2 Target Type - derived
/// @tparam TT traits type defaults to adr32sTraits<T>
/// @param[in] i_target the fapi2 target of the port
/// @param[in] i_data the value of the register
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template< uint64_t I, fapi2::TargetType T, typename TT = adr32sTraits<T> >
inline fapi2::ReturnCode write_dll_cntl( const fapi2::Target<T>& i_target, const fapi2::buffer<uint64_t>& i_data )
{
    static_assert( I < TT::ADR32S_COUNT, "adr32s instance out of range");
    FAPI_INF("dll_cntl adr32s%d: 0x%016lx", I, i_data);
    FAPI_TRY( mss::putScom(i_target, TT::DLL_CNFG_REG[I], i_data) );
fapi_try_exit:
    return fapi2::current_err;
}

//
// Reseting the DLL registers TODO RTC:156518
//

///
/// @brief Set the DLL cal reset (begins DLL cal operations)
/// @tparam T fapi2 Target Type - derived
/// @tparam TT traits type defaults to adr32sTraits<T>
/// @param[in] o_data the value of the register
/// @param[in] i_state mss::LOW or mss::HIGH representing the state of the bit
/// @note Default state is 'low' as writing a 0 forces the cal to begin.
///
template< fapi2::TargetType T = fapi2::TARGET_TYPE_MCA, typename TT = adr32sTraits<T> >
inline void set_dll_cal_reset( fapi2::buffer<uint64_t>& o_data, const states i_state = mss::LOW )
{
    FAPI_INF("set_dll_cal_reset %s", (i_state == mss::LOW ? "low" : "high"));
    o_data.writeBit<TT::DLL_CNTL_INIT_RXDLL_CAL_RESET>(i_state);
}

} // close namespace adr

} // close namespace mss

#endif
<commit_msg>Add flush, init io to phy reset<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/phy/adr32s.H $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file adr32s.H
/// @brief Subroutines for the PHY ADR32S registers
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB

#ifndef _MSS_ADR32S_H_
#define _MSS_ADR32S_H_

#include <fapi2.H>
#include <p9_mc_scom_addresses.H>
#include <p9_mc_scom_addresses_fld.H>

#include <lib/shared/mss_const.H>
#include <lib/utils/scom.H>

namespace mss
{

// I have a dream that the PHY code can be shared among controllers. So, I drive the
// engine from a set of traits. This might be folly. Allow me to dream. BRS

///
/// @class adr32sTraits
/// @brief a collection of traits associated with the PHY ADR32S interface
/// @tparam T fapi2::TargetType representing the PHY
///
template< fapi2::TargetType T >
class adr32sTraits;

///
/// @class adr32sTraits
/// @brief a collection of traits associated with the Centaur PHY ADR32S interface
///
template<>
class adr32sTraits<fapi2::TARGET_TYPE_MBA>
{
};

///
/// @class adr32sTraits
/// @brief a collection of traits associated with the Nimbus PHY ADR32S
///
template<>
class adr32sTraits<fapi2::TARGET_TYPE_MCA>
{
    public:

        // Number of ADR32S units
        static constexpr uint64_t ADR32S_COUNT = 2;

        // MCA ADR32S control registers all come in pairs.
        static const std::vector<uint64_t> DLL_CNFG_REG;
        static const std::vector<uint64_t> OUTPUT_DRIVER_REG;

        enum
        {
            DLL_CNTL_INIT_RXDLL_CAL_RESET = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_INIT_RXDLL_CAL_RESET,
            DLL_CNTL_INIT_RXDLL_CAL_UPDATE = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_INIT_RXDLL_CAL_UPDATE,
            DLL_CNTL_REGS_RXDLL_CAL_SKIP = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_REGS_RXDLL_CAL_SKIP,
            DLL_CNTL_REGS_RXDLL_CAL_SKIP_LEN = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_REGS_RXDLL_CAL_SKIP_LEN,
            DLL_CNTL_REGS_RXDLL_COARSE_ADJ_BY2 = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_REGS_RXDLL_COARSE_ADJ_BY2,
            DLL_CNTL_RXREG_FILTER_LENGTH_DC = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_RXREG_FILTER_LENGTH_DC,
            DLL_CNTL_RXREG_FILTER_LENGTH_DC_LEN = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_RXREG_FILTER_LENGTH_DC_LEN,
            DLL_CNTL_RXREG_LEAD_LAG_SEPARATION_DC = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_RXREG_LEAD_LAG_SEPARATION_DC,
            DLL_CNTL_RXREG_LEAD_LAG_SEPARATION_DC_LEN =
                MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_RXREG_LEAD_LAG_SEPARATION_DC_LEN,
            DLL_CNTL_EN_DRIVER_INVFB_DC = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_EN_DRIVER_INVFB_DC,
            DLL_CNTL_RXREG_FINECAL_2XILSB_DC = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_RXREG_FINECAL_2XILSB_DC,
            DLL_CNTL_CAL_GOOD = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_CAL_GOOD,
            DLL_CNTL_CAL_ERROR = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_CAL_ERROR,
            DLL_CNTL_CAL_ERROR_FINE = MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0_ADR0_CAL_ERROR_FINE,

            FLUSH = MCA_DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL_P0_ADR32S0_ADR0_FLUSH,
            INIT_IO = MCA_DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL_P0_ADR32S0_ADR0_INIT_IO,

        };

};

namespace adr32s
{

///
/// @brief Read DLL_CNTL
/// @tparam I ADR32S instance e.g., 0 or 1 for a 64 bit implementation of the PHY
/// @tparam T fapi2 Target Type - derived
/// @tparam TT traits type defaults to adr32sTraits<T>
/// @param[in] i_target the fapi2 target of the port
/// @param[out] o_data the value of the register
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template< uint64_t I, fapi2::TargetType T, typename TT = adr32sTraits<T> >
inline fapi2::ReturnCode read_dll_cntl( const fapi2::Target<T>& i_target, fapi2::buffer<uint64_t>& o_data )
{
    static_assert( I < TT::ADR32S_COUNT, "adr32s instance out of range");
    FAPI_TRY( mss::getScom(i_target, TT::DLL_CNFG_REG[I], o_data) );
    FAPI_INF("dll_cntl adrs32%d: 0x%016lx", I, o_data);
fapi_try_exit:
    return fapi2::current_err;
}

///
/// @brief Write DLL_CNTL_ADR32S0
/// @tparam I ADR32S instance e.g., 0 or 1 for a 64 bit implementation of the PHY
/// @tparam T fapi2 Target Type - derived
/// @tparam TT traits type defaults to adr32sTraits<T>
/// @param[in] i_target the fapi2 target of the port
/// @param[in] i_data the value of the register
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template< uint64_t I, fapi2::TargetType T, typename TT = adr32sTraits<T> >
inline fapi2::ReturnCode write_dll_cntl( const fapi2::Target<T>& i_target, const fapi2::buffer<uint64_t>& i_data )
{
    static_assert( I < TT::ADR32S_COUNT, "adr32s instance out of range");
    FAPI_INF("dll_cntl adr32s%d: 0x%016lx", I, i_data);
    FAPI_TRY( mss::putScom(i_target, TT::DLL_CNFG_REG[I], i_data) );
fapi_try_exit:
    return fapi2::current_err;
}

//
// Reseting the DLL registers TODO RTC:156518
//

///
/// @brief Set the DLL cal reset (begins DLL cal operations)
/// @tparam T fapi2 Target Type - defaults to TARGET_TYPE_MCA
/// @tparam TT traits type defaults to adr32sTraits<T>
/// @param[in] o_data the value of the register
/// @param[in] i_state mss::LOW or mss::HIGH representing the state of the bit
/// @note Default state is 'low' as writing a 0 forces the cal to begin.
///
template< fapi2::TargetType T = fapi2::TARGET_TYPE_MCA, typename TT = adr32sTraits<T> >
inline void set_dll_cal_reset( fapi2::buffer<uint64_t>& o_data, const states i_state = mss::LOW )
{
    FAPI_INF("set_dll_cal_reset %s", (i_state == mss::LOW ? "low" : "high"));
    o_data.writeBit<TT::DLL_CNTL_INIT_RXDLL_CAL_RESET>(i_state);
}

///
/// @brief Read OUTPUT_DRVIER register
/// @tparam I ADR32S instance e.g., 0 or 1 for a 64 bit implementation of the PHY
/// @tparam T fapi2 Target Type - derived
/// @tparam TT traits type defaults to adr32sTraits<T>
/// @param[in] i_target the fapi2 target of the port
/// @param[out] o_data the value of the register
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template< uint64_t I, fapi2::TargetType T, typename TT = adr32sTraits<T> >
inline fapi2::ReturnCode read_output_driver( const fapi2::Target<T>& i_target, fapi2::buffer<uint64_t>& o_data )
{
    static_assert( I < TT::ADR32S_COUNT, "adr32s instance out of range");
    FAPI_TRY( mss::getScom(i_target, TT::OUTPUT_DRIVER_REG[I], o_data) );
    FAPI_INF("output_driver adrs32%d: 0x%016lx", I, o_data);
fapi_try_exit:
    return fapi2::current_err;
}

///
/// @brief Write OUTPUT_DRIVER
/// @tparam I ADR32S instance e.g., 0 or 1 for a 64 bit implementation of the PHY
/// @tparam T fapi2 Target Type - derived
/// @tparam TT traits type defaults to adr32sTraits<T>
/// @param[in] i_target the fapi2 target of the port
/// @param[in] i_data the value of the register
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template< uint64_t I, fapi2::TargetType T, typename TT = adr32sTraits<T> >
inline fapi2::ReturnCode write_output_driver( const fapi2::Target<T>& i_target, const fapi2::buffer<uint64_t>& i_data )
{
    static_assert( I < TT::ADR32S_COUNT, "adr32s instance out of range");
    FAPI_INF("output_driver adr32s%d: 0x%016lx", I, i_data);
    FAPI_TRY( mss::putScom(i_target, TT::OUTPUT_DRIVER_REG[I], i_data) );
fapi_try_exit:
    return fapi2::current_err;
}

///
/// @brief Set the output flush
/// @tparam T fapi2 Target Type - defaults to TARGET_TYPE_MCA
/// @tparam TT traits type defaults to adr32sTraits<T>
/// @param[in] o_data the value of the register
/// @param[in] i_state mss::LOW or mss::HIGH representing the state of the bit
/// @note Default state is 'low' as writing a 0 forces the cal to begin.
///
template< fapi2::TargetType T = fapi2::TARGET_TYPE_MCA, typename TT = adr32sTraits<T> >
inline void set_output_flush( fapi2::buffer<uint64_t>& o_data, const states i_state )
{
    FAPI_INF("set_output_flush %s", (i_state == mss::LOW ? "low" : "high"));
    o_data.writeBit<TT::FLUSH>(i_state);
}

///
/// @brief Set the init io state
/// @tparam T fapi2 Target Type - defaults to TARGET_TYPE_MCA
/// @tparam TT traits type defaults to adr32sTraits<T>
/// @param[in] o_data the value of the register
/// @param[in] i_state mss::LOW or mss::HIGH representing the state of the bit
/// @note Default state is 'low' as writing a 0 forces the cal to begin.
///
template< fapi2::TargetType T = fapi2::TARGET_TYPE_MCA, typename TT = adr32sTraits<T> >
inline void set_init_io( fapi2::buffer<uint64_t>& o_data, const states i_state )
{
    FAPI_INF("set_init_io %s", (i_state == mss::LOW ? "low" : "high"));
    o_data.writeBit<TT::INIT_IO>(i_state);
}

} // close namespace adr

} // close namespace mss

#endif
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/utils/imageProcs/p9_infrastruct_help.H $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#ifndef _P9_INFRASTRUCT_HELP_H_
#define _P9_INFRASTRUCT_HELP_H_

#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>     //memcpy()
#include <errno.h>

//
// Various image/ring buffer sizes. Must be used by all users (VBU, FSP, HB, HBI, Cronus)
//
const uint32_t  MAX_REF_IMAGE_SIZE    =     1024 *
        1024; // Max reference image size.
const uint32_t  FIXED_RING_BUF_SIZE   =
    60000; // Fixed ring buf size for _fixed.

#define CHIPLET_ID_MIN            (uint8_t)0x00
#define CHIPLET_ID_MAX            (uint8_t)0x37

#define MY_INF(_fmt_, _args_...) printf(_fmt_, ##_args_)
#define MY_ERR(_fmt_, _args_...) printf(_fmt_, ##_args_)
#define MY_DBG(_fmt_, _args_...) printf(_fmt_, ##_args_)

// Byte-reverse a 32-bit integer
inline uint32_t myRev32(const uint32_t i_x)
{
    uint32_t rx;

#ifdef _BIG_ENDIAN
    rx = i_x;
#else
    uint8_t* pix = (uint8_t*)(&i_x);
    uint8_t* prx = (uint8_t*)(&rx);

    prx[0] = pix[3];
    prx[1] = pix[2];
    prx[2] = pix[1];
    prx[3] = pix[0];
#endif

    return rx;
}

// Byte-reverse a 64-bit integer
inline uint64_t myRev64(const uint64_t i_x)
{
    uint64_t rx;

#ifdef _BIG_ENDIAN
    rx = i_x;
#else
    uint8_t* pix = (uint8_t*)(&i_x);
    uint8_t* prx = (uint8_t*)(&rx);

    prx[0] = pix[7];
    prx[1] = pix[6];
    prx[2] = pix[5];
    prx[3] = pix[4];
    prx[4] = pix[3];
    prx[5] = pix[2];
    prx[6] = pix[1];
    prx[7] = pix[0];
#endif

    return rx;
}

// Byte-reverse a 16-bit integer if on an LE machine
inline uint16_t myRev16(const uint16_t i_x)
{
    uint16_t rx;

#ifdef _BIG_ENDIAN
    rx = i_x;
#else
    uint8_t* pix = (uint8_t*)(&i_x);
    uint8_t* prx = (uint8_t*)(&rx);

    prx[0] = pix[1];
    prx[1] = pix[0];
#endif

    return rx;
}

// N-byte align an address, offset or size (aos)
inline uint64_t myByteAlign( const uint8_t nBytes, const uint64_t aos)
{
    return ((aos + nBytes - 1) / nBytes) * nBytes;
}

#endif //_P9_INFRASTRUCT_HELP_H_
<commit_msg>p9_infrastruct_help: cleaning up endianess conversion<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/utils/imageProcs/p9_infrastruct_help.H $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#ifndef _P9_INFRASTRUCT_HELP_H_
#define _P9_INFRASTRUCT_HELP_H_

#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>     //memcpy()
#include <errno.h>

//
// Various image/ring buffer sizes. Must be used by all users (VBU, FSP, HB, HBI, Cronus)
//
const uint32_t  MAX_REF_IMAGE_SIZE    =     1024 *
        1024; // Max reference image size.
const uint32_t  FIXED_RING_BUF_SIZE   =
    60000; // Fixed ring buf size for _fixed.

#define CHIPLET_ID_MIN            (uint8_t)0x00
#define CHIPLET_ID_MAX            (uint8_t)0x37

#define MY_INF(_fmt_, _args_...) printf(_fmt_, ##_args_)
#define MY_ERR(_fmt_, _args_...) printf(_fmt_, ##_args_)
#define MY_DBG(_fmt_, _args_...) printf(_fmt_, ##_args_)

// N-byte align an address, offset or size (aos)
inline uint64_t myByteAlign( const uint8_t nBytes, const uint64_t aos)
{
    return ((aos + nBytes - 1) / nBytes) * nBytes;
}

#endif //_P9_INFRASTRUCT_HELP_H_
<|endoftext|>