Gentoo on MacBook Pro Retina Part 1: Base System

Published on Author Artem Butusov6 Comments

Introduction

I would like to have Gentoo Linux as second OS on my MacBook Pro Retina 13″ (Early 2013).
Also I would like to have both full functional console and full functional X with Gnome 3 desktop.
Also I would like to have support for Russian and English everywhere. Main language is English with options to type in Russian and to see Russian text.
I will use x86-64 default gentoo profile with gnome 3 and systemd.

Let’s start.

Free some space for Gentoo

I have MacOS X 10.11 El Captain so screenshot will show that OS.

We will need at least two partitions – one for root and one for swap (for swap and hibernation).

I have 8GB of RAM, so swap should be a little bit larger to make sure that hibernation data will fit.
I selected 50GB for Gentoo.

Open Disk Utility, resize main partition and create 2 new partitions in the end with any filesystem and and label (we will change fs and label later).

screenshot_2016-01-09_14.44.50

screenshot_2016-01-09_14.45.05

Create installation media

I recommend to use SystemRescueCD as installation media because it has more drivers for wireless and ethernet out of the box in comparison with gentoo minimal install CD. But technically you could use almost any livecd linux distro.

ISO image could be downloaded here: http://sysresccd.org

We will install gentoo from USB thumb drive, so we will need to convert ISO image to EFI bootable image for thumb drive.

Attach thumb drive, open Disk Utility and erase thumb drive like on screenshot below.

screenshot_2016-01-09_17.16.09

Remember device id (see behind) to select valid device in UNetBootIn.

Next we need to write iso as EFI bootable thumb drive. It could be done with UNetBootIn available here http://unetbootin.github.io

After procedure will be completed we could proceed with installation. We no need OS X anymore.

Please disregard unetbootin message that mac will be unbootable with created media. It’s wrong.

Boot from installation media

Plug in you UDB thumb drive with installation media, reboot OS X and hold ALT after you will hear boot sound.

You will see boot screen, on left there will be Macintosh HD and EFI Boot on right side.

There could other label for other distros, for example “Windows” =)

After livecd linux boot you will see console with very small text if you have retina on your macbook pro. It’s ok, at least for now.

Configuring the network

To be able to download the latest source code, networking will need to be configured.

Let’s look what hardware we have:

root@sysresccd /root % lspci | grep 'Ethernet\|Network'
02:00.0 Ethernet controller: Broadcom Corporation NetXtreme BCM57786 Gigabit Ethernet PCIe (rev 21)
03:00.0 Network controller: Broadcom Corporation BCM4331 802.11a/b/g/n (rev 02)

Over Ethernet

The easiest way to get network for me was to use original Apple Thunderbolt Ethernet adaptor and it works fine. It uses kernel module tg3. Details are here.

Check if interface available:

ifconfig

Run network setup (in my case it’s ens9 interface):

net-setup ens9

I have wired network and DHCP so I selected it in net-setup wizard.

Over Wireless

My MacBook Pro has Broadcom BCM4331 wireless controller.

SystemRescueCD has driver for it but without firmware =)

If you would like to get wireless installation you will need to add broadcom driver on installation media after media creation.

Download fresh version of driver from http://www.lwfinger.com/b43-firmware/ .

In my case it’s http://www.lwfinger.com/b43-firmware/broadcom-wl-6.30.163.46.tar.bz2

Put it on created installation media in drivers directory.

After booting in SystemRescueCD please do the following:

cp /livemnt/boot/drivers/broadcom-wl-6.30.163.46.tar.bz2 .
tar -xvf broadcom-wl-6.30.163.46.tar.bz2
b43-fwcutter -w /lib/firmware broadcom-wl-6.30.163.46.wl_apsta.o

Remove bad modules if loaded and reload b43:

rmmod b43 bcma
modprobe b43

b43 will not give you wireless-N but wireless-B/G should be sufficient to perform initial gentoo installation. Later I will show how to install broadcom-sta driver with wireless-N support.

Check if wireless interface is available:

ifconfig

Connect to wireless network through NetworkManager:

nmcli dev wifi connect "network name" password "secret"

Check internet connection

Now we need to check that network is fine:

ping google.com

Ok, pings are coming back.

Get remote access

I recommend to proceed with installation from remote PC via ssh. It will require working network too.

Change the following options in /etc/ssh/sshd_config:

PermitRootLogin yes
PasswordAuthentication yes

Start SSH:

/etc/init.d/sshd restart

Remember local network IP address:

ifconfig | grep inet

