forked from canonical/nvidia-prime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprime-select
executable file
·407 lines (337 loc) · 13.8 KB
/
prime-select
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
#!/usr/bin/python3
#
# prime-select
#
# Copyright 2013 Canonical Ltd.
# Author: Alberto Milone <[email protected]>
#
# Script to switch between NVIDIA and Intel graphics driver libraries.
#
# Usage:
# prime-select nvidia|intel|on-demand|query
# nvidia: switches to NVIDIA's version of libGL.so
# on-demand: load NVIDIA driver, and on-demend for others
# intel: switches to the open-source version of libGL.so
# query: checks which version is currently active and writes
# "nvidia", "intel", "on-demand" or "unknown" to the
# standard output
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
import glob
import os
import sys
import re
import subprocess
import shutil
from copy import deepcopy
from subprocess import Popen, PIPE, CalledProcessError
class Switcher(object):
def __init__(self):
self._power_profile_path = '/etc/prime-discrete'
self._grub_path = '/etc/default/grub'
self._grub_cmdline_start = 'GRUB_CMDLINE_LINUX_DEFAULT='
self._old_blacklist_file = '/etc/modprobe.d/blacklist-nvidia.conf'
self._blacklist_file = '/lib/modprobe.d/blacklist-nvidia.conf'
self._nvidia_kms_file = '/lib/modprobe.d/nvidia-kms.conf'
self._nvidia_runtimepm_file = '/lib/modprobe.d/nvidia-runtimepm.conf'
self._gdm_conf_file = '/etc/gdm3/custom.conf'
self._udev_rule_file = '/lib/udev/rules.d/50-pm-nvidia.rules'
self._old_udev_rule_file = '/lib/udev/rules.d/80-pm-nvidia.rules'
def _get_profile(self):
try:
settings = open(self._power_profile_path, 'r')
except:
return 'unknown'
config = settings.read().strip()
if config == 'on':
return 'nvidia'
elif config == "on-demand":
return 'on-demand'
else:
return 'intel'
def print_profile(self):
profile = self._get_profile()
if profile == 'unknown':
return False
print('%s' % profile)
return True
def _write_profile(self, profile):
if profile == 'intel':
nvidia_power = 'off'
elif profile == "on-demand":
nvidia_power = "on-demand"
elif profile == 'nvidia':
nvidia_power = 'on'
else:
return False
# Write the settings to the file
settings = open(self._power_profile_path, 'w')
settings.write('%s\n' % nvidia_power)
settings.close()
def _has_intel_gpu(self):
status = False;
path = '/var/lib/ubuntu-drivers-common/last_gfx_boot'
if os.path.isfile(path):
with open(path, 'r') as f:
t = f.read()
if t.find('8086') != -1:
status = True
f.close()
return status
def _supports_runtimepm(self):
return os.path.isfile('/run/nvidia_runtimepm_supported')
def _is_runtimepm_enabled(self):
return os.path.isfile('/run/nvidia_runtimepm_enabled')
def _enable_runtimepm(self):
print('Writing %s' % self._nvidia_runtimepm_file)
pm_fd = open(self._nvidia_runtimepm_file, 'w')
pm_fd.write('options nvidia \"NVreg_DynamicPowerManagement=0x02\"\n')
pm_fd.close()
def _disable_runtimepm(self):
try:
print('Deleting %s' % self._nvidia_runtimepm_file)
os.unlink(self._nvidia_runtimepm_file)
except:
pass
def enable_profile(self, profile):
current_profile = self._get_profile()
if profile == current_profile:
# No need to do anything if we're already using the desired
# profile
sys.stdout.write('Info: the %s profile is already set\n' % (profile))
return True
sys.stdout.write('Info: selecting the %s profile\n' % (profile))
self._backup_grub_config()
if profile == 'nvidia':
# Always allow enabling nvidia
# (No need to check if nvidia is available)
self._enable_nvidia()
elif profile == "on-demand":
self._disable_nvidia(keep_nvidia_modules=True)
if self._supports_runtimepm():
self._enable_runtimepm()
self._enable_kms()
else:
# Make sure that the installed packages support PRIME
#if not self._supports_prime():
# sys.stderr.write('Error: the installed packages do not support PRIME\n')
# return False
self._disable_nvidia()
# Write the settings to the config file
self._write_profile(profile)
return True
def _create_pm_udev_rule(self, keep_nvidia=True, with_workaround=False):
workaround = '''# Remove NVIDIA USB xHCI Host Controller devices, if present
ACTION=="add", SUBSYSTEM=="pci", ATTR{vendor}=="0x10de", ATTR{class}=="0x0c0330", ATTR{remove}="1"
# Remove NVIDIA USB Type-C UCSI devices, if present
ACTION=="add", SUBSYSTEM=="pci", ATTR{vendor}=="0x10de", ATTR{class}=="0x0c8000", ATTR{remove}="1"
# Remove NVIDIA Audio devices, if present
ACTION=="add", SUBSYSTEM=="pci", ATTR{vendor}=="0x10de", ATTR{class}=="0x040300", ATTR{remove}="1"\n'''
udev_rule_stub = '''%s%s# Enable runtime PM for NVIDIA VGA/3D controller devices on driver bind
ACTION=="bind", SUBSYSTEM=="pci", ATTR{vendor}=="0x10de", ATTR{class}=="0x030000", TEST=="power/control", ATTR{power/control}="auto"
ACTION=="bind", SUBSYSTEM=="pci", ATTR{vendor}=="0x10de", ATTR{class}=="0x030200", TEST=="power/control", ATTR{power/control}="auto"
# Disable runtime PM for NVIDIA VGA/3D controller devices on driver unbind
ACTION=="unbind", SUBSYSTEM=="pci", ATTR{vendor}=="0x10de", ATTR{class}=="0x030000", TEST=="power/control", ATTR{power/control}="on"
ACTION=="unbind", SUBSYSTEM=="pci", ATTR{vendor}=="0x10de", ATTR{class}=="0x030200", TEST=="power/control", ATTR{power/control}="on"'''
disable_nvidia_stub = '''# Remove NVIDIA VGA/3D controller
ACTION=="add", SUBSYSTEM=="pci", ATTR{vendor}=="0x10de", ATTR{class}=="0x030000", ATTR{remove}="1"
ACTION=="add", SUBSYSTEM=="pci", ATTR{vendor}=="0x10de", ATTR{class}=="0x038000", ATTR{remove}="1"\n'''
if with_workaround:
workaround_stub = workaround
else:
workaround_stub = ''
if keep_nvidia or not self._has_intel_gpu():
complete_stub = ''
else:
complete_stub = disable_nvidia_stub
udev_rule = udev_rule_stub % (complete_stub, workaround_stub)
try:
os.unlink(self._old_udev_rule_file)
except:
pass
rule_fd = open(self._udev_rule_file, 'w')
rule_fd.write('%s\n' % (udev_rule))
rule_fd.close()
def _disable_nvidia(self, keep_nvidia_modules=False):
try:
os.unlink(self._old_blacklist_file)
except:
pass
if keep_nvidia_modules:
try:
os.unlink(self._blacklist_file)
except:
pass
else:
self._blacklist_nvidia()
try:
os.unlink(self._old_udev_rule_file)
except:
pass
self._create_pm_udev_rule(keep_nvidia_modules)
def _enable_nvidia(self):
try:
os.unlink(self._old_blacklist_file)
except:
pass
self._disable_runtimepm()
try:
os.unlink(self._blacklist_file)
except:
pass
try:
os.unlink(self._udev_rule_file)
except:
pass
# Create configuration file so that users can enable
# KMS easily.
# modeset is off by default.
if not os.path.isfile(self._nvidia_kms_file):
self._enable_kms()
def _blacklist_nvidia(self):
blacklist_text = '''# Do not modify
# This file was generated by nvidia-prime
blacklist nvidia
blacklist nvidia-drm
blacklist nvidia-modeset
alias nvidia off
alias nvidia-drm off
alias nvidia-modeset off'''
blacklist_fd = open(self._blacklist_file, 'w')
blacklist_fd.write(blacklist_text)
blacklist_fd.close()
def _write_kms_settings(self, value):
# This is actually disabled now, but it can be enabled
# by users with a simple change.
kms_text = '''# This file was generated by nvidia-prime
# Set value to 1 to enable modesetting
options nvidia-drm modeset=%d''' % (value)
kms_fd = open(self._nvidia_kms_file, 'w')
kms_fd.write(kms_text)
kms_fd.close()
def _enable_kms(self):
self._write_kms_settings(1)
def _disable_kms(self):
self._write_kms_settings(0)
def _add_boot_params(self, pattern, path, params):
it = 0
arg_found = False
with open(path, 'r+') as f:
t = f.read()
f.seek(0)
for line in t.split('\n'):
if line.startswith(pattern):
boot_args = line.replace(pattern, '').replace('"', '')
boot_args_list = boot_args.split(' ')
final_boot_args = deepcopy(boot_args_list)
for key, value in params.items():
target_param = '%s=%s' % (key, value)
for i, arg in enumerate(boot_args_list):
if key in arg:
arg_found = True
final_boot_args[i] = '%s' % (target_param)
if not arg_found:
final_boot_args.append(target_param)
else:
arg_found = False
new_line = '%s"%s"' % (pattern, ' '.join(final_boot_args))
f.write('%s%s' % ((it > 0 and '\n' or ''), new_line))
else:
f.write('%s%s' % ((it > 0 and '\n' or ''), line))
it +=1
f.truncate()
def _remove_boot_params(self, pattern, path, params):
it = 0
arg_found = False
with open(path, 'r+') as f:
t = f.read()
f.seek(0)
for line in t.split('\n'):
if line.startswith(pattern):
boot_args = line.replace(pattern, '').replace('"', '')
boot_args_list = boot_args.split(' ')
final_boot_args = deepcopy(boot_args_list)
for key in params:
for i, arg in enumerate(boot_args_list):
if key in arg:
final_boot_args[i] = ''
final_boot_args = list(filter(bool, final_boot_args))
new_line = '%s"%s"' % (pattern, ' '.join(final_boot_args))
f.write('%s%s' % ((it > 0 and '\n' or ''), new_line))
else:
f.write('%s%s' % ((it > 0 and '\n' or ''), line))
it +=1
f.truncate()
def _find_connected_connectors(self, card):
connectors = glob.glob('/sys/class/drm/%s-*' % (card))
connected_connectors = []
for connector in connectors:
path = '%s/status' % connector
with open(path, 'r') as f:
t = f.read()
if t.strip() == 'connected':
connected_connectors.append(connector)
f.close()
return connected_connectors
def _get_boot_params_from_phantom_vga_connectors(self):
params = []
connectors = self._find_connected_connectors('card1')
for connector in connectors:
if 'vga' in connector.lower():
conn = connector.replace('/sys/class/drm/card1-', '').replace('-', '')
param = 'video=%s:d' % conn
params.append(param)
return params
def _update_grub(self):
subprocess.call(['update-grub'])
def _backup_grub_config(self):
destination = '%s.prime-backup' % self._grub_path
if not os.path.isfile(destination):
shutil.copyfile(self._grub_path, destination)
def check_root():
if not os.geteuid() == 0:
sys.stderr.write("This operation requires root privileges\n")
exit(1)
def handle_query_error():
sys.stderr.write("Error: no profile can be found\n")
exit(1)
def usage():
sys.stderr.write("Usage: %s nvidia|intel|on-demand|query\n" % (sys.argv[0]))
if __name__ == '__main__':
try:
arg = sys.argv[1]
except IndexError:
arg = None
if len(sys.argv[1:]) != 1:
usage()
exit(1)
switcher = Switcher()
if arg in ['intel', 'nvidia', 'on-demand']:
check_root()
switcher.enable_profile(arg)
elif arg == 'query':
if not switcher.print_profile():
handle_query_error()
else:
usage()
sys.exit(1)
exit(0)