rha130 workbook 03 student 5.0 0 linux file system management

97
Workbook 3. Linux Filesystem Management

Upload: claudio-hernan-valenzuela-zepeda

Post on 07-Apr-2015

2.141 views

Category:

Documents


7 download

TRANSCRIPT

Page 1: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Workbook 3. Linux FilesystemManagement

Page 2: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Workbook 3. Linux Filesystem Management

Page 3: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Table of Contents1. Disk Recognition and Partitioning.......................................................................................................6

Discussion..........................................................................................................................................6Disk Partitions..........................................................................................................................6Partitioning withfdisk ..............................................................................................................9Viewing Partitions in/proc/partitions...........................................................................18

Examples..........................................................................................................................................18Partitioning a New Drive........................................................................................................18

Online Exercises...............................................................................................................................21Specification...........................................................................................................................22Deliverables............................................................................................................................22

Questions..........................................................................................................................................22

2. Creating and Managing Filesystems..................................................................................................26

Discussion........................................................................................................................................26Filesystems.............................................................................................................................26Linux Filesystems...................................................................................................................27Creating Filesystems..............................................................................................................28Creating ext2 Filesystems:mke2fs........................................................................................28Examining Filesystems withdumpe2fs.................................................................................30Filesystem Features................................................................................................................32The ext3 Journaling Filesystem..............................................................................................33

Examples..........................................................................................................................................34Creating an ext2 Filesystem...................................................................................................34Creating a vfat Filesystem......................................................................................................36Creating an ext3 Filesystem...................................................................................................36

Online Exercises...............................................................................................................................37Specification...........................................................................................................................37Deliverables............................................................................................................................37

Questions..........................................................................................................................................38

3. Mounting Filesystems..........................................................................................................................42

Discussion........................................................................................................................................42Mounting Filesystems............................................................................................................42Mounting Filesystems with themount Command.................................................................50Unmounting Filesystems with theumount Command..........................................................52Remounting Partitions withmount -o remount....................................................................53

Examples..........................................................................................................................................53Creating Mount Points............................................................................................................53

Online Exercises...............................................................................................................................54Specification...........................................................................................................................54Deliverables............................................................................................................................54

Questions..........................................................................................................................................55

iii

Page 4: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

4. The/etc/fstab File...........................................................................................................................59

Discussion........................................................................................................................................59The/etc/fstab File Syntax................................................................................................59Mount Options Relevant to the/etc/fstab File.................................................................60Specifying Devices by Filesystem Label................................................................................61Using Filesystem Labels on the Mount Command Line........................................................61Adding Lines to the/etc/fstab File ..................................................................................62

Examples..........................................................................................................................................62Defining Mount Points in the/etc/fstab File....................................................................62

Online Exercises...............................................................................................................................64Specification...........................................................................................................................64Deliverables............................................................................................................................64

Questions..........................................................................................................................................64

5. Managing Swap Space.........................................................................................................................68

Discussion........................................................................................................................................68Swap Space.............................................................................................................................68Monitoring Swap Partitions:/proc/swaps and/proc/meminfo ......................................68Initializing Swap Space withmkswap...................................................................................69Activating Swap Space withswapon.....................................................................................69Deactivating Swap Areas withswapoff.................................................................................70Predefining Swap Areas in the/etc/fstab File..................................................................70

Examples..........................................................................................................................................70Initializing Swap Partitions....................................................................................................70Using Swap Files....................................................................................................................71

Online Exercises...............................................................................................................................71Specification...........................................................................................................................72Deliverables............................................................................................................................72

Questions..........................................................................................................................................72

6. Miscellaneous Filesystem Management Commands........................................................................75

Discussion........................................................................................................................................75Thee2labelCommand...........................................................................................................75File System Repair withfsck .................................................................................................75Thetune2fsCommand...........................................................................................................76Review: Adding a New Disk..................................................................................................77

Examples..........................................................................................................................................78Converting an ext2 filesystem to ext3.....................................................................................78

Online Exercises...............................................................................................................................79Specification...........................................................................................................................79Deliverables............................................................................................................................79

Questions..........................................................................................................................................79

7. SELinux: Secure Linux.......................................................................................................................83

Discussion........................................................................................................................................83Introduction to SELinux ("Secure Linux").............................................................................83ThetargetedSELinux Policy.................................................................................................84Enabling SELinux:/etc/sysconfig/selinux, setenforce, andgetenforce...................84Viewing SELinux contexts:ps -Z andls -Z...........................................................................86

rha130-5.0-0-en-2007-12-13T13:35:30-0500Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat

Academy. Any other use is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated,stored in a retrieval system, or otherwise duplicated whether in electronic or print format without prior written conse nt of Red Hat, Inc.If you believe Red Hat course materials are being used, copied, or otherwise improperly distributed please email [email protected] phone toll-free (USA) +1 866 626 2994 or +1 (919) 754 3700.

iv

Page 5: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Monitoring SELinux violations:sealertand/var/log/messages....................................87Changing the SELinux Context of a File:chcon...................................................................88Restoring the SELinux Context of a File:restorecon............................................................89Managing SELinux Booleans:getseboolandsetsebool........................................................89Administering SELinux withsystem-config-selinux............................................................90

Examples..........................................................................................................................................91Changing the SELinux Context of a File...............................................................................91

Online Exercises...............................................................................................................................93Specification...........................................................................................................................94Deliverables............................................................................................................................94Clean Up.................................................................................................................................95

Questions..........................................................................................................................................95

rha130-5.0-0-en-2007-12-13T13:35:30-0500Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use is a violationof U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrievalsystem, or otherwise duplicated whether in electronic or printformat without prior written consent of Red Hat, Inc. If you b elieve Red Hat course materials are being used, copied, or otherwise improperly distributed please [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919) 754 3700.

v

Page 6: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 1. Disk Recognition and Partitioning

Key Concepts

• Thefdisk utility is used to display and edit partition tables.

• Disks may have up to 4 primary partitions.

• One primary partition may be used a an extended partition.

• The extended partition is then used as a container for holding multiple logical partitions.

• Every partition has an associated label which identifies howthe partition is intended to be used.

DiscussionThe Linux Operating System treat disks as a large array of bytes, which can be divided and structured toserve a variety of needs. This Workbook teaches the skills that allow administrators to configure andstructure disks to their needs.

Disk PartitionsLike most modern operating systems, Linux allows disks to bedivided into multiplepartitions, whereeach partition is effectively treated as a separate disk. The process of creating partitions is referred to aspartitioninga disk.

How Linux Refers to Partitions

The Linux kernel refers to individual partitions through distinct device nodes, where the name of thenode is derived by appending the partition number to the nameof the disk. For example, the firstpartition on the drive/dev/hda is referred to as/dev/hda1, while the seventh partition on the drive/dev/sdc would be referred to as/dev/sdc7.

DOS Partitioning Oddities

Different operating systems have established different conventions for recording a disk’s partitioninginformation. Because Linux has historically inter-operated with DOS based operating systems, the mostcommonly encountered partitioning scheme is DOS partitioning. The DOS partitioning format wasderived in days when a 200 megabyte hard disk was considered large and the number of necessarypartitions on a disk was small, the implications of which will soon be discovered.

6

Page 7: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 1. Disk Recognition and Partitioning

Figure 1-1. A Sample Partitioning of the Drive/dev/hda

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

7

Page 8: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 1. Disk Recognition and Partitioning

The above figure diagrams a disk partitioned using DOS partitioning, including the features outlinedbelow.

The Master Boot Record (MBR)

The first block (512 bytes) of every disk is reserved for the Master Boot Record, or MBR. (The size ofthe MBR in the above figure is greatly out of proportion.) The MBR contains the following items.

• Bootloader: On bootable disks, a low level executable referred to as abootloaderresides in the MBR.When booting, BIOS passes control to the bootloader, which is then responsible for loading andpassing control to the appropriate operating system. The bootloader will be discussed in more detail ina later Workbook.

• Partition Table: On every disk, 64 bytes of the Master Boot Record is reserved for the disk’s partitiontable. This small amount of space records information for upto 4 partitions, referred to asprimarypartitions. For each partition, a starting location, an ending location, and a partition type is recorded.

Primary Partitions

Each disk can be divided into up to four primary partitions, whose properties are recorded in the partitiontable located in the MBR. Linux always uses partition numbers 1 through 4 to refer to primary partitions.In the above diagram, the first primary partition,/dev/hda1, is a FAT filesystem for Windows operatingsystem. The second primary partition,/dev/hda2, is a swap partition which Linux uses to implementvirtual memory. The third partition,/dev/hda3, is an ext3 filesystem which contains a Linux/bootpartition.

The Extended Partition

With the three partitions mentioned above, we are already about to use up the four allowed primarypartitions. As a way to work around this limitation, an awkward structure was created, referred to as theextended partition. DOS partitioning allows any one primary partition to be used as the extendedpartition. The extended partition is used as a container forstoring more partitions, referred to aslogicalpartitions. Once a primary partition is used as the extended partition,it may not be used for any otherpurpose.

An extended partition is optional. If four partitions servethe partitioning needs for a particular disk, thenno extended partition is required. In theory, any of the fourprimary partitions may be used as theextended partition. In practice, the first three primary partitions are generally created as needed, and theremainder of the disk is devoted to a fourth primary partition used as the extended partition. This strategywas implemented in the figure above, where/dev/hda4 serves as the extended partition.

Logical Partitions

Within the extended partition, multiplelogical partitions may be created. The partitioning informationfor logical partitions is maintained as a linked list, so in theory, there is no limit to the number of logicalpartitions which may be created. In practice, device drivers impose limitations. There may be no morethan 63 IDE partitions, and no more than 15 SCSI partitions. Linux always begins counting the firstlogical partition as partition number 5, even if not all 4 primary partitions are used.

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

8

Page 9: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 1. Disk Recognition and Partitioning

In the above figure, 4 logical partitions (/dev/hda5, /dev/hda6, /dev/hda7and/dev/hda8) containext3 filesystems for the/, /home, /var, andpub partitions, respectively.

Partitioning with fdiskThe most commonly used tool in Red Hat Enterprise Linux for partitioning disks isfdisk. The commandline utility is intentionally kept simple and unpretentious, so that it can be used in minimal environmentssuch as a rescue shell. As standard users do not have permission to read (and certainly not modify) disksdirectly through their device node, thefdisk utility can only usefully be used as the root user.

Using fdisk to List Partitions

Perhaps the simplest use offdisk is to display known partitions. With the-l command line switch,fdiskwill list partition tables for all known disks. In the following example,fdisk -l generates a partition tableof the two attached hard disks on the system,/dev/hda and/dev/hdb. The output of this singlecommand has been broken into two listings, in order to allow us to focus on each disk individually.

[root@station root]# fdisk -l

Disk /dev/hda: 120.0 GB, 120034123776 bytes ➊

240 heads, 63 sectors/track, 15505 cylinders ➋

Units = cylinders of 15120 * 512 = 7741440 bytes ➌

Device Boot Start End Blocks Id System ➍

/dev/hda1 1 540 4082368+ b Win95 FAT32/dev/hda2 * 541 3249 20480040 7 HPFS/NTFS/dev/hda3 3250 ➎3926 5118120 83 Linux

We now attempt to make sense of the reported structure of the first disk.

➊ The first disk is 120 gigabytes in size.

➋ This line displays the drive’s geometry, or how the drive is internally structured. The importantparameter is cylinders, becausefdisk forces partitions to begin and end on cylinder boundaries. Acylinder is composed of multiple heads, which are in turn composed of multiple blocks of 512 byteseach. Doing the math, on this disk each cylinder contains (512 bytes/head) * (240 heads/sector) *(63 sectors/cylinder) = 7741440 bytes/cylinder, or about 7.5 megabytes per cylinder.

➌ We really didn’t have to do all of that math,fdisk did it for us.

➍ Here we find the actual partition table. This disk has only three partitions, each as a primarypartition. (How do we know this? For starters, the partitionnumbers are less then or equal to 4).Each line gives the device name, the starting and ending cylinder, the size of the partition, and thepartition type. We will further discuss interpreting theselines below.

➎ The last partition ends on cylinder 3926, while we know from the line listing the disk geometry(labeled "2" above) that the disk has 15505 cylinders. We canestimate that the disk has about(15505 - 3926 cylinders) * (7.5 megabytes/cylinder) = 87 gigabytes of space left unallocated.

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use isa violation of U.S. and international copyrights. No part ofthis publication may be photocopied, duplicated, stored ina retrieval system, or otherwise duplicated whetherin electronic or print format without prior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, or otherwise improperly distributedplease email [email protected] or phone toll-free (USA)+1 866 626 2994 or +1 (919) 754 3700.

9

Page 10: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 1. Disk Recognition and Partitioning

Next, we focus on the second disk,/dev/hdb.

Disk /dev/hdb: 80.0 GB, 80026361856 bytes ➊

255 heads, 63 sectors/track, 9729 cylinders ➋

Units = cylinders of 16065 * 512 = 8225280 bytes ➌

Device Boot Start End Blocks Id System/dev/hdb1 * 1 9 72261 83 Linux ➍

/dev/hdb2 10 270 2096482+ 82 Linux swap/dev/hdb3 271 1302 8289540 83 Linux/dev/hdb4 1303 9729 67689877+ f Win95 Ext’d (LBA) ➎

/dev/hdb5 1303 5127 30724281 83 Linux ➏

/dev/hdb6 5128 6171 8385898+ 83 Linux/dev/hdb7 6172 ➐9729 28579603+ 83 Linux

We now perform a similar analysis on the second disk.

➊ The second disk is 80 gigabytes in size.

➋ Now that we know thatfdisk does the work for us, we only focus on the number of cylinders,in thiscase 9729...

➌ ... where each cylinder is a little over 8 megabytes in size.

➍ This disk has allocated all four primary partitions.

➎ The fourth primary partition is being used as the extended partition, ending on the disk’s lastcylinder (9729).

➏ The remaining partitions are logical partitions. Notice that their cylinder boundaries fallinsidethebounds of the extended partition (i.e., between cylinder numbers 1303 and 9729 inclusively).

➐ The end of the last logical partition (cylinder 9729) coincides with the end of the extended partition,which coincides with the end of the disk. There is no more space left on the drive.

Focusing on a Single Line of fdisk ’s Partition Table

In order to discuss a single line in detail, we list again the partition table for the disk/dev/hda.

Disk /dev/hda: 120.0 GB, 120034123776 bytes240 heads, 63 sectors/track, 15505 cylindersUnits = cylinders of 15120 * 512 = 7741440 bytes

Device Boot Start End Blocks Id System/dev/hda1 1 540 4082368+ b Win95 FAT32/dev/hda2 * 541 3249 20480040 7 HPFS/NTFS/dev/hda3 3250 3926 5118120 83 Linux

Each line of the partition contains the following seven columns.

Table 1-1. Column Definitions for fdisk

Column Function

rha130-5.0-0-en-2007-12-13T13:35:30-0500Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use is a violation

of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrievalsystem, or otherwise duplicated whether in electronic or print

format without prior written consent of Red Hat, Inc. If you b elieve Red Hat course materials are being used, copied, or otherwise improperly distributed please email

[email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919) 754 3700.

10

Page 11: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 1. Disk Recognition and Partitioning

Column Function

Device The device node which references the partition, commonly used as the"name" of the partition.

Boot Identifies the "bootable" partition. On each disk, one of theprimarypartitions may be labeled "bootable". Although not used by Linux (it is usedby the MS/DOS bootloader),fdisk does report and allow the user to set thebootable partition.

Start and End The starting and ending cylinder of the partition.

Blocks The size of the partition, in "blocks" of 1024 bytes (i.e, 1k). Usually, this isredundant (albeit convenient) information, as it can be calculated fromcylinder boundaries. For example, for the partition/dev/hda2, multiplyingthe number of cylinders by the number of kilobytes per cylinder yields20480040 exactly.Sometimes, especially when examining disks partitioned bysome utilityother thanfdisk, cylinders do not fall exactly on cylinder boundaries. Forexample, when performing similar math on the first partition(/dev/hda1),the reported number of bytes is exactly 32 kilobytes short. In suchsituations,fdisk flags the reported number of blocks with an appended “+”.

Id A 2 digit hexadecimal number representing the partition’s type Id.

System A text name for the partition type, as defined by the Id.

Partition Labels

As seen in the above table, the partition table includes a onebyte identifier that is used to assign thepartition’s "Id" (sometimes referred to as the partition’s"type", or the partition’s "label"). The Id is usedto identify the role for the partition: is it to be used as swapspace, an ext3 filesystem, a FAT filesystem,part of Linux Volume Management, or an extended partition?

Many different operating systems follow the same partitionId naming conventions. The following tablelists partition types which occur commonly within Linux, inapproximate order of how commonly theyoccur.

Table 1-2. Partition Id’s Relevant to Linux

Id Label Role

83 Linux A Linux ext2 or ext3 filesystem

82 Linux Swap A Linux swap (virtual memory) partition

8e Linux LVM A Linux logical volume management physicalvolume

fd Linux raid auto A Linux software RAID partition

In Linux, partition Ids are often cosmetic. A partition labeledLinuxmay be initialized and used for swapspace, while a partition labeledLinux Swapmay be used as an ext2 filesystem. Some Ids, however, aresignificant to the Linux kernel (for instance,Linux raid auto), and many are significant to other operatingsystems which might be sharing the same disk. Good practice suggests that each partition’s Id should

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

11

Page 12: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 1. Disk Recognition and Partitioning

reflect its intended use.

Using fdisk to Edit a Partition Table

Starting fdisk and Using the Command Menu

When usingfdisk to edit a partition table, thefdisk command should be called with a single argument:the device node of thedisk to be edited.

[root@station root]# fdisk /dev/hda

The number of cylinders for this disk is set to 15505.There is nothing wrong with that, but this is larger than 1024,and could in certain setups cause problems with:1) software that runs at boot time (e.g., old versions of LILO)2) booting and partitioning software from other OSes

(e.g., DOS FDISK, OS/2 FDISK)

Command (m for help):

As fdisk starts, it issues a warning that the disk exceeds 1024 cylinders. Some older BIOS’s are limitedto only accessing the first 1024 cylinders, a topic covered ina later Workbook. Usually, this warning canbe safely ignored. Next,fdisk waits patiently to be told what to do next.

Note: One of the most common mistakes by new users is to invoke fdisk with the name of apartition, instead of a disk . For example, fdisk /dev/hda3 would cause fdisk to exit with an error.Partitions do not have partition tables to edit; disks do.

In interactive (editing) mode,fdisk expects to be driven with single letter commands. The command “m”displays a list of possible commands.

Command (m for help): m

Command actiona toggle a bootable flagb edit bsd disklabelc toggle the dos compatibility flagd delete a partitionl list known partition typesm print this menun add a new partitiono create a new empty DOS partition tablep print the partition tableq quit without saving changess create a new empty Sun disklabelt change a partition’s system idu change display/entry unitsv verify the partition tablew write table to disk and exitx extra functionality (experts only)

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use isa violation of U.S. and international copyrights. No part ofthis publication may be photocopied, duplicated, stored ina retrieval system, or otherwise duplicated whetherin electronic or print format without prior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, or otherwise improperly distributedplease email [email protected] or phone toll-free (USA)+1 866 626 2994 or +1 (919) 754 3700.

12

Page 13: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 1. Disk Recognition and Partitioning

Fortunately, most users can survive using a small subset of these commands.

Table 1-3. Commonly Used fdisk Commands

Command Function

m list command (m)enu

p (p)rint partition table

n create (n)ew partition

d (d)elete partition

t change partition (t)ype (Id)

q (q)uit without saving changes

w (w)rite changes and exit

Often, a user’s first action is orient themselves by using the“p” command to print the current partitiontable.

Command (m for help): p

Disk /dev/hda: 120.0 GB, 120034123776 bytes240 heads, 63 sectors/track, 15505 cylindersUnits = cylinders of 15120 * 512 = 7741440 bytes

Device Boot Start End Blocks Id System/dev/hda1 1 540 4082368+ b Win95 FAT32/dev/hda2 * 541 3249 20480040 7 HPFS/NTFS/dev/hda3 3250 3926 5118120 83 Linux

We see again the partition table for the disk/dev/hda, with three primary partitions and over 80gigabytes of free space.

Adding a Partition

In our discussion, we assume that the administrator wants tocreate two new partitions. The first will beused as a 512 megabyte swap space, and the second will be used as a 1024 megabyte ext3 filesystem.The “n” command is used to create a new partition.

Command (m for help): n

Command actione extendedp primary partition (1-4)

The next question depends on the state of the drive. If no extended partitions exist (our case),fdisk asksif the new partition should be the extended partition, or a (normal) primary partition. If an extendedpartition does exist,fdisk asks if the new partition should be logical or primary. If allprimary partitionsare used,fdisk just doesn’t ask.

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

13