Change password for root to known value:

passwd

Connect from remote PC in that network via SSH.

For mac os x and linux its ssh root@192.168.1.111 where 192.168.1.111 is macbook ip address.
On windows it could be done through PuTTY: http://www.chiark.greenend.org.uk/~sgtatham/putty/

Preparing the disks

Now we will need to fix filesystem and labels for created in OS X partitions.

We would like to see what we have:

blkid

You will see something like that:

/dev/loop0: TYPE="squashfs"
/dev/sda1: LABEL="EFI" UUID="67E3-17ED" TYPE="vfat" PARTLABEL="EFI System Partition" PARTUUID="446f244e-b2ec-4ddd-8d61-97d704ee5a94"
/dev/sda2: UUID="1a7d3725-5644-355d-a695-aa73f5626175" LABEL="Macintosh HD" TYPE="hfsplus" PARTLABEL="Macintosh HD" PARTUUID="49ec15f6-4df2-4d35-92d2-11f9897badef"
/dev/sda3: UUID="0e0e14ee-0755-3efb-824d-052946dfffda" LABEL="Recovery HD" TYPE="hfsplus" PARTLABEL="Recovery HD" PARTUUID="6bfccdc7-ea58-441d-b501-9db9c9c8320a"
/dev/sda4: LABEL="gentoo" UUID="80767dcc-31dc-45df-9a69-9ca2144efa01" TYPE="ext4" PARTLABEL="gentoo" PARTUUID="e870777a-f01e-481f-a12a-dfcca34af5a1"
/dev/sda5: LABEL="swap" UUID="20ad5033-a72e-46a2-bf58-2947a3891634" TYPE="swap" PARTLABEL="swap" PARTUUID="9931c671-0048-45d2-981b-db793bc2ad8b"
/dev/sdb1: LABEL="GENTOO" UUID="E6C3-1B0D" TYPE="vfat"

Perfect, /dev/sda4 is our linux root and /dev/sda5 is swap.

Now we know device names and could format partitions and set labels for them.

mkfs.ext4 /dev/sda4
e2label /dev/sda4 gentoo
mkswap /dev/sda5 --label swap

Mounting the disks

mount /dev/sda4 /mnt/gentoo
mkdir -p /mnt/gentoo/boot/efi
touch /mnt/gentoo/boot/efi/.keep
mount /dev/sda1 /mnt/gentoo/boot/efi

Set time

It’s important to have valid timestamps on extracted files so sync system time with time server:

ntpdate -s time.nist.gov

Installing the base system

Go to future system root:

cd /mnt/gentoo

Go to http://distfiles.gentoo.org/releases/amd64/autobuilds/ and find fresh stage3 tarball.

Download and unpack fresh stage3:

wget http://distfiles.gentoo.org/releases/amd64/autobuilds/current-stage3-amd64/stage3-amd64-20160107.tar.bz2
tar xvpf stage3-*
rm stage3-*

Download and unpack fresh portage tree:

wget http://distfiles.gentoo.org/releases/snapshots/current/portage-latest.tar.xz
tar xvf portage-latest.* -C /mnt/gentoo/usr
rm portage-latest.*

Chrooting

Copy nameserver list from host environment to chroot environment:

cp /etc/resolv.conf /mnt/gentoo/etc/

Mount kernel resources:

mount -t proc none /mnt/gentoo/proc
mount -o bind /dev /mnt/gentoo/dev
mount -o bind /sys /mnt/gentoo/sys

Chroot:

chroot /mnt/gentoo /bin/bash
env-update && source /etc/profile

If for some reason you will loose ssh connection then repeat just previous step “chroot”.
If for some reason you will reboot pc, then after reboot you will need to setup network again, do mounting and do chrooting.

Configuring mount points

blkid | grep 'gentoo\|swap\|EFI'
/dev/sda1: LABEL="EFI" UUID="67E3-17ED" TYPE="vfat" PARTLABEL="EFI System Partition" PARTUUID="446f244e-b2ec-4ddd-8d61-97d704ee5a94"
/dev/sda4: LABEL="gentoo" UUID="80767dcc-31dc-45df-9a69-9ca2144efa01" TYPE="ext4" PARTLABEL="gentoo" PARTUUID="e870777a-f01e-481f-a12a-dfcca34af5a1"
/dev/sda5: LABEL="swap" UUID="20ad5033-a72e-46a2-bf58-2947a3891634" TYPE="swap" PARTLABEL="swap" PARTUUID="9931c671-0048-45d2-981b-db793bc2ad8b"
nano /etc/fstab
# <fs>                                          <mountpoint>    <type>  <opts>          <dump/pass>

