forked from Witko/nvidia-xrun
-
Notifications
You must be signed in to change notification settings - Fork 1
/
nvidia-xrun-core
executable file
·578 lines (440 loc) · 14.8 KB
/
nvidia-xrun-core
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
#!/bin/bash
# nvidia-xrun-core - Utility to run separate X with discrete nvidia graphics with full performance
# Copyright (C) 2018 Witko
# Copyright (C) 2018 Pekka Helenius (~Fincer)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# TODO During script initialization, remove all old inactive TTY override confs which are created by the nvidia-xrun script
# TODO When checking 'nvidia-xrun' process, consider existence of multiple 'nvidia-xrun' processes
# TODO Do not try to turn off Nvidia GPU if another nvidia-xrun-core process exists. Else, do it.
# TODO Make TTY selectable by user
# TODO Prevent multiple similar arguments (such as '--tty=3 --tty=4', '-u -u', '-h --help' etc.)
# TODO Make '-h' and '--help' arguments to override any other given arguments
# TODO Support init.d? Especially Gentoo users in mind
# TODO Replace systemd getty stuff with openvt?
# TODO Investigate behavior of multi-monitor setups with different resolutions
# BUG in some cases, Nvidia TTY does not automatically change back to the original TTY session. When the script terminates, Nvidia GPU may stay ON, too. This can happen when user boots up computer, logs in Xorg session and immediately runs the script.
# BUG In some cases, the script attempts to switch to Nvidia TTY session but fails in that. Re-running the script may succeed.
# BUG Black screen in graphically intense apps when switching between TTYs.
###########################################################
# Essential commands
COMMANDS=(
agetty
awk
cat
chvt
date
grep
id
ls
lsmod
modprobe
ps
realpath
rmmod
sleep
sudo
tail
tee
ttyecho
who
xinit
)
###########################################################
# Check for command dependencies
function checkCommands() {
if [[ $(which --help 2>/dev/null) ]] && [[ $(echo --help 2>/dev/null) ]]; then
local a=0
for command in ${@}; do
if [[ ! $(which $command 2>/dev/null) ]]; then
COMMANDS_NOTFOUND[$a]=$command
let a++
fi
done
if [[ -n $COMMANDS_NOTFOUND ]]; then
echo -e "\nError! The following commands could not be found: ${COMMANDS_NOTFOUND[*]}\nAborting\n"
exit 1
fi
else
exit 1
fi
}
checkCommands "${COMMANDS[*]}"
###########################################################
# Prevent running this script independently
# Check if 'nvidia-xrun' executable is inactive and return an error.
if [[ $(echo $(ps --no-headers -C nvidia-xrun &> /dev/null)$?) -ne 0 ]]; then
echo "Can't run this executable independently. Use 'nvidia-xrun' instead."
exit 1
fi
###########################################################
# Check who I truly am
# TODO This may be useless check, see 'nvidia-xrun' file
USER_NAME=$(who -m | awk '{print $1}')
# Get current user UID
USER_ID=`id -u ${USER_NAME}`
###########################################################
# Check if we are root or not.
# TODO This may be useless check, see 'nvidia-xrun' file
if [[ ${USER_NAME} != "root" ]] && [[ ${UID} -ne 0 ]]; then
echo "Please run this program as regular user using sudo."
exit 1
elif [[ ${USER_NAME} == "root" ]] && [[ ${UID} -eq 0 ]]; then
echo "Please run this program as regular user using sudo. Do not use root."
exit 1
fi
###########################################################
# Help message
function printHelp {
echo -e "\nUsage:"
echo -e "\nnvidia-xrun [<app>]\nOptions:\n\t-h, --help\tThis help text\n\t-u, --unload\tUnload Nvidia GPU\n"
}
###########################################################
# Set user input arguments
a=0
for arg in ${@}; do
args[$i]=${arg}
let i++
done
unset a
###########################################################
# Get user input arguments
function getArguments() {
if [[ -n "${args[*]}" ]]; then
# Test if executable exists in path
if [[ -x "$(which "${args[0]}" 2> /dev/null)" ]]; then
# Generate exec line
EXECL="$(which "${args[0]}")"
# Test if executable exists on disk
elif [[ -e "$(realpath "${args[0]}")" ]]; then
# Generate exec line
EXECL="$(realpath "${args[0]}")"
else
echo "${args[0]}: No such executable!"
exit 1
fi
#shift 1
#EXECL="$EXECL ${args[*]}"
# Exit the script if no arguments passed
else
echo "No valid input arguments given!"
printHelp
exit 1
fi
if [[ -f /etc/X11/xinit/nvidia-xinitrc ]]; then
EXECL="/etc/X11/xinit/nvidia-xinitrc $EXECL"
else
echo "Can't find file '/etc/X11/xinit/nvidia-xinitrc'. Aborting."
exit 1
fi
}
###########################################################
# Check existence of bbswitch
if [[ $(echo $(lsmod | grep bbswitch > /dev/null)$?) -eq 1 ]]; then
echo "Kernel module 'bbswitch' is not loaded. Aborting"
exit 1
fi
###########################################################
# Execute functions
function execute() {
bash -c "${1}"
}
function execute_user() {
sudo -u \#${USER_ID} -- bash -c "${1}"
}
###########################################################
# Calculate the first usable TTY
function findTTY() {
# Get all already used system TTYs and list them in TTY_RESERVED array
function reservedTTY() {
local IFS=$'\n'
local i=0
for tty in $(who | grep tty | awk '{print $2}'); do
TTY_RESERVED[$i]=${tty}
let i++
done
}
# Get all available system TTYs and list them in TTY_ALL array
function allTTY() {
# Get available TTYs using systemd logind.conf settings
# See https://www.freedesktop.org/software/systemd/man/logind.conf.html
#
if [[ -f /etc/systemd/logind.conf ]]; then
TTY_COUNT=`grep -m 1 NAutoVTs /etc/systemd/logind.conf | grep -Eo "[0-9]*"`
else
# Default TTY count
TTY_COUNT=6
fi
# First available TTY for user is 1, not 0. Thus i=1
for ((i=1;i<=TTY_COUNT;i++)); do
TTY_ALL[$i]="tty$i"
done
}
# Find all existing TTY overrides in the system and put them into a new array TTY_OVERRIDES
function existingTTYoverrides() {
if [[ -d /etc/systemd/system ]]; then
local i=0
for tty_override in $(ls /etc/systemd/system | grep -oE "tty[0-9]"); do
TTY_OVERRIDES[$i]=${tty_override}
let i++
done
fi
}
function ttyCleanup() {
# Delete all reserved tty's from TTY_ALL array
for i in "${TTY_RESERVED[@]}"; do
TTY_ALL=(${TTY_ALL[@]//*$i*})
done
if [[ -n TTY_OVERRIDES ]]; then
# Delete all overridden tty's from TTY_ALL array
for i in "${TTY_OVERRIDES[@]}"; do
TTY_ALL=(${TTY_ALL[@]//*$i*})
done
fi
if [[ -z TTY_ALL ]]; then
echo "Error: Couldn't find any free TTY sessions. Aborting."
exit 1
fi
# Get the first available TTY and set it into NVIDIA_TTY variable
NVIDIA_TTY=${TTY_ALL[0]}
NVIDIA_TTY_NUM=`echo $NVIDIA_TTY | sed 's/[a-z]//g'`
# Unset temporary arrays
unset TTY_ALL
unset TTY_RESERVED
unset TTY_OVERRIDES
echo "Running Nvidia in TTY session ${NVIDIA_TTY_NUM}"
echo "Press Alt + Ctrl + F${NVIDIA_TTY_NUM} to switch"
}
reservedTTY
allTTY
existingTTYoverrides
ttyCleanup
}
###########################################################
# Calculate the first usable display
function findDisplay() {
XNUM=-1
SOCK="something"
while [[ -n "$SOCK" ]]; do
XNUM=$(( $XNUM + 1 ))
SOCK=$(ls -A1 /tmp/.X11-unix | grep "X$XNUM")
done
NEWDISP=":$XNUM"
}
###########################################################
# Set TTY session overrides & enable the new TTY for use
function setTTYoverride() {
if [[ -n NVIDIA_TTY ]]; then
if [[ ! -d /etc/systemd/system/getty@${NVIDIA_TTY}.service.d ]]; then
execute "mkdir -p /etc/systemd/system/getty@${NVIDIA_TTY}.service.d"
fi
else
echo "Error! Couldn't determine a free TTY session."
exit 1
fi
execute "chmod 0755 /etc/systemd/system/getty@${NVIDIA_TTY}.service.d/"
#####
execute "cat <<TTY_MSG > /etc/systemd/system/getty@${NVIDIA_TTY}.service.d/issue
nvidia-xrun [${NVIDIA_TTY}]: Press Ctrl + Alt + F${CUR_VT} to switch back.
TTY_MSG"
#####
#####
execute "cat <<TTY_OVERRIDE > /etc/systemd/system/getty@${NVIDIA_TTY}.service.d/override.conf
#NVIDIA_TTY_OVERRIDE
# This file has been automatically generated by nvidia-xrun-core on $(date)
[Service]
ExecStart=
ExecStart=-/usr/bin/agetty --autologin ${USER_NAME} --noclear -f /etc/systemd/system/getty@${NVIDIA_TTY}.service.d/issue %I $TERM
TTY_OVERRIDE"
#####
execute "chmod 0644 /etc/systemd/system/getty@${NVIDIA_TTY}.service.d/override.conf"
}
function loadTTYsession() {
execute "systemctl restart getty@${NVIDIA_TTY}.service"
if [[ $(systemctl is-active getty@${NVIDIA_TTY}.service) == inactive ]]; then
echo "Error! Couldn't activate a new TTY session."
execute "rm -Rf /etc/systemd/system/getty@${NVIDIA_TTY}.service.d/"
exit 1
fi
}
###########################################################
# Enable GPU
function enableGPU() {
# Turn on Nvidia GPU
echo 'Waking up Nvidia GPU'
if ! [[ -f /proc/acpi/bbswitch ]]; then
execute "modprobe bbswitch"
fi
execute "tee /proc/acpi/bbswitch <<<ON &> /dev/null"
# Load Nvidia kernel modules
# NOTE: We need to load these individually!
echo 'Loading Nvidia kernel modules'
execute "modprobe nvidia 2>/dev/null"
execute "modprobe nvidia_modeset 2>/dev/null"
execute "modprobe nvidia_uvm 2>/dev/null"
execute "modprobe nvidia_drm 2>/dev/null"
}
###########################################################
# Disable GPU
function disableGPU() {
# Unload Nvidia kernel modules
# NOTE: We need to unload these individually!
echo 'Unloading Nvidia kernel modules'
execute "rmmod nvidia_drm 2>/dev/null"
execute "rmmod nvidia_modeset 2>/dev/null"
execute "rmmod nvidia_uvm 2>/dev/null"
execute "rmmod nvidia 2>/dev/null"
# Turn off Nvidia GPU
if [[ -f /proc/acpi/bbswitch ]]; then
echo 'Turning off Nvidia GPU'
local c=3
while [[ $c -ge 0 ]]; do
execute "tee /proc/acpi/bbswitch <<<OFF &> /dev/null"
if [[ $(cat /proc/acpi/bbswitch) == *"OFF"* ]]; then
break
fi
sleep 1
let c--
done
if [[ $(cat /proc/acpi/bbswitch) == *"ON"* ]]; then
echo "Warning: Couldn't turn off Nvidia GPU."
fi
echo "Current state of Nvidia GPU: $(cat /proc/acpi/bbswitch | awk '{print $NF}')"
else
echo "bbswitch kernel module not loaded."
fi
if [[ -n "$NVIDIA_TTY_NUM" ]]; then
# Log out from the new TTY session
echo "Logging out from graphical TTY ${NVIDIA_TTY_NUM}..."
fi
}
###########################################################
# Script arguments
if [[ $1 == "-h" ]] || [[ $1 == "--help" ]] || [[ -z $1 ]]; then
echo -e "\nUtility to run games and applications in separate X on discrete Nvidia graphic card"
printHelp
exit 0
elif [[ $1 == "-u" ]] || [[ $1 == "--unload" ]]; then
if [[ $(echo $(grep ON /proc/acpi/bbswitch > /dev/null)$?) -eq 0 ]]; then
disableGPU
exit 0
else
echo "Nvidia GPU already unloaded."
exit 0
fi
else
# TODO This may be useless check, see 'nvidia-xrun' file
for arg in ${@}; do
if [[ $arg == "sudo" ]] || [[ $arg == "su" ]]; then
echo "Can't use either 'sudo' or 'su' as an input argument. Aborting."
exit 1
fi
# TODO Match arguments such as -t 4 or -t 7
# TODO Limit TTY number between max allowed by systemd. See & modify findTTY function
# TODO Prevent setting override for TTYs which already have been overridden
#if [[ $arg =~ ^\-\-tty=[0-9]$ ]]; then
# NVIDIA_TTY_NUM=`echo $arg | sed 's/[^0-9]*//g'`
# NVIDIA_TTY=`echo "tty$NVIDIA_TTY_NUM"`
#fi
done
unset arg
getArguments
fi
# TODO remove these tests
#echo $NVIDIA_TTY
#echo $NVIDIA_TTY_NUM
#exit
###########################################################
function removeTTY() {
# Stop the Nvidia TTY session
execute "systemctl stop getty@${NVIDIA_TTY}.service"
# Remove Nvidia TTY overrides
execute "rm -Rf /etc/systemd/system/getty@${NVIDIA_TTY}.service.d/"
}
###########################################################
# Current VT session
function currentVT() {
CUR_VT=`grep -oE "[0-9]" /sys/class/tty/tty0/active`
# We set CUR_VT variable in anyway to avoid some wierd behavior
# when determining CUR_XORG_PID variable
if [[ $CUR_VT = "" ]]; then
CUR_VT="none"
fi
}
currentVT
###########################################################
# Current Xorg PID
CUR_XORG_PID=`ps h -o tty -o pid -C Xorg | grep "tty${CUR_VT}" | awk '{print $2}'`
###########################################################
# Emergency exit behavior (Ctrl + C // SIGINT)
function emergency() {
trap SIGINT
disableGPU
# if [[ $(echo $(${CUR_XORG_PID})$?) -ne 0 ]]; then
if [[ $CUR_XORG_PID != "" ]]; then
execute "chvt $CUR_VT"
removeTTY
fi
exit 0
}
###########################################################
# Allow interruption of the script at any time (Ctrl + C)
trap "emergency" INT
###########################################################
###########################################################
# RUN MOST OF THE SCRIPT FUNCTIONS HERE
# Enable Nvidia GPU
enableGPU
if [[ $CUR_XORG_PID != "" ]]; then
# Find first available TTY session for Nvidia GPU
findTTY
# Set TTY session configuration override for Nvidia GPU
setTTYoverride
# Load the new TTY session
loadTTYsession
else
NVIDIA_TTY="tty${CUR_VT}"
NVIDIA_TTY_NUM=${CUR_VT}
fi
# Find usable display
findDisplay
# Set command to execute new X session
XRUN_COMMAND="xinit ${EXECL} -- $NEWDISP vt${NVIDIA_TTY_NUM} -nolisten tcp -br -config nvidia-xorg.conf -configdir nvidia-xorg.conf.d"
if [[ $CUR_XORG_PID != "" ]]; then
# Switch to the new TTY session
execute "chvt ${NVIDIA_TTY_NUM}"
sleep 4
execute "ttyecho -n /dev/${NVIDIA_TTY} ${XRUN_COMMAND}"
else
execute_user "${XRUN_COMMAND}"
fi
# Get Nvidia Xorg server PID and wait for it to finish
echo "nvidia-xrun PID: $$"
if [[ $CUR_XORG_PID != "" ]]; then
NVIDIA_XORG_PID=`ps h -o tty -o pid -C Xorg | grep "${NVIDIA_TTY}" | awk '{print $2}'`
echo "Nvidia session Xorg PID: ${NVIDIA_XORG_PID}"
tail --pid=${NVIDIA_XORG_PID} -f /dev/null 2> /dev/null
fi
# Disable Nvidia GPU
disableGPU
if [[ $CUR_XORG_PID != "" ]]; then
# Switch back to the default VT
execute "chvt ${CUR_VT}"
# Remove TTY overrides
removeTTY
fi
# Exit the script
exit 0
trap SIGINT