Установка freebsd рядом с windows

��� ��������� FreeBSD � Windows, � ������� BIOS ����������� ��������
� CD/DVD ��� USB ������.

� ������ UEFI BIOS, ��������� UEFI BIOS � ����� Legacy.

1.1 ��������� FreeBSD

��������� ��������� FreeBSD � CD/DVD ��� USB-Live, � �������
�� �������� �����:

�������� ����� Manual — ������ ��������.

�������� ��� ����, ���� ����� ����������� �� FreeBSD � Windows 7/8/10:

�������� ������� — «Create»:

�������� �������� ���������� ����:

�������� � ���� «MBR — DOS Partition»:

������� ������ ������ (��������� MBR) ��� FreeBSD:

  • Type: freebsd
  • Size: 8GB
  • Mountpoint:

��-�������, ������� ������� MBR ��� ������ (slices) � �������� FreeBSD, Mountpoint �� ��������.

� ����������, ������� ���������:

���, ada0 — ������� (������) ���� � ����������

s1 — ������ ������ (����� � �������� xBSD) ��� �������� MBR (������ �� 4’��)

ada0s1 — ������ �������� MBR ��� FreeBSD, �������� 8GB

������, ����� ��������� �������� ����� FreeBSD, ������ ������ ����
������� �� ada0s1

�����, «Create»:

�������� FreeBSD ����� ���� ���� �����:

  • Type: freebsd-ufs (�������� �������� �������)
  • Type: freebsd-swap (�������� ��������)

� ������� ������� ������ ���� �������� FS «/» — freebsd-ufs , �������� 8GB:

  • Type: freebsd-ufs
  • Size: 8192MB
  • Mountpoint: /

�� ����� ������� ��������� �������� ������.

�����: ���� �������� ��� ������ ufs-�������������� ��� �������� FS,

���� � ��� � FreeBSD ���� ��������, �������� Options:

�������� ����� SUJ:

����������� ��������� �����: OK

� ��� ��� ������������ �������� �������� �������: OK

��� ��� ����� ��������� ��������� �������� ������� ��� �����������
��������� �� ��� �� FreeBSD:

�����:
���� �� ������ ��������� ��������� �������� ������ FreeBSD � swap ��
���� ���������, ����������� ����������� ��������� ������� ��������:

  1. ������ �������� �������� FS: «/» — ada0s1a
  2. ����� �������� swapada0s1b
  3. ����� ������ ��������� ��������� FS

��������, �������� �����:

�������� swap:

����:

�������� �������� ������ FreeBSD ��������� -> Finish
�������� ��������� �� FreeBSD:

1.2 ��������� Windows

�������� ����� � ���� ��������, �� ������� ��� �� ������, ����������� OS FreeBSD:

  • — ���� 0, ������ 1 — 8GB ������� (FreeBSD)
  • — ��������� ����� �� ����� 0 — 42GB (������ ��� ��������� Windows)

�������� ��������� ����� �� ����� 0 � �������� �����, ���������� ��������� Windows �� ��������� �����

����� ��������� Windows, ���������, ��������� ���� ���������� — ��������
�� ���� ��������.

����������� � CD/DVD ��� USB-Live FreeBSD � ������� � SHELL, ���
��������� Boot Manager FreeBSD:

� ������ ������, ��������� ��������� �������:

— ���������� �������� ����� ada0

# gpart show ada0

— �������������, ����� ���������� BSD �������� ������ ada0s1

# gpart show ada0s1

— �������, ���������� �� Boot Manager FreeBSD

# boot0cfg -v ada0

— ������������� Boot Manager FreeBSD � ���������������:

# boot0cfg -B ada0
# reboot

�������� ��������� �������:

���:

  • — �������� F1 ��� �������� FreeBSD
  • — �������� F2 ��� �������� Windows

����������:
����� ������ �� ���� F3, ���������� ����� ��������������� boo0cfg ��� ����� ������ ���������.

HowTo: [LegacyBIOS/MBR]Install FreeBSD RootOnZFS in a FreeBSD Slice and Dual Boot Windows

Heads up:

  • Dual boot FreeBSD 13.0 RELEASE and Windows 10 was tested in a VirtualBox virtual Machine (VM).
  • Only works with legacy BIOS boot and MBR partition scheme.
  • UEFI boot and/or GPT partition scheme not tested.

2021-09-25 Jackie

Modified from an answer by Trond Endrestøl in the freebsd-questions mail list: Dualboot and ZFS, answer post 13

PURPOSE:

  1. Dual boot FreeBSD and Windows on a single hard disk;
  2. Legacy BIOS boot and MBR partition scheme;
  3. FreeBSD in a slice with a swap partition and a RootOnZFS filesystem.

Steps to go:

Download DISC or DVD iso file from freebsd.org, FreeBSD-13.0-RELEASE-amd64-disc1.iso for example. Burn it into CD/DVD/flash driver if you intend to install on real hardware. If you plan to try out with a VM, simply iso files are fine. If you’re sure Internet is accessible during install, bootonly.iso or memstick.img can also be used as installation media. Below I’ll cover only a VM case with DISC or DVD iso as installation media.

Create a new VM with one hard disk and our FreeBSD-13.0-RELEASE-amd64-disc1.iso file as CD. Here I create a new 24G hard disk for it. Start the machine and choose CD-rom as boot media. In VirtualBox, press F12 at boot and you’ll be able to choose which boot media to use. After that, FreeBSD will start to boot , choose Boot Multiuser Mode or just press Enter to continue. Choose Live CD mode when a window prompts asking to go Install, Shell or Live CD. At the login prompt, type root and Enter and we’re in as root user now.

