Example #1
0
def hot_reset_nvidia():

    bus_ids = get_gpus_bus_ids(notation_fix=False)

    if "nvidia" not in bus_ids.keys():
        raise PCIError("Nvidia not in PCI bus")

    nvidia_pci_bridges_ids_list = _get_connected_pci_bridges(bus_ids["nvidia"])

    if len(nvidia_pci_bridges_ids_list) == 0:
        raise PCIError(
            "PCI hot reset : cannot find PCI bridge connected to Nvidia card")

    if len(nvidia_pci_bridges_ids_list) > 1:
        raise PCIError(
            "PCI hot reset : found more than one PCI bridge connected to Nvidia card"
        )

    nvidia_pci_bridge = nvidia_pci_bridges_ids_list[0]

    print("Removing Nvidia from PCI bridge")
    remove_nvidia()

    print("Triggering PCI hot reset of bridge %s" % nvidia_pci_bridge)
    try:
        exec_bash("setpci -s %s 0x488.l=0x2000000:0x2000000" %
                  nvidia_pci_bridge)
    except BashError as e:
        raise PCIError("failed to run setpci command : %s" % str(e))

    print("Rescanning PCI bus")
    rescan()

    if not is_nvidia_visible():
        raise PCIError("failed to bring Nvidia card back")
Example #2
0
def kill_current_xorg_servers():

    pids_list = get_xorg_servers_pids()

    if len(pids_list) == 0:
        return

    for signal in ["SIGTERM", "SIGKILL"]:

        if len(pids_list) > 0:
            print("There are %d X11 servers remaining, terminating them manually with %s" % (len(pids_list), signal))

        for pid in pids_list:
            try:
                exec_bash("kill -s %s %d" % (signal, pid))
            except BashError:
                pass

        success = poll_block(_is_xorg_running)

        if success:
            return
        else:
            pids_list = get_xorg_servers_pids()

    if not success:
        raise XorgError("Failed to kill all X11 servers")
Example #3
0
def is_module_loaded(module_name):

    try:
        exec_bash("lsmod | grep -E \"^%s \"" % module_name)
    except BashError:
        return False
    else:
        return True
Example #4
0
def _unload_nvidia_modules():

    print("Unloading Nvidia modules (if any)")

    try:
        exec_bash("modprobe -r nvidia_drm nvidia_modeset nvidia_uvm nvidia")
    except BashError as e:
        raise KernelSetupError("Cannot unload Nvidia modules : %s" % str(e))
Example #5
0
def _unload_nouveau():

    print("Unloading nouveau module (if any)")

    try:
        exec_bash("modprobe -r nouveau")
    except BashError as e:
        raise KernelSetupError("Cannot unload nouveau : %s" % str(e))
Example #6
0
def is_module_available(module_name):

    try:
        exec_bash("modinfo %s" % module_name)
    except BashError:
        return False
    else:
        return True
Example #7
0
def _unload_bbswitch():

    print("Unloading bbswitch module (if any)")

    try:
        exec_bash("modprobe -r bbswitch")
    except BashError as e:
        raise KernelSetupError("Cannot unload bbswitch : %s" % str(e))
Example #8
0
def _is_service_active_bash(service_name):

    try:
        exec_bash("systemctl is-active %s" % service_name)
    except BashError:
        return False
    else:
        return True
Example #9
0
def _load_nouveau(config):

    print("Loading nouveau module")

    modeset_value = 1 if config["intel"]["modeset"] == "yes" else 0

    try:
        exec_bash("modprobe nouveau modeset=%d" % modeset_value)
    except BashError as e:
        raise KernelSetupError("Cannot load nouveau : %s" % str(e))
Example #10
0
def _load_nouveau(config):

    modeset_value = {"yes": 1, "no": 0}[config["intel"]["modeset"]]

    print("Loading nouveau module")

    try:
        exec_bash("modprobe nouveau modeset=%d" % modeset_value)
    except BashError as e:
        raise KernelSetupError("Cannot load nouveau : %s" % str(e))
