[решено] как исправить ошибки, связанные с mke2fs.exe

DESCRIPTION

mke2fsdevice

The file system size is specified by
fs-size.

If
fs-size

does not have a suffix, it is interpreted as power-of-two kilobytes,
unless the
-b

blocksize

option is specified, in which case
fs-size

is interpreted as the number of
blocksize

blocks. If the fs-size is suffixed by ‘k’, ‘m’, ‘g’, ‘t’
(either upper-case or lower-case), then it is interpreted in
power-of-two kilobytes, megabytes, gigabytes, terabytes, etc.
If
fs-size

is omitted,
mke2fs

will create the file system based on the device size.

If
mke2fs

is run as
mkfs.XXX

(i.e.,
mkfs.ext2,

mkfs.ext3,

or
mkfs.ext4)

the option
-t

XXX

is implied; so
mkfs.ext3

will create a file system for use with ext3,
mkfs.ext4

will create a file system for use with ext4, and so on.

The defaults of the parameters for the newly created filesystem, if not
overridden by the options listed below, are controlled by the
/etc/mke2fs.conf

configuration file. See the
mke2fs.conf(5)

manual page for more details.

Detecting FAT type

If you need to know which a partition uses, use the file command:

# file -s /dev/partition
/dev/partition: DOS/MBR boot sector, code offset 0x3c+2, OEM-ID "mkfs.fat", sectors/cluster 4, root entries 512, sectors 4096 (volumes <=32 MB), Media descriptor 0xf8, sectors/FAT 3, sectors/track 32, heads 64, serial number 0x5bc09c21, unlabeled, FAT (12 bit)

Alternatively you can use minfo from the package:

# minfo -i /dev/partition ::
device information:
===================
filename="/dev/partition"
sectors per track: 32
heads: 64
cylinders: 2

media byte: f8

mformat command line: mformat -t 2 -h 64 -s 32 -i "/dev/partition" ::

bootsector information
======================
banner:"mkfs.fat"
sector size: 512 bytes
cluster size: 4 sectors
reserved (boot) sectors: 1
fats: 2
max available root directory slots: 512
small size: 4096 sectors
media descriptor byte: 0xf8
sectors per fat: 3
sectors per track: 32
heads: 64
hidden sectors: 0
big size: 0 sectors
physical drive id: 0x80
reserved=0x0
dos4=0x29
serial number: 5BC09C21
disk label="NO NAME    "
disk type="FAT12   "

SSD Optimizations

ATA Trim

Ext4 supports ATA Trim for solid state drives (SSDs):

  • Online discard from Kernel 2.6.33

    The -o discard mount option (for example mount -o discard /dev/sdb1 /mnt/. For permanent activation, the option must be entered in /etc/fstab, because the discard capability is deactivated by default)

  • Batched discard from Kernel 2.6.37
  • Accelerated batched discard from Kernel 3.1
  • Pre-discard during formatting from mke2fs 1.41.10
    • Extract from the man page for mke2fs: -E discard: Attempt to discard blocks at mkfs time (discarding blocks initially is useful on solid state devices and sparse / thin-provisioned storage). When the device advertises that discard also zeroes data (any subsequent read after the discard and before write returns zero), then mark all not-yet-zeroed inode tables as zeroed. This significantly speeds up file system initialization. This is set as default.

      Caution when using this feature with the device mapper with mixed physical volumes. discard_zeros_data will first be properly returned as of Kernel 3.0 — see patch block: Fix discard topology stacking and reporting)

    • In our test, we observed significantly different time requirements for the discard operation during formatting. However, significant effects were not caused by discard also zeroes data (regarding this, see ATA Trim Performance).
    • With discard also zeroes data, displayed Deterministic read ZEROs after TRIM (or deterministic read data after TRIM). The following example shows an OCZ Vertex 3 SSD and an Intel 320 Series SSD:
# hdparm -V
hdparm v9.36
# hdparm -I /dev/sda | grep 'Model\|TRIM'
	Model Number:       OCZ-VERTEX3                             
	   *	Data Set Management TRIM supported (limit 1 block)
	   *	Deterministic read data after TRIM
# hdparm -I /dev/sdb | grep 'Model\|TRIM'
	Model Number:       INTEL SSDSA2CW160G3                     
	   *	Data Set Management TRIM supported (limit 8 blocks)
	   *	Deterministic read ZEROs after TRIM
# 

File System Journal: Yes or No?