This is optional but I’ll leave it here as a memo: I prefer to set up sshd service and connect to the machine over ssh so copy-paste commands are convenient.

# first start network service, interface name from output of ifconfig command
dhclient le0

# set up sshd in LiveCD mode requires to change `sshd` config file
# so we first have to mount /etc at /tmp/etc because the LiveCD mode was 
# mounted read-only and config files were thus read-only

mkdir /tmp/etc
mount_unionfs /tmp/etc /etc
echo "PermitRootLogin yes" >> /etc/ssh/sshd_config
service sshd onestart

# now set password for root so we can login from ssh connect
passwd root

Now regrardless of you’re in ssh session or still in VBox, follow the steps below.

1. Setup partitions

Since it’s a new VM with a newly created hard disk (We’ll assume it’s ada0, check with gpart list or camcontrol devlist), We’ll run

gpart destroy -F ada0
gpart create -s mbr ada0

first to create MBR partition scheme on the disk.

CAUTION: THIS ERASES ALL EXISTING DATA ON THE DISK!

change the command line prompt for better visual(optional)

set prompt="(%l)[%{\033[36m%}`whoami`@%{\033[1;30m%}%m:%{\033[0;32m%}%~%{\033[0m%}]%# "

At any time we can check disk partition layout gpart show -p ada0. For the purpose of installing FreeBSD in a MBR slice and testing dual boot Windows. We first create two NTFS partitions (slices).

gpart add -t ntfs -s 1G ada0
gpart add -t ntfs -s 2G ada0

If you’re to install Windows and dual boot FreeBSD. Now it’s the time to install Windows in ada0s1 or ada0s2. We’ll skip it here and pretend Windows is installed in one of the two partiotions and we’d like to keep them the way they’re now.

All the left space on the disk are allocated to a BSD slice:

gpart add -t freebsd ada0
gpart show ada0

In this single slice, we’ll create two partitions, one for swap and one for ZFS filesystem.
( assuming the partition (or slice) to install BSD is ada0s3 here)

gpart create -s BSD ada0s3
gpart show ada0
gpart show ada0s3
gpart add -t freebsd-zfs -s 20G ada0s3
gpart add -t freebsd-swap ada0s3

Remember now, ada0s3a for ZFS an ada0s3b for swap.

2. Create the ZFS filesystem

Then we create the ZFS filesystem in ada0s3a and mount it at /mnt. zroot is the name we use for the pool, which of course can be changed if you want to.

kldload zfs
sysctl vfs.zfs.min_auto_ashift=12

mount -t tmpfs tmpfs /mnt
zpool create -o altroot=/mnt zroot /dev/ada0s3a
zfs set compress=zstd zroot         
zfs create -o mountpoint=none zroot/ROOT
zfs create -o mountpoint=/ -o canmount=noauto zroot/ROOT/default
mount -t zfs zroot/ROOT/default /mnt
zfs create -o mountpoint=/tmp -o exec=on -o setuid=off zroot/tmp
zfs create -o canmount=off -o mountpoint=/usr zroot/usr
zfs create zroot/usr/home
#zfs create -o exec=off -o setuid=off zroot/usr/src
#zfs create zroot/usr/obj
zfs create -o mountpoint=/usr/ports -o setuid=off zroot/usr/ports
#zfs create -o exec=off -o setuid=off zroot/usr/ports/distfiles
#zfs create -o exec=off -o setuid=off zroot/usr/ports/packages
#zfs create -o canmount=off -o mountpoint=/var zroot/var
#zfs create -o exec=off -o setuid=off zroot/var/audit
#zfs create -o exec=off -o setuid=off zroot/var/crash
#zfs create -o exec=off -o setuid=off zroot/var/log
#zfs create -o atime=on -o exec=off -o setuid=off zroot/var/mail
# zfs create -o exec=on -o setuid=off zroot/var/tmp         
ln -s /usr/home /mnt/home
#chmod 1777 /mnt/var/tmp
chmod 1777 /mnt/tmp
zpool set bootfs=zroot/ROOT/default zroot

(There are lines commented out because creation of ZFS filesystems can be highly customized and this is just a simple example here I provide.)

3. Install FreeBSD system

It’s recommeded to run df -ah first to double check the our newly created ZFS filesystems are correctly mounted now.
If everything is OK, we install FreeBSD system in the zroot pool. Here I’ll only choose base and kernel to be installed. As we’re using DISC/DVD, they’re all in /usr/freebsd-dist.

cd /mnt
tar -xzf /usr/freebsd-dist/base.txz
tar -xzf /usr/freebsd-dist/kernel.txz

That’s it. The fresh new system is now installed. But it’s not yet bootable because boot loader is not set.

To set up the bootloader, it’s safer if the disk and partitions are not currently in use or mounted. But before umount the disk, there are a few neccessary tweaks we might as well add now. The most important thing here is to make sure ZFS support during boot.

echo 'zfs_load="YES"' >> boot/loader.conf
echo 'zfs_enable="YES"' > etc/rc.conf 
echo '/dev/ada0s3b none swap sw 0 0' >> etc/fstab
# not really vital but a good choice
echo 'autoboot_delay="5"' >> boot/loader.conf

4. Get boot loader in place

Now it’s time to umount and install boot loader. Ensure first cd / to be out of the filesystem to be umounted, otherwise umount will fail.

cd /
zfs unmount -a
zpool set bootfs=zroot/ROOT/default zroot
zpool export zroot

# here run `mount` and `df -ah` again to make sure ZFS filesystems are not mounted anymore
mount
df -ah

