git.iko.soy/typeable/nixpkgs
on master help sign in
Merge pull request #85895 from nh2/extra-grub-install-flags

grub: Add `boot.loader.grub.extraGrubInstallArgs` option

commitd676d5d11988e5c40c15ac92cc6631de7cc63795 authorNiklas Hambüchen <mail@nh2.me> dateMon 6 Jul 2020, 22:08 (6 years ago) parentd4d9d9ca90ae33
2 files changed+92−28
nixos/modules/system/boot/loader/grub/grub.nix+29−1 nixos/modules/system/boot/loader/grub/install-grub.pl+63−27
nixos/modules/system/boot/loader/grub/grub.nix+29−1
@@ -61,6 +61,7 @@ let
6161 inherit (efi) canTouchEfiVariables;
6262 inherit (cfg)
6363 version extraConfig extraPerEntryConfig extraEntries forceInstall useOSProber
64+ extraGrubInstallArgs
6465 extraEntriesBeforeNixOS extraPrepareConfig configurationLimit copyKernels
6566 default fsIdentifier efiSupport efiInstallAsRemovable gfxmodeEfi gfxmodeBios gfxpayloadEfi gfxpayloadBios;
6667 path = with pkgs; makeBinPath (
@@ -298,6 +299,33 @@ in
298299 '';
299300 };
300301
302+ extraGrubInstallArgs = mkOption {
303+ default = [ ];
304+ example = [ "--modules=nativedisk ahci pata part_gpt part_msdos diskfilter mdraid1x lvm ext2" ];
305+ type = types.listOf types.str;
306+ description = ''
307+ Additional arguments passed to <literal>grub-install</literal>.
308+
309+ A use case for this is to build specific GRUB2 modules
310+ directly into the GRUB2 kernel image, so that they are available
311+ and activated even in the <literal>grub rescue</literal> shell.
312+
313+ They are also necessary when the BIOS/UEFI is bugged and cannot
314+ correctly read large disks (e.g. above 2 TB), so GRUB2's own
315+ <literal>nativedisk</literal> and related modules can be used
316+ to use its own disk drivers. The example shows one such case.
317+ This is also useful for booting from USB.
318+ See the
319+ <link xlink:href="http://git.savannah.gnu.org/cgit/grub.git/tree/grub-core/commands/nativedisk.c?h=grub-2.04#n326">
320+ GRUB source code
321+ </link>
322+ for which disk modules are available.
323+
324+ The list elements are passed directly as <literal>argv</literal>
325+ arguments to the <literal>grub-install</literal> program, in order.
326+ '';
327+ };
328+
301329 extraPerEntryConfig = mkOption {
302330 default = "";
303331 example = "root (hd0)";
@@ -669,7 +697,7 @@ in
669697 in pkgs.writeScript "install-grub.sh" (''
670698 #!${pkgs.runtimeShell}
671699 set -e
672− export PERL5LIB=${with pkgs.perlPackages; makePerlPath [ FileSlurp XMLLibXML XMLSAX XMLSAXBase ListCompare ]}
700+ export PERL5LIB=${with pkgs.perlPackages; makePerlPath [ FileSlurp XMLLibXML XMLSAX XMLSAXBase ListCompare JSON ]}
673701 ${optionalString cfg.enableCryptodisk "export GRUB_ENABLE_CRYPTODISK=y"}
674702 '' + flip concatMapStrings cfg.mirroredBoots (args: ''
675703 ${pkgs.perl}/bin/perl ${install-grub-pl} ${grubConfig args} $@
nixos/modules/system/boot/loader/grub/install-grub.pl+63−27
@@ -8,6 +8,7 @@ use File::stat;
88use File::Copy;
99use File::Slurp;
1010use File::Temp;
11+use JSON;
1112require List::Compare;
1213use POSIX;
1314use Cwd;
@@ -20,6 +21,16 @@ my $dom = XML::LibXML->load_xml(location => $ARGV[0]);
2021
2122sub get { my ($name) = @_; return $dom->findvalue("/expr/attrs/attr[\@name = '$name']/*/\@value"); }
2223
24+sub getList {
25+ my ($name) = @_;
26+ my @list = ();
27+ foreach my $entry ($dom->findnodes("/expr/attrs/attr[\@name = '$name']/list/string/\@value")) {
28+ $entry = $entry->findvalue(".") or die;
29+ push(@list, $entry);
30+ }
31+ return @list;
32+}
33+
2334sub readFile {
2435 my ($fn) = @_; local $/ = undef;
2536 open FILE, "<$fn" or return undef; my $s = <FILE>; close FILE;
@@ -241,7 +252,7 @@ if ($grubVersion == 1) {
241252 timeout $timeout
242253 ";
243254 if ($splashImage) {
244− copy $splashImage, "$bootPath/background.xpm.gz" or die "cannot copy $splashImage to $bootPath\n";
255+ copy $splashImage, "$bootPath/background.xpm.gz" or die "cannot copy $splashImage to $bootPath: $!\n";
245256 $conf .= "splashimage " . ($grubBoot->path eq "/" ? "" : $grubBoot->path) . "/background.xpm.gz\n";
246257 }
247258}
@@ -319,7 +330,7 @@ else {
319330 ";
320331
321332 if ($font) {
322− copy $font, "$bootPath/converted-font.pf2" or die "cannot copy $font to $bootPath\n";
333+ copy $font, "$bootPath/converted-font.pf2" or die "cannot copy $font to $bootPath: $!\n";
323334 $conf .= "
324335 insmod font
325336 if loadfont " . ($grubBoot->path eq "/" ? "" : $grubBoot->path) . "/converted-font.pf2; then
@@ -347,7 +358,7 @@ else {
347358 background_color '$backgroundColor'
348359 ";
349360 }
350− copy $splashImage, "$bootPath/background$suffix" or die "cannot copy $splashImage to $bootPath\n";
361+ copy $splashImage, "$bootPath/background$suffix" or die "cannot copy $splashImage to $bootPath: $!\n";
351362 $conf .= "
352363 insmod " . substr($suffix, 1) . "
353364 if background_image --mode '$splashMode' " . ($grubBoot->path eq "/" ? "" : $grubBoot->path) . "/background$suffix; then
@@ -381,8 +392,8 @@ sub copyToKernelsDir {
381392 # kernels or initrd if this script is ever interrupted.
382393 if (! -e $dst) {
383394 my $tmp = "$dst.tmp";
384− copy $path, $tmp or die "cannot copy $path to $tmp\n";
385− rename $tmp, $dst or die "cannot rename $tmp to $dst\n";
395+ copy $path, $tmp or die "cannot copy $path to $tmp: $!\n";
396+ rename $tmp, $dst or die "cannot rename $tmp to $dst: $!\n";
386397 }
387398 $copied{$dst} = 1;
388399 return ($grubBoot->path eq "/" ? "" : $grubBoot->path) . "/kernels/$name";
@@ -405,10 +416,10 @@ sub addEntry {
405416 # Make sure initrd is not world readable (won't work if /boot is FAT)
406417 umask 0137;
407418 my $initrdSecretsPathTemp = File::Temp::mktemp("$initrdSecretsPath.XXXXXXXX");
408− system("$path/append-initrd-secrets", $initrdSecretsPathTemp) == 0 or die "failed to create initrd secrets\n";
419+ system("$path/append-initrd-secrets", $initrdSecretsPathTemp) == 0 or die "failed to create initrd secrets: $!\n";
409420 # Check whether any secrets were actually added
410421 if (-e $initrdSecretsPathTemp && ! -z _) {
411− rename $initrdSecretsPathTemp, $initrdSecretsPath or die "failed to move initrd secrets into place\n";
422+ rename $initrdSecretsPathTemp, $initrdSecretsPath or die "failed to move initrd secrets into place: $!\n";
412423 $copied{$initrdSecretsPath} = 1;
413424 $initrd .= " " . ($grubBoot->path eq "/" ? "" : $grubBoot->path) . "/kernels/$initrdName-secrets";
414425 } else {
@@ -575,7 +586,7 @@ if (get("useOSProber") eq "true") {
575586}
576587
577588# Atomically switch to the new config
578−rename $tmpFile, $confFile or die "cannot rename $tmpFile to $confFile\n";
589+rename $tmpFile, $confFile or die "cannot rename $tmpFile to $confFile: $!\n";
579590
580591
581592# Remove obsolete files from $bootPath/kernels.
@@ -596,9 +607,12 @@ struct(GrubState => {
596607 efi => '$',
597608 devices => '$',
598609 efiMountPoint => '$',
610+ extraGrubInstallArgs => '@',
599611});
612+# If you add something to the state file, only add it to the end
613+# because it is read line-by-line.
600614sub readGrubState {
601− my $defaultGrubState = GrubState->new(name => "", version => "", efi => "", devices => "", efiMountPoint => "" );
615+ my $defaultGrubState = GrubState->new(name => "", version => "", efi => "", devices => "", efiMountPoint => "", extraGrubInstallArgs => () );
602616 open FILE, "<$bootPath/grub/state" or return $defaultGrubState;
603617 local $/ = "\n";
604618 my $name = <FILE>;
@@ -611,24 +625,34 @@ sub readGrubState {
611625 chomp($devices);
612626 my $efiMountPoint = <FILE>;
613627 chomp($efiMountPoint);
628+ # Historically, arguments in the state file were one per each line, but that
629+ # gets really messy when newlines are involved, structured arguments
630+ # like lists are needed (they have to have a separator encoding), or even worse,
631+ # when we need to remove a setting in the future. Thus, the 6th line is a JSON
632+ # object that can store structured data, with named keys, and all new state
633+ # should go in there.
634+ my $jsonStateLine = <FILE>;
635+ # For historical reasons we do not check the values above for un-definedness
636+ # (that is, when the state file has too few lines and EOF is reached),
637+ # because the above come from the first version of this logic and are thus
638+ # guaranteed to be present.
639+ $jsonStateLine = defined $jsonStateLine ? $jsonStateLine : '{}'; # empty JSON object
640+ chomp($jsonStateLine);
641+ my %jsonState = %{decode_json($jsonStateLine)};
642+ my @extraGrubInstallArgs = @{$jsonState{'extraGrubInstallArgs'}};
614643 close FILE;
615− my $grubState = GrubState->new(name => $name, version => $version, efi => $efi, devices => $devices, efiMountPoint => $efiMountPoint );
644+ my $grubState = GrubState->new(name => $name, version => $version, efi => $efi, devices => $devices, efiMountPoint => $efiMountPoint, extraGrubInstallArgs => \@extraGrubInstallArgs );
616645 return $grubState
617646}
618647
619−sub getDeviceTargets {
620− my @devices = ();
621− foreach my $dev ($dom->findnodes('/expr/attrs/attr[@name = "devices"]/list/string/@value')) {
622− $dev = $dev->findvalue(".") or die;
623− push(@devices, $dev);
624− }
625− return @devices;
626−}
627−my @deviceTargets = getDeviceTargets();
648+my @deviceTargets = getList('devices');
628649my $prevGrubState = readGrubState();
629650my @prevDeviceTargets = split/,/, $prevGrubState->devices;
651+my @extraGrubInstallArgs = getList('extraGrubInstallArgs');
652+my @prevExtraGrubInstallArgs = $prevGrubState->extraGrubInstallArgs;
630653
631654my $devicesDiffer = scalar (List::Compare->new( '-u', '-a', \@deviceTargets, \@prevDeviceTargets)->get_symmetric_difference());
655+my $extraGrubInstallArgsDiffer = scalar (List::Compare->new( '-u', '-a', \@extraGrubInstallArgs, \@prevExtraGrubInstallArgs)->get_symmetric_difference());
632656my $nameDiffer = get("fullName") ne $prevGrubState->name;
633657my $versionDiffer = get("fullVersion") ne $prevGrubState->version;
634658my $efiDiffer = $efiTarget ne $prevGrubState->efi;
@@ -637,25 +661,25 @@ if (($ENV{'NIXOS_INSTALL_GRUB'} // "") eq "1") {
637661 warn "NIXOS_INSTALL_GRUB env var deprecated, use NIXOS_INSTALL_BOOTLOADER";
638662 $ENV{'NIXOS_INSTALL_BOOTLOADER'} = "1";
639663}
640−my $requireNewInstall = $devicesDiffer || $nameDiffer || $versionDiffer || $efiDiffer || $efiMountPointDiffer || (($ENV{'NIXOS_INSTALL_BOOTLOADER'} // "") eq "1");
664+my $requireNewInstall = $devicesDiffer || $extraGrubInstallArgsDiffer || $nameDiffer || $versionDiffer || $efiDiffer || $efiMountPointDiffer || (($ENV{'NIXOS_INSTALL_BOOTLOADER'} // "") eq "1");
641665
642666# install a symlink so that grub can detect the boot drive
643−my $tmpDir = File::Temp::tempdir(CLEANUP => 1) or die "Failed to create temporary space";
644−symlink "$bootPath", "$tmpDir/boot" or die "Failed to symlink $tmpDir/boot";
667+my $tmpDir = File::Temp::tempdir(CLEANUP => 1) or die "Failed to create temporary space: $!";
668+symlink "$bootPath", "$tmpDir/boot" or die "Failed to symlink $tmpDir/boot: $!";
645669
646670# install non-EFI GRUB
647671if (($requireNewInstall != 0) && ($efiTarget eq "no" || $efiTarget eq "both")) {
648672 foreach my $dev (@deviceTargets) {
649673 next if $dev eq "nodev";
650674 print STDERR "installing the GRUB $grubVersion boot loader on $dev...\n";
651− my @command = ("$grub/sbin/grub-install", "--recheck", "--root-directory=$tmpDir", Cwd::abs_path($dev));
675+ my @command = ("$grub/sbin/grub-install", "--recheck", "--root-directory=$tmpDir", Cwd::abs_path($dev), @extraGrubInstallArgs);
652676 if ($forceInstall eq "true") {
653677 push @command, "--force";
654678 }
655679 if ($grubTarget ne "") {
656680 push @command, "--target=$grubTarget";
657681 }
658− (system @command) == 0 or die "$0: installation of GRUB on $dev failed\n";
682+ (system @command) == 0 or die "$0: installation of GRUB on $dev failed: $!\n";
659683 }
660684}
661685
@@ -663,7 +687,7 @@ if (($requireNewInstall != 0) && ($efiTarget eq "no" || $efiTarget eq "both")) {
663687# install EFI GRUB
664688if (($requireNewInstall != 0) && ($efiTarget eq "only" || $efiTarget eq "both")) {
665689 print STDERR "installing the GRUB $grubVersion EFI boot loader into $efiSysMountPoint...\n";
666− my @command = ("$grubEfi/sbin/grub-install", "--recheck", "--target=$grubTargetEfi", "--boot-directory=$bootPath", "--efi-directory=$efiSysMountPoint");
690+ my @command = ("$grubEfi/sbin/grub-install", "--recheck", "--target=$grubTargetEfi", "--boot-directory=$bootPath", "--efi-directory=$efiSysMountPoint", @extraGrubInstallArgs);
667691 if ($forceInstall eq "true") {
668692 push @command, "--force";
669693 }
@@ -674,17 +698,29 @@ if (($requireNewInstall != 0) && ($efiTarget eq "only" || $efiTarget eq "both"))
674698 push @command, "--removable" if $efiInstallAsRemovable eq "true";
675699 }
676700
677− (system @command) == 0 or die "$0: installation of GRUB EFI into $efiSysMountPoint failed\n";
701+ (system @command) == 0 or die "$0: installation of GRUB EFI into $efiSysMountPoint failed: $!\n";
678702}
679703
680704
681705# update GRUB state file
682706if ($requireNewInstall != 0) {
683− open FILE, ">$bootPath/grub/state" or die "cannot create $bootPath/grub/state: $!\n";
707+ # Temp file for atomic rename.
708+ my $stateFile = "$bootPath/grub/state";
709+ my $stateFileTmp = $stateFile . ".tmp";
710+
711+ open FILE, ">$stateFileTmp" or die "cannot create $stateFileTmp: $!\n";
684712 print FILE get("fullName"), "\n" or die;
685713 print FILE get("fullVersion"), "\n" or die;
686714 print FILE $efiTarget, "\n" or die;
687715 print FILE join( ",", @deviceTargets ), "\n" or die;
688716 print FILE $efiSysMountPoint, "\n" or die;
717+ my %jsonState = (
718+ extraGrubInstallArgs => \@extraGrubInstallArgs
719+ );
720+ my $jsonStateLine = encode_json(\%jsonState);
721+ print FILE $jsonStateLine, "\n" or die;
689722 close FILE or die;
723+
724+ # Atomically switch to the new state file
725+ rename $stateFileTmp, $stateFile or die "cannot rename $stateFileTmp to $stateFile: $!\n";
690726}