Page 14: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 1. Disk Recognition and Partitioning

Because three primary partitions already exist, and our administrator wants to create 2 new partitions,she must first create an extended partition to hold them. She answers “e”. Next, fdisk prompts for thestarting cylinder number for the partition. Our administrator just pressesRETURN, accepting thesuggested default 3927 (the first available cylinder).

Selected partition 4First cylinder (3927-15505, default 3927): RETURN

Next, fdisk asks for the ending cylinder number.

Using default value 3927Last cylinder or +size or +sizeM or +sizeK (3927-15505, default 15505):

Four different formats can be used when specifying the ending cylinder.

Format Interpretation

n Use ending cylindern.

+n Use starting cylinder incremented byn cylinders.

+nM Use starting cylinder incremented byn megabytes. (A trailingK implieskilobytes).

RETURN Use the suggested default, which is chosen to make the resulting partition aslarge as possible.

Because the extended partitionis a primary partition, it will be the fourth (and thus last) primary partitionon the disk. Since any disk space not included in the extendedpartition will become inaccessible, there isno reason not to use the suggested cylinder (which is the lastcylinder on the disk).

Our administrator does so, and then prints the new partitiontable.

Using default value 15505

Command (m for help): p

Disk /dev/hda: 120.0 GB, 120034123776 bytes240 heads, 63 sectors/track, 15505 cylindersUnits = cylinders of 15120 * 512 = 7741440 bytes

Device Boot Start End Blocks Id System/dev/hda1 1 540 4082368+ b Win95 FAT32/dev/hda2 * 541 3249 20480040 7 HPFS/NTFS/dev/hda3 3250 3926 5118120 83 Linux/dev/hda4 3927 15505 87537240 5 Extended ➊

Command (m for help):

➊ The newly added extended partition, which spans the rest of the drive.

Happy with the results, she next proceeds to add a new 512 megabyte partition. Because all four primarypartitions are now used,fdisk does not prompt for the partition type. A logical partition is the only typeavailable.

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use isa violation of U.S. and international copyrights. No part ofthis publication may be photocopied, duplicated, stored ina retrieval system, or otherwise duplicated whetherin electronic or print format without prior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, or otherwise improperly distributedplease email [email protected] or phone toll-free (USA)+1 866 626 2994 or +1 (919) 754 3700.

14

Page 15: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 1. Disk Recognition and Partitioning

Command (m for help): n

First cylinder (3927-15505, default 3927): RETURN ➊

Using default value 3927Last cylinder or +size or +sizeM or +sizeK (3927-15505, default 15505): +512M ➋

Command (m for help): p

Disk /dev/hda: 120.0 GB, 120034123776 bytes240 heads, 63 sectors/track, 15505 cylindersUnits = cylinders of 15120 * 512 = 7741440 bytes

Device Boot Start End Blocks Id System/dev/hda1 1 540 4082368+ b Win95 FAT32/dev/hda2 * 541 3249 20480040 7 HPFS/NTFS/dev/hda3 3250 3926 5118120 83 Linux/dev/hda4 3927 15505 87537240 5 Extended/dev/hda5 3927 3993 506488+ 83 Linux ➌

Command (m for help):

➊ By simply pressingRETURN, the default starting cylinder is accepted.

➋ The syntax+512M specifies that the partition should be 512 megabytes in size (or as close aspossible).

➌ The newly added logical partition.

Even though she asked for a 512 megabyte partition, the resulting partition is closer to 506 megabytes.Because partitions must fall on cylinder boundaries, and (for this drive) a cylinder is about 7.5 megabytesin size,fdisk did the best it could.

Changing a Partition’s Label

By default, whenfdisk adds a partition, the partition Id is set to "Linux" (appropriate for a partition thatwill contain an ext2 or ext3 filesystem). Because she plans touse the partition for swap space, she wouldlike to set the partition Id appropriately. She uses the “t” command to set the partitions type, andspecifies the appropriate partition. Taking advantage of the ability to list all known labels, she locates theappropriate "Linux swap" label, and its associated hex code, “82”.

Command (m for help): t

Partition number (1-5): 5

Hex code (type L to list codes): L