# if we don't see any zpool/zfs filesystems mounted, go ahead and install boot
gpart bootcode -b /boot/boot0 /dev/ada0
dd if=/boot/zfsboot of=/tmp/zfsboot1 count=1
gpart bootcode -b /tmp/zfsboot1 /dev/ada0s3

# `/dev/ada0s3a` is the 1st partition in BSD slice, regardless of
# whether it is swap or zfs part.
dd if=/boot/zfsboot of=/dev/ada0s3a skip=1 seek=1024

5. Finish

All done now. We can safely exit and reboot into the newly installed system.

Happy BSDing!

FreeBSD_ZFS.png

6. Read More

  • JJBA blog post: FreeBSD Root on ZFS — Partitions
  • FreeBSDWiki: Installing FreeBSD Root on ZFS using FreeBSD-ZFS partition in a FreeBSD MBR Slice
  • Disk Setup On FreeBSD
  • Installing_FreeBSD_Root_on_ZFS_using_FreeBSD-ZFS_partition_in_a_FreeBSD_MBR_Slice.txt
  • Migrate FreeBSD root on UFS to ZFS
  • FreeBSD Handbook
  • FreeBSD manual: zfsboot
  • FreeBSD manual: gpart

Important notes:
1) This tutorial assumes you have the OS you want to dual-boot with already installed on your drive, and that you already have freed up some disk space. Essentially, you will be installing FreeBSD with root-on-ZFS on the remaining free space of the disk, instead of using the entire drive as it’s done by default by FreeBSD’s installer.
2) This method only works for GPT disk layouts using UEFI mode. Legacy BIOS and MBR disks are not supported. As always, make sure to disable Secure Boot and Fast Boot.
3) Here, we use ada0 (disk 1) for everything, and we assume your disk already has an EFI partition, located in partition 1 (ada0p1). Change it according to your setup, if needed. Run gpart show to be sure.
4) We will create our ZFS Pool with «Stripe» as the Virtual Device type (vdev).
5) After completing installation, to be able to choose what OS to boot you’ll need to either install rEFInd boot manager, or use GRUB (assuming the other OS is a Linux distro). I personally recommend rEFInd, but I won’t detail how to install it here. Neither will I explain how to alter the GRUB config. Just gonna show you how the respective entries should look like in each case.
6) Finally, I’m not responsible for any problem or data loss you may experience. This tutorial is not an unsafe procedure if you understand what you’re doing (especially in regards to selecting the correct disk where you want to install). Anyway, do it at your own risk!

Well, let’s start:
First of all, boot your FreeBSD install USB stick. Proceed installing as usual, until you reach the «Partitioning» stage. Here, choose the «Shell» option, so you can create your swap and ZFS partitions by hand:

# Load the ZFS kernel module:
kldload zfs

# Force 4K sectors:
sysctl vfs.zfs.min_auto_ashift=12

# Create a swap partition (in this case, of 4 GB size):
gpart add -a 4k -l swap0 -s 4G -t freebsd-swap ada0

# Create a ZFS partition to fill the remaining free space:
gpart add -a 4k -l zfs0 -t freebsd-zfs ada0

# Mount tmpfs in /mnt, where the installer will install the operating system to:
mount -t tmpfs tmpfs /mnt

# Create your zroot pool:
zpool create -f -o altroot=/mnt -O compress=lz4 -O atime=off -m none zroot /dev/gpt/zfs0

# Create ZFS file system hierarchy:
zfs create -o mountpoint=none zroot/ROOT
zfs create -o mountpoint=/ zroot/ROOT/default

# Define the default ZFS datasets for root zpool:
zfs create -o mountpoint=/tmp -o exec=on -o setuid=off zroot/tmp # We’ll be using tmpfs for /tmp.
zfs create -o mountpoint=/usr -o canmount=off zroot/usr
zfs create zroot/usr/home
zfs create -o setuid=off zroot/usr/ports
zfs create zroot/usr/src
zfs create -o mountpoint=/var -o canmount=off zroot/var
zfs create -o exec=off -o setuid=off zroot/var/audit
zfs create -o exec=off -o setuid=off zroot/var/crash
zfs create -o exec=off -o setuid=off zroot/var/log
zfs create -o atime=on zroot/var/mail
zfs create -o setuid=off zroot/var/tmp

# Create a symlink to /usr/home:
ln -s /usr/home /mnt/home

# Change /tmp and /var/tmp permissions:
chmod 1777 /mnt/tmp # Not needed now.
chmod 1777 /mnt/var/tmp

# Configure the Boot Environment:
zpool set bootfs=zroot/ROOT/default zroot

# Instruct FreeBSD to mount ZFS pools during system initialization:
printf 'zfs_enable="YES"' >> /tmp/bsdinstall_etc/rc.conf

# Add an fstab entry to use a GELI-encrypted swap partition:
printf "/dev/gpt/swap0.eli\tnone\tswap\tsw\t0\t0\n" >> /tmp/bsdinstall_etc/fstab

# Add an fstab entry to use tmpfs for /tmp:
printf "tmpfs\t/tmp\ttmpfs\trw,mode=1777\t0\t0\n" >> /tmp/bsdinstall_etc/fstab

# Mount the existing EFI partition of your disk:
mount -t msdosfs /dev/ada0p1 /media

# Create FreeBSD boot directory in the EFI partition:
mkdir -p /media/efi/freebsd

# Copy FreeBSD loader to the previously created directory:
cp /boot/loader.efi /media/efi/freebsd/loader.efi

# Now add a UEFI boot entry:
efibootmgr --create --activate --label "FreeBSD" --loader "/media/efi/freebsd/loader.efi"

# Unmount EFI partition:
umount /media

# Exit Shell Partitioning mode, so bsdinstall can continue and complete the installation:
exit

After finishing the installation, don’t forget to add a boot entry for FreeBSD in GRUB or rEFInd.
Here I share some sample entries to guide you a bit. Remember to modify them to reflect your own reality:

# For GRUB:

Code:

menuentry "FreeBSD" {
    insmod part_gpt
    insmod fat
    set root=(hd0,gpt1)
    chainloader /efi/freebsd/loader.efi
}

# For rEFInd, add something like this at the end of

refind.conf

:

Code:

# FreeBSD
menuentry "FreeBSD" {
    loader /efi/freebsd/loader.efi
    icon /efi/refind/icons/os_freebsd.png
}

That’s all. Hope you find it useful!

Sources:
https://www.freebsd.org/doc/handbook/bsdinstall-partitioning.html
https://wiki.freebsd.org/RootOnZFS/GPTZFSBoot
http://kev009.com/wp/2016/07/freebsd-uefi-root-on-zfs-and-windows-dual-boot/
https://github.com/freebsd/freebsd-src/blob/releng/13.0/usr.sbin/bsdinstall/scripts/zfsboot
https://github.com/freebsd/freebsd-src/blob/releng/13.0/usr.sbin/bsdinstall/scripts/bootconfig

EDIT 1:
-Added some sources.

EDIT 2:
-Reworded the title for better clarity.
-Added a note about FreeBSD’s efi loader name used in this tutorial.
-Removed /tmp from ZFS datasets, to use a tmpfs /tmp instead. This way it provides better performance and doesn’t cause troubles with some programs, like Firefox on Wayland, for instance.

UPDATE (2021/02/12):
-Fixed some little issues.
-Added useful efibootmgr command.
-Updated FreeBSD efi boot loader name and location to match new FreeBSD 13.0 defaults.
-Added more sources.

As much as I like FreeBSD UNIX I can not change the fact that the most common computer combination on a planet is a PC with Windows system on it.

The most secure way to try another operating system is to run it inside some virtual machine – like VirtualBox for example – but as you get used to new os – its best to run it natively … and this is where the problems begin – you REALLY do not want to brick your laptop while trying to make some dual boot configuration. Its a lot better if your computer allows to use two different physical disks – does not matter if laptop or regular PC – this way you would be able to choose desired disk from BIOS – but with laptops its not always that easy.

This guide will show you how to install FreeBSD alongside existing Windows installation – without breaking Windows – and without touching the Windows bootloader – we will use Windows bootloader to boot FreeBSD here.

Its kinda based on earlier Install FreeBSD with One Command article.

By doing all these things – we will either use FreeBSD tools or Windows native tools – no third party software involved.

Shrink Windows Disk

The first thing we will do is shrinking the Windows partition – its officially supported.

To start – right-click with mouse on the This PC on your Windows system and select Manage.

Next – right-click the C: disk and select Shrink Volume… option.

Put at least 10240 MB for a desired size – I used 15 GB as I had some more free space.

Then click Shrink button.

After a while you will see Unallocated free space as shown below.

Create Temporary FAT32 Partition

You may create new FAT32 partition in the Disk Management addon – here are the steps.

Mouse right-click the empty space and select New Simple Volume… option.

Hit Next button.

Hit Next without changing the size.

Hit Next on the letter assign part.

For the File system: select FAT32 type and hit Next button.

Click Finish button.

You New Volume is ready.

Alternatively you can use cmd.exe instead to achieve that.

Hit [Windows] key – then type cmd – and as Command Prompt will be displayed – select Run as Administrator on the right side.

After clicking it you will see something like that – I already typed some diskpart.exe commands – and I will repeat them below in text form.

Now – the instructions to create FAT32 filesystem in that free space – here they are.

C:\Windows\system32> diskpart

Microsoft DiskPart version 10.0.19041.3636

Copyright (C) Microsoft Corporation.
On computer: DESKTOP-RP45912

DISKPART> list disk

  Disk ###  Status         Size     Free     Dyn  Gpt
  --------  -------------  -------  -------  ---  ---
  Disk 0    Online           40 GB    15 GB        *

DISKPART> select disk 0

Disk 0 is now the selected disk.

DISKPART> list partition

  Partition ###  Type              Size     Offset
  -------------  ----------------  -------  -------
  Partition 1    System             100 MB  1024 KB
  Partition 2    Reserved            16 MB   101 MB
  Partition 3    Primary             24 GB   117 MB
  Partition 4    Recovery           509 MB    39 GB

DISKPART> create partition primary size=10240

DiskPart succeeded in creating the specified partition.

DISKPART> format fs=fat32

  100 percent completed

DiskPart successfully formatted the volume.

DISKPART> assign

DiskPart successfully assigned the drive letter or mount point.

DISKPART> list partition

  Partition ###  Type              Size     Offset
  -------------  ----------------  -------  -------
  Partition 1    System             100 MB  1024 KB
  Partition 2    Reserved            16 MB   101 MB
  Partition 3    Primary             24 GB   117 MB
  Partition 5    Primary             10 GB    24 GB
  Partition 4    Recovery           509 MB    39 GB

After these instructions my Windows system assigned E: letter for this temporary FAT32 place.

Next we will download FreeBSD-14.2-RELEASE-amd64-zfs.raw.xz and put it into that E: drive.

Copying of the image shown below.

We are ready to reboot and boot from FreeBSD system live media.

We can use FreeBSD-14.2-RELEASE-amd64-disc1.iso and put it into some USB pendrive … or burn on a CD-ROM disc. Does not matter which method you would use – boot from this media on your Windows computer … I hope you know how to do it – but if you are not – let me know in the comments – I will try to help because its different for each vendor and computer. Sometimes its [F11] key and sometimes its [F9] key … you got the idea.

