Linux raspberry pi 4 ssd

Raspberry Pi. Загрузка с USB-накопителя

Не так давно я описывал процесс установки сервера Home Assistant на Raspberry Pi и упоминал недостаток подобной системы: работающий Home Assistant может довольно быстро «убивать» microSD-карточки интенсивными операциями чтения-записи.

Выход из ситуации — установка системы на внешний HDD или SSD диск и загрузка микрокомпьютера с него.

Что нам понадобится

Для осуществления описываемых в этой статье действий понадобится:

  • Raspberry Pi 3 / 4
  • Внешний накопитель с USB-интерфейсом
  • microSD-карта (только для Raspberry Pi 3)

Хорошая новость — все свежие модели микрокомпьютеров линейки Raspberry Pi «из коробки» поддерживают загрузку с USB-накопителей. И только на старых моделях эту возможность нужно активировать вручную.

Активация загрузки с USB на Raspberry Pi 2 / 3

Для нужно загрузиться в Raspberry Pi OS с microSD-карты и добавить строчку с командой в файл config.txt:

А затем перезагрузить систему:

Во время следующей загрузки команда будет обработана и пропишет активирующее возможность загрузки с USB-дисков значение в OTP-память микрокомпьютера. Данная операция необратима. Но волноваться по этому поводу не стоит: активация USB Boot Mode не лишит вас возможности запускать «малинку» с microSD-карты, а всего лишь добавит новую опцию, которая активна по умолчанию в более свежих моделях микрокомпьютера.

Также обращу внимание, что из config.txt строка program_usb_boot_mode=1 сама по себе никуда не денется, поэтому после перезагрузки ее желательно оттуда удалить.

Установка системы

Установка операционной системы для Raspberry Pi на USB-накопитель ничем принципиально не отличается от установки на microSD-карту: нам все также потребуется скачать образ нужной системы и записать его на подходящий диск.

Удобнее всего использовать для этого специальную утилиту Raspberry Pi Imager, доступную под Windows, Ubuntu и macOS. В отличие от универсальных приложений для записи образов (Rufus, Win32DiskImager, balenaEtcher и т.п.), она может работать не только с локально хранящимися файлами, но и выкачивать нужный образ с сайта Raspberry Pi Foundation прямо в процессе записи.

Выбираем нужный образ из списка:

Выбираем накопитель для записи:

И дожидаемся окончания процесса:

На этом все. Но если в дальнейшем планируется использовать Raspberry Pi в headless-режиме, то стоит сразу закинуть в корень получившегося загрузочного диска пустой файл с названием «ssh» без расширения. А если для подключения к сети будет использоваться беспроводной интерфейс, то туда же в корень нужно добавить файл wpa_supplicant.conf с данными для подключения к точке доступа:

Загрузка

Извлекаем из Raspberry Pi microSD-карточку с системой, подключаем к USB наш внешний диск и подаем питание.

Начнется загрузка с внешнего диска и через десяток-другой секунд система будет готова к работе.

Заключение

Легкость перевода Raspberry Pi на загрузку с USB-накопителей — еще один довод за покупку микрокомпьютеров именно этой линейки.

Буквально 10 минут работы позволяют в разы повысить надежность системы, отказавшись от использования карточек памяти с ограниченным ресурсом в пользу твердотельных накопителей или обычных HDD.

Источник

Move your existing Raspberry Pi 4 Ubuntu install from SD card to USB/SSD

Raspberry Pi 4 recently started supporting booting from SSD drives directly rather than using a slower, more fragile SD card.

Although, there’s a lot of content describing how to create a new system on SSD, it doesn’t seem like there’s a good summarizing article describing how to take your existing Ubuntu install, with all your existing server configurations and files etc, and move that existing install from SD card to SSD.

I’ll try to answer the many unclear steps in the process.

Preamble

  • Raspberry Pi’s bootloader has a 2020/09/03 version that just started supporting booting from SSD.
  • Ubuntu 20.10 supports booting from SSD “out-of-the-box” without messing with the boot folder’s kernel files yourself.

Given the above and given the assumption that you bought your Raspberry Pi 4 before September 2020 and you already have a unmount .

Then byte-wise copy everything from the SD card into a file.

Update your Ubuntu to 20.10

Ambiguity 1: can any existing Ubuntu install be booted from SSD.
Answer: sort of. Assuming you don’t want to go through the trouble of manually configuring your boot partition , just upgrading to 20.10 might be the easiest solution.

While still booted in your SD card install, upgrade to 20.10.

Ambiguity 2: do all Ubuntu variants’ 20.10 support external USB/SSD?
Answer: yes, it doesn’t matter if you have Desktop/Server or Ubuntu MATE etc.

See lsb_release -a for your current Ubuntu version (which is probably not 20.10 if you’re reading this).

First stay updated

If you’re on Server, you might need to install the update manager

If you started off with something like 20.04 which is a long term support version, it’ll stay on that track and not update to 20.10 unless you change the track. Use your favorite editor:

If it said Prompt=lts , change it to Prompt=normal .

Save the file. Then

Give it a while to upgrade. Then confirm you have 20.10 by running lsb_release -a again.

Update your bootloader

Prep work #2, you need to update the bootloader as mentioned above.

Ambiguity 3: it seems like Raspbian OS has a dedicated tool to do all the bootloader management stuff, what do I do in Ubuntu?
Answer: as far as I can tell, the Raspbian tool isn’t special. You can just install the package in Ubuntu.

Get the bootloader tool

Then check your current bootloader version to see if you need to do anything. The bootloader also has tracks. Critical or stable.

The 2020/09/03 version is the latest critical version with the stable version being monthly and having more recent versions. Just opting here to be conservative and update to 2020/09/03.

If yours already says something like

you can skip this whole section. Otherwise, there’s a whole bunch of ways of tweaking your bootloader configs and update your version etc, but the easiest 1 step way is:

This opens an editor (that you specified in your $EDITOR, or just opens nano) with the bootloader configuration displaying. Here, if you’d like to customize the order of boot for your Raspberry Pi, you can do so by adding a BOOT_ORDER row (details here).

BOOT_ORDER=0xf41 will try SD card first, then USB. If neither works, the Raspberry Pi reboots and retries everything again.

BOOT_ORDER=0xf14 does the reverse. Tries USB first, then the SD card. Then if both fail, reboot and retry again.

Save and exit the file. It should then prompt something like the bootloader will be re-written on the next boot. Double check that the bootloader image being written looks something like

Читайте также:  Skype выбрать для windows

Copy your SD card to an SSD

Ambiguity 4: will the Raspberry Pi pump enough power through USB to power my portable SSD enclosure?
Answer: magnetic drives will use more power. But if you supplied a full 3A to your Raspberry Pi, it should work. I used a Samsung T7 SSD. If it doesn’t, you can use a powered USB hub.

At this point, don’t reboot yet, since you don’t have an SSD card with your OS yet.

There’s a bunch of ways you can do this. I used this script https://github.com/billw2/rpi-clone, which worked fine for me. To “install” it, just clone the GitHub repo and move it. See https://github.com/billw2/rpi-clone#on-other-os.

It just uses a combination of dd for the first partition and rsync for the second partition to not copy some junk over like /tmp/ etc.

Connect your SSD at this point. It should get recognized automatically. Run

to find its name (probably something like sba depending on how many USB drives you have connected).

Then just run the rpi-clone thing

replacing sba with the location of your drive as needed.

The script will ask you for a label. It’s actually important since your SD card’s boot partition’s configuration (and thus your future SSD boot partition’s configuration) actually specifies how to find the drive to mount as root. In this case, the coupling is really loose. The configuration file is at /boot/firmware/cmdline.txt . There’s a part in that file that says root=LABEL=writable . That’s the label. So your label (the script asks for the label of the second partition) must be writable .

At this point, you can try shutting down your Raspberry Pi, removing the SD card and try booting again. If it works, you’re done.

Update the boot folder

In my case, upgrading to 20.10 didn’t actually update the boot folder on my SD card in the first place. I had to do it manually to get everything to work.

Using the same SD that’s now copied to the SSD (you did backup right?) or with a different SD card, write a fresh Ubuntu 20.10 install.

Specifically, go to https://www.raspberrypi.org/software. The easiest way is to download an imager tool for another machine’s OS. The burn a new 20.10 (server or otherwise) install on an SD card.

Then boot into that card (by removing the SSD first if needed). The default Ubuntu ssh password is ubuntu and ubuntu . Once in, then mount the SSD drive again by plugging it in, then finding the name of the drive with lsblk .

Mount it to a mount point, such as

Then copy off everything from the new Ubuntu install’s boot folder (mounted by default to /boot/firmware to the SSD. Such as via

Old Ubuntu versions have a bunch of other kernels and firmware for older Raspberry Pi hardware. The 20.10 image seems cleaner so —delete gets rid of all the old files too.

Shutdown, remove the SD card and reboot and it should work now.

Источник

Raspberry Pi 4 / 400 Ubuntu USB Mass Storage Boot Guide

Official support from Canonical for the Raspberry Pi has come a long way. We can now install officially supported Ubuntu on the Pi! In my previous guide for Ubuntu 18.04 on the Pi the Raspberry Pi was not officially supported yet and to be honest the experience was pretty janky.

The previous LTS “unofficial” release had so many problems I actually rolled my own image with dozens of fixes to common ailments before I quickly realized that maintaining a Linux distro, even in such a limited capacity as patching in and distributing fixed binaries, was a monumental undertaking.

Fortunately the current Ubuntu 20.04 LTS release is officially certified for the Raspberry Pi. This combined with Ubuntu’s full 64 bit userland/system environment allows you to take full advantage of the 8 GB Pi’s memory without per-process 3GB memory limits (very useful if you are doing something like running a Minecraft server and want to allocate almost all of the 8 GB to it) means there has never been a better time to give Ubuntu a try on the Pi.

This guide takes it a step further and shows you how to get Ubuntu 20.04 / 20.10 / 21.04 / etc. working with a SSD. Let’s get started!

Equipment Used

The Kingston A400 has been a great drive to use with the Pi for years. It’s reliable, widely available around the world, has low power requirements and performs very well. It’s also very affordable. This drive has been benchmarked over 1000 times at pibenchmarks.com and is the #1 most popular SSD among the Pi community!

Both the USB 3.0 and USB 3.1 variants of the StarTech 2.5″ SATA adapter work well with the Pi 4. I’ve used the 3.0 variant with my Pi 4 since launch and it has always worked well. I later bought the 3.1 variant and had the same positive experience. These two adapter variants are my go to adapters for all my Pi related projects that need a fast and easy 2.5″ SATA SSD!

NVME Option (powered USB hub required, see “Power Requirements” section in my more generalized Raspberry Pi 4 USB booting guide):

The Samsung 970 EVO Plus is a fantastic drive and has fallen in price substantially. It’s widely available around the world. The smaller capacities (such as the 250GB version) of this drive are perfect for the Pi! This is the top performance option without going into the “Pro” series of the lineup which are much more expensive.

If you really want to take things over the top the ASUS Rog Strix M.2 NVMe enclosure uses the latest USB 3.2 Gen2 specification, is RGB capable and works with the Pi! Unsurprisingly, adding the extra lighting does take extra power! A powered USB hub is also required for this enclosure. More widely available than the ICY BOX but tends to be on the expensive side.

Prerequisites

Check your Raspberry Pi’s power supply size and make sure it is delivering at least 3.5A. There are a lot of USB C adapters for the Raspberry Pi that are only 3.0A. These will typically work fine, until you plug in something like a SSD which draws power from the Pi and there is nothing left to give.

Most SSDs are quite power efficient but HDDs draw significantly more. Older generations of SSDs used quite a bit more power than newer ones as well. If you are using an older drive or a drive that you know is power hungry you need to pay extra attention to having a quality power source with plenty of capacity.

A good alternative option to relying on the Pi to power the drive is using a powered USB hub* so your drive doesn’t need to draw power from the Pi’s limited power budget. Make sure you get one that is compatible with the Pi as some powered USB hubs won’t work properly with it so check the reviews and do your research to make sure people are using it successfully with the Pi.

Using a 3.5A power supply* or powered USB hub* will ensure your drive is getting enough power without impacting the Pi’s stability.

The Sabrent powered USB hub delivers a whopping 2.5A of dedicated power for your USB attached devices. This is almost as much as the Pi adapter itself is rated for (3.0A). It will easily power the most thirsty of setups such as NVMe enclosures.

Читайте также:  Драйвер для qualcomm hs usb qdloader 9008 для windows х86

Note: Make sure Amazon doesn’t try to take you to the non-powered version and that it’s the one with the AC adapter that plugs in to provide extra power

The CanaKit 3.5A adapter has an extra half an amp (500 mA) of capacity to give some breathing room to your accessories. This is bigger than the official Pi power supply which provides 3.0A.

Verify Storage Adapter Compatibility

You will need a USB 3.0 storage adapter. See my other article on USB booting not specific to Ubuntu for a lot more details on the storage adapters!

Get Latest Raspbian & Updates

To update your bootloader / firmware you should use Raspbian on a SD card. Right now support in third party operating systems to do anything with the new Raspberry Pi 4’s firmware or bootloader is very limited / nonexistent. You can use a third party operating system later once you set the boot mode, but to actually make these changes we will use official Raspbian.

First make sure that you have the absolute latest updates and firmware for the Pi. To upgrade all your packages and firmware to the latest version use the following command:

Once the update has completed restart your Pi with a sudo reboot command to apply the latest firmware / kernel updates.

Verify EEPROM Bootloader is up to date

We can check if your Pi’s bootloader firmware is up to date with the following command:

If your Raspbian is *very* out of date you may not have this utility and can install it using:

The output from rpi-eeprom-update will look like this if you are not up to date:

If it says any updates are available they be installed manually by adding ‘-a’ to the end of our previous command like this:

After the updates finish installing restart your Pi as firmware updates will not be applied until after a reboot. Now if you run rpi-eeprom-update to check for updates again it should say you are on the latest and up to date!

Changing rpi-eeprom’s Release Channel

Note: As of February 16th the firmware available in the “critical” branch is new enough to USB boot so I no longer recommend changing this. One reader even let me know in the comments that on the “stable” channel his storage was getting corrupted prompting a full reinstall!

By default you will only receive updates from Raspbian’s “critical” channel. This is a very conservative firmware update channel that will only give you very well tested firmware updates that are considered critical fixes for the device. Another channel that is available is “stable”.

Carlos and other commenters have reported that the current “critical” firmware didn’t work for them and they had to upgrade to the “stable” channel.

To switch to the stable channel we are going to edit the file /etc/default/rpi-eeprom-update:

Change the line FIRMWARE_RELEASE_STATUS=”critical” to:

Now you can run sudo rpi-eeprom-update and you should see a new update available.

Install Ubuntu on USB Storage Device

The new official Raspberry Pi imaging tool is really good. It’s available on Windows, Linux and MacOS and is a small and fast download. It also works fine on most USB mass storage devices like SSDs. Since Ubuntu is now officially supported the image itself is also available in this tool which saves you the trouble of having to find and download the right image files.

64 bit images are recommended for the Pi 4 for better performance but the 32 bit images work as well.

If you want to do things the traditional way you can download the image from the main Ubuntu site and write it yourself using Etcher / dd / Win32diskimager / your preferred tool and skip to the next section. It’s recommended to create the media with the Raspberry Pi Imager unless you are having problems with that utility or are using this as a troubleshooting step.

Once you’ve downloaded the tool run it as administrator/sudo to avoid permission errors. To run the utility from the command line is usually sudo rpi-imager. You’ll be greeted with this screen:

Next click the “Choose OS” button:

Ahh, the benefits of being officially supported! Ubuntu is right there on the list waiting for us. Select the Ubuntu option and you will get the different choices of flavors/architectures. There’s Ubuntu Desktop, Ubuntu Server, and Ubuntu Core in various forms of 64-bit (arm64) and 32-bit (armhf).

If you want to use the out-of-the-box Ubuntu Desktop edition you need to use the 64 bit Ubuntu 20.10 image as they never made a 20.04 desktop version for some reason. This really isn’t usually a big deal though because you can always choose the “Server” version and install Ubuntu’s desktop environment later with:

Once you’ve selected the edition you want go ahead and pick the “Choose SD Card” option and write the image. Despite not being a SD card my USB mass storage devices showed up anyway (writing the guide I used a StarTech adapter and a Kingston A400 SSD).

I’m sure some of you will manage to find unusual devices and configurations that may not show up in this tool. It doesn’t appear to show “fixed drives” that are physically installed in your machine. Regardless if it is causing a headache you may need to do it the old fashioned way and download the image from the main Ubuntu site and write the image using your favorite imaging tool instead.

Modifying Ubuntu for USB Booting

We need to make some changes to the Ubuntu drive we just created before we boot from it. Make sure your Pi is powered on and booted into Raspbian then plug in your newly imaged Ubuntu drive. We are going to make the changes using the Pi.

Find and Mount Storage Device

First let’s find your storage device using the command:

This will show you all the storage devices attached to your system:

Your SD card will always start with mmcblk so you can rule that one out. That leaves sda as the only other disk device on the system. This will be the same for most of you but depending on what type of drive and storage adapter you use this can vary. You can substitute whatever yours is in place of /dev/sda in these instructions going forward. If yours is sdb use /dev/sdb. If it’s nvme0 use /dev/nvme0, etc.

In my output under the “MOUNTPOINT” column you can see it is blank. This means the drive isn’t mounted on my system. My mmcblk0p1 mountpoint though is not blank and is “/boot” as an example of a non-blank mountpoint. If you are using the full “Desktop” version of Raspbian it may have automatically mounted your drive and created 2 shortcuts on your desktop that will take you to the files. If your mountpoint is not blank and has something like /media/pi/writable go ahead and unmount them now using the following commands substituting the mountpoint listed for your drive:

Читайте также:  Выключение микрофона горячими клавишами windows 10

Now we are going to create two mountpoints and mount the Ubuntu drive. Use these commands substituting your own drive it is not /dev/sda:

Once you have mounted everything correctly your lsblk command’s output should look like this with the mountpoint field now populated:

Modify Mounted Partitions – Option A – Automated Script

If you just want to get your Ubuntu partition bootable I have made an automated script to do this. As long as you have mounted the partitions as /mnt/boot and /mnt/writable the script will make the necessary changes for Ubuntu 20.04 / 20.10 to boot! The source code for the script is available at https://github.com/TheRemote/Ubuntu-Server-raspi4-unofficial/blob/master/BootFix.sh

Here is a one liner to run the script:

You may also download it for inspection (such as nano BootFix.sh or opening it in the Text Editor if you are using Desktop Raspbian) with:

To execute the script use:

As long as you mounted your partitions correctly it will modify the partition and tell you that it was successful. Now unmount your partitions with the following commands:

You may now shut down your Pi and remove the SD card from the Pi leaving just the USB mass storage device plugged in. Reconnect the power.

Modify Mounted Partitions – Option B – Manual Instructions

See bottom of the article for the manual instructions section

First Boot

If all went well the system should boot up into Ubuntu’s logon screen! The default credentials are:

Before logging in for the first time you will be forced to select a new password. Once you have done that you will be fully logged in!

Once the patching is finished your shiny new Ubuntu 20.04 system is fully ready to use!

Manual Instructions

These are the manual instructions to recreate what the automated script does. If you used the automated script you don’t need to do anything further in this section unless you want to understand more about how it works or you want to do the process manually.

Decompress the kernel

We need to decompress the kernel as we will be changing the way the Pi is booting. Ubuntu uses u-boot by default and we will be switching away from that. We can do this with the following command:

Update config.txt with correct parameters

Now let’s update /mnt/boot/config.txt with the parameters we need to load the decompressed kernel. Open up config.txt with nano with:

Change the [pi4] section to the following contents:

Create script to automatically decompress kernel

We are going to create a script to automatically decompress the kernel. If we don’t do this we have to decompress it every time Ubuntu updates. This particular part of the script was not written by me and was found at the post on the Raspberry Pi forums by egrechko.

First let’s create the decompression script. Open up a new file with nano using:

Paste the following contents:

Create apt script to call kernel decompression script automatically

This is a one liner to create a script to call the auto_decompress_kernel script:

Verify Drive Performance

You can make sure everything is running correctly (and as fast as it should be) by running my quick storage benchmark. You can run the benchmark with the following one-liner:

This will give you a score you can compare to the other Raspberry Pi Storage Benchmark results and make sure that you are getting an equivalent speed to your peers with the same device!

Fix (some) USB Adapter Problems Using Quirks

Some storage adapters don’t work very well with the Raspberry Pi 4. There is an option that can get a lot of them working using quirks. If your Ubuntu is booting to emergency mode but not in normal mode it’s worth giving quirks a try. This lowers performance, but it’s still much faster than a SD card and your adapter won’t go to waste.

To find out the quirks mode string to use we need to find the device ID string for your adapter and then add an entry to cmdline.txt telling the kernel to apply them on boot.

Find Your Adapter

To apply the quirks we first need to get the adapter id. We will use the sudo lsusb command:

On line 2 we can see my ASM1051E SATA 6Gb/s bridge adapter (it’s the known working StarTech.com 2.5″ SATA to USB 3.1* adapter). You will see something very similar to mine when you run the command and it shouldn’t be too hard to figure out which device it is. If you need more information add a -v switch to make the command sudo lsusb -v. This can sometimes add some additional details to make it easier to figure out which one is your adapter.

If you’re still not sure, we have another command that between the two that can narrow things down. Type / paste the following:

This is the dmesg log showing the hardware detection as hardware is activated on the Pi. If your log is really long you can generate fresh entries by just unplugging a device and plugging it back in and running the command again. Here we can clearly see that the ASM105x is what our StarTech adapter is being detected as.

Now we can go back to our first lsusb command and we want the 8 characters from the ID field that comes right after the Device:

Our adapter’s ID is: 174c:55aa

Applying Quirks

To apply the quirks to our USB adapter we are going to edit /boot/firmware/cmdline.txt. Type:

We are going to add the following entry into the very front of cmdline.txt:

In place of the X’s above you will put in your adapter’s ID that we got before. With the example commands I gave above mine would look like this: usb-storage.quirks=174c:55aa:u. After this my cmdline.txt looks like this (everything should be one continuous line, no line breaks!):

Now reboot the Pi. If the Pi fails to boot you can plug the SD card into the computer and go to /boot/cmdline.txt and undo the change we did so you can boot back in with your SD card.

Verifying Quirks

Once you have rebooted after changing cmdline.txt we can verify the quirks have been applied by doing another dmesg | grep usb command:

This time we can see in dmesg that UAS was blacklisted for the device and it has loaded with the usb-storage driver instead. This driver tends to be more compatible with the “problematic adapters” but the performance is usually significantly lower. It’s definitely worth a try though as some adapters do better with the quirks performance-wise. The only way to know for sure is to run a benchmark (see “Verify Drive Performance” section).

Other Resources

To find out where to get the 64 bit version of Raspberry Pi OS: where to get the 64 bit Raspberry Pi OS image

To find out how to add a UPS backup battery to your Pi check out my UPS for Raspberry Pi guide

To reduce your CPU usage by 1% when USB booting check out my reducing 1% CPU usage while booting from mass storage device guide here

Источник

Оцените статью