0 Empty 1c Hidden Win95 FA 70 DiskSecure Mult bb Boot Wizard hid1 FAT12 1e Hidden Win95 FA 75 PC/IX be Solaris boot2 XENIX root 24 NEC DOS 80 Old Minix c1 DRDOS/sec (FAT-3 XENIX usr 39 Plan 9 81 Minix / old Lin c4 DRDOS/sec (FAT-4 FAT16 <32M 3c PartitionMagic 82 Linux swap c6 DRDOS/sec (FAT-5 Extended 40 Venix 80286 83 Linux c7 Syrinx6 FAT16 41 PPC PReP Boot 84 OS/2 hidden C: da Non-FS data7 HPFS/NTFS 42 SFS 85 Linux extended db CP/M / CTOS / .

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use isa violation of U.S. and international copyrights. No part ofthis publication may be photocopied, duplicated, stored ina retrieval system, or otherwise duplicated whetherin electronic or print format without prior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, or otherwise improperly distributedplease email [email protected] or phone toll-free (USA)+1 866 626 2994 or +1 (919) 754 3700.

15

Page 16: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 1. Disk Recognition and Partitioning

8 AIX 4d QNX4.x 86 NTFS volume set de Dell Utility9 AIX bootable 4e QNX4.x 2nd part 87 NTFS volume set df BootIta OS/2 Boot Manag 4f QNX4.x 3rd part 8e Linux LVM e1 DOS accessb Win95 FAT32 50 OnTrack DM 93 Amoeba e3 DOS R/Oc Win95 FAT32 (LB 51 OnTrack DM6 Aux 94 Amoeba BBT e4 SpeedStore Win95 FAT16 (LB 52 CP/M 9f BSD/OS eb BeOS fsf Win95 Ext’d (LB 53 OnTrack DM6 Aux a0 IBM Thinkpad hi ee EFI GPT

10 OPUS 54 OnTrackDM6 a5 FreeBSD ef EFI (FAT-12/16/11 Hidden FAT12 55 EZ-Drive a6 OpenBSD f0 Linux/PA-RISC b12 Compaq diagnost 56 Golden Bow a7 NeXTSTEP f1 SpeedStor14 Hidden FAT16 <3 5c Priam Edisk a8 Darwin UFS f4 SpeedStor16 Hidden FAT16 61 SpeedStor a9 NetBSD f2 DOS secondary17 Hidden HPFS/NTF 63 GNU HURD or Sys ab Darwin boot fd Linux raid auto18 AST SmartSleep 64 Novell Netware b7 BSDI fs fe LANstep1b Hidden Win95 FA 65 Novell Netware b8 BSDI swap ff BBTHex code (type L to list codes): 82

Changed system type of partition 5 to 82 (Linux swap)

Command (m for help): p

Disk /dev/hda: 120.0 GB, 120034123776 bytes240 heads, 63 sectors/track, 15505 cylindersUnits = cylinders of 15120 * 512 = 7741440 bytes

Device Boot Start End Blocks Id System/dev/hda1 1 540 4082368+ b Win95 FAT32/dev/hda2 * 541 3249 20480040 7 HPFS/NTFS/dev/hda3 3250 3926 5118120 83 Linux/dev/hda4 3927 15505 87537240 5 Extended/dev/hda5 3927 3993 506488+ 82 Linux swap ➊

Command (m for help):

➊ The partition label, which was "Linux", has changed to "Linux swap".

Adding a Second Partition

The administrator now proceeds to add the second partition.

Command (m for help): n

First cylinder (3994-15505, default 3994): RETURN

Using default value 3994Last cylinder or +size or +sizeM or +sizeK (3994-15505, default 15505): +1024M

Command (m for help): p

Disk /dev/hda: 120.0 GB, 120034123776 bytes240 heads, 63 sectors/track, 15505 cylindersUnits = cylinders of 15120 * 512 = 7741440 bytes

Device Boot Start End Blocks Id System/dev/hda1 1 540 4082368+ b Win95 FAT32

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use isa violation of U.S. and international copyrights. No part ofthis publication may be photocopied, duplicated, stored ina retrieval system, or otherwise duplicated whetherin electronic or print format without prior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, or otherwise improperly distributedplease email [email protected] or phone toll-free (USA)+1 866 626 2994 or +1 (919) 754 3700.

16

Page 17: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 1. Disk Recognition and Partitioning

/dev/hda2 * 541 3249 20480040 7 HPFS/NTFS/dev/hda3 3250 3926 5118120 83 Linux/dev/hda4 3927 15505 87537240 5 Extended/dev/hda5 3927 3993 506488+ 82 Linux swap/dev/hda6 3994 4126 1005448+ 83 Linux ➊

Command (m for help):

➊ The newly added partition.

Deleting a Partition

Were the administrator to make a mistake, or needed to removea partition to create more room, deletinga partition is straightforward, and would look like the following.

Command (m for help): d

Partition number (1-6): 4

There are only a couple of details to note.

1. If an extended partition is deleted, all logical partitions that it contains are deleted as well.

2. Because the partitioning information for logical partitions is maintained as a linked list, they must benumbered consecutively. If partition number 5 of 7 is deleted, partitions 6 and 7 will becomepartitions 5 and 6. (This is not the case for primary partitions.)

Exiting fdisk

When finished, there are two ways to exitfdisk. First, the “q” command can be used to "quit"fdisk,abandoning any changes. Thefdisk utility does not write any changes until specifically instructed to, sousers may safely quit at any time.

With the “w” command, fdisk will "write" changes and exit. This is the normal way to exitfdisk,implementing any specified edits.

Command (m for help): w

The partition table has been altered!

Calling ioctl() to re-read partition table.

WARNING: Re-reading the partition table failed with error 16: Device or resource busy.The kernel still uses the old table.The new table will be used at the next reboot.Syncing disks.

While exiting,fdisk warns that the changes will not take effect until the next reboot. This is a fib.Rebooting will cause the change to take affect, but so will running a relatively newer calledpartprobe.

The administrator runspartprobe, so the kernel will reread the partition table and implementthechanges.

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use isa violation of U.S. and international copyrights. No part ofthis publication may be photocopied, duplicated, stored ina retrieval system, or otherwise duplicated whetherin electronic or print format without prior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, or otherwise improperly distributedplease email [email protected] or phone toll-free (USA)+1 866 626 2994 or +1 (919) 754 3700.

17

Page 18: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 1. Disk Recognition and Partitioning

[root@station root]# partprobe

Viewing Partitions in /proc/partitions

As an alternative tofdisk -l (which only root has permissions to perform), the proc filesystem file/proc/partitions lists all known partitions, as well as sizes (in blocks of 1024 bytes) and activitystatistics.

[root@station root]# cat /proc/partitions

major minor #blocks name

3 0 117220824 hda3 1 4082368 hda13 2 20480040 hda23 3 5118120 hda33 64 78150744 hdb3 65 72261 hdb13 66 2096482 hdb23 67 8289540 hdb33 69 30724281 hdb53 70 8385898 hdb63 71 28579603 hdb7

Notice the prominence of the major and minor number of each partition (and disk) in the output. TheLinux kernel internally identifies a partition by the major and minor number associated with its devicedriver, not by the name of the device node, a fact that is oftenobserved in kernel level error messages.

Examples

Partitioning a New DriveIn this example, we look over the shoulders of the user prince, who has just attached a new disk to hismachine. He would like to divide his new disk into the following partitions.

Number Size Purpose

1 128 megs swap space

2 512 megs ext2 filesystem

3 512 megs vfat filesystem

4 1024 megs ext3 filesystem

Upon first booting the machine, after the new drive has been connected, prince skims the kernel bootmessages for evidence of the newly detected drive. Unfortunately, the kernel is too fast for his monitor,which does not power up to full strength until after the messages have past.

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use isa violation of U.S. and international copyrights. No part ofthis publication may be photocopied, duplicated, stored ina retrieval system, or otherwise duplicated whetherin electronic or print format without prior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, or otherwise improperly distributedplease email [email protected] or phone toll-free (USA)+1 866 626 2994 or +1 (919) 754 3700.

18

Page 19: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 1. Disk Recognition and Partitioning

Once the system has booted, prince skims the/var/log/dmesg file, where he finds the following lines.

...hda: Maxtor 51536H2, ATA DISK drivehdb: ST310212A, ATA DISK driveblk: queue c03cdfe0, I/O limit 4095Mb (mask 0xffffffff)blk: queue c03ce124, I/O limit 4095Mb (mask 0xffffffff)hdc: LTN485, ATAPI CD/DVD-ROM driveide0 at 0x1f0-0x1f7,0x3f6 on irq 14ide1 at 0x170-0x177,0x376 on irq 15hda: attached ide-disk driver.hda: host protected area => 1hda: 29336832 sectors (15020 MB) w/2048KiB Cache, CHS=1940/240/63, UDMA(66)hdb: attached ide-disk driver.hdb: host protected area => 1hdb: 20005650 sectors (10243 MB) w/512KiB Cache, CHS=1323/240/63, UDMA(66)ide-floppy driver 0.99.newide...

Convinced that his new drive is being detected correctly, hebegins partitioning the drive with thefdiskcommand. He first prints the partition table with the “p” command.

[root@station root]$ fdisk /dev/hdb

The number of cylinders for this disk is set to 1323.There is nothing wrong with that, but this is larger than 1024,and could in certain setups cause problems with:1) software that runs at boot time (e.g., old versions of LILO)2) booting and partitioning software from other OSs

(e.g., DOS FDISK, OS/2 FDISK)

Command (m for help): p

Disk /dev/hdb: 10.2 GB, 10242892800 bytes240 heads, 63 sectors/track, 1323 cylindersUnits = cylinders of 15120 * 512 = 7741440 bytes

Device Boot Start End Blocks Id System

Command (m for help):

As expected, the partition table is empty. As he proceeds to add his first partition, the only reallyinteresting interaction is when he specifies the partition’s size, using+128M.

Command (m for help): n

Command actione extendedp primary partition (1-4)

p

Partition number (1-4): 1First cylinder (1-1323, default 1): RETURNUsing default value 1Last cylinder or +size or +sizeM or +sizeK (1-1323, default 1323): +128M

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use isa violation of U.S. and international copyrights. No part ofthis publication may be photocopied, duplicated, stored ina retrieval system, or otherwise duplicated whetherin electronic or print format without prior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, or otherwise improperly distributedplease email [email protected] or phone toll-free (USA)+1 866 626 2994 or +1 (919) 754 3700.

19

Page 20: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 1. Disk Recognition and Partitioning

Command (m for help): p

Disk /dev/hdb: 10.2 GB, 10242892800 bytes240 heads, 63 sectors/track, 1323 cylindersUnits = cylinders of 15120 * 512 = 7741440 bytes

Device Boot Start End Blocks Id System/dev/hdb1 1 18 136048+ 83 Linux

Because the partition is going to be used as swap space, prince changes the partition’s label to theappropriate code forLinux Swap.

Command (m for help): t

Selected partition 1Hex code (type L to list codes): 82

Changed system type of partition 1 to 82 (Linux swap)

The next two partitions are then added in a straightforward manner.

Command (m for help): n

Command actione extendedp primary partition (1-4)

p

Partition number (1-4): 2

First cylinder (19-1323, default 19): RETURNUsing default value 19Last cylinder or +size or +sizeM or +sizeK (19-1323, default 1323): +512M

Command (m for help): n

Command actione extendedp primary partition (1-4)

p

Partition number (1-4): 3

First cylinder (86-1323, default 86): RETURNUsing default value 86Last cylinder or +size or +sizeM or +sizeK (86-1323, default 1323): +512M

Command (m for help): p

Disk /dev/hdb: 10.2 GB, 10242892800 bytes240 heads, 63 sectors/track, 1323 cylindersUnits = cylinders of 15120 * 512 = 7741440 bytes

Device Boot Start End Blocks Id System/dev/hdb1 1 18 136048+ 82 Linux swap/dev/hdb2 19 85 506520 83 Linux/dev/hdb3 86 152 506520 83 Linux

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

20

Page 21: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 1. Disk Recognition and Partitioning

Although prince only wants to add one more partition now, he will leave unallocated space on the drive.If he were to use his last primary partition for the filesystem, he would no longer be able to make anextended partition, and the remaining space would be wasted. Instead, prince creates an extendedpartition to span the rest of the drive, and then adds his new partition as a logical partition within it.

Command (m for help): n

Command actione extendedp primary partition (1-4)

e

Selected partition 4First cylinder (153-1323, default 153): RETURNUsing default value 153Last cylinder or +size or +sizeM or +sizeK (153-1323, default 1323): RETURNUsing default value 1323

Command (m for help): n

First cylinder (153-1323, default 153): RETURNUsing default value 153Last cylinder or +size or +sizeM or +sizeK (153-1323, default 1323): +1024M

Command (m for help): p

Disk /dev/hdb: 10.2 GB, 10242892800 bytes240 heads, 63 sectors/track, 1323 cylindersUnits = cylinders of 15120 * 512 = 7741440 bytes

Device Boot Start End Blocks Id System/dev/hdb1 1 18 136048+ 82 Linux swap/dev/hdb2 19 85 506520 83 Linux/dev/hdb3 86 152 506520 83 Linux/dev/hdb4 153 1323 8852760 5 Extended/dev/hdb5 153 285 1005448+ 83 Linux

Command (m for help):

Happy with his work, he writes and exits.

Command (m for help): w

The partition table has been altered!

Calling ioctl() to re-read partition table.Syncing disks.

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

21

Page 22: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 1. Disk Recognition and Partitioning

Online Exercises

Lab ExerciseObjective: Use fdisk to add new partitions.

Estimated Time: 10 mins.

SpecificationIn this lab, you will add two small partitions to a disk on yourcomputer.

1. Use thefdisk -l command to confirm that your machine has at least 256 megabytes of unallocatedspace. If your machine has multiple hard drives, the space must exist all on one drive. Create the file~/lab3.1/disk, which contains the name of the disk you will use for this lab,as an absolutereference. For example, if the disk you will use is/dev/hda, the file should contain the single word/dev/hda.

2. Use thefdisk command to edit the drive’s partition table. Note that you will have to use your rootaccount. Add two new partitions, each 128 megabytes in size (or nearly so). Set the partition Id ofthe first newly added partition toLinux Swap. The partition Id of the second newly added partitionshould remainLinux. The two new partitions should be the last two partitions on the drive. Exitfdisk, saving changes.

3. If necessary, reboot your machine in order for the new partitions to be recognized by the kernelbefore grading your lab.

Deliverables

1. The file~/lab3.1/disk, which contains the name of the drive you used for this lab, asan absolute reference.The drive name should be the only word in the file.

2. The next to the last partition on the specified drive shouldbe (nearly) 128 megabytes in size, and have apartition Id ofLinux Swap.

3. The last partition on the specified drive should be (nearly) 128 megabytes in size, and have a partition Id ofLinux.

Questions

Use the output from the following command to answer the next question.

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use is a violation of U.S.and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwise duplicated whether in electronic or print format withoutprior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, or otherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919) 754 3700.

22

Page 23: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 1. Disk Recognition and Partitioning

[root@station root]$ cat /proc/partitions

major minor #blocks nameng use aveq

8 0 8891650 sda8 1 136521 sda18 2 3502170 sda28 3 2096482 sda38 5 2096451 sda5

1. Which of the following best explains why the partition sda4 is not listed in/proc/partitions?

( ) a. The partition has been initialized with a filesystem, but thefilesystem is not mounted.

( ) b. The partition is being used as the extended partition, and therefore is not accessed directly.

( ) c. The partition has been initialized as swap space, but there has not yet been a high demand placed onphysical memory.

( ) d. The disk has not yet had a partition sda4 allocated.

( ) e.None of the above

2. Which of the following partitions could be an extended partition?

( ) a./dev/hda7

( ) b. /dev/sdb5

( ) c./dev/sdb4

( ) d. /dev/hdc8

( ) e.None of the above

3. Which of the following would be a logical partition?

( ) a./dev/hda3

( ) b. /dev/hda5

( ) c./dev/hdb1

( ) d. /dev/hdb4

( ) e.None of the above

4. Which of the following commands would list all known partitions?

( ) a. fdisk --dump

( ) b. dumppart

( ) c. fdisk -l

( ) d. fdisk --list

rha130-5.0-0-en-2007-12-13T13:35:30-0500Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use is a violationof U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrievalsystem, or otherwise duplicated whether in electronic or printformat without prior written consent of Red Hat, Inc. If you b elieve Red Hat course materials are being used, copied, or otherwise improperly distributed please [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919) 754 3700.

23

Page 24: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 1. Disk Recognition and Partitioning

( ) e.None of the above

5. Which of the following commands could be used to add the partition /dev/sda8?

( ) a.fdisk -a /dev/sda8

( ) b. fdisk /dev/sda8

( ) c.fdisk -l /dev/sda8

( ) d. fdisk --add /dev/sda8

( ) e.None of the above

Use the following transcript to answer the next 3 questions.

[root@station root]$ fdisk -l

Disk /dev/hda: 15.0 GB, 15020457984 bytes240 heads, 63 sectors/track, 1940 cylindersUnits = cylinders of 15120 * 512 = 7741440 bytes

Device Boot Start End Blocks Id System/dev/hda1 * 1 14 105808+ 83 Linux/dev/hda2 15 1124 8391600 83 Linux/dev/hda3 1125 1193 521640 82 Linux swap

Disk /dev/hdb: 10.2 GB, 10242892800 bytes240 heads, 63 sectors/track, 1323 cylindersUnits = cylinders of 15120 * 512 = 7741440 bytes

Device Boot Start End Blocks Id System/dev/hdb1 * 1 17 128488+ 83 Linux/dev/hdb2 18 585 4294080 83 Linux/dev/hdb3 586 1323 5579280 83 Linux

6. Assuming that the system Id’s indicate the true use of the partitions, approximately how much partition space isallocated to swap space?

( ) a. 128 megabytes

( ) b. 520 megabytes

( ) c. 8.4 gigabytes

( ) d. 5.5 megabytes

( ) e.Not enough information is provided

rha130-5.0-0-en-2007-12-13T13:35:30-0500Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use is a violationof U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrievalsystem, or otherwise duplicated whether in electronic or printformat without prior written consent of Red Hat, Inc. If you b elieve Red Hat course materials are being used, copied, or otherwise improperly distributed please [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919) 754 3700.

24

Page 25: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 1. Disk Recognition and Partitioning

7. Approximately how much space is left unallocated on the drive/dev/hda?

( ) a. 0

( ) b. 512 megabytes

( ) c. 2 gigabytes

( ) d. 5.75 gigabytes

( ) e.Note enough information is provided

8. Approximately how much space is left unallocated on the drive/dev/hdb?

( ) a. 0

( ) b. 512 megabytes

( ) c. 2 gigabytes

( ) d. 5.75 gigabytes

( ) e.Note enough information is provided

9. After editing the partition table withfdisk, what action must (usually) be taken for the kernel to recognize the newpartitions?

( ) a. The machine must be rebooted.

( ) b. The new partition should be added to/proc/partitions with a text editor.

( ) c. Thepartprobe command should be run.

( ) d. None of the above

( ) e.Either A or C

10.Which of the followingfdisk commands is used to abandon all changes?

( ) a. a

( ) b. q

( ) c. x

( ) d. w

( ) e.z

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

25

Page 26: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 2. Creating and Managing Filesystems

Key Concepts

• Themkfs command, and its filesystem specific friends, are used to create filesystems.

• The most common filesystem in Linux is the ext2 filesystem, andits close cousin, the ext3 filesystem.

• The ext3 filesystem is exactly like the ext2 filesystem, with the added feature of journaling.

• Thedumpe2fscommand can be used to examine ext2 and ext3 filesystems.

Discussion

FilesystemsAt the lowest level, block device nodes allow disks and disk partitions to be accessed as if they weresimply an array of bytes (recall the Unix mantra, "everything is a file"). But when Linux users storeinformation on disks, they prefer to use the familiar constructs of files and directories. Somehow, thisarray of bytes that is a disk partition must be made to act likethe/home/elvis directory, and the files itcontains.

The Linux kernel implements avirtual filesystem layer, which dictates that everything that exists in adirectory tree, such as regular files, directories, device nodes, and symbolic links, must have a uniformstructure which consists of the following elements.

inodes

Inodes store all of the metadata associated with a file. A file’s metadata is all of the informationassociated with a file, except for its name and its content. For example, a file’s ownerships,permissions, and modify time are all stored in it’s inode. More than anything else, the inodeprovides the identity of the file.

dentries

Dentries, whose name is a shortening of the term "Directory Entries", contain a file’s name andlocation within the directory structure, and associate this identity with the file’s inode.

data

Lastly, every file has an array of bytes which constitute its content and are referenced by the file’sinode.

The intermediate structure which occurs on a disk or disk partition that defines a particular chunk ofbytes as containing dentries, and another chunk of bytes as containing the inodes which the dentriesreference, and another chunk of bytes as containing the datawhich the inodes reference, is referred to as

26

Page 27: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 2. Creating and Managing Filesystems

a filesystem. In other operating systems, the act of initializing the filesystem on a particular partition isreferred to asformattingthe partition. In Linux (and Unix), the act is usually simplyreferred to ascreating a filesystem.

Linux FilesystemsFilesystem design is a general problem in computer engineering, and much time and effort has beendevoted to designing filesystems which balance efficiency, robustness, capability, and simplicityappropriately for a given situation. Because a filesystem must be closely coordinated with the operatingsystem that supports it, most operating systems only support one or two filesystems which are considered"native" to that operating system.

In contrast, Linux supports a large number of filesystems, some of which are native to Linux, many ofwhich are shared with other operating systems. The following table contains a partial list of filesystemssupported by Linux.

Table 2-1. Filesystems Supported in Linux

Filesystem Comments

ext2 The ext2 ("extended 2") filesystem has been the native filesystem of Linuxduring its rise in popularity from the mid 1990’s. The ext2 filesystem is themodel around which the virtual filesystem layer is designed,and nativelyimplements almost all of the features expected from a filesystem underLinux.

ext3 The ext3 ("extended 3") filesystem, introduced around the year 2000, is anextension of the ext2 filesystem that supports journaling. In every other way,the ext3 filesystem is identical to the ext2 filesystem, and what is said aboutone generally applies to the other. The ext3 filesystem is thedefaultfilesystem in Red Hat Enterprise Linux.

msdos The msdos filesystem is the FAT filesystem used by DOS and Windows. Itdoes not support many advanced features, such as file ownerships andpermissions, and file names consist of at most 8 characters with a 3 characterextension.

vfat The vfat filesystem is an extension of the msdos filesystem that allows longfilenames.

nfs The nfs "network filesystem" is used to share directories between Linux (andUnix) machines. One machine exports part of its directory structure over thenetwork, which another machine may import into its local directory structureat the filesystem level.

smbfs The smbfs filesystem is used to share directories between Linux (and Unix)and Windows machines. Using smbfs, a Linux machine can incorporate anexported Windows share into its local directory structure.

iso9660 The iso9660 filesystem is a read-only filesystem commonly used on compactdisks.

rha130-5.0-0-en-2007-12-13T13:35:30-0500Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use is a violation

of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrievalsystem, or otherwise duplicated whether in electronic or print

format without prior written consent of Red Hat, Inc. If you b elieve Red Hat course materials are being used, copied, or otherwise improperly distributed please email

[email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919) 754 3700.

27

Page 28: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 2. Creating and Managing Filesystems

Filesystem Comments

proc The proc filesystem is a virtual filesystem that resides entirely within thekernel (i.e., there is no hard disk associated with the filesystem).

reiserfs The reiserfs is an alternate journaling filesystem native toLinux andsupported by Red Hat Enterprise Linux.

jfs The jfs "journaling filesystem" is a mature journaling filesystem with manyenterprise features native to IBM machines. The jfs filesystem has beenrecently open sourced and ported to Linux, and is supported by Red HatEnterprise Linux.

More could be added to the table, but hopefully the point has been made that Linux features support for awide variety of filesystems. The curious should start with the fs(5)man page for more information. Wewill discuss the ext2/ext3 filesystem in some detail, and acquaint ourselves with a few others from thetable as well.

Creating FilesystemsBefore a block device can be used to store files, it must be initialized with a filesystem. In Red HatLinux, some variant of themkfs command is used to create filesystems. These commands tend toresidein the/sbin directory.

[root@station root]# ls /sbin/mkfs.*mkfs.cramfs mkfs.ext2 mkfs.ext3 mkfs.msdos mkfs.vfat

Themkfs command is a front-end command that expects to be called withthe-t command line switch,whose argument is the filesystem type to create. The other listed commands, which startmkfs., arefilesystem specific variants for particular filesystems. Forexample,mkfs -t ext2 andmkfs.ext2 areequivalent commands.

Initializing a partition can be as easy as the following.

[root@station root]# mkfs.ext2 /dev/hda6

All versions of themkfs commands expect some optional, filesystem specific command line switches,and a required first argument which is the file (partition) to structure. An optional, seldom used secondargument may also be used, which specifies the size of the filesystem in blocks. The second argument isseldom used because, by default, the filesystem will fill the entire specified partition or disk. Whileanyone has permissions to execute themkfs commands, in practice, only root has permissions to write tothe block device nodes that are being initialized.

Creating ext2 Filesystems: mke2fsThe most common filesystem encountered in Linux is the ext2 filesystem, or its close cousin the ext3filesystem. Our discussion will focus on the ext2 filesystem.Near its conclusion, we will find that all thatis said about the ext2 filesystem applies directly to the ext3filesystem as well.

Because the ext2 filesystem is so commonly used, yet another command synonymous withmkfs.ext2exists, namelymke2fs. The commandsmke2fs, mkfs.ext, andmkfs -t ext2 yield identical results.

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

28

Page 29: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 2. Creating and Managing Filesystems

Command Line Switches

The following table specifies some of themke2fscommand’s more commonly used command lineswitches.

Table 2-2. Command Line Switches for the mke2fs Command

Switch Effect

-b blocksize Specify the filesystem blocksize in bytes, whereblocksize may be one of1024, 2048, or 4096.

-c Check for bad block while creating the filesystem.

-i density Specify an inode density ofdensity bytes per inode.

-L label Set the volume label of the filesystem tolabel.

-m n Set the reserved block percentage ton.

-N number Directly specify the number of inodes.

-j Create a filesystem journal

The command line switches introduce some filesystem concepts which are addressed below.

Filesystem Labels (-L)

Like most filesystems, an ext2 filesystem can be labeled with atext string identifier, which is at most 16characters. Other operating systems often refer to this label as avolume name(as they refer to a partitionformatted with a filesystem as avolume). We will discover that Red Hat Enterprise Linux makesfunctional use of filesystem labels.

Block Size (-b)

Above, we ambiguously mentioned organizing a filesystem around "chunks of bytes", as in "this chunkof bytes is storing inodes, while this chunk of bytes is storing dentries." The chunks we refer to are moreappropriately calledblocks, and when creating a filesystem, ablock sizehas to be decided. The ext2filesystem supports block sizes of 1024, 2048, and 4096 bytes("1k", "2k", and "4k", respectively).

The block size establishes the granularity of the filesystem. When space on the filesystem is devoted tostoring the contents of a particular file, the space is allocated in fixed size blocks of the specified blocksize. For example, if the block size were 1024 bytes, then storing a file with 5000 bytes of data wouldrequire 5 blocks. The same file stored in a filesystem with a block size of 4096 would require 2 blocks.Once a block has been assigned to a particular purpose, it cannot be used for anything else.

At first glance, a smaller block size seems to result in less wasted space. In the above example, the filesystem with a block size of 1k wastes about 1020 bytes (the remainder of the fifth block), while thefilesystem with a blocksize of 4k wastes 4092 bytes (the remainder of the second block). However, asmaller blocksize requires more overhead on the part of the filesystem. For example, the filesystem needsto maintain an internal table of which blocks have been used,and for what purpose. Again referring tothe above example, the filesystem with a 1k blocksize has to keep track of 5 blocks, while the filesystemwith a 4k blocksize only has to keep track of 2.

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

29

Page 30: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 2. Creating and Managing Filesystems

As a general rule, the larger the filesystem, the larger the appropriate block size. By default, themke2fschooses a block size of either 1k or 4k, depending on the size of the filesystem being created.

Inodes (-N or -i)

Every file is directly associated with a structure called an inode. An inode must exist for each file in thefilesystem. The number of inodes that a filesystem contains needs to be specified as the filesystem iscreated. Because the number of inodes cannot be changed later, care must be taken to estimate thenumber of required inodes conservatively.

Usually, themke2fscommand chooses appropriate default settings. In a couple of situations, however,the number of inodes may need to be specified directly.

• When a filesystem is expected to contain a large number of small files, the number of inodes may needto be increased, or the filesystem may run out.

• When the filesystem is expected to contain a small number of large files, the excess amount of spacedevoted to unused inodes takes away from space that could potentially be used for storing data. As aresult, the number of inodes may want to be decreased.

There are two ways to specify the number of inodes. The-N command line switch can be used to specifyan absolute number of inodes. For situations where a statement such as "This filesystem will nevercontain more than 18,112 files." can be made, this switch is appropriate. In contrast, the-i command lineswitch is used to specify an inodedensity, in bytes per inode. When constructing the filesystem, themke2fscommand will divide the total size of the filesystem by the density (or, more exactly, theinverse-density) to determine the number of inodes. For situations where statements such as "I expect myaverage file size to be 180 kilobytes" can be made, this is the appropriate switch.

Reserved Blocks

By default, the ext2 filesystem reserves 5% of its space for the root user. This feature attempts to providethe administrator a little bit of wiggle room if a user on the system accidentally (or intentionally) fills theentire filesystem. The-m command line switch allows the percentage of blocks to reserve to be specified.

Examining Filesystems with dumpe2fsAs the name implies, thedumpe2fscommand dumps to standard out low level information about anext2filesystem. In the following example, themke2fscommand is used to create a filesystem on the partitionsda1 with default options.

[root@station root]# mke2fs /dev/sda1

mke2fs 1.39 (29-May-2006)Filesystem label= ➊

OS type: LinuxBlock size=1024 (log=0) ➋

Fragment size=1024 (log=0)31744 inodes, 126960 blocks ➌

6348 blocks (5.00%) reserved for the super user

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use isa violation of U.S. and international copyrights. No part ofthis publication may be photocopied, duplicated, stored ina retrieval system, or otherwise duplicated whetherin electronic or print format without prior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, or otherwise improperly distributedplease email [email protected] or phone toll-free (USA)+1 866 626 2994 or +1 (919) 754 3700.

30

Page 31: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 2. Creating and Managing Filesystems

First data block=116 block groups8192 blocks per group, 8192 fragments per group1984 inodes per groupSuperblock backups stored on blocks:

8193, 24577, 40961, 57345, 73729

Writing inode tables: doneWriting superblocks and filesystem accounting information: done

This filesystem will be automatically checked every 39 mounts or180 days, whichever comes first. Use tune2fs -c or -i to override.

As the filesystem is being created, themke2fscommand displays details about the new filesystem,including the following.

➊ The specified filesystem label (in this case, none).

➋ The blocksize (chosen bymke2fs, if not specified on the command line). In this case, 1024 bytes.

➌ The number of inodes and blocks in the filesystem.

After the filesystem has been created, thedumpe2fscommand is used to examine its details. Thedumpe2fscommand expects to be called with a single argument, the nameof a file (disk or partition)that contains an ext2 filesystem.

[root@station root]# dumpe2fs /dev/sda1

dumpe2fs 1.39 (29-May-2006)Filesystem volume name: /boot ➊

Last mounted on: <not available>Filesystem UUID: dcf63b6b-157f-4493-a257-5221a44c37b9Filesystem magic number: 0xEF53Filesystem revision #: 1 (dynamic)Filesystem features: filetype sparse_super ➋

Default mount options: user_xattr acl ➌

Filesystem state: cleanErrors behavior: ContinueFilesystem OS type: LinuxInode count: 31744 ➍

Block count: 126960 ➎

Reserved block count: 6348Free blocks: 122934Free inodes: 31733First block: 1Block size: 1024 ➏

Fragment size: 1024Blocks per group: 8192Fragments per group: 8192Inodes per group: 1984Inode blocks per group: 248Filesystem created: Fri Sep 26 17:17:53 2003Last mount time: n/aLast write time: Fri Sep 26 17:17:54 2003Mount count: 0

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use isa violation of U.S. and international copyrights. No part ofthis publication may be photocopied, duplicated, stored ina retrieval system, or otherwise duplicated whetherin electronic or print format without prior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, or otherwise improperly distributedplease email [email protected] or phone toll-free (USA)+1 866 626 2994 or +1 (919) 754 3700.

31

Page 32: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 2. Creating and Managing Filesystems

Maximum mount count: 39Last checked: Fri Sep 26 17:17:53 2003Check interval: 15552000 (6 months)Next check after: Wed Mar 28 18:17:53 2004Reserved blocks uid: 0 (user root)Reserved blocks gid: 0 (group root)First inode: 11Inode size: 128

Group 0: (Blocks 1-8192) ➐

Primary superblock at 1, Group descriptors at 2-2Block bitmap at 3 (+2), Inode bitmap at 4 (+3)Inode table at 5-252 (+4)7927 free blocks, 1973 free inodes, 2 directoriesFree blocks: 266-8192Free inodes: 12-1984

Group 1: (Blocks 8193-16384)Backup superblock at 8193, Group descriptors at 8194-8194

...

➊ The filesystem label. Unlike many versions of Linux, Red Hat Enterprise Linux makes functionaluse of the volume label. For reasons we will see, Anaconda initializes volume labels with theintended mount point of the filesystem. The label can later bechanged with thee2labelcommand.

➋ The ext2 filesystem can have several features enabled, whichwould be listed here.

➌ The Anaconda installer embeds theacl mount option into the filesystem superblock, so that Red HatEnterprise Linux filesystems (which were created at installtime) support access control lists bydefault. Access control lists will be covered in more detailin a later lesson.

➍ The number of inodes in the filesystem.

➎ The number of blocks in the filesystem. Dividing this value bythe number of inodes (found on theprevious line), we find that by default, themke2fscommand included one inode for every fourblocks.

➏ The blocksize, in this case 1024 bytes ("1k"). Because the partition was relatively small (126960blocks at "1k" each = about 127 megabytes), themke2fscommand chose the smaller block size.

➐ Lastly, themke2fscommand generates an accounting of free blocks and other information for eachof several block groups. The role of block groups in the ext2 filesystem structure is beyond the scopeof this discussion.

More detailed information about the design of the ext2 filesystem can be found athttp://e2fsprogs.sourceforge.net.

Filesystem FeaturesWe now use thedumpe2fscommand to examine a currently mounted/dev/hda3 partition.

[root@station root]# dumpe2fs /dev/hda3

dumpe2fs 1.39 (29-May-2006)

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use isa violation of U.S. and international copyrights. No part ofthis publication may be photocopied, duplicated, stored ina retrieval system, or otherwise duplicated whetherin electronic or print format without prior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, or otherwise improperly distributedplease email [email protected] or phone toll-free (USA)+1 866 626 2994 or +1 (919) 754 3700.

32

Page 33: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 2. Creating and Managing Filesystems

Filesystem volume name: / ➊

Last mounted on: <not available>Filesystem UUID: c6c6c0ec-6430-470d-b371-754503e49ff6Filesystem magic number: 0xEF53Filesystem revision #: 1 (dynamic)Filesystem features: has_journal filetype needs_recovery sparse_super ➋

Default mount options: (none)Filesystem state: cleanErrors behavior: ContinueFilesystem OS type: LinuxInode count: 652800Block count: 1303273Reserved block count: 65163Free blocks: 148316Free inodes: 418518First block: 0Block size: 4096 ➌

Fragment size: 4096...

➊ In this case, the filesystem has been given a label of “/”.

➋ The filesystem features. More on these below.

➌ The blocksize of the filesystem is 4096 bytes.

In the above output, a couple of filesystem features merit attention.

needs_recovery

Recall from the previous Workbook that the kernel buffers all I/O activity associated with block devices.While this provides a wonderful boost to performance, if thekernel were to shutdown for some reasonbefore committing any pending writes from its in memory cache, the internal information of thefilesystem (i.e., which blocks are being used for what purpose) could be left in an inconsistent state.

When a filesystem is mounted (i.e., used. More on this in the next Lesson), itsneeds_recoveryflag is set.If the filesystem is unmounted through normal techniques, aswhen the system is shut down from thecommand line, the kernel has an opportunity to flush its pending writes to disk, and theneeds_recoveryflag is removed. If the filesystem is not cleanly unmounted, however, as when the system loses power oris switched off without being shut down, theneeds_recoveryflag never gets cleared. When next used(upon next boot, for example), theneeds_recoveryflag will be discovered, and maintenance will beperformed on the filesystem.

has_journal

Themke2fscommand subtly mentions that this ext2 filesystem has an associated journal. Earlier, westated that the ext3 filesystem is just an ext2 filesystem witha journal. What are we left to conclude? Weare using thedumpe2fscommand to examine what is really an ext3 filesystem! Again, the ext3filesystem is just an ext2 filesystem with the added "feature"of a journal.

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

33

Page 34: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 2. Creating and Managing Filesystems

The ext3 Journaling Filesystem

Journaling Filesystems

What is the importance of a journaling filesystem? A journaling filesystem maintains a log of all of itspending transactions, through a process commonly referredto as a "two phase commit". When writinginformation to disk, a journaling filesystem takes an approach similar to the following.

1. The filesystem writes to the journal the details about the transaction it is about to perform.

2. The filesystem performs the transaction.

3. Upon successful completion, the filesystem removes the details about the transaction from thejournal.

What is gained by this extra work? Just as the captain’s log isused tell rescuers what was happening onthe ship when disaster struck, the filesystem’s journal tells filesystem repair utilities what the filesystemwas up to when a filesystem crash occurs.

When repairing an ext2 filesystem, which does not maintain a journal, the filesystem repair utility mustexamine the entire filesystem, searching for any internal structuring information which is in aninconsistent state. For even a moderately large filesystem (40 gigabytes, for example), this process cantake several minutes.

In contrast, when repairing an ext3 filesystem, the repair utility needs only to focus on the journal ofpending transactions. The repair utility can then reset theinternal filesystem structures associated withthese transactions to a consistent state, and assume the rest of the filesystem is healthy. The presence of ajournal to guide the repair utility dramatically reduces the amount of time needed to begin reusing acrashed filesystem.

Creating ext3 Filesystems

How is an ext3 filesystem created? Notice in the above table ofcommonly used command line switchesfor themke2fscommand, the-j command line switch was included without discussion. The switchspecifies that themke2fsutility should include a journal with the newly created ext2filesystem. In otherwords, make an ext3 filesystem.

As a convenience, themkfs.ext3command is also provided. The command is a synonym formke2fs -j(or mkfs.ext2 -j, or mkfs -t ext2 -j). It shares all command line switches in common withmke2fs.

Examples

Creating an ext2 FilesystemContinuing to configure his new disk, the user prince next proceeds to create his first filesystem, whichhe wanted to be the ext2 filesystem. He makes the following decisions about the specifications.

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

34

Page 35: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 2. Creating and Managing Filesystems

• He knows that he is going to be using the filesystem for storingimages, so he decides to give thefilesystem the labelpics.

• As he is the only user that will routinely be using the partition, he decides not to waste space reservingblocks for the root user, and sets the reserved block percentage to 0.

• Because he expecting to store relatively few large files, he decides to force the blocksize to 4096 bytes.

• To be safe, he has themke2fscommand check for bad blocks before creating the filesystem.

Composing the appropriate command line switches, he runs the themke2fs command on the partition.

[root@station root]# mke2fs -L pics -m 0 -b 4096 -c /dev/hdb2

mke2fs 1.39 (29-May-2006)Filesystem label=picsOS type: LinuxBlock size=4096 (log=2)Fragment size=4096 (log=2)126720 inodes, 126622 blocks0 blocks (0.00%) reserved for the super userFirst data block=04 block groups32768 blocks per group, 32768 fragments per group31680 inodes per groupSuperblock backups stored on blocks:

32768, 98304

Checking for bad blocks (read-only test): doneWriting inode tables: doneWriting superblocks and filesystem accounting information: done

This filesystem will be automatically checked every 20 mounts or180 days, whichever comes first. Use tune2fs -c or -i to override.

In order to confirm that the filesystem was created "to spec", he turn right around and runs thedumpe2fscommand, whose output is excerpted below.

[root@station root]# dumpe2fs /dev/hdb2

dumpe2fs 1.39 (29-May-2006)Filesystem volume name: picsLast mounted on: <not available>Filesystem UUID: dbc2276d-3393-4f75-9e1b-e6d114e87e53Filesystem magic number: 0xEF53Filesystem revision #: 1 (dynamic)Filesystem features: filetype sparse_super...Inode count: 126720Block count: 126622Reserved block count: 0...Block size: 4096...

All appears to be well.

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

35

Page 36: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 2. Creating and Managing Filesystems

Creating a vfat FilesystemThe user prince’s machine is a dual boot machine, with Red HatEnterprise Linux and Windows XP. HisWindows partition is using the NTFS filesystem, which is not supported by Red Hat Enterprise Linux.Because he would like to easily share files between the two operating systems, prince wants to make aFAT partition that can be seen from both worlds.

Although he knows that themkfs.vfat command has several options which can be used to specify FATfilesystem details, he assumes that the default settings areappropriate, and quickly creates the partition.

[root@station root]# mkfs.vfat /dev/hdb3

mkfs.vfat 2.11 (12 Mar 2005)

Seeing no information returned from the command, an knowingno analogue to thedumpe2fscommandfor the vfat filesystem, prince assumes all went well and moves along.

Creating an ext3 FilesystemLastly, prince is going to create an ext3 filesystem to hold all of his music which he has ripped fromCD’s, into theogg vorbisformat. He decides to label the filesystemogg, appropriately. He knows hecould use themkfs.ext3command, but because his fingers are in the habit of typingmke2fs, that justseems to fall out of his fingers. He adds the-j command line switch, so that the resulting filesystem isext3.

[root@station root]# mke2fs -j -c -L ogg /dev/hdb5

mke2fs 1.39 (29-May-2006)Filesystem label=oggOS type: LinuxBlock size=4096 (log=2)Fragment size=4096 (log=2)125696 inodes, 251362 blocks12568 blocks (5.00%) reserved for the super userFirst data block=08 block groups32768 blocks per group, 32768 fragments per group15712 inodes per groupSuperblock backups stored on blocks:

32768, 98304, 163840, 229376

Checking for bad blocks (read-only test): doneWriting inode tables: doneCreating journal (4096 blocks): doneWriting superblocks and filesystem accounting information: done

This filesystem will be automatically checked every 27 mounts or180 days, whichever comes first. Use tune2fs -c or -i to override.

Again, he confirms the results with thedumpe2fs command.

[root@station root]# dumpe2fs /dev/hdb5

dumpe2fs 1.39 (29-May-2006)Filesystem volume name: ogg

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use isa violation of U.S. and international copyrights. No part ofthis publication may be photocopied, duplicated, stored ina retrieval system, or otherwise duplicated whetherin electronic or print format without prior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, or otherwise improperly distributedplease email [email protected] or phone toll-free (USA)+1 866 626 2994 or +1 (919) 754 3700.

36

Page 37: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 2. Creating and Managing Filesystems

Last mounted on: <not available>Filesystem UUID: 7c82a031-a594-4579-a63f-fb28972bcfc8Filesystem magic number: 0xEF53Filesystem revision #: 1 (dynamic)Filesystem features: has_journal filetype sparse_super...Inode count: 125696Block count: 251362Reserved block count: 12568...Block size: 4096...Journal UUID: <none>Journal inode: 8Journal device: 0x0000...

Seeing some signs that the journal was created, prince is satisfied that the filesystem is an ext3 filesystem.

Online Exercises

Lab ExerciseObjective: Create a new ext2 partition.

Estimated Time: 10 mins.

SpecificationThis lab exercise will continue to use the partition createdin the previous lab exercise. Ensure that thefile ~/lab3.1/disk still exists, and that it still references the correct drive.

Create an ext2 filesystem on the last partition created in theprevious exercise. The filesystem shouldmeet the following criteria.

1. The filesystem should have the labellab3.2.

2. The filesystem should have a blocksize of 2048 bytes.

3. The filesystem should have exactly 24,000 inodes (or as near to 24,000 as possible).

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

37

Page 38: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 2. Creating and Managing Filesystems

Deliverables

1. The last partition on the drive specified in the file~/lab3.1/disk should be formatted with an ext2 filesystem,whose label islab3.2, has a blocksize of 2048 bytes, and has (very close to) 24,000inodes.

Questions

1. Which of the following filesystems is usually associated with compact disks?

( ) a. ext3

( ) b. iso9660

( ) c. reiserfs

( ) d. vfat

( ) e.None of the above

2. Which of the following commands could be used to create an ext3 filesystem?

( ) a. mkfs.ext3

( ) b. mkfs -t ext3

( ) c. mke2fs -j

( ) d. mkfs.ext2 -j

( ) e.All of the above

3. Which of the following command lines could be used to create an ext2 filesystem with a blocksize of 2048 bytes?

( ) a.mke2fs -b 2048 /dev/hda4

( ) b. mke2fs /dev/hda4

( ) c.mke2fs -b2k /dev/hda4

( ) d. mke2fs -b2 /dev/hda4

( ) e.A and B

Use the following transcript to answer the next 2 questions.

[root@station root]# dumpe2fs /dev/hdb5

dumpe2fs 1.39 (29-May-2006)Filesystem volume name: /home

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use is a violation of U.S.and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwise duplicated whether in electronic or print format withoutprior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, or otherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919) 754 3700.

38

Page 39: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 2. Creating and Managing Filesystems

Last mounted on: <not available>Filesystem UUID: 4a26ac4a-fcd9-4231-bf3a-e5e5fb2456b5Filesystem magic number: 0xEF53Filesystem revision #: 1 (dynamic)Filesystem features: has_journal filetype needs_recovery sparse_superDefault mount options: (none)Filesystem state: cleanErrors behavior: ContinueFilesystem OS type: LinuxInode count: 3842720Block count: 7681070Reserved block count: 384053Free blocks: 1150544Free inodes: 3597708First block: 0Block size: 4096Fragment size: 4096Blocks per group: 32768Fragments per group: 32768Inodes per group: 16352Inode blocks per group: 511Last mount time: Sun Oct 5 13:59:31 2003Last write time: Sun Oct 5 13:59:31 2003Mount count: 74Maximum mount count: -1Last checked: Fri Sep 19 09:16:20 2003Check interval: 15552000 (6 months)Next check after: Wed Mar 17 08:16:20 2004Reserved blocks uid: 0 (user root)Reserved blocks gid: 0 (group root)First inode: 11Inode size: 128Journal UUID: <none>Journal inode: 8Journal device: 0x0000First orphan inode: 0

4. Which of the following command lines could have created thisfilesystem? (Assume that the filesystem has notbeen modified withtune2fssince it was created.)

( ) a.mke2fs -L /home -b 2048 /dev/hdb5

( ) b. mkfs.ext3 -b 2048 /dev/hdb5

( ) c.mkfs -t ext2 -b 4096 /dev/hdb5

( ) d. mke2fs -j -L /home -b 4096 -N 3842720 /dev/hdb5

( ) e.None of the above

rha130-5.0-0-en-2007-12-13T13:35:30-0500Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use is a violationof U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrievalsystem, or otherwise duplicated whether in electronic or printformat without prior written consent of Red Hat, Inc. If you b elieve Red Hat course materials are being used, copied, or otherwise improperly distributed please [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919) 754 3700.

39

Page 40: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 2. Creating and Managing Filesystems

5. When creating this filesystem, which of the following would be the appropriate argument to the-i command lineswitch to themke2fscommand to generate the appropriate number of inodes?

( ) a. -i 2

( ) b. -i 4096

( ) c. -i 8192

( ) d. -i 4

( ) e.None of the above

6. When formatting a floppy with themke2fscommand, why might one be tempted to include the-m 0 commandline switch?

( ) a. Because journaling would be too slow on a floppy, this commandline switch would disable journaling.

( ) b. The command line switch would prevent any blocks being reserved for only the root user.

( ) c. The command line switch would set the number of inodes to 0, which is appropriate for temporary mediasuch as floppies.

( ) d. The command line switch would cause the floppy to be overwritten with binary 0’s before the filesystem isconstructed, wiping clean any previous data.

( ) e.None of the above

7. Which of the following command lines would create a filesystem with a volume label ofdata?

( ) a. mkfse2 -l data /dev/hda1

( ) b. mkfs.ext2 --label=data /dev/hda1

( ) c. mkfs.ext2 -m data /dev/hda1

( ) d. mkfs -t ext2 -L data /dev/hda1

( ) e.None of the above

8. Which of the following command lines would create an ext3 filesystem with a block size of 4096?

( ) a. mke2fs --journal --block=4096 /dev/hda1

( ) b. mkfs.ext3 -b 4k /dev/hda1

( ) c. mkfs -t ext2 -j -b4 /dev/hda1

( ) d. mkfs -t ext3 --block=4k /dev/hda1

( ) e.None of the above

rha130-5.0-0-en-2007-12-13T13:35:30-0500Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use is a violationof U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrievalsystem, or otherwise duplicated whether in electronic or printformat without prior written consent of Red Hat, Inc. If you b elieve Red Hat course materials are being used, copied, or otherwise improperly distributed please [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919) 754 3700.

40

Page 41: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 2. Creating and Managing Filesystems

9. Which of the following command line switches causes themke2fscommand to check the disk for bad blocksbefore creating a filesystem?

( ) a. -L

( ) b. -c

( ) c. -b

( ) d. -s

( ) e.None of the above

10.Your friend has just run thedumpe2fscommand on his/home filesystem, and noticed that the flagneeds_recoverywas set. What advice would you give him?

( ) a. He should reboot his machine immediately.

( ) b. When convenient, he should unmount the partition, and perform filesystem maintenance.

( ) c. He should not be concerned, as the flag is always set on mountedfilesystems.

( ) d. He should not be concerned, as the Linux kernel automatically runs a filesystem recovery algorithm every10 minutes.

( ) e.You do not believe him, and suspect he ran thedumpe2fscommand on a partition that does not contain anext2 filesystem.

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

41

Page 42: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 3. Mounting Filesystems

Key Concepts

• Themount command is used to attach the root directories of filesystemsto already existing directoriesin the directory tree.

• The pre-existing directory is referred to as themount pointof the mount.

• Theumount command is used to detach filesystems (which are not busy) from the directory tree.

• Various mount options can be used to qualify the capabilities of mounted filesystems.

• Theremount mount option can be used to associate new options with already existing mounts.

Discussion

Mounting FilesystemsIn Linux (and Unix), filesystems are gracefully combined into a single directory tree through a conceptcalledmounting. Every filesystem provides aroot directorywhich servers as the base of the filesystem.When a filesystem is mounted, its root directory is bound to analready existing directory in the system’sdirectory tree, referred to as themount pointfor the filesystem. Whenever the mount point is referenced,the root directory of the mounted filesystem is presented instead.

As we elaborate on the concept of mounting, we will continue to use the IDE drive introduced in ourpartitioning discussion.

42

Page 43: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 3. Mounting Filesystems

Figure 3-1. Partitioning for the Drive /dev/hda

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

43

Page 44: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 3. Mounting Filesystems

The root partition

Because the mount point must be an already existing directory, the first mount is special, and performedby the kernel directly at startup. This first filesystem is referred to as theroot partition, and the rootpartition’s root directory becomes the root directory of the directory tree, "/". In the above example, thepartition/dev/hda5 is being used as the root partition.

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

44

Page 45: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 3. Mounting Filesystems

Figure 3-2. The/dev/hda5 Root Partition

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

45

Page 46: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 3. Mounting Filesystems

This filesystem contains a root directory and commonly recognized subdirectories such as/etc, /home,and/boot. If desired, the root partition could serve as a machine’s only filesystem. The directoriesabove would contain subdirectories, and those subdirectories would in turn contain subdirectories, sothat every file on the system is stored in this single filesystem. For simple workstations, this may well bethe appropriate design.

"Partitioning Off" Parts of the Directory Tree

In practice, Linux (and Unix) administrators often choose to compose their system’s directory tree out ofmultiple partitions. In the above example, the partition/dev/hda6 is referred to as the/home partition,because the filesystem in intended to be mounted to the/home directory in the directory tree. In thefollowing diagram, we examine the contents of this filesystem.

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

46

Page 47: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 3. Mounting Filesystems

Figure 3-3. The/dev/hda6 Filesystem

The filesystem has its own root directory, and subdirectories such as/blondie, /elvis, etc. Whenmounted to the/home directory, the mount point/home becomes bound to the root directory of the/dev/hda6 filesystem.

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

47

Page 48: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 3. Mounting Filesystems

Figure 3-4. The/dev/hda6 Filesystem Mounted to/home

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

48

Page 49: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 3. Mounting Filesystems

Once mounted, all subsequent references to the/home directory no longer see the contents of the/home

directory on the partition/dev/hda5, but instead theroot directory of the partition/dev/hda6. To theend user, the effect is seamless. When the user asks for als of /home he sees the directorieselvis,madonna, etc.

The process can be continued as often as desired. The following diagram reflects the fully assembleddirectory tree for the IDE drive above, with the/dev/hda6 filesystem mounted to/home, the/dev/hda7 filesystem mounted to/var, and the/dev/hda8 filesystem mounted to/var/ftp/pub.All filenames are listed relative to the root directory of thefilesystem which contains them.

Figure 3-5. The Fully Assembled Directory Tree

Often, the end user, who might ask for an md5sum of the file/var/ftp/pub/images/bootdisk.img,does not realize that her absolute reference traverses three different partitions.

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy.Any other use is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, orotherwise duplicated whether in electronic or print format without prior written consent of Red Hat, Inc. If you believe Red Hat course materials are beingused, copied, or otherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919) 754 3700.

49

Page 50: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 3. Mounting Filesystems

Note: In the diagram of the IDE drive, and in our discussion, the partition /dev/hda6 has beenreferred to as the "/home" partition. The fact that the directory /home does not exist in the /dev/hda6

filesystem should be emphasized. The filesystem is only referred to as the /home partition because itis intended to be mounted on the /home directory. It could just as easily be mounted to the /etc

directory, resulting in a directory tree which contains the directories /etc/blondie, /etc/elvis, etc.(This is possible, not desirable.)

Mounting Filesystems with the mount CommandFilesystems are mounted with themount command. Generally, only root can mount filesystems. Thefollowing example of themount command illustrates the general syntax.

[root@station root]# mount -t ext2 -o noatime,noexec /dev/sda1 /home

Each execution of themount command must somehow resolve the following four questions.

1. What device is being mounted? The first argument specifies the name of a block device to bemounted.

2. What filesystem is the device formatted with? The filesystem can be specified with the-t commandline switch.

3. Where should the device be mounted? The second argument specifies the already existing directorywhich should serve as the mount point for the filesystem.

4. Are there any options which should be associated with the mounted filesystem? Mount options aregenerally specified with the-o command line switch. In the above example, the mounted filesystemwill not record file access times, and will not interpret any files as commands to be executed.

Listing All Mounted Devices

Themount command, when called without arguments, will list all mounted filesystems along with theanswers to the four questions above.

[root@station root]# mount

/dev/hda3 on / type ext3 (rw)proc on /proc type proc (rw)sysfs on /sys type sysfs (rw)devpts on /dev/pts type devpts (rw,gid=5,mode=620)/dev/hda1 on /boot type ext3 (rw)tmpfs on /dev/shm type tmpfs (rw)none on /proc/sys/fs/binfmt_misc type binfmt_misc (rw)sunrpc on /var/lib/nfs/rpc_pipefs type rpc_pipefs (rw)/dev/sda1 on /home type ext2 (rw,noexec,noatime)

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

50

Page 51: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 3. Mounting Filesystems

Shortcutting the Filesystem Type

If the filesystem type is not specified explicitly, themount command will consult the file/etc/filesystems for a list of candidate filesystems.

[root@station root]# cat /etc/filesystems

ext3ext2nodev procnodev devptsiso9660vfathfs

When mounting one of these filesystem types, the filesystem does not need to be specified manually.

Mount Options

The Linux kernel supports the following mount options, which by design are generic to any filesystem. Inpractice, some filesystems silently ignore some of the options. Most mount options are implemented ascomplementary choices, such asexecandnoexec. Such binary options are coupled in the following table.

Table 3-1. Linux Mount Options

Option Effect

ro, rw Thero option specifies that the filesystem should be mounted read only. Internalfilesystem parameters (such as the mount count, or last mounttime) are notmodified as well. The default isrw .

(a)sync Thesyncoption specifies that all transactions should occur synchronously, i.e.,writes should bypass the kernel cache. While this option provides better integrity(transactions are written to disk immediately), it can significantly degrade overallsystem performance. The default isasync. This option is currently only supportedby the ext2/ext3 and ufs filesystems.

(no)atime Thenoatimeoption specifies that file access times should not be maintained.When access times are recorded, every read effectively becomes a write (becausethe inode’s atime requires updating). If access times are not considered important,system performance can be improved by ignoring them. Also useful on laptops,this option can prevent the drive from "spinning up" unnecessarily. The default isatime.

(no)dev Thenodevoption specifies that no files within the filesystem should beinterpreted as device nodes. The default isdev.

(no)exec Thenoexecoption specifies that no files within the filesystem should beinterpreted as executable commands. The default isexec.

(no)suid Thenosuid option specifies that the suid permission bit should not be honored onany files within the filesystem. The suid bit allows scripts toelevate privilegesupon execution, and is commonly used to implement trap doorson compromisedsystems. The default issuid.

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

51

Page 52: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 3. Mounting Filesystems

In addition, most filesystems support mount options specificto that filesystem. Consult themount(8)man page for details.

In practice, the default options are generally appropriate, and themount command is often called withonly two arguments, as in the following.

[root@station root]# mount /dev/sda1 /home

Unmounting Filesystems with the umount CommandFilesystems are unmounted with theumount command. Theumount command expects to be calledwith a single argument, which may be either the device name orthe mount point associated with themount. Either of the following two commands would attempt tounmount the/dev/sda1 partition fromthe/home directory.

[root@station root]# umount /home

[root@station root]# umount /dev/sda1

While simple in concept, one complication often serves to frustrate attempts to unmount devices:

[root@station home]# umount /home

umount: /home: device is busy

Theumount command will only unmount filesystems which are not "busy". Afilesystem is consideredbusy if any process has an open file in the filesystem, or any process has a directory within the filesystemas its current working directory. Before the filesystem can be unmounted, the process which is busying itmust be tracked down and killed (or convinced to release the files and/or directories to which it is layingclaim).

Using fuser or lsof to Track Down Processes

Fortunately, a command is designed with just this purpose inmind. Thefuser command lists the processids of processes which are somehow using a file. More relevantfor our purposes, if thefuser commandis called with the the-m command line switch, it will list all processes which are using files anywhere onthe filesystem which contains the specified file.

[root@station home]# fuser -m /home

/home: 1912c

In this case, process id 1912 has a current working directorywithin the specified filesystem. Observationof thebashprompt implies that the id probably belongs to the shell itself. Changing directories "out of"the /home partition, the device can be unmounted.

[root@station home]# cd

[root@station root]# umount /home/

The lsof command (for "list open files") provides an alternative tofuser. When invoked on a directoryserving as amount point,lsof lists every currently open file within the filesystem.

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use isa violation of U.S. and international copyrights. No part ofthis publication may be photocopied, duplicated, stored ina retrieval system, or otherwise duplicated whetherin electronic or print format without prior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, or otherwise improperly distributedplease email [email protected] or phone toll-free (USA)+1 866 626 2994 or +1 (919) 754 3700.

52

Page 53: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 3. Mounting Filesystems

[root@station6 foo]# lsof /home

COMMAND PID USER FD TYPE DEVICE SIZE NODE NAMEbash 1912 root cwd DIR 3,5 1024 12049 /homelsof 15612 root cwd DIR 3,5 1024 12049 /homelsof 15613 root cwd DIR 3,5 1024 12049 /home

The lsof command is very versatile and is a good tool to have at your disposal, but at this point wemerely mention this one use.

Remounting Partitions with mount -o remountThemount command can also be used to associate new mount options with already mounted partitions.When remounting partitions, themount command should be called with theremount option, combinedwith whatever new options are to be associated with the filesystem. Consider the following example.

[root@station root]# date > /home/foo

[root@station root]# mount -o remount,ro /home

[root@station root]# date > /home/foo

-bash: /home/foo: Read-only file system[root@station root]# mount -o remount,rw /home

[root@station root]# date > /home/foo

Examples

Creating Mount PointsContinuing his work from the previous example, prince decides to create the following mount points forhis 3 filesystems.

Partition Size Filesystem Mountpoint

/dev/hdb2 512 megabytes ext2 /picts

/dev/hdb3 512 megabytes vfat /dosd

/dev/hdb5 1024 megabytes ext3 /ogg

His first step is to create the needed directories.

[root@station root]# mkdir /picts /dosd /ogg

Next, he mount his new partitions, one by one. Because he is using standard filesystem types, he does notneed to specify filesystem types to themount command.

[root@station root]# mount /dev/hda6 /picts/

[root@station root]# mount /dev/hda7 /dosd

[root@station root]# mount /dev/hda8 /ogg

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use isa violation of U.S. and international copyrights. No part ofthis publication may be photocopied, duplicated, stored ina retrieval system, or otherwise duplicated whetherin electronic or print format without prior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, or otherwise improperly distributedplease email [email protected] or phone toll-free (USA)+1 866 626 2994 or +1 (919) 754 3700.

53

Page 54: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 3. Mounting Filesystems

[root@station root]# mount

/dev/hda6 on / type ext3 (rw)none on /proc type proc (rw)usbdevfs on /proc/bus/usb type usbdevfs (rw)/dev/hda7 on /var/ftp/pub type ext3 (rw)/dev/hda5 on /home type ext3 (rw)none on /dev/pts type devpts (rw,gid=5,mode=620)none on /dev/shm type tmpfs (rw)/dev/hdb2 on /picts type ext2 (rw)/dev/hdb3 on /dosd type vfat (rw)/dev/hdb5 on /ogg type ext3 (rw)

After performing the mount, price decides he would like to protect the vfat filesystem until he canconfirm that it looks good after rebooting into Windows XP. Hedecides to add thero mount option.

[root@station root]# mount -o remount,ro /dosd

[root@station root]# mount

.../dev/hdb2 on /picts type ext2 (rw)/dev/hdb3 on /dosd type vfat (ro)/dev/hdb5 on /ogg type ext3 (rw)

Online Exercises

Lab ExerciseObjective: Mount an ext2 filesystem to the specified directory, with appropriatemount options.

Estimated Time: 10 mins.

SpecificationThis lab exercise will continue to use the filesystem createdin the previous lab exercise. Ensure that thefile ~/lab3.1/disk still exists, and that it still references the correct drive. The last partition of thedrive should have a properly formatted ext2 filesystem.

1. Create the directory/lab3, which will serve as a mount point for your partition.

2. Mount the last partition on the specified drive to the/lab3 directory, with thenoexecandnoatimemount options.

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use is a violationof U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrievalsystem, or otherwise duplicated whether in electronic orprint format without prior written consent of Red Hat, Inc. I f you believe Red Hat course materials are being used, copied, or otherwise improperly distributed please [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919) 754 3700.

54

Page 55: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 3. Mounting Filesystems

Deliverables

1. The last partition on the drive specified in the file~/lab3.1/disk should be mounted to the directory/lab3,with thenoexecandnoatimeoptions.

Questions

1. Which of the following could be a legitimate invocation of themount command?

( ) a.mount -t /dev/hda2 /home

( ) b. mount /home /dev/hda2

( ) c.mount /dev/hda2 /home

( ) d. mount -o /home /dev/hda2

( ) e.None of the above

2. Which of the following command lines would mount the device/dev/hda3, formatted with the vfat filesystem,to the mount point/dosc?

( ) a.mount -o vfat -d /dev/hda3 /dosc

( ) b. mount -t vfat /dev/hda3 /dosc

( ) c.mount -t vfat -o /dosc /dev/hda3

( ) d. mount -o vfat /dosc /dev/hda3

( ) e.None of the above

3. Which of the following is not a common Linux mount option?

( ) a. mtime

( ) b. noatime

( ) c. noexec

( ) d. ro

( ) e.All are common mount options

Use the following transcript to answer the next 3 questions.

[root@station root]# mount

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use is a violation of U.S.and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwise duplicated whether in electronic or print format withoutprior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, or otherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919) 754 3700.

55

Page 56: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 3. Mounting Filesystems

/dev/hda3 on / type ext3 (rw)proc on /proc type proc (rw)sysfs on /sys type sysfs (rw)devpts on /dev/pts type devpts (rw,gid=5,mode=620)/dev/hda1 on /boot type ext3 (rw)tmpfs on /dev/shm type tmpfs (rw)none on /proc/sys/fs/binfmt_misc type binfmt_misc (rw)sunrpc on /var/lib/nfs/rpc_pipefs type rpc_pipefs (rw)[root@station root]# mount /dev/hda7 /var

[root@station root]# mount /dev/hda5 /var/www/html

4. Which partition contains the file/proc/meminfo?

( ) a./dev/hda1

( ) b. /dev/hda7

( ) c./dev/hda5

( ) d. /dev/hda3

( ) e.None of the above

5. Which partition contains the mount point/var/www/html?

( ) a./dev/hda3

( ) b. /dev/hda7

( ) c./dev/hda1

( ) d. /dev/hda5

( ) e.None of the above

6. When accessing the file/var/www/html/index.html, how many partitions does the kernel involve?

( ) a. 1

( ) b. 3

( ) c. 0

( ) d. 2

( ) e.Not enough information is provided

Use the following transcript to answer the next 2 questions.

[root@station root]# mount /dev/fd0 /mnt/floppy

[root@station root]# cd /mnt/floppy

[root@station floppy]# cal > september.txt

[root@station floppy]# umount /mnt/floppy

umount: /mnt/floppy: device is busy

rha130-5.0-0-en-2007-12-13T13:35:30-0500Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use is a violationof U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrievalsystem, or otherwise duplicated whether in electronic or printformat without prior written consent of Red Hat, Inc. If you b elieve Red Hat course materials are being used, copied, or otherwise improperly distributed please [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919) 754 3700.

56

Page 57: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 3. Mounting Filesystems

7. Which is the most likely reason the/mnt/floppy device was considered busy?

( ) a. The kernel had not yet finished writing the fileseptember.txt.

( ) b. Although the kernel had finished writing the fileseptember.txt, the writes had not yet been committedto disk.

( ) c. The filesystem on the/mnt/floppy device has become corrupted.

( ) d. Thebashshell’s current working directory is/mnt/floppy.

( ) e.None of the above

8. Which of the following commands would resolve the problem, so that if it were immediately followed by thesameumount command listed above, the unmount would succeed?

( ) a.fuser -m /mnt/floppy

( ) b. fsck -m /mnt/floppy

( ) c.sync

( ) d. cd

( ) e.None of the above

9. Which of the following command lines would add thenoatimeoption to an already mounted/home partition?

( ) a.mount -o noatime /dev/hda4 /home

( ) b. mount -a noatime /dev/hda4 /home

( ) c.mount -remount -o noatime /dev/hda4 /home

( ) d. mount -o remount,noatime /dev/hda4 /home

( ) e.None of the above

Use the following transcript to answer the next question.

[root@station root]# mount

/dev/hdb6 on / type ext3 (rw)none on /proc type proc (rw)usbdevfs on /proc/bus/usb type usbdevfs (rw)/dev/hdb7 on /var/ftp/pub type ext3 (rw)/dev/hdb5 on /home type ext3 (rw)none on /dev/pts type devpts (rw,gid=5,mode=620)none on /dev/shm type tmpfs (rw)

rha130-5.0-0-en-2007-12-13T13:35:30-0500Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use is a violationof U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrievalsystem, or otherwise duplicated whether in electronic or printformat without prior written consent of Red Hat, Inc. If you b elieve Red Hat course materials are being used, copied, or otherwise improperly distributed please [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919) 754 3700.

57

Page 58: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 3. Mounting Filesystems

10.Which of the following command lines could be used to unmountthe /home partition?

( ) a.unmount /home

( ) b. umount -t ext3

( ) c.umount /dev/hdb5

( ) d. unmount -a

( ) e.None of the above

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

58

Page 59: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 4. The /etc/fstab File

Key Concepts

• The/etc/fstab file can be used to predefine mount points.

• When themount command is called with only half of the information it needs,it consults the/etc/fstab for the rest.

• Themount -a command attempts to mount (almost) every predefined mount point listed in the/etc/fstab file.

• In the/etc/fstab file, devices may either be referenced by name, or by filesystem label.

DiscussionIn the previous Lesson, themount command was introduced requiring two arguments: the devicetomount, and the mount point to which to mount it. Often, however, shortcuts are taken with themountcommand, as in the following 3 examples.

[root@station root]# mount /mnt/floppy

[root@station root]# mount /dev/fd0

[root@station root]# mount -a

Whenever themount command is called without enough information, it looks to a "filesystem table" toprovide more: the/etc/fstab file.

The /etc/fstab File SyntaxThe following/etc/fstab file might be found on the machine using the IDE drive from our previouslesson.

[root@station root]# cat /etc/fstab

/dev/hda5 / ext3 defaults 1 1/dev/hda6 /home ext3 defaults 1 2/dev/hda7 /var ext3 defaults 1 2/dev/hda8 /var/ftp/pub ext3 defaults 1 2/dev/hda3 /boot ext3 defaults 1 2devpts /dev/pts devpts gid=5,mode=620 0 0proc /proc proc defaults 0 0sysfs /sys sysfs defaults 0 0tmpfs /dev/shm tmpfs defaults 0 0/dev/hda2 swap swap defaults 0 0

Each column of the file is separated by some combination of white space (generally, spaces and/or tabs).Each row defines a mount, with the first four column directly answering the four questions associated

59

Page 60: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 4. The/etc/fstab File

with each mount posed in the previous lesson: what, where, with which filesystem, and how. The lattertwo columns are more subtle, and are described in the table below.

Table 4-1. Format of the/etc/fstab File

Column Example Role

1 /dev/hda6 Which device (disk, partition, or otherwise) to mount.

2 /home The mount point associated with the mount.

3 ext3 The filesystem to expect to find on the device, or the keyword "auto",which means the filesystem should be automatically detected.

4 defaults A comma separated list of options to associate with the mount, aswould be specified with the-o command line switch to themountcommand.

5 0 Used by thedump command to determine if this partition should bearchived when performing backups. Thedump utility is seldom used.

6 2 The "fsck"ing order. On system startup, thefsck "file system check"command is run on each identified filesystem. There are three relevantvalues for this field: 1 (reserved for the root partition), 2 (for allpartitions to be checked except for the root partition), and0 (forpartitions which should not befscked on startup).

Whenever themount command is called with just a mount point, or just a device, asits lone argument, itlooks for a matching line within the/etc/fstab file to supply the remaining information. Examples ofsuccessful commands have been given above. Notice the reference to the/etc/fstab file when thefollowing unsuccessfulmount command complains.

[root@station root]# mount /foo

mount: can’t find /foo in /etc/fstab or /etc/mtab

Themount -a command specifies to mount "all". The command reads the/etc/fstab line by line, andperforms all appropriate mounts. Themount -a command is executed as part of the system startup.

Mount Options Relevant to the /etc/fstab FileThe following options, while documented in themount(8) man page, only make sense when used in the/etc/fstab file.

Table 4-2. Mount Options Relevant to the/etc/fstab File

Option Effect

defaults Use default options: rw, suid, dev, exec, auto, nouser, and async. (The worddefaultshas the same effect as specifying no options, but something must hold theplace of the fourth column in the/etc/fstab file.)

rha130-5.0-0-en-2007-12-13T13:35:30-0500Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use is a violation

of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrievalsystem, or otherwise duplicated whether in electronic or print

format without prior written consent of Red Hat, Inc. If you b elieve Red Hat course materials are being used, copied, or otherwise improperly distributed please email

[email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919) 754 3700.

60

Page 61: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 4. The/etc/fstab File

Option Effect

(no)auto Thenoautooption specifies that the partition shouldnot be mounted whenexecutingmount -a. This option is generally used on lines defining mount pointsfor temporary media, such as floppies, CD-ROM’s, and USB drives.

user By default, only root may perform mounts. Theuseroption specifies that anyoneshould be able to perform the predefined mount.

Specifying Devices by Filesystem LabelThe above example of an/etc/fstab file could be found in most any version of Unix, and would alsowork in Linux. The default/etc/fstab file in Red Hat Enterprise Linux, however, takes advantage ofan additional feature of the Linuxmount command. In Red Hat Enterprise Linux, the same file wouldprobably look more like the following, where the only differences occur in the first column.

[root@station root]# cat /etc/fstab

LABEL=/ / ext3 defaults 1 1LABEL=/home /home ext3 defaults 1 2LABEL=/var /var ext3 defaults 1 2LABEL=pub /var/ftp/pub ext3 defaults 1 2LABEL=/boot /boot ext3 defaults 1 2devpts /dev/pts devpts gid=5,mode=620 0 0procfs /proc proc defaults 0 0sysfs /sys sysfs defaults 0 0tmpfs /dev/shm tmpfs defaults 0 0LABEL=SWAP-hda2 swap swap defaults 0 0

When discussing themke2fs command, we mentioned that Red Hat Enterprise Linux makes functionaluse of a filesystem labels. This is it. Rather than specifyinga device directly, the device can be specifiedby filesystem label. Think of the second line as saying, "Examine all known filesystems, and mount theone labeled "/home" to the/home directory.

By convention, Anaconda (the Red Hat Enterprise Linux Installer) labels filesystems by their intendedmount point. This way, the filesystem internally "knows" where it is intended to be mounted. As thefourth line above implies, however, this is merely convention. Any label will suffice.

Why does Red Hat Enterprise Linux add this extra level of indirection, with its associated complexity?Because device names can be fickle. There are two situations that can lead to devices shifting identities.

1. Deleting Logical Partitions: Recall that logical partitions are maintained as a linked list, and iflogical partition/dev/hda6 were to be deleted, logical partitions/dev/hda7 and/dev/hda8would shift to/dev/hda6 and/dev/hda7.

2. Adding (or Removing) SCSI Drives:When a SCSI drive is added or removed from the system,SCSI drives can shift identities. What was/dev/sdb on a previous boot might become/dev/sdc.

In the latter case, a move as innocently intentioned as adding a SCSI disk to the system could throw atraditional/etc/fstab file out of whack, potentially leaving the system unbootable. Identifyingfilesystems by filesystem label rather than device names protects against such unfortunate events.

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

61

Page 62: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 4. The/etc/fstab File

Using Filesystem Labels on the Mount Command LineJust as filesystem labels can be used in the/etc/fstab file to specify a device, they can be used on themount command line directly, with the-L command line switch, as in the following example.

[root@station root]# dumpe2fs /dev/hda1 | head -1

dumpe2fs 1.39 (29-May-2006)Filesystem volume name: /boot[root@station root]# mount -L /boot /boot

Similarly, devices can be identified on themount command line (and the/etc/fstab file) by their"UUID" (Universal Unique Identifier). Refer to themount(8) andfstab(5)man pages for moreinformation.

Adding Lines to the /etc/fstab FileWhen creating a new filesystem, there are several reasons whya line defining a mount point for thefilesystem might be added to the/etc/fstab file.

• A /etc/fstab line defines a "place" for the filesystem. While the filesystemcould be mounted at anytime to any directory, defining a default mount point has the effect of giving the files a home in thedirectory tree.

• The mount becomes part of system bootup process. Unless thenoautooption is added, the mount willoccur automatically as the system boots.

• Users other than root can perform the mount. By default, onlyroot may perform a mount. If theuseror owner option is specified in the/etc/fstab file, however, this privilege may be bestowed to otherusers.

In principle, adding a line to the/etc/fstab file is easy, and may be performed with any text editor.Care must be taken, however, not to mangle the syntax of the file. Because of themount -a command,the/etc/fstab file plays a fundamental role in the system’s bootup process.A mangled ormis-specified/etc/fstab file can leave the system unbootable. When editing the/etc/fstab file,text editors (or word processors) that implement "word wrapping" should be avoided like the plague.

Examples

Defining Mount Points in the /etc/fstab FileBecause prince does not want to perform the three mounts for his three new filesystems manually everytime he reboots the machine, he decides to define the mounts inhis/etc/fstab file. He first examinehis current file, looking for lines similar to what he desires.

[root@station root]# cat /etc/fstab

LABEL=/ / ext3 defaults 1 1LABEL=/var/ftp/pub /var/ftp/pub ext3 defaults 1 2

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use isa violation of U.S. and international copyrights. No part ofthis publication may be photocopied, duplicated, stored ina retrieval system, or otherwise duplicated whetherin electronic or print format without prior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, or otherwise improperly distributedplease email [email protected] or phone toll-free (USA)+1 866 626 2994 or +1 (919) 754 3700.

62

Page 63: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 4. The/etc/fstab File

LABEL=/home /home ext3 defaults 1 2LABEL=/boot /boot ext3 defaults 1 2devpts /dev/pts devpts gid=5,mode=620 0 0proc /proc proc defaults 0 0sysfs /sys sysfs defaults 0 0tmpfs /dev/shm tmpfs defaults 0 0LABEL=SWAP-hda2 swap swap defaults 0 0

He decides that the line specifying the/boot partition looks as good as any. Before proceeding, hemakes a backup of the/etc/fstab file, just in case.

[root@station root]# cp /etc/fstab /etc/fstab.bak

Next, using a text editor, he duplicates his chosen line 3 times.

LABEL=/boot /boot ext3 defaults 1 2LABEL=/boot /boot ext3 defaults 1 2LABEL=/boot /boot ext3 defaults 1 2LABEL=/boot /boot ext3 defaults 1 2

Next, he begins implementing his customizations, changingonly what is necessary.

LABEL=/boot /boot ext3 defaults 1 2LABEL=pics /picts ext2 defaults 1 2/dev/hdb3 /dosd vfat defaults 1 2LABEL=/ogg /ogg ext3 defaults 1 2

Because he did not give his vfat filesystem a volume label, he must refer to it by device name.Fortunately, it is an IDE drive and a primary partition, so itshould be safe. He saves the file and quits theeditor.

Lastly, he tests out his configuration by first unmounting hispartitions, and then simulating a systemstartup by running themount -a command.

[root@station root]# umount /picts

[root@station root]# umount /dosd

[root@station root]# umount /ogg

[root@station root]# mount -a

mount: special device LABEL=/ogg does not exist

Realizing his mistake, he corrects the/etc/fstab file (replacingLABEL=/ogg with LABEL=ogg), andtries again.

[root@station root]# umount /picts

[root@station root]# umount /dosd

[root@station root]# umount /ogg

umount: /ogg: not mounted[root@station root]# mount -a

[root@station root]# mount

.../dev/hdb2 on /picts type ext2 (rw)/dev/hdb3 on /dosd type vfat (rw)/dev/hdb5 on /ogg type ext3 (rw)

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

63

Page 64: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 4. The/etc/fstab File

He is now satisfied with the results.

Online Exercises

Lab ExerciseObjective: Create a /etc/fstab entry which correctly defines a mount point foryour drive.

Estimated Time: 10 mins.

SpecificationThis exercise will continue to use the filesystem created andmounted in the previous 2 exercises. Ensurethat the file~/lab3.1/disk still exists, and that it still references the correct drive. The last partition ofthe drive should have a properly formatted ext2 filesystem.

1. Add a line to your/etc/fstab file which defines the mount performed in the last lab. To recap, thelast partition of the specified drive should be mounted to thedirectory/lab3, with thenoatimeandnoexecoptions.

2. The line should refer to your partition not by device name,but by filesystem label.

3. Add the appropriate customization so that your filesystemis not mounted by default on systemboots.

4. Configure the line appropriately so that the filesystem would not be archived by thedump command.

5. Unmount the partition before grading your exercise.

Deliverables

1. A properly configured/etc/fstab file which mounts the last partition on the specified drive to the directory/lab3 with thenoexecandnoatimeoptions. The partition shouldnot be mounted automatically on systemboots, and should not be included in archives created by thedump command. The partition should bereferenced by filesystem label.

2. The partition should not be currently mounted.

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use is a violation of U.S.and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwise duplicated whether in electronic or print format withoutprior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, or otherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919) 754 3700.