Not using the Ext4 file system journal can increase file system performance, is however connected with disadvantages when the shutdown procedure is not completely clean (such as during a power failure). Theodore Tso, an Ext4 file system developer, determined in tests that the performance disadvantages caused by journaling were between four and twelve percent. Therefore, the journal should be used. Not using the atime journaling would be a more recommendable way of increasing performance.

Should stride and stripe-width Parameters be used?

There are a number of different recommendations for the stride and stripe-width parameters for using SSDs under Ext4.

If certain values really do provide a benefit cannot be determined with certainty at this time. Individualized tests with the respective SSD would be required for making a determination.

Tips and tricks

Using file-based encryption

Since Linux 4.1, ext4 natively supports file encryption, see the fscrypt article. Encryption is applied at the directory level, and different directories can use different encryption keys. This is different from both dm-crypt, which is block-device level encryption, and from eCryptfs, which is a stacked cryptographic filesystem.

Enabling metadata checksums

When a filesystem has been created with 1.44 or later, metadata checksums should already be enabled by default. Existing filesystems may be converted to enable metadata checksum support.

Tip: Use to check the features that are enabled on the filesystem:

# dumpe2fs /dev/path/to/disk

New filesystem

To enable support for ext4 metadata checksums on creating a new file system:

# mkfs.ext4 -O metadata_csum /dev/path/to/disk

Convert existing filesystem

Note: The filesystem should not be mounted.

First the partition needs to be checked and optimized using :

# e2fsck -Df /dev/path/to/disk  

Convert the filesystem to 64bit:

# resize2fs -b /dev/path/to/disk 

Finally enable checksums support:

# tune2fs -O metadata_csum /dev/path/to/disk

Создание раздела на жёстком диске в Linux

cfdisk — утилита создания разделов на жестком диске Linux.Запускаем cfdisk, указывая имя диска, с которым собираемся работать:

cfdisk /dev/sdb


 

Нажимаем на New, создать раздел. Выбираем Primary (основной)


 

Создастся, нажимаем Bootable, если нужно, чтобы он был загрузочный. К слову, в Ubuntu если эту опцию не выбрать, дальше дело не пойдет.
Нажимаем Write и пишем yes

Как уже говорилось, создать раздел в Linux довольно просто, и это только что сделано. Всё, разделы созданы, выходим из программы, выбирая Quit.
Если необходимо переразметить разделы на б/у диске, не тратя время на удаление существующих, можно запустить cfdisk с ключем -z :

cfdisk -z /dev/sdb

Параметр -z создаёт нулевую таблицу разделов, и позволяет сразу начать формировать новую.

Также для создания и удаления резделов на жестком диске можно использовать утилиту parted, а в среде GNOME ее графический вариант gparted.

Пример использования tmpfs для сервера печати в домене AD

Вот живой пример использования tmpfs для ускорения работы очереди печати SAMBA+CUPS. Создаем tmpfs раздел /spooler при загрузке системы, в который размещаем спулер очереди печати демонов CUPS и SAMBA:

ramdisk-host ~ # grep tmp /etc/fstab
tmpfs	/spooler	tmpfs	noexec,size=4000M	0       0
ramdisk-host ~ # grep -A5 printers /etc/smb.conf

        comment = Очередь печати SMB
        path = /spooler/samba
        printable = Yes
        browseable = No
ramdisk-host ~ # grep spool /etc/cupsd.conf

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

DESCRIPTION

mke2fsdevice

The file system size is specified by
fs-size.

If
fs-size

does not have a suffix, it is interpreted as power-of-two kilobytes,
unless the
-b

blocksize

option is specified, in which case
fs-size

is interpreted as the number of
blocksize

blocks. If the fs-size is suffixed by ‘k’, ‘m’, ‘g’, ‘t’
(either upper-case or lower-case), then it is interpreted in
power-of-two kilobytes, megabytes, gigabytes, terabytes, etc.
If
fs-size

is omitted,
mke2fs

will create the file system based on the device size.

If
mke2fs

is run as
mkfs.XXX

(i.e.,
mkfs.ext2,

mkfs.ext3,

or
mkfs.ext4)

the option
-t

XXX

is implied; so
mkfs.ext3

will create a file system for use with ext3,
mkfs.ext4

will create a file system for use with ext4, and so on.

The defaults of the parameters for the newly created filesystem, if not
overridden by the options listed below, are controlled by the
/etc/mke2fs.conf

configuration file. See the
mke2fs.conf(5)