FreeBSD Live System Operations

After you boot the FreeBSD-14.2-RELEASE-amd64-disc1.iso media – choose Live System and type root on the login: prompt and hit [ENTER] key.

It will look more or less like that image below.

Now – we have live FreeBSD UNIX at our hands – we will now dump a FreeBSD partition into that ‘free’ 15 GB spot.

It will require to use ramdisk (as AMIGA systems always used) – then create a ZFS pool with compression enabled there – extract the FreeBSD-14.2-RELEASE-amd64-zfs.raw.xz image there – then map that image as virtual disk – and then dump needed partition into that free 15 GB spot … for a start 🙂

FreeBSD # mdconfig -a -t malloc -s 4g
md0

FreeBSD # zpool create -m /tmp/ramdisk ramdisk md0
ZFS filesystem version: 5
ZFS storage pool version: features support (5000)

FreeBSD # zfs get compress
NAME     PROPERTY     VALUE  SOURCE
ramdisk  compression  on     default

FreeBSD # cd /tmp/ramdisk

FreeBSD # df -g .
Filesystem 1G-blocks Used Avail Capacity  Mounted on
ramdisk            3    0     3     0%    /tmp/ramdisk

Now we have our temp space ready.

We will now mount our FAT32 space at /mnt dir to get access to the FreeBSD-14.2-RELEASE-amd64-zfs.raw.xz disk image. Then we will extract that image into our ZFS compression enabled ramdisk pool.

In my computer my one and only physical disk is represented as ada0 device – as shown below.

You can press [CTRL]+[T] key combination to get the status of the xz(1) command.

FreeBSD # gpart show -p ada0
=>      34  83886013    ada0  GPT  (40G)
        34      2014          - free -  (1.0M)
      2048    204800  ada0p1  efi  (100M)
    206848     32768  ada0p2  ms-reserved  (16M)
    239616  51141261  ada0p3  ms-basic-data  (24G)
  51380877      1395          - free -  (698K)
  51382272  20971520  ada0p4  ms-basic-data  (10G)
  72353792  10485760          - free -  (5.0G)
  82839552   1042432  ada0p5  ms-recovery  (509M)
  83881984      4063          - free -  (2.0M)

FreeBSD # mount_msdosfs /dev/ada0p4 /mnt

FreeBSD # xz -c -d /mnt/FreeBSD-14.2-RELEASE-amd64-zfs.raw.xz > /tmp/ramdisk/14.2.raw

load: 0.65  cmd: xz 925 [running] 16.37r 13.91u 1.49s 78% 10584k
/mnt/FreeBSD-14.2-RELEASE-amd64-zfs.raw.xz (1/1)
  6.8 %       54.4 MiB / 1444.2 MiB = 0.038    89 MiB/s       0:16   3 min 50 s
load: 0.68  cmd: xz 925 [runnable] 24.76r 20.64u 2.07s 79% 10584k
 11.9 %       95.8 MiB / 1649.7 MiB = 0.058    67 MiB/s       0:24   3 min 10 s
load: 0.73  cmd: xz 925 [running] 33.01r 27.43u 2.71s 90% 10584k
 16.8 %      134.8 MiB / 1907.3 MiB = 0.071    58 MiB/s       0:32   2 min 50 s
load: 0.86  cmd: xz 925 [running] 50.50r 40.48u 4.34s 88% 10584k
 27.5 %      220.8 MiB / 2378.5 MiB = 0.093    47 MiB/s       0:50   2 min 20 s
load: 1.32  cmd: xz 925 [tx->tx_sync_done_cv] 123.00r 97.71u 10.53s 85% 10584k
 78.2 %      627.5 MiB / 4295.0 MiB = 0.146    35 MiB/s       2:03         35 s

FreeBSD # echo ${?}
0

FreeBSD # du -sm /tmp/ramdisk/14.2.raw
1632  /tmp/ramdisk/14.2.raw

FreeBSD # df -g .
Filesystem 1G-blocks Used Avail Capacity  Mounted on
ramdisk            3    1     2    44%    /tmp/ramdisk

Now we will map the FreeBSD-14.2-RELEASE-amd64-zfs.raw.xz image to a virtual disk – from which we would copy FreeBSD partition.

The process will involve deleting the temporary FAT32 partition.

FreeBSD # mdconfig -a -t vnode -f 14.2.raw
md1

FreeBSD # gpart show -p md1
=>      34  12649841    md1  GPT  (6.0G)
        34       345  md1p1  freebsd-boot  (173K)
       379     66584  md1p2  efi  (33M)
     66963   2097152  md1p3  freebsd-swap  (1.0G)
   2164115  10485760  md1p4  freebsd-zfs  (5.0G)

FreeBSD # gpart show ada0
=>      34  83886013    ada0  GPT  (40G)
        34      2014          - free -  (1.0M)
      2048    204800  ada0p1  efi  (100M)
    206848     32768  ada0p2  ms-reserved  (16M)
    239616  51141261  ada0p3  ms-basic-data  (24G)
  51380877      1395          - free -  (698K)
  51382272  20971520  ada0p4  ms-basic-data  (10G)
  72353792  10485760          - free -  (5.0G)
  82839552   1042432  ada0p5  ms-recovery  (509M)
  83881984      4063          - free -  (2.0M)

FreeBSD # umount /mnt

FreeBSD # gpart delete -i 4 ada0
ada0p4 deleted

FreeBSD # gpart add -t freebsd-zfs ada0
ada0p4 added