Example #11
0
def _load_acpi_call():

    if not checks.is_module_available("acpi_call"):
        raise KernelSetupError("Module acpi_call not available for current kernel.")

    print("Loading acpi_call module")
    try:
        exec_bash("modprobe acpi_call")
    except BashError as e:
        raise KernelSetupError("Cannot load acpi_call : %s" % str(e))
Example #12
0
def _load_bbswitch():

    if not checks.is_module_available("bbswitch"):
        raise KernelSetupError("Module bbswitch not available for current kernel.")

    print("Loading bbswitch module")
    try:
        exec_bash("modprobe bbswitch")
    except BashError as e:
        raise KernelSetupError("Cannot load bbswitch : %s" % str(e))
Example #13
0
def read_gpu_mode():
    try:
        exec_bash("glxinfo")
    except BashError as e:
        raise CheckError("Cannot find the current mode : %s" % str(e))

    try:
        exec_bash("glxinfo | grep NVIDIA")
        return "nvidia"
    except BashError:
        return "intel"
Example #14
0
def set_DPI(config):

    dpi_str = config["nvidia"]["DPI"]

    if dpi_str == "":
        return

    try:
        exec_bash("xrandr --dpi %s" % dpi_str)
    except BashError as e:
        raise XorgSetupError("Cannot set DPI : %s" % str(e))
Example #15
0
def _load_module(available_modules, module, options=None):

    options = options or ""

    print("Loading module %s" % module)

    if module not in available_modules:
        raise KernelSetupError("module %s is not available for current kernel."
                               " Is the corresponding package installed ?" % module)
    try:
        exec_bash("modprobe %s %s" % (module, options))
    except BashError as e:
        raise KernelSetupError("error running modprobe for %s : %s" % (module, str(e)))
Example #16
0
def _load_nvidia_modules(config):

    print("Loading Nvidia modules")

    pat_value = _get_PAT_parameter_value(config)
    modeset_value = 1 if config["nvidia"]["modeset"] == "yes" else 0

    try:
        exec_bash("modprobe nvidia NVreg_UsePageAttributeTable=%d" % pat_value)
        exec_bash("modprobe nvidia_drm modeset=%d" % modeset_value)

    except BashError as e:
        raise KernelSetupError("Cannot load Nvidia modules : %s" % str(e))
Example #17
0
def logout_current_desktop_session():

    print("Logging out the current desktop session")

    try:
        session_bus = dbus.SessionBus()
    except dbus.exceptions.DBusException:
        pass
    else:
        # KDE Plasma
        try:
            kde = session_bus.get_object("org.kde.ksmserver", "/KSMServer")
            kde.logout(0, 3, 3, dbus_interface="org.kde.KSMServerInterface")
        except dbus.exceptions.DBusException:
            pass

        # GNOME
        try:
            gnome = session_bus.get_object("org.gnome.SessionManager",
                                           "/org/gnome/SessionManager")
            gnome.Logout(1, dbus_interface="org.gnome.SessionManager")
        except dbus.exceptions.DBusException:
            pass

        # XFCE
        try:
            xfce = session_bus.get_object("org.xfce.SessionManager",
                                          "/org/xfce/SessionManager")
            xfce.Logout(False, True, dbus_interface="org.xfce.Session.Manager")
        except dbus.exceptions.DBusException:
            pass

        # Deepin
        try:
            deepin = session_bus.get_object('com.deepin.SessionManager',
                                            '/com/deepin/SessionManager')
            deepin.RequestLogout()
        except dbus.exceptions.DBusException:
            pass

    # i3
    try:
        exec_bash("i3-msg exit")
    except BashError:
        pass

    # openbox
    try:
        exec_bash("openbox --exit")
    except BashError:
        pass
Example #18
0
def _unload_modules(available_modules, modules_list):

    modules_to_unload = [m for m in modules_list if m in available_modules]

    if len(modules_to_unload) == 0:
        return

    print("Unloading modules %s (if loaded)" % str(modules_to_unload))

    try:
        # Unlike "rmmod", "modprobe -r" does not return an error if the module is not loaded.
        exec_bash("modprobe -r " + " ".join(modules_to_unload))
    except BashError as e:
        raise KernelSetupError("Cannot unload modules %s : %s" % (str(modules_to_unload), str(e)))
