Как установить netbsd на virtualbox
This document will guide you through the setup of a NetBSD VM using VirtualBox to perform all your course work on. Please follow these steps as shown; if you run into problems or have questions, please send them to the class mailing list.
Installing your NetBSD VM
Creating a new VirtualBox Image

Select ‘New‘ and fill in the following values:

Accept all defaults after this, clicking ‘Continue‘ until the initial VM image is configured:

Configuring the new VM
Select the newly created image and go to ‘Settings‘:
Go to ‘System‘ and bump up ‘Hard Disk‘ in the boot order to the top.

We do this, so that we can initially boot off the CD, but then boot off the disk once the OS installed without having to eject the CD from the VM (although we will do that later, too).
Select the (empty) CD drive on the left-hand side, then select the disc icon on the right-hand side next to the ‘Optical Drive: IDE Secondary Master‘ option.

Select ‘Choose Virtual Optical Disk File. ‘.
Find the ISO you had downloaded before, i.e. /tmp/NetBSD.iso.

Select the first adapter, keep it as ‘NAT‘, select ‘Advanced‘ and then ‘Port Forwarding‘.
Add a new rule (upper right), and fill in:

If you want a dual-stack environment, and your network serves you an IPv6 address, you can enable another interface in bridge mode (NAT does not apply to IPv6):
To do that, select ‘Adapter 2‘, ‘Enable Network Adapter‘, and select ‘Bridged Adapter‘.
Finally, select ‘Ok‘ to commit your configuration changes.
(You may also wish to adjust the display size for the virtual machine. To do that, select the «Display» option and slide the ‘Scale Factor‘ slider to, say, 200%, then click ‘Ok‘.
Installing NetBSD
Start your newly created VM by selecting ‘Start‘.
The VM should start and get you to the NetBSD install screen, where we’ll follow a very basic NetBSD installation:

Select ‘Install messages in English‘, then leave the keyboard type ‘unchanged‘, then select ‘Install NetBSD to hard disk‘. Then:

After extraction is complete, ‘hit enter to continue‘, then configure the network:
This should get you a DHCP lease and an overall network configuration that we wish to commit to the system:
(If you enabled a second interface above for IPv6 only, then leave wm1 unconfigured; we will configure that interface manually further below.)
Back on the configuration screen, ‘Enable installation of binary packages‘ should be set to ‘install’. While not immediately necessary, this will allow you to later on install additional software via the pkgin tool, so is a useful step to complete here. Go ahead and hit ‘enter’, then select «Install pkgin and update package summary» at the bottom, accepting all other defaults.
‘Hit enter to continue‘.
The option ‘Fetch and unpack pkgsrc‘ can be disabled if you so choose — we won’t be using pkgsrc in this class, but if you’re interested, installing it doesn’t hurt.
Add your username, e.g., «jschauma«.
Note: it is required for this class to create and run your code as a non-root user, so this step is not optional.
Add the user to ‘wheel‘, so you can su(1).
Select a shell, e.g. /bin/sh and set a password.
(Note: we did not set a password for the root account. If you like, you can do that. You may also choose not to do that, but it’s important to understand why that might be acceptable: root is not allowed to log in remotely (which is one of the reasons why you had to create an additional user account), but any user on the system could run su(1) to become the super user without requiring a password.)
NetBSD requires users to be in the ‘wheel‘ group to run su(1), so only your newly created user should be able to do this.
This, together with the fact that the VM is intended for nothing of importance whatsoever may make it ok to not have any additional protections on the superuser account.)
Select ‘x: Finished configuring‘, then ‘Hit enter to continue‘.
Now you’re back at the main install menu, where we will perform a few minor configuration changes before we reboot, so select ‘x: Exit install System. This drops you into a shell. Mount the virtual disk and edit the file /etc/rc.conf on it:
If you want to enable the second network interface for IPv6 only connectivity, update dhcpcd_flags="-qM wm0" to become dhcpcd_flags="-qM wm0 wm1". Either way append the following lines, then write the file and quit (:wq):

If you are connected to an IPv6 enabled network, and you previously created the second network interface in bridged mode, then you can now configure it for IPv6 only. To do that, run the following command to append the right lines to /mnt/etc/dhcpcd.conf:
You also want to change the SLAAC address used by NetBSD, if you use IPv6. To do that:
Finally, unmount the disk and reboot the system. It should now boot into your newly installed system with the ISO still in the CD drive:

When the system comes up, it should display messages about DHCP etc. and ultimately present you with a prompt:

You can now log in and verify network connectivity (for IPv6 only if your network is IPv6 enabled and you did configure the second interface as described above), then eject the CD:
Finally, we also want to avoid having to use the VirtualBox application GUI every time we want to work with our VM. So instead of relying on the GUI to start our VM, we will use the command-line utility ‘VBoxManage’. To verify that this works as intended, let’s first shut down and power off our VM. For that, we need super-user privileges, which we gain via the su(1) command, and because we’re notoriously lazy, we immediately create another alias to save ourselves some typing:
And now to start the VM again, we create an alias in our parent OS, here assuming your login shell is bash(1):
Set up your VM for this class
With the VM now ready for use, you can next follow the steps to set up everything for use in this class. That will include configuration of SSH, configuring your development environment, and fetching all source code and code examples.
These steps are more or less the same for use of VirtualBox and UTM, and you can find them in this document.
Глава 2. Установка и начальная настройка
Документация по NetBSD в основном находится в формате страниц руководства man и предоставляет превосходное техническое описание системы. Не стану отрицать, что это не подходит для учебного пособия (не говоря о том, что Вы не сможете прочитать их без установки NetBSD); это повод для существования этого руководства.
Замечание
Конечно, Вы можете изучать страницы руководства через вэб интерфейс, но я не думаю, что это подходящий способ для изучения системы.
После установки Вы сможете найти некоторые руководства BSD в каталоге /usr/share/doc . Они разделены на три основных секции, psd (Дополнительная документация UNIX программиста), smm (Руководство системного администратора UNIX) и usd (Дополнительная документация пользователя UNIX). Вы можете читать текст на терминале с помощью, например:
или Вы можете сгенерировать вывод Postscript, используя Makefile s.
Неоспоримо, что этого недостаточно и поэтому Вам необходимо использовать максимум из имеющихся возможностей; релиз NetBSD содержит некоторые документы в текстовом формате и на сайте NetBSD Вы можете найти дополнительную информацию и коллекцию FAQ .
Оригинальная документация
Сайт NetBSD содержит документацию и руководства двух типов: общие и платформно-зависимые. Эта информация написана просто и обычно легка для понимания; например, Вы можете найти:
- как получить доступ к DOS/Windows разделам из NetBSD
- как запустить NetBSD из загрузчика Windows NT
- …
Все версии NetBSD содержат следующие файлы:
INSTALL.txt , INSTALL.ps , INSTALL.html Замечания по установке. Это самый важный документ и Вы должны внимательно прочитать (и перечитать его). Он содержит описание системы NetBSD, список поддерживаемого аппаратного обеспечения и, самое главное, инструкцию по установке. Страница руководства release (7) описание структуры NetBSD, выпуск которой Вы установили.
На вэб сайте NetBSD Вы можете найти, среди прочего, следующую документацию:
NetBSD FAQ основная информация и ссылки на другие FAQ . NetBSD/i386 FAQ NetBSD/i386 специфичный FAQ . NetBSD основы работы в сети руководство по сети и конфигурации PPP.
2.2. Схема установки NetBSD
Структура файлов установки NetBSD описана в вышеупомянутых файлах INSTALL.* . Например, для платформы i386 бинарные файлы располагаются в каталоге i386/binary/sets и исходные тексты в source/sets . Каталог source/patches содержит патчи к основному релизу, которые часто исправляют ошибки или проблемы безопасности, обнаруженные после выпуска.
2.3. Установка
Первое, что нужно сделать перед установкой NetBSD — прочитать информацию о релизе и замечания по установке в одном из файлов INSTALL.* : это официальное описание процедуры установки.
Далее, Вам необходимо решить какой носитель вы будете использовать. Вы можете выбрать следующее:
- FTP
- NFS
- CD-ROM/DVD
- floppy disk (гибкий диск)
- Unmounted filesystem (размонтированная файловая система)
- local directory (локальный каталог)
2.3.1. Клавиатура
Установочная программа NetBSD sysinst позволит вам сменить раскладку клавиатуры в процессе установки. Если по каким-либо причинам у Вас это не сработает, можно использовать схему из следующей таблицы.
| US | IT | DE | FR |
|---|---|---|---|
| — | ‘ | ? | ) |
| / | — | — | ! |
| = | ? | ‘ | — |
| : | ? | ? | M |
| ; | ? | ? | m |
| # | ? | § | 3 |
| « | ° | ? | % |
| * | ( | ( | 8 |
| ( | ) | ) | 9 |
| ) | = | = | 0 |
| ‘ | ? | ? | ? |
| ` | ^ | @ | |
| ? | # | ` |
Если вы используете клавиатуру не US, Вы должны сменить раскладку клавиатуры после установки.
2.3.2. Геометрия дисков
В установочной программе упоминается два типа геометрии жесткого диска. Вам необходимо понимать, что имеется ввиду:
- real geometry (реальная геометрия)
- BIOS geometry (геометрия BIOS)
real geometry это реальная геометрия жесткого диска, определенная системой. BIOS geometry это геометрия, используемая BIOS, и она может отличаться от реальной (например, BIOS может перепланировать диск с использованием LBA).
Диск, используемый в установочном примере, — IDE диск со следующей геометрией:
Как Вы можете видеть, BIOS перепланировала диск, используя LBA, эффективное снижение количества цилиндров и увеличение количества дорожек (но результат один: 6232 * 16 = 779 * 128 = 99712). Сектор содержит 512 байт, которые определяют размер диска в 6232 * 16 * 63 * 512 = 3 GB. NetBSD нет необходимости перепланировать геометрию диска (и, в сущности, она не хочет этого делать). В процессе установки возможно изменение геометрии вручную, если sysinst делает это неправильно.
2.3.3. Разделы
Терминология, используемая в NetBSD для разбиения, отличается от типичной терминологии DOS/Windows. Фактически здесь имеется две схемы разбиения: NetBSD устанавливается в один из первичных разделов BIOS (разделы определяются в таблице разделов жесткого диска).
Внутри этого BIOS раздела (также называемого slice (англ.; часть, доля)) NetBSD определяет BSD разделы, используя disklabel : эти разделы можно увидеть только из NetBSD и они идентифицируются буквами в нижнем регистре (начиная с « a »). Например, wd0a указывает на раздел « a » первого диска IDE (wd0) и sd0a указывает на раздел « a » первого диска SCSI. В Рисунок 2.1, «Разделы», где имеется два первичных BIOS раздела, один используется DOS, а другой NetBSD. NetBSD описывает структуру диска через метки диска.
Рисунок 2.1. Разделы
Замечание
Смысл раздела « c » и « d » типичен для реализации платформы i386. Другие реализации используют отличные от данного соглашения (т.е. « c » обозначает весь диск.)
Замечание
Если NetBSD разделяет жесткий диск с другими ОС (как в предыдущем примере) Вам, вероятно, необходимо установить загрузочный менеджер , т.е. программу, позволяющую Вам выбирать ОС во время загрузки. sysinst может это для Вас сделать и сконфигурировать простой, но эффективный менеджер загрузки.
2.3.4. Требования к размеру жесткого диска
Объем, необходимый для установки NetBSD, зависит от того, какую установку Вы планируете выполнять (т.е. сервер или рабочую станцию). Например, рассмотрим домашний компьютер с жестким диском на 420 MB (несколько маловат по сегодняшним меркам) с системой X, исходными текстами ядра и несколькими приложениями (Netscape, …). Раздел swap — 32 MB. df покажет следующее:
Как Вы видите, в NetBSD 225 MB свободного места всего, из них 120 MB в файловой системе /usr для Вас и Ваших файлов.
2.3.5. Повторим
Когда Вы устанавливаете ОС впервые, то успех редок и NetBSD не исключение. Даже если все идет хорошо, так скоро, как Вы начнете использовать систему, Вы, скорее всего, поймете то, (например) что Вам необходимо выбрать лучшую схему для Вашего раздела. Главное не отказаться от этого, если Вы попробуете снова реализовать то, что так сложно для понимания в первый раз. Мало-помалу придет прояснение достоинств за счет накопления опыта и количества перечитываний документа INSTALL.* .
В процессе первой инсталляции разумнее одобрить предложения по умолчанию sysinst и избегать, например, изменения разметки дисков.
Virtualization and Cloud Computing
137, 0 
I use Ubuntu 9.04 as desktop operating system and I want to make some tests on NetBSD. I tried to install as a virtual sistem on VirtualBox but it doesn’t want to install. You can see the error in the attached file.
Do you guys have any clue about what the problem could be?
111, 0 
It’s hardware issue. Virtualbox hardware is not properly recognized by NetBSD. Here is what I got from virtualbox site:
137, 0 
Thanks for your answer, Nitin!
I disabled ACPI. IO APIC was already disabled. Unfortunately the "Enable VT-x/AMD-V" options is not active. It still doesn’t work. I guess that my CPU doesn’t support this option. Could this be the problem? I installed other operating systems and it installed without any problem — Ubuntu, CentOS, FreeBSD, OpenSolaris, Windows XP.
111, 0 
What version of NetBSD are you trying to install? I don’t think host OS (i.e. Ubuntu) and your hardware have anything to do with it. Especially, if you said that you were able to install other OS’s. It’s Virtualbox. Another OS you can try is FreeBSD or OpenBSD. They are very closely related to each other.
Sorry, I’m not very big on BSD troubleshooting. I just prefer to use Mac
Try Xen or Vmplayer. Vmplayer (from Vmware) should definitely work. I think you can download some pre-made BSD images/appliances from Vmware site. Virtualbox will also play Vmware vmdk files. Also there is a hack way to make your own images on Vmplayer. But I won’t go there yet!
Как установить netbsd на virtualbox
It is possible to install NetBSD together with other operating systems on one hard disk.
If there is already an operating system on the hard disk, think about how you can free some space for NetBSD; if NetBSD will share the disk with other operating systems you will probably need to create a new partition (which you will do with sysinst ). Oftentimes this will not be possible unless you resize an existing partition.
Unfortunately, it is not possible to resize an existing partition with sysinst , but there are some commercial products (like Partition Magic ) and some free tools ( GNU Parted , FIPS , pfdisk ) available for this.
You can also install NetBSD on a separate hard disk.
Advice
Unless you are comfortable with setting up a partitioning scheme for two or more operating systems, and unless you understand the risk of data loss if you should make a mistake, it is recommended that you give NetBSD its own hard disk. This removes the risk of damage to the existing operating system.
2.1.2.�NetBSD on emulation and virtualization
It is possible to install and run NetBSD on top of other operating systems without having to worry about partitioning. Emulators or virtualization environments provide a quick and secure way to try out NetBSD. The host operating system remains unchanged, and the risk of damaging important data is minimized.
Information about NetBSD as a Xen host and guest system is available on the NetBSD/xen web page.
The NetBSD on emulated hardware web page provides detailed information about various emulators and the supported NetBSD platforms. It should also be noted that NetBSD runs as a VMware guest.
2.2.�Install preparations
2.2.1.�The INSTALL document
The first thing to do before installing NetBSD is to read the release information and installation notes in one of the INSTALL files: this is the official description of the installation procedure, with platform-specific information and important details. It is available in HTML, PostScript, plain text, and an enhanced text format to be used with more . These files can be found in the root directory of the NetBSD release (on the install CD or on the FTP server). For example, the amd64 install instructions are available at ftp.NetBSD.org/pub/NetBSD/NetBSD-9.3/amd64/INSTALL.html
2.2.2.�Partitions
The terminology used by NetBSD for partitioning is different from the typical DOS/Windows terminology; in fact, there are two partitioning schemes involved when running NetBSD on a typical PC. NetBSD installs in one of the four primary BIOS partitions (the partitions defined in the hard disk partition table).
Within a BIOS partition (also called slice ) NetBSD defines its BSD partitions using a disklabel . These partitions can be seen only by NetBSD and are identified by lowercase letters (starting with “ a ” ). For example, wd0a refers to the “ a ” partition of the first IDE disk (wd0) and sd0a refers to the “ a ” partition of the first SCSI disk. In Figure�2.1, “Partitions” there are two primary BIOS partitions, one used by DOS and the other by NetBSD. NetBSD describes the disk layout through the disklabel.
Figure�2.1.�Partitions
The meaning of partitions “ c ” and “ d ” is typical of the amd64 port. On most other ports, “ c ” represents the whole disk.
If NetBSD shares the hard disk with another operating system (like in the previous example) you will want to install a boot manager , i.e., a program which lets you choose which OS to start at boot time. sysinst can do this for you and will ask if you want to install one. Unless you have specific reasons not to, you should let sysinst perform this step.
2.2.3.�Hard disk space requirements
The exact amount of space required for a given NetBSD installation varies depending on the platform being used and which distribution sets are selected. Generally speaking, if you have a few GB of free space on your hard drive, you will have enough space for a full installation of the base system.
2.2.4.�Network settings
If you plan to fetch distribution sets over the network (not necessary if you downloaded a full-size install ISO) and do not use DHCP, write down your basic network settings. You will need:
Your IP address (example: 192.168.1.7)
the netmask (example: 255.255.255.0)
the IP address of your default gateway (example: 192.168.1.1)
the IP address of the DNS server you use (example: 145.253.2.75)
2.2.5.�Backup your data and operating systems!
Before you begin the installation, make sure that you have a reliable backup of any operating systems and data on the used hard disk. Mistakes in partitioning your hard disk can lead to data loss. Existing operating systems may become unbootable. «Reliable backup» means that the backup and restore procedure is tested and works flawlessly!
2.2.6.�Preparing the installation media
The NetBSD installation system consists of two parts. The first part is the installation kernel. This kernel contains the NetBSD install program sysinst and it is booted from the install media (e.g, CD/DVD, USB drive, memory card, etc.). The sysinst program will prepare the disk: it separates the disk space into partitions, makes the disk bootable and creates the necessary file systems.
The second part of the install system is made up of the binary distribution sets: the files of the NetBSD operating system. The installer needs to have access to the distribution sets. sysinst will usually fetch these files from the install media you booted from, but it can also fetch them via FTP, NFS, or a local filesystem.
The NetBSD Project provides complete install media for every supported hardware architecture. This is usually in the form of bootable CD images ( .iso files).
2.2.6.1.�Booting the install system from USB
To use a bootable USB install image (on amd64, i386), download the img.gz file for your hardware architecture, decompress and copy the image to a USB. For example on a Unix-like system you may use:
Examples of your-usb are /dev/rsd0d (NetBSD), /dev/sda (Linux).
Caution
Selecting the wrong device in dd may destroy your current system. Double-check it isn’t mounted and is your USB stick. It should appear at the bottom of dmesg on connect, for example, if you see:
on NetBSD, you will want to select /dev/rsd0d .
2.2.6.2.�Booting the install system from CD
To use a bootable NetBSD install CD, download the iso file for your hardware architecture and burn it to a CD or DVD. You will need to handle this step alone, as burning programs vary widely. Ensure that your computer is set up to boot from CD-ROM before hard drives, insert the disc, and reboot the computer.
2.3.�Checklist
This is the checklist about the things that should be clear and on-hand now:
Available disk space
Bootable medium with the install system
CD/DVD or server with the distribution sets
Your network information (only if you will be fetching distribution sets via the network and do not use DHCP)