1#! @perl@
2
3use strict;
4use Cwd 'abs_path';
5use File::Spec;
6use File::Path;
7use File::Basename;
8use File::Slurp;
9use File::stat;
10
11
12sub uniq {
13 my %seen;
14 my @res = ();
15 foreach my $s (@_) {
16 if (!defined $seen{$s}) {
17 $seen{$s} = 1;
18 push @res, $s;
19 }
20 }
21 return @res;
22}
23
24sub runCommand {
25 my ($cmd) = @_;
26 open FILE, "$cmd 2>&1 |" or die "Failed to execute: $cmd\n";
27 my @ret = <FILE>;
28 close FILE;
29 return ($?, @ret);
30}
31
32# Process the command line.
33my $outDir = "/etc/nixos";
34my $rootDir = ""; # = /
35my $force = 0;
36my $noFilesystems = 0;
37my $showHardwareConfig = 0;
38
39for (my $n = 0; $n < scalar @ARGV; $n++) {
40 my $arg = $ARGV[$n];
41 if ($arg eq "--help") {
42 exec "man nixos-generate-config" or die;
43 }
44 elsif ($arg eq "--dir") {
45 $n++;
46 $outDir = $ARGV[$n];
47 die "$0: ‘--dir’ requires an argument\n" unless defined $outDir;
48 }
49 elsif ($arg eq "--root") {
50 $n++;
51 $rootDir = $ARGV[$n];
52 die "$0: ‘--root’ requires an argument\n" unless defined $rootDir;
53 $rootDir =~ s/\/*$//; # remove trailing slashes
54 }
55 elsif ($arg eq "--force") {
56 $force = 1;
57 }
58 elsif ($arg eq "--no-filesystems") {
59 $noFilesystems = 1;
60 }
61 elsif ($arg eq "--show-hardware-config") {
62 $showHardwareConfig = 1;
63 }
64 else {
65 die "$0: unrecognized argument ‘$arg’\n";
66 }
67}
68
69
70my @attrs = ();
71my @kernelModules = ();
72my @initrdKernelModules = ();
73my @initrdAvailableKernelModules = ();
74my @modulePackages = ();
75my @imports;
76
77
78sub debug {
79 return unless defined $ENV{"DEBUG"};
80 print STDERR @_;
81}
82
83
84my $cpuinfo = read_file "/proc/cpuinfo";
85
86
87sub hasCPUFeature {
88 my $feature = shift;
89 return $cpuinfo =~ /^flags\s*:.* $feature( |$)/m;
90}
91
92
93# Detect the number of CPU cores.
94my $cpus = scalar (grep {/^processor\s*:/} (split '\n', $cpuinfo));
95
96
97# Virtualization support?
98push @kernelModules, "kvm-intel" if hasCPUFeature "vmx";
99push @kernelModules, "kvm-amd" if hasCPUFeature "svm";
100
101
102# Look at the PCI devices and add necessary modules. Note that most
103# modules are auto-detected so we don't need to list them here.
104# However, some are needed in the initrd to boot the system.
105
106my $videoDriver;
107
108sub pciCheck {
109 my $path = shift;
110 my $vendor = read_file "$path/vendor"; chomp $vendor;
111 my $device = read_file "$path/device"; chomp $device;
112 my $class = read_file "$path/class"; chomp $class;
113
114 my $module;
115 if (-e "$path/driver/module") {
116 $module = basename `readlink -f $path/driver/module`;
117 chomp $module;
118 }
119
120 debug "$path: $vendor $device $class";
121 debug " $module" if defined $module;
122 debug "\n";
123
124 if (defined $module) {
125 # See the bottom of http://pciids.sourceforge.net/pci.ids for
126 # device classes.
127 if (# Mass-storage controller. Definitely important.
128 $class =~ /^0x01/ ||
129
130 # Firewire controller. A disk might be attached.
131 $class =~ /^0x0c00/ ||
132
133 # USB controller. Needed if we want to use the
134 # keyboard when things go wrong in the initrd.
135 $class =~ /^0x0c03/
136 )
137 {
138 push @initrdAvailableKernelModules, $module;
139 }
140 }
141
142 # broadcom STA driver (wl.ko)
143 # list taken from http://www.broadcom.com/docs/linux_sta/README.txt
144 if ($vendor eq "0x14e4" &&
145 ($device eq "0x4311" || $device eq "0x4312" || $device eq "0x4313" ||
146 $device eq "0x4315" || $device eq "0x4327" || $device eq "0x4328" ||
147 $device eq "0x4329" || $device eq "0x432a" || $device eq "0x432b" ||
148 $device eq "0x432c" || $device eq "0x432d" || $device eq "0x4353" ||
149 $device eq "0x4357" || $device eq "0x4358" || $device eq "0x4359" ||
150 $device eq "0x4331" || $device eq "0x43a0" || $device eq "0x43b1"
151 ) )
152 {
153 push @modulePackages, "config.boot.kernelPackages.broadcom_sta";
154 push @kernelModules, "wl";
155 }
156
157 # broadcom FullMac driver
158 # list taken from
159 # https://wireless.wiki.kernel.org/en/users/Drivers/brcm80211#brcmfmac
160 if ($vendor eq "0x14e4" &&
161 ($device eq "0x43a3" || $device eq "0x43df" || $device eq "0x43ec" ||
162 $device eq "0x43d3" || $device eq "0x43d9" || $device eq "0x43e9" ||
163 $device eq "0x43ba" || $device eq "0x43bb" || $device eq "0x43bc" ||
164 $device eq "0xaa52" || $device eq "0x43ca" || $device eq "0x43cb" ||
165 $device eq "0x43cc" || $device eq "0x43c3" || $device eq "0x43c4" ||
166 $device eq "0x43c5"
167 ) )
168 {
169 # we need e.g. brcmfmac43602-pcie.bin
170 push @imports, "<nixpkgs/nixos/modules/hardware/network/broadcom-43xx.nix>";
171 }
172
173 # Can't rely on $module here, since the module may not be loaded
174 # due to missing firmware. Ideally we would check modules.pcimap
175 # here.
176 push @attrs, "networking.enableIntel2200BGFirmware = true;" if
177 $vendor eq "0x8086" &&
178 ($device eq "0x1043" || $device eq "0x104f" || $device eq "0x4220" ||
179 $device eq "0x4221" || $device eq "0x4223" || $device eq "0x4224");
180
181 push @attrs, "networking.enableIntel3945ABGFirmware = true;" if
182 $vendor eq "0x8086" &&
183 ($device eq "0x4229" || $device eq "0x4230" ||
184 $device eq "0x4222" || $device eq "0x4227");
185
186 # Assume that all NVIDIA cards are supported by the NVIDIA driver.
187 # There may be exceptions (e.g. old cards).
188 # FIXME: do we want to enable an unfree driver here?
189 #$videoDriver = "nvidia" if $vendor eq "0x10de" && $class =~ /^0x03/;
190}
191
192foreach my $path (glob "/sys/bus/pci/devices/*") {
193 pciCheck $path;
194}
195
196push @attrs, "services.xserver.videoDrivers = [ \"$videoDriver\" ];" if $videoDriver;
197
198
199# Idem for USB devices.
200
201sub usbCheck {
202 my $path = shift;
203 my $class = read_file "$path/bInterfaceClass"; chomp $class;
204 my $subclass = read_file "$path/bInterfaceSubClass"; chomp $subclass;
205 my $protocol = read_file "$path/bInterfaceProtocol"; chomp $protocol;
206
207 my $module;
208 if (-e "$path/driver/module") {
209 $module = basename `readlink -f $path/driver/module`;
210 chomp $module;
211 }
212
213 debug "$path: $class $subclass $protocol";
214 debug " $module" if defined $module;
215 debug "\n";
216
217 if (defined $module) {
218 if (# Mass-storage controller. Definitely important.
219 $class eq "08" ||
220
221 # Keyboard. Needed if we want to use the
222 # keyboard when things go wrong in the initrd.
223 ($class eq "03" && $protocol eq "01")
224 )
225 {
226 push @initrdAvailableKernelModules, $module;
227 }
228 }
229}
230
231foreach my $path (glob "/sys/bus/usb/devices/*") {
232 if (-e "$path/bInterfaceClass") {
233 usbCheck $path;
234 }
235}
236
237
238# Add the modules for all block and MMC devices.
239foreach my $path (glob "/sys/class/{block,mmc_host}/*") {
240 my $module;
241 if (-e "$path/device/driver/module") {
242 $module = basename `readlink -f $path/device/driver/module`;
243 chomp $module;
244 push @initrdAvailableKernelModules, $module;
245 }
246}
247
248
249my $virt = `systemd-detect-virt`;
250chomp $virt;
251
252
253# Check if we're a VirtualBox guest. If so, enable the guest
254# additions.
255if ($virt eq "oracle") {
256 push @attrs, "virtualisation.virtualbox.guest.enable = true;"
257}
258
259
260# Likewise for QEMU.
261if ($virt eq "qemu" || $virt eq "kvm" || $virt eq "bochs") {
262 push @imports, "<nixpkgs/nixos/modules/profiles/qemu-guest.nix>";
263}
264
265
266# Pull in NixOS configuration for containers.
267if ($virt eq "systemd-nspawn") {
268 push @attrs, "boot.isContainer = true;";
269}
270
271
272# Provide firmware for devices that are not detected by this script,
273# unless we're in a VM/container.
274push @imports, "<nixpkgs/nixos/modules/installer/scan/not-detected.nix>"
275 if $virt eq "none";
276
277
278# For a device name like /dev/sda1, find a more stable path like
279# /dev/disk/by-uuid/X or /dev/disk/by-label/Y.
280sub findStableDevPath {
281 my ($dev) = @_;
282 return $dev if substr($dev, 0, 1) ne "/";
283 return $dev unless -e $dev;
284
285 my $st = stat($dev) or return $dev;
286
287 foreach my $dev2 (glob("/dev/disk/by-uuid/*"), glob("/dev/mapper/*"), glob("/dev/disk/by-label/*")) {
288 my $st2 = stat($dev2) or next;
289 return $dev2 if $st->rdev == $st2->rdev;
290 }
291
292 return $dev;
293}
294
295
296# Generate the swapDevices option from the currently activated swap
297# devices.
298my @swaps = read_file("/proc/swaps");
299shift @swaps;
300my @swapDevices;
301foreach my $swap (@swaps) {
302 $swap =~ /^(\S+)\s/;
303 next unless -e $1;
304 my $dev = findStableDevPath $1;
305 push @swapDevices, "{ device = \"$dev\"; }";
306}
307
308
309# Generate the fileSystems option from the currently mounted
310# filesystems.
311sub in {
312 my ($d1, $d2) = @_;
313 return $d1 eq $d2 || substr($d1, 0, length($d2) + 1) eq "$d2/";
314}
315
316my $fileSystems;
317my %fsByDev;
318foreach my $fs (read_file("/proc/self/mountinfo")) {
319 chomp $fs;
320 my @fields = split / /, $fs;
321 my $mountPoint = $fields[4];
322 next unless -d $mountPoint;
323 my @mountOptions = split /,/, $fields[5];
324
325 next if !in($mountPoint, $rootDir);
326 $mountPoint = substr($mountPoint, length($rootDir)); # strip the root directory (e.g. /mnt)
327 $mountPoint = "/" if $mountPoint eq "";
328
329 # Skip special filesystems.
330 next if in($mountPoint, "/proc") || in($mountPoint, "/dev") || in($mountPoint, "/sys") || in($mountPoint, "/run") || $mountPoint eq "/var/lib/nfs/rpc_pipefs";
331 next if $mountPoint eq "/var/setuid-wrappers";
332
333 # Skip the optional fields.
334 my $n = 6; $n++ while $fields[$n] ne "-"; $n++;
335 my $fsType = $fields[$n];
336 my $device = $fields[$n + 1];
337 my @superOptions = split /,/, $fields[$n + 2];
338
339 # Skip the read-only bind-mount on /nix/store.
340 next if $mountPoint eq "/nix/store" && (grep { $_ eq "rw" } @superOptions) && (grep { $_ eq "ro" } @mountOptions);
341
342 # Maybe this is a bind-mount of a filesystem we saw earlier?
343 if (defined $fsByDev{$fields[2]}) {
344 # Make sure this isn't a btrfs subvolume.
345 my $msg = `btrfs subvol show $rootDir$mountPoint`;
346 if ($? != 0 || $msg =~ /ERROR:/s) {
347 my $path = $fields[3]; $path = "" if $path eq "/";
348 my $base = $fsByDev{$fields[2]};
349 $base = "" if $base eq "/";
350 $fileSystems .= <<EOF;
351 fileSystems.\"$mountPoint\" =
352 { device = \"$base$path\";
353 fsType = \"none\";
354 options = \[ \"bind\" \];
355 };
356
357EOF
358 next;
359 }
360 }
361 $fsByDev{$fields[2]} = $mountPoint;
362
363 # We don't know how to handle FUSE filesystems.
364 if ($fsType eq "fuseblk" || $fsType eq "fuse") {
365 print STDERR "warning: don't know how to emit ‘fileSystem’ option for FUSE filesystem ‘$mountPoint’\n";
366 next;
367 }
368
369 # Is this a mount of a loopback device?
370 my @extraOptions;
371 if ($device =~ /\/dev\/loop(\d+)/) {
372 my $loopnr = $1;
373 my $backer = read_file "/sys/block/loop$loopnr/loop/backing_file";
374 if (defined $backer) {
375 chomp $backer;
376 $device = $backer;
377 push @extraOptions, "loop";
378 }
379 }
380
381 # Is this a btrfs filesystem?
382 if ($fsType eq "btrfs") {
383 my ($status, @id_info) = runCommand("btrfs subvol show $rootDir$mountPoint");
384 if ($status != 0 || join("", @id_info) =~ /ERROR:/) {
385 die "Failed to retrieve subvolume info for $mountPoint\n";
386 }
387 my @ids = join("", @id_info) =~ m/Subvolume ID:[ \t\n]*([^ \t\n]*)/;
388 if ($#ids > 0) {
389 die "Btrfs subvol name for $mountPoint listed multiple times in mount\n"
390 } elsif ($#ids == 0) {
391 my ($status, @path_info) = runCommand("btrfs subvol list $rootDir$mountPoint");
392 if ($status != 0) {
393 die "Failed to find $mountPoint subvolume id from btrfs\n";
394 }
395 my @paths = join("", @path_info) =~ m/ID $ids[0] [^\n]* path ([^\n]*)/;
396 if ($#paths > 0) {
397 die "Btrfs returned multiple paths for a single subvolume id, mountpoint $mountPoint\n";
398 } elsif ($#paths != 0) {
399 die "Btrfs did not return a path for the subvolume at $mountPoint\n";
400 }
401 push @extraOptions, "subvol=$paths[0]";
402 }
403 }
404
405 # Emit the filesystem.
406 $fileSystems .= <<EOF;
407 fileSystems.\"$mountPoint\" =
408 { device = \"${\(findStableDevPath $device)}\";
409 fsType = \"$fsType\";
410EOF
411
412 if (scalar @extraOptions > 0) {
413 $fileSystems .= <<EOF;
414 options = \[ ${\join " ", map { "\"" . $_ . "\"" } uniq(@extraOptions)} \];
415EOF
416 }
417
418 $fileSystems .= <<EOF;
419 };
420
421EOF
422
423 # If this filesystem is on a LUKS device, then add a
424 # boot.initrd.luks.devices entry.
425 if (-e $device) {
426 my $deviceName = basename(abs_path($device));
427 if (-e "/sys/class/block/$deviceName"
428 && read_file("/sys/class/block/$deviceName/dm/uuid", err_mode => 'quiet') =~ /^CRYPT-LUKS/)
429 {
430 my @slaves = glob("/sys/class/block/$deviceName/slaves/*");
431 if (scalar @slaves == 1) {
432 my $slave = "/dev/" . basename($slaves[0]);
433 if (-e $slave) {
434 my $dmName = read_file("/sys/class/block/$deviceName/dm/name");
435 chomp $dmName;
436 $fileSystems .= " boot.initrd.luks.devices.\"$dmName\".device = \"${\(findStableDevPath $slave)}\";\n\n";
437 }
438 }
439 }
440 }
441}
442
443
444# Generate the hardware configuration file.
445
446sub toNixStringList {
447 my $res = "";
448 foreach my $s (@_) {
449 $res .= " \"$s\"";
450 }
451 return $res;
452}
453sub toNixList {
454 my $res = "";
455 foreach my $s (@_) {
456 $res .= " $s";
457 }
458 return $res;
459}
460
461sub multiLineList {
462 my $indent = shift;
463 return " [ ]" if !@_;
464 my $res = "\n${indent}[ ";
465 my $first = 1;
466 foreach my $s (@_) {
467 $res .= "$indent " if !$first;
468 $first = 0;
469 $res .= "$s\n";
470 }
471 $res .= "$indent]";
472 return $res;
473}
474
475my $initrdAvailableKernelModules = toNixStringList(uniq @initrdAvailableKernelModules);
476my $kernelModules = toNixStringList(uniq @kernelModules);
477my $modulePackages = toNixList(uniq @modulePackages);
478
479my $fsAndSwap = "";
480if (!$noFilesystems) {
481 $fsAndSwap = "\n$fileSystems ";
482 $fsAndSwap .= "swapDevices =" . multiLineList(" ", @swapDevices) . ";\n";
483}
484
485my $hwConfig = <<EOF;
486# Do not modify this file! It was generated by ‘nixos-generate-config’
487# and may be overwritten by future invocations. Please make changes
488# to /etc/nixos/configuration.nix instead.
489{ config, lib, pkgs, ... }:
490
491{
492 imports =${\multiLineList(" ", @imports)};
493
494 boot.initrd.availableKernelModules = [$initrdAvailableKernelModules ];
495 boot.kernelModules = [$kernelModules ];
496 boot.extraModulePackages = [$modulePackages ];
497$fsAndSwap
498 nix.maxJobs = lib.mkDefault $cpus;
499${\join "", (map { " $_\n" } (uniq @attrs))}}
500EOF
501
502
503if ($showHardwareConfig) {
504 print STDOUT $hwConfig;
505} else {
506 $outDir = "$rootDir$outDir";
507
508 my $fn = "$outDir/hardware-configuration.nix";
509 print STDERR "writing $fn...\n";
510 mkpath($outDir, 0, 0755);
511 write_file($fn, $hwConfig);
512
513 # Generate a basic configuration.nix, unless one already exists.
514 $fn = "$outDir/configuration.nix";
515 if ($force || ! -e $fn) {
516 print STDERR "writing $fn...\n";
517
518 my $bootLoaderConfig = "";
519 if (-e "/sys/firmware/efi/efivars") {
520 $bootLoaderConfig = <<EOF;
521 # Use the systemd-boot EFI boot loader.
522 boot.loader.systemd-boot.enable = true;
523 boot.loader.efi.canTouchEfiVariables = true;
524EOF
525 } elsif ($virt ne "systemd-nspawn") {
526 $bootLoaderConfig = <<EOF;
527 # Use the GRUB 2 boot loader.
528 boot.loader.grub.enable = true;
529 boot.loader.grub.version = 2;
530 # Define on which hard drive you want to install Grub.
531 # boot.loader.grub.device = "/dev/sda";
532EOF
533 }
534
535 write_file($fn, <<EOF);
536# Edit this configuration file to define what should be installed on
537# your system. Help is available in the configuration.nix(5) man page
538# and in the NixOS manual (accessible by running ‘nixos-help’).
539
540{ config, pkgs, ... }:
541
542{
543 imports =
544 [ # Include the results of the hardware scan.
545 ./hardware-configuration.nix
546 ];
547
548$bootLoaderConfig
549 # networking.hostName = "nixos"; # Define your hostname.
550 # networking.wireless.enable = true; # Enables wireless support via wpa_supplicant.
551
552 # Select internationalisation properties.
553 # i18n = {
554 # consoleFont = "Lat2-Terminus16";
555 # consoleKeyMap = "us";
556 # defaultLocale = "en_US.UTF-8";
557 # };
558
559 # Set your time zone.
560 # time.timeZone = "Europe/Amsterdam";
561
562 # List packages installed in system profile. To search by name, run:
563 # \$ nix-env -qaP | grep wget
564 # environment.systemPackages = with pkgs; [
565 # wget
566 # ];
567
568 # List services that you want to enable:
569
570 # Enable the OpenSSH daemon.
571 # services.openssh.enable = true;
572
573 # Enable CUPS to print documents.
574 # services.printing.enable = true;
575
576 # Enable the X11 windowing system.
577 # services.xserver.enable = true;
578 # services.xserver.layout = "us";
579 # services.xserver.xkbOptions = "eurosign:e";
580
581 # Enable the KDE Desktop Environment.
582 # services.xserver.displayManager.kdm.enable = true;
583 # services.xserver.desktopManager.kde4.enable = true;
584
585 # Define a user account. Don't forget to set a password with ‘passwd’.
586 # users.extraUsers.guest = {
587 # isNormalUser = true;
588 # uid = 1000;
589 # };
590
591 # The NixOS release to be compatible with for stateful data such as databases.
592 system.stateVersion = "${\(qw(@nixosRelease@))}";
593
594}
595EOF
596 } else {
597 print STDERR "warning: not overwriting existing $fn\n";
598 }
599}
600
601# workaround for a bug in substituteAll