Zfs для windows 10

Файловая система ZFS

В наши дни все большей и большей популярности набирают файловые системы следующего поколения, которые имеют более широкую функциональность, чем в обычных файловых системах. Одни из таких файловых систем — это Btrfs и ZFS, Обе они уже стали достаточно стабильными и активно применяются пользователями. Для многих пользователей очень важна сохранность данных, и такие файловые системы могут обеспечить ее наилучшим образом.

В одной из предыдущих статей мы рассматривали файловую систему Btrfs. В нашей сегодняшней статье мы остановимся на ZFS, эти файловые системы похожи по своему применению и назначению, но имеют некоторые отличия. Мы рассмотрим как установить эту файловую систему в вашем дистрибутиве, настроить ее и использовать для решения повседневных задач.

Что такое ZFS?

ZFS — это файловая система, объединенная с менеджером логических томов. Ее разработка началась в компании Sun Microsystems для ОСhttps://losst.ru/fajlovaya-sistema-btrfs Solaris. Файловая система выпускалась под открытой лицензией Common Development and Distribution License (CDDL). Она была предназначена для высокопроизводительных серверов, поэтому уже тогда поддерживала мгновенные снимки и клонирование данных. Но после покупки ее компанией Oracle, исходный код был закрыт, а сообщество создало форк последней доступной версии под именем OpenZFS. Именно эту файловую систему сейчас и можно установить и использовать.

Файловая система ZFS имеет обычные для таких файловых систем возможности. Это просто огромный размер одного раздела, и размер файла, поддерживается возможность хранения файлов на нескольких устройствах, проверка контрольных сумм для данных и шифрование на лету, а также запись новых данных в режиме COW, когда данные не переписываются, а пишутся в новое место, что позволяет делать мгновенные снапшоты.

Возможности очень похожи на Btrfs, но есть кое-какие отличия. В Btrfs можно посмотреть все файлы, измененные с момента последнего снапшота. Второе отличие, это отсутствие в Btrfs логических блоков zvol.

Установка ZFS

В последних версиях Ubuntu файловая система ZFS была добавлена в официальный репозиторий и в установочный диск. Поэтому для того, чтобы ее установить будет достаточно выполнить несколько команд:

sudo apt install -y zfs

В других дистрибутивах. например, CentOS или Fedora ситуация немного сложнее, сначала вам придется добавить официальный репозиторий, а затем установка zfs и самого набора утилит и модулей ядра:

sudo yum install http://download.zfsonlinux.org/epel/zfs-release.el7_3.noarch.rpm
$ sudo yum install zfs

Затем осталось включить загрузить модуль ядра с поддержкой этой файловой системы:

sudo modprobe zfs

Теперь файловая система установлена и готова к использованию. Дальше нам нужно выбрать разделы и создать на них файловые системы. Для настройки zfs используется утилита zpool, но для начала давайте рассмотрим ее синтаксис и возможности. Файловая система может быть расположена на нескольких разделах или жестких дисках, поэтому на уровне ядра формируется общий пул (куча), а к нему уже подключаются разделы. Тут можно провести аналогию с группой томов LVM.

Команда zpool

Это основной инструмент управления разделами и функциональными возможностями ZFS, поэтому вам важно его освоить. Общий синтаксис команды достаточно прост, но у нее есть множество подкоманд, которые имеют свой синтаксис и параметры:

$ zpool команда параметры опции устройства

Как я уже сказал, параметры и опции для каждой команды свои, а в качестве устройства может указываться пул или физический раздел на жестком диске. Теперь рассмотрим основные команды и их предназначение, чтобы вы могли немного ориентироваться, а более детальные параметры разберем уже на примерах:

  • add — добавить раздел к существующему пулу;
  • attach — добавить раздел или жесткий диск к пулу файловой системы;
  • clean — очистить все ошибки дисков;
  • create — создать новый пул из физического раздела, на котором будут размещены виртуальные диски;
  • destroy — удалить пул разделов zfs;
  • detach — отключить физический раздел от пула;
  • events — посмотреть сообщения ядра, отправленные модулем zfs;
  • export — экспортировать пул для переноса в другую систему;
  • get — посмотреть параметры пула;
  • set — установить значение переменной;
  • history — отобразить историю команд zfs;
  • import — импортировать пул;
  • iostat — отобразить статистику ввода/вывода для выбранного пула zfs;
  • list — вывести список всех пулов;
  • offline/online — выключить/включить физическое устройство, данные на нем сохраняются, но их нельзя прочитать или изменить;
  • remove — удалить устройство из пула;
  • replace — перенести все данные со старого устройства не новое;
  • scrub — проверка контрольных сумм для всех данных;
  • status — вывести статус пула.