FreeBSD # gpart show -p ada0
=>      34  83886013    ada0  GPT  (40G)
        34      2014          - free -  (1.0M)
      2048    204800  ada0p1  efi  (100M)
    206848     32768  ada0p2  ms-reserved  (16M)
    239616  51141261  ada0p3  ms-basic-data  (24G)
  51380877       115          - free -  (58K)
  51380992  31458560  ada0p4  freebsd-zfs  (15G)
  82839552   1042432  ada0p5  ms-recovery  (509M)
  83881984      4063          - free -  (2.0M)

FreeBSD # gpart show -p md1
=>      34  12649841    md1  GPT  (6.0G)
        34       345  md1p1  freebsd-boot  (173K)
       379     66584  md1p2  efi  (33M)
     66963   2097152  md1p3  freebsd-swap  (1.0G)
   2164115  10485760  md1p4  freebsd-zfs  (5.0G)

FreeBSD # dd bs=1m status=progress if=/dev/md1p4 of=/dev/ada0p4
  5302648832 bytes (5303 MB, 5057 MiB) transferred 73.007s, 73 MB/s
5120+0 records in
5120+0 records out
5368709120 bytes transferred in 73.332077 secs (73210924 bytes/sec)

Now – as we have FreeBSD system copied into the right place – we need to take care about the bootloader part – and stick with me here – we do not change Windows bootloader to anything else – we just mount the UEFI partition and add one FreeBSD loader file there.

FreeBSD # mkdir /tmp/efi-bsd

FreeBSD # mount_msdosfs /dev/md1p2 /tmp/efi-bsd

FreeBSD # find /tmp/efi-bsd
/tmp/efi-bsd
/tmp/efi-bsd/EFI
/tmp/efi-bsd/EFI/BOOT
/tmp/efi-bsd/EFI/BOOT/bootx64.efi

FreeBSD # mkdir /tmp/efi-win

FreeBSD # mount_msdosfs /dev/ada0p1 /tmp/efi-win

FreeBSD # cp /tmp/efi-bsd/EFI/BOOT/bootx64.efi /tmp/efi-win/EFI/Boot/fbsdx64.efi

FreeBSD # umount /tmp/efi-bsd

FreeBSD # umount /tmp/efi-win

We need to clear the /etc/fstab file because it includes entries to partitions that does not exist on our disk.

FreeBSD # zpool import -R /mnt zroot

FreeBSD # zfs list
NAME                 USED  AVAIL  REFER  MOUNTPOINT
ramdisk             1.60G  2.03G  1.60G  /tmp/ramdisk
zroot               3.82G   557M   424K  none
zroot/ROOT          3.81G   557M   424K  none
zroot/ROOT/default  3.81G   557M  3.81G  /mnt
zroot/home           436K   557M   436K  /mnt/home
zroot/tmp            436K   557M   436K  /mnt/tmp
zroot/usr           1.69M   557M   424K  /mnt/usr
zroot/usr/obj        436K   557M   436K  /mnt/usr/obj
zroot/usr/ports      436K   557M   436K  /mnt/usr/ports
zroot/usr/src        436K   557M   436K  /mnt/usr/src
zroot/var           2.56M   557M   424K  /mnt/var
zroot/var/audit      444K   557M   444K  /mnt/var/audit
zroot/var/crash      440K   557M   440K  /mnt/var/crash
zroot/var/log        436K   557M   436K  /mnt/var/log
zroot/var/mail       436K   557M   436K  /mnt/var/mail
zroot/var/tmp        440K   557M   440K  /mnt/var/tmp

FreeBSD # :> /mnt/etc/fstab

FreeBSD # zpool export zroot

If you would not clear that – you will get an error message like this in the first FreeBSD boot.

If you forgot that – and you find FreeBSD in that state when booting it – do instructions from below.

Enter full pathname of shell or RETURN for /bin/sh: [ENTER]
root@:/ # zfs set readonly=off zroot
root@:/ # :> /etc/fstab
root@:/ # exit

That should fix it.

We are now done with operations in the FreeBSD Live System mode – we will not reboot back into Windows system.

FreeBSD # poweroff

Windows Bootloader Entry

As I said before – we will use native Windows bootloader to boot FreeBSD – so we are sure that we will not break the Windows installation and boot configuration.

Same as earlier – hit the [Windows] key – then type cmd – and as Command Prompt will be displayed – select Run as Administrator on the right side.

Now – type bcdedit to show current Windows boot entries.

It will look more or less like below.

C:\Windows\system32> bcdedit

Windows Boot Manager
--------------------
identifier              {bootmgr}
device                  partition=\Device\HarddiskVolume1
path                    \EFI\Microsoft\Boot\bootmgfw.efi
description             Windows Boot Manager
locale                  en-US
inherit                 {globalsettings}
default                 {current}
resumeobject            {e9d80909-b296-11ef-af20-c59746508e06}
displayorder            {current}
toolsdisplayorder       {memdiag}
timeout                 30

Windows Boot Loader
-------------------
identifier              {current}
device                  partition=C:
path                    \Windows\system32\winload.efi
description             Windows 10
locale                  en-US
inherit                 {bootloadersettings}
recoverysequence        {e9d8090b-b296-11ef-af20-c59746508e06}
displaymessageoverride  Recovery
recoveryenabled         Yes
isolatedcontext         Yes
allowedinmemorysettings 0x15000075
osdevice                partition=C:
systemroot              \Windows
resumeobject            {e9d80909-b296-11ef-af20-c59746508e06}
nx                      OptIn
bootmenupolicy          Standard

The ‘upper’ part is the Windows bootloader config – the ‘lower’ part is the Windows entry that allows that Windows system to boot.

We will now copy that Windows entry into FreeBSD one.