manual page for more details.

Create the partition

The following two sections show how to create an EFI system partition (ESP).

Warning: The EFI system partition must be a physical partition in the main partition table of the disk, not under LVM or software RAID etc.

Note: It is recommended to use GPT since some firmwares might not support UEFI/MBR booting due to it not being supported by Windows Setup. See also for the advantages of GPT in general.

GPT partitioned disks

EFI system partition on a GUID Partition Table is identified by the .

Choose one of the following methods to create an ESP for a GPT partitioned disk:

  • fdisk: Create a partition with partition type .
  • gdisk: Create a partition with partition type .
  • GNU Parted: Create a partition with as the file system type and set the flag on it.

Proceed to section below.

MBR partitioned disks

EFI system partition on a Master Boot Record partition table is identified by the partition type ID .

Choose one of the following methods to create an ESP for a MBR partitioned disk:

  • fdisk: Create a primary partition with partition type .
  • GNU Parted: Create a primary partition with as the file system type and set the flag on it.

Proceed to section below.

Data corruption

If for whatever reason you experience data corruption, you will need to repair the filesystem manually.

First unmount the XFS filesystem.

# umount /dev/sda3

Once unmounted, run the tool.

# xfs_repair -v /dev/sda3

Online Metadata Checking (scrub)

Warning: This program is experimental, which means that its behavior and interface could change at any time. See .

asks the kernel to scrub all metadata objects in the XFS filesystem. Metadata records are scanned for obviously bad values and then cross-referenced against other metadata. The goal is to establish a reasonable confidence about the consistency of the overall filesystem by examining the consistency of individual metadata records against the other metadata in the filesystem. Damaged metadata can be rebuilt from other metadata if there exists redundant data structures which are intact.

Enable/start to periodic check online metadata for all XFS filesystems.

Note: One may want to edit : the timer runs every Sunday at 3:10am and will be if it missed the last start time, i.e. due to the system being powered off.

Kernel configuration

Here is an example of the default mount configuration in the kernel:

$ zgrep -e FAT -e DOS /proc/config.gz | sort -r
# DOS/FAT/NT Filesystems
CONFIG_FAT_FS=m
CONFIG_MSDOS_PARTITION=y
CONFIG_FAT_FS=m
CONFIG_MSDOS_FS=m
CONFIG_VFAT_FS=m
CONFIG_FAT_DEFAULT_CODEPAGE=437
CONFIG_FAT_DEFAULT_IOCHARSET="utf-8"
CONFIG_NCPFS_SMALLDOS=y

A short description of the options:

  • Language settings: ,
  • All filenames to lower letters on a FAT partitions if enabled:
  • Enables support of the FAT file systems: , ,
  • Enables support of a FAT partitioned harddisks on 86x PCs:

If the partition type detected by mount is VFAT then it will run the script.

/usr/bin/mount.vfat
#!/bin/bash
#mount VFAT with full rw (read-write) permissions for all users
#/usr/bin/mount -i -t vfat -oumask=0000,iocharset=utf-8 "$@"
#The above is the same as
mount -i -t vfat -oiocharset=utf-8,fmask=0000,dmask=0000 "$@"

Tips & Tricks tmpfs

Bind-монтирование для куска файловой системы

Про bind mounting можно почитать в ссылках в конце статьи. Далее, интересный пример с сайта ibm.com: вы монтируете tmpfs к /dev/shm, его «традиционной» точке, но одновременно хотите использовать tmpfs для /tmp. Вместо монтирования еще одной tmpfs к /tmp (что возможно), вы решаете объединить /tmp с /dev/shm. Но, bind mount /dev/shm к /tmp нужно сделать так, чтобы каталоги из /dev/shm не были видны в /tmp. Как это сделать? Пример:

# mkdir /dev/shm/tmp
# chmod 1777 /dev/shm/tmp
# mount --bind /dev/shm/tmp /tmp

В этом примере сначала создается каталог /dev/shm/tmp и назначаются права доступа (обычные для /tmp). Далее можно монтировать только отдельный /dev/shm/tmp. После этого файл /tmp/foo будет дополнительно виден как /dev/shm/tmp/foo, но файл /dev/shm/bar в каталоге /tmp отображен не будет.

Swap без изменений в структуре файловой системы

Если Вам необходимо разово расширить объем виртуальной памяти за счет своп раздела, при этом нет возможности изменить таблицу разделов, есть возможность добавить кусок свопа в виде файла. Это может понадобиться, например, для сборки крупного пакета. Пример данной конфигурации:

# dd if=/dev/zero of=/home/swap.img bs=1M count=1024
# chmod 600 /home/swap.img
# mkswap /home/swap.img
# swapon /home/swap.img

Стоит учитывать, что на linux архитектуре x86 возможно использовать размер свопа не более 2 Гб. Но этих файлов можно подключать несколько.

Сравнение рамдисков (итог)

Давайте подведем краткий итог вышеизложенного. Для большинства задач наиболее подходящим является реализация tmpfs, как обладающая наибольшим функционалом и отсутствием недостатков. Ниже маленькая сводная таблица:

ramdisk ramfs tmpfs
Лимит размера диска Да Нет Да
Изменение размера Да (ограниченно) Да Да (без прерывания работы)
Использование swap Нет Нет Да
Монтирование через fstab Нет Да Да
Высвобождение неиспользуемого пространства Нет Да Да

Что еще почитать о tmpfs

Документация ядра linux:

https://www.kernel.org/doc/Documentation/blockdev/ramdisk.txt
https://www.kernel.org/doc/Documentation/filesystems/tmpfs.txt
https://www.kernel.org/doc/Documentation/filesystems/ramfs-rootfs-initramfs.txt

Дополнительные ссылки:

http://www.vanemery.com/Linux/Ramdisk/rd-c.txt — что-то похожее на исходники модуля ядра rd
http://linux-mm.org/ — wiki с кучей информации о работе оперативной памяти в Linux
http://0pointer.de/blog/projects/tmp.html — статья о использовании tmpfs в /tmp или /var/tmp

Man-страницы

man mknod
man mount
man fstab

Монтирование диска

После форматирования раздел сразу же можно смонтировать и использовать. Создаём точку монтирования (каталог на диске):

mkdir /photos

и даём директории полные права:

chmod 770 /photos

И монтируем:

mount -t ext4 /dev/sdb1 /photos

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

Чтоб сделать подключение диска постоянным, надо прописать в файл /etc/fstab строку с идентификатором раздела и другими параметрами.

Идентификатор устройства узнаем командой:

blkid

Далее откроем привычным редактором файл /etc/fstab, например так:

vi /etc/fstab

и впишем туда строку следующего вида:

UUID=ca7e6047-670a-428f-a2da-452e8b00015b /photos/ ext4 users,defaults,umask=0 0 0

Более подробно процесс автоматического монтирования диска в Linux описан в этой статье.

Creating a fresh FAT filesystem

Typically during development you want to create a disk image with a FAT filesystem. There are two common approaches for this, either by using a utility that works directly on images, or by using a Loopback Device and using the OS’ own driver to work on the image. A less common alternative is to have an actual disk in your drive.

The most buildscript-friendly tool is MTools — which can do all operations directly on a disk image using the -i argument and supplies every DOS command related to files in this fashion, only prefixed with an m. It can also use a configuration file to access drives in their DOS fashion, allowing you to use for instance A: and C: as actual drives. The tool can be built out of the box for Windows and is included in many a linux package manager.

Linux-only developers can, often with a bit of sudo and permission magic, automate the Loopback Device in combination with mkdosfs or mkfs.vfat as well as partition editing. This method is less portable as the commands often can’t be reused outside of Linux. Several developers also make the error of passing -F to mkdosfs in an attempt to choose a FAT size, which often has the effect of creating a corrupt filesystem since the result doesn’t follow .

Windows users can make use of VFD for loopback devices. It comes with a GUI, but at the cost of not being properly automatable in a script.

ENVIRONMENT

MKE2FS_SYNC

If set to non-zero integer value, its value is used to determine how often
sync(2)

is called during inode table initialization.

MKE2FS_CONFIG

Determines the location of the configuration file (see
mke2fs.conf(5)).

MKE2FS_FIRST_META_BG

If set to non-zero integer value, its value is used to determine first meta
block group. This is mostly for debugging purposes.
MKE2FS_DEVICE_SECTSIZE

If set to non-zero integer value, its value is used to determine logical
sector size of the
device.

MKE2FS_DEVICE_PHYS_SECTSIZE

If set to non-zero integer value, its value is used to determine physical
sector size of the
device.

MKE2FS_SKIP_CHECK_MSG

If set, do not show the message of filesystem automatic check caused by
mount count or check interval.

DESCRIPTION

mke2fs.confmke2fsmke2fs