Это были все основные опции команды, которые мы будем использовать. Теперь рассмотрим примеры настройки zfs и управления разделами.

Как пользоваться ZFS

Настройка ZFS не очень сильно отличается от Btrfs, все базовые действия выполняются очень просто, вы сами в этом убедитесь.

Создание файловой системы

Сначала посмотрим есть ли уже созданные пулы ZFS. Для этого выполните такую команду:

Читайте также:  Bss plugin mac os big sur

sudo zpool list

Если вы устанавливаете эту файловую систему в первый раз, то здесь будет пустой список. Теперь создадим пул на основе существующего раздела, мы будем использовать раздел /dev/sda6

sudo zpool create -f pool0 /dev/sda6

Хотя вы можете использовать не только раздел, а целый диск. Теперь смотрим еще раз список пулов:

sudo zpool list

Затем смотрим состояние нашего пула с помощью команды status, здесь выводится больше подробной информации. Если у вас есть несколько дисков, вы можете настроить RAID массив, чтобы данные хранились не на одном разделе, а синхронно копировались на несколько, это может в несколько раз увеличить производительность.

sudo zpool create pool0 zraid /dev/sda /dev/sdb /dev/sdc

Обратите внимание, что диски должны иметь одинаковый раздел. Если вам не нужен RAID, вы можете настроить обычное зеркалирование на второй диск. Это увеличивает надежность хранения данных:

sudo zpool create pool0 mirror sda sdb

Теперь данные будут писаться на оба диска. Такую же вещь можно проделать с разделами, но здесь нет смысла, поскольку если жесткий диск накроется, то данные вы потеряете, а прироста производительности не увидите. Вы можете использовать даже файлы, для создания файловых систем.

Вы можете добавить новый жесткий диск или раздел к пулу:

sudo zpool attach pool0 /dev/sdd

Или удалить устройство из пула:

sudo zpool detach pool0 /dev/sdd

Чтобы удалить пул используйте команду destroy:

sudo zpool destroy pool0

Для проверки раздела на ошибки используйте команду scrub:

sudo zpool scrub pool0

Статистику использования пула можно посмотреть с помощью команды iostat:

sudo zpool iostat pool0

Файловые системы ZFS

Теперь нужно создать файловые системы на только что созданном пуле. Создадим три файловые системы, data, files и media. Для этого используется команда zfs:

sudo zfs create pool0/data
$ sudo zfs create pool0/files
$ sudo zfs create pool0/media

Файловые системы готовы, дальше рассмотрим монтирование zfs.

Монтирование ZFS

Точка монтирования для пула и для каждой созданной в нем файловой системы создается в корневом каталоге. Например, в нашем случае точки монтирования выглядят так:

Или можно использовать такую команду:

Чтобы размонтировать файловую систему для одного из созданных разделов используйте команду zfs umount:

sudo zfs umount /pool0/data

Затем можно ее обратно примонтировать:

sudo zfs mount pool0/data

Параметры файловой системы

Кроме всего прочего, вы можете настроить различные параметры файловой системы ZFS, например, можно изменить точку монтирования или способ сжатия. Вы можете посмотреть все текущие параметры для файловой системы или пула с помощью команды:

sudo zfs get all pool0/files

Сначала включим сжатие:

sudo zfs set compression=gzip pool0/files

Затем отключим проверку контрольных сумм:

sudo zfs set checksum=off pool0/files

Смотрим точку монтирования:

sudo zfs get mountpoint pool0/files

Затем установим свою:

sudo zfs set mountpoint=/mnt pool0/files

Теперь раздел будет монтироваться в /mnt, настройки можно изменить для каждого из разделов.

Снимки состояния ZFS

Снапшоты zfs или снимки состояния могут использоваться восстановления данных. Благодаря особенностям файловой системы снимки можно создавать мгновенно. Для создания снимка просто наберите:

sudo zfs snapshot pool0/files pool0/files@shot1

Для восстановления используйте:

sudo zfs rollback pool0/files@shot1

Посмотреть список снимков вы можете командой:

sudo zfs list -t snapshot

А удалить ненужный снимок:

sudo zfs destory pool0/files@shot1

Выводы

В этой статье мы рассмотрели как работает файловая система zfs, как выполняется настройка zfs и как ее использовать. Это очень перспективная файловая система, с огромным набором функций, которая способна сравняться, а в некоторых областях и обойти Btrfs. Надеюсь, эта информация была полезной для вас, если у вас остались вопросы, спрашивайте в комментариях!

Zfs для windows 10

To setup a development environment for compiling ZFS.

Download free development Windows 10 image from Microsoft.

and create two VMs.

  • Host (running Visual Studio and Kernel Debugger)
  • Target (runs the compiled kernel module)

The VM images comes with Visual Studio 2017, which we use to compile the driver.

It is recommended that the VMs are placed on static IP, as they can change IP with all the crashes, and you have to configure the remote kernel development again.

Go download the Windows Driver Kit 10

and install on both VMs. You will need both the SDK and WDK: Download the SDK with the Visual Studio 2017 community edition first and install it. It will update the already installed Visual Studio. Then install the WDK. At the end of the installer, allow it to install the Visual Studio extension.

On Target VM, complete the guide specified here, under section «Prepare the target computer for provisioning».

Which mostly entails running:

C:\Program Files (x86)\Windows Kits\10\Remote\x64\WDK Test Target Setup x64-x64_en-us.msi

On the Host VM, continue the guide to configure Visual Studio 2017.

  • Load Visual Studio 2017, there is no need to load the project yet.
  • Menu > Driver > Test > Configure Devices
  • Click «Add New Device»
  • In «Display name:» enter «Target»
  • In «Device type:» leave as «Computer»
  • In «Network host name:» enter IP of Target VM, for me «172.16.248.103»
  • Provisioning options: o Provision device and choose debugger settings.
  • Click «Next >»
Читайте также:  Как узнать код ошибки синего экрана windows

It now confirms that it talked to the Target, and note here that «Host IP» it that of the Host VM, for me, «172.16.248.102», and not to be confused by the Target IP entered on previous screen.

Watch and wait as remote items are installed on the Target VM. It will most likely reboot the Target VM as well.

I’ve had dialog boxes pop up and I agree to installation, but I am not sure they are supposed to. They probably shouldn’t, it would seem it failed to put WDKRemoteUser in Administrators group. If that happens, use «lusrmgr.msc» to correct it.

The task «Creating system restore point» will most likely fail and that is acceptable, however, if other tasks fail, you may need to retry until they work.

At the end of the run, the output window offers a link to the full log, which is worth reading if you encounter issues.

When things fail, I start a CMD prompt as Administrator, and paste in the commands that fail, from the log file. It would be nice if this process just worked though.

If your version of .NET newer, just move along.

The Target VM should reboot, and login as «WDKRemoteUser».

It is recommended you get GIT bash for Windows and install:

Handling configuration errors with Visual Studio 2019 & WDK 10:

There are some issues with Visual Studio 2019 which can cause the following problem in setting up kernel debugging. ERROR: Task “Configuring kernel debugger settings (possible reboot)” failed to complete successfully. Look at the logs in the driver test group explorer for more details on the failure.

This problem is related to MSVC debug tool location mismatch, and as a workaround use the following steps to mitigate this problem:

As Administrator, run Developer Command Prompt for VS 2019 in your Host VM Run the following commands in the VS Developer Command Prompt:

cd /d %VCToolsRedistDir%\debug_nonredist MKLINK /J x86\Microsoft.VC141.DebugCRT x86\Microsoft.VC142.DebugCRT MKLINK /J x64\Microsoft.VC141.DebugCRT x64\Microsoft.VC142.DebugCRT

Retry configuration by following guide to configure Visual Studio 2017 mentioned above.

Host and Target VMs are now configured.

First time you load the project it might default to

you probably want to change ARM ==> X64.

Load ZFSin solution

Menu > Debug > ZFSin Properties

Configuration Properties > Debugging «Debugging tools for Windows — Kernel Debugger» Remote Computer Name: Target

Configuration Properties > Driver Install > Deployment Target Device Name: Target [Tick] Remove previous driver versions O Hardware ID Driver Update Root\ZFSin

You can run DbgView on the Target VM to see the kernel prints on that VM.

Run the compiled Target

  • Compile solution
  • Menu > Debug > Start Debugging (F5)

wait a while, for VS2017 to deploy the .sys file on Target and start it.

Target VM optionals.

If you find it frustrating to do development work when Windows Defender or Windows Updates run, you can disable those in gpedit.msc

  • Computer Configuration > Administrative Templates > Windows Components > Windows Defender Windows Updates

✅ Compile SPL sources

  • Godzillion warnings yet to be addressed

✅ Port SPL sources, atomics, mutex, kmem, condvars

  • C11 _Atomics in kmem not yet handled

✅ Compile ZFS sources, stubbing out code as needed

✅ Include kernel zlib library

✅ Load and Unload SPL and ZFS code

✅ Port kernel zfs_ioctl.c to accept ioctls from userland

✅ Compile userland libspl, libzpool, libzfs, .

✅ Include pthread wrapper library

  • Replaced with thin pthread.h file

✅ Include userland zlib library

✅ Port functions in libzpool, libzfs. Iterate disks, ioctl

✅ Test ioctl from zpool to talk to kernel

✅ Port kernel vdev_disk.c / vdev_file.c to issue IO

✅ Port over cmd/zfs

✅ Add ioctl calls to MOUNT and create Volume to attach

✅ Add ioctl calls to UNMOUNT and detach and delete Volume

✅ Port kernel zfs_vnops.c / zfs_vnops_windows.c

  • Many special cases missing, flags to create/read/etc

✅ Correct file information (dates, size, etc)

✅ Basic DOS usage

✅ Simple Notepad text edit, executables also work.

✅ Basic drag’n’drop in Explorer

✅ zfs send / recv, file and pipe.

✅ git clone ZFS repo on ZFS mounted fs

✅ Compile ZFS on top of ZFS

❎ Scrooge McDuck style swim in cash

Design issues that need addressing.

  • Windows does not handle EFI labels, for now they are parsed with libefi, and we send offset and size with the filename, that both libzfs and kernel will parse out and use. This works for a proof of concept.
Читайте также:  Theme windows go launcher theme

Possibly a more proper solution would be to write a thin virtual hard disk driver, which reads the EFI label and present just the partitions.

vdev_disk.c spawns a thread to get around that IoCompletionRoutine is called in a different context, to sleep until signalled. Is there a better way to do async in Windows?

ThreadId should be checked, using PsGetCurrentThreadId() but it makes zio_taskq_member(taskq_member()) crash. Investigate.

Functions in posix.c need sustenance.

The Volume created for MOUNT has something wrong with it, we are unable to query it for mountpoint, currently has to string compare a list of all mounts. Possibly also related is that we can not call any of the functions to set mountpoint to change it. This needs to be researched.

Find a way to get system RAM in SPL, so we can size up the kmem as expected. Currently looks up the information in the Registry. kmem should also use Windows signals «\KernelObjects\LowMemoryCondition» to sense pressure.

Thinking on mount structure. Second design:

Add dataset property WinDriveLetter, which is ignored on Unix system. So for a simple drive letter dataset:

zfs set driveletter=Z pool

The default creating of a new pool, AND, importing a UNIX pool, would set the root dataset to

So it is assigned first-available drive letter. All lower datasets will be mounted inside the drive letter. If pool’s WinDriveLetter is not set, it will mount «/pool» as «C:/pool».

Installing a binary release

Latest binary files are available at GitHub releases

If you are running windows 10 with secure boot on and/or installing an older release you will need to enable unsigned drivers from an elevated CMD:

  • bcdedit.exe -set testsigning on
  • Then reboot. After restart it should have Test Mode bottom right corner of the screen.

After that either

  • Run OpenZFSOnWindows.exe installer to install
  • Would you like to install device software? should pop up, click install
    • If installing an unsigned release, click «Install anyway» in the «unknown developer» popup

Or if you do not want to run the Installer, run this command by hand from elevated CMD:

  • zfsinstaller.exe install .\ZFSin.inf
  • Would you like to install device software? should pop up, click install
    • If installing an unsigned release, click «Install anyway» in the «unknown developer» popup

Run zpool.exe status to confirm it can talk to the kernel

Failure would be:

Success would be:

Creating your first pool.

The basic syntax to creating a pool is as below. We use the pool name «tank» here as with Open ZFS documentation. Feel free to pick your own pool name.

The default options will «mostly» work in Windows, but for best compatibility should use a case insensitive filesystem.

The recommended options string for Windows is currently:

  • Creating filebased pools would look like:
  • Creating a HDD pool

First, locate disk name

Creating a ZVOL virtual hard disk

Creating a virtual hard disk (ZVOL) is done by passing «-V » to the «zfs create» command.

Which would create a disk of 2GB in size, called «tank/hello». Confirm it was created with:

Exporting the pool

If you have finished with ZFS, or want to eject the USB or HDD that the pool resides on, it must first be exported. Similar to «ejecting» a USB device before unplugging it.

Importing a pool

If a zpool has been created on a disk partition from a different system make sure the partition label contains «zfs». Otherwise zpool import won’t recognize the pool and will fail with «no pools available to import».

Uninstalling the driver

If you used the Installer, you can browse to «C:\Program Files (x86)\OpenZFS On Windows» and run the «uninst000.exe» Uninstaller program.

You can also use «Add Remove Programs» from the Settings menu, and click on «OpenZFS On Windows-debug version x.xx» and select Uninstall.

If you did not use the Installer, you can manually uninstall it:

To verify that the driver got uninstalled properly you can check «zpool.exe status».

When uninstalled with success, «zpool.exe status» should return:

If the driver is still there, it would be:

A reboot might be necessary to uninstall it completely.

You can use the registry to tune various parameters.
Also, there is kstat to dynamically change parameters.

There are nightly builds available at AppVeyor

  • These builds are currently not signed and therefore require test mode to be enabled.

There also are test builds available here. These are «hotfix» builds for allowing people to test specific fixes before they are ready for a release.

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