Advertisement
Guest User

sabayon 14 patch for nvidia drivers

a guest
Nov 1st, 2015
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 24.90 KB | None | 0 0
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3.  
  4. import os
  5. import errno
  6. import subprocess
  7. try:
  8.     from subprocess import getoutput
  9. except ImportError:
  10.     from commands import getoutput
  11. import shutil
  12. import sys
  13.  
  14. # Variables
  15. xorgfile = "/etc/X11/xorg.conf"
  16. lspci = '/usr/sbin/lspci'
  17. nvidia_settings = "/usr/share/applications/nvidia-settings.desktop"
  18.  
  19. device_id_prefix = "SabayonVga"
  20. nvidia_option_prefix = "--nvidia-opt--"
  21. screen_layout_sections = []
  22. device_sections = []
  23. xorg_conf_structure = """
  24. Section "Module"
  25.    SubSection  "extmod"
  26.       Option    "omit xfree86-dga"
  27.    EndSubSection
  28.    Load    "i2c"
  29.    Load    "ddc"
  30.    Load    "vbe"
  31.    Load    "dri"
  32.    Load    "glx"
  33.    Load    "synaptics"
  34. EndSection
  35.  
  36. Section "ServerFlags"
  37.     Option    "AllowMouseOpenFail"    "true"
  38. EndSection
  39.  
  40. Section "Monitor"
  41.    Identifier    "Generic Monitor"
  42.    VertRefresh    43 - 60
  43.    HorizSync      28 - 80
  44. EndSection
  45.  
  46. __device_section__
  47.  
  48. __screen_section__
  49.  
  50. Section "DRI"
  51.    Mode 0666
  52. EndSection
  53.  
  54. Section "ServerLayout"
  55.    Identifier   "Main Layout"
  56.    __screen_layout_section__
  57. EndSection
  58.  
  59. Section "Extensions"
  60.   #Option "Composite" "Enable"
  61. EndSection
  62. """
  63.  
  64. screen_sections = []
  65. screen_section = """
  66. Section "Screen"
  67.  
  68.    Identifier    "Screen __screen_id__"
  69.    Device        "%s__screen_id__"
  70.    Monitor       "Generic Monitor"
  71.    %sOption       "AddARGBGLXVisuals" "true"
  72.    %sOption       "RegistryDwords" "EnableBrightnessControl=1"
  73.  
  74.    DefaultDepth 24
  75.  
  76.    SubSection "Display"
  77.         Depth       8
  78.         ViewPort    0 0
  79.         #Modes      "1024x768" "800x600" "640x480"
  80.    EndSubsection
  81.  
  82.    SubSection "Display"
  83.        Depth           16
  84.        ViewPort        0 0
  85.         #Modes      "1024x768" "800x600" "640x480"
  86.    EndSubsection
  87.  
  88.    SubSection "Display"
  89.        Depth           24
  90.        ViewPort        0 0
  91.         #Modes      "1024x768" "800x600" "640x480"
  92.    EndSubsection
  93.  
  94. EndSection
  95. """ % (device_id_prefix, nvidia_option_prefix,
  96.        nvidia_option_prefix,)
  97.  
  98. # cmdlines
  99. options = sys.argv[1:]
  100. dryrun = False
  101. noproprietary = False
  102. nvidia_forcefail = False
  103. nvidia_disablelegacy = False
  104. legacy = False
  105. livecd = False
  106. steps = []
  107. forced_xdriver = ''
  108. current_arch = os.uname()[4]
  109. nomodeset = False
  110. noefi = False
  111.  
  112. fglrx_supported = sorted(getoutput(
  113.         "modinfo fglrx | grep alias | grep pci | "
  114.         "cut -d':' -f 3 | cut -d'*' -f 1 | "
  115.         "sed 's/.*1002d//' | sed 's/^0000//' | sed 's/sv$//'"
  116.         ).lower().split())
  117.  
  118. nvidia_71xx_supported = ['0020', '0028', '0029', '002c', '002d', '00a0',
  119.     '0100', '0101', '0103', '0150', '0151', '0152', '0153']
  120. nvidia_96xx_supported = ['0110', '0111', '0112', '0113', '0170', '0171',
  121.     '0172', '0173', '0174', '0175', '0176', '0177', '0178', '0179', '017a',
  122.     '017c', '017d', '0181', '0182', '0183', '0185', '0188', '018a', '018b',
  123.     '018c', '01a0', '01f0', '0200', '0201', '0202', '0203', '0250', '0251',
  124.     '0253', '0258', '0259', '025b', '0280', '0281', '0282', '0286', '0288',
  125.     '0289', '028c']
  126. nvidia_173xx_supported = ['00fa', '00fb', '00fc', '00fd', '00fe', '0301',
  127.     '0302', '0308', '0309', '0311', '0312', '0314', '031a', '031b', '031c',
  128.     '0320', '0321', '0322', '0323', '0324', '0325', '0326', '0327', '0328',
  129.     '032a', '032b', '032c', '032d', '0330', '0331', '0332', '0333', '0334',
  130.     '0338', '033f', '0341', '0342', '0343', '0344', '0347', '0348', '034c',
  131.     '034e']
  132. # Taken from here:
  133. # http://www.nvidia.com/object/IO_32667.html
  134. nvidia_304xx_supported = ['0040', '0041', '0042', '0043', '0044', '0045',
  135.     '0046', '0047', '0048', '004e', '0090', '0091', '0092', '0093', '0095',
  136.     '0098', '0099', '009d', '00c0', '00c1', '00c2', '00c3', '00c8', '00c9',
  137.     '00cc', '00cd', '00ce', '00f1', '00f2', '00f3', '00f4', '00f5', '00f6',
  138.     '00f8', '00f9', '0140', '0141', '0142', '0143', '0144', '0145', '0146',
  139.     '0147', '0148', '0149', '014a', '014c', '014d', '014e', '014f', '0160',
  140.     '0161', '0162', '0163', '0164', '0165', '0166', '0167', '0168', '0169',
  141.     '016a', '01d0', '01d1', '01d2', '01d3', '01d6', '01d7', '01d8', '01da',
  142.     '01db', '01dc', '01dd', '01de', '01df', '0211', '0212', '0215', '0218',
  143.     '0221', '0222', '0240', '0241', '0242', '0244', '0245', '0247', '0290',
  144.     '0291', '0292', '0293', '0294', '0295', '0297', '0298', '0299', '029a',
  145.     '029b', '029c', '029d', '029e', '029f', '02e0', '02e1', '02e2', '02e3',
  146.     '02e4', '038b', '0390', '0391', '0392', '0393', '0394', '0395', '0397',
  147.     '0398', '0399', '039c', '039e', '03d0', '03d1', '03d2', '03d5', '03d6',
  148.     '0531', '0533', '053a', '053b', '053e', '07e0', '07e1', '07e2', '07e3',
  149.     '07e5']
  150. savage_supported = ['8a20', '8a21', '8a22', '9102', '8c10', '8c11', '8c12',
  151.     '8c13', '8c22', '8c24', '8c26', '8c2a', '8c2b', '8c2c', '8c2d', '8c2e',
  152.     '8c2f', '8a25', '8a26', '8d01', '8d02', '8d03', '8d04']
  153. unichrome_supported = ['3108', '3118', '3157', '3343', '3344', '7205']
  154.  
  155. lspci_output = ''
  156. for option in options:
  157.     if option == "--dry-run":
  158.         dryrun = True
  159.     elif option.startswith('--with-lspci=') and len(option.split("=")) >= 2:
  160.         option = option.split("=")[1:]
  161.         option = "=".join(option)
  162.         if option.startswith('"'):
  163.             option = option[1:]
  164.         if option.startswith("'"):
  165.             option = option[1:]
  166.         if option.endswith("'"):
  167.             option = option[:len(option)-1]
  168.         if option.endswith('"'):
  169.             option = option[:len(option)-1]
  170.         lspci_output = option
  171.     elif option.startswith('--forced-xdriver=') and len(option.split("=")) == 2:
  172.         forced_xdriver = option.split("=")[1]
  173.  
  174. if not lspci_output:
  175.     lspci_output = getoutput(lspci+' -mm -n')
  176.  
  177. # parse cmdline
  178. with open("/proc/cmdline","r") as f:
  179.     cmdline = f.readline().split()
  180. for cmd in cmdline:
  181.     if cmd == "noproprietary":
  182.         noproprietary = True
  183.     elif cmd == "nomodeset":
  184.         nomodeset = True
  185.     elif cmd == "nvidia=forcefail":
  186.         nvidia_forcefail = True
  187.     elif cmd == "nvidia=disablelegacy":
  188.         nvidia_disablelegacy = True
  189.     elif cmd == "legacy":
  190.         legacy = True
  191.     elif cmd == "cdroot":
  192.         livecd = True
  193.     elif cmd == "noefi":
  194.         noefi = True
  195.     elif cmd.startswith("xdriver=") and (len(cmd.split("=")) == 2):
  196.         if not forced_xdriver:
  197.             forced_xdriver = cmd.split("=")[1] # --forced-xdriver= owns
  198.  
  199. def openrc_running():
  200.     return os.path.isfile("/run/openrc/softlevel")
  201.  
  202. def systemd_running():
  203.     return os.path.isdir("/run/systemd/system")
  204.  
  205. def remove_proprietary_opengl(bumblebee):
  206.     if not dryrun:
  207.         if not bumblebee:
  208.             os.system("""
  209.            mount -t tmpfs none /usr/lib/opengl/ati &> /dev/null
  210.            mount -t tmpfs none /usr/lib/opengl/nvidia &> /dev/null
  211.            sed -i '/LIBGL_DRIVERS_PATH/ s/.*//' /etc/profile.env
  212.            """)
  213.             fix_possible_opengl_misconfiguration('xorg-x11')
  214.         else:
  215.             print("Bumblebee enabled, not deactivating proprietary drivers")
  216.     else:
  217.         print("I was about to remove proprietary OpenGL libraries")
  218.  
  219. def get_kernel_version():
  220.     try:
  221.         return int(os.uname()[2].replace(".", "")[:3])
  222.     except (ValueError, TypeError) as err:
  223.         print("get_kernel_version: ouch: %s" % (err,))
  224.         return None
  225.  
  226. def setup_radeon_kms():
  227.     # Starting from kernel 3.6, we have CONFIG_DRM_RADEON_KMS=y
  228.     kver = get_kernel_version()
  229.     if kver is None:
  230.         kver = 360 # assume new kernel
  231.     if not dryrun and kver < 360:
  232.         os.system("""
  233.        modprobe -r radeon &> /dev/null
  234.        modprobe radeon modeset=1 && touch /tmp/.radeon.kms
  235.        """)
  236.     else:
  237.         print("I was about to modprobe radeon modeset=1")
  238.  
  239. def generate_fglrx_steps(videocard, cardnumber, total_cards, bus_id):
  240.     print("AMD!")
  241.     print("total supported AMD cards: %s" % (len(fglrx_supported),))
  242.     print("supported list:", fglrx_supported)
  243.     supported = card_id in fglrx_supported
  244.     if supported:
  245.         print("fglrx driver supports this card")
  246.     # check if nomodeset is enabled for >=3.6.0 kernel
  247.     kver = get_kernel_version()
  248.     if kver is None:
  249.         kver = 360 # assume new kernel
  250.     if not nomodeset and kver >= 360:
  251.         print("however, nomodeset is not set, though KMS is active,"
  252.               " defaulting to OSS driver")
  253.         supported = False
  254.  
  255.     if supported:
  256.         if noproprietary:
  257.             steps.append((drop_kernel_mod, "fglrx",))
  258.             steps.append((setup_radeon_kms,))
  259.         else:
  260.             steps.append((fix_possible_opengl_misconfiguration,
  261.                           "ati"))
  262.             steps.append((copy_ati_settings_on_desktop,))
  263.             steps.append((opengl_activate, "ati"))
  264.             steps.append((set_xorg_device, "fglrx",
  265.                           cardnumber, total_cards, bus_id,))
  266.     else:
  267.         # video card not supported by fglrx
  268.         print("using OSS 'ati' drivers")
  269.         generate_generic_steps()
  270.         # This works for Mach64, Rage128
  271.         # Radeon and in future RadeonHD driver
  272.         steps.append((drop_kernel_mod, "fglrx",))
  273.         steps.append((setup_radeon_kms,))
  274.  
  275. def check_if_driver_is_available(xdriver):
  276.     drv_path = "/usr/lib/xorg/modules/drivers/" + xdriver + "_drv.so"
  277.     if os.path.isfile(drv_path):
  278.         print("check_if_driver_is_available for " + xdriver + ": available")
  279.         return True
  280.     print("check_if_driver_is_available for " + xdriver + ": not available")
  281.     return False
  282.  
  283. def check_if_proprietary_driver_system_is_healthy(kernelmod):
  284.     rc = subprocess.call(["modprobe", kernelmod])
  285.     if rc == 0:
  286.         if kernelmod == "nvidia":
  287.             if os.path.exists("/usr/lib/opengl/nvidia/lib"):
  288.                 print("check_if_proprietary_driver_system_is_healthy:"
  289.                       " nvidia healthy")
  290.                 return True
  291.             print("check_if_proprietary_driver_system_is_healthy:"
  292.                   " nvidia NOT healthy")
  293.             return False
  294.         elif kernelmod == "fglrx":
  295.             kver = get_kernel_version()
  296.             if kver is None:
  297.                 kver = 360 # assume new kernel
  298.             if not nomodeset and kver >= 360:
  299.                 print("check_if_proprietary_driver_system_is_healthy:"
  300.                       " fglrx (ati) NOT healthy, 'nomodeset' boot argument"
  301.                       " is mising")
  302.                 return False
  303.             if os.path.exists("/usr/lib/opengl/ati/lib"):
  304.                 print("check_if_proprietary_driver_system_is_healthy:"
  305.                       " fglrx (ati) healthy")
  306.                 return True
  307.             print("check_if_proprietary_driver_system_is_healthy:"
  308.                   " fglrx (ati) NOT healthy")
  309.             return False
  310.     return False
  311.  
  312. def deploy_nvidia_xxxxxx_drivers(ver):
  313.     if dryrun:
  314.         print("I was about to run deploy_nvidia_xxxxxx_drivers"
  315.               ", ver: %s" % (ver,))
  316.         return False
  317.  
  318.     drivers_dir = "/install-data/drivers"
  319.     # are they available ? we're on livecd...
  320.     if not os.path.isdir(drivers_dir):
  321.         print("drivers_dir not available")
  322.         return False
  323.  
  324.     packages = os.listdir(drivers_dir)
  325.     _packages = []
  326.     for pkg in packages:
  327.         if not pkg.endswith(".tbz2"):
  328.             continue
  329.         if pkg.startswith("x11-drivers:nvidia-drivers-" + ver):
  330.             _packages.append(pkg)
  331.         elif pkg.startswith("x11-drivers:nvidia-userspace-" + ver):
  332.             _packages.append(pkg)
  333.  
  334.     packages = [os.path.join(drivers_dir, x) for x in _packages]
  335.     if not packages:
  336.         return False
  337.  
  338.     rc = subprocess.call(["/usr/bin/equo", "install", "--nodeps"] + packages)
  339.     if rc:
  340.         return False
  341.  
  342.     # try to check driver status now
  343.     return check_if_proprietary_driver_system_is_healthy("nvidia")
  344.  
  345. efivars_loaded = False
  346. def is_efi():
  347.     """
  348.    Return whether the system boots from EFI
  349.    """
  350.     global efivars_loaded
  351.  
  352.     if noefi:
  353.         return False
  354.  
  355.     if not efivars_loaded:
  356.         subprocess.call(["modprobe", "efivars"])
  357.         efivars_loaded = True
  358.  
  359.     return os.path.exists("/sys/firmware/efi")
  360.  
  361. def get_vesa_driver():
  362.     """
  363.    Return either "vesa" or "fbdev" as the fallback
  364.    vesa-like X driver.
  365.    """
  366.     if is_efi():
  367.         # vesa does not work
  368.         return "fbdev"
  369.     return "vesa"
  370.  
  371. def set_xorg_device(xdriver, cardnum, total_cards, bus_id):
  372.     if (xdriver not in ("nvidia", "fglrx",)) and \
  373.             (not check_if_driver_is_available(xdriver)):
  374.         xdriver = get_vesa_driver() # fallback to vesa
  375.     bus_id_mark = "#"
  376.     if total_cards > 1:
  377.         bus_id_mark = ""
  378.  
  379.     device_sections.append("""
  380. Section "Device"
  381.  
  382.    Identifier  "%s%s"
  383.    Driver      "%s"
  384.    %sBusID    "%s"
  385.    #Option "RenderAccel" "on"
  386.    #Option "XAANoOffscreenPixmaps"
  387.    #Option "BusType" "PCI"
  388.    #Option "ColorTiling" "on"
  389.    #Option "EnablePageFlip" "on"
  390.    # UseEvents is causing segmentation faults with
  391.    # NVIDIA 6xxx, 7xxx and >=275.xx.xx drivers
  392.    #Option "UseEvents" "True"
  393.    Option "LogoPath" "/usr/share/backgrounds/sabayonlinux-nvidia.png"
  394.  
  395. EndSection
  396.    """ % (device_id_prefix, cardnum, xdriver, bus_id_mark, bus_id,))
  397.  
  398.     my_screen_section = screen_section.replace("__screen_id__", str(cardnum))
  399.     # setup Option AddARGBVisuals
  400.     # especially needed for legacy nvidia drivers, but works
  401.     # on all of them
  402.     if xdriver == "nvidia":
  403.         my_screen_section = my_screen_section.replace(nvidia_option_prefix, "")
  404.     else:
  405.         my_screen_section = my_screen_section.replace(nvidia_option_prefix, "#")
  406.     screen_sections.append(my_screen_section)
  407.     screen_layout_sections.append('Screen %s    "Screen %s"' % (
  408.             cardnum, cardnum,))
  409.  
  410. def opengl_activate(profile, force=False):
  411.     if not dryrun:
  412.         if not force:
  413.             current = opengl_show()
  414.             if current == profile:
  415.                 print("OpenGL profile is already set to: " + profile)
  416.                 return
  417.         subprocess.call(["eselect", "opengl", "set", profile])
  418.     else:
  419.         print("I was about to set opengl subsystem to: " + profile)
  420.  
  421. def opengl_show():
  422.     return getoutput("eselect opengl show").split("\n")[0].strip()
  423.  
  424. def fix_possible_opengl_misconfiguration(profile):
  425.     # get current subsystem
  426.     current = opengl_show()
  427.     if not dryrun:
  428.         if (profile in ("ati","nvidia","xorg-x11")) and (profile != current):
  429.             if profile == "ati" or profile == "nvidia":
  430.                 subprocess.call(["umount", "/usr/lib/opengl/" + profile])
  431.                 subprocess.call(["umount", "/usr/lib/opengl/" + profile])
  432.                 opengl_activate(profile)
  433.     else:
  434.         print("I was about to fix OpenGL subsystem to: " + \
  435.                   profile + " while the current implementation is: " + \
  436.                   current)
  437.  
  438. def copy_nvidia_settings_on_desktop():
  439.     homes = []
  440.     if os.path.isfile(nvidia_settings):
  441.         _homes = os.listdir("/home")
  442.         homes += [x for x in os.listdir("/home") \
  443.                       if os.path.isdir("/home/" + x + "/Desktop")]
  444.  
  445.     for home in homes:
  446.         try:
  447.  
  448.             full_home = os.path.join("/home", home)
  449.             st = os.stat(full_home)
  450.             dest_path = "/home/" + home + "/Desktop/" + \
  451.                 os.path.basename(nvidia_settings)
  452.             shutil.copy2(nvidia_settings, dest_path)
  453.             os.chmod(dest_path, 0o755)
  454.             os.chown(dest_path, st.st_uid, st.st_gid)
  455.  
  456.             if os.path.isdir("/etc/skel/Desktop"):
  457.                 dest_path = os.path.join(
  458.                     "/etc/skel/Desktop",
  459.                     os.path.basename(nvidia_settings))
  460.                 shutil.copy2(nvidia_settings, dest_path)
  461.                 os.chmod(dest_path, 0o755)
  462.  
  463.         except Exception:
  464.             pass
  465.  
  466. def copy_ati_settings_on_desktop():
  467.     desktop_files = getoutput(
  468.         'equo query files ati-drivers --quiet | grep ".desktop"').split("\n")
  469.     desktop_files = [x for x in desktop_files if os.path.isfile(x)]
  470.     print("copy_ati_settings_on_desktop: found files: "+str(desktop_files))
  471.  
  472.     for ati_settings in desktop_files:
  473.         homes = os.listdir("/home")
  474.         homes = [x for x in homes if os.path.isdir("/home/" + x + "/Desktop")]
  475.         for home in homes:
  476.             try:
  477.                 full_home = os.path.join("/home", home)
  478.                 st = os.stat(full_home)
  479.                 dest_path = "/home/" + home + "/Desktop/" + \
  480.                     os.path.basename(ati_settings)
  481.                 shutil.copy2(ati_settings, dest_path)
  482.                 os.chmod(dest_path, 0o755)
  483.                 os.chown(dest_path, st.st_uid, st.st_gid)
  484.  
  485.                 if os.path.isdir("/etc/skel/Desktop"):
  486.                     dest_path = os.path.join(
  487.                         "/etc/skel/Desktop",
  488.                         os.path.basename(ati_settings))
  489.                     shutil.copy2(ati_settings, dest_path)
  490.                     os.chmod(dest_path, 0o755)
  491.             except Exception:
  492.                 pass
  493.  
  494. def setup_nvidia_drivers(card_id):
  495.     drv_string = ''
  496.     done_legacy = False
  497.  
  498.     drivers_map = (
  499.         ("304", nvidia_304xx_supported,),
  500.         ("173", nvidia_173xx_supported,),
  501.         ("96", nvidia_173xx_supported,),
  502.         ("71", nvidia_173xx_supported,),
  503.         )
  504.  
  505.     if not nvidia_disablelegacy:
  506.         for ver, lst in drivers_map:
  507.             if card_id not in lst:
  508.                 continue
  509.             print("NVIDIA %s driver selected" % (ver,))
  510.             drv_string = ver
  511.             if livecd:
  512.                 rc = deploy_nvidia_xxxxxx_drivers(ver)
  513.                 if rc:
  514.                     print("NVIDIA %s deployed correctly" % (ver,))
  515.                     done_legacy = True
  516.                     break
  517.  
  518.     if not done_legacy:
  519.         drv_string = '[latest]'
  520.         print("latest and greatest NVIDIA driver selected or unsupported")
  521.  
  522.     healthy = check_if_proprietary_driver_system_is_healthy("nvidia")
  523.     if healthy:
  524.         print("NVIDIA proprietary driver %s is loaded" % (drv_string,))
  525.  
  526.         if done_legacy:
  527.             try:
  528.                 os.makedirs("/lib/nvidia/legacy")
  529.             except OSError  as err:
  530.                 if err.errno != errno.EEXIST:
  531.                     raise
  532.             with open("/lib/nvidia/legacy/running", "w") as f:
  533.                 f.write("%s" % (drv_string,))
  534.  
  535.     return done_legacy, healthy
  536.  
  537. def generate_nvidia_bumblebee_steps(v3dcard, company_id, card_id):
  538.     done_legacy, healthy = setup_nvidia_drivers(card_id)
  539.     if not healthy:
  540.         print("NVIDIA drivers couldn't be loaded, cannot enable bumblebee")
  541.         return
  542.  
  543.     if dryrun:
  544.         print("Was about to start bumblebee")
  545.         return
  546.  
  547.     if not livecd:
  548.         print("LiveCD mode off, not starting bumblebee service")
  549.         return
  550.  
  551.     # This is used by our Installer
  552.     with open("/tmp/.bumblebee.enabled", "w") as f:
  553.         pass
  554.  
  555.     if openrc_running():
  556.         os.system("/etc/init.d/bumblebee start")
  557.     elif systemd_running():
  558.         os.system("/usr/bin/systemctl start bumblebeed")
  559.  
  560. def generate_nvidia_steps(videocard, cardnumber, total_cards, bus_id):
  561.     comp_id, card_id = extract_pci_ids(videocard)
  562.     done_legacy, healthy = setup_nvidia_drivers(card_id)
  563.  
  564.     if healthy:
  565.         if done_legacy:
  566.             # then activate nvidia opengl subsystem after resetting it
  567.             steps.append((opengl_activate, "xorg-x11"))
  568.             steps.append((opengl_activate, "nvidia"))
  569.  
  570.             steps.append((set_xorg_device, "nvidia",
  571.                           cardnumber, total_cards, bus_id,))
  572.             steps.append((fix_possible_opengl_misconfiguration, "nvidia"))
  573.             steps.append((copy_nvidia_settings_on_desktop,))
  574.  
  575.         else:
  576.  
  577.             steps.append((fix_possible_opengl_misconfiguration, "nvidia"))
  578.             steps.append((copy_nvidia_settings_on_desktop,))
  579.             steps.append((opengl_activate, "nvidia"))
  580.             steps.append((set_xorg_device, "nvidia",
  581.                           cardnumber, total_cards, bus_id,))
  582.     else:
  583.         print("NVIDIA drivers couldn't be loaded, switchting to nv driver")
  584.         steps.append((opengl_activate, "xorg-x11"))
  585.  
  586. def generate_generic_steps():
  587.     steps.append((remove_proprietary_opengl, bb_enabled))
  588.     steps.append((opengl_activate, "xorg-x11",))
  589.  
  590. def drop_kernel_mod(kmod):
  591.     return subprocess.call(["modprobe", "-r", kmod])
  592.  
  593. def extract_pci_ids(videocard_str):
  594.     videocard_split = [x.strip() for x in videocard_str.strip().split('"') \
  595.                            if x.strip()]
  596.     try:
  597.         card_id = videocard_split[3].split()[-1].lower().strip("[]")
  598.     except IndexError:
  599.         card_id = None
  600.  
  601.     try:
  602.         company_id = videocard_split[2].split()[-1].lower().strip("[]")
  603.     except IndexError:
  604.         company_id = None
  605.  
  606.     return company_id, card_id
  607.  
  608. def extract_vga_cards(lspci_list):
  609.     cards = []
  610.     for item in lspci_list:
  611.         try:
  612.             class_type = item.split()[1].strip('"')
  613.             if class_type == "0300":
  614.                 cards.append(item)
  615.         except IndexError:
  616.             continue
  617.     return cards
  618.  
  619. def extract_3d_cards(lspci_list):
  620.     # bumblebee support
  621.     cards = []
  622.     for item in lspci_list:
  623.         try:
  624.             class_type = item.split()[1].strip('"')
  625.             if class_type == "0302":
  626.                 cards.append(item)
  627.         except IndexError:
  628.             continue
  629.     return cards
  630.  
  631.  
  632. # Create videocards list
  633. lspci_out_split = lspci_output.split("\n")
  634. videocards = extract_vga_cards(lspci_out_split)
  635. v3dcards = extract_3d_cards(lspci_out_split)
  636. # Run the program
  637. cardnumber = -1
  638.  
  639. total_cards = len(videocards)
  640. forced_monitor_modes = False
  641. steps = []
  642. bb_enabled = False
  643. write_config = False
  644.  
  645. for v3dcard in v3dcards:
  646.  
  647.     company_id, card_id = extract_pci_ids(v3dcard)
  648.  
  649.     if company_id == "10de":
  650.         print("NVIDIA Optimus 3D Acceleration detected, enabling bumblebee")
  651.         generate_nvidia_bumblebee_steps(v3dcard, company_id, card_id)
  652.         bb_enabled = True
  653.  
  654. for videocard in videocards:
  655.  
  656.     # setup card number
  657.     cardnumber += 1
  658.     print("Card Number: " + str(cardnumber))
  659.     try:
  660.         bus_id = "PCI:%s" % (
  661.                 videocard.split()[0].split(".", 1)[0]
  662.             )
  663.     except (IndexError,ValueError,TypeError,):
  664.         bus_id = None
  665.  
  666.     if forced_xdriver:
  667.         print("You have chosen to force the X driver: " + forced_xdriver)
  668.         if forced_xdriver == "fglrx":
  669.             if check_if_proprietary_driver_system_is_healthy("fglrx") \
  670.                     or noproprietary:
  671.                 steps.append((opengl_activate, "xorg-x11"))
  672.                 forced_xdriver = "ati"
  673.                 steps.append((drop_kernel_mod, "fglrx",))
  674.             else:
  675.                 steps.append((fix_possible_opengl_misconfiguration, "ati"))
  676.                 steps.append((copy_ati_settings_on_desktop,))
  677.                 steps.append((opengl_activate, "ati"))
  678.  
  679.         elif forced_xdriver == "nvidia" and (not noproprietary):
  680.             generate_nvidia_steps(videocard, cardnumber, total_cards, bus_id)
  681.         elif forced_xdriver == "vesa":
  682.             forced_monitor_modes = True
  683.         else:
  684.             generate_generic_steps()
  685.             steps.append((set_xorg_device, forced_xdriver,
  686.                           cardnumber, total_cards, bus_id,))
  687.         write_config = True
  688.  
  689.     else:
  690.         company_id, card_id = extract_pci_ids(videocard)
  691.         print("[%s] company_id: %s | card_id: %s" % (
  692.                 cardnumber, company_id, card_id,))
  693.  
  694.         if company_id == "10de": # NVIDIA
  695.             if noproprietary:
  696.                 steps.append((set_xorg_device, "nv",
  697.                               cardnumber, total_cards, bus_id,))
  698.             else:
  699.                 generate_nvidia_steps(
  700.                     videocard, cardnumber, total_cards, bus_id)
  701.                 print("NVIDIA!")
  702.             write_config = True
  703.  
  704.         elif company_id == "1002":
  705.             generate_fglrx_steps(
  706.                 videocard, cardnumber, total_cards, bus_id)
  707.             write_config = True
  708.  
  709.         else:
  710.             generate_generic_steps()
  711.             print("GPU will be automatically detected by X.Org and udevd")
  712.  
  713.  
  714. # now create the file
  715. for args in steps:
  716.     func, args = args[0], args[1:]
  717.     func(*args)
  718.  
  719. if write_config:
  720.     config = xorg_conf_structure.replace(
  721.         '__device_section__',
  722.         '\n\n'.join(device_sections))
  723.     config = config.replace(
  724.         '__screen_section__',
  725.         '\n\n'.join(screen_sections))
  726.     config = config.replace(
  727.         '__screen_layout_section__',
  728.         '\n    '.join(screen_layout_sections))
  729.     if forced_monitor_modes:
  730.         config = config.replace('#Modes', 'Modes')
  731.  
  732.     if not dryrun:
  733.         with open(xorgfile, "w") as f:
  734.             f.write(config)
  735.             f.flush()
  736. else:
  737.     try:
  738.         os.remove(xorgfile)
  739.     except (OSError, IOError):
  740.         pass
  741.  
  742. raise SystemExit(0)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement