Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
2282 lines (2025 loc) · 97.8 KB
/
Copy pathmain.py
File metadata and controls
2282 lines (2025 loc) · 97.8 KB
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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import json
import os
import re
import struct
import shutil
import stat
import subprocess
import time
import urllib.request
import urllib.error
from pathlib import Path
import vdf as _vdf
# Decky enregistre son PROPRE module `updater` dans sys.modules → un simple
# `import updater` renvoie celui de Decky (sans is_autoupdate_enabled) au lieu du
# nôtre, cassant silencieusement l'auto-update après une MAJ Decky. On charge notre
# fichier explicitement par chemin, sous un nom unique, pour éviter la collision.
import importlib.util as _ilu
_uspec = _ilu.spec_from_file_location(
"bc250_updater", os.path.join(os.path.dirname(os.path.abspath(__file__)), "updater.py")
)
updater = _ilu.module_from_spec(_uspec)
_uspec.loader.exec_module(updater)
# Même chargement explicite pour bios_uma (règle générale : tout module maison à
# la racine du plugin est importé par chemin pour éviter toute collision Decky).
# Best-effort : si le fichier manque (zip incomplet), le plugin doit survivre —
# l'UI affichera simplement « UMA non supporté » au lieu de tuer tout le plugin.
try:
_bspec = _ilu.spec_from_file_location(
"bc250_bios_uma", os.path.join(os.path.dirname(os.path.abspath(__file__)), "bios_uma.py")
)
bios_uma = _ilu.module_from_spec(_bspec)
_bspec.loader.exec_module(bios_uma)
except Exception:
bios_uma = None
GAMES_DB_URL = "https://raw.githubusercontent.com/Necrosiak/bc250-toolkit-decky/main/games_db.json"
LOCAL_DB_PATH = Path(os.path.dirname(__file__)) / "games_db.json"
CACHE_DB_PATH = Path("/tmp/bc250_games_db_cache.json")
TWEAKS_APPLY = "/opt/bc250-tweaks/apply.sh"
TWEAKS_UPDATE = "/opt/bc250-tweaks/update.sh"
# ── User home resolution ───────────────────────────────────────────────────────
# Le plugin tourne en root (HOME=/root). SUDO_HOME contient le vrai home user.
def _get_user_home() -> Path:
sudo_home = os.environ.get("SUDO_HOME")
if sudo_home and Path(sudo_home).is_dir():
return Path(sudo_home)
try:
import decky # injecté par DeckyLoader au runtime
h = getattr(decky, "DECKY_USER_HOME", None)
if h:
return Path(h)
except ImportError:
pass
try:
root_home = os.environ.get("HOME", "/root")
loader_json = Path(root_home) / "homebrew/settings/loader.json"
data = json.loads(loader_json.read_text())
h = data.get("user_info.user_home")
if h:
return Path(h)
except Exception:
pass
import pwd
for entry in pwd.getpwall():
if 1000 <= entry.pw_uid < 65000:
return Path(entry.pw_dir)
return Path.home()
_USER_HOME = _get_user_home()
BC250_DATA_DIR = _USER_HOME / ".local/share/bc250-toolkit"
PENDING_LO_FILE = BC250_DATA_DIR / "pending_launch_options.json"
PRE_STEAM_SCRIPT = BC250_DATA_DIR / "bc250-apply-vdf.py"
STEAM_DROPIN_DIR = _USER_HOME / ".config/systemd/user/app-steam@autostart.service.d"
STEAM_DROPIN = STEAM_DROPIN_DIR / "bc250-vdf-apply.conf"
# ── Per-game radv/drirc options ───────────────────────────────────────────────
# Certaines configs ont besoin d'options mesa radv par-jeu (ex: désactiver le
# unified heap pour les jeux DX12/VKD3D, cf Code Vein 2). On possède entièrement
# ~/.drirc : on le régénère depuis un état JSON. Match sur le pApplicationName
# que DXVK/vkd3d passent à radv (= nom de l'exe, ex "Jeu-Win64-Shipping.exe").
DRIRC_PATH = _USER_HOME / ".drirc"
RADV_STATE_FILE = BC250_DATA_DIR / "radv_configs.json"
# ── Réglages du plugin (auto-apply + variante choisie par jeu) ─────────────────
# { "auto_apply": bool, "variants": { "<appid>": <index|null> } }
TOOLKIT_SETTINGS_FILE = BC250_DATA_DIR / "toolkit_settings.json"
# ── CU management ─────────────────────────────────────────────────────────────
# Hardware : 5 WGPs × 2 CU × 4 rangées (SE0.SH0, SE0.SH1, SE1.SH0, SE1.SH1) = 40 CU max
# Stock BC-250 : WGP0-2 actifs (mask 0x07) = 6 CU/rangée × 4 = 24 CU
CU_PROFILES: dict = {
"stock": {"label": "24 CU (stock)", "cu": 24, "masks": [0x07, 0x07, 0x07, 0x07]},
"32cu": {"label": "32 CU", "cu": 32, "masks": [0x0f, 0x0f, 0x0f, 0x0f]},
"36cu": {"label": "36 CU", "cu": 36, "masks": [0x1f, 0x1f, 0x0f, 0x0f]},
"40cu": {"label": "40 CU (full)", "cu": 40, "masks": [0x1f, 0x1f, 0x1f, 0x1f]},
}
CU_ASIC = "cyan_skillfish.gfx1013"
CU_ASIC_INSTANCE = "cyan_skillfish@1" # instance 1 sur kernel 6.17+ (debugfs /dri/1/)
CU_ASIC_INSTANCE_CANDIDATES = (CU_ASIC_INSTANCE, "cyan_skillfish@0", None)
CU_REG_CC = "mmCC_GC_SHADER_ARRAY_CONFIG"
CU_REG_SPI = "mmSPI_PG_ENABLE_STATIC_WGP_MASK"
CU_REG_RLC = "mmRLC_PG_ALWAYS_ON_WGP_MASK"
CU_SE_SH = [(0, 0), (0, 1), (1, 0), (1, 1)]
CU_RESTORE_SCRIPT = Path("/usr/local/bin/bc250-cu-restore")
CU_SERVICE_NAME = "bc250-cu-profile"
CU_SERVICE_PATH = Path(f"/etc/systemd/system/{CU_SERVICE_NAME}.service")
CU_MANAGER = Path("/usr/local/bin/bc250-cu-live-manager")
CU_LIVE_CACHE = Path("/tmp/bc250-cu-live.json") # état courant, effacé au reboot
# Déverrouillage CPU au boot (8C/16T). Les scripts sont RECOPIÉS hors du dossier
# du plugin : celui-ci est réécrit à chaque mise à jour Decky, et un service du
# système ne doit pas dépendre d'un chemin que Decky peut effacer.
CORE_BOOT_SCRIPT = Path("/usr/local/bin/bc250-core-boot")
CORE_SERVICE_NAME = "bc250-core-unlock"
CORE_SERVICE_PATH = Path(f"/etc/systemd/system/{CORE_SERVICE_NAME}.service")
CORE_LIB_DIR = Path("/usr/local/lib/bc250-core-unlock")
CORE_STATE_DIR = Path("/var/lib/bc250-core-unlock")
_cu_reading = False # verrou simple pour éviter des lectures umr simultanées
_cu_last_attempt = 0.0 # timestamp du dernier lancement bg read (rate-limit 30s)
def _find_umr() -> str | None:
for p in ("/usr/bin/umr", "/usr/local/bin/umr"):
if os.path.isfile(p):
return p
return None
def _cmd_exists(cmd: str) -> bool:
return shutil.which(cmd) is not None
def _sudo_cmd(cmd: list) -> list:
if os.geteuid() == 0:
return cmd
return ["sudo", "-n"] + cmd
def _is_ostree() -> bool:
"""Système immuable basé sur ostree (Bazzite/SteamOS/Silverblue) : rpm-ostree
ET dnf y coexistent, mais seul rpm-ostree installe (le / est en lecture seule)."""
return _cmd_exists("rpm-ostree") and (
os.path.isdir("/run/ostree") or os.path.isdir("/ostree"))
def _umr_install_hint() -> str:
if _is_ostree():
return "rpm-ostree install --apply-live umr"
if _cmd_exists("pacman"):
return "sudo pacman -S umr"
if _cmd_exists("paru"):
return "paru -S umr"
if _cmd_exists("yay"):
return "yay -S umr"
if _cmd_exists("shelly"):
return "shelly aur install umr"
if _cmd_exists("dnf"):
return "sudo dnf install umr"
if _cmd_exists("apt-get"):
return "sudo apt install umr"
return "installer le paquet umr"
def _umr_cmd_prefix(umr: str) -> list:
# Repli si le flag root du plugin.json n'a pas été honoré : umr exige root pour debugfs
if os.geteuid() != 0:
return ["sudo", "-n", umr]
return [umr]
def _umr_cmd_base(umr: str, instance: str | None) -> list:
cmd = _umr_cmd_prefix(umr)
if instance:
cmd += ["-g", instance]
return cmd
def _umr_write(umr: str, reg: str, value: int,
se: int | None = None, sh: int | None = None) -> bool:
# -g sélectionne l'instance GPU (instance 1 sur kernel 6.17+)
# -b DOIT précéder -w : umr traite les flags séquentiellement
for instance in CU_ASIC_INSTANCE_CANDIDATES:
cmd = _umr_cmd_base(umr, instance)
if se is not None and sh is not None:
cmd += ["-b", str(se), str(sh), "0xffffffff"]
cmd += ["-w", f"{CU_ASIC}.{reg}", hex(value)]
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=15)
if result.returncode == 0:
return True
print(f"[BC250 CU] umr write failed instance={instance}: rc={result.returncode} stderr={result.stderr[:200]!r}")
except Exception as e:
print(f"[BC250 CU] umr write exception instance={instance}: {e}")
return False
def _umr_read(umr: str, reg: str,
se: int | None = None, sh: int | None = None) -> int | None:
# -g sélectionne l'instance GPU (instance 1 sur kernel 6.17+)
# -b DOIT précéder -r
for instance in CU_ASIC_INSTANCE_CANDIDATES:
cmd = _umr_cmd_base(umr, instance)
if se is not None and sh is not None:
cmd += ["-b", str(se), str(sh), "0xffffffff"]
cmd += ["-r", f"{CU_ASIC}.{reg}"]
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=15)
m = re.search(r'0x[0-9a-fA-F]+', result.stdout)
if m:
return int(m.group(), 16)
# Certaines versions umr écrivent sur stderr
m = re.search(r'0x[0-9a-fA-F]+', result.stderr)
if m:
return int(m.group(), 16)
print(f"[BC250 CU] umr read failed instance={instance}: rc={result.returncode} stderr={result.stderr[:200]!r} stdout={result.stdout[:100]!r}")
except Exception as e:
print(f"[BC250 CU] umr read exception instance={instance}: {e}")
return None
def _masks_cu_count(masks: list) -> int:
return sum(bin(m & 0x1f).count("1") * 2 for m in masks)
def _read_all_cu_masks_seq(umr: str) -> list:
"""Lecture séquentielle des 4 masques SPI (utilisé dans un thread executor)."""
results = []
for se, sh in CU_SE_SH:
v = _umr_read(umr, CU_REG_SPI, se, sh)
print(f"[BC250 CU] SE{se} SH{sh} => {v}")
results.append(v)
return results
async def _bg_cu_read(umr: str):
"""Tâche asyncio de fond : lit les registres CU et écrit le cache."""
global _cu_reading
try:
print("[BC250 CU] lecture umr en fond...")
loop = asyncio.get_running_loop()
masks_raw = await loop.run_in_executor(None, _read_all_cu_masks_seq, umr)
print(f"[BC250 CU] masks_raw={masks_raw}")
# Si tous les reads ont échoué (None ou 0), ne pas écrire un faux cache à 0
if not any(v is not None and v != 0 for v in masks_raw):
print("[BC250 CU] bg_cu_read: tous les reads ont échoué — cache non écrit")
return
masks = [v or 0 for v in masks_raw]
cu_count = _masks_cu_count(masks)
current_profile = _identify_profile(masks)
print(f"[BC250 CU] cache mis à jour: cu_count={cu_count}, profile={current_profile}")
CU_LIVE_CACHE.write_text(json.dumps({"cu_count": cu_count, "current_profile": current_profile}))
except Exception as e:
print(f"[BC250 CU] erreur bg_cu_read: {e}")
finally:
_cu_reading = False
def _identify_profile(masks: list) -> str | None:
clean = [m & 0x1f for m in masks]
for name, p in CU_PROFILES.items():
if clean == p["masks"]:
return name
return None
# ── Script d'application des launch options VDF (ExecStartPre Steam) ──────────
_APPLY_VDF_SCRIPT = r'''#!/usr/bin/env python3
"""Applique les launch options en attente dans localconfig.vdf.
Lancé via ExecStartPre avant que Steam démarre."""
import json
import re
import sys
from pathlib import Path
try:
import vdf as _vdf
except ImportError:
sys.exit(0)
PENDING_FILE = Path.home() / ".local/share/bc250-toolkit/pending_launch_options.json"
def _pick_active_steam_user(users, home):
"""SteamID64 du compte ACTIF parmi ceux de loginusers.vdf, ou None.
⚠️ Steam a CHANGÉ ce fichier (constaté le 25/08/2026) : "MostRecent" a
disparu, remplacé par "AutoLogin" + "Timestamp", et registry.vdf n'expose
plus "ActiveUser" numérique mais "AutoLoginUser" (le NOM du compte). Le code
d'origine retombait alors sur « le PREMIER utilisateur du fichier » — juste
par hasard sur une machine mono-compte, faux dès qu'il y en a plusieurs.
On garde "MostRecent" en premier : un Steam plus ancien ne change pas.
"""
autologin_name = ""
try:
reg = (home / ".steam/registry.vdf").read_text(errors="ignore")
m = re.search(r'"AutoLoginUser"\s+"([^"]+)"', reg)
if m:
autologin_name = m.group(1)
except Exception:
pass
by_name = by_flag = by_time = None
newest = -1
for uid, info in (users or {}).items():
if not isinstance(info, dict):
continue
if autologin_name and info.get("AccountName") == autologin_name:
by_name = by_name or uid
if by_flag is None and (info.get("MostRecent") == "1"
or info.get("AutoLogin") == "1"):
by_flag = uid
try:
ts = int(info.get("Timestamp", 0))
except (TypeError, ValueError):
ts = 0
if ts > newest:
newest, by_time = ts, uid
return by_name or by_flag or by_time
def find_userid():
try:
data = _vdf.load(open(Path.home() / ".steam/steam/config/loginusers.vdf"))
uid = _pick_active_steam_user(data.get("users", {}), Path.home())
if uid:
return str(int(uid) & 0xFFFFFFFF)
except Exception:
pass
try:
dirs = [d for d in (Path.home() / ".steam/steam/userdata").iterdir()
if d.is_dir() and d.name.isdigit() and d.name != "0"]
if dirs:
return dirs[0].name
except Exception:
pass
return None
def main():
if not PENDING_FILE.exists():
return
try:
pending = json.loads(PENDING_FILE.read_text())
except Exception:
PENDING_FILE.unlink(missing_ok=True)
return
if not pending:
PENDING_FILE.unlink(missing_ok=True)
return
userid = find_userid()
if not userid:
return
lc = Path.home() / ".steam/steam/userdata" / userid / "config/localconfig.vdf"
if not lc.exists():
return
try:
data = _vdf.load(open(lc))
apps = (
data
.setdefault("UserLocalConfigStore", {})
.setdefault("Software", {})
.setdefault("Valve", {})
.setdefault("Steam", {})
.setdefault("apps", {})
)
for app_id, opts in list(pending.items()):
if app_id not in apps or not isinstance(apps[app_id], dict):
apps[app_id] = {}
apps[app_id]["LaunchOptions"] = opts
del pending[app_id]
with open(lc, "w") as f:
_vdf.dump(data, f)
if pending:
PENDING_FILE.write_text(json.dumps(pending))
else:
PENDING_FILE.unlink(missing_ok=True)
except Exception:
pass
if __name__ == "__main__":
main()
'''
def _pick_active_steam_user(users, home):
"""SteamID64 du compte ACTIF parmi ceux de loginusers.vdf, ou None.
⚠️ Steam a CHANGÉ ce fichier (constaté le 25/08/2026) : "MostRecent" a
disparu, remplacé par "AutoLogin" + "Timestamp", et registry.vdf n'expose
plus "ActiveUser" numérique mais "AutoLoginUser" (le NOM du compte). Le code
d'origine retombait alors sur « le PREMIER utilisateur du fichier » — juste
par hasard sur une machine mono-compte, faux dès qu'il y en a plusieurs.
On garde "MostRecent" en premier : un Steam plus ancien ne change pas.
"""
autologin_name = ""
try:
reg = (home / ".steam/registry.vdf").read_text(errors="ignore")
m = re.search(r'"AutoLoginUser"\s+"([^"]+)"', reg)
if m:
autologin_name = m.group(1)
except Exception:
pass
by_name = by_flag = by_time = None
newest = -1
for uid, info in (users or {}).items():
if not isinstance(info, dict):
continue
if autologin_name and info.get("AccountName") == autologin_name:
by_name = by_name or uid
if by_flag is None and (info.get("MostRecent") == "1"
or info.get("AutoLogin") == "1"):
by_flag = uid
try:
ts = int(info.get("Timestamp", 0))
except (TypeError, ValueError):
ts = 0
if ts > newest:
newest, by_time = ts, uid
return by_name or by_flag or by_time
# How many release checks, and how long between two. The check runs a few
# seconds after the backend, which is often BEFORE the network is reachable:
# the logs on the test machine show three boots out of four dying on
# "Temporary failure in name resolution". Nothing retried, so the plugin stayed
# on its version until the next boot — which failed the same way.
UPDATE_CHECK_TRIES = 10
UPDATE_CHECK_DELAY_S = 30
async def _recheck(updater):
"""`updater.check()`, retried for as long as it is the network that is missing."""
from asyncio import sleep as _sleep
info = await updater.check()
for _ in range(UPDATE_CHECK_TRIES - 1):
if not info.get("error"):
break
await _sleep(UPDATE_CHECK_DELAY_S)
info = await updater.check()
return info
# ── Pont vers BC250 Control Center (movacx/bc250-control-center, MIT) ─────────
# Quand le Control Center est installé, le Toolkit ne garde AUCUN état matériel
# à lui : il passe par le helper root du Control Center, exactement comme le
# plugin Decky livré avec ce dernier. Les deux interfaces lisent et écrivent
# donc les mêmes fichiers (/etc/bc250-cu-live-manager.conf, /etc/bc250-smu-oc.conf,
# TOML du governor…) : ce qui change au bureau apparaît en gamemode et
# inversement, sans synchro à maintenir. Sans Control Center, le Toolkit
# retombe sur son propre code.
CC_HELPER = Path("/usr/libexec/bc250-control-center/bc250-quick-access-helper")
CC_PROTOCOL = 13 # celui du helper de la v1.19.0 ; renvoyé par `status`
CC_GPU_PROFILES = (
"recovery", "balanced", "gaming", "benchmark",
"oberon-1500", "oberon-1850", "oberon-2000",
)
CC_FAN_CHANNELS = (2, 3, 4, 5)
CC_CPU_FREQUENCIES = tuple(range(3500, 4201, 50))
CC_CPU_VIDS = tuple(range(950, 1326, 5))
CC_CPU_SCALES = tuple(range(-50, 1))
# Le statut complet coûte umr + hwmon + systemctl : l'onglet CU et l'onglet
# Système le sondent toutes les 5-10 s, on partage donc une lecture récente.
CC_STATUS_MAX_AGE = 4.0
# Installation depuis l'onglet : version FIGÉE sur celle dont on parle le
# protocole (CC_PROTOCOL) et empreinte vérifiée avant de passer le paquet à
# rpm-ostree en root. Changer les trois ensemble, jamais « latest ».
CC_RPM_VERSION = "1.19.0"
CC_RPM_URL = ("https://github.com/movacx/bc250-control-center/releases/download/"
"v1.19.0/bc250-control-center-1.19.0-1.fc44.noarch.rpm")
CC_RPM_SHA256 = "914d1879f6ab6c1cd7767ce52d142f5876a1864ec878018df1a36471c618309b"
RPM_OSTREE = Path("/usr/bin/rpm-ostree")
_cc_helper_lock = asyncio.Lock() # sérialise TOUT appel au helper, lectures comprises
_cc_operation_lock = asyncio.Lock() # refuse une 2e écriture au lieu de la mettre en file
_cc_status_cache: dict = {"at": 0.0, "value": None}
def _cc_helper_trusted() -> bool:
"""N'exécute jamais un helper remplacé : fichier régulier root, non inscriptible."""
try:
st = CC_HELPER.lstat()
except OSError:
return False
return (
stat.S_ISREG(st.st_mode)
and st.st_uid == 0
and not st.st_mode & 0o022
and bool(st.st_mode & stat.S_IXUSR)
)
def _cc_run(*args: str, timeout: int = 190) -> dict:
if not _cc_helper_trusted():
return {"ok": False, "error": "BC250 Control Center helper is missing or not protected."}
try:
r = subprocess.run(
[str(CC_HELPER), *args], text=True, capture_output=True,
timeout=timeout, check=False,
env={"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LANG": "C.UTF-8", "LC_ALL": "C.UTF-8"},
)
except subprocess.TimeoutExpired:
return {"ok": False, "error": "BC250 Control Center operation timed out."}
except OSError as e:
return {"ok": False, "error": str(e)}
out = (r.stdout or "").strip()
if r.returncode:
return {"ok": False, "error": (r.stderr or out or "helper failed").strip()[-2000:]}
try:
payload = json.loads(out)
except json.JSONDecodeError:
payload = {"ok": True, "message": out[-2000:]}
return payload if isinstance(payload, dict) else {"ok": True, "value": payload}
def _cc_status_blocking() -> dict:
r = _cc_run("status", timeout=20)
if r.get("ok") is False:
return r
if type(r.get("protocol")) is not int or r["protocol"] != CC_PROTOCOL:
return {
"ok": False,
"protocol_mismatch": True,
"error": f"helper protocol {r.get('protocol')!r}, expected {CC_PROTOCOL}",
}
return r
def _cc_gpu_profiles(lo: int, hi: int, governor: str) -> list:
"""Mêmes bornes que bc250cc/domain/gpu/profiles.py du Control Center."""
if governor == "oberon":
cands = (
("oberon-1500", "Balanced", 1000, 1500),
("oberon-1850", "Gaming", 1000, 1850),
("oberon-2000", "Benchmark", 1000, 2000),
)
else:
cands = (
("balanced", "Balanced", max(500, lo), 1500),
("gaming", "Gaming", max(1000, lo), 1850),
("benchmark", "Benchmark", max(1000, lo), 2000),
)
out = []
for key, name, pmin, pmax in cands:
a, b = max(lo, pmin), min(hi, pmax)
if a <= b:
out.append({"key": key, "name": name, "min": a, "max": b})
return out
def _cc_masks_error(masks) -> str | None:
if not isinstance(masks, (list, tuple)) or len(masks) != 4:
return "A CU table must contain exactly four row masks."
if any(type(m) is not int or not 0 <= m <= 0x1F for m in masks):
return "Every CU row mask must be an integer from 0 through 31."
if sum(bin(m).count("1") * 2 for m in masks) not in range(24, 41, 2):
return "A CU table must route 24 through 40 CUs."
return None
def _cc_bounded(value, allowed) -> int | None:
"""Entier exact et dans la liste autorisée — jamais d'argument libre vers root."""
if isinstance(value, bool) or type(value) not in (int, str):
return None
try:
n = int(value)
except (TypeError, ValueError, OverflowError):
return None
return n if str(n) == str(value) and n in allowed else None
def _cc_live_gpu_clock(status: dict) -> dict:
"""Le helper du CC lit `pp_dpm_sclk`, qui reste bloqué sur 14-100 MHz même
avec fix-freq du governor ; `hwmon/freq1_input` (ce que lit MangoHud) donne
la vraie horloge. Copie : le cache du statut garde la valeur du helper."""
try:
for hwmon in Path("/sys/class/hwmon").iterdir():
if (hwmon / "name").read_text().strip() != "amdgpu":
continue
mhz = round(int((hwmon / "freq1_input").read_text()) / 1_000_000)
if mhz > 0:
return {**status, "gpu_core_mhz": mhz}
except (OSError, ValueError):
pass
return status
# phase : idle → running → staged | failed. `staged` survit au rechargement du
# plugin grâce à la lecture de rpm-ostree, faite une seule fois (le démon est
# réveillé à chaque `status`, pas question de le sonder toutes les 5 s).
_cc_install_state: dict = {"phase": "idle", "error": None, "checked": False, "task": None}
def _cc_install_supported() -> bool:
return Path("/run/ostree-booted").exists() and RPM_OSTREE.is_file()
def _cc_install_staged_blocking() -> bool:
"""Le prochain déploiement (index 0), pas encore booté, embarque déjà le paquet."""
try:
r = subprocess.run([str(RPM_OSTREE), "status", "--json"], text=True,
capture_output=True, timeout=30, check=False)
deps = json.loads(r.stdout or "{}").get("deployments") or []
except (OSError, subprocess.TimeoutExpired, json.JSONDecodeError):
return False
if not deps or deps[0].get("booted"):
return False
return any(str(p).startswith("bc250-control-center-")
for p in deps[0].get("requested-local-packages") or [])
def _cc_install_blocking() -> None:
import hashlib
import tempfile
work = Path(tempfile.mkdtemp(prefix="bc250-toolkit-cc-", dir="/var/tmp"))
rpm = work / CC_RPM_URL.rsplit("/", 1)[1]
try:
digest = hashlib.sha256()
req = urllib.request.Request(CC_RPM_URL, headers={"User-Agent": "BC250-Toolkit-Decky"})
with urllib.request.urlopen(req, timeout=60, context=updater._ssl_context()) as resp, \
open(rpm, "wb") as f:
while chunk := resp.read(1 << 16):
digest.update(chunk)
f.write(chunk)
if digest.hexdigest() != CC_RPM_SHA256:
raise RuntimeError("checksum mismatch, package rejected")
r = subprocess.run(
[str(RPM_OSTREE), "install", "--idempotent", str(rpm)],
text=True, capture_output=True, timeout=1800, check=False,
env={"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LANG": "C.UTF-8", "LC_ALL": "C.UTF-8"},
)
if r.returncode:
raise RuntimeError((r.stderr or r.stdout or "rpm-ostree failed").strip()[-600:])
_cc_install_state.update(phase="staged", error=None, checked=True)
except Exception as e:
_cc_install_state.update(phase="failed", error=str(e)[-600:] or type(e).__name__)
finally:
shutil.rmtree(work, ignore_errors=True)
def _retire_toolkit_cu_service() -> bool:
"""Le Control Center restaure les CU au boot : notre service ferait un 2e
passage, peut-être avec une AUTRE table. On le désactive sans supprimer ses
fichiers, pour que ce soit réversible."""
unit = f"{CU_SERVICE_NAME}.service"
try:
r = subprocess.run(["systemctl", "is-enabled", unit], capture_output=True, text=True, timeout=5)
if r.stdout.strip() != "enabled":
return False
d = subprocess.run(_sudo_cmd(["systemctl", "disable", unit]), capture_output=True, timeout=15)
return d.returncode == 0
except Exception:
return False
class Plugin:
async def _main(self):
self._games_db: dict = {}
if _cc_helper_trusted():
asyncio.create_task(self._cc_retire_duplicate_cu_boot())
# Purge le cache CU si cu_count=0 (lecture umr ratée lors d'une session précédente)
if CU_LIVE_CACHE.exists():
try:
cached = json.loads(CU_LIVE_CACHE.read_text())
if not cached.get("cu_count"):
CU_LIVE_CACHE.unlink()
print("[BC250 CU] cache invalide (cu_count=0) purgé au démarrage")
except Exception:
CU_LIVE_CACHE.unlink(missing_ok=True)
self._install_pre_steam_hook()
await asyncio.get_event_loop().run_in_executor(None, self._refresh_core_boot_script)
await self._load_db()
asyncio.create_task(self._autoupdate_check())
async def _autoupdate_check(self):
# Silent release check at boot: if enabled and a newer release exists,
# download + unpack over the plugin dir and restart plugin_loader.
try:
if not updater.is_autoupdate_enabled():
return
info = await _recheck(updater)
if not info.get("update_available"):
return
print(f"[BC250 updater] {info['latest']} available (have {info['current']}); applying")
# apply() returns a dict: {"ok": False, "error": …} is always
# truthy, so a failure used to pass for a success and the loader
# was restarted anyway — on a loop, since the installed version
# had not changed. Read the field, not the dict.
# We apply it OURSELVES. This plugin declares `flags: ["root"]`, so
# its backend runs as root and can always write — which is exactly
# why it never hit the Permission denied the others did.
#
# ⛔ Do NOT delegate to `utilities/install_plugin`: that is the Decky
# Store route, and it reports the install to plugins.deckbrew.xyz.
# Our plugins are not there → 404 → the rest never runs: files
# written, plugin never reloaded, and a frozen modal across the
# Steam UI. Measured here on 2026-09-13.
res = await updater.apply(info["url"])
if res.get("ok"):
if updater.restart_loader():
return
# Being root is NOT enough on its own: until 2026-09-22 the
# restart died on the loader's bundled libraries before polkit
# was ever reached, for every plugin alike (see restart_loader).
# Keep the honest branch — a silent no-reload is exactly what
# kept machines on stale code (Steamcord #52).
print(f"[BC250 updater] {info['latest']} written to disk; loader "
"restart refused — active at next Steam start")
self._pending_update = {"version": info["latest"], "reload": True}
return
print(f"[BC250 updater] update aborted: {res.get('error', 'unknown reason')}")
self._pending_update = {"version": info["latest"],
"error": res.get("error", "")}
except Exception as e:
print(f"[BC250 updater] auto-check error: {e}")
# Failure notice parked by _autoupdate_check, taken by the frontend that notifies.
_pending_update = None
async def take_pending_update(self):
"""Hand the failed-update notice to the frontend, once.
Cleared on read: the notification must fire ONCE, not on every QAM open.
"""
pending, self._pending_update = self._pending_update, None
return pending or {}
async def check_update(self):
return await updater.check()
async def get_version(self):
return updater.get_current_version()
async def apply_update(self, url):
res = await updater.apply(url)
# The frontend reloads this plugin through the loader; restarting
# plugin_loader from here would bounce every plugin instead.
return res
async def get_autoupdate(self):
return updater.is_autoupdate_enabled()
async def set_autoupdate(self, enabled):
return updater.set_autoupdate_enabled(enabled)
# ── Réglages plugin : auto-apply + variante par jeu ────────────────────────
def _read_settings(self) -> dict:
try:
if TOOLKIT_SETTINGS_FILE.exists():
return json.loads(TOOLKIT_SETTINGS_FILE.read_text())
except Exception:
pass
return {}
def _write_settings(self, data: dict) -> None:
BC250_DATA_DIR.mkdir(parents=True, exist_ok=True)
_chown_user(BC250_DATA_DIR)
TOOLKIT_SETTINGS_FILE.write_text(json.dumps(data, indent=2))
_chown_user(TOOLKIT_SETTINGS_FILE)
async def get_auto_apply(self) -> bool:
return bool(self._read_settings().get("auto_apply", False))
async def set_auto_apply(self, enabled: bool) -> bool:
s = self._read_settings()
s["auto_apply"] = bool(enabled)
self._write_settings(s)
return bool(enabled)
async def get_game_variants(self) -> dict:
"""Map { "<appid>": variant_index } des variantes choisies par l'utilisateur."""
return self._read_settings().get("variants", {})
async def set_game_variant(self, app_id: int, variant_index: int | None) -> dict:
s = self._read_settings()
variants = s.get("variants", {})
if variant_index is None:
variants.pop(str(app_id), None)
else:
variants[str(app_id)] = variant_index
s["variants"] = variants
self._write_settings(s)
return {"ok": True}
def _install_pre_steam_hook(self):
"""Installe ExecStartPre dans le service Steam pour appliquer les VDF pending."""
try:
BC250_DATA_DIR.mkdir(parents=True, exist_ok=True)
_chown_user(BC250_DATA_DIR)
PRE_STEAM_SCRIPT.write_text(_APPLY_VDF_SCRIPT)
PRE_STEAM_SCRIPT.chmod(0o755)
_chown_user(PRE_STEAM_SCRIPT)
STEAM_DROPIN_DIR.mkdir(parents=True, exist_ok=True)
_chown_user(STEAM_DROPIN_DIR)
STEAM_DROPIN.write_text(f"[Service]\nExecStartPre=-{PRE_STEAM_SCRIPT}\n")
_chown_user(STEAM_DROPIN)
# daemon-reload dans le contexte user (le plugin tourne en root).
# _user_uid() et PAS le propriétaire de BC250_DATA_DIR : ce dossier
# est créé par nous, donc par root — on aurait pointé
# XDG_RUNTIME_DIR sur /run/user/0 et parlé au mauvais systemd.
user_uid = _user_uid()
if user_uid:
subprocess.run(
["systemctl", "--user", "daemon-reload"],
capture_output=True, timeout=5,
env=_clean_env(HOME=str(_USER_HOME),
XDG_RUNTIME_DIR=f"/run/user/{user_uid}"),
)
except Exception:
pass
async def _unload(self):
pass
# ── Games database ────────────────────────────────────────────────────────
async def _load_db(self):
try:
req = urllib.request.Request(
GAMES_DB_URL,
headers={"User-Agent": "BC250-Toolkit-Decky/0.1"},
)
with urllib.request.urlopen(req, timeout=5) as resp:
data = json.loads(resp.read().decode())
self._games_db = data
CACHE_DB_PATH.write_text(json.dumps(data))
return
except Exception:
pass
if CACHE_DB_PATH.exists():
try:
self._games_db = json.loads(CACHE_DB_PATH.read_text())
return
except Exception:
pass
if LOCAL_DB_PATH.exists():
try:
self._games_db = json.loads(LOCAL_DB_PATH.read_text())
except Exception:
self._games_db = {}
async def get_games_db(self) -> dict:
return self._games_db
async def refresh_games_db(self) -> dict:
await self._load_db()
return self._games_db
async def get_game_settings(self, app_id: str) -> dict | None:
return self._games_db.get(str(app_id))
# ── System status ─────────────────────────────────────────────────────────
# Instantané fdinfo précédent, pour calculer la charge GPU par DIFFÉRENCE.
# L'interface interroge périodiquement : chaque appel mesure donc la charge
# écoulée depuis le précédent, sans thread ni échantillonnage bloquant.
_gpu_prev: tuple | None = None
async def get_system_status(self) -> dict:
status: dict = {}
# ── GPU : mesures RÉELLES (cf. _read_gpu_metrics / _drm_gfx_snapshot) ──
try:
metrics = _read_gpu_metrics()
status.update({k: v for k, v in metrics.items()
if k != "gfx_activity_supported"})
# Dit à l'interface que le MATÉRIEL ne mesure pas la charge : c'est
# cette sentinelle que MangoHud affiche en 655 %.
status["gpu_activity_from_firmware"] = metrics.get(
"gfx_activity_supported", False)
except Exception:
pass
try:
now = time.monotonic_ns()
snap = _drm_gfx_snapshot()
prev = self._gpu_prev
self._gpu_prev = (snap, now)
if prev:
old_snap, old_ns = prev
elapsed = now - old_ns
# Sous ~200 ms la division amplifie le bruit d'échantillonnage ;
# au-delà de 30 s l'instantané précédent ne décrit plus rien.
if 200_000_000 <= elapsed <= 30_000_000_000:
busy = sum(max(0, ns - old_snap.get(cid, ns))
for cid, ns in snap.items())
status["gpu_load_pct"] = round(
min(100.0, busy / elapsed * 100), 1)
except Exception:
pass
try:
for hwmon in Path("/sys/class/hwmon").iterdir():
name_f = hwmon / "name"
if not name_f.exists():
continue
name = name_f.read_text().strip()
if name == "k10temp":
tctl = hwmon / "temp1_input"
if tctl.exists():
status["cpu_temp"] = round(int(tctl.read_text()) / 1000, 1)
elif name in ("amdgpu", "gpu_thermal"):
edge = hwmon / "temp1_input"
if edge.exists():
status["gpu_temp"] = round(int(edge.read_text()) / 1000, 1)
freq = hwmon / "freq1_input" # GPU shader clock (Hz)
if freq.exists():
try:
status["gpu_clock_mhz"] = round(
int(freq.read_text()) / 1_000_000)
except (OSError, ValueError):
pass
except Exception:
pass
# CPU clock — average of the per-core current MHz (cpufreq isn't always
# exposed on this APU, so read /proc/cpuinfo which always is).
try:
mhz = [float(l.split(":")[1]) for l in
Path("/proc/cpuinfo").read_text().splitlines()
if l.lower().startswith("cpu mhz")]
if mhz:
status["cpu_clock_mhz"] = round(sum(mhz) / len(mhz))
except Exception:
pass
# CPU topology — cores / threads. The BC-250 enumerates 6 of the 8 Zen 2
# cores on its Oberon die (6C/12T); boards running the community core
# unlock report 8C/16T, so surfacing both numbers makes the state
# obvious. /proc/cpuinfo only lists ONLINE CPUs, and its "physical id"
# + "core id" pair is what distinguishes a core from its SMT sibling.
try:
pairs, threads = set(), 0
phys = core = None
for line in Path("/proc/cpuinfo").read_text().splitlines() + [""]:
key, _, val = line.partition(":")
key, val = key.strip(), val.strip()
if key == "processor":
threads += 1
elif key == "physical id":
phys = val
elif key == "core id":
core = val
elif not key: # blank line = end of block
if core is not None:
pairs.add((phys, core))
phys = core = None
if threads:
status["cpu_threads"] = threads
if pairs:
status["cpu_cores"] = len(pairs)
except Exception:
pass
# Fan speed — the BC-250's fan shows up as a Super-I/O sensor (nct6686 on
# this board); most fanN_input headers read 0 (unused), so report the
# fastest spinning one as the active fan.
try:
rpms = []
for hwmon in Path("/sys/class/hwmon").iterdir():
for fan in sorted(hwmon.glob("fan*_input")):
try:
rpm = int(fan.read_text())
except (OSError, ValueError):
continue
if rpm > 0:
rpms.append(rpm)
if rpms:
status["fan_rpm"] = max(rpms)
except Exception:
pass
# RAM système = ce qui reste à l'OS après le carve-out UMA (MemTotal bouge
# avec le réglage UMA du BIOS). used = MemTotal - MemAvailable (vision htop).
try:
mem: dict = {}
for line in Path("/proc/meminfo").read_text().splitlines():
key, _, rest = line.partition(":")
if key in ("MemTotal", "MemAvailable"):
mem[key] = int(rest.strip().split()[0]) # kB
if "MemTotal" in mem:
status["mem_total_mb"] = mem["MemTotal"] // 1024
if "MemAvailable" in mem:
status["mem_used_mb"] = max(0, mem["MemTotal"] - mem["MemAvailable"]) // 1024
except Exception:
pass
try:
scx_state = Path("/sys/kernel/sched_ext/state").read_text().strip()
status["scx_state"] = scx_state