UUID="67E3-17ED"                                /boot/efi       vfat    noauto,noatime  1 2
UUID="80767dcc-31dc-45df-9a69-9ca2144efa01"     /               ext4    noatime         0 1
UUID="20ad5033-a72e-46a2-bf58-2947a3891634"     none            swap    sw              0 0

/dev/cdrom                                      /mnt/cdrom      auto    noauto,ro       0 0
/dev/fd0                                        /mnt/floppy     auto    noauto          0 0

Configuring the compiler

Edit file:

nano /etc/portage/make.conf
CFLAGS="-O2 -pipe -mtune=native"
CXXFLAGS="${CFLAGS}"
CHOST="x86_64-pc-linux-gnu"
USE=""
MAKEOPTS="-j5"
ACCEPT_LICENSE="*"
LINGUAS="en_US ru"
PORTDIR="/usr/portage"
DISTDIR="${PORTDIR}/distfiles"
PKGDIR="${PORTDIR}/packages"

It’s standard config. Here we set:
-mtune=native to optimize binaries for laptop hardware
MAKEOPTS="-j5" to compile in 5 threads to better utilize multicore CPU and speedup compilation
– other things are obvious

Amount of cores could be detected with: cat /proc/cpuinfo | grep processor | wc -l

Later we will add some other options in that config.

Create directories for future manipulation with package options:

mkdir -p /etc/portage/package.mask
mkdir -p /etc/portage/package.use
mkdir -p /etc/portage/package.accept_keywords

We will need to set package options based on supported by CPU features:

emerge app-portage/cpuinfo2cpuflags -1
cpuinfo2cpuflags-x86 >> /etc/portage/make.conf

Now you will see something like that in the end of make.conf:

CPU_FLAGS_X86="aes avx mmx mmxext popcnt sse sse2 sse3 sse4_1 sse4_2 ssse3"

emerge -1 will merge package once and it will be cleaned on next emerge --depclean.

Compile kernel

emerge gentoo-sources
emerge genkernel-next
genkernel all --menuconfig

Below are the changes in comparison to vanilla kernel config shipped with genkernel.

Systemd:

Gentoo Linux
    Support for init systems, system and service managers  --->
        [*] OpenRC, runit and other script based systems and managers
        [*] systemd
General setup
    [*] Configure standard kernel features (expert users)  --->
Firmware Drivers --->
    < > BIOS update support for DELL systems via sysfs
    < > Dell Systems Management Base Driver
Device Drivers  --->
    Generic Driver Options  --->
        [*] Support for uevent helper
        () path to uevent helper 
        [ ] Fallback user-helper invocation for firmware loading
    Character devices  --->
        [*] Support multiple instances of devpts

Broadcom Wireless BCM43XX (options for compatibility with broadcom-sta driver):

Networking support  --->
    Wireless  --->
        < >   Generic IEEE 802.11 Networking Stack (mac80211)
Device Drivers  ---> 
    [*] Network device support  --->
        [*]   Wireless LAN  --->
            < >   Broadcom IEEE802.11n embedded FullMAC WLAN driver
            <M>   Intel PRO/Wireless 2100 Network Connection
        [*]   Ethernet driver support  --->
            [*]   Broadcom devices
                < >     Broadcom 440x/47xx ethernet support
    Sonics Silicon Backplane  --->
        < > Sonics Silicon Backplane support
    Broadcom specific AMBA  --->
        < > BCMA support

Thunderbolt:

Bus options (PCI etc.)  --->
    [*] PCI support
    [*]   PCI Express Port Bus support
    [*]     PCI Express Hotplug driver
    [*] Support for PCI Hotplug  --->
        [*]   ACPI PCI Hotplug driver
Device Drivers  ---> 
    <*> Thunderbolt support for Apple devices

Apple Thunderbolt Ethernet:

Device Drivers  ---> 
    [*] Network device support  --->
        [*]   Ethernet driver support  --->
            [*]   Broadcom devices
                <M>     Broadcom Tigon3 support

Other:

Processor type and features
    Processor family  --->
        (X) Core 2/newer Xeon
    Preemption Model  --->
        (X) Voluntary Kernel Preemption (Desktop)
    Timer frequency  --->
        (X) 1000 HZ
    [*] EFI runtime service support
    [ ]   EFI stub support