64

Page 65: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 4. The/etc/fstab File

Questions

Use the following transcript to answer the next 5 questions.

[root@station root]# cat /etc/fstab

LABEL=/ / ext3 defaults 1 1LABEL=/var/ftp/pub /var/ftp/pub ext3 defaults 1 2LABEL=/home /home ext3 defaults 1 2LABEL=/boot /mnt/boot ext3 defaults,noauto 1 2/dev/hda5 /dos vfat defaults,noauto,user 0 2devpts /dev/pts devpts gid=5,mode=620 0 0proc /proc proc defaults 0 0sysfs /sys sysfs defaults 0 0tmpfs /dev/shm tmpfs defaults 0 0LABEL=SWAP-hdb2 swap swap defaults 0 0/dev/fd0 /media/floppy auto user 0 0

1. Which of the following mount points would not be used by amount -a command?

( ) a./var/ftp/pub

( ) b. /dev/pts

( ) c./home

( ) d. /dos

( ) e.All of the above mount points would be used.

2. Which of the following command lines would attempt to mount the/dev/hda5 partition?

( ) a.mount /dev/hda5

( ) b. mount /dos

( ) c.mount /dev/hda5 /mnt/dos

( ) d. All of the above

( ) e.A and B only

3. Which of the following command lines would attempt to mount afilesystem to the/mnt/boot directory?

( ) a.mount -a

( ) b. mount /boot

( ) c.mount -L /boot

( ) d. A and C

( ) e.None of the above

rha130-5.0-0-en-2007-12-13T13:35:30-0500Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use is aviolation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in aretrieval system, or otherwise duplicated whether inelectronic or print format without prior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, or otherwise improperly distributedplease email [email protected] or phone toll-free (USA)+1 866 626 2994 or +1 (919) 754 3700.

65

Page 66: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 4. The/etc/fstab File

4. What is the most likely reason that the third column of the last line contains the wordauto?

( ) a. Because a FAT or ext2 or otherwise formatted floppy could be inserted into the drive, the filesystem typeshould be probed for each mount.

( ) b. When a floppy is inserted into the drive, the filesystem shouldbe automatically mounted.

( ) c. Upon bootup, the system should attempt to mount the floppy automatically.

( ) d. The auto filesystem is the most common filesystem used on floppydrives.

( ) e.None of the above adequately explain the configuration.

5. What users would be able to mount the device/dev/fd0?

( ) a. Only root may perform mounts.

( ) b. Any user logged in physically at the console (and root).

( ) c. Any user on the system.

( ) d. The current owner of the directory/mnt/floppy (and root).

( ) e.None of the above.

6. What does thenoautomount option imply?

( ) a. The filesystem should not be managed by an automounting daemon.

( ) b. The filesystem should not be automatically mounted whenevera file within the filsystem is references.

( ) c. The filesystem should not be mounted as part of the system startup process.

( ) d. The line should not be automatically removed from the configuration file if the underlying partition isdeleted.

( ) e.None of the above

7. What command could be used to create the label referred to by theLABEL= syntax in the/etc/fstab file?

( ) a. mke2fs

( ) b. fdisk

( ) c. mount

( ) d. fuser

( ) e.None of the above

Use the following transcript to answer the next 3 questions.

[root@station root]$ cat /etc/fstab

/dev/hda6 / ext3 defaults 1 1/dev/hda2 /boot ext3 defaults 1 2devpts /dev/pts devpts gid=5,mode=620 0 0proc /proc proc defaults 0 0

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use is a violation of U.S.and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwise duplicated whether in electronic or print format withoutprior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, or otherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919) 754 3700.

66

Page 67: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 4. The/etc/fstab File

sysfs /sys sysfs defaults 0 0tmpfs /dev/shm tmpfs defaults 0 0/dev/hda1 tmp ext3 defaults 1 2/dev/hda3 /var ext3 defaults 1 2/dev/hda4 /var/data ext3 defaults 1 1

8. What is suspicious about the first column of this file, which leads you to believe that there must be some mistake?

( ) a. A logical partition is being used as the root partition, which is not allowed.

( ) b. A device of type "none" is being mounted to the/proc partition, which makes no sense.

( ) c. All of the partitions are being mounted from a single drive.

( ) d. There is a jump from 4 to 6 in the listed partitions, with no mention of partition number 5.

( ) e.The file implies that all 4 primary partitions contain a filesystem, but a logical partition exists as well.

9. What is suspicious about the second column of this file, whichleads you to believe that there must be somemistake?

( ) a. Partitions are configured to be mounted to both/var/data and/var, but partitions may only be mountedto directories contained by the root partition.

( ) b. The mount pointtmp is specified as a relative reference.

( ) c. Filesystems are configured to be mounted to directories in the/dev directory, but the/dev directory mayonly contain device nodes.

( ) d. A partition is configured to be mounted to/, but only the kernel may mount the root partition.

( ) e.A filesystem is configured to be mounted to/proc, but the kernel automatically mounts/proc as part ofits bootup process.

10.What is suspicious about the last column of this file, which leads you to believe that there must be some mistake?

( ) a. The column contains the value 0, when only the values greaterthan 0 are allowed.

( ) b. The column contains multiple entries for the value "2", which will result in an error when thefsckcommand tries to decide which to check first.

( ) c. The column contains the value "2", when only the values 1 and 0are meaningful.

( ) d. The last column only exists for legacy reasons, so the fact that it contains non-zero values is suspect.

( ) e.The column contains multiple entries for the value "1", whenthe value 1 is only supposed to be used forthe root partition.

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

67

Page 68: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 5. Managing Swap Space

Key Concepts

• Partitions and Files may be used as Swap Space to extend a system’s apparent memory.

• Swap areas must be initialized with themkswap command.

• Swap areas are activated with theswaponcommand, and deactivated with the complementaryswapoffcommand.

• Swap areas may be listed in the/etc/fstab file in order to be activated automatically at systemstartup.

Discussion

Swap SpaceLinux allows block devices to be used to extend the system’s physical memory. In other operatingsystems, disk space used for such a purpose is often referredto as "virtual memory". In Linux (andUnix), it is referred to asswap space, and the act of using the disk based memory is referred to asswapping outmemory to disk.

In Linux, swap space may be allocated either as an entire partition or as a file in an already existing (andmounted) filesystem. The former is the more common, but can bemore difficult to set up once the systemis installed. The latter is less efficient, but can be quicklyput into place if some upcoming operation isgoing to require large amounts of memory.

Disk based memory is dramatically slower to access than RAM.As a result, swap space is generally usedto overcome temporary peak memory demands, and not as a general replacement for physical memory. Ifa system is consistently using large amounts of swap space, more physical memory would greatlyimprove its performance.

Users new to Linux are sometimes surprised to discover that,even when not running processesdemanding large amounts of memory, the Linux kernel uses swap space. Recall that the Linux kernelprimarily uses memory for two purposes: process memory, andcaching I/O operations. Sometimes, thekernel will sacrifice seldom used process memory for the sakeof increasing the size of the I/O cache,"swapping out" portions of seldom used processes in an attempt to improve overall system performance.The fact that the Linux kernel is using a little bit of swap space does not necessarily imply that morephysical memory is required.

In a similar vein, even systems with large amounts of physical memory should provide some amount ofswap space. The Linux kernel prefers to have the option of swapping memory to disk available as itdevelops its memory optimization strategies. Systems which do not provide swap space are officiallyconsidered an unsupported configuration by Red Hat.

68

Page 69: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 5. Managing Swap Space

Monitoring Swap Partitions: /proc/swaps and /proc/meminfo

The proc filesystem file/proc/swaps lists currently active swap spaces, their type (either partition orfile), their sizes, and their priority.

[root@station root]# cat /proc/swaps

Filename Type Size Used Priority/dev/hda2 partition 522104 42284 -1

The already familiar proc filesystem file/proc/meminfo lists the total amount of currently allocatedswap space, along with physical memory statistics.

[root@station root]# cat /proc/meminfo

MemTotal: 255232 kBMemFree: 19200 kBMemShared: 0 kB...SwapTotal: 522104 kB ➊

SwapFree: 479820 kB

➊ Swap utilization in conventional kilobytes (where 1 kB = 1024 bytes).

Initializing Swap Space with mkswapIn order to use a disk partition or file as swap space, it must first be initialized with themkswapcommand. Like themkfs family of commands, themkswap command expects to be called with amandatory argument, the file to be initialized. In the following example, themkswap command is usedto initialize the device/dev/sda1 as swap space.

[root@station root]# mkswap /dev/sda1

Setting up swapspace version 1, size = 130002 kB

Like creating a filesystem, initializing swap space with themkswap command is a one time action.

Activating Swap Space with swaponOnce initialized, swap space must be activated with theswaponcommand. In the following example, thepreviously initialized device/dev/sda1 is activated, examining the file/proc/swaps both before andafter to reflect the change.

[root@station root]# cat /proc/swaps

Filename Type Size Used Priority/dev/hda2 partition 522104 42284 -1[root@station root]# swapon /dev/sda1

[root@station root]# cat /proc/swaps

Filename Type Size Used Priority/dev/hda2 partition 522104 42284 -1/dev/sda1 partition 126952 0 -2

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

69

Page 70: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 5. Managing Swap Space

Theswaponcommand also allows priorities to be set with the-p command line switch. Swap areas withhigher priorities will be used before swap areas with lower priorities. See theswapon(2)man page fordetails.

Deactivating Swap Areas with swapoffThe complement to theswaponcommand,swapoffdeactivates the specified swap file. If the swap filewas in use, the command may take a while to run, as the kernel relocates all of the swapped pages toother swap areas, or back into RAM.

Predefining Swap Areas in the /etc/fstab FileWhen invoked with the-a command line switch, theswaponcommand will examine the/etc/fstab,and activate all listed swap partitions or files. When specifying a swap area in/etc/fstab, the firstcolumn should be the name of the partition or file to activate,the second and third columns should bothbe set to the word “swap”, and the fourth column should either be set to “defaults”, or the “pri=n”option can be used to assign the swap area a priority ofn. The last two fields should be set to 0.

Examples

Initializing Swap PartitionsHaving configured his filesystems to his liking, elvis now returns his attention to the swap partition hecreated. He initializes the partition with themkswap command.

[root@station root]# mkswap /dev/hda9

Setting up swapspace version 1, size = 139309 kB

Next, he activates the swap space with theswaponcommand, and confirms that it activated properly byexamining/proc/swaps.

[root@station root]# swapon /dev/hda9

[root@station root]# cat /proc/swaps

Filename Type Size Used Priority/dev/hda2 partition 2096472 0 -1/dev/hdb1 partition 136040 0 -2

In order to activate the swap partition automatically at system bootup, he adds a line to the/etc/fstabfile. Following the same technique used with his filesystems,he finds a similar line and duplicates it.

[root@rosemont-es root]# cp /etc/fstab /etc/fstab.bak

cp: overwrite ‘/etc/fstab.bak’? y

/dev/hda2 swap swap defaults 0 0/dev/hda2 swap swap defaults 0 0

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use isa violation of U.S. and international copyrights. No part ofthis publication may be photocopied, duplicated, stored ina retrieval system, or otherwise duplicated whetherin electronic or print format without prior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, or otherwise improperly distributedplease email [email protected] or phone toll-free (USA)+1 866 626 2994 or +1 (919) 754 3700.

70

Page 71: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 5. Managing Swap Space

Now, by editing a single word, his new swap partition is incorporated into the bootup process.

/dev/hda2 swap swap defaults 0 0/dev/hdb1 swap swap defaults 0 0

Using Swap FilesThe user blondie is about to perform a compilation of a large program she downloaded, and is concernedthat her machine does not have enough memory. In order to helpherself get past this one task, shedecides to create a swap file.

First, she used thedd command to create a 256 megabyte file full of zeros. On thedd command line, shespecifies her input file as the virtual device/dev/zero, the output file as her swap file,/tmp/swap, theblocksize as 1 megabyte, and the transfer size of 256 blocks.

[root@station root]# dd if=/dev/zero of=/tmp/swap bs=1024k count=256

256+0 records in256+0 records out[root@station root]# ls -s /tmp/swap

262404 /tmp/swap

After creating the file, she treats it as if it were a partition, first initializing it for use as swap space, andthen activating the file.

[root@station root]# mkswap /tmp/swap

Setting up swapspace version 1, size = 268431 kB[root@station root]# swapon /tmp/swap

[root@station root]# cat /proc/swaps

Filename Type Size Used Priority/dev/hdb2 partition 2096472 0 -1/dev/hda9 partition 136040 0 -2/tmp/swap file 262136 0 -3

She then performs her compilation. When finished, she cleansup by first deactivating the swap space,and the removing the file.

[root@station root]# swapoff /tmp/swap

[root@station root]# rm /tmp/swap

rm: remove regular file ‘/tmp/swap’? y

Online Exercises

Lab ExerciseObjective: Initialize a swap partition, and configure your /etc/fstab file so thatthe partition is activated automatically at system startup.

Estimated Time: 15 mins.

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

71

Page 72: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 5. Managing Swap Space

SpecificationThis exercise will use the first partition created in the firstExercise of this Workbook. Ensure that the file~/lab3.1/disk still exists, and that it still references the correct drive. The next to the last partition ofthe specified drive should be about 128 megabytes in size, andhave a partition id ofLinux Swap.

1. Initialize the next to the last partition to be used as swapspace.

2. Manually activate the swap partition.

3. Add a line to your/etc/fstab file, such that the swap partition is activated automatically at systemstartup.

Note: In the process of grading your lab, the swap space will be deactivated and reactivated. If thereactivation fails, you should manually restart the swap space (step 2) before regrading.

Deliverables

1. A properly initialized and activated swap partition, which is the next to the last partition on the specified drive.

2. A properly configured/etc/fstab file, such that the swap partition is automatically activated at bootup.

Questions

1.What is the threshold amount of physical memory, above whichallocating swap space is no longer recommended?

( ) a. 128 megabytes

( ) b. 256 megabytes

( ) c. 512 megabytes

( ) d. 1 gigabyte

( ) e.A swap partition should always be created, no matter how muchphysical memory is available.

2. Which of the following files lists currently active swap partitions?

( ) a./proc/swaps

( ) b. /etc/fstab

( ) c./var/state/swap

rha130-5.0-0-en-2007-12-13T13:35:30-0500Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use is a violationof U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrievalsystem, or otherwise duplicated whether in electronic or printformat without prior written consent of Red Hat, Inc. If you b elieve Red Hat course materials are being used, copied, or otherwise improperly distributed please [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919) 754 3700.

72

Page 73: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 5. Managing Swap Space

( ) d. /etc/swaptab

( ) e.None of the above

3. Which file is used to define swap partitions which should be activated automatically as the system boots?

( ) a./etc/swaptab

( ) b. /etc/fstab

( ) c./proc/swaps

( ) d. /var/state/swap

( ) e.none of the above

4. What command line would be used to initialize a disk partition to be used as swap space?

( ) a.swapinit /dev/hda3

( ) b. mkswap /dev/hda3

( ) c.mkfs -t swap /dev/hda3

( ) d. fdisk /dev/hda3

( ) e.None of the above

5. What command line would be used to initialize a file to be used as swap space?

( ) a.mkswap /tmp/swapfile

( ) b. mkswap -f /tmp/swapfile

( ) c.swapinit -f /tmp/swapfile

( ) d. mkswapfile /tmp/swapfile

( ) e.None of the above

6. ext3 is tomount as swap is to ....

( ) a. swapon

( ) b. mkswap

( ) c. swaps

( ) d. swapoff

( ) e. startswap

rha130-5.0-0-en-2007-12-13T13:35:30-0500Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use is a violationof U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrievalsystem, or otherwise duplicated whether in electronic or printformat without prior written consent of Red Hat, Inc. If you b elieve Red Hat course materials are being used, copied, or otherwise improperly distributed please [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919) 754 3700.

73

Page 74: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 5. Managing Swap Space

7. Which of the following lines could be used to define a swap areathat should be activated at system startup in the/etc/fstab file?

( ) a./dev/hda4 swap swap defaults 0 0

( ) b. swap /dev/hda4 swap defaults 0 0

( ) c./tmp/swapfile swap swap noauto 0 0

( ) d. /tmp/swapfile none none defaults 0 0

( ) e.None of the above

8. Which of the following commands is used to deactivate a swap area?

( ) a. swapstop

( ) b. umount

( ) c. uswap

( ) d. swapoff

( ) e.None of the above

9. Which of the following command lines could be used to activate a swap partition with a priority of 3?

( ) a.mkswap -p 3 /dev/hda3; swapon /dev/hda3

( ) b. swap /dev/hda3 3

( ) c.mount -t swap -o pri=3 /dev/hda3

( ) d. swapon -p 3 /dev/hda3

( ) e.none of the above

10.Which of the following commands could confirm that a swap partition is active with a priority of 3?

( ) a.cat /proc/swaps

( ) b. cat /proc/meminfo

( ) c.top

( ) d. cat /proc/slabinfo

( ) e.A and B

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

74

Page 75: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 6. Miscellaneous FilesystemManagement Commands

Key Concepts

• Thee2labelcommand can be used to examine and set ext2 and ext3 filesystemlabels.

• Thefsck command is used to check and repair filesystems.

• Thetune2fscommand can be used to modify already existing ext2 and ext3 filesystems.

• With the-j command line switch, thetune2fscommand can convert ext2 filesystems into ext3filesystems.

DiscussionIn this last Lesson of the Workbook, we cover a few miscellaneous commands and concepts that have notyet been addressed, and end with a summary which ties together the skills developed in this Workbookand places them into context with one another.

The e2label CommandThee2labelcommand is used to display or set the volume name of an ext2 or ext3 filesystem. The firstargument should be the name of the partition which contains the filesystem. If only one argument isprovided, the volume name is displayed. If an optional second argument is provided, the volume name isset to it. Both are exemplified in the following sequence.

[root@station root]# e2label /dev/hda1

/boot[root@station root]# e2label /dev/hda1 foo

[root@station root]# e2label /dev/hda1

foo

Recall that in Red Hat Enterprise Linux, you should not change volume names without also consideringthe configuration of the/etc/fstab file. After performing this example, unless theLABEL= referencefor the/boot partition is also changed in the/etc/fstab file, the/dev/hda1 partition will probablynot be mounted when the machine reboots.

File System Repair with fsckFilesystems generally maintain large amounts of internal data about their directory structure. Over time,disk imperfections or kernel bugs can lead to minor corruptions of this filesystem data. If a system isshutdown before a filesystem is unmounted, the filesystem is almost certain to contain corruptions.

75

Page 76: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 6. Miscellaneous Filesystem Management Commands

Traditionally, Unix provides afsck command, named for "(f)ile (s)ystem (c)hec(k)", which is used todiagnose and fix filesystem corruptions. The act of executingthefsck command on a filesystem is oftenreferred to as"fisking" the partition.

Much like themkfs command, Linux uses a front-endfsck command, backed by several file-systemspecific versions which startfsck..

[root@station root]# ls /sbin/fsck*/sbin/fsck /sbin/fsck.ext2 /sbin/fsck.jfs /sbin/fsck.reiserfs/sbin/fsck.cramfs /sbin/fsck.ext3 /sbin/fsck.msdos /sbin/fsck.vfat

Thefsck command can be called with the-t command line switch to specify a filesystem type, or thefilesystem specific version of the command can be used. Iffsck is used without the-t switch, it will try toautomatically determine the filesystem type, though this could be risky for heavily damaged filesystems.

Because the ext2 filesystem is so common, yet another name forthefsck.ext2command exists,e2fsck.The commandsfsck -t ext2, fsck.ext2, ande2fsckare all synonyms.

Using fsck

Thefsck command is generally called with the name of the partition tocheck as its lone argument. If thefsck command finds a problem which it can fix without a risk of losingdata, it will implement the fix. Ifthere is a possibility of losing data, thefsck command will pause and prompt to ask if it shouldimplement the fix. For administrators not blessed with a detailed knowledge of internal ext2 filesystemdesign, there is really little choice but to say "yes". In fact, thefsck command is often invoked with the-ycommand line switch, which in effect says "don’t ask, just doit".

The /lost+found Directory

Often, thefsck command may come across damaged data which it recognizes as afile, but which has noassociated a name or directory. (Recall that a file’s name is generally stored in a dentry, not in the inode.)Whenever anext2filesystem is created, a directory calledlost+found is created in its root directory.This directory exists to claim any lost files discovered byfsck. Thefsck command will make up a namefor the file, and place it in this directory.

Automatic fscking on Startup

By default, most Linux (and Unix) systems apply thefsck command to all filesystems at startup. If afilesystem was not previously unmounted cleanly, a thoroughfscking occurs. For ext2 filesystems, theentire filesystem is examined. For ext3 (and other) journaling filesystems, only the journal of pendingtransactions is examined, resulting in a much quicker check. Even for journaling filesystems, however, anoccasional, thorough check of the entire filesystem is suggested.

The tune2fs CommandThetune2fscommand is used to tweak filesystem parameters for an alreadyexisting ext2 or ext3filesystem, which is specified as its lone argument. Before a filesystem can be operated on withtune2fs,

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

76

Page 77: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 6. Miscellaneous Filesystem Management Commands

it must be unmounted. The following table lists some of the parameters which may be modified by thetune2fscommand.

Table 6-1. Command Line Switches for the tune2fs Command

Switch Effect

-c n Set the maximum mount count ton. After the filesystem has been mountedn

times, a mandatoryfsck check of the filesystem occurs.

-j Add an ext3 filesystem journal.

-L name Set the volume name toname. This option is identical in function to thee2labelcommand.

-m n Set the reserved blocks percentage ton.

The ext2 Mount Count

Most of these options refer to features of the ext2 filesystemwhich should already be familiar. Theexception is the-c command lines switch, and the concept of a maximum mount count.

The ext2 filesystem maintains a mount count, which is incremented every time the filesystem is mounted,and a maximum mount count parameter. If a mount would exceed the maximum mount count, amandatoryfsck of the filesystem is applied, and the mount count is reset to 0.

Converting ext2 Filesystems to ext3

As implied by the-j command line switch mentioned above, converting an ext2 filesystem into an ext3filesystem is trivial. Runtune2fs -j on it. Afterward, specify the filesystem type as ext3 when mounting it(or in the/etc/fstab file).

The only complexity occurs if this is thefirst time an ext3 filesystem has been used on the system. In thatcase, the system’s initial ramdisk (initrd) needs to be reconstructed so as to contain theext3.o kernelmodule. While this rather complicated topic will be addressed in a later Workbook, for now, consider thefollowing command line, run as root, the appropriate incantation for reconstructing an initial ramdisk.

[root@station root]# mkinitrd /boot/initrd-$(uname -r).img $(uname -r)

Again, this command is only necessary if the system does not already contain an ext3 filesystem.Because the ext3 filesystem is the default, this is rarely thecase.

Mounting ext3 filesystems as ext2

There is no need to "convert" an ext3 filesystem to ext2. Instead, just mount the filesystem, specifying thefilesystem type as ext2. The journal will be ignored.

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

77

Page 78: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 6. Miscellaneous Filesystem Management Commands

Review: Adding a New DiskIn order to make use of a new disk added to an existing system, the following steps are required. Thesesteps serve as a review of many of the topics covered in this workbook, placed into context with oneanother.

1. Physical Connection:Physically connect the disk to the machine. Upon rebooting,the new diskshould be identified in the stream of kernel messages seen on the console at bootup, or logged in thefile /var/log/dmesg. If evidence of the new drive is not found, there is a BIOS or physicalconnectivity problem which must be addressed before continuing.

2. Partitioning: The disk is subdivided into multiple partitions using thefdisk command. As we areconsidering a newly connected drive, the system will probably not have to be rebooted, as would bethe case for repartitioning a drive already in use.

3. Formatting: Any partitions which are going to be used as filesystems must be initialized with theappropriate variant of themkfs command, such asmkfs.ext3. Likewise, any partitions which aregoing to be used as swap space must be initialized with themkswap command.

4. Mounting: Filesystems must be mounted to a mount point before they can be used. Using themkdir command to create the mount point is an often overlooked step. Analogously, any swappartitions must be activated with theswaponcommand.

5. Updating /etc/fstab: If the filesystem is to be mounted (or the swap area activated)automatically at bootup, the appropriate lines should be added to the/etc/fstab file.

Examples

Converting an ext2 filesystem to ext3After a few weeks of using his new disk, and one too many waits for his ext2 filesystem to repair itself,prince decides he really should have made the filesystem ext3to begin with. He decides to convert it now.

First, he unmounts the filesystem.

[root@station root]# umount /picts

Next, he operates on the ext2 filesystem with thetune2fscommand, using the-j command line switch tospecify that a journal should be added. Because his memory ishazy, he first confirms that he has the rightpartition by examining its label.

[root@station root]# e2label /dev/hda6

pics[root@station root]# tune2fs -j /dev/hda6

tune2fs 1.32 (09-Nov-2002)Creating journal inode: doneThis filesystem will be automatically checked every 20 mounts or180 days, whichever comes first. Use tune2fs -c or -i to override.

Having finished the conversion, he tries performing the mount as an ext3 filesystem manually.

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use isa violation of U.S. and international copyrights. No part ofthis publication may be photocopied, duplicated, stored ina retrieval system, or otherwise duplicated whetherin electronic or print format without prior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, or otherwise improperly distributedplease email [email protected] or phone toll-free (USA)+1 866 626 2994 or +1 (919) 754 3700.

78

Page 79: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 6. Miscellaneous Filesystem Management Commands

[root@station root]# mount -t ext3 -L pics /picts

[root@station root]# mount

.../dev/hda7 on /dosd type vfat (rw)/dev/hda8 on /ogg type ext3 (rw)/dev/hda6 on /picts type ext3 (rw)

As that seemed to work without incident, he updates his/etc/fstab file.

LABEL=pics /picts ext3 defaults 1 2

Online Exercises

Lab ExerciseObjective: Use filesystem maintenance commands to modify existing filesystems.

Estimated Time: 20 mins.

SpecificationThis exercise will continue to use the filesystem created andmounted in the previous Exercises. Ensurethat the file~/lab3.1/disk still exists, and that it still references the correct drive. The last partition ofthe drive should have a properly formatted ext2 filesystem.

1. Use the appropriate commands to convert your ext2 filesystem into an ext3 filesystem.Do not createa new filesystem. Any information contained in the filesystem should be preserved.

2. Change the filesystem label tolab3.6.

3. Update your/etc/fstab file, so that the appropriate label is used, and the filesystemis mounted asan ext3 filesystem.

4. Unmount the partition before grading your exercise.

Deliverables

1. The last partition of the specified drive should be an ext3 filesystem, with a label oflab3.6, and no blocksreserved for root. The contents of the filesystem should be preserved in the process.

2. An appropriately configured/etc/fstab file, updated to refer to the new label and the ext3 filesystem.

rha130-5.0-0-en-2007-12-13T13:35:30-0500Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use is a violationof U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrievalsystem, or otherwise duplicated whether in electronic or printformat without prior written consent of Red Hat, Inc. If you b elieve Red Hat course materials are being used, copied, or otherwise improperly distributed please [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919) 754 3700.

79

Page 80: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 6. Miscellaneous Filesystem Management Commands

Questions

1. Which of the following command lines could be used to check and repair an ext2 filesystem?

( ) a.fsck /dev/hda3

( ) b. fsck -t ext2 /dev/hda3

( ) c.fsck.ext2 /dev/hda3

( ) d. e2fsck /dev/hda3

( ) e.All of the above

2. Which of the following command lines could be used to assign the label/datato an ext2 filesystem?

( ) a.e2label /data /dev/hda3

( ) b. e2label -L /data /dev/hda3

( ) c.e2label /dev/hda3 /data

( ) d. label -t ext2 /dev/hda3 /data

( ) e.None of the above

The remaining questions refer to the following scenario.

You have just attached a newly purchased drive to an already existing Red Hat Enterprise Linux installation, as theIDE secondary slave drive. Using only the tools discussed inthis Workbook, you would like to create 6 ext2filesystems, each mounted to the directories/data1, /data2, ...,/data6, and a 256 megabyte swap partition. Youwould like all 6 partitions to be mounted and the swap area to be activated automatically at bootup.

3. Which of the following commands could you get away withnot using?

( ) a. e2label

( ) b. mkswap

( ) c. fdisk

( ) d. mount

( ) e.All of the above commands are required.

4. What is the most reasonable ordering for the commands you will use?

( ) a. mke2fs, mkswap, fdisk, mount, swapon

( ) b. fdisk, swapon, mkswap, mke2fs, mount

( ) c. mount, fdisk, mke2fs, mkswap, swapon

( ) d. fdisk, mke2fs, mkswap, mount, swapon

( ) e. mkswap, swapon, mke2fs, mount, fdisk

rha130-5.0-0-en-2007-12-13T13:35:30-0500Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use is a violationof U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrievalsystem, or otherwise duplicated whether in electronic or printformat without prior written consent of Red Hat, Inc. If you b elieve Red Hat course materials are being used, copied, or otherwise improperly distributed please [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919) 754 3700.

80

Page 81: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 6. Miscellaneous Filesystem Management Commands

5. At least how many logical partitions will need to be used?

( ) a. 1

( ) b. 2

( ) c. 3

( ) d. 4

( ) e.5

6. Which of the following command lines could be used to create an ext2 filesystem on the first logical partition, andassign it the label/data3?

( ) a.mke2fs -L /data3 /dev/hdd5

( ) b. mke2fs /dev/hdd5; e2label /dev/hda5 /data3

( ) c.mke2fs /dev/hdd5; tune2fs -L /dev/hda5 /data3

( ) d. All of the above

( ) e.None of the above

7. Once the ext2 filesystems have been created, and are all mounted, you decide that you would like the filesystemon partition /dev/hdd2 to be an ext3 filesystem instead. Which command line could be used to convert the filesystemto ext3 (without losing any data already in the filesystem)?

( ) a.tune2fs -j /dev/hdd2

( ) b. umount /dev/hdd2 && mkfs.ext3 /dev/hdd2

( ) c.umount /dev/hdd2 && tune2fs -j /dev/hdd2

( ) d. umount /dev/hdd2 && mke2fs -j /dev/hdd2

( ) e.None of the above

8. You decide that you would like to check and repair the filesystem on partition/dev/hdd3. You unmount thepartition. What command could you run next to perform the check?

( ) a.swapoff /dev/hdd3

( ) b. fsck.vfat /dev/hdd3

( ) c.fisk /dev/hdd3

( ) d. fsck /dev/hdd3

( ) e.None of the above

rha130-5.0-0-en-2007-12-13T13:35:30-0500Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use is a violationof U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrievalsystem, or otherwise duplicated whether in electronic or printformat without prior written consent of Red Hat, Inc. If you b elieve Red Hat course materials are being used, copied, or otherwise improperly distributed please [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919) 754 3700.

81

Page 82: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 6. Miscellaneous Filesystem Management Commands

9. The check and repair utility used above mentions that it has restored some file, but could not find names for.Where should you look for these files?

( ) a. The/lost+found directory in your root partition.

( ) b. Thelost+found directory in the repaired filesystem’s root directory.

( ) c. The/proc/lost+found directory.

( ) d. The/tmp/lost+found directory.

( ) e.None of the above

10.You realize that your previously installed Red Hat Enterprise Linux system had not used the ext3 filesystem.After successfully converting your new ext2 filesystem to ext3, what additional command should be run?

( ) a. ext3init

( ) b. kudzu

( ) c. mkinitrd

( ) d. setup

( ) e. mkext3

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

82

Page 83: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 7. SELinux: Secure Linux

Key Concepts

• Red Hat Enterprise Linux 4 ships with a new security mechanism implemented by the kernel, knownas SELinux.

• SELinux potentially casts every process into a SELinuxdomain, and every resource (such as files) intoa SELinux securitycontext. A SELinuxpolicy then specifies which processes can access whichresources.

• The SELinux policy is implemented at a low level, and is in general not configurable by an end systemadministrator.

• The SELinux policy that ships with Red Hat Enterprise Linux 4is know as thetargetedpolicy, andonly effects selected networking daemons.

• The system can boot into one of three SELinux related states,enforcing, permissive, or disabled.

• The default state can be set by editing the/etc/sysconfig/selinux configuration file.

• The SELinux state can be immediately switched fromenforcingto permissiveand back using thesetenforcecommand.

• SELinux domains and contexts can be examined by adding the new -Z command line switch to thetraditionalps andls commands.

• The SELinux context of a file can be modified using the newchconcommand.

Discussion