Example #19
0
def _is_xorg_running():
    try:
        exec_bash("pidof X")
        return True
    except BashError:
        pass

    try:
        exec_bash("pidof Xorg")
        return True
    except BashError:
        pass

    return False
Example #20
0
def _set_bbswitch_mode(requested_gpu_state):

    assert requested_gpu_state in ["OFF", "ON"]

    print("Setting GPU power to %s via bbswitch" % requested_gpu_state)
    exec_bash("echo %s | tee /proc/acpi/bbswitch" % requested_gpu_state)

    current_gpu_state = ("ON" if checks.is_gpu_powered() else "OFF")

    if current_gpu_state != requested_gpu_state:
        raise KernelSetupError("bbswitch failed to set the GPU to %s" %
                               requested_gpu_state)
    else:
        print("bbswitch reports that the GPU is %s" % current_gpu_state)
Example #21
0
def switch_to_intel(config):

    print("Switching to Intel")

    # Nvidia modules
    print("Unloading Nvidia modules")

    try:
        exec_bash("modprobe -r nvidia_drm nvidia_modeset nvidia_uvm nvidia")
    except BashError as e:
        raise SwitchError("Cannot unload Nvidia modules : %s" % str(e))

    if config["optimus"]["switching"] == "bbswitch":

        # Load bbswitch
        print("Loading bbswitch module")
        try:
            exec_bash("modprobe bbswitch")
        except BashError as e:
            raise SwitchError("Cannot load bbswitch : %s" % str(e))

        # bbswitch switching
        print("Ordering OFF via bbswitch")
        exec_bash("echo OFF | tee /proc/acpi/bbswitch")
        if checks.is_gpu_powered():
            raise SwitchError("bbswitch refuses to turn OFF the GPU")
        else:
            print("bbswitch reports that the GPU is OFF")

    elif config["optimus"]["switching"] == "nouveau":

        modeset_value = {"yes": 1, "no": 0}[config["intel"]["modeset"]]

        # Loading nouveau
        print("Loading nouveau module")
        try:
            exec_bash("modprobe nouveau modeset=%d" % modeset_value)
        except BashError as e:
            raise SwitchError("Cannot load nouveau : %s" % str(e))

    else:
        print("Power switching backend is disabled.")

    # PCI power management
    if config["optimus"]["pci_power_control"] == "yes":
        if config["optimus"]["switching"] == "bbswitch":
            print("bbswitch is enabled, pci_power_control option ignored.")
        else:
            try:
                pci.set_power_management(True)
            except pci.PCIError as e:
                print("WARNING : Cannot set PCI power management : %s" % str(e))

    # Xorg configuration
    print("Configuring Xorg...")
    configure_xorg(config, mode="intel")

    # Login managers configuration
    print("Configuring login managers..")
    configure_login_managers(config, mode="intel")
Example #22
0
def _try_custom_set_power_state(state):

    if state == "ON":
        script_path = envs.NVIDIA_MANUAL_ENABLE_SCRIPT_PATH
    elif state == "OFF":
        script_path = envs.NVIDIA_MANUAL_DISABLE_SCRIPT_PATH

    print("Running %s" % script_path)

    try:
        exec_bash(script_path)
    except BashError as e:
        print("ERROR : cannot run %s. Continuing anyways. Error is : %s" %
              (script_path, str(e)))
Example #23
0
def setup_PRIME():

    try:
        requested_mode = read_requested_mode()
    except VarError as e:
        raise XorgSetupError(
            "Cannot setup PRIME : cannot read requested mode : %s" % str(e))

    if requested_mode == "nvidia":

        print("Running xrandr commands")

        try:
            exec_bash("xrandr --setprovideroutputsource modesetting NVIDIA-0")
            exec_bash("xrandr --auto")
        except BashError as e:
            raise XorgSetupError("Cannot setup PRIME : %s" % str(e))

        print("Running %s" % envs.XSETUP_SCRIPT_NVIDIA)
        try:
            exec_bash(envs.XSETUP_SCRIPT_NVIDIA)
        except BashError as e:
            print("ERROR : cannot run %s : %s" %
                  (envs.XSETUP_SCRIPT_NVIDIA, str(e)))

    elif requested_mode == "intel":

        print("Running %s" % envs.XSETUP_SCRIPT_INTEL)
        try:
            exec_bash(envs.XSETUP_SCRIPT_INTEL)
        except BashError as e:
            print("ERROR : cannot run %s : %s" %
                  (envs.XSETUP_SCRIPT_INTEL, str(e)))