The
mke2fs.conf

file uses an INI-style format. Stanzas, or top-level sections, are
delimited by square braces: . Within each section, each line
defines a relation, which assigns tags to values, or to a subsection,
which contains further relations or subsections.

An example of the INI-style format used by this configuration file
follows below:

tag1 = value_atag1 = value_btag2 = value_c

tag3 = {subtag1 = subtag_value_asubtag1 = subtag_value_bsubtag2 = subtag_value_c}tag1 = value_dtag2 = value_e}

Comments are delimited by a semicolon (‘;’) or a hash (‘#’) character
at the beginning of the comment, and are terminated by the end of
line character.

Tags and values must be quoted using double quotes if they contain
spaces. Within a quoted string, the standard backslash interpretations
apply: «\n» (for the newline character),
«\t» (for the tab character), «\b» (for the backspace character),
and «\\» (for the backslash character).

Some relations expect a boolean value. The parser is quite liberal on
recognizing «yes», ‘`y», «true», «t», «1», «on», etc. as a
boolean true value, and «no», «n», «false», «nil», «0»,
«off» as a boolean false value.

The following stanzas are used in the
mke2fs.conf

file. They will be described in more detail in future sections of this
document.

Contains relations which influence how mke2fs behaves.

Contains relations which define the default parameters
used by
mke2fs(8).

In general, these defaults may be overridden by a definition in the
fs_types

stanza, or by a command-line option provided by the user.

Contains relations which define defaults that should be used for specific
file system and usage types. The file system type and usage type can be
specified explicitly using
the
-tand-T

options to
mke2fs(8),

respectively.

Contains relations which define defaults for specific devices.

Writing to FAT32 as normal user

To write on a FAT32 partition, you must make a few changes to the fstab file.

/etc/fstab
/dev/sdxY    /mnt/some_folder  vfat   user,rw

The option means that any user (even non-root) can mount and unmount the partition . gives read-write access.

For example, if your FAT32 partition is on , and you wish to mount it to , then you would use:

/etc/fstab
/dev/sda9    /mnt/fat32        vfat   user,rw

Now, any user can mount it with:

$ mount /mnt/fat32

And unmount it with:

$ umount /mnt/fat32

Note that FAT does not support Linux file permissions. Each file will also appear to be executable. You may want to use the option to only mark Windows executables (com, exe, bat) as executable. See for more options.

Improving performance

E4rat

E4rat is a preload application designed for the ext4 filesystem. It monitors files opened during boot, optimizes their placement on the partition to improve access time, and preloads them at the very beginning of the boot process. E4rat does not offer improvements with SSDs, whose access time is negligible compared to hard disks.

Disabling access time update

The ext4 file system records information about when a file was last accessed and there is a cost associated with recording it. With the option, the access timestamps on the filesystem are not updated.

/etc/fstab
/dev/sda5    /    ext4    defaults,noatime    0    1

Doing so breaks applications that rely on access time, see for possible solutions.

Increasing commit interval

The sync interval for data and metadata can be increased by providing a higher time delay to the option.

The default 5 sec means that if the power is lost, one will lose as much as the latest 5 seconds of work.
It forces a full sync of all data/journal to physical media every 5 seconds. The filesystem will not be damaged though, thanks to the journaling.
The following fstab illustrates the use of :

/etc/fstab
/dev/sda5    /    ext4    defaults,noatime,commit=60    0    1

Turning barriers off

Warning: Disabling barriers for disks without battery-backed cache is not recommended and can lead to severe file system corruption and data loss.

Ext4 enables write barriers by default. It ensures that file system metadata is correctly written and ordered on disk, even when write caches lose power. This goes with a performance cost especially for applications that use fsync heavily or create and delete many small files. For disks that have a write cache that is battery-backed in one way or another, disabling barriers may safely improve performance.

To turn barriers off, add the option to the desired filesystem. For example:

/etc/fstab
/dev/sda5    /    ext4    noatime,barrier=0    0    1

Disabling journaling

Warning: Using a filesystem without journaling can result in data loss in case of sudden dismount like power failure or kernel lockup.

Disabling the journal with ext4 can be done with the following command on an unmounted disk:

# tune2fs -O "^has_journal" /dev/sdXN

Use external journal to optimize performance

This article or section needs language, wiki syntax or style improvements. See Help:Style for reference.

You can then format a dedicated device to journal to with . Use to assign the journal to an existing device, or replace with if you are making a new filesystem.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector