FreeBSD Operating System

File systems and devices

Разбить на страницы
Показывать лекцию целиком

One of the most revolutionary concepts of the UNIX operating system was its file system the way in which it stores data. Although most other operating systems have copied it since then, including Microsoft's platforms, none have come close to the elegance with which it is implemented. Many aspects of the file system are not immediately obvious, some of them not even to seasoned UNIX users.

We've already looked at file naming conventions on page 125. In the next section, we'll look at the file system access, structure and hierarchy, and on page 195 we'll look at how the file system treats hardware devices as files.

File permissions

A UNIX system may potentially be used by many people, so UNIX includes a method of protecting data from access by unauthorized persons. Every file has three items of information associated with it that describe who can access it in what manner:

  • The file owner the user ID of the person who owns the file.
  • The file group the group ID of the group that "owns" the file.
  • A list of what the owner, the group and other people can do with the file. The possible actions are reading, writing or executing.
  • For example, you might have a program that accesses private data, and you want to be sure that only you can execute it. You do this by setting the permissions so that only the owner can execute it. Or you might have a text document in development, and you want to be sure that you are the only person who can change it. On the other hand, the people who work with you have a need to be able to refer to the document. You set the permissions so that only the owner can write it, that the owner and group can read it, and, because it's not ready for publication yet, you don't allow anybody else to access it.

    Traditionally, the permissions are represented by three groups of rwx: r stands for read permission, w stands for write permission, and x stands for execute permission. The three groups represent the permissions for the owner, the group and others respectively. If the permission is not granted, it is represented by a hyphen (-). Thus, the permissions for the program I discussed above would be r-x------ (I can read and execute the program, and nobody else can do anything with it). The permissions for the draft document would be rw-r----- (I can read and write, the group can read, and others can't access it).

    Typical FreeBSD file access permissions are rwxr-xr-x for programs and rw-r--r-- for other systcode files. In some cases, however, you'll find that other permissions are required. For example, the file ~/.rhosts, which is used by some network programs for user validation, may contain the user's password in legible form. To help ensure that other people don't read it, the network programs refuse to read it unless its permissions are rw-------. The vast majority of system problems in UNIX can be traced to in correct permissions, so you should pay particular attention to them.

    Apart from these access permissions, executable can also have two bits set to specify the access permissions of the process when it is run. If the setuid (set user ID) bit is set, the process always runs as if it had been started by its owner. If the setgid (set group ID) bit is set, it runs as if it had been started by its group. This is frequently used to start system programs that need to access resources that the user may not access directly. We'll see an example of this with the ps command on page 185. ls represents the setuid bit by setting the third letter of the permissions string to s instead of x; similarly, It represents the setgid bit by setting the sixth letter of the permissions string to s instead of x.

    In addition to this access information, the permissions contain a character that describes what kind of file it represents. The first letter may be a - (hyphen), which designates a regular file, the letter d for directory, or the letters b or c for a device node. We'll look at device nodes in Chapter 11. There are also a number of other letters that are less used. See the man page ls(1) for a full list.

    To list files and show the permissions, use the ls command with the -l option:

    $ ls -l
    total 2429
    -rw-rw-r--  1 grog    wheel    28204 Jan  4 14:17 %backup%?
    drwxrwxr-x  3 grog    wheel      512 Oct 11 15:26 2.1.0-951005-SNAP
    drwx------  4 grog    wheel      512 Nov 25 17:23 Mail
    -rw-rw-r--  1 grog    wheel      149 Dec  4 14:18 Makefile
    -rw-rw-r--  1 grog    wheel      108 Dec  4 12:36 Makefile.bak
    -rw-rw-r--  1 grog    wheel      108 Dec  4 12:36 Makefile?
    -rw-rw-r--  1 grog    wheel        0 Dec  4 12:36 depend
    -rw-rw-r--  1 daemon  wheel  1474560 Dec 14 17:03 deppert.floppy
    -rwxr-xr-x  1 grog    wheel      100 Dec 19 15:24 doio
    -rwxrwxr-x  1 grog    wheel      204 Dec 19 15:25 doiovm
    -rwxrwxr-x  1 grog    wheel      204 Dec 19 15:16 doiovm~
    -rwxr-xr-x  1 grog    wheel      115 Dec 26 08:42 dovm
    -rwxr-xr-x  1 grog    wheel      114 Dec 19 15:30 dovm~
    drwxr-xr-x  2 grog    wheel      512 Oct 16  1994 emacs
    drwxrwxrwx  2 grog    wheel      512 Jan  3 14:07 letters
    

    This format shows the following information:

  • First, the permissions, which we've already discussed.
  • Then, the link count. This is the number of hard links to the file. For a regular file, this is normally 1, but directories have at least 2. We look at links on page 186.
  • Next come the names of the owner and the group, and the size of the file in bytes. You'll notice that the file deppert.floppy belongs to daemon This was probably an accident, and it could lead to problems. Incidentally, looking at the name of the file and its size, it's fairly obvious that this is an image of a 3,5" floppy, that is to say, a literal copy of the data on the complete floppy.
  • The date is normally the date that the file was last modified. With the -u, option to ls you can list the last time the file was accessed.
  • Finally comes the name of the file. As you can see from this example, the names can be quite varied.
  • A couple of the permissions are of interest. The directories all have the x (execute) permission bit set. This enables accessing (i.e. opening) files in the directory—that's the way the term execute is defined for a directory. If l reset the execute permission, I can still list the names of the files, but I can't access them.

    I am the only person who can access the directory Mail This is the normal permission for a mail directory.

    Changing file permissions and owners

    Often enough, you may want to change file permissions or owners. UNIX supplies three programs to do this:

  • To change the file owner, use chown. For example, to change the ownership of the file deppert.floppy, which in the list above belongs to dacodeon, root would enter:
    # chown grog deppert.floppy
    

    Note that only root may perform this operation.

  • To change the file group, use chgrp, which works in the same way as chown. To change the group ownership to lemis, you would enter:
    # chgrp lemis deppert.floppy
    

    chown can also change both the owner and the group. Instead of the two previous examples, you could enter:

    # chown grog:lemis deppert.floppy
    

    This changes the owner to grog, as before, and also changes the group to lemis

  • To change the permissions, use the chmod program. chmod has a number of different formats, but unfortunately the nine-character representation isn't one of the code. Read the man page chmod(1) for the full story, but you can achieve just about anything you want with one of the formats shown in table 10-1
  • chmod permission codes
    SpecificationEffect
    go-wDeny write permission to group and others
    =rw,+XSet the read and write permissions to the usual defaults, but retain any execute permissions that are currently set
    +XMake a directory or file searchable/executable by everyone if it is already searchable/executable by anyone
    u=rwx,go=rxMake a file readable/executable by everyone and writable by the owner only
    go=Clear all mode bits for group and others
    g=u-wSet the group bits equal to the user bits, but clear the group write bit

    Permissions for new files

    None of this tells us what the permissions for new files are going to be. The wrong choice could be disastrous. For example, if files were automatically created with the permissions rwxrwxrwx anybody could access thcode in any way. On the other hand, creating thcode with r-------- could result in a lot of work setting thcode to what you really want them to be. UNIX solves this problem with a thing called umask (User mask) This is a default non-permission: it specifies which permission bits not to allow.

    As if this weren't confusing enough, it's specified in the octal number system, in which the valid digits are 0 to 7. Each octal digit represents 3 bits. By contrast, the more common hexadecimal system uses 16 digits, 0 to 9 and a to f .The original versions of UNIX ran on machines that used the octal number system, and since the permissions come in threes, it made sense to leave the umask value in octal.

    An example: by default, you want to create files that anybody can read, but only you can write. You set the mask to 022. This corresponds to the binary bit pattern 000010010

    The leading 0 is needed to specify that the number is in octal, not to make up three digits. If you want to set the permissions so that by default nobody can read, you'd set it to 0222. Some shells automatically assume that the number is octal, so you may be able to omit the 0, but it's not good practice.

    The permissions are allowed where the corresponding bit is 0:

    rwxrwxrwx     Possible permissions 
    000010010     umask
    rwxr-xr-x     resultant permissions
    

    By default, files are created without the x bits, whereas directories are created with the allowed x bits, so with this umask a file would be created with the permissions rw-r--r--

    umask is a shell command. To set it, just enter:

    $ umask 022
    

    It's preferable to set this in your shell initialization file—see page 135 for further details.

    Beware of creating a too restrictive umask. For example, you will get into a lot of trouble with a umask like 377, which creates files that you can only read, and that nobody else can access at all. If you disallow the x (executable) bit, you will not be able to access directories you create, and you won't be able to run programs you compile.

    Making a program executable

    File permissions enable one problem that occurs so often that it's worth drawing attention to it. Many operating systems require that an executable program have a special naming convention, such as COMMAND.COM or FOO.BAT which in MS-DOS denotes a specific kind of binary executable and a script file, respectively. In UNIX, executable programs don't need a special suffix, but they must have the x bit set. Sometimes this bit gets reset (turned off), for example if you copy it across the Net with ftp. The result looks like this:

    $ ps
    bash: ps: Permission denied $ ls -l /bin/ps
    -r--r--r--  1 bin  kmem  163840 May 6 06:02 /bin/ps
    $ su                             you need to be super user to set ps permission
    Password:                        password doesn't echo
    # chmod +x /bin/ps               make it executable
    # ps                             now it works
    PID  TT     TIME  COMMAND
    226  p2  0:00.56  su (bash)
    239  p2  0:00.02  ps
    146  v1  0:00.06  /usr/libexec/getty Pc ttyv1
    147  v2  0:00.05  /usr/libexec/getty Pc ttyv2
    # ^D                             exit su
    $ ps
    ps: /dev/mem: Permission denied  hey! it’s stopped working
    

    Huh? It only worked under su and stopped working when I became a mere mortal again? What's going on here?

    There's a second problem with programs like ps: some versions need to be able to access special files, in this case /dev/mem, a special file that addresses the system memory. To do this, we need to set the setgid bit, s, which requires becoming super user again:

    $ su                  you need to be super user to set ps permission
    Password:             password doesn't echo
    # chmod g+s /bin/ps   set the setgid bit
    # ls -l /bin/ps       see what it looks like
    -r-xr-sr-x  1 bin  kmem  163840 May   6 06:02 /bin/ps
    # ^D                  exit su
    $ ps                  now it still works
    PID  TT  STAT     TIME  COMMAND
    226  p2  S     0:00.56  su (bash)
    239  p2  R+    0:00.02  ps
    146  v1  Is+   0:00.06  /usr/libexec/getty Pc ttyv1
    147  v2  Is+   0:00.05  /usr/libexec/getty Pc ttyv2
    

    In this example, the permissions in the final result really are the correct permissions for ps. It's impossible to go through the permissions for every standard program. If you suspect that you have the permissions set in correctly, use the permissions of the files on the Live File system CD-ROM as a guideline.

    setuid and setgid programs can be a security issue. What happens if the program called ps is really something else, a Trojan Horse? We set the permissions to allow it to break into the system. As a result, FreeBSD has found an alternative method for ps to do its work, and it no longer needs to be set setgid.

    Mandatory Access Control

    For some purposes, traditional UNIX permissions are insufficient. Release 5.0 of FreeBSD introduces Mandatory Access Control, or MAC, which permits loadable kernel modules to augment the system security policy. MAC is intended as a toolkit for developing local and vendor security extensions, and it includes a number of sample policy modules, including Multi-Level Security (MLS) with compartments, and a number of augmented UNIX security models including a file system firewall. At the time of writing it is still considered experimental software, so this book doesn't discuss it further. See the man pages for more details.

    Links

    In UNIX, files are defined by inodes structures on disk that you can't access directly. They contain the meta data, all the information about the file, such as owner, permissions and timestamps. What they don't contain are the things you think of as making up a file: they don't have any data, and they don't have names. Instead, the inode contains information about where the data blocks are located on the disk. It doesn't know anything about the name: that's the job of the directories.

    A directory is simply a special kind of file that contains a list of names and inode numbers: in other words, they assign a name to an Inode, and thus to a file. More than one name can point to the same inode, so files can have more than one name. This connection between a name and an inode is called a link sometimes confusingly hard link. The inode numbers relate to the file system, so files must be in the same file system as the directory that refers to them.

    Directory entries are independent of each other: each points to the Inode, so they're completely equivalent. The inode contains a link count that keeps track of how many directory entries point to it: when you remove the last entry, the system deletes the file data and metadata.

    Alternatively, symbolic links sometimes called soft links, are not restricted to the same file system (not even to the same system!), and they refer to another file name, not to the file itself. The difference is most evident if you delete a file: if the file has been hard linked, the other names still exist and you can access the file by them. If you delete a file name that has a symbolic link pointing to it, the file goes away and the symbolic link can't find it anymore.

    It's not easy to decide which kind of link to use—see UNIX Power Tools (O'Reilly) for more details.

    Directory hierarchy

    Although Microsoft platforms have a hierarchical directory structure, there is little standardization of the directory names: it's difficult to know where a particular program or data file might be. UNIX systems have a standard directory hierarchy, though every vendor loves to change it just a little bit to ensure that they're not absolutely compatible. In the course of its evolution, UNIX has changed its directory hierarchy several times. It's still better than the situation in the Microsoft world. The most recent, and probably most far-reaching changes, occurred over ten years ago with System V.4 and 4.4BSD, both of which made almost identical changes.

    Nearly every version of UNIX prefers to have at least two file systems, / (the root file system) and /usr even if they only have a single disk. This arrangement is considered more reliable than a single file system: it's possible for a file system to crash so badly that it can't be mounted anymore, and you need to read in a tape backup, or use programs like fsck or fsdb to piece them together. We have already discussed this issue on page 68, where I recommend having /usr on the same file system as /.

    Standard directories

    The physical layout of the file systems does not affect the names or contents of the directories, which are standardized. Table 10-2 gives an over view of the standard FreeBSD directories; see the man page hier(7) for more details.

    FreeBSD directory hierarchy
    Directory nameUsage
    /Root file system. Contains a couple of system directories and mount points for other file systems. It should not contain anything else.
    /binExecutable programs of general use needed at system startup time. The name was originally an abbreviation for binary,but many of the files in here are shell scripts.
    /bootFiles used when booting the system, including the kernel and its associated klds.
    /cdromAmount point for CD-ROM drives.
    /compatA link to /usr/compat: see below.
    /devDirectory of device nodes. The name is an abbreviation for devices. From FreeBSD 5.0 onward, this is normally a mount point for the device file system, devfs. We'll look at the contents of this directory in more detail on page 195.
    /etcConfiguration files used at system startup. Unlike System V, /etc does not contain kernel build files, which are not needed at system startup. Unlike earlier UNIX versions, it also does not contain executable—they have been moved to /sbin.
    /homeBy convention, put user files here. Despite the name, /usr is for system files.
    /mntA mount point for floppies and other temporary file systems.
    /procThe process file system. This directory contains pseudo-files that refer to the virtual memory of currently active processes.
    /rootThe home directory of the user root. In traditional UNIX file systems, root's home directory was /, but this is messy.
    /sbinSystem executable needed at system startup time. These are typically system administration files that used to be stored in /etc.
    /sysIf present, this is usually a symbolic link to /usr/src/sys, the kernel sources. This is a tradition derived from 4.3BSD.
    /tmpA place for temporary files. This directory is an anachronism: normally it is on the root file system, though it is possible to mount it as a separate file system or make it a symbolic link to /var/tmp. It is maintained mainly for programs that expect to find it.
    /usrThe "second file system." See the discussion above.
    /usr/XllR6The X WindowSystem.
    /usr/XllR6/binExecutable X11 programs.
    /usr/XllR6/includeHeader files for X11 programming.
    /usr/XllR6/libLibrary files for X11.
    /usr/XllR6/manMan pages for X11.
    /usr/binStandard executable programs that are not needed at system start. Most standard programs you use are stored here.
    /usr/compatA directory containing code for emulated systems, such as Linux.
    /usr/gamesGames.
    /usr/includeHeader files for programmers.
    /usr/libLibrary files. FreeBSD does not have a directory /lib.
    /usr/libexecExecutable files that are not started directly by the user, for example the phases of the C compiler (which are started by /usr/bin/gcc)or the getty program, which is started by init.
    /usr/libdataMiscellaneous files used by system utilities.
    /usr/localAdditional programs that are not part of the operating system. It parallels the /usr directory in having subdirectories bin, include, lib, man, sbin, and share. This is where you can put programs that you get from other sources.
    /usr/objObject files created when building the system. See Chapter 33 .
    /usr/portsThe Ports Collection.
    /usr/sbinSystem administration programs that are not needed at system startup.
    /usr/shareMiscellaneous read-only files, mainly informative. Subdirectories include doc, the FreeBSD documentation, games, info, the GNU info documentation, locale, internationization information, and man, the man pages.
    /usr/srcSystem source files.
    /varA file system for data that changes frequently, such as mail, news, and log files. If /var is not a separate file system, you should create a directory on another file system and symlink /var to it.
    /var/logDirectory with system log files
    /var/mailIncoming mail for users on this system
    /var/spoolTransient data, such as outgoing mail, print data and anonymous ftp.
    /var/tmpTemporary files.

    File system types

    FreeBSD supports a number of file system types. The most important are:

  • UFS is the UNIX File SystemParadoxically, although BSD may not be called UNIX, its file system is called the UNIX File System. The UNIX System Group, the developers of UNIX System V.4, adopted UFS as the standard file system for System V and gav e it this name. Previously it was called the Berkeley Fast File System, or ffs. All native disk file systems are of this type. Since FreeBSD 5.0, you have a choice of two different versions, UFS 1 and UFS2. As the names suggest, UFS 2 is a successor to UFS 1. Unlike UFS 1, UFS 2 file systems are not limited to 1 TB (1024 GB) in size. UFS 2 is relatively new, so unless you require very large file systems, you should stick to UFS 1.
  • cd9660 is the ISO 9660 CD-ROM format with the so-called Rock Ridge Extensions that enable UNIX-like file names to be used. Use this file system type for all CD-ROMs, even if they don't have the Rock Ridge Extensions.
  • nfs is the Network File System a means of sharing file systems across a network. We'll look at it in Chapter 25.
  • FreeBSD supports a number of file systems from other popular operating systems. You mount the file systems with the mount command and the -t option to specify the file system type. For example:
    # mount -t ext2fs /dev/dalsl /linux    mount a Linux ext2 file system
    # mount -t msdos /dev/da2s1 /C:        mount a Microsoft FAT file system
    

    Here’s a list of currently supported file systems:

  • File system support
    File systemmount option
    CD-ROMcd9660
    DVDudf
    Linux ext2ext2fs
    Microsoft MS-DOSmsdosfs
    Microsoft NTntfs
    Novell Netwarenwfs
    Microsoft CIFSsmbfs

    Soft updates

    Soft updates change the way the file system performs I/O. They enable metadata to be written less frequently. This can give rise to dramatic performance improvements under certain circumstances, such as file deletion. Specify soft updates with the –U option when creating the file system. For example:

    # newfs -U /dev/da1s2h
    

    If you forget this fag, you can enable them later with tunefs :

    # tunefs -n enable /dev/da1s2h
    

    You can't perform this operation on a mounted file system.

    Snapshots

    One of the problems with backing up file systems is that you don't get a consistent view of the file system: while you copy a file, other programs may be modifying it, so what you get on the tape is not an accurate view of the file at any time. Snapshots are a method to create a unified view of a file system. They maintain a relatively small file in the file system itself containing information on what has changed since the snapshot was taken. When you access the snapshot, you get this data rather than the current data for the parts of the disk which have changed, so you get a view of the file system as it was at the time of the snapshot.

    Creating snapshots

    You create snapshots with the mount command and the -o snapshot option. For example, you could enter

    # mount -u -o snapshot /var/snapshot/snapl /var
    

    This command creates a snapshot of the /var file system called /var/snapshot/snapl. Snapshot files have some interesting properties:

  • You can have multiple snapshots on a file system, up to the current limit of 20.
  • Snapshots have the schg fag set, which prevents anybody writing to them.
  • Despite the schg fag, you can still remove them.
  • They are automatically updated when anything is written to the file system. The view of the file system doesn't change , but this update is necessary in order to maintain the "old" view of the file system.
  • They look like normal file systems. You can mount them with the md driver. We'll look at that on page 193.
  • Probably the most useful thing you can do with a snapshot is to take a backup of it. We'll look at backups on page 253.

    At the time of writing, snapshots are still under development. It's possible that you might still have trouble with them, in particular with deadlocks that can only be cleared by rebooting.

    It takes about 30 seconds to create a snapshot of an 8 GB file system. During the last five seconds, file system activity is suspended. If there's a lot of soft update activity going on in the file system (for example, when deleting a lot of files), this suspension time can become much longer, up to several minutes. To remove the same snapshot takes about two minutes, but it doesn't suspend file system activity at all.

    Mounting file systems

    Microsoft platforms identify partitions by letters that are assigned at boot time. There is no obvious relation between the partitions, and you have little control over the way the system assigns them. By contrast, all UNIX partitions have a specific relation to the root file system, which is called simply /.This flexibility has one problem: you have the choice of where in the overall file system structure you put your individual file systems. You specify the location with the mount command. For example, you would typically mount a CD-ROM in the directory /cdrom, but if you have three CD-ROM drives attached to your SCSI controller, you might prefer to mount them in the directories /cd0, /cd1, and /cd2. To mount a file system, you need to specify the device to be mounted, where it is to be mounted, and the type of file system (unless it is ufs). The mount point (the directory where it is to be mounted) must already exist. To mount your second CD-ROM on /cd1, you enter:

    # mkdir /cdl                    only if it doesn't exist
    # mount -t cd9660 -o ro /dev/cdla /cdl
    

    When the system boots, it calls the startup script /etc/rc, which among other things automatically mounts the file systems. All you need to do is to supply the information: what is to be mounted, and where? This is in the file /etc/fstab. If you come from a System V environment, you'll notice significant difference in format—see the man page fstab(5), for the full story. A typical /etc/fstab might look like:

    /dev/ad0s1a           /                   ufs        rw         1 1  root file system
    /dev/ad0s1b           none                swap       sw         0 0  swap
    /dev/ad0s1e           /usr                ufs        rw         2 2  /usr file system
    /dev/dalsle           /src                ufs        rw         2 2  additional file system
    /dev/da2s1            /linux              ext2fs     rw         2 2  Linux file system
    /dev/adlsl            /C:                 msdos      rw         2 2  Microsoft file system
    proc                  /proc               procfs     rw         0 0  proc pseudo-file system
    linproc               /compat/linux/proc  linprocfs  rw         0 0  
    /dev/cd0a             /cdrom              cd9660     ro         0 0  CD-ROM
    presto:/              /presto/root        nfs        rw         0 0  NFS file systems on other systems
    presto:/usr           /presto/usr         nfs        rw         0 0  
    presto:/home          /presto/home        nfs        rw         0 0  
    presto:/S             /S                  nfs        rw         0 0  
    //guestasamba/public  /smb                smbfs      rw,noauto  0 0  SMB file system
    

    The format of the file is reasonably straight forward:

  • The first column gives the name of the device (if it's a real file system), a keyword for some file systems, like proc or the name of the remote file system for NFS mounts.
  • The second column specifies the mount point. Swap partitions don't have amount point, so the mount point for the swap partition is specified as none.
  • The third column specifies the type of file system. Local file systems on hard disk are always ufs and file systems on CD-ROM are cd9660. Remote file systems are always nfs. Specify swap partitions with swap, and the proc file system with proc
  • The fourth column contains rw for file systems that can be read or written, ro for file systems (like CD-ROM) that can only be read, and sw for swap partitions. It can also contain options like the noauto in the bottom line, which tells the system startup scripts to ignore the line. It's there so that you can use the shorthand notation mount /smb when you want to mount the file system.
  • The fifth and sixth columns are used by the dump and fsck programs. You won't normally need to change them. Enter 1 for a root file system, 2 for other UFS file systems, and 0 for everything else.
  • Mounting files as file systems

    So far, our files have all been on devices, also called special files. Sometimes, though, you may want to access the contents of a file as a file system:

  • It's sometimes of interest to access the contents of a snapshot, for example to check the contents.
  • After creating an ISO image to burn on CD-R, you should check that it's valid.
  • Also, after downloading an ISO image from the Net, you may just want to access the contents, and not create a CD-R at all.
  • In each case, the solution is the same: you mount the files as a vnode device with the md driver.

    The md driver creates a number of different kinds of pseudo-device. See the man page md(4).. We use the vnode device, a special file that refers to file system files. Support for md is included in the GENERIC kernel, but if you've built a kernel without the md drive, you can load it as a kld. If you're not sure, try loading the kld anyway.

    In the following example, we associate a vnode device with the ISO image iso-image using the program mdconfig:

    # kldload md                          load the kld module if necessary
    kldload: can't load md: File exists   already loaded or in the kernel
    # mdconfig -a -t vnode -f iso -image  and configure the device
    md0                                   this is the name assigned in directory /dev
    # mount -t cd9660 /dev/md0 /mnt       then mount it
    

    After this, you can access the image at /mnt as a normal file system. You specify -t cd9660 in this case because the file system on the image is a CD9660 file system. You don't specify this if you're mounting a UFS file system, for example a snapshot image.

    Older versions of FreeBSD used the vn driver, which used different syntax. Linux uses loop mounts, which FreeBSD doesn't support.

    Unmounting file systems

    When you mount a file system, the system assumes it is going to stay there, and in the interests of efficiency it delays writing data back to the file system. This is also the reason why you can't just turn the power off when you shut down the system. If you want to stop using a file system, you must tell the system about it so that it can flush any remaining data. You do this with the umount command. Note the spelling of this command—there's no n in the command name.

    You need to do this even with read-only media such as CD-ROMs: the system assumes it can access the data from a mounted file system, and it gets quite unhappy if it can't. Where possible, it locks removable media so that you can't remove them from the device until you unmount them.

    Using umount is straightforward: just tell it what to unmount, either the device name or the directory name. For example, to unmount the CD-ROM we mounted in the example above, you could enter one of these commands:

    # umount /dev/cdla
    # umount /cdl
    

    Before unmounting a file system, umount checks that nobody is using it. If somebody is using it, it refuses to unmount it with a message like umount: /cdl: Device busy. This message often occurs because you have changed your directory to a directory on the file system you want to remove. For example (which also shows the usefulness of having directory names in the prompt):

    === root@freebie (/dev/ttyp2)  /cdl 16 -> umount /cdl
    umount: /cd1: Device busy
    === root@freebie (/dev/ttyp2)  /cd1 17 -> cd
    === root@freebie (/dev/ttyp2)  ~ 18 -> umount /cdl
    === root@freebie (/dev/ttyp2)  ~ 19 ->
    

    After unmounting a vnode file system, don't forget to unconfigure the file:

    # umount /mnt
    # mdconfig -d -u 0
    

    The parameter 0 refers to md device 0, in other words /dev/md0.

    FreeBSD devices

    UNIX refers to devices in the same manner as it refers to normal files. By contrast to normal ("regular") files, they are called special files. They're not really files at all: they're information about device support in the kernel, and the term device node is more accurate. Conventionally, they are stored in the directory /dev. Some devices don't have device nodes, for example Ethernet interfaces: they are treated differently by the ifconfig program.

    Traditional UNIX systems distinguish two types of device, blockdevices and character devices. FreeBSD no longer has block devices; we discussed the reasons for this on page 36.

    In traditional UNIX systems, including FreeBSD up to Release 4, it was necessary to create device nodes manually. This caused a number of problems when they didn't match what was in the system. Release 5 of FreeBSD has solved this problem with the device file system, also known as devfs. devfs is a pseudo-file system that dynamically creates device nodes for exactly those devices that are in the kernel, which makes it unnecessary to manually create devices.

    Overview of FreeBSD devices

    Every UNIX system has its own peculiarities when it comes to device names and usage. Even if you're used to UNIX, you'll find the following table useful.

    FreeBSD device names
    acd0First ata (IDE) CD-ROM drive.
    ad0First ata (IDE or similar) disk drive. See Chapter 2, page 38, for a complete list of disk drive names.
    bpf0Berkeley packet filter.
    cd0First SCSI CD-ROM drive.
    ch0SCSI CD-ROM changer (juke box)
    consoleSystem console, the device that receives console messages. Initially it is /dev/ttyv0, but it can be changed.
    cuaa0First serial port in callout mode.
    cuaia0First serial port in callout mode, initial state. Note the letter i for initial.
    cuala0First serial port in callout mode, lock state. Note the letter l for lock.
    da0First SCSI disk drive. See Chapter 2, page 38, for a complete list of disk drive names.
    esa0First SCSI tape drive, eject on close mode.
    fdFile descriptor pseudo-devices: a directory containing pseudo-devices that, when opened, return a duplicate of the file descriptor with the same number. For example, if you open /dev/fd/0, you get another handle on your stdin stream (file descriptor 0).
    fd0The first floppy disk drive, accessed as a file system.
    kmemKernel virtual memory pseudo-device.
    lpt0First parallel printer.
    memPhysical virtual memory pseudo-device.
    nsa0First SCSI tape drive, no-rewind mode.
    nullThe "bit bucket." Send data to this device if you never want to see it again.
    psm0PS/2 mouse.
    ptyp0First master pseudo-terminal. Master pseudo-terminals are named /dev/ptyp0 through /dev/ptypv, /dev/ptyq0 through /dev/ptyqv, /dev/ptyr0 through /dev/ptyrv, /dev/ptys0 through /dev/ptysv, /dev/ptyP0 through /dev/ptyPv, /dev/ptyQ0 through /dev/ptyQv, /dev/ptyR0 through /dev/ptyRv and /dev/ptyS0 through /dev/ptySv.
    randomRandom number generator.
    sa0First SCSI tape drive, rewind on close mode.
    sysmouseSystem mouse, controlled by moused. We’ll look at this again on page 519.
    ttyCurrent controlling terminal.
    ttyd0First serial port in callin mode.
    ttyid0First serial port in callin mode, initial state.
    ttyld0First serial port in callin mode, lock state.
    ttyp0First slave pseudo-terminal. Slave pseudo-terminals are named /dev/ttyp0 through /dev/ttypv, /dev/ttyq0 through /dev/ttyqv, /dev/ttyr0 through /dev/ttyrv, /dev/ttys0 through /dev/ttysv, /dev/ttyP0 through /dev/ttyPv, /dev/ttyQ0 through /dev/ttyQv, /dev/ttyR0 through /dev/ttyRv and /dev/ttyS0 through /dev/ttySv. Some processes, such as xterm, only look at /dev/ttyp0 through /dev/ttysv.
    ttyv0First virtual tty. This is the display with which the system starts. Up to 10 virtual ttys can be activated by adding the appropriate getty information in the file /etc/ttys. See Chapter 19 , page 338, for further details.
    ugen0First generic USB device.
    ukbd0First USB keyboard.
    ulpt0First USB printer.
    umass0First USB mass storage device.
    ums0First USB mouse.
    uscanner0First USB scanner.
    vinumDirectory for Vinum device nodes. See Chapter 12 , for further details.
    zeroDummy device that always returns the value (binary) 0 when read.

    You'll note a number of different modes associated with the serial ports. We'll look at them again in Chapter 19 .

    Virtual terminals

    As we have seen, UNIX is a multitasking operating system, but a PC generally only has one screen. FreeBSD solves this problem with virtual terminals. When in text mode, you can change between up to 16 different screens with the combination of the Alt key and a function key. The devices are named /dev/ttyv0 through /dev/ttyv15 and correspond to the keystrokes Alt-Fl through Alt-F16. By default, three virtual terminals are active: /dev/ttyv0 through /dev/ttyv2. The system console is the virtual terminal /dev/ttyv0 and that's what you see when you boot the machine. To activate additional virtual terminals, edit the file /etc/ttys. There you find:

    ttyvO  "/usr/libexec/getty Pc"  cons25  on secure
    ttyvl  "/usr/libexec/getty Pc"  cons25  on secure
    ttyv2  "/usr/libexec/getty Pc"  cons25  on secure
    ttyv3  "/usr/libexec/getty Pc"  cons25  off secure
    

    The key words on and off refer to the state of the terminal: to enable one, set its state to on. To enable extra virtual terminals, add a line with the corresponding terminal name, in the range /dev/ttyv4 to /dev/ttyv15. After you have edited /etc/ttys, you need to tell the system to re-read it in order to start the terminals. Do this as root with this command:

    # kill -1 1
    

    Process 1 is init —see page 528 for more details.

    Pseudo-terminals

    In addition to virtual terminals, FreeBSD offers an additional class of terminals called pseudo-terminals. They come in pairs: a master device also called a pry (pronounced pity) is used only by processes that use the interface, and has a name like /dev/ptyp0. The slave device looks like a terminal, and has a name like /dev/ttyp0. Any process can open it without any special knowledge of the interface. These terminals are used for network connections such as xterm, telnet and rlogin. You don't need a getty for pseudo-terminals. Since FreeBSD Release 5.0, pseudo-terminals are created as required.

    Страницы:

    One of the most revolutionary concepts of the UNIX operating system was its file system the way in which it stores data. Although most other operating systems have copied it since then, including Microsoft's platforms, none have come close to the elegance with which it is implemented. Many aspects of the file system are not immediately obvious, some of them not even to seasoned UNIX users.

    We've already looked at file naming conventions on page 125. In the next section, we'll look at the file system access, structure and hierarchy, and on page 195 we'll look at how the file system treats hardware devices as files.

    File permissions

    A UNIX system may potentially be used by many people, so UNIX includes a method of protecting data from access by unauthorized persons. Every file has three items of information associated with it that describe who can access it in what manner:

  • The file owner the user ID of the person who owns the file.
  • The file group the group ID of the group that "owns" the file.
  • A list of what the owner, the group and other people can do with the file. The possible actions are reading, writing or executing.
  • For example, you might have a program that accesses private data, and you want to be sure that only you can execute it. You do this by setting the permissions so that only the owner can execute it. Or you might have a text document in development, and you want to be sure that you are the only person who can change it. On the other hand, the people who work with you have a need to be able to refer to the document. You set the permissions so that only the owner can write it, that the owner and group can read it, and, because it's not ready for publication yet, you don't allow anybody else to access it.

    Traditionally, the permissions are represented by three groups of rwx: r stands for read permission, w stands for write permission, and x stands for execute permission. The three groups represent the permissions for the owner, the group and others respectively. If the permission is not granted, it is represented by a hyphen (-). Thus, the permissions for the program I discussed above would be r-x------ (I can read and execute the program, and nobody else can do anything with it). The permissions for the draft document would be rw-r----- (I can read and write, the group can read, and others can't access it).

    Typical FreeBSD file access permissions are rwxr-xr-x for programs and rw-r--r-- for other systcode files. In some cases, however, you'll find that other permissions are required. For example, the file ~/.rhosts, which is used by some network programs for user validation, may contain the user's password in legible form. To help ensure that other people don't read it, the network programs refuse to read it unless its permissions are rw-------. The vast majority of system problems in UNIX can be traced to in correct permissions, so you should pay particular attention to them.

    Apart from these access permissions, executable can also have two bits set to specify the access permissions of the process when it is run. If the setuid (set user ID) bit is set, the process always runs as if it had been started by its owner. If the setgid (set group ID) bit is set, it runs as if it had been started by its group. This is frequently used to start system programs that need to access resources that the user may not access directly. We'll see an example of this with the ps command on page 185. ls represents the setuid bit by setting the third letter of the permissions string to s instead of x; similarly, It represents the setgid bit by setting the sixth letter of the permissions string to s instead of x.

    In addition to this access information, the permissions contain a character that describes what kind of file it represents. The first letter may be a - (hyphen), which designates a regular file, the letter d for directory, or the letters b or c for a device node. We'll look at device nodes in Chapter 11. There are also a number of other letters that are less used. See the man page ls(1) for a full list.

    To list files and show the permissions, use the ls command with the -l option:

    $ ls -l
    total 2429
    -rw-rw-r--  1 grog    wheel    28204 Jan  4 14:17 %backup%?
    drwxrwxr-x  3 grog    wheel      512 Oct 11 15:26 2.1.0-951005-SNAP
    drwx------  4 grog    wheel      512 Nov 25 17:23 Mail
    -rw-rw-r--  1 grog    wheel      149 Dec  4 14:18 Makefile
    -rw-rw-r--  1 grog    wheel      108 Dec  4 12:36 Makefile.bak
    -rw-rw-r--  1 grog    wheel      108 Dec  4 12:36 Makefile?
    -rw-rw-r--  1 grog    wheel        0 Dec  4 12:36 depend
    -rw-rw-r--  1 daemon  wheel  1474560 Dec 14 17:03 deppert.floppy
    -rwxr-xr-x  1 grog    wheel      100 Dec 19 15:24 doio
    -rwxrwxr-x  1 grog    wheel      204 Dec 19 15:25 doiovm
    -rwxrwxr-x  1 grog    wheel      204 Dec 19 15:16 doiovm~
    -rwxr-xr-x  1 grog    wheel      115 Dec 26 08:42 dovm
    -rwxr-xr-x  1 grog    wheel      114 Dec 19 15:30 dovm~
    drwxr-xr-x  2 grog    wheel      512 Oct 16  1994 emacs
    drwxrwxrwx  2 grog    wheel      512 Jan  3 14:07 letters
    

    This format shows the following information:

  • First, the permissions, which we've already discussed.
  • Then, the link count. This is the number of hard links to the file. For a regular file, this is normally 1, but directories have at least 2. We look at links on page 186.
  • Next come the names of the owner and the group, and the size of the file in bytes. You'll notice that the file deppert.floppy belongs to daemon This was probably an accident, and it could lead to problems. Incidentally, looking at the name of the file and its size, it's fairly obvious that this is an image of a 3,5" floppy, that is to say, a literal copy of the data on the complete floppy.
  • The date is normally the date that the file was last modified. With the -u, option to ls you can list the last time the file was accessed.
  • Finally comes the name of the file. As you can see from this example, the names can be quite varied.
  • A couple of the permissions are of interest. The directories all have the x (execute) permission bit set. This enables accessing (i.e. opening) files in the directory—that's the way the term execute is defined for a directory. If l reset the execute permission, I can still list the names of the files, but I can't access them.

    I am the only person who can access the directory Mail This is the normal permission for a mail directory.

    Changing file permissions and owners

    Often enough, you may want to change file permissions or owners. UNIX supplies three programs to do this:

  • To change the file owner, use chown. For example, to change the ownership of the file deppert.floppy, which in the list above belongs to dacodeon, root would enter:
    # chown grog deppert.floppy
    

    Note that only root may perform this operation.

  • To change the file group, use chgrp, which works in the same way as chown. To change the group ownership to lemis, you would enter:
    # chgrp lemis deppert.floppy
    

    chown can also change both the owner and the group. Instead of the two previous examples, you could enter:

    # chown grog:lemis deppert.floppy
    

    This changes the owner to grog, as before, and also changes the group to lemis

  • To change the permissions, use the chmod program. chmod has a number of different formats, but unfortunately the nine-character representation isn't one of the code. Read the man page chmod(1) for the full story, but you can achieve just about anything you want with one of the formats shown in table 10-1
  • chmod permission codes
    SpecificationEffect
    go-wDeny write permission to group and others
    =rw,+XSet the read and write permissions to the usual defaults, but retain any execute permissions that are currently set
    +XMake a directory or file searchable/executable by everyone if it is already searchable/executable by anyone
    u=rwx,go=rxMake a file readable/executable by everyone and writable by the owner only
    go=Clear all mode bits for group and others
    g=u-wSet the group bits equal to the user bits, but clear the group write bit

    Permissions for new files

    None of this tells us what the permissions for new files are going to be. The wrong choice could be disastrous. For example, if files were automatically created with the permissions rwxrwxrwx anybody could access thcode in any way. On the other hand, creating thcode with r-------- could result in a lot of work setting thcode to what you really want them to be. UNIX solves this problem with a thing called umask (User mask) This is a default non-permission: it specifies which permission bits not to allow.

    As if this weren't confusing enough, it's specified in the octal number system, in which the valid digits are 0 to 7. Each octal digit represents 3 bits. By contrast, the more common hexadecimal system uses 16 digits, 0 to 9 and a to f .The original versions of UNIX ran on machines that used the octal number system, and since the permissions come in threes, it made sense to leave the umask value in octal.

    An example: by default, you want to create files that anybody can read, but only you can write. You set the mask to 022. This corresponds to the binary bit pattern 000010010

    The leading 0 is needed to specify that the number is in octal, not to make up three digits. If you want to set the permissions so that by default nobody can read, you'd set it to 0222. Some shells automatically assume that the number is octal, so you may be able to omit the 0, but it's not good practice.

    The permissions are allowed where the corresponding bit is 0:

    rwxrwxrwx     Possible permissions 
    000010010     umask
    rwxr-xr-x     resultant permissions
    

    By default, files are created without the x bits, whereas directories are created with the allowed x bits, so with this umask a file would be created with the permissions rw-r--r--

    umask is a shell command. To set it, just enter:

    $ umask 022
    

    It's preferable to set this in your shell initialization file—see page 135 for further details.

    Beware of creating a too restrictive umask. For example, you will get into a lot of trouble with a umask like 377, which creates files that you can only read, and that nobody else can access at all. If you disallow the x (executable) bit, you will not be able to access directories you create, and you won't be able to run programs you compile.

    Making a program executable

    File permissions enable one problem that occurs so often that it's worth drawing attention to it. Many operating systems require that an executable program have a special naming convention, such as COMMAND.COM or FOO.BAT which in MS-DOS denotes a specific kind of binary executable and a script file, respectively. In UNIX, executable programs don't need a special suffix, but they must have the x bit set. Sometimes this bit gets reset (turned off), for example if you copy it across the Net with ftp. The result looks like this:

    $ ps
    bash: ps: Permission denied $ ls -l /bin/ps
    -r--r--r--  1 bin  kmem  163840 May 6 06:02 /bin/ps
    $ su                             you need to be super user to set ps permission
    Password:                        password doesn't echo
    # chmod +x /bin/ps               make it executable
    # ps                             now it works
    PID  TT     TIME  COMMAND
    226  p2  0:00.56  su (bash)
    239  p2  0:00.02  ps
    146  v1  0:00.06  /usr/libexec/getty Pc ttyv1
    147  v2  0:00.05  /usr/libexec/getty Pc ttyv2
    # ^D                             exit su
    $ ps
    ps: /dev/mem: Permission denied  hey! it’s stopped working
    

    Huh? It only worked under su and stopped working when I became a mere mortal again? What's going on here?

    There's a second problem with programs like ps: some versions need to be able to access special files, in this case /dev/mem, a special file that addresses the system memory. To do this, we need to set the setgid bit, s, which requires becoming super user again:

    $ su                  you need to be super user to set ps permission
    Password:             password doesn't echo
    # chmod g+s /bin/ps   set the setgid bit
    # ls -l /bin/ps       see what it looks like
    -r-xr-sr-x  1 bin  kmem  163840 May   6 06:02 /bin/ps
    # ^D                  exit su
    $ ps                  now it still works
    PID  TT  STAT     TIME  COMMAND
    226  p2  S     0:00.56  su (bash)
    239  p2  R+    0:00.02  ps
    146  v1  Is+   0:00.06  /usr/libexec/getty Pc ttyv1
    147  v2  Is+   0:00.05  /usr/libexec/getty Pc ttyv2
    

    In this example, the permissions in the final result really are the correct permissions for ps. It's impossible to go through the permissions for every standard program. If you suspect that you have the permissions set in correctly, use the permissions of the files on the Live File system CD-ROM as a guideline.

    setuid and setgid programs can be a security issue. What happens if the program called ps is really something else, a Trojan Horse? We set the permissions to allow it to break into the system. As a result, FreeBSD has found an alternative method for ps to do its work, and it no longer needs to be set setgid.

    Mandatory Access Control

    For some purposes, traditional UNIX permissions are insufficient. Release 5.0 of FreeBSD introduces Mandatory Access Control, or MAC, which permits loadable kernel modules to augment the system security policy. MAC is intended as a toolkit for developing local and vendor security extensions, and it includes a number of sample policy modules, including Multi-Level Security (MLS) with compartments, and a number of augmented UNIX security models including a file system firewall. At the time of writing it is still considered experimental software, so this book doesn't discuss it further. See the man pages for more details.

    Links

    In UNIX, files are defined by inodes structures on disk that you can't access directly. They contain the meta data, all the information about the file, such as owner, permissions and timestamps. What they don't contain are the things you think of as making up a file: they don't have any data, and they don't have names. Instead, the inode contains information about where the data blocks are located on the disk. It doesn't know anything about the name: that's the job of the directories.

    A directory is simply a special kind of file that contains a list of names and inode numbers: in other words, they assign a name to an Inode, and thus to a file. More than one name can point to the same inode, so files can have more than one name. This connection between a name and an inode is called a link sometimes confusingly hard link. The inode numbers relate to the file system, so files must be in the same file system as the directory that refers to them.

    Directory entries are independent of each other: each points to the Inode, so they're completely equivalent. The inode contains a link count that keeps track of how many directory entries point to it: when you remove the last entry, the system deletes the file data and metadata.

    Alternatively, symbolic links sometimes called soft links, are not restricted to the same file system (not even to the same system!), and they refer to another file name, not to the file itself. The difference is most evident if you delete a file: if the file has been hard linked, the other names still exist and you can access the file by them. If you delete a file name that has a symbolic link pointing to it, the file goes away and the symbolic link can't find it anymore.

    It's not easy to decide which kind of link to use—see UNIX Power Tools (O'Reilly) for more details.

    Directory hierarchy

    Although Microsoft platforms have a hierarchical directory structure, there is little standardization of the directory names: it's difficult to know where a particular program or data file might be. UNIX systems have a standard directory hierarchy, though every vendor loves to change it just a little bit to ensure that they're not absolutely compatible. In the course of its evolution, UNIX has changed its directory hierarchy several times. It's still better than the situation in the Microsoft world. The most recent, and probably most far-reaching changes, occurred over ten years ago with System V.4 and 4.4BSD, both of which made almost identical changes.

    Nearly every version of UNIX prefers to have at least two file systems, / (the root file system) and /usr even if they only have a single disk. This arrangement is considered more reliable than a single file system: it's possible for a file system to crash so badly that it can't be mounted anymore, and you need to read in a tape backup, or use programs like fsck or fsdb to piece them together. We have already discussed this issue on page 68, where I recommend having /usr on the same file system as /.

    Standard directories

    The physical layout of the file systems does not affect the names or contents of the directories, which are standardized. Table 10-2 gives an over view of the standard FreeBSD directories; see the man page hier(7) for more details.

    FreeBSD directory hierarchy
    Directory nameUsage
    /Root file system. Contains a couple of system directories and mount points for other file systems. It should not contain anything else.
    /binExecutable programs of general use needed at system startup time. The name was originally an abbreviation for binary,but many of the files in here are shell scripts.
    /bootFiles used when booting the system, including the kernel and its associated klds.
    /cdromAmount point for CD-ROM drives.
    /compatA link to /usr/compat: see below.
    /devDirectory of device nodes. The name is an abbreviation for devices. From FreeBSD 5.0 onward, this is normally a mount point for the device file system, devfs. We'll look at the contents of this directory in more detail on page 195.
    /etcConfiguration files used at system startup. Unlike System V, /etc does not contain kernel build files, which are not needed at system startup. Unlike earlier UNIX versions, it also does not contain executable—they have been moved to /sbin.
    /homeBy convention, put user files here. Despite the name, /usr is for system files.
    /mntA mount point for floppies and other temporary file systems.
    /procThe process file system. This directory contains pseudo-files that refer to the virtual memory of currently active processes.
    /rootThe home directory of the user root. In traditional UNIX file systems, root's home directory was /, but this is messy.
    /sbinSystem executable needed at system startup time. These are typically system administration files that used to be stored in /etc.
    /sysIf present, this is usually a symbolic link to /usr/src/sys, the kernel sources. This is a tradition derived from 4.3BSD.
    /tmpA place for temporary files. This directory is an anachronism: normally it is on the root file system, though it is possible to mount it as a separate file system or make it a symbolic link to /var/tmp. It is maintained mainly for programs that expect to find it.
    /usrThe "second file system." See the discussion above.
    /usr/XllR6The X WindowSystem.
    /usr/XllR6/binExecutable X11 programs.
    /usr/XllR6/includeHeader files for X11 programming.
    /usr/XllR6/libLibrary files for X11.
    /usr/XllR6/manMan pages for X11.
    /usr/binStandard executable programs that are not needed at system start. Most standard programs you use are stored here.
    /usr/compatA directory containing code for emulated systems, such as Linux.
    /usr/gamesGames.
    /usr/includeHeader files for programmers.
    /usr/libLibrary files. FreeBSD does not have a directory /lib.
    /usr/libexecExecutable files that are not started directly by the user, for example the phases of the C compiler (which are started by /usr/bin/gcc)or the getty program, which is started by init.
    /usr/libdataMiscellaneous files used by system utilities.
    /usr/localAdditional programs that are not part of the operating system. It parallels the /usr directory in having subdirectories bin, include, lib, man, sbin, and share. This is where you can put programs that you get from other sources.
    /usr/objObject files created when building the system. See Chapter 33 .
    /usr/portsThe Ports Collection.
    /usr/sbinSystem administration programs that are not needed at system startup.
    /usr/shareMiscellaneous read-only files, mainly informative. Subdirectories include doc, the FreeBSD documentation, games, info, the GNU info documentation, locale, internationization information, and man, the man pages.
    /usr/srcSystem source files.
    /varA file system for data that changes frequently, such as mail, news, and log files. If /var is not a separate file system, you should create a directory on another file system and symlink /var to it.
    /var/logDirectory with system log files
    /var/mailIncoming mail for users on this system
    /var/spoolTransient data, such as outgoing mail, print data and anonymous ftp.
    /var/tmpTemporary files.

    File system types

    FreeBSD supports a number of file system types. The most important are:

  • UFS is the UNIX File SystemParadoxically, although BSD may not be called UNIX, its file system is called the UNIX File System. The UNIX System Group, the developers of UNIX System V.4, adopted UFS as the standard file system for System V and gav e it this name. Previously it was called the Berkeley Fast File System, or ffs. All native disk file systems are of this type. Since FreeBSD 5.0, you have a choice of two different versions, UFS 1 and UFS2. As the names suggest, UFS 2 is a successor to UFS 1. Unlike UFS 1, UFS 2 file systems are not limited to 1 TB (1024 GB) in size. UFS 2 is relatively new, so unless you require very large file systems, you should stick to UFS 1.
  • cd9660 is the ISO 9660 CD-ROM format with the so-called Rock Ridge Extensions that enable UNIX-like file names to be used. Use this file system type for all CD-ROMs, even if they don't have the Rock Ridge Extensions.
  • nfs is the Network File System a means of sharing file systems across a network. We'll look at it in Chapter 25.
  • FreeBSD supports a number of file systems from other popular operating systems. You mount the file systems with the mount command and the -t option to specify the file system type. For example:
    # mount -t ext2fs /dev/dalsl /linux    mount a Linux ext2 file system
    # mount -t msdos /dev/da2s1 /C:        mount a Microsoft FAT file system
    

    Here’s a list of currently supported file systems:

  • File system support
    File systemmount option
    CD-ROMcd9660
    DVDudf
    Linux ext2ext2fs
    Microsoft MS-DOSmsdosfs
    Microsoft NTntfs
    Novell Netwarenwfs
    Microsoft CIFSsmbfs

    Soft updates

    Soft updates change the way the file system performs I/O. They enable metadata to be written less frequently. This can give rise to dramatic performance improvements under certain circumstances, such as file deletion. Specify soft updates with the –U option when creating the file system. For example:

    # newfs -U /dev/da1s2h
    

    If you forget this fag, you can enable them later with tunefs :

    # tunefs -n enable /dev/da1s2h
    

    You can't perform this operation on a mounted file system.

    Snapshots

    One of the problems with backing up file systems is that you don't get a consistent view of the file system: while you copy a file, other programs may be modifying it, so what you get on the tape is not an accurate view of the file at any time. Snapshots are a method to create a unified view of a file system. They maintain a relatively small file in the file system itself containing information on what has changed since the snapshot was taken. When you access the snapshot, you get this data rather than the current data for the parts of the disk which have changed, so you get a view of the file system as it was at the time of the snapshot.

    Creating snapshots

    You create snapshots with the mount command and the -o snapshot option. For example, you could enter

    # mount -u -o snapshot /var/snapshot/snapl /var
    

    This command creates a snapshot of the /var file system called /var/snapshot/snapl. Snapshot files have some interesting properties:

  • You can have multiple snapshots on a file system, up to the current limit of 20.
  • Snapshots have the schg fag set, which prevents anybody writing to them.
  • Despite the schg fag, you can still remove them.
  • They are automatically updated when anything is written to the file system. The view of the file system doesn't change , but this update is necessary in order to maintain the "old" view of the file system.
  • They look like normal file systems. You can mount them with the md driver. We'll look at that on page 193.
  • Probably the most useful thing you can do with a snapshot is to take a backup of it. We'll look at backups on page 253.

    At the time of writing, snapshots are still under development. It's possible that you might still have trouble with them, in particular with deadlocks that can only be cleared by rebooting.

    It takes about 30 seconds to create a snapshot of an 8 GB file system. During the last five seconds, file system activity is suspended. If there's a lot of soft update activity going on in the file system (for example, when deleting a lot of files), this suspension time can become much longer, up to several minutes. To remove the same snapshot takes about two minutes, but it doesn't suspend file system activity at all.

    Mounting file systems

    Microsoft platforms identify partitions by letters that are assigned at boot time. There is no obvious relation between the partitions, and you have little control over the way the system assigns them. By contrast, all UNIX partitions have a specific relation to the root file system, which is called simply /.This flexibility has one problem: you have the choice of where in the overall file system structure you put your individual file systems. You specify the location with the mount command. For example, you would typically mount a CD-ROM in the directory /cdrom, but if you have three CD-ROM drives attached to your SCSI controller, you might prefer to mount them in the directories /cd0, /cd1, and /cd2. To mount a file system, you need to specify the device to be mounted, where it is to be mounted, and the type of file system (unless it is ufs). The mount point (the directory where it is to be mounted) must already exist. To mount your second CD-ROM on /cd1, you enter:

    # mkdir /cdl                    only if it doesn't exist
    # mount -t cd9660 -o ro /dev/cdla /cdl
    

    When the system boots, it calls the startup script /etc/rc, which among other things automatically mounts the file systems. All you need to do is to supply the information: what is to be mounted, and where? This is in the file /etc/fstab. If you come from a System V environment, you'll notice significant difference in format—see the man page fstab(5), for the full story. A typical /etc/fstab might look like:

    /dev/ad0s1a           /                   ufs        rw         1 1  root file system
    /dev/ad0s1b           none                swap       sw         0 0  swap
    /dev/ad0s1e           /usr                ufs        rw         2 2  /usr file system
    /dev/dalsle           /src                ufs        rw         2 2  additional file system
    /dev/da2s1            /linux              ext2fs     rw         2 2  Linux file system
    /dev/adlsl            /C:                 msdos      rw         2 2  Microsoft file system
    proc                  /proc               procfs     rw         0 0  proc pseudo-file system
    linproc               /compat/linux/proc  linprocfs  rw         0 0  
    /dev/cd0a             /cdrom              cd9660     ro         0 0  CD-ROM
    presto:/              /presto/root        nfs        rw         0 0  NFS file systems on other systems
    presto:/usr           /presto/usr         nfs        rw         0 0  
    presto:/home          /presto/home        nfs        rw         0 0  
    presto:/S             /S                  nfs        rw         0 0  
    //guestasamba/public  /smb                smbfs      rw,noauto  0 0  SMB file system
    

    The format of the file is reasonably straight forward:

  • The first column gives the name of the device (if it's a real file system), a keyword for some file systems, like proc or the name of the remote file system for NFS mounts.
  • The second column specifies the mount point. Swap partitions don't have amount point, so the mount point for the swap partition is specified as none.
  • The third column specifies the type of file system. Local file systems on hard disk are always ufs and file systems on CD-ROM are cd9660. Remote file systems are always nfs. Specify swap partitions with swap, and the proc file system with proc
  • The fourth column contains rw for file systems that can be read or written, ro for file systems (like CD-ROM) that can only be read, and sw for swap partitions. It can also contain options like the noauto in the bottom line, which tells the system startup scripts to ignore the line. It's there so that you can use the shorthand notation mount /smb when you want to mount the file system.
  • The fifth and sixth columns are used by the dump and fsck programs. You won't normally need to change them. Enter 1 for a root file system, 2 for other UFS file systems, and 0 for everything else.
  • Mounting files as file systems

    So far, our files have all been on devices, also called special files. Sometimes, though, you may want to access the contents of a file as a file system:

  • It's sometimes of interest to access the contents of a snapshot, for example to check the contents.
  • After creating an ISO image to burn on CD-R, you should check that it's valid.
  • Also, after downloading an ISO image from the Net, you may just want to access the contents, and not create a CD-R at all.
  • In each case, the solution is the same: you mount the files as a vnode device with the md driver.

    The md driver creates a number of different kinds of pseudo-device. See the man page md(4).. We use the vnode device, a special file that refers to file system files. Support for md is included in the GENERIC kernel, but if you've built a kernel without the md drive, you can load it as a kld. If you're not sure, try loading the kld anyway.

    In the following example, we associate a vnode device with the ISO image iso-image using the program mdconfig:

    # kldload md                          load the kld module if necessary
    kldload: can't load md: File exists   already loaded or in the kernel
    # mdconfig -a -t vnode -f iso -image  and configure the device
    md0                                   this is the name assigned in directory /dev
    # mount -t cd9660 /dev/md0 /mnt       then mount it
    

    After this, you can access the image at /mnt as a normal file system. You specify -t cd9660 in this case because the file system on the image is a CD9660 file system. You don't specify this if you're mounting a UFS file system, for example a snapshot image.

    Older versions of FreeBSD used the vn driver, which used different syntax. Linux uses loop mounts, which FreeBSD doesn't support.

    Unmounting file systems

    When you mount a file system, the system assumes it is going to stay there, and in the interests of efficiency it delays writing data back to the file system. This is also the reason why you can't just turn the power off when you shut down the system. If you want to stop using a file system, you must tell the system about it so that it can flush any remaining data. You do this with the umount command. Note the spelling of this command—there's no n in the command name.

    You need to do this even with read-only media such as CD-ROMs: the system assumes it can access the data from a mounted file system, and it gets quite unhappy if it can't. Where possible, it locks removable media so that you can't remove them from the device until you unmount them.

    Using umount is straightforward: just tell it what to unmount, either the device name or the directory name. For example, to unmount the CD-ROM we mounted in the example above, you could enter one of these commands:

    # umount /dev/cdla
    # umount /cdl
    

    Before unmounting a file system, umount checks that nobody is using it. If somebody is using it, it refuses to unmount it with a message like umount: /cdl: Device busy. This message often occurs because you have changed your directory to a directory on the file system you want to remove. For example (which also shows the usefulness of having directory names in the prompt):

    === root@freebie (/dev/ttyp2)  /cdl 16 -> umount /cdl
    umount: /cd1: Device busy
    === root@freebie (/dev/ttyp2)  /cd1 17 -> cd
    === root@freebie (/dev/ttyp2)  ~ 18 -> umount /cdl
    === root@freebie (/dev/ttyp2)  ~ 19 ->
    

    After unmounting a vnode file system, don't forget to unconfigure the file:

    # umount /mnt
    # mdconfig -d -u 0
    

    The parameter 0 refers to md device 0, in other words /dev/md0.

    FreeBSD devices

    UNIX refers to devices in the same manner as it refers to normal files. By contrast to normal ("regular") files, they are called special files. They're not really files at all: they're information about device support in the kernel, and the term device node is more accurate. Conventionally, they are stored in the directory /dev. Some devices don't have device nodes, for example Ethernet interfaces: they are treated differently by the ifconfig program.

    Traditional UNIX systems distinguish two types of device, blockdevices and character devices. FreeBSD no longer has block devices; we discussed the reasons for this on page 36.

    In traditional UNIX systems, including FreeBSD up to Release 4, it was necessary to create device nodes manually. This caused a number of problems when they didn't match what was in the system. Release 5 of FreeBSD has solved this problem with the device file system, also known as devfs. devfs is a pseudo-file system that dynamically creates device nodes for exactly those devices that are in the kernel, which makes it unnecessary to manually create devices.

    Overview of FreeBSD devices

    Every UNIX system has its own peculiarities when it comes to device names and usage. Even if you're used to UNIX, you'll find the following table useful.

    FreeBSD device names
    acd0First ata (IDE) CD-ROM drive.
    ad0First ata (IDE or similar) disk drive. See Chapter 2, page 38, for a complete list of disk drive names.
    bpf0Berkeley packet filter.
    cd0First SCSI CD-ROM drive.
    ch0SCSI CD-ROM changer (juke box)
    consoleSystem console, the device that receives console messages. Initially it is /dev/ttyv0, but it can be changed.
    cuaa0First serial port in callout mode.
    cuaia0First serial port in callout mode, initial state. Note the letter i for initial.
    cuala0First serial port in callout mode, lock state. Note the letter l for lock.
    da0First SCSI disk drive. See Chapter 2, page 38, for a complete list of disk drive names.
    esa0First SCSI tape drive, eject on close mode.
    fdFile descriptor pseudo-devices: a directory containing pseudo-devices that, when opened, return a duplicate of the file descriptor with the same number. For example, if you open /dev/fd/0, you get another handle on your stdin stream (file descriptor 0).
    fd0The first floppy disk drive, accessed as a file system.
    kmemKernel virtual memory pseudo-device.
    lpt0First parallel printer.
    memPhysical virtual memory pseudo-device.
    nsa0First SCSI tape drive, no-rewind mode.
    nullThe "bit bucket." Send data to this device if you never want to see it again.
    psm0PS/2 mouse.
    ptyp0First master pseudo-terminal. Master pseudo-terminals are named /dev/ptyp0 through /dev/ptypv, /dev/ptyq0 through /dev/ptyqv, /dev/ptyr0 through /dev/ptyrv, /dev/ptys0 through /dev/ptysv, /dev/ptyP0 through /dev/ptyPv, /dev/ptyQ0 through /dev/ptyQv, /dev/ptyR0 through /dev/ptyRv and /dev/ptyS0 through /dev/ptySv.
    randomRandom number generator.
    sa0First SCSI tape drive, rewind on close mode.
    sysmouseSystem mouse, controlled by moused. We’ll look at this again on page 519.
    ttyCurrent controlling terminal.
    ttyd0First serial port in callin mode.
    ttyid0First serial port in callin mode, initial state.
    ttyld0First serial port in callin mode, lock state.
    ttyp0First slave pseudo-terminal. Slave pseudo-terminals are named /dev/ttyp0 through /dev/ttypv, /dev/ttyq0 through /dev/ttyqv, /dev/ttyr0 through /dev/ttyrv, /dev/ttys0 through /dev/ttysv, /dev/ttyP0 through /dev/ttyPv, /dev/ttyQ0 through /dev/ttyQv, /dev/ttyR0 through /dev/ttyRv and /dev/ttyS0 through /dev/ttySv. Some processes, such as xterm, only look at /dev/ttyp0 through /dev/ttysv.
    ttyv0First virtual tty. This is the display with which the system starts. Up to 10 virtual ttys can be activated by adding the appropriate getty information in the file /etc/ttys. See Chapter 19 , page 338, for further details.
    ugen0First generic USB device.
    ukbd0First USB keyboard.
    ulpt0First USB printer.
    umass0First USB mass storage device.
    ums0First USB mouse.
    uscanner0First USB scanner.
    vinumDirectory for Vinum device nodes. See Chapter 12 , for further details.
    zeroDummy device that always returns the value (binary) 0 when read.

    You'll note a number of different modes associated with the serial ports. We'll look at them again in Chapter 19 .

    Virtual terminals

    As we have seen, UNIX is a multitasking operating system, but a PC generally only has one screen. FreeBSD solves this problem with virtual terminals. When in text mode, you can change between up to 16 different screens with the combination of the Alt key and a function key. The devices are named /dev/ttyv0 through /dev/ttyv15 and correspond to the keystrokes Alt-Fl through Alt-F16. By default, three virtual terminals are active: /dev/ttyv0 through /dev/ttyv2. The system console is the virtual terminal /dev/ttyv0 and that's what you see when you boot the machine. To activate additional virtual terminals, edit the file /etc/ttys. There you find:

    ttyvO  "/usr/libexec/getty Pc"  cons25  on secure
    ttyvl  "/usr/libexec/getty Pc"  cons25  on secure
    ttyv2  "/usr/libexec/getty Pc"  cons25  on secure
    ttyv3  "/usr/libexec/getty Pc"  cons25  off secure
    

    The key words on and off refer to the state of the terminal: to enable one, set its state to on. To enable extra virtual terminals, add a line with the corresponding terminal name, in the range /dev/ttyv4 to /dev/ttyv15. After you have edited /etc/ttys, you need to tell the system to re-read it in order to start the terminals. Do this as root with this command:

    # kill -1 1
    

    Process 1 is init —see page 528 for more details.

    Pseudo-terminals

    In addition to virtual terminals, FreeBSD offers an additional class of terminals called pseudo-terminals. They come in pairs: a master device also called a pry (pronounced pity) is used only by processes that use the interface, and has a name like /dev/ptyp0. The slave device looks like a terminal, and has a name like /dev/ttyp0. Any process can open it without any special knowledge of the interface. These terminals are used for network connections such as xterm, telnet and rlogin. You don't need a getty for pseudo-terminals. Since FreeBSD Release 5.0, pseudo-terminals are created as required.

    Вернуться к учебному плану