Example #24
0
def restart_login_manager(config):

    login_manager_control = config["optimus"]["login_manager_control"]

    if login_manager_control != "yes":
        print("Login manager control is disabled, not restarting it.")
        return

    try:
        exec_bash("systemctl restart display-manager")
    except BashError as e:
        raise LoginManagerError("Warning : cannot restart service display-manager : %s" % str(e))

    if not checks.is_login_manager_active(config):
        raise LoginManagerError("Warning : cannot restart service display-manager.")
Example #25
0
def get_xorg_servers_pids():

    try:
        x_pids = exec_bash("pidof X")
    except BashError:
        x_pids = ""

    try:
        xorg_pids = exec_bash("pidof Xorg")
    except BashError:
        xorg_pids = ""

    pids_str_list = (x_pids.split() + xorg_pids.split())

    return [int(p_str) for p_str in pids_str_list]
Example #26
0
def _get_bus_ids(match_pci_class, match_vendor_id, notation_fix=True):

    try:
        lspci_output = exec_bash("lspci -n").stdout.decode('utf-8')
    except BashError as e:
        raise PCIError("cannot run lspci -n : %s" % str(e))

    bus_ids_list = []

    for line in lspci_output.splitlines():

        items = line.split(" ")

        bus_id = items[0]

        if notation_fix:
            # Xorg expects bus IDs separated by colons in decimal instead of
            # hexadecimal format without any leading zeroes and prefixed with
            # `PCI:`, so `3c:00:0` should become `PCI:60:0:0`
            bus_id = "PCI:" + ":".join(
                str(int(field, 16)) for field in re.split("[.:]", bus_id))

        pci_class = items[1][:-1]
        vendor_id, product_id = items[2].split(":")

        if re.fullmatch(match_pci_class, pci_class) and re.fullmatch(
                match_vendor_id, vendor_id):
            bus_ids_list.append(bus_id)

    return bus_ids_list
Example #27
0
def get_PIDs_from_process_names(processes_names_list):

    PIDs_list = []

    for p_name in processes_names_list:

        try:
            process_PIDs_str = exec_bash("pidof %s" %
                                         p_name).stdout.decode('utf-8')[:-1]
        except BashError:
            continue

        try:
            process_PIDs_list = [
                int(pid_str) for pid_str in process_PIDs_str.split(" ")
            ]
        except ValueError:
            print(
                "Warning : cannot parse pidof output for process %s : invalid value : %s"
                % (p_name, process_PIDs_str))
            continue

        PIDs_list += process_PIDs_list

    return PIDs_list
Example #28
0
def kill_current_xorg_servers():

    pids_list = get_xorg_servers_pids()

    if len(pids_list) > 0:
        print("There are %d X11 servers remaining, terminating them manually" % len(pids_list))

    for pid in pids_list:
        try:
            exec_bash("kill -9 %d" % pid)
        except BashError:
            pass

    success = poll_block(_is_xorg_running)

    if not success:
        raise XorgError("Failed to kill all X11 servers")
Example #29
0
def _is_service_active(service_name):

    try:
        state = exec_bash("systemctl is-active %s.service" %
                          service_name).stdout.decode('utf-8')[:-1]
    except BashError:
        return False
    else:
        return (state == "active")
Example #30
0
def get_PID_user(PID_value):

    try:
        user = exec_bash("ps -o uname= -p %d" %
                         PID_value).stdout.decode('utf-8')[:-1]
    except BashError:
        raise ProcessesError("PID %d does not exist" % PID_value)

    return user