Device Drivers  --->
    Input device support  --->
        [*]   Mice  --->
            <M>   Apple USB BCM5974 Multitouch trackpad support
    {*} Hardware Monitoring support  --->
        <M>   Apple SMC (Motion sensor, light sensor, keyboard backlight)
    [*] X86 Platform Specific Device Drivers  --->
        <M>   Apple Gmux Driver
    <M> Multimedia support  --->
        [*]   Cameras/video grabbers support 
        [*]   Media USB Adapters  --->
            <M>   USB Video Class (UVC)
    <*> Sound card support  --->
        <M>   Advanced Linux Sound Architecture  --->
            [*]   PCI sound devices  --->
            HD-Audio  --->
                <M> Build HDMI/DisplayPort HD-audio codec support
                <M> Build Cirrus Logic codec support
    <M> MMC/SD/SDIO card support  --->
        <M>   MMC block device driver
        [*]     Use bounce buffer for simple hosts
    [*] Real Time Clock  --->
    USB support  --->
        <M>     xHCI HCD (USB 3.0) support
Power management and ACPI options  --->
    [*] ACPI (Advanced Configuration and Power Interface) Support  --->
        <*>   Smart Battery System

Install wireless driver

echo "net-wireless/broadcom-sta" >> /etc/portage/package.accept_keywords/broadcom-sta
emerge net-wireless/broadcom-sta

Install bootloader

Install EFI GRUB:

echo 'GRUB_PLATFORMS="efi-64"' >> /etc/portage/make.conf
emerge grub

Install EFI bootloader:

grub2-install --efi-directory=/boot/efi

Check that EFI boot menu has new default gentoo bootloader pointing to GRUB:

sysresccd / # efibootmgr -v
BootCurrent: 0000
Timeout: 5 seconds
BootOrder: 0000,0080
Boot0000* gentoo        HD(1,GPT,446f244e-b2ec-4ddd-8d61-97d704ee5a94,0x28,0x64000)/File(\EFI\gentoo\grubx64.efi)
Boot0080* Mac OS X      PciRoot(0x0)/Pci(0x1f,0x2)/Sata(0,0,0)/HD(3,GPT,6bfccdc7-ea58-441d-b501-9db9c9c8320a,0x3a2a1158,0x135f28)
Boot0081* Mac OS X      PciRoot(0x0)/Pci(0x1f,0x2)/Sata(0,0,0)/HD(3,GPT,6bfccdc7-ea58-441d-b501-9db9c9c8320a,0x3a2a1158,0x135f28)
Boot0082*       PciRoot(0x0)/Pci(0x1f,0x2)/Sata(0,0,0)/HD(3,GPT,6bfccdc7-ea58-441d-b501-9db9c9c8320a,0x3a2a1158,0x135f28)
BootFFFF*       PciRoot(0x0)/Pci(0x1f,0x2)/Sata(0,0,0)/HD(2,GPT,49ec15f6-4df2-4d35-92d2-11f9897badef,0x64028,0x3a23d130)/File(\System\Library\CoreServices\boot.efi)

Manually add EFI boot entry:

efibootmgr --create --label Gentoo --loader "\EFI\gentoo\grubx64.efi"

Manually remove EFI boot entry:

efibootmgr -B -b <hex>

Then we need to configure GRUB.

nano /etc/default/grub:

GRUB_CMDLINE_LINUX_DEFAULT="rootfstype=ext4 init=/usr/lib/systemd/systemd"

rootfstype is optional but will speedup root mounting.
init is required to switch inti system to systemd.

To be able to boot OS X from grub you will need to edit /etc/grub.d/40_custom:

menuentry "Mac OS X" {
    insmod hfsplus
    set root='(hd1,gpt3)'
    chainloader ($root)/System/Library/CoreServices/boot.efi
}

Generate GRUB config:

grub2-mkconfig -o /boot/grub/grub.cfg

Install systemd

Base stage3 has OpenRC as default init system. It’s perfect for servers but has less functions than systemd and systemd is better integrated with Gnome.
We are building desktop gentoo, so we need to swith to systemd to get best integration.

View list of available profiles:

eselect profile list

Select systemd profile (without gnome for now):

eselect profile set default/linux/amd64/13.0/systemd

Merge world again and networkmanager:

emerge --deep --update --newuse world -va

Install NetworkManager

Fix USE flags in /etc/portage/make.conf if needed. In my case I have to add dbus in USE.

emerge networkmanager -va

Setting root password

To be able to login into system after reboot we need to change root password.

passwd

Check system

Ok, now we need to check kernel, systemd and bootloader.

Reboot and check that you can login into gentoo linux console.

reboot

Post-installation configuration

Configuring network

systemctl enable NetworkManager
systemctl start NetworkManager

Connecting wirelessly:

nmcli dev wifi connect "network name" password "secret"

Configuring SSH

Add your public ssh key to /root/.ssh/authorized_keys or allow password login over ssh in the same way as it was done to get initial access to livecd console.

systemctl enable sshd
systemctl start sshd

Fix /etc/mtab

ln -sf /proc/self/mounts /etc/mtab

Configuring the hostname

hostnamectl set-hostname macbookpro
hostnamectl status
nano /etc/hosts
127.0.0.1 macbookpro.local macbookpro localhost

Configuring the locale

nano /etc/locale.gen:

en_US.UTF-8 UTF-8
ru_RU.UTF-8 UTF-8
locale-gen
localectl list-locales
localectl set-locale LANG=en_US.UTF-8
localectl status

Configuring the keymap

localectl list-keymaps
localectl set-keymap ruwin_alt_sh-UTF-8
localectl status

Configuring the timezone

timedatectl list-timezones
timedatectl set-timezone US/Eastern
timedatectl status

Configuring NTP sync

timedatectl set-ntp 1
timedatectl status

cron

systemd has support of timers and they could be used as replacement for cron task but some services assume to have cron compatible tasks in /etc/cron.*

We could install compatibility layer for that:

emerge sys-process/systemd-cron
systemctl enable cron
systemctl start cron

syslog

systemd journald will handle all log messages.

syslog is not required

logrotate

systemd journald will handle journald retention policy.

logrotate is not required

Fix font

Resolution can’t be set on Apple EFI, so we can just increase font size.

MacBook Pro Retina has 2x resolution in comparison to MacBook Pro. So if console looks fine with 8×16 font then retina will look fine with 16×32 font.

We need bitmap console-optimized for with Russian characters. Terminus font is a good choice.

Change GRUB2 font

emerge media-fonts/terminus-font
echo "sys-boot/grub truetype" >> /etc/portage/package.use/grub
emerge sys-boot/grub
mount /boot/efi
grub2-install --efi-directory=/boot/efi
grub2-mkfont -s 32 -o /boot/grub/fonts/terminus_32.pf2 /usr/share/fonts/terminus/ter-x32b.pcf.gz
echo 'GRUB_FONT="/boot/grub/fonts/terminus_32.pf2"' >> /etc/default/grub
grub2-mkconfig -o /boot/grub/grub.cfg
reboot

Change console font

setfont ter-v32b
nano /etc/vconsole.conf
FONT=ter-v32b

Change Linux kernel font

Read more about it here.

Fix issues

Fix noise on console

If you see annoying noise on console from kernel then it could be fixed, we just need to stop printing on console kernel messages after successful load.

nano /etc/systemd/system/dmesg-console-off.service

[Unit]
Description=Disable printing of kernel messages to console

[Service]
Type=oneshot
ExecStart=/bin/sh -c "echo 0 > /proc/sys/kernel/printk"

[Install]
WantedBy=multi-user.target
systemctl enable dmesg-console-off

Remove all boot noise

Pass quiet to kernel command line to hide kernel messages.

Disable grub2 extra echos:

sed '/$(echo "$message" | grub_quote)/ s/^#*/#/' -i /etc/grub.d/10_linux
grub2-mkconfig /boot/grub/grub.cfg

Remove systemd version: TODO…
Remove systemd output: TODO…

Base utilities

eselect news read

emerge gentoolkit
emerge eix && eix-update
echo "app-misc/mc -xdg" >> /etc/portage/package.use/mc
emerge app-misc/mc
emerge gptfdisk
emerge lsof
emerge nmap
emerge traceroute
emerge bind-tools
emerge telnet-bsd
emerge tcpdump
echo "sys-process/nmon" > /etc/portage/package.accept_keywords/nmon
emerge nmon
emerge speedtest-cli
emerge screen

Links

https://wiki.gentoo.org/wiki/Systemd
https://wiki.gentoo.org/wiki/NetworkManager
https://wiki.gentoo.org/wiki/Apple_Macbook_Pro_Retina
https://help.ubuntu.com/community/AppleKeyboard
https://wiki.archlinux.org/index.php/Silent_boot

6 Responses to Gentoo on MacBook Pro Retina Part 1: Base System

  1. Good morning,
    first of all thank you for the tutorial really well done.
    I would be grateful if you complete it installing gnome. I’m trying but beyond install X server and xterm I can not go.

Leave a Reply to Artem Butusov Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.