Introduction to SELinux ("Secure Linux")In Red Hat Enterprise Linux 4, A fundamentally new approach to Linux (and Unix) security wasintroduced:SELinux. The result of an NSA development effort (http://www.nsa.gov/selinux) targeted atsecuring computer infrastructure, SELinux allows administrators to define highly customizable securitypolicies which are enforced by the Linux kernel as it performs its normal operations.

Using SELinux, processes can be cast into a particular SELinux domain, and every resource on thesystem (such as files, networking sockets, system calls, andso on) can be assigned a particular SELinuxcontext. A SELinux policy loaded into the kernel (usually as part of the system bootup process) thendefines which process domains may access which resource contexts.

The design of any security mechanism must be flexible enough to be useful, but simple enough for anadministrator to confidently implement the policy. As comparatively simple as the standard Unix modelof file ownerships and permissions is, it’s probably the mostcommon source of administrative headaches- either because a file was left too exposed, or not exposed enough.

83

Page 84: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 7. SELinux: Secure Linux

SELinux falls way to the flexible and complex side of the simple-flexible spectrum. From the Red Hatperspective, as an administrator, you should never need to write or modify your own SELinux policy.Instead, in Red Hat Enterprise Linux, your SELinux related decisions should be limited to to thefollowing.

1. Do I want to enable SELinux?

2. If enabled, do I want SELinux in thepermissiveor enforcingstate?

3. What SELinux context do I want to assign to a particular file?

The targeted SELinux PolicyAs mentioned above, designing an appropriate SELinux policy is a complex task. One of severaldifferent policies could be chosen as a system boots. Although other policies ship with Red HatEnterprise Linux 5, we will restrict our attention to the default targetedpolicy. The targeted policy affectsa selection of more commonly used network applications, including the ones listed below, and more.

• dhcpd

• httpd

• mysqld

• named

• nscd

• ntpd

• portmap

• postgres

• snmpd

• squid

• syslogd

• and more...

Unless you are managing files which are used by one of the included applications, the targeted SELinuxpolicy should not hinder interactive uses of a Red Hat Enterprise Linux workstation. As onlysyslogdfrom this list is relevant to this course, managing SELinux is not a major focus. However, anyadministrator of a Red Hat Enterprise Linux system should atleast be aware of the topics covered in thislesson.

Enabling SELinux: /etc/sysconfig/selinux, setenforce, andgetenforceUpon bootup, a Red Hat Enterprise Linux 4 machine enters one of three SELinux states.

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

84

Page 85: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 7. SELinux: Secure Linux

• enforcing: Any action that would violate the SELinux policy is prohibited, and the violation is loggedas a kernel message.

• permissive: Any action that would violate the SELinux policy generatesa warning (in the form of akernel message), but the action is allowed to continue.

• disabled.

The default state is specified as part of the installation process, and recorded in the file/etc/sysconfig/selinux. The default SELinux state can be changed by editing this file, or the statecan be changed immediately using thesetenforcecommand.

The /etc/sysconfig/selinux configuration file

This simple configuration file is used upon bootup to determine the SELinux state and policy.

[student@station ~]$ cat /etc/sysconfig/selinux

# This file controls the state of SELinux on the system.# SELINUX= can take one of these three values:# enforcing - SELinux security policy is enforced.# permissive - SELinux prints warnings instead of enforcing.# disabled - SELinux is fully disabled.SELINUX=permissive ➊

# SELINUXTYPE= type of policy in use. Possible values are:# targeted - Only targeted network daemons are protected.# strict - Full SELinux protection.SELINUXTYPE=targeted ➋

➊ The default SELinux state can be set usingSELINUX. Changes will apply on the next boot.

➋ The policy can be chosen usingSELINUXTYPE.

The setenforce and getenforce commands

Assuming SELinux is not disabled, the SELinux state can alsobe immediately switched fromenforcingto permissive(and back) using thesetenforcecommand. The command expects a single argument, eithera 0 or 1, which respond to the permissive and enforcing states, respectively.

The following command switches SELinux to thepermissivestate.

[root@station ~]# setenforce 0

[root@station ~]# getenforce

Permissive

The following command switches SELinux to theenforcingstate.

[root@station ~]# setenforce 1

[root@station ~]# getenforce

Enforcing

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

85

Page 86: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 7. SELinux: Secure Linux

Note thatgetenforcemerely displays the current state. Thesetenforcecommand takes effectimmediately, but does not change the default state if the machine is rebooted. These commands are oftenhelpful in debugging SELinux configuration problems.

Viewing SELinux contexts: ps -Z and ls -ZAs mentioned, each process belongs to a SELinux domain, and each file can be assigned a SELinuxcontext. The relevant domains and contexts can be viewed by using the (new)-Z command line switchwith the conventionalls andpscommands.

The following command can be used to view the SELinux domain of all running processes.

[student@station ~]$ ps ax -Z

LABEL PID TTY STAT TIME COMMANDsystem_u:system_r:init_t 1 ? Ss 0:00 init [5]system_u:system_r:kernel_t 2 ? S 0:00 [migration/0]system_u:system_r:kernel_t 3 ? SN 0:00 [ksoftirqd/0]system_u:system_r:kernel_t 4 ? S 0:00 [watchdog/0]...system_u:system_r:httpd_t 1631 ? S 0:00 /usr/sbin/httpdsystem_u:system_r:xfs_t 1651 ? Ss 0:00 xfs -dropprivsystem_u:system_r:crond_t:SystemLow-SystemHigh 1672 ? Ss 0:00 /usr/sbin/atdsystem_u:system_r:rpm_t 1697 ? S 0:00 /usr/sbin/yum-updatesdsystem_u:system_r:avahi_t 1709 ? Ss 0:00 avahi-daemon: running...system_u:system_r:unconfined_t:SystemLow-SystemHigh 2030 ? Ss 0:00 sshd: root@pts/0root:system_r:unconfined_t:SystemLow-SystemHigh 2032 pts/0 Ss 0:00 -bashroot:system_r:unconfined_t:SystemLow-SystemHigh 2058 pts/0 R+ 0:00 ps ax -Zroot:system_r:unconfined_t:SystemLow-SystemHigh 2059 pts/0 D+ 0:00 -bash

Notice that the domain type of interactive processes, such as thebashshell and thepscommand startedfrom the shell, domain type isunconfined_t, implying that the process is not restrained by any SELinuxcontext. User interactive shells, and generally processesstarted them, are generally not effected by thedefault SELinuxtargetedpolicy.

The SELinux context of files can be seen by adding-Z to thels command. In the following example, the-a switch is only necessary because the fairly recently created home directory has not yet collected any"nonhidden" files.

[student@station ~]$ ls -a -Z

drwx------ student student user_u:object_r:user_home_dir_t .drwxr-xr-x root root system_u:object_r:home_root_t ..-rw-r--r-- student student user_u:object_r:user_home_t .bash_logout-rw-r--r-- student student user_u:object_r:user_home_t .bash_profile-rw-r--r-- student student user_u:object_r:user_home_t .bashrcdrwxr-xr-x student student user_u:object_r:user_home_t Desktop-rw-r--r-- student student user_u:object_r:user_home_t .zshrc

Note that all of these files have the typeuser_home_t. Some were created by the userstudentas she, forexample, fired up the Firefox web browser, others were created automatically when the account was

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

86

Page 87: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 7. SELinux: Secure Linux

added (before the student ever logged on). Theuser_uportion of the SELinux context denotes that thefile was created by the user.

Exploration of the filesystem with thels -Z command will produce a large number of SELinux typesassociated with various files. (The/etc and/var directories are particularly interesting).

Realize that knowing the SELinux domain of a process, or the SELinux context of a file, is not enough.You also need to know what the current policy dictates. Unfortunately, with the current set of SELinuxtools, examining the current policy is not easy, and the effects of the SELinux policy are generally onlydiscovered when something tries to violate it.

Monitoring SELinux violations: sealert and/var/log/messages

Whenever a SELinux violation occurs, the kernel notifies thedeamonsetroubleshootdthat a violationhas occured. The daemons stores information about the violation, and logs a message containing theviolation’s unique identifier in/var/log/messages.

Aug 13 15:37:47 station setroubleshoot: SELinux is preventing the/usr/sbin/httpd from using potentially mislabeled files (/var/www/html/index.html).For complete SELinux messages. run sealert -l 88f46e71-fda2-41e4-b3d6-0874996f9c9a

Following the log message’s advice, we can use thesealertcommand to reveal much more informationabout the violation.

[root@station log]# sealert -l 88f46e71-fda2-41e4-b3d6-0874996f9c9a

SummarySELinux is preventing the /usr/sbin/httpd from using potentially mislabeledfiles (/var/www/html/index.html).

Detailed DescriptionSELinux has denied /usr/sbin/httpd access to potentially mislabeled file(s)(/var/www/html/index.html). This means that SELinux will not allow/usr/sbin/httpd to use these files. It is common for users to edit files intheir home directory or tmp directories and then move (mv) them to systemdirectories. The problem is that the files end up with the wrong filecontext which confined applications are not allowed to access.

Allowing AccessIf you want /usr/sbin/httpd to access this files, you need to relabel themusing restorecon -v /var/www/html/index.html. You might want to relabel theentire directory using restorecon -R -v /var/www/html.

Additional Information

Source Context system_u:system_r:httpd_tTarget Context root:object_r:tmp_tTarget Objects /var/www/html/index.html [ file ]Affected RPM Packages httpd-2.2.3-6.el5 [application]Policy RPM selinux-policy-2.4.6-30.el5Selinux Enabled True

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use isa violation of U.S. and international copyrights. No part ofthis publication may be photocopied, duplicated, stored ina retrieval system, or otherwise duplicated whetherin electronic or print format without prior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, or otherwise improperly distributedplease email [email protected] or phone toll-free (USA)+1 866 626 2994 or +1 (919) 754 3700.

87

Page 88: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 7. SELinux: Secure Linux

Policy Type targetedMLS Enabled TrueEnforcing Mode EnforcingPlugin Name plugins.home_tmp_bad_labelsHost Name station.example.comPlatform Linux station.example.com 2.6.18-8.el5xen #1 SMP

Fri Jan 26 14:42:21 EST 2007 i686 i686Alert Count 2Line Numbers

Raw Audit Messages

avc: denied { getattr } for comm="httpd" dev=xvda2 egid=48 euid=48exe="/usr/sbin/httpd" exit=-13 fsgid=48 fsuid=48 gid=48 items=0name="index.html" path="/var/www/html/index.html" pid=1626scontext=system_u:system_r:httpd_t:s0 sgid=48 subj=system_u:system_r:httpd_t:s0suid=48 tclass=file tcontext=root:object_r:tmp_t:s0 tty=(none) uid=48

By examining the detailed message, we deduce that the file/var/www/html/index.html did not havethe appropriate SELinux context.

If the targetedSELinux policy is causing a problem, an administrator generally has three options.

1. Disable SELinux.

2. Change the SELinux context of the file which is causing the violation.

3. Tweak the policy through the use of SELinux booleans.

We’ve already discussed how to disable SELinux (recall thesetenforcecommand and the/etc/sysconfig/selinux configuration file). In the following sections, we discuss changing a file’sSELinux context and tweaking a policy through the use of SELinux booleans.

Changing the SELinux Context of a File: chconJust as a file’s owner, group, or mode (permissions) are changed withchown, chgrp, andchmod(respectively), a file’s SELinux security context is changed with chcon.

Table 7-1. Common Command Line Switches for the chcon Command

Switch Effect

-R, --recursive change files and directories recursively

--reference=FILE Use the security context of FILE to define theresulting context.

-u, --user=USER; -r, --role=ROLE; -t,--type=TYPE

set USER, ROLE, or TYPE component of thefile’s security context, respectively.

Most commonly, an administrator would like a problematic file to take on the context of a "known good"file. As an example, the following command would cause/etc/named.conf to inherit the SELinuxsecurity context of/etc/named.conf.rpmorig.

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use isa violation of U.S. and international copyrights. No part ofthis publication may be photocopied, duplicated, stored ina retrieval system, or otherwise duplicated whetherin electronic or print format without prior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, or otherwise improperly distributedplease email [email protected] or phone toll-free (USA)+1 866 626 2994 or +1 (919) 754 3700.

88

Page 89: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 7. SELinux: Secure Linux

[root@station ~]# chcon --reference=/etc/named.conf.orig /etc/named.conf

Restoring the SELinux Context of a File: restoreconWhile thechconcommand gives and adminstrator the ability to change the SELinux context of a file, itdoesn’t necessarily tell the adminstrator what the contextof a file should be. The targeted policy includesa database of file and directory locations, and associated SELinux contexts. Using the assumption that afile’s appropriate SELinux context is defined by where it resides in the filesystem, therestoreconcommand restores the appropriate context.

As an example, the problematicindex.html file was created in the/tmp directory, and thereforeacquired the associatedtmp_t type.

[root@station log]# ls -Z /var/www/html/

-rw-r--r-- root root root:object_r:tmp_t index.html

As thesealertmessage implied, an adminstrator can trivially align the file’s SELinux type with theexpectations of the SELinux policy using therestoreconcommand.

[root@station log]# restorecon /var/www/html/index.html

[root@station log]# ls -Z /var/www/html

-rw-r--r-- root root system_u:object_r:httpd_sys_content_t index.html

By specifying-R, therestoreconcommand recurses through subdirectories as well.

[root@station log]# restorecon -R /var/www/html/

Managing SELinux Booleans: getsebool and setseboolWhile an adminstrator is discouraged from crafting their own SELinux policy, the default policy doesfeature a collection of yes/no options which an adminstrator can modify on the fly, referred to asSELinuxbooleans.

Booleans can be listed with thegetseboolcommand, using-a to list all available booleans and theircurrent setting.

[root@station html]# getsebool -a

NetworkManager_disable_trans --> offallow_cvs_read_shadow --> offallow_daemons_dump_core --> onallow_daemons_use_tty --> offallow_execheap --> offallow_execmem --> on...ftp_home_dir --> off...

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use isa violation of U.S. and international copyrights. No part ofthis publication may be photocopied, duplicated, stored ina retrieval system, or otherwise duplicated whetherin electronic or print format without prior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, or otherwise improperly distributedplease email [email protected] or phone toll-free (USA)+1 866 626 2994 or +1 (919) 754 3700.

89

Page 90: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 7. SELinux: Secure Linux

SElinux booleans can be modified with the complementarysetseboolcommand. For example, thedefault policy does not allow users to access their home directory using the FTP service. Thesetseboolcommand can be used to enable home directory access.

[root@station www]# setsebool ftp_home_dir 1

[root@station www]# getsebool ftp_home_dir

ftp_home_dir --> on

By default,setseboolmodifies the policy dynamically, and the default will be restored the next time themachine reboots. The-P command line switch causes the modification to persist across reboots.

[root@station www]# setsebool -P ftp_home_dir 1

Administering SELinux with system-config-selinuxRed Hat Enterprise Linux provides a graphical tool for administering SELinux,system-config-selinux.After understanding the role of/etc/sysconfig/selinux, getenforceandsetenforce, getseboolandsetsebool, andchconandrestorecon, the functionallity of the first two panels should be self evident,with one exception.

Figure 7-1. Managing SELinux State with system-config-selinux

On the first "Status" panel, "Relabel on next reboot" can be selected. This has the effect of runningrestorecon -R / early in the bootup process, effectively resetting the SELinux state of the entirefilesystem. This is accomplished by createing the file/.autorelabel, which is discovered by startupscripts upon a reboot.

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

90

Page 91: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 7. SELinux: Secure Linux

Figure 7-2. Managing SELinux Booleans with system-config-selinux

Thesystem-config-selinuxutility has many other capabilities, most of which relate topolicies other thanthetargetedpolicy. While interesting, they are beyond the scope of thiscourse. (Browsing theFileLabellingpanel, however, can provide insight into the behaviour ofrestorecon.)

Examples

Changing the SELinux Context of a FileThe userprince would like to publish files which document elvis sightings through the web server byplacing them in the Web Server’s document root directory,/var/www/html. He starts with two fileswhich he had previously created in his home directory,elvis_in_austin.html andelvis_in_pheonix.html. The first, he copies to the document root. The second, he moves there. Hethen checks that the files can be read by the system userapache.

[prince@station ~]$ su

Password:[root@station prince]# cp elvis_in_austin.html /var/www/html/

[root@station prince]# mv elvis_in_pheonix.html /var/www/html/

[root@station prince]# ls -l /var/www/html/

total 56-rw-r--r-- 1 root root 219 Jul 31 19:38 elvis_in_austin.html-rw-rw-r-- 1 prince prince 228 Jul 31 19:37 elvis_in_pheonix.html

Seeing that each of the files is readable by all, he’s satisfiedthat the webserver (which runs as the userapache) will be able to read the file. He next opens a browser, and references the files.

[prince@localhost ~]$ elinks -dump http://localhost/elvis_in_austin.html

Elvis seen watching bats in Austin

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use isa violation of U.S. and international copyrights. No part ofthis publication may be photocopied, duplicated, stored ina retrieval system, or otherwise duplicated whetherin electronic or print format without prior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, or otherwise improperly distributedplease email [email protected] or phone toll-free (USA)+1 866 626 2994 or +1 (919) 754 3700.

91

Page 92: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 7. SELinux: Secure Linux

Austin native Fred Anderson claims to have seen Elvis watching the batsfly from a underneath the Congress St. bridge in Austin TX. When...

[prince@localhost ~]$ elinks -dump http://localhost/elvis_in_pheonix.html

Forbidden

You don’t have permission to access /elvis_in_pheonix.html on this server....

Perplexed as to why access toelvis_in_pheonix.html was forbidden, prince suspects SELinux. Toconfirm, prince becomes root, and temporarily drops the SELinux state fromenforcingto permissive,and tries again.

[prince@localhost ~]$ su -

Password:[root@station ~]# getenforce

Enforcing[root@station ~]# setenforce 0

[root@station ~]# getenforce

Permissive

[prince@localhost ~]$ elinks -dump http://localhost/elvis_in_pheonix.html

Elvis seen Jousting Cactus outside of Pheonix

Pheonix native John Doe claims to have seen Elvis riding a llama, joustinga cactus with a fishing pole. When approached, however, Elvis and the...

Convinced that the SELinux policy was causing the problem, he looks for a log message in/var/log/messages.

[root@station8 prince]# tail /var/log/messages

...Aug 13 16:10:10 station setroubleshoot: SELinux is preventing the/usr/sbin/httpd from using potentially mislabeled files(/var/www/html/elvis_in_pheonix.html). For complete SELinux messages.run sealert -l 09f29720-4a3a-490d-b815-3205ca39333f...

Following the message advice, he explores the problem.

[root@station ~]# sealert -l 09f29720-4a3a-490d-b815-3205ca39333f

SummarySELinux is preventing the /usr/sbin/httpd from using potentially mislabeledfiles (/var/www/html/elvis_in_pheonix.html).

...

Allowing AccessIf you want /usr/sbin/httpd to access this files, you need to relabel themusing restorecon -v /var/www/html/elvis_in_pheonix.html. You might want torelabel the entire directory using restorecon -R -v /var/www/html.

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use isa violation of U.S. and international copyrights. No part ofthis publication may be photocopied, duplicated, stored ina retrieval system, or otherwise duplicated whetherin electronic or print format without prior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, or otherwise improperly distributedplease email [email protected] or phone toll-free (USA)+1 866 626 2994 or +1 (919) 754 3700.

92

Page 93: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 7. SELinux: Secure Linux

Additional Information

Source Context system_u:system_r:httpd_tTarget Context root:object_r:user_home_tTarget Objects /var/www/html/elvis_in_pheonix.html [ file ]Affected RPM Packages httpd-2.2.3-6.el5 [application]...

[root@station ~]# ls -Z /var/www/html/

-rw-r--r-- root root root:object_r:httpd_sys_content_t elvis_in_austin.html-rw-rw-r-- prince prince user_u:object_r:file_t elvis_in_pheonix.html

Becauseelvis_in_austin.html is copied to/var/www/html usingcp, the resulting file is a newlycreated file, which inherits the user who created it (root) and the SELinux context of the directory inwhich it is created (httpd_sys_content_t).

In contrast, the fileelvis_in_pheonix.html is movedto its new destination using themv command.Moving a files does not create a new one, but relocates an already existing one. As a result, the user whocreated it (prince) and more pertinently the SELinux context (user_home_t) is retained. When the webserver process tries to read a file of typeuser_home_t, a SELinux policy violation occurs.

To fix the situation, prince (as root) uses thechconcommand to pass the SELinux context from the"good" file to the "bad", andsetenforceto restore SELinux to theenforcingstate.

[root@station ~]# cd /var/www/html/

[root@station html]# chcon --reference elvis_in_austin.html elvis_in_pheonix.html

[root@station html]# ls -Z

-rw-r--r-- root root root:object_r:httpd_sys_content_t elvis_in_austin.html-rw-rw-r-- prince prince root:object_r:httpd_sys_content_t elvis_in_pheonix.html[root@station html]# setenforce 1

Now, the web server can view the file with ease.

[prince@localhost ~]$ elinks -dump http://localhost/elvis_in_pheonix.html

Elvis seen Jousting Cactus outside of Pheonix

Pheonix native John Doe claims to have seen Elvis riding a llama, joustinga cactus with a fishing pole. When approached, however, Elvis and the

...

Note: If you are confused by the use of the web server above, or the reference to the term"document root", don’t be too concerned, and take heart that we needed to stretch to find anexample of a problem caused by SELinux for this course.

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

93

Page 94: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 7. SELinux: Secure Linux

Online Exercises

Lab ExerciseObjective: Set appropriate SELinux contexts for a files

Estimated Time: 20 mins.

Specification

1. Your system should be in the SELinuxenforcingstate. If this is not the case, edit the/etc/sysconfig/selinux file appropriately, and reboot your machine. You should be able toreproduce the following command.

[root@station4 html]# getenforce

Enforcing

2. In this lab, you will publish files using your web server. Ifyou have not yet started your web server(and you probably haven’t), start it using theservicecommand.

[root@station8 ~]# service httpd start

Starting httpd: [ OK ][root@station8 ~]# service httpd status

httpd (pid 15611 15610 15609 15608 15607 15606 15605 15604 15601) is running...

3. You would like to publish a copy of your/var/log/dmesg file. (Don’t worry if you don’t knowwhat it is yet.) Copy the file to the/var/www/html directory, and observe the ownerships andpermissions. You should be able to view the contents by pointing any browser tohttp://localhost/dmesg.

4. You would also like to publish a copy of the/var/log/rpmpkgs file, but you realize this file isupdated nightly. In order to automatically publish the updates as well,hard link the file into the/var/www/html directory.

[root@station4 html]# ln /var/log/rpmpkgs /var/www/html/

[root@station4 html]# ls -i /var/log/rpmpkgs /var/www/html/rpmpkgs

180333 /var/log/rpmpkgs 180333 /var/www/html/rpmpkgs[root@station8 html]# ll /var/www/html/rpmpkgs

-rw-r--r-- 2 root root 23076 Jul 2 04:04 /var/www/html/rpmpkgs

Although the file/var/www/html/rpmpkgs is readable by all, you should still not be able toaccess http://localhost/rpmpkgs from a web browser. Why?

5. Use thechconcommand, referencing the "working" file/var/www/html/dmesg, to assign/var/log/html/rpmpkgs the appropriate SELinux security context. If completed successfully,you should be able to access http://localhost/rpmpkgs froma web browser.

Usels -Z to observe the SELinux context of/var/log/rpmpkgs. Why did it change as well?

rha130-5.0-0-en-2007-12-13T13:35:30-0500Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use is a violation

of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrievalsystem, or otherwise duplicated whether in electronic orprint format without prior written consent of Red Hat, Inc. I f you believe Red Hat course materials are being used, copied, or otherwise improperly distributed please [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919) 754 3700.

94

Page 95: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 7. SELinux: Secure Linux

Deliverables

1. The system is in the SELinuxenforcingstate.

2. A web browser can access http://localhost/dmesg.

3. A web browser can access http://localhost/rpmpkgs.

4. The files/var/log/rpmpkgs and/var/www/html/rpmpkgs have the same inode number (i.e., they are hardlinks of the same file).

Clean UpAfter you have completed the exercise, restore your system to the desired SELinux state, remove/var/www/html/rpmpkgs, and restore the appropriate context on/var/log/rpmpkgs with thefollowing command.

[root@station8 ~]# chcon --reference /var/log /var/log/rpmpkgs

Questions

1. Which of the following isnot a SELinux state?

( ) a. disabled

( ) b. enforcing

( ) c. paranoid

( ) d. permissive

2. What is the name of the default Red Hat Enterprise Linux 5 SELinux policy?

( ) a. targeted

( ) b. strong

( ) c. shadowman

( ) d. full

( ) e.None of the above.

rha130-5.0-0-en-2007-12-13T13:35:30-0500Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use is a violationof U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrievalsystem, or otherwise duplicated whether in electronic or printformat without prior written consent of Red Hat, Inc. If you b elieve Red Hat course materials are being used, copied, or otherwise improperly distributed please [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919) 754 3700.

95

Page 96: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 7. SELinux: Secure Linux

3. Which file establishes the default SELinux state upon bootup?

( ) a./etc/selinux

( ) b. /etc/boot.opts

( ) c./etc/fstab

( ) d. /etc/security/selinux

( ) e.None of the above

4. Which of the following processes would you expect to be most constrained by the default Red Hat EnterpriseLinux 5 SELinux policy?

( ) a. bash

( ) b. dd

( ) c. ls

( ) d. httpd

( ) e. ps

5. Which of the following command lines could be used to most directly determine the current SELinux state?

( ) a.lscon

( ) b. ps -axZ

( ) c.service selinux status

( ) d. getenforce

( ) e.cat /proc/selinux

6. Which of the following commands can be used to immediately change the SELinux state of a machine?

( ) a. selinux

( ) b. setstate

( ) c. setenforce

( ) d. chcon

( ) e.None of the above

rha130-5.0-0-en-2007-12-13T13:35:30-0500Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any other use is a violationof U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrievalsystem, or otherwise duplicated whether in electronic or printformat without prior written consent of Red Hat, Inc. If you b elieve Red Hat course materials are being used, copied, or otherwise improperly distributed please [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919) 754 3700.

96

Page 97: Rha130 Workbook 03 Student 5.0 0 Linux File System Management

Chapter 7. SELinux: Secure Linux

7. Which of the following commands would view the SELinux domain of the process with process ID 3452?

( ) a.selinux 3452

( ) b. ps -Z 3452

( ) c.getenforce -p 3452

( ) d. lscon -p 3452

( ) e.None of the above

8. Which of the following command would display the SELinux security context of the file/etc/passwd?

( ) a.ls -Z /etc/passwd

( ) b. selinux /etc/passwd

( ) c.getenforce /etc/passwd

( ) d. lscon /etc/passwd

( ) e.None of the above

9. What file would you examine in order to see logs of SELinux violations?

( ) a./var/log/selinux

( ) b. /var/log/messages

( ) c./var/log/secure

( ) d. /var/log/dmesg

( ) e.None of the above

10.Which of the following commands would cause the filefoo to inherit the SELinux security context of the filebam?

( ) a.chcon --reference=bam foo

( ) b. chcon --reference=foo bam

( ) c.chcon -R bam foo

( ) d. chcon -R foo bam

( ) e.Both A and C

rha130-5.0-0-en-2007-12-13T13:35:30-0500

Copyright (c) 2003-2007 Red Hat, Inc. All rights reserved. For use only by a student enrolled in a Red Hat Academy course taught at a Red Hat Academy. Any otheruse is a violation of U.S. and international copyrights. No part of this publication may be photocopied, duplicated, stored in a retrieval system, or otherwiseduplicated whether in electronic or print format without pr ior written consent of Red Hat, Inc. If you believe Red Hat course materials are being used, copied, orotherwise improperly distributed please email [email protected] or phone toll-free (USA) +1 866 626 2994 or +1 (919)754 3700.

97