The first command will return us the ‘key’ under which this entry will be known – it was {e9d8090d-b296-11ef-af20-c59746508e06} in my case – we will use that in the next commands.

C:\Windows\system32> bcdedit /copy {current} /d "FreeBSD"
The entry was successfully copied to {e9d8090d-b296-11ef-af20-c59746508e06}.

C:\Windows\system32> bcdedit /set {e9d8090d-b296-11ef-af20-c59746508e06} path \EFI\BOOT\fbsdX64.efi
The operation completed successfully.​

C:\Windows\system32> bcdedit /set {bootmgr} displaybootmenu yes
The operation completed successfully.​

The last option was to enable always showing the boot menu to choose from.

After our copying operation now the bcdedit output will look more or less like that.

C:\Windows\system32> bcdedit

Windows Boot Manager
--------------------
identifier              {bootmgr}
device                  partition=\Device\HarddiskVolume1
path                    \EFI\Microsoft\Boot\bootmgfw.efi
description             Windows Boot Manager
locale                  en-US
inherit                 {globalsettings}
default                 {current}
resumeobject            {e9d80909-b296-11ef-af20-c59746508e06}
displayorder            {current}
                        {e9d8090d-b296-11ef-af20-c59746508e06}
toolsdisplayorder       {memdiag}
timeout                 30
displaybootmenu         Yes

Windows Boot Loader
-------------------
identifier              {current}
device                  partition=C:
path                    \Windows\system32\winload.efi
description             Windows 10
locale                  en-US
inherit                 {bootloadersettings}
recoverysequence        {e9d8090b-b296-11ef-af20-c59746508e06}
displaymessageoverride  Recovery
recoveryenabled         Yes
isolatedcontext         Yes
allowedinmemorysettings 0x15000075
osdevice                partition=C:
systemroot              \Windows
resumeobject            {e9d80909-b296-11ef-af20-c59746508e06}
nx                      OptIn
bootmenupolicy          Standard

Windows Boot Loader
-------------------
identifier              {e9d8090d-b296-11ef-af20-c59746508e06}
device                  partition=C:
path                    \EFI\BOOT\fbsdX64.efi
description             FreeBSD
locale                  en-US
inherit                 {bootloadersettings}
recoverysequence        {e9d8090b-b296-11ef-af20-c59746508e06}
displaymessageoverride  Recovery
recoveryenabled         Yes
isolatedcontext         Yes
allowedinmemorysettings 0x15000075
osdevice                partition=C:
systemroot              \Windows
resumeobject            {e9d80909-b296-11ef-af20-c59746508e06}
nx                      OptIn
bootmenupolicy          Standard

We are now done on the Windows bootloader operation.

Reboot the Windows system.

First FreeBSD Boot

After the reboot the Windows loader menu will welcome us.

Reasonable person would think that after choosing the FreeBSD position – we would just boot into it … we will – but not directly.

… and yes – it will require from you to walk thru all these windows and buttons everytime you would want to boot FreeBSD – but your Windows ‘ecosystem’ remains unmodified and untouched.

I am not a Windows expert – maybe someone of you will point me into better Windows bootloader configuration for FreeBSD hopefully 🙂

If you feel comfortable – you can switch to REFIND bootloader … but that is a topic for another story.

Next thing after choosing the FreeBSD system you will see Preparing Automatic Repair message.

… and after a moment the Diagnosing your PC one.

Its also VERY symbolic that in all words in the last two messages only the your part was in LOWERCASE … like it is not your PC at all 🙂

Next on the Automatic Repair screen click the Advanced options button.

On the next Choose an option screen choose Use another operating system button.

… and finally on a screen Choose an operating system window choose FreeBSD position.

Now – finally – you will boot into FreeBSD UNIX system.

You will see FreeBSD loader(8) as shown below.

… and later – after FreeBSD finishes to boot – you will see the login: prompt.

Welcome to the FreeBSD world.

“A world where anything is possible. Where we go from there is a choice I leave to you.”

EOF

null

Приобрёл я себе как-то ноутбук Asus N56JK, внутри которого вместо привычного BIOS установлен новомодный UEFI.
Большинство людей ограничивается тем, что выключают SecureBoot, включают CSM (это efi программка, которая эмулирует из себя legacy boot) и накатывают парк систем по старинке. Но этот путь не для нас.
Рассказать мне хочется о том, как же всё-таки установить и добиться загрузки FreeBSD 10 именно через UEFI, благо EFI-загрузчик они всё-таки доделали.
Из требований: красота и дуал-бут с Windows 8.1 enterprise.
Вкратце опишу как же работает UEFI с точки зрения пользователя. Во-первых, после включения компьютера проходит всё тот-же POST, только под другим соусом. Во многих UEFI его можно урезать до минимума, чтобы опросом (и диагностикой) устройств занималось ядро ОС во время загрузки. Дальше, если внезапно EFI-раздела на системе не оказалось, включается режим совместимости и всё работает по старым и объезженным сценариям. Но это не наш случай ;) У нас же GPT с EFI разделом. После выполнения подготовительных процедур, UEFI выбирает стандартный ‘boot option’ — фактически, это efi программа, которой UEFI передаёт управление. По умолчанию, это /EFI/Boot/bootx64.efi. Эта программа загружает загрузчик ОС, который уже загружает ядро.
А теперь про мой конкретный кейс:
Установка лицензионной windows 8.1 создала мне на диске схему GPT, создала свой загрузочный раздел (ada0p1), создала EFI-раздел (ada0p2) и, собственно, раздел под диск C: (ada0p3). После установки, естественно, всё работало как по маслу. Не зря же корпорация Microsoft трудится над user-friendly софтом.
В принципе, если вы не собираетесь ставить винду, можно и руками создать EFI раздел, который по-сути представляет из себя обычный слайс с определённым типом (0xef) и на котором обычная fat32. Внутри него должна быть определённая иерархия, которая в общем случае ограничивается файлом /EFI/Boot/bootx64.efi.
Дальше я приступил к установке FreeBSD 10. И вот тут начались грабли. Так как разработчики добавили поддержку EFI начиная с r264095, а на установочном диске у нас (если мне не изменяет память) примерно r260890, пришлось временно включить в «BIOS-e» запуск CSM. Загрузившись с диска, я как-обычно выбрал shell и установил фрю без особых танцев. В качестве исключения стоит отметить, что UEFI загрузчик FreeBSD не умеет ZFS (который для меня критичен), поэтому когда создавал разделы с помощью gpart, добавил два раздела: -t freebsd-ufs -s 2048M ada0p4 (да, я очень люблю много ядер с дебаг-символами в /boot) и -t freebsd-zfs ada0p5.
Изначально я монтировал ada0p4 в /boot и не знал проблем, ибо грузиться приходилось руками, но позже походил по граблям с loader.efi и теперь ada0p4 я монтирую /altboot, а /boot ссылается на /altboot/boot. Поэтому советую сразу исходить из этого при установке системы.
Естественно, никаких загрузчиков в процессе инсталляции я не ставил.
После успешной установки базовой поставки фри (хоть и без загрузчика), рекомендую перезагрузиться. Грузиться мы будем опять с cdrom, но в меню загрузки нажмём кнопочку ‘3’ и попадём в boot-prompt. А теперь, используя загруженный с CD загрузчик, загрузим свежепоставленную фрю:

unload
load disk0p4:/boot/kernel/kernel
load disk0p4:/boot/kernel/opensolaris.ko
load disk0p4:/boot/kernel/zfs.ko
set vfs.root.mountfrom="zfs:rpool/ROOT"
boot

Если на данном этапе загрузилась фря, значит дальше всё будет хорошо.
В первую очередь, обновим систему.

svnlite co svn://svn.freebsd.org/base/stable/10 /usr/src
cd /usr/src
make kernel-toolchain
# я указываю -j10 для сборки в 10 потоков
make -j10 buildworld
# тут кстати можно сразу кастомный конфиг ядра сделать. Мой называется KORG
make -j10 buildkernel KERNCONF=KORG
# ну а если собирать GENERIC, то просто
#make -j10 buildkernel
make installkernel KERNCONF=KORG
# или для GENERIC
#make installkernel

На этом шаге хэндбук рекомендует «shutdown now», но я привык к полноценному reboot в single-user (опять же, с cdrom, только «boot -s» вместо «boot»)

mount -a
zfs mount -a
# запустим mergemaster в режиме pre-buildworld
mergemaster -p
make installworld
# остальной merge-инг
mergemaster -iF
cd /usr/src
# удалим старые ненужные файлы, которые могут приводить к конфликтам
make delete-old

Если всё прошло гладко, у нас есть свежая система (в моём случае, это r273924), но совсем без загрузчика.
Дальше я вспомнил про существование требований (см. выше) и отправился на поиски красивого загрузчика. Для себя я выбрал rEFInd, который можно скачать на SourceForge (даже в бинарном виде).
Установим загрузчики — rEFInd и фряшный.

mount_msdosfs /dev/ada0p2 /mnt
cd /mnt/EFI/
cp -r ...../refind .
cd refind
rm -rf *ia32*
cp refind.conf-sample refind.conf
# пока-что конфигурировать его не будем, об этом чуть позже
cd /mnt/EFI
mkdir FreeBSD
cp /usr/obj/usr/src/sys/boot/amd64/boot1.efi/boot1.efi FreeBSD/
# и, наконец, настроим loader.conf
cat <<@ >/boot/loader.conf
zfs_load="YES"
vfs.root.mountfrom="zfs:rpool/ROOT"
@

И перезагрузимся в «BIOS». Разработчики ASUS настолько лояльны к «прочим операционным системам», что из останстки UEFI можно удобно управлять boot-option-ами. Я добавил опцию rEFInd, которая загружает /EFI/refind/refind_x64.efi и выбрал её как опцию «по-умолчанию». Если же у вас не ASUS, то единственное, что могу посоветовать, это загрузиться в какой-нибудь linux liveCD и воспользоваться efibootmgr для выполнения этой операции.

В общем, после перезагрузки должен загрузиться rEFInd и показать на выбор два значка: винду и фрю, каждый из которых должен загружать соответствующую систему.
Ну и на десерт — немного красивостей. Этот замечательный refind можно легко темизировать (достаточно найти в интернете красивую тему, или сделать свою, как это сделал я). Мой конфиг refind я решил выложить тут же:

timeout 10
hideui label singleuser safemode hwtest arrows hints editor
icons_dir korg
banner korg/bg.png
banner_scale fillscreen
selection_big korg/selection_big.png
selection_small korg/selection_small.png
resolution 1920 1080
showtools
scanfor manual

menuentry "FreeBSD" {
        icon /EFI/refind/korg/os_freebsd.png
        loader /EFI/FreeBSD/boot1.efi
}
menuentry "MustDIE" {
        icon /EFI/refind/korg/os_win.png
        loader /EFI/Boot/bootx64.efi
}

Когда всё ещё-раз будет проверено и настроено, нужно на забыть выключить CSM — он нам больше не понадобится.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • My contacts backup windows
  • Spy fox windows 10
  • Обновить таблицу маршрутизации windows 10
  • Серые обои для windows 7
  • Алкоголик 120 для windows 10